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
5 changes: 3 additions & 2 deletions apps/api/src/opendirector_api/creation.py
Original file line number Diff line number Diff line change
Expand Up @@ -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):
Expand Down
2 changes: 1 addition & 1 deletion docs/guides/cli.md
Original file line number Diff line number Diff line change
Expand Up @@ -63,7 +63,7 @@ CLI 输出 JSON。修改回执附带对应的 assetId、itemId、specId 及其

读取类查询 `job.get`、`object.get`、`canvas.status` 与 `job.status` 不占用本轮执行锁,因此等待任务不会阻塞同轮其他工具调用。`job.status` 是 `job wait` 使用的批量查询:一次快照读取回答整组任务,并按需等待终态。

普通终端写入申请独立编辑租约,完成后释放。工程已在其他窗口编辑时会返回占用错误。使用 `--session UUID` 表示沿用已有授权会话,CLI 完成后保留该会话。
普通终端写入申请独立编辑租约,完成后释放。浏览器窗口打开工程后会一直保留编辑权,关闭标签页也不会释放,此时 CLI 写入会返回占用错误,并提示可改用 `--take-over`。在子命令前加 `--take-over` 会把编辑权从该窗口移到本次命令:原窗口立即转为预览,未完成的保存会被拒绝,之后可用“在此编辑”收回。Agent 使用 `--take-over` 前须先征得用户同意。本次命令持有的编辑权与普通 CLI 写入一样为 60 秒且不自动续期,进程被强行终止也不会长期占用;单条命令(例如上传大文件)超过 60 秒时,写入可能因会话过期被拒,原窗口此时已转为预览,需要重新执行或在窗口中收回。使用 `--session UUID` 时,接管的编辑权留在该会话、命令结束后不释放,仍在 60 秒后过期,除非该会话自行续期。

Agent 的 Shell 通过 PATH 使用同一个 `opendirector`。宿主提供受令牌保护的本轮连接、工程范围、编辑会话和执行目录,文件登记限制在本轮执行目录。每次调用产生业务活动及回执,供聊天与轨迹页展示。

Expand Down
27 changes: 23 additions & 4 deletions packages/core/src/opendirector/cli.py
Original file line number Diff line number Diff line change
Expand Up @@ -179,9 +179,17 @@ def timeline_import(ctx: typer.Context, file: Path, operation_id: Annotated[UUID
if value['status'] != 'applied': raise typer.Exit(1)


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:
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
Expand Down Expand Up @@ -252,7 +260,16 @@ 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"), headers={"X-OpenDirector-Persistent": "false"})
else:
try:
self.request("POST", self.path("/open"))
except ProjectError as error:
if error.code != "project_open_elsewhere":
raise
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):
Expand Down Expand Up @@ -329,8 +346,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",
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

def close():
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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:
Expand Down
63 changes: 63 additions & 0 deletions tests/test_cli.py
Original file line number Diff line number Diff line change
Expand Up @@ -303,6 +303,69 @@ 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"}

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"}
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):
runner = CliRunner()
for kind in cli.COMMANDS:
Expand Down
Loading