From 4f37cfa659c53801bab4fc00a2fe75bb21d2345c Mon Sep 17 00:00:00 2001 From: wtz2333 Date: Tue, 17 Nov 2026 11:11:41 +0800 Subject: [PATCH 01/11] [feat] agent: run a message sent while a turn is running MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit ## summary - Replace the single-per-project `active` slot with a `Chain` that covers the running turn together with the messages queued behind it, so the moment between one turn ending and the next starting stays closed. - Accept a supplementary message while a turn runs: `POST /assistant/messages` starts a turn when the project is idle and answers 202 with the queued message when one is running. The message is stored in the conversation at once, shows up as `queued`, and starts when the active turn ends. - Give every event a `seq`, let `GET /turns/{id}/events?after=` resume from a cursor, and keep one stream across turns: an `end` frame that carries `nextTurnId` means the next reply continues on the same connection. - Stopping ends the whole chain and marks messages that never started as `cancelled`, so a stopped run cannot leave work that begins later by surprise. ## validation - `python -m pytest tests/test_assistant_queue.py tests/test_assistant_conversations.py -q` → 35 passed. - Full `tests/` run against the same environment: the failures that remain (missing libx264 / ffmpeg options on this host) are identical with and without this change. - `lint-imports` and `python scripts/generate_contracts.py --check` pass. Refs: #379 --- apps/api/src/opendirector_api/agent.py | 564 ++++++++++++++++++------- docs/architecture/agent-runtime.md | 2 +- tests/test_assistant_conversations.py | 4 +- tests/test_assistant_queue.py | 218 ++++++++++ 4 files changed, 629 insertions(+), 159 deletions(-) create mode 100644 tests/test_assistant_queue.py diff --git a/apps/api/src/opendirector_api/agent.py b/apps/api/src/opendirector_api/agent.py index 7ef36a60b..4af17544f 100644 --- a/apps/api/src/opendirector_api/agent.py +++ b/apps/api/src/opendirector_api/agent.py @@ -1,15 +1,16 @@ """Project-scoped assistant persistence and native runtime streaming.""" import asyncio from contextlib import aclosing, suppress +from dataclasses import dataclass import json import logging from pathlib import Path 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 -from fastapi.responses import FileResponse, StreamingResponse +from fastapi.responses import FileResponse, JSONResponse, StreamingResponse from pydantic import BaseModel, ConfigDict, Field, JsonValue from opendirector.agent.catalog import model_choices @@ -148,6 +149,82 @@ def update(self, project_id: UUID, session: str | None = None, *, draft: Draft | result = public_conversation(value) return with_trace_sources(result, directory) + def queue(self, project_id: UUID, session: str, message: dict, conversation_id: UUID | None = None) -> dict: + """Store a supplementary message that runs after the active turn. + + The record keeps the shape of an accepted turn, so the run that picks it + up later needs nothing but what the user sent and the settings frozen + with 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) + 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) + value['queueSeq'] = value.get('queueSeq', 0) + 1 + queued = {**message, 'status': 'queued', 'queueSeq': value['queueSeq']} + value['messages'].append(queued) + durable_json(file, value) + return queued + + def dispatch(self, project_id: UUID, session: str | None = None) -> dict | None: + """Start the oldest queued message as this turn's user message. + + Dispatching takes the same lock as starting a run, so the project slot + never opens between one turn ending and the next beginning; a second run + cannot slip in ahead of the message that is already waiting. + """ + 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) + 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')) + pending = next((item for item in value['messages'] if item.get('status') == 'queued'), None) + if pending is None: + return None + index = value['messages'].index(pending) + pending['status'] = 'complete' + value['messages'].insert(index + 1, { + 'id': str(uuid5(UUID(pending['id']), 'assistant')), + 'role': 'assistant', 'text': '', 'status': 'streaming', + **{key: pending[key] for key in ('model', 'runtime') if key in pending}}) + value.update(draft='', draftContent=None, assets=[], skills=[]) + durable_json(file, value) + result = public_conversation(value) + return {'message': pending, 'conversation': with_trace_sources(result, directory)} + + def cancel_queued(self, project_id: UUID, session: str | None = None) -> list[dict]: + """Mark messages that will not run as cancelled, keeping them readable.""" + 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) + file = child(child(directory, 'agent-runs'), 'conversation.json') + if not file.exists(): + return [] + value = read_json(file) + cancelled = [item for item in value['messages'] if item.get('status') == 'queued'] + if not cancelled: + return [] + for item in cancelled: + item['status'] = 'cancelled' + durable_json(file, value) + return cancelled + def list(self, project_id: UUID) -> dict: directory = self.path(project_id) file = child(child(directory, 'agent-runs'), 'conversation.json') @@ -204,34 +281,66 @@ class ConversationCreate(BaseModel): class RunEvents: - """Events of one accepted turn, kept until the turn ends. + """Events of one conversation chain, replayable from any cursor. The run belongs to the project, not to the HTTP request that started it: leaving the project closes the stream, and returning attaches a new one that - replays from the beginning. Only an explicit stop cancels the run. + replays from the beginning, or from the last frame a viewer already has. A + chain keeps its events across turns, so one stream can carry the turn that is + running and the supplementary messages queued behind it. """ def __init__(self): self.items: list[dict] = [] self.changed = asyncio.Event() + self.closed = False def put(self, event: dict) -> None: - self.items.append(event) + self.items.append({**event, 'seq': len(self.items)}) + if event['type'] == 'end' and not event.get('nextTurnId'): + self.closed = True self.changed.set() self.changed = asyncio.Event() - async def follow(self): - index = 0 + async def follow(self, after: int = 0): + index = max(0, after) while True: while index < len(self.items): event = self.items[index] index += 1 yield 'data: ' + json.dumps(event, ensure_ascii=False) + '\n\n' - if event['type'] == 'end': + if event['type'] == 'end' and not event.get('nextTurnId'): return + if self.closed: + # The chain finished while this viewer was still catching up: its + # cursor is past the last frame, so serve what is left and stop + # rather than waiting for events that will never come. + return await self.changed.wait() +@dataclass +class Chain: + """One running turn and the messages queued behind it. + + The chain owns the project slot rather than the turn: the moment between one + turn ending and the next starting must stay closed, otherwise a second run + could be admitted alongside the follow-up that is about to start. A chain + lives until its queue is empty, so a supplementary message never races the + turn it was sent during. + """ + + id: UUID + project_id: UUID + events: RunEvents + session: str + turn: UUID + conversation_id: UUID | None = None + task: asyncio.Task | None = None + stopped: bool = False + last: dict | None = None + + def agent_routes(projects, generation, configs, provider=None) -> APIRouter: router = APIRouter(prefix='/api/creation/projects/{project_id}/assistant') conversations = Conversations(projects) @@ -257,17 +366,17 @@ def trace(project_id: UUID, turn_id: UUID, raise ProjectError('轨迹文件不存在。', 404) return FileResponse(file, media_type='text/plain', headers={'Cache-Control': 'no-store'}) - active: dict[UUID, tuple[UUID, asyncio.Task, RunEvents]] = {} + active: dict[UUID, Chain] = {} admission: dict[UUID, asyncio.Lock] = {} @router.get('') async def conversation(project_id: UUID): value = await asyncio.to_thread(conversations.update, project_id) running = active.get(project_id) - # A streaming message without an active turn was interrupted (for - # example by a restart); with one, the client can attach to it. - if running and not running[1].done(): - value = {**value, 'activeTurnId': str(running[0])} + # A streaming message without a chain was interrupted (for example by a + # restart); with one, the client can attach to the turn it is running. + if running is not None: + value = {**value, 'activeTurnId': str(running.turn)} return value @router.get('/conversations') @@ -320,163 +429,306 @@ async def catalog(project_id: UUID): found = await skills(projects.local.repository, directory) return [{key: item[key] for key in ('name', 'description', 'source')} for item in found] + def preferences_for(model_selections: dict) -> dict: + names = {row['id']: row['modelId'] for row in configs.list()} + return {kind: {'modelConfigId': model_id, 'modelName': names.get(model_id)} + for kind, model_id in model_selections.items() if model_id} + + async def prepare(project_id: UUID, value: Turn, session: str, accept_language: str | None) -> dict: + """Validate a submitted turn and resolve everything it needs to run. + + Validation happens while the user is still at the keyboard: a message + that could never run must fail now, not after the active turn, when the + user has already moved on. + """ + directory = await asyncio.to_thread(conversations.path, project_id, session) + if not runtime_available(value.runtime): + raise ProjectError(f'{value.runtime} 未安装,请安装 CLI 并登录。', 503) + spec = runtime_spec(value.runtime) + if not spec.supportsSkills and value.skills: + raise ProjectError(f'{spec.label} 不支持技能,请移除技能后发送。', 409) + if value.runtime == 'jiuwenswarm' and value.thinking != 'auto': + raise ProjectError('JiuwenSwarm 当前使用原生默认推理强度。', 409) + config = await asyncio.to_thread(configs.resolve, str(value.modelId), 'agent') if spec.modelSource == 'settings' else None + available = await skills(projects.local.repository, directory) if spec.supportsSkills else [] + if set(value.skills) - {item['name'] for item in available}: + raise ProjectError('技能已失效,请重新选择。', 409) + snapshot = await asyncio.to_thread(projects.snapshot, project_id) + assets = {str(asset.id): asset for asset in snapshot.assets} + for asset_id in value.assets: + if str(asset_id) not in assets: + raise ProjectError('引用素材不属于当前工程。', 409) + model = config['modelId'] if config else (value.runtimeModel or 'CLI 默认模型') + model_selections = dict(value.modelSelections) + return {'session': session, 'directory': directory, 'config': config, 'available': available, + 'model': model, 'model_selections': model_selections, + 'preferences': preferences_for(model_selections), 'thinking': value.thinking, + 'accept_language': accept_language, + 'message': {'id': str(value.id), 'role': 'user', 'text': value.text, 'content': value.content, + 'assets': [{'id': str(asset.id), 'name': asset.name, 'type': asset.metadata.mimeType, + 'size': asset.metadata.size, 'fingerprint': asset.fingerprint} + for asset in (assets[str(key)] for key in value.assets)], + 'skills': value.skills, 'runtime': value.runtime, 'runtimeModel': value.runtimeModel, + 'modelSelections': dict(value.modelSelections), 'model': model, + 'thinking': value.thinking, 'status': 'complete', + **({'modelConfigId': str(value.modelId)} if value.modelId else {})}} + + async def plan_for(project_id: UUID, message: dict, session: str, accept_language: str | None) -> dict: + """Settings for a message that was accepted earlier and is due now. + + The message was validated when the user sent it, so this rebuilds the + run settings without rejecting input that is already typed: a model that + has disappeared in the meantime falls back to the runtime default. + """ + directory = await asyncio.to_thread(conversations.path, project_id, session) + spec = runtime_spec(message['runtime']) + config = None + if spec.modelSource == 'settings' and message.get('modelConfigId'): + try: + config = await asyncio.to_thread(configs.resolve, message['modelConfigId'], 'agent') + except Exception: + logger.warning('agent.queue.model_missing project_id=%s message_id=%s', + project_id, message.get('id')) + available = await skills(projects.local.repository, directory) if spec.supportsSkills else [] + model_selections = dict(message.get('modelSelections') or {}) + return {'session': session, 'directory': directory, 'config': config, 'available': available, + 'model': message.get('model') or 'CLI 默认模型', 'model_selections': model_selections, + 'preferences': preferences_for(model_selections), 'accept_language': accept_language, + 'thinking': message.get('thinking') or 'auto', 'message': message} + + async def produce_one(chain: Chain, plan: dict) -> tuple[dict | None, str | None, str]: + """Run one turn and persist its reply; the caller decides what runs next.""" + project_id = chain.project_id + message = plan['message'] + turn_id = UUID(message['id']) + text, status, error = '', 'complete', None + activities: list[dict] = [] + sources: dict = {} + previous_sources: dict = {} + steps = None + try: + saved = plan['start'] + chain.conversation_id = UUID(saved['conversationId']) + chain.events.put({'type': 'start', 'conversation': saved}) + previous_sources = {source['id']: source for reply in saved['messages'][:-2] + for source in reply.get('sources', [])} + snapshot = await asyncio.to_thread(projects.snapshot, project_id) + assets = {str(asset.id): asset for asset in snapshot.assets} + context = [] + for reply in saved['messages'][:-1]: + content = reply['text'] or '(empty reply)' + references = [] + for attachment in reply.get('assets', []): + asset = assets.get(attachment['id']) + if asset is not None: + references.append({'id': str(asset.id), 'name': attachment['name'], + 'kind': asset.kind, 'path': str((plan['directory'] / asset.path).resolve()), + 'metadata': asset.metadata.model_dump(mode='json', exclude_none=True)}) + if references: + content += '\nReferenced project assets: ' + json.dumps(references, ensure_ascii=False) + content += '\nThese are asset references, not visual observations. Inspect media with available tools before describing its contents.' + context.append({'role': reply['role'], 'content': content}) + if plan['preferences']: + context[-1]['content'] += '\nUser model preferences for this turn: ' + json.dumps(plan['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=message['runtime'], project_id=project_id, turn_id=turn_id, + session=chain.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) + async with aclosing(runtimes.stream(run)) as stream: + async for event in stream: + if event['type'] == 'delta': + text += event['text'] + inherited = ([source for source in referenced_sources(text, previous_sources) + if source['id'] not in sources] + if previous_sources and '\ue201' in event['text'] else []) + if inherited: + sources.update({source['id']: source for source in inherited}) + chain.events.put({'type': 'sources', 'sources': inherited}) + if event['type'] == 'sources': + for source in event['sources']: + sources.setdefault(source['id'], source) + if event['type'] == 'plan': + steps = event['entries'] + if event['type'] == 'tool': + previous = next((item for item in activities if item['id'] == event['id']), None) + activity = {**{key: item for key, item in event.items() if key != 'type'}, + 'textOffset': previous['textOffset'] if previous else len(text)} + if previous is None: + activities.append(activity) + else: + activities[activities.index(previous)] = activity + event = {'type': 'tool', **activity} + chain.events.put(event) + except asyncio.CancelledError: + status = 'stopped' + raise + except Exception as failure: + # Persist partial output even when an integration fails unexpectedly. + status = 'interrupted' + if isinstance(failure, ProjectError): + error = localized_error_for_language( + plan.get('accept_language'), chinese=str(failure), + status=failure.status, code=failure.code) + else: + error = localized_error_for_language( + plan.get('accept_language'), + chinese='Agent 执行失败,请检查后端日志。', + status=500, code='operation_rejected') + logger.exception(f'agent.turn.failed project_id={project_id} turn_id={turn_id}') + finally: + for activity in activities: + if activity['status'] == 'running': + activity['status'] = 'interrupted' + try: + saved = await asyncio.to_thread(conversations.update, project_id, finish={ + 'id': str(uuid5(turn_id, 'assistant')), 'role': 'assistant', 'text': text, 'status': status, + 'model': plan['model'], + 'runtime': message['runtime'], 'thinking': plan['thinking'], 'tools': activities, + 'sources': list(sources.values()), + **({'plan': steps} if steps is not None else {})}, conversation_id=chain.conversation_id) + except Exception: + logger.exception(f'agent.turn.unfinished project_id={project_id} turn_id={turn_id}') + saved = None + chain.last = saved + return saved, error, status + + async def run_chain(chain: Chain, plan: dict) -> None: + """Run a turn, then take the next queued message until the queue is empty. + + Dispatching the next message and releasing the project slot happen under + the admission lock, so a message can never be appended after the queue + was found empty but before the slot is released: it either runs in this + chain or it starts a new one. + """ + project_id = chain.project_id + turn_id, saved, error, status = chain.turn, None, None, 'complete' + try: + while True: + saved, error, status = await produce_one(chain, plan) + turn_id = UUID(plan['message']['id']) + if status != 'complete' or chain.stopped: + break + async with admission.setdefault(project_id, asyncio.Lock()): + dispatched = None if chain.stopped else await asyncio.to_thread( + conversations.dispatch, project_id, chain.session) + if dispatched is None: + break + chain.turn = UUID(dispatched['message']['id']) + chain.events.put({'type': 'end', 'turnId': str(turn_id), 'nextTurnId': str(chain.turn), + 'conversation': dispatched['conversation'], 'error': None}) + plan = await plan_for(project_id, dispatched['message'], chain.session, None) + plan['start'] = dispatched['conversation'] + saved = None + except asyncio.CancelledError: + status, error = 'stopped', None + raise + finally: + 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: + active.pop(project_id, None) + + def launch(project_id: UUID, plan: dict, conversation_id: UUID | None) -> StreamingResponse: + chain = Chain(id=uuid4(), project_id=project_id, events=RunEvents(), session=plan['session'], + turn=UUID(plan['message']['id']), conversation_id=conversation_id) + active[project_id] = chain + chain.task = asyncio.create_task(run_chain(chain, plan)) + def release(completed: asyncio.Task) -> None: + # The chain normally releases the slot itself; this covers a task + # cancelled before it ever started. + if active.get(project_id) is chain and completed is chain.task: + active.pop(project_id, None) + chain.task.add_done_callback(release) + # Closing this stream (switching projects, reloading) only detaches the + # viewer; the run continues and can be attached again. + return StreamingResponse(chain.events.follow(), media_type='text/event-stream') + + def rejected(turn_id: UUID, failure: ProjectError, accept_language: str | None) -> StreamingResponse: + """Report a message that cannot be opened as one already closed stream. + + A rejected message never entered the conversation, so the viewer has + nothing to catch up on: the stream carries the end frame a client + already knows how to show. + """ + events = RunEvents() + events.put({'type': 'end', 'turnId': str(turn_id), 'nextTurnId': None, 'conversation': None, + 'error': localized_error_for_language(accept_language, chinese=str(failure), + status=failure.status, code=failure.code)}) + return StreamingResponse(events.follow(), media_type='text/event-stream') + @router.post('/turns/{turn_id}/stop') async def stop(project_id: UUID, turn_id: UUID, x_opendirector_session: UUID = Header()): - await asyncio.to_thread(conversations.path, project_id, str(x_opendirector_session)) - running = active.get(project_id) - if running and running[0] == turn_id: + session = str(x_opendirector_session) + await asyncio.to_thread(conversations.path, project_id, session) + chain = active.get(project_id) + if chain is not None and turn_id in (chain.turn, chain.id, chain.conversation_id): + chain.stopped = True with CancelScope(shield=True): - if not running[1].cancelling(): - running[1].cancel() - with suppress(asyncio.CancelledError): - await running[1] + if chain.task is not None and not chain.task.cancelling(): + chain.task.cancel() + if chain.task is not None: + with suppress(asyncio.CancelledError): + await chain.task + async with admission.setdefault(project_id, asyncio.Lock()): + await asyncio.to_thread(conversations.cancel_queued, project_id, session) return {'ok': True} @router.get('/turns/{turn_id}/events') - async def turn_events(project_id: UUID, turn_id: UUID): + async def turn_events(project_id: UUID, turn_id: UUID, after: int = 0): await asyncio.to_thread(conversations.path, project_id) - running = active.get(project_id) - if not running or running[0] != turn_id: + chain = active.get(project_id) + if chain is None or turn_id not in (chain.turn, chain.id): raise ProjectError('这轮回复已结束,请重新读取对话。', 404) - return StreamingResponse(running[2].follow(), media_type='text/event-stream') + return StreamingResponse(chain.events.follow(after), media_type='text/event-stream') @router.post('/turns') async def turn(project_id: UUID, value: Turn, x_opendirector_session: UUID = Header(), accept_language: str | None = Header(default=None, alias='Accept-Language')): + session = str(x_opendirector_session) async with admission.setdefault(project_id, asyncio.Lock()): if project_id in active: raise ProjectError('当前工程已有回复正在执行。', 409) - session = str(x_opendirector_session) - directory = await asyncio.to_thread(conversations.path, project_id, session) - if not runtime_available(value.runtime): - raise ProjectError(f'{value.runtime} 未安装,请安装 CLI 并登录。', 503) - spec = runtime_spec(value.runtime) - if not spec.supportsSkills and value.skills: - raise ProjectError(f'{spec.label} 不支持技能,请移除技能后发送。', 409) - if value.runtime == 'jiuwenswarm' and value.thinking != 'auto': - raise ProjectError('JiuwenSwarm 当前使用原生默认推理强度。', 409) - config = await asyncio.to_thread(configs.resolve, str(value.modelId), 'agent') if spec.modelSource == 'settings' else None - available = await skills(projects.local.repository, directory) if spec.supportsSkills else [] - if set(value.skills) - {item['name'] for item in available}: - raise ProjectError('技能已失效,请重新选择。', 409) - snapshot = await asyncio.to_thread(projects.snapshot, project_id) - assets = {str(asset.id): asset for asset in snapshot.assets} - for asset_id in value.assets: - if str(asset_id) not in assets: - raise ProjectError('引用素材不属于当前工程。', 409) - model = config['modelId'] if config else (value.runtimeModel or 'CLI 默认模型') - model_selections = dict(value.modelSelections) - model_names = {row['id']: row['modelId'] for row in configs.list()} - preferences = {kind: {'modelConfigId': model_id, 'modelName': model_names.get(model_id)} - for kind, model_id in model_selections.items() if model_id} - events = RunEvents() - async def produce() -> None: - text, status, error, accepted = '', 'complete', None, False - activities = [] - sources = {} - previous_sources = {} - plan = 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, - 'size': asset.metadata.size, 'fingerprint': asset.fingerprint} - for asset in (assets[str(key)] for key in value.assets)], - 'skills': value.skills, 'runtime': value.runtime, 'runtimeModel': value.runtimeModel, - 'modelSelections': dict(value.modelSelections), - 'model': model, 'status': 'complete'} - saved = await asyncio.to_thread(conversations.update, project_id, session, begin=user, conversation_id=value.conversationId) - accepted = True - events.put({'type': 'start', 'conversation': saved}) - previous_sources = {source['id']: source for message in saved['messages'][:-2] - for source in message.get('sources', [])} - context = [] - for message in saved['messages'][:-1]: - content = message['text'] or '(empty reply)' - references = [] - for attachment in message.get('assets', []): - asset = assets.get(attachment['id']) - if asset is not None: - references.append({'id': str(asset.id), 'name': attachment['name'], - 'kind': asset.kind, 'path': str((directory / asset.path).resolve()), - 'metadata': asset.metadata.model_dump(mode='json', exclude_none=True)}) - if references: - content += '\nReferenced project assets: ' + json.dumps(references, ensure_ascii=False) - content += '\nThese are asset references, not visual observations. Inspect media with available tools before describing its contents.' - context.append({'role': message['role'], 'content': content}) - if preferences: - 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, - 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: - async for event in stream: - if event['type'] == 'delta': - text += event['text'] - inherited = ([source for source in referenced_sources(text, previous_sources) - if source['id'] not in sources] - if previous_sources and '\ue201' in event['text'] else []) - if inherited: - sources.update({source['id']: source for source in inherited}) - events.put({'type': 'sources', 'sources': inherited}) - if event['type'] == 'sources': - for source in event['sources']: - sources.setdefault(source['id'], source) - if event['type'] == 'plan': - plan = event['entries'] - if event['type'] == 'tool': - previous = next((item for item in activities if item['id'] == event['id']), None) - activity = {**{key: item for key, item in event.items() if key != 'type'}, - 'textOffset': previous['textOffset'] if previous else len(text)} - if previous is None: - activities.append(activity) - else: - activities[activities.index(previous)] = activity - event = {'type': 'tool', **activity} - events.put(event) - except asyncio.CancelledError: - status = 'stopped' - raise - except Exception as failure: - # Persist partial output even when an integration fails unexpectedly. - status = 'interrupted' - if isinstance(failure, ProjectError): - error = localized_error_for_language( - accept_language, chinese=str(failure), - status=failure.status, code=failure.code) - else: - error = localized_error_for_language( - accept_language, - chinese='Agent 执行失败,请检查后端日志。', - status=500, code='operation_rejected') - logger.exception(f'agent.turn.failed project_id={project_id} turn_id={value.id}') - finally: - if accepted: - 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, - '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 - events.put({'type': 'end', 'conversation': saved, 'error': error}) - - if project_id in active: - raise ProjectError('当前工程已有回复正在执行。', 409) - task = asyncio.create_task(produce()) - active[project_id] = (value.id, task, events) - def release(completed: asyncio.Task) -> None: - running = active.get(project_id) - if running and running[0] == value.id and running[1] is completed: - active.pop(project_id) - task.add_done_callback(release) - # Closing this stream (switching projects, reloading) only detaches - # the viewer; the run continues and can be attached again. - return StreamingResponse(events.follow(), media_type='text/event-stream') + plan = await prepare(project_id, value, session, accept_language) + try: + plan['start'] = await asyncio.to_thread(conversations.update, project_id, session, + begin=plan['message'], conversation_id=value.conversationId) + except ProjectError as failure: + # The message points at a thread that is no longer the active one. + # Clients of this endpoint read that from the stream, so report it + # where they already look instead of as a bare status code. + return rejected(UUID(plan['message']['id']), failure, accept_language) + return launch(project_id, plan, UUID(plan['start']['conversationId'])) + + @router.post('/messages') + async def message(project_id: UUID, value: Turn, x_opendirector_session: UUID = Header(), + accept_language: str | None = Header(default=None, alias='Accept-Language')): + """Accept a message while a turn runs and run it when that turn is done. + + A message that arrives while the project is idle starts a turn right + away, so a client can use one endpoint for both cases and never has to + guess whether the active turn has finished. + """ + session = str(x_opendirector_session) + async with admission.setdefault(project_id, asyncio.Lock()): + plan = await prepare(project_id, value, session, accept_language) + chain = active.get(project_id) + 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): + raise ProjectError('当前对话已切换,请重新加载后重试;原对话未覆盖。', 409) + queued = await asyncio.to_thread(conversations.queue, project_id, session, + plan['message'], value.conversationId) + chain.events.put({'type': 'queued', 'message': queued}) + return JSONResponse({'queued': queued, 'chainId': str(chain.id), + 'turnId': str(chain.turn)}, status_code=202) + await asyncio.to_thread(conversations.queue, project_id, session, plan['message'], value.conversationId) + dispatched = await asyncio.to_thread(conversations.dispatch, project_id, session) + if dispatched is None: + raise ProjectError('这条消息未能开始执行,请重新发送。', 409) + started = await plan_for(project_id, dispatched['message'], session, accept_language) + started['start'] = dispatched['conversation'] + return launch(project_id, started, UUID(dispatched['conversation']['conversationId'])) return router diff --git a/docs/architecture/agent-runtime.md b/docs/architecture/agent-runtime.md index 3f86072af..7f2e78b3b 100644 --- a/docs/architecture/agent-runtime.md +++ b/docs/architecture/agent-runtime.md @@ -51,7 +51,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. -同一工程同时只接受一个回复运行。运行事件转换为回复正文和工具活动,保存到对应会话;原生事件与业务工具事件追加到 `agent-runs/..jsonl`。Default 使用 `opencode` 作为轨迹文件的 runtime 名称。 +同一工程同时只执行一个回复。运行期间仍可提交补充消息:`POST /assistant/messages` 在空闲时直接开始一轮,在运行中返回 202 并按 `queueSeq` 把消息排入投递队列,本轮结束后依次运行。`end` 事件带 `nextTurnId` 时事件流不关闭,客户端因此能在同一条连接上接着收到下一轮;断线重连用 `GET /turns/{turn_id}/events?after=` 从已收到的最后一帧续读。排队消息立即出现在会话里并可读;停止时整条链一起停止,排队消息标记为 `cancelled` 并保留下来供用户重新发送。运行事件转换为回复正文和工具活动,保存到对应会话;原生事件与业务工具事件追加到 `agent-runs/..jsonl`。Default 使用 `opencode` 作为轨迹文件的 runtime 名称。 Default 的模型网关在 `agent-runs/.model.jsonl` 记录实际转发的请求体,包括生效的系统消息、会话上下文、工具 Schema 与模型参数。请求 ID 关联上游 HTTP 状态、响应头等待耗时和传输错误。该文件仅供本地调试,创建权限为 `0600`,不记录 HTTP 鉴权头。回复片段、工具结果和 token 用量仍见原生轨迹。 diff --git a/tests/test_assistant_conversations.py b/tests/test_assistant_conversations.py index 8480e1619..56f7d5dc7 100644 --- a/tests/test_assistant_conversations.py +++ b/tests/test_assistant_conversations.py @@ -461,11 +461,11 @@ async def stream(self, run): yield {'type': 'delta', 'text': ',返回后完成'} monkeypatch.setattr(agent.AgentRuntimes, 'stream', stream) follow, calls = agent.RunEvents.follow, [] - async def counted(self): + async def counted(self, after=0): calls.append(self) if len(calls) > 1: attached.set() - async for item in follow(self): + async for item in follow(self, after): yield item monkeypatch.setattr(agent.RunEvents, 'follow', counted) turn_id = str(uuid4()) diff --git a/tests/test_assistant_queue.py b/tests/test_assistant_queue.py new file mode 100644 index 000000000..80df837b1 --- /dev/null +++ b/tests/test_assistant_queue.py @@ -0,0 +1,218 @@ +"""A message sent while a turn runs is queued and runs when that turn ends. + +#379: the project accepts one reply at a time, so a supplementary message used +to be refused outright. These cases pin the delivery guarantee: the message is +stored at once, it runs in order after the active turn, and stopping or +rejecting cannot leave a message that runs later by surprise. +""" +import asyncio +from concurrent.futures import ThreadPoolExecutor +import json +import threading +import time +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 + + +def frames(response): + return [json.loads(line[6:]) for line in response.text.splitlines() if line.startswith('data: ')] + + +def wait_until(condition, timeout=5.0): + deadline = time.monotonic() + timeout + while time.monotonic() < deadline: + if condition(): + return True + time.sleep(0.01) + return False + + +def replay(events, after=0): + """Collect one chain's replay exactly as a viewer receives it.""" + async def collect(): + return [json.loads(chunk.removeprefix('data: ')) + for chunk in [item async for item in events.follow(after)]] + return asyncio.run(collect()) + + +async def empty_skills(*args): + return [] + + +@pytest.fixture +def assistant(tmp_path, monkeypatch): + """A project whose first turn blocks until the test lets it finish.""" + contexts = [] + gate = {'started': threading.Event(), 'release': 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) + 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_supplementary_message_waits_for_the_running_turn_and_then_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) + sent = client.post(path + '/messages', json={ + 'id': second, 'runtime': 'default', 'conversationId': cid, 'text': '再补一句'}) + assert sent.status_code == 202, sent.text + assert sent.json()['queued']['status'] == 'queued' + assert sent.json()['queued']['id'] == second and sent.json()['turnId'] == first + # The viewer sees the supplementary message at once, without waiting. + waiting = client.get(path).json() + assert [item['status'] for item in waiting['messages']] == ['complete', 'streaming', 'queued'] + assert waiting['activeTurnId'] == first + gate['release'].set() + events = frames(running.result(timeout=10)) + + ending = [event for event in events if event['type'] == 'end'] + # The message is queued, not merged: it becomes its own turn on the same stream. + assert [event['turnId'] for event in ending] == [first, second] + assert ending[0]['nextTurnId'] == second + assert ending[-1]['nextTurnId'] is None and ending[-1]['error'] is None + messages = ending[-1]['conversation']['messages'] + assert [(item['role'], item['status']) for item in messages] == [ + ('user', 'complete'), ('assistant', 'complete'), ('user', 'complete'), ('assistant', 'complete')] + assert [item['text'] for item in messages if item['role'] == 'assistant'] == [ + '收到:先做这个|完', '收到:再补一句|完'] + assert [context[-1]['content'] for context in contexts] == ['先做这个', '再补一句'] + assert 'activeTurnId' not in client.get(path).json() + + +def test_one_stream_carries_every_turn_and_replays_from_a_cursor(): + events = agent.RunEvents() + events.put({'type': 'start'}) + events.put({'type': 'end', 'turnId': 't1', 'nextTurnId': 't2'}) + events.put({'type': 'start'}) + events.put({'type': 'end', 'turnId': 't2', 'nextTurnId': None}) + + # An end that names the next turn does not close the stream: the queued + # message runs on the connection the viewer already has open. + assert [frame['seq'] for frame in replay(events)] == [0, 1, 2, 3] + assert [frame['seq'] for frame in replay(events, 2)] == [2, 3] + # A cursor past the end of a finished chain ends at once instead of waiting. + assert replay(events, 9) == [] + + +def test_events_endpoint_resumes_from_the_cursor_the_viewer_sent(assistant, monkeypatch): + client, path, _, gate = assistant + seen = [] + original = agent.RunEvents.follow + + async def recorded(self, after=0): + seen.append(after) + async for item in original(self, after): + yield item + + monkeypatch.setattr(agent.RunEvents, 'follow', recorded) + cid = client.get(path).json()['conversationId'] + turn = str(uuid4()) + with ThreadPoolExecutor() as pool: + running = pool.submit(client.post, path + '/turns', json={ + 'id': turn, 'runtime': 'default', 'conversationId': cid, 'text': '长任务'}) + assert gate['started'].wait(5) + tail = pool.submit(client.get, path + f'/turns/{turn}/events?after=1') + assert wait_until(lambda: len(seen) >= 2), seen + gate['release'].set() + resumed = frames(tail.result(timeout=10)) + whole = frames(running.result(timeout=10)) + + assert seen == [0, 1] + # The viewer receives exactly the frames that follow the one it already has. + assert resumed == whole[1:] + + +def test_stop_cancels_the_chain_and_leaves_queued_messages_cancelled(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 + assert client.post(path + f'/turns/{first}/stop').status_code == 200 + events = frames(running.result(timeout=10)) + + assert events[-1]['type'] == 'end' and events[-1]['nextTurnId'] is None + # Stopping ends the whole chain: the queued message never runs, and it stays + # readable so the user can send it again deliberately. + assert [item['status'] for item in client.get(path).json()['messages']] == [ + 'complete', 'stopped', 'cancelled'] + assert len(contexts) == 1 + + +def test_supplementary_message_that_cannot_run_is_rejected_before_it_is_queued(assistant, monkeypatch): + 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) + before = len(client.get(path).json()['messages']) + monkeypatch.setattr(agent, 'runtime_available', lambda _: False) + missing = client.post(path + '/messages', json={ + 'id': str(uuid4()), 'runtime': 'codex', 'conversationId': cid, 'text': '发不出去'}) + assert missing.status_code == 503 and '未安装' in missing.json()['detail'] + monkeypatch.setattr(agent, 'runtime_available', lambda _: True) + stale = client.post(path + '/messages', json={ + 'id': str(uuid4()), 'runtime': 'default', 'conversationId': str(uuid4()), 'text': '发错会话'}) + assert stale.status_code == 409 + # A rejected message is visible to the sender now, not after the active turn: + # the queue never holds work that was known to be unsendable. + assert len(client.get(path).json()['messages']) == before + gate['release'].set() + frames(running.result(timeout=10)) + assert len(contexts) == 1 + + +def test_idle_message_endpoint_starts_a_turn_and_keeps_message_ids_unique(assistant): + client, path, _, gate = assistant + cid = client.get(path).json()['conversationId'] + turn = str(uuid4()) + with ThreadPoolExecutor() as pool: + started = pool.submit(client.post, path + '/messages', json={ + 'id': turn, 'runtime': 'default', 'conversationId': cid, 'text': '直接说'}) + assert gate['started'].wait(5) + gate['release'].set() + response = started.result(timeout=10) + + # With nothing running the same endpoint starts the turn, so a client never + # has to guess whether the active turn has already finished. + assert response.status_code == 200 + events = frames(response) + assert events[0]['type'] == 'start' + assert events[-1]['conversation']['messages'][-1]['text'] == '收到:直接说|完' + duplicate = client.post(path + '/messages', json={ + 'id': turn, 'runtime': 'default', 'conversationId': cid, 'text': '重复发送'}) + assert duplicate.status_code == 409 From c55c802705c364941e2eb2b1095a3abf185f6f70 Mon Sep 17 00:00:00 2001 From: wtz2333 Date: Tue, 17 Nov 2026 11:44:41 +0800 Subject: [PATCH 02/11] [feat] agent: resume a chain through the turn a viewer remembers A viewer that lost the connection between two turns holds the turn it saw last, which is already finished while its chain keeps writing. Asking for that turn's stream answered 404, so the only way back was a reload. The turn is looked up in the conversation it belongs to and compared with the running chain's conversation, so a stale turn of the same thread finds the stream while a turn from anywhere else is still refused. --- apps/api/src/opendirector_api/agent.py | 25 ++++++++- docs/architecture/agent-runtime.md | 2 +- tests/test_assistant_queue.py | 72 +++++++++++++++++++++++++- 3 files changed, 96 insertions(+), 3 deletions(-) diff --git a/apps/api/src/opendirector_api/agent.py b/apps/api/src/opendirector_api/agent.py index 4af17544f..cd6a3902d 100644 --- a/apps/api/src/opendirector_api/agent.py +++ b/apps/api/src/opendirector_api/agent.py @@ -225,6 +225,23 @@ def cancel_queued(self, project_id: UUID, session: str | None = None) -> list[di durable_json(file, value) return cancelled + def conversation_of(self, project_id: UUID, message_id: UUID) -> UUID | None: + """Find the conversation a message belongs to. + + A viewer that lost the connection keeps the turn it saw last. Once the + chain has moved on, that turn is over, but the conversation it belongs to + is still the one being written into, and that is how the stream can be + found again. + """ + directory = self.path(project_id) + file = child(child(directory, 'agent-runs'), 'conversation.json') + with self.projects.local.transaction(): + current = read_json(file) if file.exists() else {'messages': []} + for item in [current, *(current.get('archivedConversations') or [])]: + if any(message.get('id') == str(message_id) for message in item.get('messages') or []): + return UUID(item['conversationId']) + return None + def list(self, project_id: UUID) -> dict: directory = self.path(project_id) file = child(child(directory, 'agent-runs'), 'conversation.json') @@ -679,7 +696,13 @@ async def stop(project_id: UUID, turn_id: UUID, x_opendirector_session: UUID = H async def turn_events(project_id: UUID, turn_id: UUID, after: int = 0): await asyncio.to_thread(conversations.path, project_id) chain = active.get(project_id) - if chain is None or turn_id not in (chain.turn, chain.id): + if chain is not None and turn_id not in (chain.turn, chain.id): + # A viewer that lost the stream between two turns remembers the turn + # it saw last, which is already over while its chain keeps running. + settled = await asyncio.to_thread(conversations.conversation_of, project_id, turn_id) + if settled is None or settled != chain.conversation_id: + chain = None + if chain is None: raise ProjectError('这轮回复已结束,请重新读取对话。', 404) return StreamingResponse(chain.events.follow(after), media_type='text/event-stream') diff --git a/docs/architecture/agent-runtime.md b/docs/architecture/agent-runtime.md index 7f2e78b3b..c2751a701 100644 --- a/docs/architecture/agent-runtime.md +++ b/docs/architecture/agent-runtime.md @@ -51,7 +51,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=` 从已收到的最后一帧续读。排队消息立即出现在会话里并可读;停止时整条链一起停止,排队消息标记为 `cancelled` 并保留下来供用户重新发送。运行事件转换为回复正文和工具活动,保存到对应会话;原生事件与业务工具事件追加到 `agent-runs/..jsonl`。Default 使用 `opencode` 作为轨迹文件的 runtime 名称。 +同一工程同时只执行一个回复。运行期间仍可提交补充消息:`POST /assistant/messages` 在空闲时直接开始一轮,在运行中返回 202 并按 `queueSeq` 把消息排入投递队列,本轮结束后依次运行。`end` 事件带 `nextTurnId` 时事件流不关闭,客户端因此能在同一条连接上接着收到下一轮;断线重连用 `GET /turns/{turn_id}/events?after=` 从已收到的最后一帧续读;链已经推进到下一轮时,客户端手里上一轮的 turn id 同样能找到这条链,不必等页面刷新。排队消息立即出现在会话里并可读;停止时整条链一起停止,排队消息标记为 `cancelled` 并保留下来供用户重新发送。运行事件转换为回复正文和工具活动,保存到对应会话;原生事件与业务工具事件追加到 `agent-runs/..jsonl`。Default 使用 `opencode` 作为轨迹文件的 runtime 名称。 Default 的模型网关在 `agent-runs/.model.jsonl` 记录实际转发的请求体,包括生效的系统消息、会话上下文、工具 Schema 与模型参数。请求 ID 关联上游 HTTP 状态、响应头等待耗时和传输错误。该文件仅供本地调试,创建权限为 `0600`,不记录 HTTP 鉴权头。回复片段、工具结果和 token 用量仍见原生轨迹。 diff --git a/tests/test_assistant_queue.py b/tests/test_assistant_queue.py index 80df837b1..091606897 100644 --- a/tests/test_assistant_queue.py +++ b/tests/test_assistant_queue.py @@ -70,9 +70,47 @@ async def stream(self, run): 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 + try: + yield client, root + '/assistant', contexts, gate + finally: + # A cancelled run is still waiting on this gate in a worker thread; + # releasing it lets the client shut down without waiting out the wait. + gate['release'].set() + +@pytest.fixture +def gated(tmp_path, monkeypatch): + """A project whose every turn waits for a release of its own.""" + contexts = [] + gates = {} + + async def stream(self, run): + text = run.messages[-1]['content'] + contexts.append(text) + gates.setdefault(text, threading.Event()) + yield {'type': 'delta', 'text': '收到:' + text} + await asyncio.to_thread(gates[text].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', contexts, gates + finally: + for waiting in gates.values(): + waiting.set() + def test_supplementary_message_waits_for_the_running_turn_and_then_runs(assistant): client, path, contexts, gate = assistant cid = client.get(path).json()['conversationId'] @@ -216,3 +254,35 @@ def test_idle_message_endpoint_starts_a_turn_and_keeps_message_ids_unique(assist duplicate = client.post(path + '/messages', json={ 'id': turn, 'runtime': 'default', 'conversationId': cid, 'text': '重复发送'}) assert duplicate.status_code == 409 + + +def test_a_viewer_that_lost_the_stream_resumes_through_the_turn_it_remembers(gated): + """Reconnecting between two turns still finds the chain. + + The viewer knows the turn it was watching, not the one that started while it + was away. Refusing that turn would leave it with a frozen conversation until + it thought to reload. + """ + client, path, contexts, gates = gated + 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 wait_until(lambda: '先做这个' in gates) + assert client.post(path + '/messages', json={ + 'id': second, 'runtime': 'default', 'conversationId': cid, 'text': '再补一句'}).status_code == 202 + gates['先做这个'].set() + assert wait_until(lambda: '再补一句' in gates), contexts + # A turn from somewhere else is still refused: only this chain's own + # finished turn is enough to find this chain. + assert client.get(path + f'/turns/{uuid4()}/events').status_code == 404 + with client.stream('GET', path + f'/turns/{first}/events') as response: + assert response.status_code == 200 + gates['再补一句'].set() + lines = [line for line in response.iter_lines() if line.startswith('data: ')] + resumed = [json.loads(line[6:]) for line in lines] + whole = frames(running.result(timeout=10)) + + assert resumed == whole + assert [context for context in contexts] == ['先做这个', '再补一句'] From b02d6975dc5e0413c63479e5fa196bd68c58be2d Mon Sep 17 00:00:00 2001 From: wtz2333 Date: Wed, 18 Nov 2026 16:07:40 +0800 Subject: [PATCH 03/11] [fix] agent: keep the queue counter out of the conversation the view echoes back --- apps/api/src/opendirector_api/agent.py | 11 ++++++++--- tests/test_assistant_queue.py | 4 ++++ 2 files changed, 12 insertions(+), 3 deletions(-) diff --git a/apps/api/src/opendirector_api/agent.py b/apps/api/src/opendirector_api/agent.py index cd6a3902d..301b8757e 100644 --- a/apps/api/src/opendirector_api/agent.py +++ b/apps/api/src/opendirector_api/agent.py @@ -93,8 +93,11 @@ def conversation_is_empty(value): def public_conversation(value): + # Keys starting with an underscore are bookkeeping the client never sends + # back; Draft forbids extra members, so they must not reach the payload. return {key: item for key, item in value.items() - if key not in {'archivedConversations', 'reusedCreateIds'}} + if key not in {'archivedConversations', 'reusedCreateIds', 'queueSeq'} + and not key.startswith('_')} def reused_ids(value): @@ -169,8 +172,10 @@ def queue(self, project_id: UUID, session: str, message: dict, conversation_id: raise ProjectError('当前对话已切换,请重新加载后重试;原对话未覆盖。', 409) if any(item['id'] == message['id'] for item in value['messages']): raise ProjectError('这条消息已接受,请读取对话,不要重复发送。', 409) - value['queueSeq'] = value.get('queueSeq', 0) + 1 - queued = {**message, 'status': 'queued', 'queueSeq': value['queueSeq']} + if 'queueSeq' in value: + value['_queueSeq'] = value.pop('queueSeq') + value['_queueSeq'] = value.get('_queueSeq', 0) + 1 + queued = {**message, 'status': 'queued', 'queueSeq': value['_queueSeq']} value['messages'].append(queued) durable_json(file, value) return queued diff --git a/tests/test_assistant_queue.py b/tests/test_assistant_queue.py index 091606897..234abf308 100644 --- a/tests/test_assistant_queue.py +++ b/tests/test_assistant_queue.py @@ -128,6 +128,10 @@ def test_supplementary_message_waits_for_the_running_turn_and_then_runs(assistan waiting = client.get(path).json() assert [item['status'] for item in waiting['messages']] == ['complete', 'streaming', 'queued'] assert waiting['activeTurnId'] == first + # The ordering counter stays server-side: a view echoes the read model + # back as a draft, and Draft forbids members it does not declare. + assert 'queueSeq' not in waiting + assert waiting['messages'][-1]['queueSeq'] == 1 gate['release'].set() events = frames(running.result(timeout=10)) From 0925c5e5e4eb0d2a0ca9f80d852566e0946dbeb1 Mon Sep 17 00:00:00 2001 From: wtz2333 Date: Thu, 19 Nov 2026 10:53:42 +0800 Subject: [PATCH 04/11] [fix] agent: find the thinking frame by type in the deepseek trace test Every run event now carries a `seq`, so the exact-dict membership check `{'type': 'thinking'} in events` can never match the frame it means to find. The frame is present; look it up by type instead. --- tests/test_deepseek_runtime.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/tests/test_deepseek_runtime.py b/tests/test_deepseek_runtime.py index ae280c6a1..93ab8dfda 100644 --- a/tests/test_deepseek_runtime.py +++ b/tests/test_deepseek_runtime.py @@ -137,7 +137,7 @@ def test_acp_shared_write_and_native_trace(cli, tmp_path, monkeypatch, mode): assert (events[-1]['error'] is None) == (mode != 'incomplete'), events message = events[-1]['conversation']['messages'][-1] assert message['text'] == 'Saved.' - assert {'type': 'thinking'} in events + assert any(event['type'] == 'thinking' for event in events) assert 'Test native thought' not in response.text assert message['plan'] == [{'content': 'Save the plan', 'status': 'completed'}] assert client.get(path + '/assistant').json()['messages'][-1]['plan'] == message['plan'] From 0cd16a51b58d48b282c45981b3819355fe518036 Mon Sep 17 00:00:00 2001 From: wtz2333 Date: Tue, 17 Nov 2026 11:30:40 +0800 Subject: [PATCH 05/11] [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 41a8180b7..9135f0c47 100644 --- a/apps/api/src/opendirector_api/agent.py +++ b/apps/api/src/opendirector_api/agent.py @@ -241,6 +241,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') @@ -865,4 +888,39 @@ async def message(project_id: UUID, value: Turn, x_opendirector_session: UUID = started['start'] = dispatched['conversation'] 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 bdd5c8515c49b817611b180050b4ad7aec5a7368 Mon Sep 17 00:00:00 2001 From: wtz2333 Date: Tue, 17 Nov 2026 11:30:40 +0800 Subject: [PATCH 06/11] [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 9135f0c47..081e2d7d0 100644 --- a/apps/api/src/opendirector_api/agent.py +++ b/apps/api/src/opendirector_api/agent.py @@ -264,6 +264,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 5d06f194e312e16a54009ef877ddb7d9c19411b0 Mon Sep 17 00:00:00 2001 From: wtz2333 Date: Fri, 20 Nov 2026 15:00:25 +0800 Subject: [PATCH 07/11] [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 c053ca43be7a4f04d141377577b6aa1dfb6b68cf Mon Sep 17 00:00:00 2001 From: wtz2333 Date: Thu, 19 Nov 2026 10:01:28 +0800 Subject: [PATCH 08/11] [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 081e2d7d0..4898fce6e 100644 --- a/apps/api/src/opendirector_api/agent.py +++ b/apps/api/src/opendirector_api/agent.py @@ -66,6 +66,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): @@ -191,6 +192,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) -> dict | None: """Start the oldest queued message as this turn's user message. @@ -455,6 +485,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: @@ -702,7 +733,7 @@ async def produce_one(chain: Chain, plan: dict) -> tuple[dict | None, str | None session=chain.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': @@ -773,6 +804,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: @@ -792,6 +824,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: @@ -889,8 +922,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 ecd5fe47d..6f137979f 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、模型目录与认证 | @@ -51,7 +51,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 用量仍见原生轨迹。 @@ -87,7 +87,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 1a3a66ef4..56e4b722d 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 @@ -28,6 +29,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 a765bc60b..0f1813c15 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,9 +42,6 @@ def executable(runtime: str) -> str | None: return cli_executable('dsh' if runtime == 'deepseek' else runtime) -_CODEX_ISOLATION: dict[str, tuple[str, ...]] = {} - - def codex_environment() -> dict[str, str]: env = dict(os.environ) if sys.platform == 'win32' and not (env.get('HTTPS_PROXY') or env.get('ALL_PROXY')): @@ -54,31 +51,35 @@ def codex_environment() -> dict[str, str]: return env -def codex_isolation_flags(binary: 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. """ - cached = _CODEX_ISOLATION.get(binary) - if cached is not None: - return cached - wanted = ('--ignore-user-config', '--ignore-rules') - try: - probe = subprocess.run([binary, '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[binary] = 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')) @@ -123,10 +124,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: @@ -142,7 +148,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 @@ -184,7 +191,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 @@ -245,11 +252,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. ' @@ -257,7 +261,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] @@ -269,6 +274,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, @@ -284,7 +292,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() @@ -310,6 +318,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) @@ -324,7 +337,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 3b2a173f5..92a1cc55c 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 a85ad7aad..d9c49ba93 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 123d81e2ed845885537691b92408a90b6335c75f Mon Sep 17 00:00:00 2001 From: wtz2333 Date: Tue, 17 Nov 2026 11:23:17 +0800 Subject: [PATCH 09/11] [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 | 109 ++++++++++++++++++++------- src/i18n/messages/en-US/assistant.ts | 6 ++ src/i18n/messages/zh-CN/assistant.ts | 5 ++ tests/assistantQueue.test.ts | 102 +++++++++++++++++++++++++ 7 files changed, 296 insertions(+), 40 deletions(-) create mode 100644 tests/assistantQueue.test.ts diff --git a/src/backend/chat.ts b/src/backend/chat.ts index 51da14a15..d47023d4d 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; @@ -139,7 +147,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; @@ -293,6 +310,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 50d09fdeb..f9d3b6091 100644 --- a/src/canvas/AssistantPanel.tsx +++ b/src/canvas/AssistantPanel.tsx @@ -500,6 +500,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") && ( @@ -743,10 +758,10 @@ export function AssistantPanel({ onConfigure={onOpenSettings} />
- {chat.sending ? ( + {chat.sending && ( - ) : ( - )} +
@@ -788,6 +806,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 3b223a198..b5d7fce6e 100644 --- a/src/canvas/useAssistantChat.ts +++ b/src/canvas/useAssistantChat.ts @@ -18,7 +18,9 @@ import { stopChat, type ChatAsset, type Conversation, + type ChatRequest, conversationIsEmpty, + sendChat, } from "../backend/chat"; import { flushChatDraft, rememberChat } from "../backend/chatDrafts"; import { creationClient } from "../backend/creationClient.ts"; @@ -448,38 +450,81 @@ 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 ( !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, - 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 ?? [], - }, - 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. */ @@ -513,7 +558,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, @@ -521,6 +568,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, @@ -528,7 +577,7 @@ export function useAssistantChat( message.status === "streaming" ? { ...message, - id: assistantId, + id: reply, } : message, ), @@ -538,7 +587,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, ), @@ -546,7 +595,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), @@ -557,7 +606,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") { @@ -566,7 +615,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); @@ -575,7 +624,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 ffb2c0ceb9608c9b9988679c09e93f4ed4acff82 Mon Sep 17 00:00:00 2001 From: wtz2333 Date: Tue, 17 Nov 2026 11:37:09 +0800 Subject: [PATCH 10/11] [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 d47023d4d..2d9bed58f 100644 --- a/src/backend/chat.ts +++ b/src/backend/chat.ts @@ -149,6 +149,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; @@ -340,6 +342,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 f9d3b6091..f3bf66ab3 100644 --- a/src/canvas/AssistantPanel.tsx +++ b/src/canvas/AssistantPanel.tsx @@ -508,11 +508,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" || @@ -553,6 +569,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; @@ -696,6 +706,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 (!turnId.current || stopping) return; setStopping(true); @@ -747,6 +793,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); +}); From 650280741d43811002f3dd2a7bb13cc011fa2a6b Mon Sep 17 00:00:00 2001 From: wtz2333 Date: Fri, 20 Nov 2026 15:35:24 +0800 Subject: [PATCH 11/11] [feat] canvas: insert a message into the reply that is already running While a reply runs the composer now offers both deliveries: Enter (or the send button) hands the text to that reply through the runtime's own channel, and a Queue button waits for it to end. The inserted message is shown where it was sent, before the reply it joined. --- src/backend/chat.ts | 41 ++++++++++++++++++++- src/canvas/AssistantPanel.tsx | 33 ++++++++++++++--- src/canvas/assistant-experience.css | 16 +++++++++ src/canvas/useAssistantChat.ts | 54 ++++++++++++++++++++++++++++ src/i18n/messages/en-US/assistant.ts | 6 ++++ src/i18n/messages/zh-CN/assistant.ts | 6 ++++ tests/assistantQueue.test.ts | 52 +++++++++++++++++++++++++++ 7 files changed, 203 insertions(+), 5 deletions(-) diff --git a/src/backend/chat.ts b/src/backend/chat.ts index 2d9bed58f..f3219b333 100644 --- a/src/backend/chat.ts +++ b/src/backend/chat.ts @@ -27,6 +27,8 @@ export interface RuntimeInfo { | "unsupported_version" | "unknown"; supportsSkills?: boolean; + /** The runtime can take extra text inside a reply that is already running. */ + supportsSteering?: boolean; } export interface ChatSkill { source?: "builtin" | "workspace" | "project"; @@ -77,7 +79,9 @@ export interface ChatMessage { | "queued" | "cancelled" | "stopped" - | "interrupted"; + | "interrupted" + /** Text handed to the reply that was running when it was sent. */ + | "inserted"; /** Position of a queued message in the delivery order the server assigned. */ queueSeq?: number; assets?: ChatAsset[]; @@ -151,6 +155,8 @@ export type ChatEvent = | { type: "queued"; message: ChatMessage } /** A queued message was withdrawn before it started. */ | { type: "retracted"; messageId: string } + /** Text that reached the reply while it was still running. */ + | { type: "steered"; message: ChatMessage } | { type: "end"; turnId?: string; @@ -172,6 +178,8 @@ export interface ChatRequest { runtime?: AgentRuntime; runtimeModel?: string | null; skills?: string[]; + /** Insert reaches the running reply; queue waits for it to end. */ + delivery?: "queue" | "insert"; } function normalizeConversation(value: Conversation): Conversation { @@ -342,6 +350,37 @@ export async function sendChat( return null; } +export interface InsertedReply { + inserted: ChatMessage; + chainId: string; + turnId: string; +} + +/** + * Hand the text to the reply that is already running. + * + * `delivery: "insert"` goes through the runtime's own channel, so the answer + * keeps the work it has already done. The server refuses the insert when no + * reply is running, when the runtime has no such channel, or when the message + * carries assets; the caller shows that refusal as it is. + */ +export async function insertChat( + 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, delivery: "insert" }), + headers: { ...headers, "Content-Type": "application/json" }, + signal, + }); + if (response.status === 202) return (await response.json()) as InsertedReply; + await readChatEvents(response, onEvent, t); + return null; +} + /** * Take back a message that is still waiting behind the running reply. * diff --git a/src/canvas/AssistantPanel.tsx b/src/canvas/AssistantPanel.tsx index f3bf66ab3..fe303e2ce 100644 --- a/src/canvas/AssistantPanel.tsx +++ b/src/canvas/AssistantPanel.tsx @@ -518,6 +518,11 @@ export function AssistantPanel({ )} + {message.status === "inserted" && ( + + {t("assistant.panel.inserted")} + + )} {message.status === "cancelled" && ( {t("assistant.panel.cancelled")} @@ -734,7 +739,10 @@ export function AssistantPanel({ onSubmit={() => { nearBottom.current = true; pendingReferences.cancel(); - void chat.send(); + // Enter reaches the running reply when the runtime can take it; + // otherwise it queues behind that reply. + if (chat.sending && chat.steerable) void chat.insert(); + else void chat.send(); }} /> @@ -805,14 +813,29 @@ export function AssistantPanel({ )} + {chat.sending && ( + + )}