From 2851f19b05fcaf9ccf64b191cdf40f05556e7b6d Mon Sep 17 00:00:00 2001 From: wtz2333 Date: Tue, 17 Nov 2026 11:30:40 +0800 Subject: [PATCH 1/6] [feat] agent: take back a queued message and continue a stalled queue A message waiting behind the active turn could be changed by nothing but sending it: withdrawing it meant stopping the whole chain, which also threw away the turn that was running. Retracting removes a message that has not started, under the same lock the chain takes when it picks the next one up, so it is either still waiting and goes away or it has started and the caller is told to stop it instead. A failure leaves the queue waiting rather than spending it, and continuing by hand starts the oldest message without retyping it. Refs #379 --- apps/api/src/opendirector_api/agent.py | 58 +++++++++++ tests/test_assistant_retract.py | 133 +++++++++++++++++++++++++ 2 files changed, 191 insertions(+) create mode 100644 tests/test_assistant_retract.py diff --git a/apps/api/src/opendirector_api/agent.py b/apps/api/src/opendirector_api/agent.py index e049f80c5..88d3d6ce5 100644 --- a/apps/api/src/opendirector_api/agent.py +++ b/apps/api/src/opendirector_api/agent.py @@ -248,6 +248,29 @@ def cancel_queued(self, project_id: UUID, session: str | None = None) -> list[di durable_json(file, value) return cancelled + def retract(self, project_id: UUID, session: str, message_id: UUID) -> dict: + """Take a message back while it is still waiting in the queue. + + A message that already started belongs to the conversation now: it can + be stopped, but removing it would leave the reply it produced without + the words that asked for it. + """ + 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) + file = child(child(directory, 'agent-runs'), 'conversation.json') + value = read_json(file) if file.exists() else {'messages': [], **Draft().model_dump()} + found = next((item for item in value['messages'] if item['id'] == str(message_id)), None) + if found is None: + raise ProjectError('这条消息不在当前对话里,请重新加载。', 404) + if found.get('status') != 'queued': + raise ProjectError('这条消息已经开始执行,停止回复后才能撤回。', 409) + value['messages'] = [item for item in value['messages'] if item['id'] != str(message_id)] + durable_json(file, value) + result = public_conversation(value) + return {'retracted': str(message_id), 'conversation': with_trace_sources(result, directory)} + def list(self, project_id: UUID) -> dict: directory = self.path(project_id) file = child(child(directory, 'agent-runs'), 'conversation.json') @@ -912,4 +935,39 @@ async def message(project_id: UUID, value: Turn, x_opendirector_session: UUID = started['run_session'] = start_session return launch(project_id, started, UUID(dispatched['conversation']['conversationId'])) + @router.delete('/messages/{message_id}') + async def retract(project_id: UUID, message_id: UUID, x_opendirector_session: UUID = Header()): + """Take back a message that has not started yet. + + Retracting under the admission lock is what keeps it from being picked + up in the same instant: the message is either still waiting and goes + away, or it has started and the caller is told to stop it instead. + """ + session = str(x_opendirector_session) + async with admission.setdefault(project_id, asyncio.Lock()): + result = await asyncio.to_thread(conversations.retract, project_id, session, message_id) + chain = active.get(project_id) + if chain is not None: + chain.events.put({'type': 'retracted', 'messageId': str(message_id)}) + return result + + @router.post('/queue/dispatch') + async def dispatch(project_id: UUID, x_opendirector_session: UUID = Header(), + accept_language: str | None = Header(default=None, alias='Accept-Language')): + """Continue the queue when nothing is running. + + Messages outlive a restart, and a turn that failed leaves them waiting; + this starts the oldest one so the user does not have to retype it. + """ + session = str(x_opendirector_session) + async with admission.setdefault(project_id, asyncio.Lock()): + if project_id in active: + raise ProjectError('当前工程已有回复正在执行。', 409) + dispatched = await asyncio.to_thread(conversations.dispatch, project_id, session) + if dispatched is None: + raise ProjectError('没有等待执行的排队消息。', 409) + plan = await plan_for(project_id, dispatched['message'], session, accept_language) + plan['start'] = dispatched['conversation'] + return launch(project_id, plan, UUID(dispatched['conversation']['conversationId'])) + return router diff --git a/tests/test_assistant_retract.py b/tests/test_assistant_retract.py new file mode 100644 index 000000000..3ea7f535d --- /dev/null +++ b/tests/test_assistant_retract.py @@ -0,0 +1,133 @@ +"""A waiting message can be taken back, and a stalled queue can be continued. + +#379: a supplementary message waits for the active turn. These cases pin what +happens around that wait: a message that has not started can be withdrawn, a +message that has started cannot, and a queue left behind by a failed turn waits +for the user instead of running on its own and then can be continued by hand. +""" +import asyncio +from concurrent.futures import ThreadPoolExecutor +import json +import threading +from uuid import UUID, uuid4, uuid5 + +from fastapi.testclient import TestClient +import pytest + +from opendirector.infrastructure.local_projects import LocalProjects +from opendirector_api.main import create_app +from opendirector_api import agent + + +def frames(response): + return [json.loads(line[6:]) for line in response.text.splitlines() if line.startswith('data: ')] + + +async def empty_skills(*args): + return [] + + +@pytest.fixture +def assistant(tmp_path, monkeypatch): + """A project whose turns block until the test lets them finish.""" + contexts = [] + gate = {'started': threading.Event(), 'release': threading.Event(), 'fail': threading.Event()} + + async def stream(self, run): + contexts.append(run.messages) + gate['started'].set() + yield {'type': 'delta', 'text': '收到:' + run.messages[-1]['content']} + await asyncio.to_thread(gate['release'].wait, 10) + if gate['fail'].is_set(): + raise RuntimeError('provider down') + yield {'type': 'delta', 'text': '|完'} + + monkeypatch.setattr(agent.AgentRuntimes, 'stream', stream) + monkeypatch.setattr(agent, 'runtime_available', lambda _: True) + monkeypatch.setattr(agent, 'skills', empty_skills) + from opendirector.infrastructure.model_configs import ModelConfigs + monkeypatch.setattr(ModelConfigs, 'resolve', lambda *args: {'id': str(uuid4()), 'modelId': 'test-model'}) + with TestClient(create_app(LocalProjects(tmp_path)), headers={ + 'X-OpenDirector-Request': '1', 'X-OpenDirector-Session': str(uuid4())}) as client: + pid = str(uuid4()) + root = f'/api/creation/projects/{pid}' + assert client.post(root + '/commands', json={'type': 'project.create', 'projectId': pid, + 'commandId': str(uuid4()), 'payload': {'name': '撤回'}}).status_code == 200 + assert client.post(root + '/open').status_code == 200 + yield client, root + '/assistant', contexts, gate + + +def test_a_queued_message_can_be_taken_back_before_it_runs(assistant): + client, path, contexts, gate = assistant + cid = client.get(path).json()['conversationId'] + first, second = str(uuid4()), str(uuid4()) + with ThreadPoolExecutor() as pool: + running = pool.submit(client.post, path + '/turns', json={ + 'id': first, 'runtime': 'default', 'conversationId': cid, 'text': '先做这个'}) + assert gate['started'].wait(5) + assert client.post(path + '/messages', json={ + 'id': second, 'runtime': 'default', 'conversationId': cid, 'text': '再补一句'}).status_code == 202 + taken = client.delete(path + f'/messages/{second}') + assert taken.status_code == 200, taken.text + assert taken.json()['retracted'] == second + # The message is gone from the thread the user is reading, while the + # turn that is still running keeps its own reply in place. + assert [item['id'] for item in taken.json()['conversation']['messages']] == [ + first, str(uuid5(UUID(first), 'assistant'))] + gate['release'].set() + events = frames(running.result(timeout=10)) + + # The turn that was already running is not disturbed, and nothing runs after it. + assert [event['turnId'] for event in events if event['type'] == 'end'] == [first] + assert [context[-1]['content'] for context in contexts] == ['先做这个'] + assert [item['status'] for item in client.get(path).json()['messages']] == ['complete', 'complete'] + + +def test_a_message_that_already_started_is_stopped_not_removed(assistant): + client, path, contexts, gate = assistant + cid = client.get(path).json()['conversationId'] + first = str(uuid4()) + with ThreadPoolExecutor() as pool: + running = pool.submit(client.post, path + '/turns', json={ + 'id': first, 'runtime': 'default', 'conversationId': cid, 'text': '做到一半'}) + assert gate['started'].wait(5) + started = client.delete(path + f'/messages/{first}') + assert started.status_code == 409 and '已经开始执行' in started.json()['detail'] + unknown = client.delete(path + f'/messages/{uuid4()}') + assert unknown.status_code == 404 and '不在当前对话里' in unknown.json()['detail'] + gate['release'].set() + frames(running.result(timeout=10)) + + # A message that has begun is part of the record: it stays, with its reply. + assert [item['status'] for item in client.get(path).json()['messages']] == ['complete', 'complete'] + assert len(contexts) == 1 + + +def test_a_failed_turn_leaves_the_queue_to_be_continued_by_hand(assistant): + client, path, contexts, gate = assistant + cid = client.get(path).json()['conversationId'] + first, second = str(uuid4()), str(uuid4()) + gate['fail'].set() + with ThreadPoolExecutor() as pool: + running = pool.submit(client.post, path + '/turns', json={ + 'id': first, 'runtime': 'default', 'conversationId': cid, 'text': '先做这个'}) + assert gate['started'].wait(5) + assert client.post(path + '/messages', json={ + 'id': second, 'runtime': 'default', 'conversationId': cid, 'text': '补一句'}).status_code == 202 + gate['release'].set() + events = frames(running.result(timeout=10)) + + assert events[-1]['error'] is not None + # A failure does not spend the queue by itself, and it is not silent about it. + assert [item['status'] for item in client.get(path).json()['messages']] == [ + 'complete', 'interrupted', 'queued'] + assert [context[-1]['content'] for context in contexts] == ['先做这个'] + + gate['fail'].clear() + continued = client.post(path + '/queue/dispatch') + assert continued.status_code == 200, continued.text + tail = frames(continued) + assert tail[-1]['conversation']['messages'][-1]['text'] == '收到:补一句|完' + # Nothing is left waiting, so continuing again has nothing to start. + assert client.post(path + '/queue/dispatch').status_code == 409 + assert 'activeTurnId' not in client.get(path).json() From 48bdcf02396ac0bcd61e14af70e10d0a8e0d3038 Mon Sep 17 00:00:00 2001 From: wtz2333 Date: Fri, 20 Nov 2026 15:00:25 +0800 Subject: [PATCH 2/6] [test] assistant: give the retract fixture the agent config shape a turn needs --- tests/test_assistant_retract.py | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/tests/test_assistant_retract.py b/tests/test_assistant_retract.py index 3ea7f535d..e19d627c9 100644 --- a/tests/test_assistant_retract.py +++ b/tests/test_assistant_retract.py @@ -46,7 +46,9 @@ async def stream(self, run): monkeypatch.setattr(agent, 'runtime_available', lambda _: True) monkeypatch.setattr(agent, 'skills', empty_skills) from opendirector.infrastructure.model_configs import ModelConfigs - monkeypatch.setattr(ModelConfigs, 'resolve', lambda *args: {'id': str(uuid4()), 'modelId': 'test-model'}) + config = {'id': str(uuid4()), 'modelId': 'test-model', 'kind': 'agent', 'url': 'http://models.test/v1', + 'connectionType': 'api', 'protocol': 'openai', 'authMode': 'none', 'apiKey': ''} + monkeypatch.setattr(ModelConfigs, 'resolve', lambda *args: dict(config)) with TestClient(create_app(LocalProjects(tmp_path)), headers={ 'X-OpenDirector-Request': '1', 'X-OpenDirector-Session': str(uuid4())}) as client: pid = str(uuid4()) From 20f2b13b52442df5042d16992de329e61a250fd5 Mon Sep 17 00:00:00 2001 From: wtz2333 Date: Tue, 17 Nov 2026 11:30:40 +0800 Subject: [PATCH 3/6] [feat] agent: take back a queued message and continue a stalled queue A message waiting behind the active turn could be changed by nothing but sending it: withdrawing it meant stopping the whole chain, which also threw away the turn that was running. Retracting removes a message that has not started, under the same lock the chain takes when it picks the next one up, so it is either still waiting and goes away or it has started and the caller is told to stop it instead. A failure leaves the queue waiting rather than spending it, and continuing by hand starts the oldest message without retyping it. Refs #379 --- apps/api/src/opendirector_api/agent.py | 23 +++++++++++++++++++++++ 1 file changed, 23 insertions(+) diff --git a/apps/api/src/opendirector_api/agent.py b/apps/api/src/opendirector_api/agent.py index 88d3d6ce5..79e2929a9 100644 --- a/apps/api/src/opendirector_api/agent.py +++ b/apps/api/src/opendirector_api/agent.py @@ -271,6 +271,29 @@ def retract(self, project_id: UUID, session: str, message_id: UUID) -> dict: result = public_conversation(value) return {'retracted': str(message_id), 'conversation': with_trace_sources(result, directory)} + def retract(self, project_id: UUID, session: str, message_id: UUID) -> dict: + """Take a message back while it is still waiting in the queue. + + A message that already started belongs to the conversation now: it can + be stopped, but removing it would leave the reply it produced without + the words that asked for it. + """ + 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) + file = child(child(directory, 'agent-runs'), 'conversation.json') + value = read_json(file) if file.exists() else {'messages': [], **Draft().model_dump()} + found = next((item for item in value['messages'] if item['id'] == str(message_id)), None) + if found is None: + raise ProjectError('这条消息不在当前对话里,请重新加载。', 404) + if found.get('status') != 'queued': + raise ProjectError('这条消息已经开始执行,停止回复后才能撤回。', 409) + value['messages'] = [item for item in value['messages'] if item['id'] != str(message_id)] + durable_json(file, value) + result = public_conversation(value) + return {'retracted': str(message_id), 'conversation': with_trace_sources(result, directory)} + def list(self, project_id: UUID) -> dict: directory = self.path(project_id) file = child(child(directory, 'agent-runs'), 'conversation.json') From f1a60508a5d288ae3e51206b38a4c000e85aa7c6 Mon Sep 17 00:00:00 2001 From: wtz2333 Date: Thu, 19 Nov 2026 10:01:28 +0800 Subject: [PATCH 4/6] [feat] agent: insert a message into a reply that is already running Codex now runs as an app-server session instead of a one-shot exec, so a turn has a channel for extra text while it works: POST /assistant/messages with delivery "insert" hands the words to turn/steer and the answer keeps the work it has already done. Runtimes without a native channel refuse the insert and say so, leaving the queued delivery as the fallback. --- apps/api/src/opendirector_api/agent.py | 59 +++++- docs/architecture/agent-runtime.md | 6 +- .../core/src/opendirector/agent/appserver.py | 164 +++++++++++++++++ .../core/src/opendirector/agent/context.py | 3 + .../core/src/opendirector/agent/native.py | 89 +++++---- .../core/src/opendirector/agent/runtime.py | 4 +- tests/test_assistant_steer.py | 142 ++++++++++++++ tests/test_native_runtime.py | 173 +++++++++++++----- 8 files changed, 548 insertions(+), 92 deletions(-) create mode 100644 packages/core/src/opendirector/agent/appserver.py create mode 100644 tests/test_assistant_steer.py diff --git a/apps/api/src/opendirector_api/agent.py b/apps/api/src/opendirector_api/agent.py index 79e2929a9..a529e41f3 100644 --- a/apps/api/src/opendirector_api/agent.py +++ b/apps/api/src/opendirector_api/agent.py @@ -68,6 +68,7 @@ class Turn(BaseModel): thinking: Literal['auto', 'low', 'medium', 'high'] = 'auto' modelSelections: dict[str, str | None] = Field(default_factory=dict) skills: list[str] = Field(default_factory=list, max_length=1) + delivery: Literal['queue', 'insert'] = 'queue' def draft_content_is_empty(content): @@ -195,6 +196,35 @@ def queue(self, project_id: UUID, session: str, message: dict, conversation_id: durable_json(file, value) return queued + def insert(self, project_id: UUID, session: str, message: dict, + conversation_id: UUID | None = None) -> dict: + """Store a message that was handed to the turn already running. + + It is written directly before the streaming reply, so the transcript + reads the way the model met it: after the user's first message and + before the answer was finished. + """ + 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) + folder = child(directory, 'agent-runs') + folder.mkdir(exist_ok=True) + file = child(folder, 'conversation.json') + value = read_json(file) if file.exists() else {'messages': [], **Draft().model_dump()} + value['conversationId'] = value.get('conversationId') or str(uuid5(project_id, 'assistant')) + if conversation_id is not None and str(conversation_id) != value['conversationId']: + raise ProjectError('当前对话已切换,请重新加载后重试;原对话未覆盖。', 409) + if any(item['id'] == message['id'] for item in value['messages']): + raise ProjectError('这条消息已接受,请读取对话,不要重复发送。', 409) + inserted = {**message, 'status': 'inserted'} + index = len(value['messages']) + if index and value['messages'][-1].get('status') == 'streaming': + index -= 1 + value['messages'].insert(index, inserted) + durable_json(file, value) + return inserted + def dispatch(self, project_id: UUID, session: str | None = None, agent_session: str | None = None) -> dict | None: """Start the oldest queued message as this turn's user message. @@ -462,6 +492,7 @@ class Chain: task: asyncio.Task | None = None stopped: bool = False last: dict | None = None + steer: asyncio.Queue[str] | None = None def agent_routes(projects, generation, configs, provider=None, *, active=None) -> APIRouter: @@ -725,7 +756,7 @@ async def renew_session() -> None: session=run_session, directory=plan['directory'], config=plan['config'], messages=context, selected_skills=message.get('skills') or [], thinking=plan['thinking'], model_selections=plan['model_selections'], runtime_model=message.get('runtimeModel'), - skills=plan['available'], conversation_id=chain.conversation_id) + skills=plan['available'], conversation_id=chain.conversation_id, steer=chain.steer) async with aclosing(runtimes.stream(run)) as stream: async for event in stream: if event['type'] == 'delta': @@ -814,6 +845,7 @@ async def run_chain(chain: Chain, plan: dict) -> None: turn_id, saved, error, status = chain.turn, None, None, 'complete' try: while True: + chain.steer = asyncio.Queue() saved, error, status = await produce_one(chain, plan) turn_id = UUID(plan['message']['id']) if status != 'complete' or chain.stopped: @@ -835,6 +867,7 @@ async def run_chain(chain: Chain, plan: dict) -> None: status, error = 'stopped', None raise finally: + chain.steer = None chain.events.put({'type': 'end', 'turnId': str(turn_id), 'nextTurnId': None, 'conversation': saved if saved is not None else chain.last, 'error': error}) if active.get(project_id) is chain: @@ -934,8 +967,32 @@ async def message(project_id: UUID, value: Turn, x_opendirector_session: UUID = """ session = str(x_opendirector_session) async with admission.setdefault(project_id, asyncio.Lock()): + if value.delivery == 'insert' and (value.assets or value.content or value.skills): + # Checked before the run settings are rebuilt: a supplement is + # text for the turn that is already running, nothing else. + raise ProjectError('运行中插入只支持文字,请等回复结束后再附带素材或技能。', 409) plan = await prepare(project_id, value, session, accept_language) chain = active.get(project_id) + if value.delivery == 'insert': + # Text handed to the turn that is already running. It reaches the + # model through the runtime's own channel, never through a second + # turn, so the answer keeps the work it has already done. + if chain is None: + raise ProjectError('当前没有正在执行的回复,直接发送即可。', 409) + if value.conversationId is not None and chain.conversation_id is not None \ + and str(value.conversationId) != str(chain.conversation_id): + raise ProjectError('当前对话已切换,请重新加载后重试;原对话未覆盖。', 409) + spec = runtime_spec(value.runtime) + if not spec.supportsSteering: + raise ProjectError(f'{spec.label} 不支持在回复执行中插入内容,请改用排队。', 409) + if chain.steer is None: + raise ProjectError('这一轮回复刚刚结束,请重新发送。', 409) + chain.steer.put_nowait(value.text) + inserted = await asyncio.to_thread(conversations.insert, project_id, session, + plan['message'], value.conversationId) + chain.events.put({'type': 'steered', 'message': inserted}) + return JSONResponse({'inserted': inserted, 'chainId': str(chain.id), + 'turnId': str(chain.turn)}, status_code=202) if chain is not None: if value.conversationId is not None and chain.conversation_id is not None \ and str(value.conversationId) != str(chain.conversation_id): diff --git a/docs/architecture/agent-runtime.md b/docs/architecture/agent-runtime.md index acf55b1e2..2f7dab706 100644 --- a/docs/architecture/agent-runtime.md +++ b/docs/architecture/agent-runtime.md @@ -10,7 +10,7 @@ Harness 指承担模型调用、工具执行和上下文管理的 Agent 执行 | --- | --- | --- | | Default | 固定版本的 bundled OpenCode | OpenDirector 模型配置,经本地模型代理访问服务 | | OpenCode CLI | opencode,优先 PATH,再查找常见 CLI 安装目录 | CLI 原生配置与模型目录 | -| Codex | 优先 PATH 中的 codex,再查找常见桌面版与 CLI 安装目录 | 原生认证与模型目录;隔离启动前解析所选模型或默认模型 | +| Codex | 优先 PATH 中的 codex,再查找常见桌面版与 CLI 安装目录;以 `app-server` 常驻进程通信,沙箱与审批策略作为协议参数传入 | 原生认证与模型目录;隔离启动前解析所选模型或默认模型 | | Claude Code | claude,优先 PATH,再查找常见 CLI 安装目录 | 原生认证、环境变量与初始化模型目录 | | JiuwenSwarm | jiuwenswarm-process,优先 PATH,再查找常见 CLI 安装目录,通过 stdin/stdout JSONL 直接调用 | 本机 Jiuwen 模型目录、配置与环境变量 | | DeepSeek Harness | dsh,优先 PATH,再查找常见 CLI 安装目录,以 acp profile 运行标准 JSON-RPC | CLI 原生 profile、模型目录与认证 | @@ -55,7 +55,7 @@ Default 将模型配置中的输入模态传入 bundled OpenCode。外部 harnes Search citations keep their native markers in the original reply and trace. Completed Codex MCP web-search results supply validated source IDs, HTTP(S) URLs and titles through `sources` events; the conversation retains this metadata with the reply. The UI splits tool activities using raw text offsets before formatting prose citations as source links, and uses the same formatting for copying. Code examples remain literal. Missing sources and incomplete final markers have a localized fallback. For saved Codex replies without source metadata, queries derive it from the matching turn's project-local trace without rewriting the conversation; a bounded metadata cache is invalidated by trace modification time and size. Reading a trace never requests a model call. -同一工程同时只执行一个回复。运行期间仍可提交补充消息:`POST /assistant/messages` 在空闲时直接开始一轮,在运行中返回 202 并按 `queueSeq` 把消息排入投递队列,本轮结束后依次运行。`end` 事件带 `nextTurnId` 时事件流不关闭,客户端因此能在同一条连接上接着收到下一轮;断线重连用 `GET /turns/{turn_id}/events?after=` 从已收到的最后一帧续读;链已经推进到下一轮时,客户端手里上一轮的 turn id 同样能找到这条链,不必等页面刷新。排队消息立即出现在会话里并可读;停止时整条链一起停止,排队消息标记为 `cancelled` 并保留下来供用户重新发送。运行事件转换为回复正文和工具活动,保存到对应会话;原生事件与业务工具事件追加到 `agent-runs/..jsonl`。Default 使用 `opencode` 作为轨迹文件的 runtime 名称。 +同一工程同时只执行一个回复。运行期间仍可提交补充消息:`POST /assistant/messages` 在空闲时直接开始一轮,在运行中返回 202 并按 `queueSeq` 把消息排入投递队列,本轮结束后依次运行。`end` 事件带 `nextTurnId` 时事件流不关闭,客户端因此能在同一条连接上接着收到下一轮;断线重连用 `GET /turns/{turn_id}/events?after=` 从已收到的最后一帧续读;链已经推进到下一轮时,客户端手里上一轮的 turn id 同样能找到这条链,不必等页面刷新。排队消息立即出现在会话里并可读;停止时整条链一起停止,排队消息标记为 `cancelled` 并保留下来供用户重新发送。运行中还可以把补充文字直接交给这一轮:`POST /assistant/messages` 带 `delivery: "insert"` 时,文字经 runtime 的原生通道进入正在执行的模型循环,而不是另起一轮,因此这一轮已经做的工作不会重来。插入只接受纯文字,素材与技能要等回复结束后再发;runtime 不支持同轮插入时返回 409 并说明原因,用户可改用排队。Codex 通过 `turn/steer` 提供该通道;其它 runtime 在接入原生通道前一律排队。运行事件转换为回复正文和工具活动,保存到对应会话;原生事件与业务工具事件追加到 `agent-runs/..jsonl`。Default 使用 `opencode` 作为轨迹文件的 runtime 名称。 Default 的模型网关在 `agent-runs/.model.jsonl` 记录实际转发的请求体,包括生效的系统消息、会话上下文、工具 Schema 与模型参数。请求 ID 关联上游 HTTP 状态、响应头等待耗时和传输错误。该文件仅供本地调试,创建权限为 `0600`,不记录 HTTP 鉴权头。回复片段、工具结果和 token 用量仍见原生轨迹。 @@ -91,7 +91,7 @@ English summary: a Job created by an Agent `generation.submit` records `agentRun | Harness | 执行约束 | | --- | --- | | OpenCode | 工具权限配置开放 Shell、文件读取、已发现技能和业务 CLI | -| Codex | workspace-write 沙箱,开放 Shell 和业务 CLI | +| Codex | `app-server` 以 workspace-write 沙箱、`never` 审批策略启动线程,开放 Shell 和业务 CLI | | Claude Code | 明确允许 Skill、Bash、Read 和业务 CLI | | JiuwenSwarm | 明确允许 skill_tool、list_skill、read_file、bash 和业务 CLI | | DeepSeek Harness | 沿用原生工具与权限;Skill 限于本轮快照,业务操作通过 Shell 调用 opendirector,未承接的审批不自动批准 | diff --git a/packages/core/src/opendirector/agent/appserver.py b/packages/core/src/opendirector/agent/appserver.py new file mode 100644 index 000000000..9758bfd3b --- /dev/null +++ b/packages/core/src/opendirector/agent/appserver.py @@ -0,0 +1,164 @@ +"""Codex app-server: one turn over the JSON-RPC stdio protocol. + +`codex exec` reads one prompt from stdin and exits, so once a turn is running +nothing can reach the model. The app server is the same engine behind a +long-lived channel: a turn can be steered while it runs, and the conversation +keeps a thread id that a later turn can resume. +""" +import asyncio +import json +from collections.abc import Awaitable, Callable +from pathlib import Path + +from opendirector.domain.projects import ProjectError + +Emit = Callable[[dict], Awaitable[None]] + +CLIENT = {'name': 'OpenDirector', 'version': '1.0'} + + +class Session: + """A JSON-RPC channel over the app server's stdin and stdout.""" + + def __init__(self, process): + self.process = process + self.notes: asyncio.Queue[dict] = asyncio.Queue() + self.pending: dict[int, asyncio.Future] = {} + self.next_id = 0 + self.reader = asyncio.create_task(self._read()) + + async def _read(self): + try: + while line := await self.process.stdout.readline(): + try: + data = json.loads(line) + except json.JSONDecodeError: + continue + if 'id' in data: + future = self.pending.pop(data['id'], None) + if future is not None and not future.done(): + future.set_result(data) + elif 'method' in data: + self.notes.put_nowait(data) + except (asyncio.CancelledError, ValueError): + return + + async def write(self, payload: dict): + self.process.stdin.write(json.dumps(payload).encode() + b'\n') + await self.process.stdin.drain() + + async def notify(self, method: str, params: dict | None = None): + await self.write({'jsonrpc': '2.0', 'method': method, 'params': params or {}}) + + async def call(self, method: str, params: dict, timeout: float = 60) -> dict: + self.next_id += 1 + identifier = self.next_id + future = asyncio.get_running_loop().create_future() + self.pending[identifier] = future + await self.write({'jsonrpc': '2.0', 'id': identifier, 'method': method, 'params': params}) + try: + data = await asyncio.wait_for(future, timeout) + except TimeoutError: + raise ProjectError('codex app-server 没有响应,请检查登录和网络。', 502) from None + finally: + self.pending.pop(identifier, None) + if 'error' in data: + detail = (data['error'] or {}).get('message') or '未知原因' + raise ProjectError(f'codex app-server 拒绝了 {method}:{detail}', 502) + return data.get('result') or {} + + async def close(self): + self.reader.cancel() + await asyncio.gather(self.reader, return_exceptions=True) + + +async def run(process, *, work: Path, model: str | None, resume: str | None, + prompt: str, fallback: str | None, steer: asyncio.Queue[str] | None, + emit: Emit) -> str: + """Run one turn and return the thread id that can be resumed later. + + `prompt` assumes the native thread is resumed and carries only the newest + message; `fallback` is the same request with the whole history, used when a + saved thread cannot be opened. + """ + session = Session(process) + try: + await session.call('initialize', {'clientInfo': CLIENT}) + await session.notify('initialized') + thread, resumed = await _thread(session, work, model, resume) + # The trace keeps the native thread id the way the exec protocol kept + # `thread.started`, so a run stays traceable to its engine session. + await emit({'native': {'type': 'thread.started', 'thread_id': thread}}) + started = await session.call('turn/start', { + 'threadId': thread, 'input': [{'type': 'text', 'text': prompt if resumed or fallback is None else fallback}], + **({'model': model} if model else {})}) + turn = (started.get('turn') or {}).get('id') + if not turn: + raise ProjectError('codex 没有开始这一轮回复。', 502) + await _drive(session, thread, turn, steer, emit) + return thread + finally: + await session.close() + + +async def _thread(session: Session, work: Path, model: str | None, + resume: str | None) -> tuple[str, bool]: + settings = {'cwd': str(work), 'approvalPolicy': 'never', 'sandbox': 'workspace-write', + **({'model': model} if model else {})} + if resume: + try: + result = await session.call('thread/resume', {'threadId': resume, **settings}) + thread = (result.get('thread') or {}).get('id') + if thread: + return thread, True + except ProjectError: + # A stale thread id is not fatal: the turn starts over with the full + # authoritative history instead of quietly losing the conversation. + pass + result = await session.call('thread/start', settings) + thread = (result.get('thread') or {}).get('id') + if not thread: + raise ProjectError('codex 没有建立会话。', 502) + return thread, False + + +async def _drive(session: Session, thread: str, turn: str, + steer: asyncio.Queue[str] | None, emit: Emit): + note = asyncio.create_task(session.notes.get()) + wanted = asyncio.create_task(steer.get()) if steer is not None else None + streamed: set[str] = set() + try: + while True: + waiting = {task for task in (note, wanted) if task is not None} + done, _ = await asyncio.wait(waiting, return_when=asyncio.FIRST_COMPLETED) + if wanted is not None and wanted in done: + text = wanted.result() + await session.call('turn/steer', { + 'threadId': thread, 'expectedTurnId': turn, + 'input': [{'type': 'text', 'text': text}]}) + wanted = asyncio.create_task(steer.get()) + if note in done: + message = note.result() + note = asyncio.create_task(session.notes.get()) + method = message.get('method') + params = message.get('params') or {} + if method == 'item/agentMessage/delta': + if params.get('itemId'): + streamed.add(params['itemId']) + await emit({'type': 'delta', 'text': params.get('delta', '')}) + elif method == 'item/completed': + item = params.get('item') or {} + if item.get('type') == 'agentMessage' and item.get('id') not in streamed: + await emit({'type': 'delta', 'text': item.get('text', '')}) + elif method == 'turn/completed': + finished = params.get('turn') or {} + status = finished.get('status') + if status == 'failed': + detail = (finished.get('error') or {}).get('message') or '未知原因' + raise ProjectError(f'codex 运行失败:{detail}', 502) + return + finally: + for task in (note, wanted): + if task is not None: + task.cancel() + await asyncio.gather(*[task for task in (note, wanted) if task is not None], return_exceptions=True) diff --git a/packages/core/src/opendirector/agent/context.py b/packages/core/src/opendirector/agent/context.py index e8708c474..afaf4689a 100644 --- a/packages/core/src/opendirector/agent/context.py +++ b/packages/core/src/opendirector/agent/context.py @@ -1,4 +1,5 @@ """Shared input contract for SDK, CLI and service-backed runtimes.""" +import asyncio import json from dataclasses import dataclass, field from pathlib import Path @@ -27,6 +28,8 @@ class RunContext: thinking: str = 'auto' runtime_model: str | None = None skills: list[dict[str, str]] = field(default_factory=list) + # Text handed to a runtime that can reach the model inside a running turn. + steer: asyncio.Queue[str] | None = None def native_session_path(self) -> Path | None: if self.conversation_id is None: diff --git a/packages/core/src/opendirector/agent/native.py b/packages/core/src/opendirector/agent/native.py index 683ad4aeb..39d72cc2d 100644 --- a/packages/core/src/opendirector/agent/native.py +++ b/packages/core/src/opendirector/agent/native.py @@ -13,7 +13,7 @@ from uuid import UUID from opendirector.agent.model_gateway import ModelGateway -from opendirector.agent import cli_transport, deepseek, windows_powershell +from opendirector.agent import appserver, cli_transport, deepseek, windows_powershell from opendirector.agent.cli_discovery import cli_executable from opendirector.agent.context import RunContext from opendirector.agent.citations import search_sources @@ -42,8 +42,6 @@ def executable(runtime: str) -> str | None: return cli_executable('dsh' if runtime == 'deepseek' else runtime) -_CODEX_ISOLATION: dict[tuple[str, ...], tuple[str, ...]] = {} - def codex_environment() -> dict[str, str]: env = dict(os.environ) @@ -54,32 +52,35 @@ def codex_environment() -> dict[str, str]: return env -def codex_isolation_flags(binary: str | tuple[str, ...]) -> tuple[str, ...]: - """Optional codex flags this CLI accepts. +def codex_home(work: Path) -> Path: + """A codex home the app server owns for this project. - Isolation flags vary across releases, and an unsupported flag prevents the - CLI from starting. Keep rollouts on disk so later turns can resume them. + `app-server` does not accept the `exec`-only `--ignore-user-config`, so the + same isolation comes from a home of its own: only the credentials are + copied in, and the rollout stays with the project so the next turn can + still resume it. """ - launcher = (binary,) if isinstance(binary, str) else binary - cached = _CODEX_ISOLATION.get(launcher) - if cached is not None: - return cached - wanted = ('--ignore-user-config', '--ignore-rules') - try: - probe = subprocess.run([*launcher, 'exec', '--help'], capture_output=True, - timeout=20, stdin=subprocess.DEVNULL) - # Help text can contain bytes outside the console code page. - help_text = (probe.stdout + probe.stderr).decode('utf-8', 'replace') - except (OSError, subprocess.SubprocessError): - help_text = '' - flags = tuple(flag for flag in wanted if flag in help_text) - _CODEX_ISOLATION[launcher] = flags - return flags + root = work + for candidate in work.parents: + if candidate.name == 'agent-runs': + root = candidate + break + home = root / '.codex' + home.mkdir(parents=True, exist_ok=True) + source = Path(os.environ.get('CODEX_HOME', Path.home() / '.codex')) / 'auth.json' + target = home / 'auth.json' + if source.is_file() and ( + not target.exists() or target.stat().st_mtime < source.stat().st_mtime): + target.write_bytes(source.read_bytes()) + target.chmod(0o600) + return home -def codex_session_available(session_id: str) -> bool: - home = Path(os.environ.get('CODEX_HOME', Path.home() / '.codex')) - return any(path.is_file() for folder in ('sessions', 'archived_sessions') +def codex_session_available(session_id: str, directory: Path) -> bool: + """A rollout of this session, in the project home or the user's own.""" + homes = (directory / 'agent-runs' / '.codex', + Path(os.environ.get('CODEX_HOME', Path.home() / '.codex'))) + return any(path.is_file() for home in homes for folder in ('sessions', 'archived_sessions') for path in (home / folder).glob(f'**/*{session_id}*.jsonl')) @@ -124,10 +125,15 @@ def command(runtime: str, work: Path, socket: str, token: str, model: str | None 'sandbox_workspace_write.network_access=true', 'skills.bundled.enabled=false', f'developer_instructions={json.dumps(SYSTEM)}'] if sys.platform == 'win32': - # --ignore-user-config also removes windows.sandbox. Without a - # Windows backend Codex downgrades workspace-write to read-only. + # `app-server` chooses the sandbox per thread, but the Windows + # backend is still a config value: without it workspace-write + # degrades to read-only. settings.append('windows.sandbox="elevated"') - args = [binary, 'exec', '--json', '--skip-git-repo-check', *codex_isolation_flags(binary), '--sandbox', 'workspace-write'] + # The app server is the same engine behind a channel a running turn can + # still receive text on; `exec` reads one prompt and exits. Its home is + # private, because `--ignore-user-config` belongs to `exec`. + env['CODEX_HOME'] = str(codex_home(work)) + args = [binary, 'app-server'] for setting in settings: args += ['-c', setting] else: @@ -143,7 +149,8 @@ def command(runtime: str, work: Path, socket: str, token: str, model: str | None '--strict-mcp-config', '--mcp-config', json.dumps({'mcpServers': {}}), '--allowedTools', 'Skill(opendirector:*)', 'Bash', 'Read', '--permission-mode', 'dontAsk', '--setting-sources', ''] - if model: + # `app-server` rejects `--model`; the model travels in the turn request. + if model and runtime != 'codex': args += ['--model', model] return args, env @@ -185,7 +192,7 @@ async def stream(self, run: RunContext, gateway: ToolGateway): # Unverifiable session directories cannot be resumed. Preserve the # old session and start with authoritative conversation context. session_id = None - if session_id and runtime == 'codex' and not codex_session_available(session_id): + if session_id and runtime == 'codex' and not codex_session_available(session_id, directory): # Retain the validated workspace while rebuilding a missing native # conversation from the full authoritative history. session_id = None @@ -246,11 +253,8 @@ async def stream(self, run: RunContext, gateway: ToolGateway): args += ['-c', f'model_reasoning_effort={json.dumps(thinking)}'] elif thinking != 'auto' and runtime == 'claude': args += ['--effort', thinking] - if session_id and runtime != 'deepseek': - if runtime == 'codex': - args += ['resume', session_id, '-'] - else: - args += ['--session' if runtime == 'opencode' else '--resume', session_id] + if session_id and runtime not in {'deepseek', 'codex'}: + args += ['--session' if runtime == 'opencode' else '--resume', session_id] execution_context = (f'Execution directory: {work}\nNative session directory: {native_work}\n' 'Set the native shell workdir to this execution directory for file and media operations. ' 'Use inherited PATH to discover installed programs with Get-Command in PowerShell or command -v in POSIX shells. ' @@ -258,7 +262,8 @@ async def stream(self, run: RunContext, gateway: ToolGateway): 'Write all intermediate files and outputs into the execution directory. ' 'Use opendirector --help to discover OpenDirector commands and opendirector --help for usage. Use opendirector for project changes.\n' + SUGGESTED_REPLIES) - prompt = execution_context + '\n' + json.dumps(context[-1:] if session_id else context, ensure_ascii=False) + recent = json.dumps(context[-1:] if session_id else context, ensure_ascii=False) + prompt = execution_context + '\n' + recent skill_instruction = '' if selected: name = selected[0] @@ -270,6 +275,9 @@ async def stream(self, run: RunContext, gateway: ToolGateway): skill_instruction = f'Use the native skill tool to load {name} from {work / ".agents/skills"} before proceeding.' else: prompt = f'Use the native skill tool to load {name} before proceeding.\n' + prompt + # The app server can only resume a saved thread; if that thread + # turns out to be gone the turn must still see the whole history. + full_prompt = prompt.replace(recent, json.dumps(context, ensure_ascii=False)) env['OPENDIRECTOR_PROJECT_ID'] = str(run.project_id) try: process = await asyncio.create_subprocess_exec(*args, cwd=native_work, env=env, @@ -285,7 +293,7 @@ async def drain_stderr(): stderr_tail.extend(chunk) del stderr_tail[:-8192] stderr_task = asyncio.create_task(drain_stderr()) - if runtime != 'deepseek': + if runtime not in {'deepseek', 'codex'}: process.stdin.write(prompt.encode() + b'\n') await process.stdin.drain() process.stdin.close() @@ -311,6 +319,11 @@ async def observe(raw): blocks.append('Current user request\n' + context[-1]['content']) reported_session = await deepseek.run(process, work, blocks, runtime_model, thinking, deepseek_server, observe, session_id) + elif runtime == 'codex': + reported_session = await appserver.run(process, work=native_work, + model=config['modelId'] if config else runtime_model, + resume=session_id, prompt=prompt, fallback=full_prompt, + steer=run.steer, emit=queue.put) else: while line := await process.stdout.readline(): raw = json.loads(line) @@ -325,7 +338,7 @@ async def observe(raw): or session_id and reported_session and reported_session != session_id): raise ProjectError('Harness 返回了不同的会话 ID。', 502) await queue.put({'native': raw}) - if await process.wait(): + if runtime != 'codex' and await process.wait(): await record_exit() raise ProjectError(f'{runtime} 进程退出({process.returncode}),请检查 CLI 登录和配置。', 502) if reported_session: diff --git a/packages/core/src/opendirector/agent/runtime.py b/packages/core/src/opendirector/agent/runtime.py index b23ba26b4..fbf3fefb3 100644 --- a/packages/core/src/opendirector/agent/runtime.py +++ b/packages/core/src/opendirector/agent/runtime.py @@ -24,6 +24,7 @@ class RuntimeSpec: modelOverride: bool engine: RuntimeId supportsSkills: bool = True + supportsSteering: bool = False RUNTIMES = { @@ -31,7 +32,8 @@ class RuntimeSpec: 'opencode': RuntimeSpec(id='opencode', label='OpenCode', group='harness', modelSource='cli', modelOverride=True, engine='opencode'), 'jiuwenswarm': RuntimeSpec(id='jiuwenswarm', label='JiuwenSwarm', group='harness', modelSource='cli', modelOverride=True, engine='jiuwenswarm'), 'deepseek': RuntimeSpec(id='deepseek', label='DeepSeek Harness', group='harness', modelSource='cli', modelOverride=True, engine='deepseek'), - 'codex': RuntimeSpec(id='codex', label='Codex', group='harness', modelSource='cli', modelOverride=True, engine='codex'), + 'codex': RuntimeSpec(id='codex', label='Codex', group='harness', modelSource='cli', modelOverride=True, engine='codex', + supportsSteering=True), 'claude': RuntimeSpec(id='claude', label='Claude Code', group='harness', modelSource='cli', modelOverride=True, engine='claude'), } diff --git a/tests/test_assistant_steer.py b/tests/test_assistant_steer.py new file mode 100644 index 000000000..690878ca0 --- /dev/null +++ b/tests/test_assistant_steer.py @@ -0,0 +1,142 @@ +"""Text handed to a turn that is already running (#379, insert delivery). + +Queueing runs a supplement after the reply. Inserting reaches the model inside +the same turn, so the reply keeps the work it has already done. The runtime +decides whether that is possible; the API only forwards and records it. +""" +import asyncio +import threading +from uuid import uuid4 + +from fastapi.testclient import TestClient +import pytest + +from opendirector.infrastructure.local_projects import LocalProjects +from opendirector_api.main import create_app +from opendirector_api import agent + + +async def empty_skills(*args): + return [] + + +@pytest.fixture +def assistant(tmp_path, monkeypatch): + """A turn that stalls until a supplement arrives, then reports it.""" + ready = threading.Event() + release = threading.Event() + + async def stream(self, run): + ready.set() + yield {'type': 'delta', 'text': '正在做'} + if run.steer is not None: + # A refused supplement never arrives; the turn must still end. + try: + text = await asyncio.wait_for(run.steer.get(), timeout=5) + except TimeoutError: + text = None + if text is not None: + yield {'type': 'delta', 'text': f'|收到补充:{text}'} + await asyncio.to_thread(release.wait, 10) + yield {'type': 'delta', 'text': '|完'} + + monkeypatch.setattr(agent.AgentRuntimes, 'stream', stream) + monkeypatch.setattr(agent, 'runtime_available', lambda _: True) + monkeypatch.setattr(agent, 'skills', empty_skills) + from opendirector.infrastructure.model_configs import ModelConfigs + monkeypatch.setattr(ModelConfigs, 'resolve', lambda *args: {'id': str(uuid4()), 'modelId': 'test-model'}) + with TestClient(create_app(LocalProjects(tmp_path)), headers={ + 'X-OpenDirector-Request': '1', 'X-OpenDirector-Session': str(uuid4())}) as client: + pid = str(uuid4()) + root = f'/api/creation/projects/{pid}' + assert client.post(root + '/commands', json={'type': 'project.create', 'projectId': pid, + 'commandId': str(uuid4()), 'payload': {'name': '插入'}}).status_code == 200 + assert client.post(root + '/open').status_code == 200 + try: + yield client, root + '/assistant', ready, release + finally: + release.set() + + +def start(client, path, runtime='codex', text='先做一个方案'): + """Open a turn in a worker thread and wait until its runtime is running.""" + from concurrent.futures import ThreadPoolExecutor + pool = ThreadPoolExecutor(max_workers=1) + turn_id = str(uuid4()) + pending = pool.submit(client.post, path + '/turns', json={'id': turn_id, 'text': text, 'runtime': runtime}) + return pending, turn_id, pool + + +def conversation(client, path): + return client.get(path).json() + + +def test_an_inserted_message_reaches_the_running_turn(assistant): + client, path, ready, release = assistant + pending, turn_id, pool = start(client, path) + assert ready.wait(5), 'runtime never started' + inserted = client.post(path + '/messages', json={ + 'id': str(uuid4()), 'text': '补一句:用蓝色', 'runtime': 'codex', 'delivery': 'insert'}) + assert inserted.status_code == 202, inserted.text + body = inserted.json() + assert body['inserted']['status'] == 'inserted' + assert body['turnId'] == turn_id + release.set() + response = pending.result() + events = [line[6:] for line in response.text.splitlines() if line.startswith('data: ')] + assert any('"type": "steered"' in line for line in events), events + reply = conversation(client, path)['messages'][-1] + assert '收到补充:补一句:用蓝色' in reply['text'] + statuses = [message['status'] for message in conversation(client, path)['messages']] + assert statuses == ['complete', 'inserted', 'complete'] + pool.shutdown(wait=False) + + +def test_an_inserted_message_stays_out_of_the_next_turn(assistant): + """The supplement is recorded where it happened, not replayed as a new turn.""" + client, path, ready, release = assistant + pending, _, pool = start(client, path) + assert ready.wait(5) + assert client.post(path + '/messages', json={ + 'id': str(uuid4()), 'text': '补一句', 'runtime': 'codex', 'delivery': 'insert'}).status_code == 202 + release.set() + pending.result() + messages = conversation(client, path)['messages'] + assert [message['role'] for message in messages] == ['user', 'user', 'assistant'] + assert messages[1]['text'] == '补一句' + pool.shutdown(wait=False) + + +def test_insert_without_a_running_turn_is_refused(assistant): + client, path, _, _ = assistant + response = client.post(path + '/messages', json={ + 'id': str(uuid4()), 'text': '补一句', 'runtime': 'codex', 'delivery': 'insert'}) + assert response.status_code == 409 + assert '没有正在执行的回复' in response.json()['detail'] + + +def test_insert_names_the_runtime_that_cannot_steer(assistant): + client, path, ready, release = assistant + pending, _, pool = start(client, path) + assert ready.wait(5) + response = client.post(path + '/messages', json={ + 'id': str(uuid4()), 'text': '补一句', 'runtime': 'claude', 'delivery': 'insert'}) + assert response.status_code == 409 + assert '不支持在回复执行中插入内容' in response.json()['detail'] + release.set() + pending.result() + pool.shutdown(wait=False) + + +def test_insert_refuses_attachments(assistant): + client, path, ready, release = assistant + pending, _, pool = start(client, path) + assert ready.wait(5) + response = client.post(path + '/messages', json={ + 'id': str(uuid4()), 'text': '补一句', 'runtime': 'codex', 'delivery': 'insert', + 'assets': [str(uuid4())]}) + assert response.status_code == 409 + assert '只支持文字' in response.json()['detail'] + release.set() + pending.result() + pool.shutdown(wait=False) diff --git a/tests/test_native_runtime.py b/tests/test_native_runtime.py index 9d44c9479..994c5dc33 100644 --- a/tests/test_native_runtime.py +++ b/tests/test_native_runtime.py @@ -34,45 +34,96 @@ FAKE = '''import json, os, subprocess, sys from pathlib import Path + + +def body(prompt): + assert 'Segment plan' not in prompt + if 'Continue plan' in prompt: + assert ('Save a plan' in prompt) == (os.environ.get('TEST_MISSING_ROLLOUT') == '1') + workspace_marker = Path('.continuation-test') + if 'Continue plan' in prompt: + assert workspace_marker.read_text() == str(Path.cwd()) + else: + workspace_marker.write_text(str(Path.cwd())) + work = Path(prompt.split('Execution directory: ', 1)[1].split(chr(10), 1)[0]) + assert list((work / '.agents/skills').glob('*/SKILL.md')) + subprocess.run([sys.executable, '-c', 'from pathlib import Path; Path("environment-check.txt").write_text("native execution works")'], cwd=work, check=True) + cli = [sys.executable, '-m', 'opendirector.cli'] + def invoke(*arguments): + return json.loads(subprocess.check_output([*cli, *arguments], text=True)) + assert 'project' in subprocess.check_output([*cli, '--help'], text=True) + assert 'Asset ID' in subprocess.check_output([*cli, 'asset', 'write-text', '--help'], text=True) or 'name' in subprocess.check_output([*cli, 'asset', 'write-text', '--help'], text=True) + operation = '00000000-0000-0000-0000-000000000003' + result = invoke('--operation-id', operation, 'asset', 'write-text', '--name', 'native.md', '--text', 'Native plan') + assert result['status'] == 'applied', result + assert invoke('--operation-id', operation, 'asset', 'write-text', '--name', 'native.md', '--text', 'Native plan') == result + preview = invoke('query', 'asset.preview', '--object-id', '00000000-0000-0000-0000-000000000001') + assert preview['preview']['mimeType'] == 'image/webp', preview + return 'Native saved.' + + +def emit(payload): + print(json.dumps(payload), flush=True) + + +if 'app-server' in sys.argv: + resumed = False + for line in sys.stdin: + message = json.loads(line) + method = message.get('method') + if method is None: + continue + identity = message.get('id') + if method == 'initialize': + emit({'jsonrpc': '2.0', 'id': identity, 'result': {'userAgent': 'fake'}}) + elif method == 'initialized': + continue + elif method == 'thread/start': + # The sandbox and approval policy are protocol parameters now, so + # they are pinned here instead of in the command line. + params = message['params'] + assert params['sandbox'] == 'workspace-write', params + assert params['approvalPolicy'] == 'never', params + emit({'jsonrpc': '2.0', 'id': identity, 'result': {'thread': {'id': 'test-native'}}}) + elif method == 'thread/resume': + assert os.environ.get('TEST_MISSING_ROLLOUT') != '1' + resumed = True + emit({'jsonrpc': '2.0', 'id': identity, 'result': {'thread': {'id': message['params']['threadId']}}}) + elif method == 'turn/start': + prompt = message['params']['input'][0]['text'] + if 'Continue plan' in prompt: + assert resumed == (os.environ.get('TEST_MISSING_ROLLOUT') != '1') + reply = body(prompt) + emit({'jsonrpc': '2.0', 'id': identity, + 'result': {'turn': {'id': 'test-turn', 'items': [], 'status': 'inProgress'}}}) + emit({'jsonrpc': '2.0', 'method': 'item/completed', 'params': {'threadId': 'test-native', + 'turnId': 'test-turn', 'completedAtMs': 0, + 'item': {'type': 'agentMessage', 'id': 'message-1', 'text': reply}}}) + emit({'jsonrpc': '2.0', 'method': 'turn/completed', 'params': {'threadId': 'test-native', + 'turn': {'id': 'test-turn', 'items': [], 'status': 'completed'}}}) + elif method == 'turn/steer': + emit({'jsonrpc': '2.0', 'id': identity, 'result': {'turnId': 'test-turn'}}) + sys.exit(0) + prompt = sys.stdin.read() assert '3 to 5 distinct suggestions' in prompt, 'missing suggested reply count' assert 'at most 80 characters per suggestion' in prompt, 'missing suggested reply length limit' assert '[opendirector-replies]: #' in prompt.splitlines(), 'missing suggested reply marker' assert 'Segment plan' not in prompt if 'Continue plan' in prompt: - assert ('Save a plan' in prompt) == (os.environ.get('TEST_MISSING_ROLLOUT') == '1') - runtime = os.environ['TEST_RUNTIME'] - resume_args = {'codex': ['resume', 'test-native', '-'], 'claude': ['--resume', 'test-native']} - assert sys.argv[2:] == ([] if os.environ.get('TEST_MISSING_ROLLOUT') == '1' else resume_args.get(runtime, ['--session', 'test-native'])) -workspace_marker = Path('.continuation-test') -if 'Continue plan' in prompt: - assert workspace_marker.read_text() == str(Path.cwd()) -else: - workspace_marker.write_text(str(Path.cwd())) -work = Path(prompt.split('Execution directory: ', 1)[1].split(chr(10), 1)[0]) -assert list((work / '.agents/skills').glob('*/SKILL.md')) -subprocess.run([sys.executable, '-c', 'from pathlib import Path; Path("environment-check.txt").write_text("native execution works")'], cwd=work, check=True) -cli = [sys.executable, '-m', 'opendirector.cli'] -def invoke(*arguments): - response = subprocess.check_output([*cli, *arguments], text=True) - return json.loads(response) -assert 'project' in subprocess.check_output([*cli, '--help'], text=True) -assert 'Asset ID' in subprocess.check_output([*cli, 'asset', 'write-text', '--help'], text=True) or 'name' in subprocess.check_output([*cli, 'asset', 'write-text', '--help'], text=True) -payload = '{"name":"native.md","text":"Native plan"}' -operation = '00000000-0000-0000-0000-000000000003' -result = invoke('--operation-id', operation, 'asset', 'write-text', '--name', 'native.md', '--text', 'Native plan') -assert result['status'] == 'applied', result -assert invoke('--operation-id', operation, 'asset', 'write-text', '--name', 'native.md', '--text', 'Native plan') == result -preview = invoke('query', 'asset.preview', '--object-id', '00000000-0000-0000-0000-000000000001') -assert preview['preview']['mimeType'] == 'image/webp', preview + if os.environ.get('TEST_MISSING_ROLLOUT') == '1': + assert '--resume' not in sys.argv and '--session' not in sys.argv + else: + assert '--resume' in sys.argv or '--session' in sys.argv +reply = body(prompt) runtime = os.environ['TEST_RUNTIME'] if runtime == 'codex': - print(json.dumps({'type':'thread.started','thread_id':'test-native'})) - print(json.dumps({'type':'item.completed','item':{'type':'agent_message','text':'Native saved.'}})) + emit({'type': 'thread.started', 'thread_id': 'test-native'}) + emit({'type': 'item.completed', 'item': {'type': 'agent_message', 'text': reply}}) elif runtime == 'claude': - print(json.dumps({'type':'assistant','session_id':'test-native','message':{'content':[{'type':'text','text':'Native saved.'}]}})) + emit({'type': 'assistant', 'session_id': 'test-native', 'message': {'content': [{'type': 'text', 'text': reply}]}}) else: - print(json.dumps({'type':'text','sessionID':'test-native','part':{'text':'Native saved.'}})) + emit({'type': 'text', 'sessionID': 'test-native', 'part': {'text': reply}}) ''' @@ -122,7 +173,7 @@ def respond(): @pytest.mark.parametrize("missing_rollout", [False, True]) def test_native_events_real_cli_and_shared_write(tmp_path, monkeypatch, runtime, missing_rollout): missing_rollout = missing_rollout and runtime == "codex" - monkeypatch.setattr(native, "codex_session_available", lambda _: not missing_rollout) + monkeypatch.setattr(native, "codex_session_available", lambda _, directory: not missing_rollout) monkeypatch.setenv("TEST_MISSING_ROLLOUT", "1" if missing_rollout else "0") local = LocalProjects(tmp_path) config = ModelConfigs(tmp_path).save('agent','http://localhost:9999/v1','test','',auth_mode='none') @@ -133,7 +184,9 @@ def test_native_events_real_cli_and_shared_write(tmp_path, monkeypatch, runtime, monkeypatch.setattr(CreationAssets, 'preview', lambda self, project_id, asset_id, target: {'preview': {'path': str(preview), 'mimeType': 'image/webp'}}) def command(kind, work, socket, token, model, model_url, catalog, **kwargs): - return [sys.executable, str(script), "--"], {**os.environ, 'TEST_RUNTIME':kind, + # Codex answers over the app-server protocol now; the other runtimes + # still get one prompt on stdin. + return [sys.executable, str(script), 'app-server' if kind == 'codex' else "--"], {**os.environ, 'TEST_RUNTIME':kind, 'PWD':str(kwargs.get('native_directory') or work), **(kwargs.get('bridge_env') or {'OPENDIRECTOR_AGENT_SOCKET':socket})} monkeypatch.setattr(native, 'command', command) monkeypatch.setattr(native, 'executable', lambda _: sys.executable) @@ -237,16 +290,22 @@ def test_claude_skill_alias_refuses_to_replace_a_real_directory(tmp_path, monkey def test_native_commands_keep_auth_and_restrict_tools(tmp_path, monkeypatch): monkeypatch.setattr(native, "executable", lambda _: sys.executable) - monkeypatch.setattr(native, 'codex_isolation_flags', lambda _: ('--ignore-user-config', '--ignore-rules')) for runtime in ('default', 'opencode', 'codex', 'claude'): work = tmp_path / runtime work.mkdir() args, env = native.command(runtime, work, '/tmp/test.sock', 'private-token', 'test-model', 'http://localhost:1', []) assert 'private-token' not in ' '.join(args) if runtime == 'opencode' else True if runtime == 'codex': - assert '--ignore-user-config' in args + # One long-lived app-server: the sandbox, approval policy and model + # travel in the thread/start request, not in the command line. + assert args[1] == 'app-server' + assert 'exec' not in args + assert '--ignore-user-config' not in args + assert env['CODEX_HOME'].endswith('.codex') + # The server takes the model in `turn/start`, not on the command line. + assert not any(item == '--model' for item in args) assert 'features.shell_tool=true' in args - assert args[args.index('--sandbox') + 1] == 'workspace-write' + assert not any(item == '--sandbox' for item in args) assert not any('mcp_servers.' in item for item in args) assert '--dangerously-bypass-approvals-and-sandbox' not in args elif runtime == 'claude': @@ -265,16 +324,24 @@ def test_native_commands_keep_auth_and_restrict_tools(tmp_path, monkeypatch): assert 'title' not in config['agent'] -def test_codex_only_passes_supported_isolation_flags(tmp_path, monkeypatch): +def test_codex_server_gets_a_home_of_its_own(tmp_path, monkeypatch): + """`app-server` has no `--ignore-user-config`; a private home isolates it.""" binary = str(tmp_path / 'codex') monkeypatch.setattr(native, 'executable', lambda _: binary) - monkeypatch.setattr(native, '_CODEX_ISOLATION', {}) - monkeypatch.setattr(native.subprocess, 'run', lambda *args, **kwargs: - SimpleNamespace(stdout=b'Options:\n --ephemeral\n --ignore-user-config\n --ignore-rules\n', stderr=b'')) - args, _ = native.command('codex', tmp_path, '', 'token', None, '', []) - assert '--ephemeral' not in args - assert '--ignore-user-config' in args - assert '--ignore-rules' in args + source = tmp_path / 'user-home' + source.mkdir() + (source / 'auth.json').write_text('{"token": "secret"}') + monkeypatch.setenv('CODEX_HOME', str(source)) + work = tmp_path / 'agent-runs' / 'turn-1' / 'work' + work.mkdir(parents=True) + args, env = native.command('codex', work, '', 'token', None, '', []) + assert args[1] == 'app-server' + assert '--ignore-user-config' not in args + home = tmp_path / 'agent-runs' / '.codex' + assert env['CODEX_HOME'] == str(home) + # The credentials travel with the private home; the user config does not. + assert (home / 'auth.json').read_text() == '{"token": "secret"}' + assert not (home / 'config.toml').exists() def test_codex_inherits_windows_system_proxy_without_overriding_explicit_proxy(monkeypatch): @@ -292,11 +359,13 @@ def test_codex_inherits_windows_system_proxy_without_overriding_explicit_proxy(m def test_codex_isolation_preserves_windows_workspace_sandbox(tmp_path, monkeypatch, platform): monkeypatch.setattr(native, 'sys', SimpleNamespace(platform=platform)) monkeypatch.setattr(native, 'executable', lambda _: 'codex') - monkeypatch.setattr(native, 'codex_isolation_flags', lambda _: ('--ignore-user-config', '--ignore-rules')) - args, _ = native.command('codex', tmp_path, '', '', None, '', []) + args, env = native.command('codex', tmp_path, '', '', None, '', []) + assert args[:2] == ['codex', 'app-server'] assert ('windows.sandbox="elevated"' in args) == (platform == 'win32') - assert args[args.index('--sandbox') + 1] == 'workspace-write' + # The sandbox itself travels in the thread settings the app server receives; + # the exec-only bypass flag must never be among the arguments. assert '--dangerously-bypass-approvals-and-sandbox' not in args + assert env['CODEX_HOME'].endswith('.codex') def test_codex_reconnect_does_not_end_turn(): @@ -829,10 +898,16 @@ async def check(): def test_codex_resume_requires_a_persisted_rollout(tmp_path, monkeypatch): - monkeypatch.setenv('CODEX_HOME', str(tmp_path)) + monkeypatch.setenv('CODEX_HOME', str(tmp_path / 'user-home')) session = '01a1b721-ec28-7f33-85a6-0cf1355f6627' - assert not native.codex_session_available(session) - rollout = tmp_path / 'sessions' / '2026' / f'rollout-{session}.jsonl' + assert not native.codex_session_available(session, tmp_path) + rollout = tmp_path / 'user-home' / 'sessions' / '2026' / f'rollout-{session}.jsonl' rollout.parent.mkdir(parents=True) rollout.write_text('{}\n') - assert native.codex_session_available(session) + assert native.codex_session_available(session, tmp_path) + # The app server writes its rollouts into the project, not the user home. + project = tmp_path / 'agent-runs' / '.codex' / 'sessions' / '2026' + project.mkdir(parents=True) + other = '01a1b721-0000-7f33-85a6-0cf1355f6627' + (project / f'rollout-{other}.jsonl').write_text('{}\n') + assert native.codex_session_available(other, tmp_path) From 8ab8ef0be5edf8fe2f44e16911819dc9cd50dec6 Mon Sep 17 00:00:00 2001 From: wtz2333 Date: Tue, 17 Nov 2026 11:23:17 +0800 Subject: [PATCH 5/6] [feat] canvas: queue a message sent while a reply runs While a reply streams, the composer kept the draft but replaced Send with Stop and Enter returned without a word, so a supplement could only be typed in and lost. It is sent now: the server answers 202 with the queued message, the log shows it as queued, and the same stream keeps feeding the replies that follow until the chain ends. Refs #379 --- src/backend/chat.ts | 51 ++++++++++++- src/canvas/AssistantPanel.tsx | 47 +++++++++--- src/canvas/assistant-experience.css | 16 ++++ src/canvas/useAssistantChat.ts | 108 +++++++++++++++++++++------ src/i18n/messages/en-US/assistant.ts | 6 ++ src/i18n/messages/zh-CN/assistant.ts | 5 ++ tests/assistantQueue.test.ts | 102 +++++++++++++++++++++++++ 7 files changed, 297 insertions(+), 38 deletions(-) create mode 100644 tests/assistantQueue.test.ts diff --git a/src/backend/chat.ts b/src/backend/chat.ts index 292fea1f2..51dd9393a 100644 --- a/src/backend/chat.ts +++ b/src/backend/chat.ts @@ -71,7 +71,15 @@ export interface ChatMessage { role: "user" | "assistant"; text: string; content?: ReferenceContent | null; - status: "complete" | "streaming" | "stopped" | "interrupted"; + status: + | "complete" + | "streaming" + | "queued" + | "cancelled" + | "stopped" + | "interrupted"; + /** Position of a queued message in the delivery order the server assigned. */ + queueSeq?: number; assets?: ChatAsset[]; model?: string | null; modelIsCliDefault?: boolean; @@ -145,7 +153,16 @@ export type ChatEvent = | ({ type: "tool" } & ChatTool) | { type: "delta"; text: string } | { type: "sources"; sources: ChatSource[] } - | { type: "end"; conversation: Conversation | null; error: string | null }; + /** A message accepted while a reply runs; it starts when that reply ends. */ + | { type: "queued"; message: ChatMessage } + | { + type: "end"; + turnId?: string; + /** Set when the server has already started the next queued message. */ + nextTurnId?: string | null; + conversation: Conversation | null; + error: string | null; + }; export interface ChatRequest { conversationId?: string; @@ -299,6 +316,36 @@ async function readChatEvents( } } +export interface QueuedReply { + queued: ChatMessage; + chainId: string; + turnId: string; +} + +/** + * Hand a message to the assistant without waiting for the running reply. + * + * The server answers with a stream when the project is idle and with + * `202 { queued }` when a reply is running, so a client submits here without + * having to know which of the two it is. + */ +export async function sendChat( + id: string, + value: ChatRequest, + signal: AbortSignal, + onEvent: (event: ChatEvent) => void, + t: Translate = defaultTranslate, +): Promise { + const response = await fetch("/api" + path(id) + "/messages", { + ...json("POST", value), + headers: { ...headers, "Content-Type": "application/json" }, + signal, + }); + if (response.status === 202) return (await response.json()) as QueuedReply; + await readChatEvents(response, onEvent, t); + return null; +} + export interface RuntimeModel { isDefault?: boolean; id: string; diff --git a/src/canvas/AssistantPanel.tsx b/src/canvas/AssistantPanel.tsx index 1adf4db51..d6d23ee2e 100644 --- a/src/canvas/AssistantPanel.tsx +++ b/src/canvas/AssistantPanel.tsx @@ -511,6 +511,21 @@ export function AssistantPanel({ )} {message.role === "user" && !!message.assets?.length && } + {message.status === "queued" && ( + + {t("assistant.panel.queued", { + position: + value.messages + .filter((item) => item.status === "queued") + .findIndex((item) => item.id === message.id) + 1, + })} + + )} + {message.status === "cancelled" && ( + + {t("assistant.panel.cancelled")} + + )} {(message.status === "stopped" || message.status === "interrupted") && ( @@ -750,10 +765,10 @@ export function AssistantPanel({ onConfigure={onOpenSettings} />
- {chat.sending ? ( + {chat.sending && ( - ) : ( - )} +
@@ -795,6 +813,11 @@ export function AssistantPanel({ ) : ( `${chat.runtimes.find((item) => item.id === (value.runtime ?? "default"))?.label ?? t("assistant.panel.chooseAgent")}` )} + {chat.sending && !!value.draft.trim() && ( + + {t("assistant.panel.queueWhileRunning")} + + )} {latestTrace && ( diff --git a/src/canvas/assistant-experience.css b/src/canvas/assistant-experience.css index 579727913..c25683e55 100644 --- a/src/canvas/assistant-experience.css +++ b/src/canvas/assistant-experience.css @@ -173,6 +173,22 @@ .cw-assistant-panel .cw-assistant-composer .cw-chat-reference-editor { min-height: 78px; } +.cw-assistant-toolbar .cw-assistant-send { + margin-left: auto; +} +.cw-assistant-toolbar .cw-assistant-send.is-stop { + width: 32px; + height: 32px; + border: 1px solid var(--chat-border); + background: transparent; + color: var(--chat-text); +} +.cw-assistant-toolbar .cw-assistant-send.is-stop + .cw-assistant-send { + margin-left: 6px; +} +.cw-assistant-queue-hint { + display: block; +} .cw-chat-markdown strong { font-weight: 600; } diff --git a/src/canvas/useAssistantChat.ts b/src/canvas/useAssistantChat.ts index 0f9eb127c..d4f109ad7 100644 --- a/src/canvas/useAssistantChat.ts +++ b/src/canvas/useAssistantChat.ts @@ -1,6 +1,6 @@ import { availabilityBlocker } from "../backend/availability.ts"; import { useCallback, useEffect, useLayoutEffect, useRef, useState } from "react"; -import { assistantModelSelection, preferredMediaModel, rememberAgentSelection, rememberMediaSelection, restoreAgentSelection } from "./agentPreferences"; +import { assistantModelSelection, builtinThinking, preferredMediaModel, rememberAgentSelection, rememberMediaSelection, restoreAgentSelection } from "./agentPreferences"; import { errorMessage } from "../backend/api"; import { attachChat, @@ -18,8 +18,10 @@ import { stopChat, type ChatAsset, type Conversation, + type ChatRequest, type ModelSelections, conversationIsEmpty, + sendChat, } from "../backend/chat"; import { flushChatDraft, rememberChat } from "../backend/chatDrafts"; import { creationClient } from "../backend/creationClient.ts"; @@ -458,36 +460,82 @@ export function useAssistantChat( commit, ); + const requestFor = (input: Conversation, id: string): ChatRequest => ({ + id, + conversationId: input.conversationId, + modelId: agent?.id, + runtime: input.runtime ?? "default", + runtimeModel: input.runtimeModel, + text: input.draft, + content: input.draftContent, + assets: input.assets.map((asset) => asset.id), + thinking: builtinThinking(input, agent?.id), + modelSelections: input.modelSelections, + skills: input.skills ?? [], + }); + /** + * Send what the composer holds without waiting for the running reply. + * + * The server queues the message and starts it when that reply ends, so the + * composer stays usable instead of dropping the keystroke on the floor. + */ + const queue = async () => { + const input = current.current; + setError(""); + try { + await flushChatDraft(projectId); + const accepted = await sendChat( + projectId, + requestFor(input, crypto.randomUUID()), + new AbortController().signal, + () => {}, + t, + ); + if (!alive.current) return; + if (!accepted) { + // The reply ended in between, so this message opened a turn of its own. + // Read that run instead of leaving its stream unread. + const { conversation: saved, activeTurnId } = await conversation(projectId); + if (!alive.current) return; + setValue(restoreConversation(projectId, saved, Boolean(activeTurnId))); + if (activeTurnId) void resume.current(activeTurnId); + return; + } + setValue((previous) => + previous.messages.some((message) => message.id === accepted.queued.id) + ? previous + : { + ...previous, + messages: [...previous.messages, accepted.queued], + draft: "", + draftContent: null, + assets: [], + skills: [], + }, + ); + } catch (reason) { + if (alive.current) setError(displayError(errorMessage(reason))); + } + }; const send = async () => { if ( !canWrite.current || !loaded || switching.current || - submitting.current || uploading.current || !canSend || !current.current.draft.trim() ) return; + // A reply is already arriving: queue behind it instead of failing silently. + if (submitting.current) { + await queue(); + return; + } const input = current.current; await follow(crypto.randomUUID(), async (id, signal, onEvent) => { await flushChatDraft(projectId); - await streamChat( - projectId, - { - id, - conversationId: input.conversationId, - ...assistantModelSelection(input, agent?.id), - text: input.draft, - content: input.draftContent, - assets: input.assets.map((asset) => asset.id), - modelSelections: input.modelSelections, - skills: input.skills ?? [], - }, - signal, - onEvent, - t, - ); + await sendChat(projectId, requestFor(input, id), signal, onEvent, t); }); }; /** Re-attach to a turn that kept running while this project was not shown. */ @@ -521,7 +569,9 @@ export function useAssistantChat( const abort = new AbortController(); controller.current = abort; turnId.current = id; - const assistantId = crypto.randomUUID(); + // One stream covers every reply in the chain, so the reply being written + // is replaced each time a `start` frame opens a new one. + let reply = crypto.randomUUID(); try { await run( id, @@ -529,6 +579,8 @@ export function useAssistantChat( (event) => { if (!alive.current) return; if (event.type === "start") { + // A new reply begins; the previous one is saved in this conversation. + reply = crypto.randomUUID(); setStarted(true); setValue({ ...event.conversation, @@ -536,7 +588,7 @@ export function useAssistantChat( message.status === "streaming" ? { ...message, - id: assistantId, + id: reply, } : message, ), @@ -546,7 +598,7 @@ export function useAssistantChat( setValue((previous) => ({ ...previous, messages: previous.messages.map((message) => - message.id === assistantId + message.id === reply ? { ...message, text: message.text + event.text } : message, ), @@ -554,7 +606,7 @@ export function useAssistantChat( } else if (event.type === "sources") { setValue((previous) => ({ ...previous, - messages: previous.messages.map((message) => message.id === assistantId + messages: previous.messages.map((message) => message.id === reply ? { ...message, sources: Array.from(new Map([ ...event.sources.map((source) => [source.id, source] as const), ...(message.sources ?? []).map((source) => [source.id, source] as const), @@ -565,7 +617,7 @@ export function useAssistantChat( else if (event.type === "plan") { setValue((previous) => ({ ...previous, - messages: previous.messages.map((message) => message.id === assistantId + messages: previous.messages.map((message) => message.id === reply ? { ...message, plan: event.entries } : message), })); } else if (event.type === "tool") { @@ -574,7 +626,7 @@ export function useAssistantChat( setValue((previous) => ({ ...previous, messages: previous.messages.map((message) => { - if (message.id !== assistantId) return message; + if (message.id !== reply) return message; const tools = [...(message.tools ?? [])]; const index = tools.findIndex((item) => item.id === tool.id); if (index < 0) tools.push(tool); @@ -583,7 +635,15 @@ export function useAssistantChat( }), })); if (event.status !== "running") onEnd.current(); + } else if (event.type === "queued") { + setValue((previous) => + previous.messages.some((message) => message.id === event.message.id) + ? previous + : { ...previous, messages: [...previous.messages, event.message] }, + ); } else if (event.type === "end") { + // The chain moves on to the next queued message; stop must follow it. + if (event.nextTurnId) turnId.current = event.nextTurnId; if (event.conversation) setValue(event.conversation); if (event.error) setError(displayError(event.error)); } diff --git a/src/i18n/messages/en-US/assistant.ts b/src/i18n/messages/en-US/assistant.ts index fe9eb643b..9e80da435 100644 --- a/src/i18n/messages/en-US/assistant.ts +++ b/src/i18n/messages/en-US/assistant.ts @@ -60,6 +60,12 @@ export const assistant = { "assistant.panel.stopped": "Reply stopped", "assistant.panel.interrupted": "Reply interrupted", "assistant.panel.send": "Send message", + "assistant.panel.queue": "Queue message", + "assistant.panel.queueHint": "Send it when the current reply finishes", + "assistant.panel.queued": "Queued · position {position}", + "assistant.panel.queueWhileRunning": + "Press Enter to queue this behind the running reply", + "assistant.panel.cancelled": "Queued message cancelled", "assistant.panel.stop": "Stop reply", "assistant.panel.upload": "Upload reference", "assistant.panel.uploadHint": "Upload images, video, audio or text", diff --git a/src/i18n/messages/zh-CN/assistant.ts b/src/i18n/messages/zh-CN/assistant.ts index 632900430..6d1a0f716 100644 --- a/src/i18n/messages/zh-CN/assistant.ts +++ b/src/i18n/messages/zh-CN/assistant.ts @@ -59,6 +59,11 @@ export const assistant = { "assistant.panel.stopped": "已停止回复", "assistant.panel.interrupted": "回复已中断", "assistant.panel.send": "发送消息", + "assistant.panel.queue": "排队发送", + "assistant.panel.queueHint": "当前回复结束后发送", + "assistant.panel.queued": "排队中 · 第 {position} 位", + "assistant.panel.queueWhileRunning": "按 Enter 排队,当前回复结束后自动发送", + "assistant.panel.cancelled": "排队消息已取消", "assistant.panel.stop": "停止回复", "assistant.panel.upload": "上传参考", "assistant.panel.uploadHint": "上传图片、视频、音频或文本", diff --git a/tests/assistantQueue.test.ts b/tests/assistantQueue.test.ts new file mode 100644 index 000000000..097312ed5 --- /dev/null +++ b/tests/assistantQueue.test.ts @@ -0,0 +1,102 @@ +import assert from "node:assert/strict"; +import test from "node:test"; +import { + sendChat, + type ChatEvent, + type ChatRequest, +} from "../src/backend/chat.ts"; + +const request: ChatRequest = { + id: "message-1", + text: "再补一点", + assets: [], + thinking: "auto", + modelSelections: {}, +}; + +const sse = (events: unknown[]) => + new Response( + events.map((event) => `data: ${JSON.stringify(event)}\n\n`).join(""), + { headers: { "Content-Type": "text/event-stream" } }, + ); + +test("a message sent while a reply runs is queued instead of started", async (t) => { + const queued = { + id: "message-1", + role: "user", + text: "再补一点", + status: "queued", + queueSeq: 2, + }; + const fetch = t.mock.method( + globalThis, + "fetch", + async (url: string, init?: RequestInit) => { + assert.ok(url.endsWith("/assistant/messages")); + assert.equal(init?.method, "POST"); + return new Response( + JSON.stringify({ queued, chainId: "chain-1", turnId: "turn-1" }), + { status: 202, headers: { "Content-Type": "application/json" } }, + ); + }, + ); + const events: ChatEvent[] = []; + const accepted = await sendChat( + "project", + request, + new AbortController().signal, + (event) => events.push(event), + ); + assert.equal(accepted?.queued.status, "queued"); + assert.equal(accepted?.chainId, "chain-1"); + assert.deepEqual(events, []); + assert.equal(fetch.mock.calls.length, 1); +}); + +test("an idle project answers on the same endpoint with the running reply", async (t) => { + const saved = { + messages: [], + draft: "", + assets: [], + thinking: "auto", + modelSelections: {}, + }; + t.mock.method(globalThis, "fetch", async () => + sse([ + { type: "start", conversation: saved }, + { type: "delta", text: "先做这个" }, + // The chain moves on to a queued message on the same stream. + { + type: "end", + turnId: "turn-1", + nextTurnId: "turn-2", + conversation: saved, + error: null, + }, + { type: "start", conversation: saved }, + { type: "delta", text: "|完" }, + { + type: "end", + turnId: "turn-2", + nextTurnId: null, + conversation: saved, + error: null, + }, + ]), + ); + const events: ChatEvent[] = []; + const accepted = await sendChat( + "project", + request, + new AbortController().signal, + (event) => events.push(event), + ); + assert.equal(accepted, null); + assert.deepEqual( + events.map((event) => event.type), + ["start", "delta", "end", "start", "delta", "end"], + ); + const ends = events.filter((event) => event.type === "end"); + assert.equal(ends[0]!.type === "end" && ends[0]!.nextTurnId, "turn-2"); + assert.equal(ends[1]!.type === "end" && ends[1]!.nextTurnId, null); +}); From c7b3df61b5860e7dd94eea966765397f76bf8854 Mon Sep 17 00:00:00 2001 From: wtz2333 Date: Tue, 17 Nov 2026 11:37:09 +0800 Subject: [PATCH 6/6] [feat] canvas: withdraw a queued message and continue a stalled queue A message waiting behind the running reply showed its position but offered no way to take it back, and a queue left behind by a failure or a restart had no way to start again without retyping it. A queued bubble now carries Withdraw, which removes it from the thread under the same lock the chain takes when it picks the next message up. A queue with nothing draining it shows a banner with the count and Continue, which starts the oldest message and reads its reply from the usual stream. A cancelled message offers Edit again, which puts it back in the composer so it is sent deliberately rather than silently. Refs #379 --- src/backend/chat.ts | 36 +++++++++++++++++++ src/canvas/AssistantPanel.tsx | 35 +++++++++++++++++++ src/canvas/assistant-experience.css | 33 ++++++++++++++++++ src/canvas/useAssistantChat.ts | 49 ++++++++++++++++++++++++++ src/i18n/messages/en-US/assistant.ts | 6 ++++ src/i18n/messages/zh-CN/assistant.ts | 6 ++++ tests/assistantQueue.test.ts | 52 ++++++++++++++++++++++++++++ 7 files changed, 217 insertions(+) diff --git a/src/backend/chat.ts b/src/backend/chat.ts index 51dd9393a..2157fcc39 100644 --- a/src/backend/chat.ts +++ b/src/backend/chat.ts @@ -155,6 +155,8 @@ export type ChatEvent = | { type: "sources"; sources: ChatSource[] } /** A message accepted while a reply runs; it starts when that reply ends. */ | { type: "queued"; message: ChatMessage } + /** A queued message was withdrawn before it started. */ + | { type: "retracted"; messageId: string } | { type: "end"; turnId?: string; @@ -346,6 +348,40 @@ export async function sendChat( return null; } +/** + * Take back a message that is still waiting behind the running reply. + * + * A message that has already started is part of the record: the server + * refuses it with 409 and the caller still has to stop the reply instead. + */ +export async function retractChatMessage( + id: string, + message: string, +): Promise<{ retracted: string; conversation: Conversation }> { + return request<{ retracted: string; conversation: Conversation }>( + path(id) + `/messages/${message}`, + { method: "DELETE", headers }, + ); +} + +/** + * Continue a queue that nothing is draining, for example after a restart + * or after a reply failed with messages still waiting behind it. + */ +export async function continueQueue( + id: string, + signal: AbortSignal, + onEvent: (event: ChatEvent) => void, + t: Translate = defaultTranslate, +) { + const response = await fetch("/api" + path(id) + "/queue/dispatch", { + ...json("POST", {}), + headers: { ...headers, "Content-Type": "application/json" }, + signal, + }); + await readChatEvents(response, onEvent, t); +} + export interface RuntimeModel { isDefault?: boolean; id: string; diff --git a/src/canvas/AssistantPanel.tsx b/src/canvas/AssistantPanel.tsx index d6d23ee2e..887164319 100644 --- a/src/canvas/AssistantPanel.tsx +++ b/src/canvas/AssistantPanel.tsx @@ -519,11 +519,27 @@ export function AssistantPanel({ .filter((item) => item.status === "queued") .findIndex((item) => item.id === message.id) + 1, })} + )} {message.status === "cancelled" && ( {t("assistant.panel.cancelled")} + )} {(message.status === "stopped" || @@ -564,6 +580,25 @@ export function AssistantPanel({
)} + {!chat.sending && + value.messages.some((message) => message.status === "queued") && ( +
+ + {t("assistant.panel.waiting", { + count: value.messages.filter( + (message) => message.status === "queued", + ).length, + })} + + +
+ )}
({ + ...previous, + messages: previous.messages.filter( + (message) => message.id !== event.messageId, + ), + })); } else if (event.type === "end") { // The chain moves on to the next queued message; stop must follow it. if (event.nextTurnId) turnId.current = event.nextTurnId; @@ -707,6 +717,42 @@ export function useAssistantChat( } } }; + /** Withdraw a message that has not started yet. */ + const retract = async (messageId: string) => { + const before = current.current; + setValue((previous) => ({ + ...previous, + messages: previous.messages.filter((message) => message.id !== messageId), + })); + try { + const result = await retractChatMessage(projectId, messageId); + if (!alive.current) return; + setValue((previous) => ({ ...previous, messages: result.conversation.messages })); + } catch (reason) { + if (!alive.current) return; + setValue(before); + setError(displayError(errorMessage(reason))); + } + }; + /** Put a cancelled message back in the composer so it can be sent again. */ + const refill = (message: ChatMessage) => { + setValue((previous) => ({ + ...previous, + draft: message.text, + draftContent: message.content ?? null, + assets: message.assets ?? [], + })); + }; + /** Start the oldest waiting message when nothing is running. */ + const proceed = async () => { + if (!loaded || switching.current || submitting.current) return; + const next = current.current.messages.find( + (message) => message.status === "queued", + ); + await follow(next?.id ?? crypto.randomUUID(), async (_id, signal, onEvent) => { + await continueQueue(projectId, signal, onEvent, t); + }); + }; const stop = async () => { if (!canWrite.current || !turnId.current || stopping) return; setStopping(true); @@ -766,6 +812,9 @@ export function useAssistantChat( addNodes, addAssets, send, + retract, + refill, + proceed, stop, reload: () => setLoadAttempt((n) => n + 1), }; diff --git a/src/i18n/messages/en-US/assistant.ts b/src/i18n/messages/en-US/assistant.ts index 9e80da435..7397536be 100644 --- a/src/i18n/messages/en-US/assistant.ts +++ b/src/i18n/messages/en-US/assistant.ts @@ -66,6 +66,12 @@ export const assistant = { "assistant.panel.queueWhileRunning": "Press Enter to queue this behind the running reply", "assistant.panel.cancelled": "Queued message cancelled", + "assistant.panel.retract": "Withdraw", + "assistant.panel.retractHint": "Withdraw this queued message before it starts", + "assistant.panel.refill": "Edit again", + "assistant.panel.refillHint": "Put this message back in the composer to send it again", + "assistant.panel.waiting": "{count} message(s) waiting to run", + "assistant.panel.proceed": "Continue", "assistant.panel.stop": "Stop reply", "assistant.panel.upload": "Upload reference", "assistant.panel.uploadHint": "Upload images, video, audio or text", diff --git a/src/i18n/messages/zh-CN/assistant.ts b/src/i18n/messages/zh-CN/assistant.ts index 6d1a0f716..4c2db151d 100644 --- a/src/i18n/messages/zh-CN/assistant.ts +++ b/src/i18n/messages/zh-CN/assistant.ts @@ -64,6 +64,12 @@ export const assistant = { "assistant.panel.queued": "排队中 · 第 {position} 位", "assistant.panel.queueWhileRunning": "按 Enter 排队,当前回复结束后自动发送", "assistant.panel.cancelled": "排队消息已取消", + "assistant.panel.retract": "撤回", + "assistant.panel.retractHint": "撤回这条还没开始执行的排队消息", + "assistant.panel.refill": "重新编辑", + "assistant.panel.refillHint": "把这条消息放回输入框,确认后再发送", + "assistant.panel.waiting": "{count} 条消息在排队等待执行", + "assistant.panel.proceed": "继续执行", "assistant.panel.stop": "停止回复", "assistant.panel.upload": "上传参考", "assistant.panel.uploadHint": "上传图片、视频、音频或文本", diff --git a/tests/assistantQueue.test.ts b/tests/assistantQueue.test.ts index 097312ed5..8c498539f 100644 --- a/tests/assistantQueue.test.ts +++ b/tests/assistantQueue.test.ts @@ -1,6 +1,8 @@ import assert from "node:assert/strict"; import test from "node:test"; import { + continueQueue, + retractChatMessage, sendChat, type ChatEvent, type ChatRequest, @@ -100,3 +102,53 @@ test("an idle project answers on the same endpoint with the running reply", asyn assert.equal(ends[0]!.type === "end" && ends[0]!.nextTurnId, "turn-2"); assert.equal(ends[1]!.type === "end" && ends[1]!.nextTurnId, null); }); + +test("a queued message is withdrawn through the message itself", async (t) => { + const fetch = t.mock.method( + globalThis, + "fetch", + async (url: string, init?: RequestInit) => { + assert.ok(url.endsWith("/assistant/messages/message-2")); + assert.equal(init?.method, "DELETE"); + return new Response( + JSON.stringify({ + retracted: "message-2", + conversation: { messages: [], draft: "", assets: [], thinking: "auto", modelSelections: {} }, + }), + { status: 200, headers: { "Content-Type": "application/json" } }, + ); + }, + ); + const result = await retractChatMessage("project", "message-2"); + assert.equal(result.retracted, "message-2"); + assert.equal(fetch.mock.calls.length, 1); +}); + +test("a stalled queue is continued and its reply read from the same stream", async (t) => { + const saved = { + messages: [], + draft: "", + assets: [], + thinking: "auto", + modelSelections: {}, + }; + const fetch = t.mock.method( + globalThis, + "fetch", + async (url: string) => { + assert.ok(url.endsWith("/assistant/queue/dispatch")); + return sse([ + { type: "start", conversation: saved }, + { type: "delta", text: "继续" }, + { type: "end", turnId: "turn-2", nextTurnId: null, conversation: saved, error: null }, + ]); + }, + ); + const events: ChatEvent[] = []; + await continueQueue("project", new AbortController().signal, (event) => events.push(event)); + assert.deepEqual( + events.map((event) => event.type), + ["start", "delta", "end"], + ); + assert.equal(fetch.mock.calls.length, 1); +});