Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
30 changes: 27 additions & 3 deletions apps/api/src/opendirector_api/creation.py
Original file line number Diff line number Diff line change
Expand Up @@ -36,6 +36,11 @@
from opendirector_api.localization import localized_error_for_language


class EditHandoffDecision(BaseModel):
requester: UUID
accept: bool


class FontCoverageResponse(BaseModel):
fingerprint: str = Field(pattern=r'^sha256:[0-9a-f]{64}$')
# One bit per Unicode scalar position: fixed 139,264 bytes / 185,688 base64 chars.
Expand Down Expand Up @@ -131,14 +136,33 @@ def open_project(project_id: UUID, x_opendirector_session: UUID = Header()):
return projects.open(project_id, str(x_opendirector_session))

@router.post('/projects/{project_id}/open-canvas')
def open_project_canvas(project_id: UUID, x_opendirector_session: UUID = Header()):
def open_project_canvas(project_id: UUID, x_opendirector_session: UUID = Header(),
x_opendirector_allow_preview: bool = Header(default=False)):
# The canvas needs its reference edges and text on first render too. Reuse the
# single snapshot this open read already published instead of making the
# page read the same project again through GET /canvas. The no-flag
# route above still returns a bare ProjectSnapshot.
snapshot = projects.open(project_id, str(x_opendirector_session))
session = str(x_opendirector_session)
editing = {}
if x_opendirector_allow_preview:
snapshot, state = projects.open_canvas(project_id, session, allow_preview=True)
editing['editing'] = state
else:
snapshot = projects.open(project_id, session)
return {'snapshot': snapshot, 'edges': canvas.reference_edges(project_id, snapshot),
'texts': canvas.text_contents(snapshot)}
'texts': canvas.text_contents(snapshot), **editing}

@router.get('/projects/{project_id}/edit-session')
def edit_session(project_id: UUID, x_opendirector_session: UUID = Header()):
return projects.editing_state(project_id, str(x_opendirector_session))

@router.post('/projects/{project_id}/edit-session')
def request_edit_session(project_id: UUID, x_opendirector_session: UUID = Header()):
return projects.request_edit(project_id, str(x_opendirector_session))

@router.put('/projects/{project_id}/edit-session')
def resolve_edit_session(project_id: UUID, value: EditHandoffDecision, x_opendirector_session: UUID = Header()):
return projects.resolve_edit(project_id, str(x_opendirector_session), str(value.requester), value.accept)

@router.put('/sessions/{session_id}')
def heartbeat(session_id: UUID, value: Session):
Expand Down
6 changes: 6 additions & 0 deletions docs/guides/user-guide.md
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,12 @@

[English](user-guide.md) · [简体中文](user-guide.zh-CN.md) · [Back to README](../../README.md)

## Preview the same project in another browser window

Open the project menu and select **Open in new tab** next to the project. The preview uses the same workspace and disables editing controls. You can pan the canvas, inspect media, and play a saved timeline while the editing window stays open. Saved changes appear automatically.

Select **Edit in this window** to request edit access. In the editing window, select **Save and hand off** to switch roles or **Keep editing here** to decline. If the editing window is already closed, edit access is granted as soon as its lease is released.

## Connect models

On the welcome screen, select **Get started**. Set up a language model for the built-in assistant or choose an existing harness. Then check one or more tasks. Each checked task shows its saved models or opens its setup form if you have none. **Start creating** places a node for each checked task on the same canvas. **Import media** opens the file picker. **Open an example canvas** opens an editable example project directly, with download progress in step two. Cancelling keeps your task selections. You can add more models in Settings anytime.
Expand Down
6 changes: 6 additions & 0 deletions docs/guides/user-guide.zh-CN.md
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,12 @@

[English](user-guide.md) · [简体中文](user-guide.zh-CN.md) · [返回首页](../../README.zh-CN.md)

## 在多个浏览器窗口查看同一项目

打开项目菜单,点项目右侧的「在新标签页打开」。两个窗口使用同一套工作区,预览窗口中的编辑控件会禁用。你可以平移缩放画布、查看素材、播放已保存的时间线。编辑窗口保存后,预览会自动更新。

需要在预览窗口修改时,点「在此编辑」。在原窗口点「保存并交接」就会交换两个窗口的角色,也可以点「继续在此编辑」拒绝。如果原窗口已关闭,等编辑权释放后即可直接接手。

## 接入模型

首次打开时,在欢迎页选择「开始设置」。为内置助手配置一个语言模型,或选择已有的 Harness。接着勾选一项或多项任务。每个勾选项可以选用已有模型,缺模型时直接显示对应的配置表单。点击「开始创作」后,画布会为每项任务添加一个节点。点「导入素材」可直接选文件,点「打开示例画布」可直接进入可编辑的示例项目,下载进度在第二步显示。取消时会保留已勾选的任务。之后可随时在设置中添加其他模型。
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -121,17 +121,47 @@ def view(self, project_id, client_id, value=None, *, session=None, missing_ok=Fa
return ViewState.model_validate(read_json(file))
return None if missing_ok else ViewState(projectId=project_id, clientId=client_id)

def open(self, project_id, session):
def open_canvas(
self, project_id: UUID | str, session: str, *, allow_preview: bool,
) -> tuple[ProjectSnapshot, dict[str, str | None]]:
with self.local.transaction() as db:
self._recover()
path, manifest = self._find(db, project_id)
self.local._open(db, dict(id=str(project_id), path=str(path)), session)
project = dict(id=str(project_id), path=str(path))
if allow_preview:
editor = self.local.editor(db, str(project_id))
if editor and editor['id'] != session:
self.local.clear_other_edit_requests(db, str(project_id), session)
db.execute("DELETE FROM sessions WHERE id=?", (session,))
else:
self.local.acquire_edit_lease(db, project, session)
else:
self.local.acquire_edit_lease(db, project, session)
state = self.local.editing_state(db, str(project_id), session)
record, validated = self._current_record(db, project_id, path, manifest)
if not validated:
# The canvas is open now; prove the ancestry in the background
# so the first autosave does not replay it under the lock.
self._schedule_warm(path, manifest)
return record.snapshot.model_copy(deep=True)
return record.snapshot.model_copy(deep=True), state

def open(self, project_id: UUID | str, session: str) -> ProjectSnapshot:
snapshot, _ = self.open_canvas(project_id, session, allow_preview=False)
return snapshot

def editing_state(self, project_id, session):
with self.local.transaction() as db:
return self.local.editing_state(db, str(project_id), session)

def request_edit(self, project_id, session):
with self.local.transaction() as db:
path, _ = self._find(db, project_id)
return self.local.request_edit(db, dict(id=str(project_id), path=str(path)), session)

def resolve_edit(self, project_id, session, requester, accept):
with self.local.transaction() as db:
path, _ = self._find(db, project_id)
return self.local.resolve_edit(db, dict(id=str(project_id), path=str(path)), session, requester, accept)

def heartbeat(self, session, project_id):
self.open(project_id, session)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -76,6 +76,8 @@ class LocalProjects:
# separate key lets browsers open or release their own editing session.
_AGENT_SESSION_PREFIX = "agent:"

HANDOFF_SECONDS = 120

def __init__(self, repository: Path):
self.repository = repository.resolve()
self.root = self.repository / "projects"
Expand All @@ -89,6 +91,10 @@ def __init__(self, repository: Path):
id TEXT PRIMARY KEY, project_id TEXT NOT NULL, expires REAL NOT NULL,
path TEXT NOT NULL DEFAULT ''
);
CREATE TABLE IF NOT EXISTS edit_handoffs (
project_id TEXT PRIMARY KEY, owner TEXT NOT NULL,
requester TEXT NOT NULL, expires REAL NOT NULL
);
""")
db.execute("DELETE FROM sessions WHERE expires<=?", (time.time(),))

Expand Down Expand Up @@ -122,9 +128,10 @@ def _conflict(parent: Path, name: str, source: Path | None = None):
raise ProjectError("该位置已有同名文件或文件夹,请使用其他名称。", 409)


def _open(self, db, project: dict, session: str):
def acquire_edit_lease(self, db: sqlite3.Connection, project: dict[str, str], session: str) -> None:
identifier(session)
project_id = project["id"]
self.clear_other_edit_requests(db, project_id, session)
if db.execute("SELECT 1 FROM sessions WHERE project_id=? AND id<>? AND id NOT LIKE ? AND expires>?",
(project_id, session, self._AGENT_SESSION_PREFIX + "%", time.time())).fetchone():
raise ProjectError("该项目正在其他窗口中打开,请先关闭后再试。", 409, code="project_open_elsewhere")
Expand All @@ -134,6 +141,58 @@ def _open(self, db, project: dict, session: str):
db.execute("INSERT INTO sessions(id,project_id,expires,path) VALUES (?,?,?,?) ON CONFLICT(id) DO UPDATE SET project_id=excluded.project_id,expires=excluded.expires,path=excluded.path", (session, project_id, time.time() + self.LEASE_SECONDS, project["path"]))


def clear_other_edit_requests(self, db, project_id, session):
db.execute(
"DELETE FROM edit_handoffs WHERE project_id!=? AND (owner=? OR requester=?)",
(project_id, session, session),
)

def editor(self, db, project_id, *, now=None):
return db.execute(
"SELECT id FROM sessions WHERE project_id=? AND id NOT LIKE ? AND expires>?",
(project_id, self._AGENT_SESSION_PREFIX + "%", time.time() if now is None else now),
).fetchone()

def editing_state(self, db, project_id, session, *, now=None):
now = time.time() if now is None else now
editor = self.editor(db, project_id, now=now)
if editor is None:
return {'mode': 'preview', 'handoff': 'available'}
owner = editor['id']
pending = db.execute(
"SELECT requester FROM edit_handoffs WHERE project_id=? AND owner=? AND expires>?",
(project_id, owner, now),
).fetchone()
if owner == session:
return {'mode': 'edit', 'requester': pending['requester'] if pending else None}
return {'mode': 'preview', 'handoff': (
'requested' if pending and pending['requester'] == session
else 'busy' if pending else 'occupied'
)}

def request_edit(self, db, project, session):
project_id = project['id']
now = time.time()
state = self.editing_state(db, project_id, session, now=now)
if state == {'mode': 'preview', 'handoff': 'available'}:
self.acquire_edit_lease(db, project, session)
elif state == {'mode': 'preview', 'handoff': 'occupied'}:
db.execute("""
INSERT INTO edit_handoffs(project_id,owner,requester,expires) VALUES (?,?,?,?)
ON CONFLICT(project_id) DO UPDATE SET owner=excluded.owner,
requester=excluded.requester, expires=excluded.expires
""", (project_id, self.editor(db, project_id, now=now)['id'], session, now + self.HANDOFF_SECONDS))
return self.editing_state(db, project_id, session)

def resolve_edit(self, db, project, session, requester, accept):
project_id = project['id']
if self.editing_state(db, project_id, session) == {'mode': 'edit', 'requester': requester}:
db.execute("DELETE FROM edit_handoffs WHERE project_id=?", (project_id,))
if accept:
db.execute("DELETE FROM sessions WHERE id=?", (session,))
self.acquire_edit_lease(db, project, requester)
return self.editing_state(db, project_id, session)

def agent_session_key(self, session: str) -> str:
return self._AGENT_SESSION_PREFIX + identifier(session)

Expand All @@ -156,4 +215,5 @@ def release_agent_session(self, session: str):

def release(self, session: str):
with self.transaction() as db:
db.execute("DELETE FROM edit_handoffs WHERE owner=? OR requester=?", (session, session))
db.execute("DELETE FROM sessions WHERE id=?", (session,))
11 changes: 10 additions & 1 deletion src/backend/creationClient.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
import { installEditingState, parseEditingState } from "./editSession.ts";
import type {
Asset,
AssetRef,
Expand Down Expand Up @@ -164,13 +165,21 @@ export class CreationClient {
state: "used" | "pending" | "unknown" | "unavailable";
}[];
texts?: Record<string, string>;
editing?: unknown;
}
>(`${creationPath(this.id)}/open-canvas`, { method: "POST" });
>(`${creationPath(this.id)}/open-canvas`, {
method: "POST",
headers: { "X-OpenDirector-Allow-Preview": "true" },
});
// The open-canvas response carries the one authoritative snapshot plus
// the reference evidence the canvas draws; a bare snapshot response is
// still accepted for compatibility and falls back to a canvas read.
// Listeners re-project during install and read referenceStates, so the
// map is installed first, the same order as refresh().
if ("editing" in opened)
installEditingState(this.id, parseEditingState(opened.editing));
else
installEditingState(this.id, { mode: "edit", requester: null });
canvas = "snapshot" in opened ? opened : undefined;
if (canvas)
this.referenceStates = new Map(
Expand Down
47 changes: 47 additions & 0 deletions src/backend/editSession.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,47 @@
import { json, request } from "./api.ts";

export type EditingState =
| { mode: "edit"; requester: string | null }
| { mode: "preview"; handoff: "available" | "occupied" | "requested" | "busy" };

export function parseEditingState(value: unknown): EditingState {
if (typeof value === "object" && value !== null && "mode" in value) {
if (value.mode === "edit" && "requester" in value &&
(value.requester === null || typeof value.requester === "string"))
return { mode: value.mode, requester: value.requester };
if (value.mode === "preview" && "handoff" in value &&
(value.handoff === "available" || value.handoff === "occupied" ||
value.handoff === "requested" || value.handoff === "busy"))
return { mode: value.mode, handoff: value.handoff };
}
throw new TypeError("Invalid editing session response");
}

let current: { projectId: string; state: EditingState } | undefined;
const listeners = new Set<() => void>();

export function subscribeEditingState(listener: () => void) {
listeners.add(listener);
return () => { listeners.delete(listener); };
}

export function getEditingState(projectId: string) {
return current?.projectId === projectId ? current.state : undefined;
}

export function installEditingState(projectId: string, state: EditingState) {
const previous = getEditingState(projectId);
if (previous?.mode === "edit" && state.mode === "edit" && previous.requester === state.requester ||
previous?.mode === "preview" && state.mode === "preview" && previous.handoff === state.handoff)
return;
current = { projectId, state };
for (const listener of listeners) listener();
}

export async function readEditingState(projectId: string, init?: RequestInit) {
return parseEditingState(await request<unknown>(`/creation/projects/${projectId}/edit-session`, init));
}

export const requestEditing = (projectId: string) => readEditingState(projectId, { method: "POST" });
export const resolveEditing = (projectId: string, requester: string, accept: boolean) =>
readEditingState(projectId, json("PUT", { requester, accept }));
Loading
Loading