From ed668da6f075ded0c0dbb22e0a62e2408ceb04af Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E6=B1=AA=E5=BF=97=E9=B9=8F?= Date: Tue, 1 Dec 2026 11:21:35 +0000 Subject: [PATCH 1/3] [bugfix] cli: take editing over from another window with --take-over ## summary - Since #523 a browser tab keeps edit ownership until another window takes it, and closing the tab does not release it. The CLI could not take it, so every write to a project a tab had opened failed until someone opened another window or deleted the session by hand. - A global `--take-over` option (or `OPENDIRECTOR_TAKE_OVER=1`) takes editing through the existing edit-session endpoint before writing. The CLI still releases its session when the command ends; the tab switches to preview and can take editing back with "Edit in this window". - Without the option the refusal says what holds the project and how to move editing to the command, and keeps its code. ## validation - New test drives the CLI against the API: refusal with guidance, write with `--take-over`, the window in preview, a later plain write, and the window taking editing back. Co-Authored-By: Claude Opus 5.5 --- docs/guides/cli.md | 2 +- packages/core/src/opendirector/cli.py | 25 +++++++++++++++++---- tests/test_cli.py | 31 +++++++++++++++++++++++++++ 3 files changed, 53 insertions(+), 5 deletions(-) diff --git a/docs/guides/cli.md b/docs/guides/cli.md index b91586561..224da46ba 100644 --- a/docs/guides/cli.md +++ b/docs/guides/cli.md @@ -63,7 +63,7 @@ CLI 输出 JSON。修改回执附带对应的 assetId、itemId、specId 及其 读取类查询 `job.get`、`object.get`、`canvas.status` 与 `job.status` 不占用本轮执行锁,因此等待任务不会阻塞同轮其他工具调用。`job.status` 是 `job wait` 使用的批量查询:一次快照读取回答整组任务,并按需等待终态。 -普通终端写入申请独立编辑租约,完成后释放。工程已在其他窗口编辑时会返回占用错误。使用 `--session UUID` 表示沿用已有授权会话,CLI 完成后保留该会话。 +普通终端写入申请独立编辑租约,完成后释放。工程已在其他窗口编辑时会返回占用错误,并提示可改用 `--take-over`。浏览器窗口打开工程后会一直保留编辑权,关闭标签页也不会释放,此时在子命令前加 `--take-over`(或设置 `OPENDIRECTOR_TAKE_OVER=1`)把编辑权移到本次命令;命令结束后释放,原窗口转为预览,可用“在此编辑”收回。使用 `--session UUID` 表示沿用已有授权会话,CLI 完成后保留该会话。 Agent 的 Shell 通过 PATH 使用同一个 `opendirector`。宿主提供受令牌保护的本轮连接、工程范围、编辑会话和执行目录,文件登记限制在本轮执行目录。每次调用产生业务活动及回执,供聊天与轨迹页展示。 diff --git a/packages/core/src/opendirector/cli.py b/packages/core/src/opendirector/cli.py index a3a497ef6..66b34137b 100644 --- a/packages/core/src/opendirector/cli.py +++ b/packages/core/src/opendirector/cli.py @@ -179,9 +179,16 @@ def timeline_import(ctx: typer.Context, file: Path, operation_id: Annotated[UUID if value['status'] != 'applied': raise typer.Exit(1) +TAKE_OVER_HINT = ("This project is being edited in another window, for example a browser tab that is still open " + "or was closed without leaving the project. Run the command again with --take-over before the " + "subcommand to move editing here; that window switches to preview and can take editing back with " + "\"Edit in this window\".") + + class Client: - def __init__(self, project, url, session, operation_id): + def __init__(self, project, url, session, operation_id, take_over=False): self.project = project + self.take_over = take_over self.command = "opendirector" self.session = str(session or uuid4()) self.operation_id = operation_id @@ -252,7 +259,15 @@ def snapshot(self): def open(self): if not self.live and not self.opened: - self.request("POST", self.path("/open")) + if self.take_over: + self.request("POST", self.path("/edit-session")) + else: + try: + self.request("POST", self.path("/open")) + except ProjectError as error: + if error.code != "project_open_elsewhere": + raise + raise ProjectError(TAKE_OVER_HINT, 409, code=error.code) from None self.opened = True def execute(self, kind, payload, versions=(), preview=None, *, identity=None): @@ -329,8 +344,10 @@ def options(ctx: typer.Context, project: Annotated[UUID | None, typer.Option(envvar="OPENDIRECTOR_PROJECT_ID", help="Target project UUID.")] = None, url: Annotated[str, typer.Option(envvar="OPENDIRECTOR_API_URL", help="Running OpenDirector server.")] = "http://127.0.0.1:18000", session: Annotated[UUID | None, typer.Option(envvar="OPENDIRECTOR_SESSION", help="Existing authorized edit session.")] = None, - operation_id: Annotated[UUID | None, typer.Option(help="Stable write identity for safe replay.")] = None): - client = Client(project, url, session, operation_id) + operation_id: Annotated[UUID | None, typer.Option(help="Stable write identity for safe replay.")] = None, + take_over: Annotated[bool, typer.Option("--take-over", envvar="OPENDIRECTOR_TAKE_OVER", + help="Take editing over from another window that holds the project, instead of failing.")] = False): + client = Client(project, url, session, operation_id, take_over) ctx.obj = client def close(): diff --git a/tests/test_cli.py b/tests/test_cli.py index 0181f7aaa..8692f0388 100644 --- a/tests/test_cli.py +++ b/tests/test_cli.py @@ -303,6 +303,37 @@ def plain_help(value): return re.sub(r'\x1b\[[0-?]*[ -/]*[@-~]', '', value) +def test_cli_write_explains_and_takes_over_a_project_another_window_edits(tmp_path, monkeypatch): + api = TestClient(create_app(LocalProjects(tmp_path)), headers={"X-OpenDirector-Request": "1"}) + original_client = httpx.Client + + def forward(request): + response = api.request(request.method, request.url.path, headers=dict(request.headers), content=request.read()) + return httpx.Response(response.status_code, headers=response.headers, content=response.content) + + monkeypatch.setattr(cli.httpx, "Client", lambda **kwargs: original_client(**kwargs, transport=httpx.MockTransport(forward))) + runner = CliRunner() + project = str(uuid4()) + assert runner.invoke(cli.app, ["--project", project, "project", "create", "--name", "Take over"]).exit_code == 0 + window = {"X-OpenDirector-Session": str(uuid4())} + path = f"/api/creation/projects/{project}" + assert api.post(path + "/open", headers={**window, "X-OpenDirector-Persistent": "true"}).is_success + write = ["asset", "write-text", "--name", "plan.txt", "--text", "Plan"] + + refused = runner.invoke(cli.app, ["--project", project, *write]) + assert refused.exit_code == 1 + assert "--take-over" in str(refused.exception) and refused.exception.code == "project_open_elsewhere" + assert api.get(path + "/edit-session", headers=window).json() == {"mode": "edit"} + + taken = runner.invoke(cli.app, ["--project", project, "--take-over", *write]) + assert taken.exit_code == 0, taken.output + assert json.loads(taken.output)["status"] == "applied" + assert api.get(path + "/edit-session", headers=window).json() == {"mode": "preview"} + again = runner.invoke(cli.app, ["--project", project, "asset", "write-text", "--name", "notes.txt", "--text", "Notes"]) + assert again.exit_code == 0, again.output + assert api.post(path + "/edit-session", headers=window).json() == {"mode": "edit"} + + def test_all_cli_business_commands_have_help(help_color): runner = CliRunner() for kind in cli.COMMANDS: From 2556eb9072914079f85b76b15fc45e38cced675a Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E6=B1=AA=E5=BF=97=E9=B9=8F?= Date: Tue, 1 Dec 2026 11:26:27 +0000 Subject: [PATCH 2/3] [bugfix] cli: localize the takeover hint, ask for consent, and let the lease expire ## summary - The refusal again starts with the server's localized message and adds the takeover hint in the CLI's language (`OPENDIRECTOR_LANGUAGE`). - The hint, `--help` and the guide say that an agent must have the user's agreement before `--take-over`; the environment variable that made it a standing default is removed. - A CLI takeover asks the edit-session endpoint for an expiring lease, so a killed command no longer leaves a lease that never expires. The browser's takeover keeps its persistent lease. - The guide states that with `--session` the taken editing stays with that session. ## validation - Tests: the zh-CN refusal; `--session` with `--take-over` keeps editing; a CLI takeover lease that is never released expires. Co-Authored-By: Claude Opus 5.5 --- apps/api/src/opendirector_api/creation.py | 5 ++-- docs/guides/cli.md | 2 +- packages/core/src/opendirector/cli.py | 18 +++++++------ .../infrastructure/creation_projects.py | 4 +-- .../infrastructure/local_projects.py | 4 +-- tests/test_cli.py | 27 +++++++++++++++++++ 6 files changed, 45 insertions(+), 15 deletions(-) diff --git a/apps/api/src/opendirector_api/creation.py b/apps/api/src/opendirector_api/creation.py index 76d6d100f..2cfca2c8d 100644 --- a/apps/api/src/opendirector_api/creation.py +++ b/apps/api/src/opendirector_api/creation.py @@ -209,8 +209,9 @@ 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 take_edit_ownership(project_id: UUID, x_opendirector_session: UUID = Header()): - return projects.take_edit_ownership(project_id, str(x_opendirector_session)) + def take_edit_ownership(project_id: UUID, x_opendirector_session: UUID = Header(), + x_opendirector_persistent: bool = Header(default=True)): + return projects.take_edit_ownership(project_id, str(x_opendirector_session), persistent=x_opendirector_persistent) @router.put('/sessions/{session_id}') def heartbeat(session_id: UUID, value: Session): diff --git a/docs/guides/cli.md b/docs/guides/cli.md index 224da46ba..1f086798c 100644 --- a/docs/guides/cli.md +++ b/docs/guides/cli.md @@ -63,7 +63,7 @@ CLI 输出 JSON。修改回执附带对应的 assetId、itemId、specId 及其 读取类查询 `job.get`、`object.get`、`canvas.status` 与 `job.status` 不占用本轮执行锁,因此等待任务不会阻塞同轮其他工具调用。`job.status` 是 `job wait` 使用的批量查询:一次快照读取回答整组任务,并按需等待终态。 -普通终端写入申请独立编辑租约,完成后释放。工程已在其他窗口编辑时会返回占用错误,并提示可改用 `--take-over`。浏览器窗口打开工程后会一直保留编辑权,关闭标签页也不会释放,此时在子命令前加 `--take-over`(或设置 `OPENDIRECTOR_TAKE_OVER=1`)把编辑权移到本次命令;命令结束后释放,原窗口转为预览,可用“在此编辑”收回。使用 `--session UUID` 表示沿用已有授权会话,CLI 完成后保留该会话。 +普通终端写入申请独立编辑租约,完成后释放。浏览器窗口打开工程后会一直保留编辑权,关闭标签页也不会释放,此时 CLI 写入会返回占用错误,并提示可改用 `--take-over`。在子命令前加 `--take-over` 会把编辑权从该窗口移到本次命令:原窗口立即转为预览,未完成的保存会被拒绝,之后可用“在此编辑”收回。Agent 使用 `--take-over` 前须先征得用户同意。本次命令持有的编辑权与普通 CLI 写入一样会自动过期,进程被强行终止也不会长期占用;使用 `--session UUID` 时,接管的编辑权留在该会话,命令结束后不释放。 Agent 的 Shell 通过 PATH 使用同一个 `opendirector`。宿主提供受令牌保护的本轮连接、工程范围、编辑会话和执行目录,文件登记限制在本轮执行目录。每次调用产生业务活动及回执,供聊天与轨迹页展示。 diff --git a/packages/core/src/opendirector/cli.py b/packages/core/src/opendirector/cli.py index 66b34137b..45b9b124b 100644 --- a/packages/core/src/opendirector/cli.py +++ b/packages/core/src/opendirector/cli.py @@ -179,10 +179,11 @@ def timeline_import(ctx: typer.Context, file: Path, operation_id: Annotated[UUID if value['status'] != 'applied': raise typer.Exit(1) -TAKE_OVER_HINT = ("This project is being edited in another window, for example a browser tab that is still open " - "or was closed without leaving the project. Run the command again with --take-over before the " - "subcommand to move editing here; that window switches to preview and can take editing back with " - "\"Edit in this window\".") +TAKE_OVER_HINT = { + "en": ("Or, with the user's agreement, run the command again with --take-over before the subcommand; that window " + "then switches to preview and can take editing back with \u201cEdit in this window\u201d."), + "zh": "或经用户同意后,在子命令前加 --take-over 重新执行;该窗口会转为预览,可用\u201c在此编辑\u201d收回编辑权。", +} class Client: @@ -260,14 +261,15 @@ def snapshot(self): def open(self): if not self.live and not self.opened: if self.take_over: - self.request("POST", self.path("/edit-session")) + self.request("POST", self.path("/edit-session"), headers={"X-OpenDirector-Persistent": "false"}) else: try: self.request("POST", self.path("/open")) except ProjectError as error: if error.code != "project_open_elsewhere": raise - raise ProjectError(TAKE_OVER_HINT, 409, code=error.code) from None + language = "zh" if os.environ.get("OPENDIRECTOR_LANGUAGE", "en-US").lower().startswith("zh") else "en" + raise ProjectError(f"{error} {TAKE_OVER_HINT[language]}", 409, code=error.code) from None self.opened = True def execute(self, kind, payload, versions=(), preview=None, *, identity=None): @@ -345,8 +347,8 @@ def options(ctx: typer.Context, url: Annotated[str, typer.Option(envvar="OPENDIRECTOR_API_URL", help="Running OpenDirector server.")] = "http://127.0.0.1:18000", session: Annotated[UUID | None, typer.Option(envvar="OPENDIRECTOR_SESSION", help="Existing authorized edit session.")] = None, operation_id: Annotated[UUID | None, typer.Option(help="Stable write identity for safe replay.")] = None, - take_over: Annotated[bool, typer.Option("--take-over", envvar="OPENDIRECTOR_TAKE_OVER", - help="Take editing over from another window that holds the project, instead of failing.")] = False): + take_over: Annotated[bool, typer.Option("--take-over", + help="Take editing over from a window that holds the project instead of failing; that window switches to preview. Agents: ask the user first.")] = False): client = Client(project, url, session, operation_id, take_over) ctx.obj = client diff --git a/packages/core/src/opendirector/infrastructure/creation_projects.py b/packages/core/src/opendirector/infrastructure/creation_projects.py index ec6d7572a..676eac4e1 100644 --- a/packages/core/src/opendirector/infrastructure/creation_projects.py +++ b/packages/core/src/opendirector/infrastructure/creation_projects.py @@ -208,10 +208,10 @@ def editing_state(self, project_id, session): with self.local.transaction() as db: return self.local.editing_state(db, str(project_id), session) - def take_edit_ownership(self, project_id, session): + def take_edit_ownership(self, project_id, session, *, persistent=True): with self.local.transaction() as db: path, _ = self._find(db, project_id) - return self.local.take_edit_ownership(db, dict(id=str(project_id), path=str(path)), session) + return self.local.take_edit_ownership(db, dict(id=str(project_id), path=str(path)), session, persistent=persistent) def heartbeat(self, session, project_id): self.open(project_id, session) diff --git a/packages/core/src/opendirector/infrastructure/local_projects.py b/packages/core/src/opendirector/infrastructure/local_projects.py index e4d531c65..5ba37630c 100644 --- a/packages/core/src/opendirector/infrastructure/local_projects.py +++ b/packages/core/src/opendirector/infrastructure/local_projects.py @@ -167,11 +167,11 @@ def editing_state(self, db, project_id, session): editor = self.editor(db, project_id) return {'mode': 'edit' if editor and editor['id'] == session else 'preview'} - def take_edit_ownership(self, db, project, session): + def take_edit_ownership(self, db, project, session, *, persistent=True): editor = self.editor(db, project['id']) if editor and editor['id'] != session: db.execute("DELETE FROM sessions WHERE id=?", (editor['id'],)) - self.acquire_edit_lease(db, project, session, persistent=True) + self.acquire_edit_lease(db, project, session, persistent=persistent) return self.editing_state(db, project['id'], session) def agent_session_key(self, session: str) -> str: diff --git a/tests/test_cli.py b/tests/test_cli.py index 8692f0388..b1a295cb4 100644 --- a/tests/test_cli.py +++ b/tests/test_cli.py @@ -333,6 +333,33 @@ def forward(request): assert again.exit_code == 0, again.output assert api.post(path + "/edit-session", headers=window).json() == {"mode": "edit"} + monkeypatch.setenv("OPENDIRECTOR_LANGUAGE", "zh-CN") + chinese = runner.invoke(cli.app, ["--project", project, *write]) + assert chinese.exit_code == 1 + assert str(chinese.exception).startswith("该项目正在其他窗口中打开") + assert "--take-over" in str(chinese.exception) and "在此编辑" in str(chinese.exception) + monkeypatch.delenv("OPENDIRECTOR_LANGUAGE") + + kept = str(uuid4()) + held = runner.invoke(cli.app, ["--project", project, "--session", kept, "--take-over", *write]) + assert held.exit_code == 0, held.output + assert api.get(path + "/edit-session", headers={"X-OpenDirector-Session": kept}).json() == {"mode": "edit"} + + +def test_a_cli_takeover_lease_expires_like_any_cli_lease(tmp_path, monkeypatch): + from opendirector.infrastructure import local_projects + api = TestClient(create_app(LocalProjects(tmp_path)), headers={"X-OpenDirector-Request": "1"}) + project = str(uuid4()) + path = f"/api/creation/projects/{project}" + assert api.post(path + "/commands", json={"commandId": str(uuid4()), "projectId": project, "type": "project.create", + "payload": {"name": "Lease"}}).is_success + window, killed = {"X-OpenDirector-Session": str(uuid4())}, {"X-OpenDirector-Session": str(uuid4())} + assert api.post(path + "/open", headers={**window, "X-OpenDirector-Persistent": "true"}).is_success + assert api.post(path + "/edit-session", headers={**killed, "X-OpenDirector-Persistent": "false"}).json() == {"mode": "edit"} + later = local_projects.time.time() + LocalProjects.LEASE_SECONDS + 1 + monkeypatch.setattr(local_projects.time, "time", lambda: later) + assert api.post(path + "/open", headers={"X-OpenDirector-Session": str(uuid4())}).is_success + def test_all_cli_business_commands_have_help(help_color): runner = CliRunner() From 3be701706ebd4144e9c4b4bdc8c82633ead7ea7c Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E6=B1=AA=E5=BF=97=E9=B9=8F?= Date: Tue, 1 Dec 2026 11:44:20 +0000 Subject: [PATCH 3/3] [docs] cli: state that a CLI takeover lease lasts 60 s and is not renewed ## summary - The guide says the lease a `--take-over` command holds lapses after 60 s like any CLI lease, what that means for a long upload, and that with `--session` it still lapses unless that session renews it. - A test pins the browser's takeover lease: without the header it stays persistent past the lease time. Co-Authored-By: Claude Opus 5.5 --- docs/guides/cli.md | 2 +- tests/test_cli.py | 5 +++++ 2 files changed, 6 insertions(+), 1 deletion(-) diff --git a/docs/guides/cli.md b/docs/guides/cli.md index 1f086798c..afbfb2372 100644 --- a/docs/guides/cli.md +++ b/docs/guides/cli.md @@ -63,7 +63,7 @@ CLI 输出 JSON。修改回执附带对应的 assetId、itemId、specId 及其 读取类查询 `job.get`、`object.get`、`canvas.status` 与 `job.status` 不占用本轮执行锁,因此等待任务不会阻塞同轮其他工具调用。`job.status` 是 `job wait` 使用的批量查询:一次快照读取回答整组任务,并按需等待终态。 -普通终端写入申请独立编辑租约,完成后释放。浏览器窗口打开工程后会一直保留编辑权,关闭标签页也不会释放,此时 CLI 写入会返回占用错误,并提示可改用 `--take-over`。在子命令前加 `--take-over` 会把编辑权从该窗口移到本次命令:原窗口立即转为预览,未完成的保存会被拒绝,之后可用“在此编辑”收回。Agent 使用 `--take-over` 前须先征得用户同意。本次命令持有的编辑权与普通 CLI 写入一样会自动过期,进程被强行终止也不会长期占用;使用 `--session UUID` 时,接管的编辑权留在该会话,命令结束后不释放。 +普通终端写入申请独立编辑租约,完成后释放。浏览器窗口打开工程后会一直保留编辑权,关闭标签页也不会释放,此时 CLI 写入会返回占用错误,并提示可改用 `--take-over`。在子命令前加 `--take-over` 会把编辑权从该窗口移到本次命令:原窗口立即转为预览,未完成的保存会被拒绝,之后可用“在此编辑”收回。Agent 使用 `--take-over` 前须先征得用户同意。本次命令持有的编辑权与普通 CLI 写入一样为 60 秒且不自动续期,进程被强行终止也不会长期占用;单条命令(例如上传大文件)超过 60 秒时,写入可能因会话过期被拒,原窗口此时已转为预览,需要重新执行或在窗口中收回。使用 `--session UUID` 时,接管的编辑权留在该会话、命令结束后不释放,仍在 60 秒后过期,除非该会话自行续期。 Agent 的 Shell 通过 PATH 使用同一个 `opendirector`。宿主提供受令牌保护的本轮连接、工程范围、编辑会话和执行目录,文件登记限制在本轮执行目录。每次调用产生业务活动及回执,供聊天与轨迹页展示。 diff --git a/tests/test_cli.py b/tests/test_cli.py index b1a295cb4..c5aed0603 100644 --- a/tests/test_cli.py +++ b/tests/test_cli.py @@ -356,9 +356,14 @@ def test_a_cli_takeover_lease_expires_like_any_cli_lease(tmp_path, monkeypatch): window, killed = {"X-OpenDirector-Session": str(uuid4())}, {"X-OpenDirector-Session": str(uuid4())} assert api.post(path + "/open", headers={**window, "X-OpenDirector-Persistent": "true"}).is_success assert api.post(path + "/edit-session", headers={**killed, "X-OpenDirector-Persistent": "false"}).json() == {"mode": "edit"} + browser = {"X-OpenDirector-Session": str(uuid4())} later = local_projects.time.time() + LocalProjects.LEASE_SECONDS + 1 monkeypatch.setattr(local_projects.time, "time", lambda: later) assert api.post(path + "/open", headers={"X-OpenDirector-Session": str(uuid4())}).is_success + assert api.post(path + "/edit-session", headers=browser).json() == {"mode": "edit"} + much_later = later + 10 * LocalProjects.LEASE_SECONDS + monkeypatch.setattr(local_projects.time, "time", lambda: much_later) + assert api.get(path + "/edit-session", headers=browser).json() == {"mode": "edit"} def test_all_cli_business_commands_have_help(help_color):