From 8be8783ccd7c4d706397864baad4d2c32d3327d9 Mon Sep 17 00:00:00 2001 From: Weiming Liao Date: Tue, 24 Nov 2026 21:25:51 +0800 Subject: [PATCH] [bugfix] agent: keep project writes authorized during a turn Signed-off-by: Weiming Liao --- apps/api/src/opendirector_api/agent.py | 83 +++++++++++----- docs/architecture/agent-runtime.md | 4 + .../infrastructure/creation_projects.py | 7 +- .../infrastructure/local_projects.py | 26 ++++- tests/test_assistant_conversations.py | 96 ++++++++++++++++++- 5 files changed, 188 insertions(+), 28 deletions(-) diff --git a/apps/api/src/opendirector_api/agent.py b/apps/api/src/opendirector_api/agent.py index f024ea7cf..b1e2cfdb2 100644 --- a/apps/api/src/opendirector_api/agent.py +++ b/apps/api/src/opendirector_api/agent.py @@ -7,7 +7,7 @@ from pathlib import Path import time from typing import Annotated, Literal -from uuid import UUID, uuid5 +from uuid import UUID, uuid4, uuid5 from anyio import CancelScope from fastapi import APIRouter, Header @@ -121,17 +121,17 @@ def path(self, project_id: UUID, session: str | None = None) -> Path: self.projects._recover() directory, _, _ = self.projects._load(db, project_id) if session: - self.projects._lease(db, project_id, directory, session) + self.projects._lease(db, project_id, directory, session, browser_only=True) return directory def update(self, project_id: UUID, session: str | None = None, *, draft: Draft | None = None, begin: dict | None = None, finish: dict | None = None, conversation_id: UUID | None = None, - before_begin=None) -> dict: + before_begin=None, agent_session: str | None = None) -> dict: with self.projects.local.transaction() as db: self.projects._recover() directory, _, _ = self.projects._load(db, project_id) if session: - self.projects._lease(db, project_id, directory, session) + self.projects._lease(db, project_id, directory, session, browser_only=True) folder = child(directory, 'agent-runs') folder.mkdir(exist_ok=True) file = child(folder, 'conversation.json') @@ -149,6 +149,8 @@ def update(self, project_id: UUID, session: str | None = None, *, draft: Draft | raise ProjectError('这条消息已接受,请读取对话,不要重复发送。', 409) if before_begin is not None: before_begin() + if agent_session is not None: + self.projects.local.start_agent_session(db, project_id, directory, agent_session) value['messages'].append(begin) value['messages'].append({'id': str(uuid5(UUID(begin['id']), 'assistant')), 'role': 'assistant', 'text': '', 'status': 'streaming', @@ -236,7 +238,7 @@ def activate(self, project_id: UUID, conversation_id: UUID, session: str, *, cre with self.projects.local.transaction() as db: self.projects._recover() directory, _, _ = self.projects._load(db, project_id) - self.projects._lease(db, project_id, directory, session) + self.projects._lease(db, project_id, directory, session, browser_only=True) folder = child(directory, 'agent-runs') folder.mkdir(exist_ok=True) file = child(folder, 'conversation.json') @@ -472,6 +474,16 @@ def validate_connection(): if config is not None: current = configs.resolve(str(value.modelId), 'agent') generation.availability.require(current, _assistant_request(current), prepared) + async def renew_agent_session(run_session: str) -> None: + while True: + await asyncio.sleep(projects.local.LEASE_SECONDS / 3) + try: + if not await asyncio.to_thread(projects.local.renew_agent_session, run_session): + return + except Exception: + # A transient lock or I/O failure can recover before the lease expires. + logger.exception('Could not renew Agent project write session') + async def produce() -> None: text, status, error, accepted = '', 'complete', None, False activities = [] @@ -480,6 +492,9 @@ async def produce() -> None: sources = {} previous_sources = {} plan = None + run_session = str(uuid4()) + renewal = None + admission_write = None try: user = {'id': str(value.id), 'role': 'user', 'text': value.text, 'content': value.content, 'assets': [{'id': str(asset.id), 'name': asset.name, 'type': asset.metadata.mimeType, @@ -488,9 +503,19 @@ async def produce() -> None: 'skills': value.skills, 'runtime': value.runtime, 'runtimeModel': value.runtimeModel, 'modelSelections': dict(value.modelSelections), 'model': model, 'modelIsCliDefault': model_is_cli_default, 'status': 'complete'} - saved = await asyncio.to_thread(conversations.update, project_id, session, begin=user, - conversation_id=value.conversationId, before_begin=validate_connection) + admission_write = asyncio.create_task(asyncio.to_thread( + conversations.update, project_id, session, begin=user, + conversation_id=value.conversationId, before_begin=validate_connection, + agent_session=run_session)) + try: + saved = await asyncio.shield(admission_write) + except asyncio.CancelledError: + # A worker already writing admission can outlive task cancellation. + await admission_write + accepted = True + raise accepted = True + renewal = asyncio.create_task(renew_agent_session(run_session)) events.put({'type': 'start', 'conversation': saved}) previous_sources = {source['id']: source for message in saved['messages'][:-2] for source in message.get('sources', [])} @@ -512,7 +537,7 @@ async def produce() -> None: context[-1]['content'] += '\nUser model preferences for this turn: ' + json.dumps(preferences, ensure_ascii=False) context[-1]['content'] += '\nUse these models for new generation unless the user explicitly requests another. If unavailable or unsuitable, explain and ask before substituting. Keep existing nodes on their configured models unless the user requests a change.' run = RunContext(runtime=value.runtime, project_id=project_id, turn_id=value.id, - session=session, directory=directory, config=config, messages=context, + session=run_session, directory=directory, config=config, messages=context, selected_skills=value.skills, thinking=value.thinking, model_selections=model_selections, runtime_model=value.runtimeModel, skills=available, conversation_id=UUID(saved['conversationId'])) async with aclosing(runtimes.stream(run)) as stream: @@ -560,21 +585,33 @@ async def produce() -> None: status=500, code='operation_rejected') logger.exception(f'agent.turn.failed project_id={project_id} turn_id={value.id}') finally: - # Measurement is best effort: losing the ledger is acceptable, - # losing the turn's reply is not. - if accepted: - agent_timing.write(directory, value.id, timing, round(time.monotonic() - turn_started, 3)) - for activity in activities: - if activity['status'] == 'running': - activity['status'] = 'interrupted' - saved = await asyncio.to_thread(conversations.update, project_id, finish={ - 'id': str(uuid5(value.id, 'assistant')), 'role': 'assistant', 'text': text, 'status': status, - 'model': model, 'modelIsCliDefault': model_is_cli_default, - 'runtime': value.runtime, 'thinking': value.thinking, 'tools': activities, - 'sources': list(sources.values()), - **({'plan': plan} if plan is not None else {})}, conversation_id=value.conversationId) - else: - saved = None + try: + # Measurement is best effort: losing the ledger is acceptable, + # losing the turn's reply is not. + if accepted: + agent_timing.write(directory, value.id, timing, round(time.monotonic() - turn_started, 3)) + for activity in activities: + if activity['status'] == 'running': + activity['status'] = 'interrupted' + saved = await asyncio.to_thread(conversations.update, project_id, finish={ + 'id': str(uuid5(value.id, 'assistant')), 'role': 'assistant', 'text': text, 'status': status, + 'model': model, 'modelIsCliDefault': model_is_cli_default, + 'runtime': value.runtime, 'thinking': value.thinking, 'tools': activities, + 'sources': list(sources.values()), + **({'plan': plan} if plan is not None else {})}, conversation_id=value.conversationId) + else: + saved = None + finally: + if renewal is not None: + renewal.cancel() + with suppress(asyncio.CancelledError): + await renewal + if admission_write is not None: + try: + await asyncio.to_thread(projects.local.release_agent_session, run_session) + except Exception: + # The lease still expires when renewal stops. + logger.exception('Could not release Agent project write session') events.put({'type': 'end', 'conversation': saved, 'error': error}) if project_id in active: diff --git a/docs/architecture/agent-runtime.md b/docs/architecture/agent-runtime.md index b7112235c..5189d2628 100644 --- a/docs/architecture/agent-runtime.md +++ b/docs/architecture/agent-runtime.md @@ -39,6 +39,10 @@ Default 与 OpenCode CLI 分别配置。外部 CLI 不读取 OpenDirector 保存 业务入口使用 Typer CLI,通过 `opendirector --help` 和子命令的 `--help` 渐进发现操作。查询、编辑及生成命令调用共用业务服务。Agent 通过受令牌保护的本轮连接继承工程范围、编辑会话、执行目录和操作回执;CLI 子进程退出不终止已接受的后台任务。普通终端通过现有 HTTP API 连接服务,写入申请独立编辑会话并遵守工程锁,查询不申请租约。`--session` 可使用已有授权会话。`--operation-id` 提供稳定修改身份,同身份相同输入重放返回原回执,不同输入拒绝。 +接受轮次时,服务端校验画布的工程会话,并为本轮签发独立的工程写入租约。运行期间服务端负责续租,画布关闭或断线后仍可执行本轮已授权的写入。运行结束或停止后释放租约。工程路径、对象锁和预期版本仍由共享业务服务校验,重新打开画布后用户可以继续编辑。 + +The server validates the canvas session when it accepts a turn and grants the turn its own project write lease. The server renews that lease while the turn runs, including after the canvas closes or disconnects, and releases it when the turn completes or stops. The shared services still check the project path, object locks and expected revisions. A reopened canvas can edit concurrently. + 新文件通过 `opendirector asset import` 登记,再根据需要调用 `opendirector canvas add-material` 展示。发布回执、素材登记和画布展示分别表达,不以创建节点代替文件交付。 ## Skill 加载与媒体输入 diff --git a/packages/core/src/opendirector/infrastructure/creation_projects.py b/packages/core/src/opendirector/infrastructure/creation_projects.py index 022b81174..2f1e2e0aa 100644 --- a/packages/core/src/opendirector/infrastructure/creation_projects.py +++ b/packages/core/src/opendirector/infrastructure/creation_projects.py @@ -80,12 +80,13 @@ def __init__(self, local: LocalProjects): def _checkpoint(self, stage): """Fault-injection boundary. Never participates in production decisions.""" - def _lease(self, db, project_id, path, session): + def _lease(self, db, project_id, path, session, *, browser_only=False): if session is None: raise ProjectError('修改工程需要已打开的会话。', 409) identifier(session) - lease = db.execute('SELECT path FROM sessions WHERE id=? AND project_id=? AND expires>?', - (session, str(project_id), time.time())).fetchone() + agent_key = session if browser_only else self.local.agent_session_key(session) + lease = db.execute('SELECT path FROM sessions WHERE id IN (?,?) AND project_id=? AND expires>?', + (session, agent_key, str(project_id), time.time())).fetchone() if lease is None: # A stable code lets the page renew its lease and resend instead of failing every save. raise ProjectError('工程已关闭或会话已过期,请重新打开后保存。', 409, code='session_expired') diff --git a/packages/core/src/opendirector/infrastructure/local_projects.py b/packages/core/src/opendirector/infrastructure/local_projects.py index 2e515e9d8..cab63bffa 100644 --- a/packages/core/src/opendirector/infrastructure/local_projects.py +++ b/packages/core/src/opendirector/infrastructure/local_projects.py @@ -72,6 +72,9 @@ def write_json(path: Path, value) -> None: class LocalProjects: """Coordination only; never reads, migrates or repairs old project data.""" LEASE_SECONDS = 60 + # A run blocks project moves and deletion like a browser lease. Its + # separate key lets browsers open or release their own editing session. + _AGENT_SESSION_PREFIX = "agent:" def __init__(self, repository: Path): self.repository = repository.resolve() @@ -122,7 +125,8 @@ def _conflict(parent: Path, name: str, source: Path | None = None): def _open(self, db, project: dict, session: str): identifier(session) project_id = project["id"] - if db.execute("SELECT 1 FROM sessions WHERE project_id=? AND id<>? AND expires>?", (project_id, session, time.time())).fetchone(): + 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") lease = db.execute("SELECT path FROM sessions WHERE id=? AND project_id=? AND expires>?", (session, project_id, time.time())).fetchone() if lease and lease["path"] != project["path"]: @@ -130,6 +134,26 @@ 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 agent_session_key(self, session: str) -> str: + return self._AGENT_SESSION_PREFIX + identifier(session) + + def start_agent_session(self, db, project_id, path: Path, session: str): + """Called in the transaction that validates the browser lease and accepts the turn.""" + now = time.time() + db.execute("DELETE FROM sessions WHERE expires<=? AND id LIKE ?", + (now, self._AGENT_SESSION_PREFIX + "%")) + db.execute("INSERT INTO sessions(id,project_id,expires,path) VALUES (?,?,?,?)", + (self.agent_session_key(session), str(project_id), now + self.LEASE_SECONDS, str(path))) + + def renew_agent_session(self, session: str) -> bool: + with self.transaction() as db: + now = time.time() + return bool(db.execute("UPDATE sessions SET expires=? WHERE id=? AND expires>?", + (now + self.LEASE_SECONDS, self.agent_session_key(session), now)).rowcount) + + def release_agent_session(self, session: str): + self.release(self.agent_session_key(session)) + def release(self, session: str): with self.transaction() as db: db.execute("DELETE FROM sessions WHERE id=?", (session,)) diff --git a/tests/test_assistant_conversations.py b/tests/test_assistant_conversations.py index dcd05498b..134894776 100644 --- a/tests/test_assistant_conversations.py +++ b/tests/test_assistant_conversations.py @@ -2,17 +2,20 @@ from concurrent.futures import ThreadPoolExecutor import json import threading +import time from uuid import uuid4 from fastapi.testclient import TestClient import pytest +from opendirector.agent.native import NativeRuntime from opendirector.infrastructure.local_projects import LocalProjects from opendirector_api.main import create_app from opendirector_api import agent pytestmark = pytest.mark.cpu +runtime_stream = agent.AgentRuntimes.stream def frames(response): @@ -428,10 +431,12 @@ def test_image_reference_reaches_runtime_with_media_metadata(assistant): assert contexts[-1][0]['content'].split('\nReferenced project assets: ', 1)[1].split('\n', 1)[0] == json.dumps(references, ensure_ascii=False) -def test_stop_releases_project_after_saving_partial_reply(assistant, monkeypatch): +def test_stop_releases_project_after_saving_partial_reply(assistant, monkeypatch, tmp_path): client, path, _ = assistant started = threading.Event() + sessions = [] async def stream(self, run): + sessions.append(run.session) yield {'type': 'delta', 'text': '保留部分回复'} started.set() await asyncio.Event().wait() @@ -446,6 +451,10 @@ async def stream(self, run): saved = client.get(path).json()['messages'][-1] assert saved['status'] == 'stopped' assert saved['text'] == '保留部分回复' + store = LocalProjects(tmp_path) + with store.transaction() as db: + assert db.execute('SELECT 1 FROM sessions WHERE id=?', + (store.agent_session_key(sessions[0]),)).fetchone() is None assert client.post(path + '/conversations', json={'id': str(uuid4())}).status_code == 200 async def finished(self, run): yield {'type': 'delta', 'text': '新回复'} @@ -587,3 +596,88 @@ async def stream(self, run): saved = client.get(path).json()['messages'][-1] assert 'timing' not in json.dumps(saved['tools']) assert json.loads(next(tmp_path.glob('**/agent-runs/conversation.json')).read_text(encoding='utf-8'))['messages'][-1] == saved + + +@pytest.mark.parametrize('browser_state', ['closed', 'expired', 'edited']) +def test_background_turn_keeps_write_session_and_checks_revisions(assistant, monkeypatch, browser_state): + client, path, _ = assistant + root = path.removesuffix('/assistant') + project_id = root.rsplit('/', 1)[1] + browser_session = client.headers['X-OpenDirector-Session'] + spec_id = str(uuid4()) + created = client.post(root + '/commands', json={ + 'type': 'generationSpec.create', 'projectId': project_id, 'commandId': str(uuid4()), + 'payload': {'spec': {'id': spec_id, 'projectId': project_id, 'kind': 'text', 'purpose': 'draft'}}, + }).json() + assert created['status'] == 'applied', created + monkeypatch.setattr(LocalProjects, 'LEASE_SECONDS', 1.5) + assert client.post(root + '/open').status_code == 200 + release = threading.Event() + results = {} + + def update_prompt(prompt): + return {'type': 'generationSpec.setPrompt', 'payload': {'specId': spec_id, 'prompt': prompt}, + 'expectedVersions': [{'objectType': 'generation_spec', 'id': spec_id, 'revision': 1}]} + + async def stream(self, run, gateway): + results['session'] = run.session + results['store'] = gateway.business.projects.local + yield {'type': 'delta', 'text': 'Waiting for generation'} + assert await asyncio.to_thread(release.wait, 10) + results['prompt'] = (await gateway.call('save', 'execute_command', update_prompt('Agent draft'))).value + results['asset'] = (await gateway.call('publish', 'execute_command', { + 'type': 'asset.writeText', 'payload': {'name': 'Result.md', 'text': 'Agent result'}, + })).value + yield {'type': 'delta', 'text': 'Finished'} + + # The fixture normally doubles AgentRuntimes.stream. Restore the shared + # gateway and double only the adapter's model output for this regression. + monkeypatch.setattr(agent.AgentRuntimes, 'stream', runtime_stream) + monkeypatch.setattr(NativeRuntime, 'stream', stream) + turn_id = str(uuid4()) + disconnect_turn(client, path, turn_id) + try: + store = results['store'] + run_session = results['session'] + session_path = '/api/creation/sessions/' + if browser_state != 'expired': + assert client.delete(session_path + browser_session).status_code == 200 + # Wait past the original lease, so the test needs server renewal. + time.sleep(store.LEASE_SECONDS + 0.05) + assert client.post(path + f'/turns/{turn_id}/stop').status_code == 409 + if browser_state == 'closed': + rename = {'type': 'project.rename', 'projectId': project_id, 'commandId': str(uuid4()), + 'payload': {'name': 'Moved project'}, + 'expectedVersions': [{'objectType': 'project', 'id': project_id, 'revision': 1}]} + assert client.post(root + '/commands', json=rename).status_code == 409 + if browser_state == 'edited': + other_window = {'X-OpenDirector-Session': str(uuid4())} + assert client.post(root + '/open', headers=other_window).status_code == 200 + receipt = client.post(root + '/commands', headers=other_window, json={ + **update_prompt('User draft'), 'projectId': project_id, 'commandId': str(uuid4()), + }).json() + assert receipt['status'] == 'applied', receipt + finally: + release.set() + + response = client.get(path + f'/turns/{turn_id}/events') + if response.status_code == 200: + assert frames(response)[-1]['error'] is None + else: + assert response.status_code == 404, response.text + assert client.get(path).json()['messages'][-1]['status'] == 'complete' + snapshot = client.get(root).json() + spec = next(spec for spec in snapshot['generationSpecs'] if spec['id'] == spec_id) + assert results['asset'].get('status') == 'applied', results['asset'] + assert any(asset['name'] == 'Result.md' for asset in snapshot['assets']) + assert run_session != browser_session + if browser_state == 'edited': + assert results['prompt']['status'] == 'rejected' + assert results['prompt']['issues'][0]['code'] == 'revision_conflict' + assert spec['prompt'] == 'User draft' + else: + assert results['prompt']['status'] == 'applied' + assert spec['prompt'] == 'Agent draft' + with store.transaction() as db: + assert db.execute('SELECT 1 FROM sessions WHERE id=?', + (store.agent_session_key(run_session),)).fetchone() is None