diff --git a/apps/api/src/opendirector_api/agent.py b/apps/api/src/opendirector_api/agent.py index ac2b1948..87f964d4 100644 --- a/apps/api/src/opendirector_api/agent.py +++ b/apps/api/src/opendirector_api/agent.py @@ -67,6 +67,76 @@ 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) + revisionOf: UUID | None = None + expectedRevision: int | None = None + + +def superseded_turn_ids(messages): + """Turn ids a revision replaced; they stay in history but leave the active path. + + The link is one field per turn, so the active path is derived from the chain + instead of from message positions. + """ + return {str(message['revisionOf']) for message in messages if message.get('revisionOf')} + + +def active_messages(messages): + """Messages of the surviving attempt, in order. + + A revised turn keeps the replaced request and its reply in history for + traceability, but neither may reach the next attempt's context. The reply id + repeats the rule used when a turn is accepted. + """ + gone = superseded_turn_ids(messages) + reply_ids = {str(uuid5(UUID(turn_id), 'assistant')) for turn_id in gone} + return [message for message in messages + if str(message.get('id')) not in gone and str(message.get('id')) not in reply_ids] + + +def revision_error(messages, revision_of): + """Why a turn may not be revised, or None when it may. + + Only the newest turn can be revised, and only once: a second revision would + have to pick between competing successors. + """ + if revision_of in superseded_turn_ids(messages): + return '这条消息已经修订过,请编辑最新一条。' + if revision_of not in {message['id'] for message in messages}: + return '找不到要修订的消息,请刷新后重试。' + turns = [message['id'] for message in messages if message.get('role') == 'user'] + if not turns or turns[-1] != revision_of: + return '只能修订刚才停止的那条消息。' + reply = next((message for message in messages + if message['id'] == str(uuid5(UUID(revision_of), 'assistant'))), None) + if reply is None or reply.get('status') not in {'stopped', 'interrupted'}: + return '只能修订已停止的消息。' + return None + + +def inherited_jobs(messages, revision_of, jobs=()): + """Jobs the replaced turn already had accepted, so a retry does not repeat them. + + The command id is the idempotency key the host derives from the turn and call, + so it is always present. The job record only exists when the submission was + accepted; ``jobId`` stays None for a call that never produced one, which is + what tells the new attempt to submit rather than reuse. + """ + reply = next((message for message in messages + if message['id'] == str(uuid5(UUID(revision_of), 'assistant'))), None) + if not reply: + return [] + turn = UUID(revision_of) + by_call = {str(job.agentCallId): job for job in jobs if str(job.agentRunId) == revision_of} + snapshot = [] + for tool in reply.get('tools', []): + job = by_call.get(str(tool.get('id'))) + snapshot.append({'commandId': str(agent_command_id(turn, tool.get('id'))), + 'callId': tool.get('id'), 'name': tool.get('name'), + 'jobId': str(job.id) if job else None, + 'status': str(job.status) if job else tool.get('status'), + 'asset': job.asset.model_dump(mode='json') if job and job.asset else None, + 'errorDetails': job.errorDetails.model_dump(mode='json') if job and job.errorDetails else None}) + return snapshot def draft_content_is_empty(content): @@ -124,7 +194,7 @@ def path(self, project_id: UUID, session: str | None = None) -> Path: def update(self, project_id: UUID, session: str | None = None, *, draft: Draft | None = None, begin: dict | None = None, finish: dict | None = None, conversation_id: UUID | None = None, - before_begin=None) -> dict: + before_begin=None, expected_revision: int | None = None) -> dict: with self.projects.local.transaction() as db: self.projects._recover() directory, _, _ = self.projects._load(db, project_id) @@ -145,13 +215,24 @@ def update(self, project_id: UUID, session: str | None = None, *, draft: Draft | if begin is not None: if any(message['id'] == begin['id'] for message in value['messages']): raise ProjectError('这条消息已接受,请读取对话,不要重复发送。', 409) + expected = begin.pop('expectedRevision', expected_revision) + if expected is not None and expected != value.get('revision', 0): + raise ProjectError('对话已在别处更新,请刷新后重试。', 409) + revision_of = begin.get('revisionOf') + if revision_of is not None: + blocked = revision_error(value['messages'], str(revision_of)) + if blocked: + raise ProjectError(blocked, 409) + begin['inheritedJobs'] = inherited_jobs(value['messages'], str(revision_of), + self.projects.snapshot(project_id).jobs) if before_begin is not None: before_begin() value['messages'].append(begin) value['messages'].append({'id': str(uuid5(UUID(begin['id']), 'assistant')), 'role': 'assistant', 'text': '', 'status': 'streaming', **{key: begin[key] for key in ('model', 'modelIsCliDefault', 'runtime') if key in begin}}) - value.update(draft='', draftContent=None, assets=[], skills=[]) + value.update(draft='', draftContent=None, assets=[], skills=[], + revision=value.get('revision', 0) + 1) changed = True if finish is not None: value['messages'] = [finish if message['id'] == finish['id'] else message for message in value['messages']] @@ -420,14 +501,18 @@ async def produce() -> None: 'skills': value.skills, 'runtime': value.runtime, 'runtimeModel': value.runtimeModel, 'modelSelections': dict(value.modelSelections), 'model': model, 'modelIsCliDefault': model_is_cli_default, 'status': 'complete'} + if value.revisionOf is not None: + user['revisionOf'] = str(value.revisionOf) saved = await asyncio.to_thread(conversations.update, project_id, session, begin=user, - conversation_id=value.conversationId, before_begin=validate_connection) + conversation_id=value.conversationId, before_begin=validate_connection, + expected_revision=value.expectedRevision) accepted = True events.put({'type': 'start', 'conversation': saved}) - previous_sources = {source['id']: source for message in saved['messages'][:-2] + active = active_messages(saved['messages']) + previous_sources = {source['id']: source for message in active for source in message.get('sources', [])} context = [] - for message in saved['messages'][:-1]: + for message in active[:-1]: content = message['text'] or '(empty reply)' references = [] for attachment in message.get('assets', []): diff --git a/packages/core/src/opendirector/agent/native.py b/packages/core/src/opendirector/agent/native.py index e9f6beab..52cb3b87 100644 --- a/packages/core/src/opendirector/agent/native.py +++ b/packages/core/src/opendirector/agent/native.py @@ -148,6 +148,9 @@ def command(runtime: str, work: Path, socket: str, token: str, model: str | None def text_events(runtime: str, raw: dict) -> list[dict]: + if 'type' not in raw: + # Plain-text stdout the harness printed outside its event protocol. + return [] if runtime == 'claude' and raw.get('error') == 'authentication_failed': raise ProjectError('Claude Code 登录已过期,请在终端执行 claude auth login 后重试。', 401) if runtime == 'codex' and raw['type'] == 'error': @@ -309,7 +312,15 @@ async def observe(raw): deepseek_server, observe, session_id) else: while line := await process.stdout.readline(): - raw = json.loads(line) + # A harness may print plain text on stdout, for example a + # warning about an unrecognized model. Keep it in the trace + # instead of failing the whole turn on a parse error. + try: + raw = json.loads(line) + except ValueError: + if line.strip(): + await queue.put({'native': {'text': line.decode('utf-8', 'replace')}}) + continue previous_session = reported_session if runtime == 'codex' and raw['type'] == 'thread.started': reported_session = raw.get('thread_id') diff --git a/src/backend/chat.ts b/src/backend/chat.ts index 51da14a1..58cb4cad 100644 --- a/src/backend/chat.ts +++ b/src/backend/chat.ts @@ -62,7 +62,21 @@ export interface ChatSource { url: string; title: string; } +/** A job the superseded attempt had already accepted, kept for the retry. */ +export interface InheritedJob { + commandId: string; + callId: string; + name: string; + jobId: string | null; + status: string; + asset?: unknown; + errorDetails?: unknown; +} export interface ChatMessage { + /** The stopped attempt this message revises, so history keeps both. */ + revisionOf?: string; + /** Jobs accepted before the revised attempt, so it does not submit them again. */ + inheritedJobs?: InheritedJob[]; sources?: ChatSource[]; plan?: ChatPlanEntry[]; runtime?: AgentRuntime; @@ -73,6 +87,7 @@ export interface ChatMessage { content?: ReferenceContent | null; status: "complete" | "streaming" | "stopped" | "interrupted"; assets?: ChatAsset[]; + skills?: string[]; model?: string | null; modelIsCliDefault?: boolean; runtimeModel?: string | null; @@ -108,6 +123,8 @@ export interface ChatDraft { } export interface Conversation extends ChatDraft { messages: ChatMessage[]; + /** Increments on every accepted turn; a stale value means the view is behind. */ + revision?: number; } export function draftContentIsEmpty( @@ -144,6 +161,10 @@ export type ChatEvent = export interface ChatRequest { conversationId?: string; id: string; + /** The turn this request replaces. Absent for an ordinary turn. */ + revisionOf?: string; + /** The conversation revision this request was composed against. */ + expectedRevision?: number; modelId?: string; text: string; content?: ReferenceContent | null; diff --git a/src/canvas/AssistantPanel.tsx b/src/canvas/AssistantPanel.tsx index 70bb8f50..e5cf077c 100644 --- a/src/canvas/AssistantPanel.tsx +++ b/src/canvas/AssistantPanel.tsx @@ -413,6 +413,13 @@ export function AssistantPanel({ )} {value.messages.map((message, index) => { const previous = value.messages[index - 1]; + const next = value.messages[index + 1]; + // Only the newest stopped attempt can be revised, matching the server. + const editable = message.role === "user" && + next?.role === "assistant" && + (next.status === "stopped" || next.status === "interrupted") && + index === value.messages.length - 2 && + !chat.sending; const trace = message.role === "assistant" && message !== latestReply && message.status !== "streaming" && previous?.role === "user" && new URLSearchParams({ traceProject: documentId, @@ -487,6 +494,33 @@ export function AssistantPanel({ {t("assistant.panel.trace")} ↗ )} + {editable && ( + + )} + {!!message.inheritedJobs?.length && ( +
+ + {t("assistant.panel.inheritedJobs", { + count: message.inheritedJobs.length, + })} + + +
+ )} {message.role === "user" && !!message.assets?.length && } {(message.status === "stopped" || message.status === "interrupted") && ( @@ -500,7 +534,15 @@ export function AssistantPanel({ ); })} -
+
+ {chat.editing && ( +
+ {t("assistant.panel.editingNotice")} + +
+ )} {chat.error && (
{chat.error} diff --git a/src/canvas/assistant-panel.css b/src/canvas/assistant-panel.css index aecc065b..2362863f 100644 --- a/src/canvas/assistant-panel.css +++ b/src/canvas/assistant-panel.css @@ -306,6 +306,62 @@ color: var(--chat-muted); font-size: 11px; } +.cw-assistant-message-edit { + margin-top: 8px; + padding: 3px 9px; + border: 1px solid var(--chat-border); + border-radius: 6px; + background: transparent; + color: var(--chat-muted); + font-size: 11px; + cursor: pointer; +} +.cw-assistant-message-edit:hover:not(:disabled) { + border-color: var(--chat-accent); + color: var(--chat-accent); +} +.cw-assistant-message-edit:disabled { + opacity: 0.45; + cursor: default; +} +.cw-assistant-inherited { + margin-top: 8px; + color: var(--chat-muted); + font-size: 11px; +} +.cw-assistant-inherited summary { + cursor: pointer; + opacity: 0.75; +} +.cw-assistant-inherited ul { + margin: 6px 0 0; + padding-left: 16px; + opacity: 0.7; +} +.cw-assistant-inherited li { + display: flex; + gap: 8px; + list-style: disc; +} +.cw-assistant-editing { + display: flex; + align-items: center; + justify-content: space-between; + gap: 10px; + margin-bottom: 8px; + padding: 7px 10px; + border: 1px solid var(--chat-border); + border-radius: 8px; + color: var(--chat-muted); + font-size: 11px; +} +.cw-assistant-editing button { + border: none; + background: transparent; + color: var(--chat-accent); + font-size: 11px; + cursor: pointer; +} .cw-assistant-message-assets { display: flex; flex-wrap: wrap; diff --git a/src/canvas/chatTurnRequest.ts b/src/canvas/chatTurnRequest.ts new file mode 100755 index 00000000..d3765495 --- /dev/null +++ b/src/canvas/chatTurnRequest.ts @@ -0,0 +1,69 @@ +import { builtinThinking } from "./agentPreferences.ts"; +import type { + AgentRuntime, + Conversation, + ModelSelections, + Thinking, +} from "../backend/chat.ts"; +import type { ReferenceContent } from "./chatReferenceContent"; + +/** The turn being edited: a stopped attempt and the draft it is replacing. */ +export interface ChatEditing { + turnId: string; + conversationId: string; + saved: Pick; +} + +export interface TurnRequest { + id: string; + conversationId?: string; + modelId?: string; + runtime: AgentRuntime; + runtimeModel?: string | null; + text: string; + content?: ReferenceContent | null; + assets: string[]; + thinking: Thinking; + modelSelections: ModelSelections; + skills: string[]; + /** The turn this request replaces. Absent for an ordinary turn. */ + revisionOf?: string; + /** The conversation revision this request was composed against. */ + expectedRevision?: number; +} + +/** + * The request body for a turn, including the identity an edit must carry so the + * server can validate it against the conversation it was composed on. + */ +export function turnRequest( + input: Conversation, + { + id, + modelId, + editing, + revision, + }: { + id: string; + modelId?: string; + editing: ChatEditing | null; + revision?: number; + }, +): TurnRequest { + return { + id, + conversationId: input.conversationId, + modelId, + runtime: input.runtime ?? "default", + runtimeModel: input.runtimeModel, + text: input.draft, + content: input.draftContent, + assets: input.assets.map((asset) => asset.id), + thinking: builtinThinking(input, modelId), + modelSelections: input.modelSelections, + skills: input.skills ?? [], + ...(editing + ? { revisionOf: editing.turnId, expectedRevision: revision } + : {}), + }; +} diff --git a/src/canvas/useAssistantChat.ts b/src/canvas/useAssistantChat.ts index 3b223a19..f9890945 100644 --- a/src/canvas/useAssistantChat.ts +++ b/src/canvas/useAssistantChat.ts @@ -18,6 +18,7 @@ import { stopChat, type ChatAsset, type Conversation, + type ChatMessage, conversationIsEmpty, } from "../backend/chat"; import { flushChatDraft, rememberChat } from "../backend/chatDrafts"; @@ -38,6 +39,7 @@ import { import type { CanvasNode } from "./model"; import { pendingCanvasReferences } from "./pendingCanvasReferences.ts"; import type { Translate } from "../i18n/I18nProvider.tsx"; +import { turnRequest, type ChatEditing } from "./chatTurnRequest.ts"; export interface ProjectChatAsset extends ReferenceAsset { kind: string; @@ -49,6 +51,32 @@ export const attachment = ({ size, fingerprint, }: ChatAsset): ChatAsset => ({ id, name, type, size, fingerprint }); +/** + * The id an uncertain submission keeps, so retrying an edit resends the same + * operation instead of creating a second attempt. + */ +const pendingKey = (conversationId: string) => + `opendirector.chat.revision.${conversationId}`; +const pendingTurnId = (conversationId: string) => { + try { + const store = globalThis.sessionStorage; + if (!store) return undefined; + return store.getItem(pendingKey(conversationId)) ?? undefined; + } catch { + return undefined; + } +}; +const rememberPendingTurnId = (conversationId: string, id?: string) => { + try { + const store = globalThis.sessionStorage; + if (!store) return; + if (id) store.setItem(pendingKey(conversationId), id); + else store.removeItem(pendingKey(conversationId)); + } catch { + // Storage can be unavailable; the retry then creates a fresh turn. + } +}; + const empty = (): Conversation => ({ messages: [], draft: "", @@ -91,6 +119,9 @@ export function useAssistantChat( const [threadsLoading, setThreadsLoading] = useState(false); const [threadsError, setThreadsError] = useState(""); const [changing, setChanging] = useState(false); + // The stopped attempt being revised: its user message id plus the draft the + // edit replaced, so cancelling restores exactly what the user had typed. + const [editing, setEditing] = useState(null); const switching = useRef(false); const [error, setError] = useState(""); const displayError = (text: string) => @@ -459,28 +490,87 @@ export function useAssistantChat( ) return; const input = current.current; - await follow(crypto.randomUUID(), async (id, signal, onEvent) => { + const revising = editing; + // A retry of the same edit keeps its id, so an uncertain submission cannot + // become a second attempt. An ordinary turn always gets a fresh one. + const id = + (revising && + input.conversationId && + pendingTurnId(input.conversationId)) || + crypto.randomUUID(); + if (revising && input.conversationId) + rememberPendingTurnId(input.conversationId, id); + await follow(id, async (turn, signal, onEvent) => { await flushChatDraft(projectId); await streamChat( projectId, - { - id, - conversationId: input.conversationId, + turnRequest(input, { + id: turn, 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 ?? [], - }, + editing: revising, + revision: input.revision, + }), signal, onEvent, t, ); }); + // The server accepted the attempt; the id must not be reused afterwards. + if (revising && input.conversationId) + rememberPendingTurnId(input.conversationId); + if (revising) setEditing(null); + }; + /** + * Open a stopped attempt for editing. The conversation itself is untouched: + * the active path only changes once the server accepts the revised turn. + */ + const beginEdit = (turn: ChatMessage) => { + if (submitting.current || !loaded) return; + const input = current.current; + setEditing({ + turnId: turn.id, + conversationId: input.conversationId ?? "", + saved: { + draft: input.draft, + draftContent: input.draftContent, + assets: input.assets, + skills: input.skills, + }, + }); + const assets = (turn.assets ?? []).flatMap((asset) => { + const known = knownAssets.current.get(asset.id); + return known ? [attachment(known)] : [attachment(asset)]; + }); + assets.forEach((asset) => knownAssets.current.set(asset.id, asset)); + const next: Conversation = { + ...input, + draft: turn.text, + // Reuse the stored content so references and skills survive the edit. + draftContent: referenceContent( + turn.text, + (turn.assets ?? []).map((asset) => asset.id), + turn.assets ?? [], + turn.content, + t, + ), + assets, + skills: turn.skills ?? input.skills, + }; + current.current = next; + rememberChat(projectId, next); + setValue(next); + setError(""); + }; + /** Leave editing without sending; the original message stays untouched. */ + const cancelEdit = () => { + if (!editing) return; + const next: Conversation = { ...current.current, ...editing.saved }; + current.current = next; + rememberChat(projectId, next); + setValue(next); + if (next.conversationId) rememberPendingTurnId(next.conversationId); + setEditing(null); + setError(""); }; /** Re-attach to a turn that kept running while this project was not shown. */ resume.current = async (id: string) => { @@ -690,6 +780,9 @@ export function useAssistantChat( addNodes, addAssets, send, + editing, + beginEdit, + cancelEdit, 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 3e19abda..fd0c49fa 100644 --- a/src/i18n/messages/en-US/assistant.ts +++ b/src/i18n/messages/en-US/assistant.ts @@ -58,6 +58,10 @@ export const assistant = { "assistant.panel.connecting": "Connecting to the conversation service…", "assistant.panel.refreshCatalog": "Read again", "assistant.panel.stopped": "Reply stopped", + "assistant.panel.editResend": "Edit and resend", + "assistant.panel.editingNotice": "Editing a stopped message. Sending it starts a new attempt.", + "assistant.panel.cancelEdit": "Cancel editing", + "assistant.panel.inheritedJobs": "Tasks already submitted ({{count}})", "assistant.panel.interrupted": "Reply interrupted", "assistant.panel.send": "Send message", "assistant.panel.stop": "Stop reply", diff --git a/src/i18n/messages/zh-CN/assistant.ts b/src/i18n/messages/zh-CN/assistant.ts index 4c95240b..f5f48d73 100644 --- a/src/i18n/messages/zh-CN/assistant.ts +++ b/src/i18n/messages/zh-CN/assistant.ts @@ -57,6 +57,10 @@ export const assistant = { "assistant.panel.connecting": "正在连接对话服务…", "assistant.panel.refreshCatalog": "重新读取", "assistant.panel.stopped": "已停止回复", + "assistant.panel.editResend": "编辑并重发", + "assistant.panel.editingNotice": "正在编辑已停止的消息,发送后会作为新的尝试。", + "assistant.panel.cancelEdit": "取消编辑", + "assistant.panel.inheritedJobs": "已提交的任务({{count}})", "assistant.panel.interrupted": "回复已中断", "assistant.panel.send": "发送消息", "assistant.panel.stop": "停止回复", diff --git a/tests/assistantRevision.test.ts b/tests/assistantRevision.test.ts new file mode 100755 index 00000000..bc65ad0b --- /dev/null +++ b/tests/assistantRevision.test.ts @@ -0,0 +1,56 @@ +import assert from "node:assert/strict"; +import test from "node:test"; +import { turnRequest } from "../src/canvas/chatTurnRequest.ts"; +import type { Conversation } from "../src/backend/chat.ts"; + +const conversation = (patch: Partial = {}): Conversation => ({ + messages: [], + draft: "NEW-标记", + assets: [], + thinking: "auto", + modelSelections: {}, + conversationId: "conversation-1", + revision: 4, + ...patch, +}); + +test("an ordinary turn carries no revision identity", () => { + const body = turnRequest(conversation(), { id: "turn-2", modelId: "model", editing: null }); + assert.equal(body.revisionOf, undefined); + assert.equal(body.expectedRevision, undefined); + assert.equal(body.text, "NEW-标记"); +}); + +test("an edit names the stopped turn and the revision it was composed on", () => { + const editing = { + turnId: "turn-stopped", + conversationId: "conversation-1", + saved: { draft: "", draftContent: null, assets: [], skills: [] }, + }; + const body = turnRequest(conversation(), { + id: "turn-3", modelId: "model", editing, revision: 4, + }); + assert.equal(body.revisionOf, "turn-stopped"); + assert.equal(body.expectedRevision, 4); + // The revised text is what the new attempt sends, exactly once. + assert.equal(body.text, "NEW-标记"); +}); + +test("an edit keeps the references and skills of the message it revises", () => { + const editing = { + turnId: "turn-stopped", + conversationId: "conversation-1", + saved: { draft: "", draftContent: null, assets: [], skills: [] }, + }; + const body = turnRequest( + conversation({ + assets: [{ id: "asset-1", name: "a", type: "image/png", size: 1, fingerprint: "f" }], + skills: ["canvas"], + draftContent: [{ type: "text", text: "NEW-标记" }], + }), + { id: "turn-3", modelId: "model", editing, revision: 4 }, + ); + assert.deepEqual(body.assets, ["asset-1"]); + assert.deepEqual(body.skills, ["canvas"]); + assert.deepEqual(body.content, [{ type: "text", text: "NEW-标记" }]); +}); diff --git a/tests/test_agent_citations.py b/tests/test_agent_citations.py index 9f6284bf..c4bb0976 100644 --- a/tests/test_agent_citations.py +++ b/tests/test_agent_citations.py @@ -81,3 +81,10 @@ def test_historical_sources_reuse_prior_turn_evidence_but_do_not_follow_trace_li (folder / f'{turn}.codex.jsonl').symlink_to(external) conversation['messages'][-1]['text'] = 'Other\ue200cite\ue202turn2view0\ue201' assert with_trace_sources(conversation, tmp_path)['messages'][-1]['sources'] == [] + + +def test_plain_stdout_outside_the_event_protocol_is_ignored(): + # A harness may print a warning on stdout, for example about an unrecognized + # model. It must not fail the turn, and it carries no events. + assert text_events('claude', {'text': '[claude-code:unrecognized_model]\n'}) == [] + assert text_events('codex', {'text': 'warning\n'}) == [] diff --git a/tests/test_assistant_revision.py b/tests/test_assistant_revision.py new file mode 100755 index 00000000..5278032d --- /dev/null +++ b/tests/test_assistant_revision.py @@ -0,0 +1,311 @@ +"""Tests for editing and resending a stopped user turn (#375). + +Covered behaviours follow the agreed design: + +* ``revisionOf`` links a new turn back to the turn it replaces; the active path + is derived by following that chain, not by slicing ``messages`` positionally. +* ``expectedRevision`` guards concurrent writes inside the same transaction. +* A revision carries a snapshot of the original turn's accepted jobs. +""" +import json +import threading +import time +from io import BytesIO +from uuid import uuid4 + +from PIL import Image + +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): + contexts = [] + # Replies stay streaming until released, so a stop request is what ends a + # turn and the server records ``stopped`` instead of ``complete``. + release = threading.Event() + + async def stream(self, run): + contexts.append(run.messages) + # Emit the tool record before waiting, so a stopped turn still owns the + # accepted job a revision has to inherit. + yield {'type': 'tool', 'id': 'call-known', 'name': 'run_command', 'status': 'complete'} + while not release.is_set(): + import asyncio + await asyncio.sleep(0.01) + yield {'type': 'delta', 'text': 'REVISED-ATTEMPT' if len(contexts) > 1 else 'FIRST-ATTEMPT'} + + 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 + 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()) + 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, release + + +def open_turn(client, path, conversation_id, text, *, revision_of=None, assets=()): + """Send a turn without waiting for its reply, and return (thread, turn id).""" + body = {'id': str(uuid4()), 'runtime': 'default', 'conversationId': conversation_id, 'text': text} + if revision_of is not None: + body['revisionOf'] = revision_of + if assets: + body['assets'] = list(assets) + captured = {} + + def run(): + captured['response'] = client.post(path + '/turns', json=body) + + thread = threading.Thread(target=run, daemon=True) + thread.start() + deadline = time.time() + 10 + while time.time() < deadline: + state = client.get(path).json() + streaming = [message for message in state['messages'] if message.get('status') == 'streaming'] + if streaming: + break + time.sleep(0.02) + turn = body['id'] + return thread, turn, captured + + +def finish(client, path, thread, turn, captured): + assert client.post(f'{path}/turns/{turn}/stop').status_code == 200 + thread.join(timeout=10) + assert not thread.is_alive(), 'the stopped turn did not end' + return captured['response'] + + +def error_of(response): + ends = [frame for frame in frames(response) if frame['type'] == 'end'] + assert ends, response.text + return ends[-1]['error'] + + +def conversation(client, path): + response = client.get(path) + assert response.status_code == 200, response.text + return response.json() + + +def test_revised_attempt_replaces_the_stopped_turn_on_the_active_path(assistant): + client, path, contexts, release = assistant + active = conversation(client, path)['conversationId'] + thread, original, captured = open_turn(client, path, active, 'OLD-标记') + finish(client, path, thread, original, captured) + assert conversation(client, path)['messages'][-1]['status'] == 'stopped' + + release.set() + revised = client.post(path + '/turns', json={'id': str(uuid4()), 'runtime': 'default', + 'conversationId': active, 'text': 'NEW-标记', 'revisionOf': original}) + assert revised.status_code == 200, revised.text + assert error_of(revised) is None, error_of(revised) + + seen = json.dumps(contexts[-1], ensure_ascii=False) + assert 'NEW-标记' in seen + assert 'OLD-标记' not in seen, 'the replaced request must leave the active path' + + saved = conversation(client, path) + assert [message['id'] for message in saved['messages']].count(original) == 1, \ + 'the stopped turn is kept for history, not rewritten' + assert saved['messages'][-2].get('revisionOf') == original + # Later turns continue from the revised attempt, not from the replaced one. + again = client.post(path + '/turns', json={'id': str(uuid4()), 'runtime': 'default', + 'conversationId': active, 'text': 'third'}) + assert error_of(again) is None, error_of(again) + later = json.dumps(contexts[-1], ensure_ascii=False) + assert 'third' in later + assert 'OLD-标记' not in later + + +def test_revision_of_an_unrelated_turn_is_rejected(assistant): + client, path, contexts, release = assistant + release.set() + active = conversation(client, path)['conversationId'] + assert error_of(client.post(path + '/turns', json={'id': str(uuid4()), 'runtime': 'default', + 'conversationId': active, 'text': 'seed'})) is None + response = client.post(path + '/turns', json={'id': str(uuid4()), 'runtime': 'default', + 'conversationId': active, 'text': 'x', 'revisionOf': str(uuid4())}) + assert response.status_code == 200, response.text + assert error_of(response), 'an unknown turn cannot be revised' + + +def test_a_turn_that_is_not_the_newest_cannot_be_revised(assistant): + client, path, contexts, release = assistant + release.set() + active = conversation(client, path)['conversationId'] + for text in ('first', 'second'): + assert error_of(client.post(path + '/turns', json={'id': str(uuid4()), 'runtime': 'default', + 'conversationId': active, 'text': text})) is None + first = [message for message in conversation(client, path)['messages'] if message['role'] == 'user'][0]['id'] + response = client.post(path + '/turns', json={'id': str(uuid4()), 'runtime': 'default', + 'conversationId': active, 'text': 'too late', 'revisionOf': first}) + assert response.status_code == 200, response.text + assert error_of(response), 'only the newest turn can be revised' + + +def test_a_turn_cannot_be_revised_twice(assistant): + client, path, contexts, release = assistant + active = conversation(client, path)['conversationId'] + thread, original, captured = open_turn(client, path, active, 'OLD-标记') + finish(client, path, thread, original, captured) + + release.set() + first = client.post(path + '/turns', json={'id': str(uuid4()), 'runtime': 'default', + 'conversationId': active, 'text': 'NEW-标记', 'revisionOf': original}) + assert error_of(first) is None, error_of(first) + again = client.post(path + '/turns', json={'id': str(uuid4()), 'runtime': 'default', + 'conversationId': active, 'text': 'NEW-again', 'revisionOf': original}) + assert again.status_code == 200, again.text + assert error_of(again), 'a turn can only be revised once' + + +def test_expected_revision_blocks_a_concurrent_write(assistant): + client, path, contexts, release = assistant + release.set() + active = conversation(client, path)['conversationId'] + assert error_of(client.post(path + '/turns', json={'id': str(uuid4()), 'runtime': 'default', + 'conversationId': active, 'text': 'seed'})) is None + revision = conversation(client, path)['revision'] + + fresh = client.post(path + '/turns', json={'id': str(uuid4()), 'runtime': 'default', + 'conversationId': active, 'text': 'second', 'expectedRevision': revision}) + assert error_of(fresh) is None, error_of(fresh) + stale = client.post(path + '/turns', json={'id': str(uuid4()), 'runtime': 'default', + 'conversationId': active, 'text': 'third', 'expectedRevision': revision}) + assert stale.status_code == 200, stale.text + assert error_of(stale), 'a stale expectedRevision must not overwrite' + + +def test_revision_snapshots_the_stopped_turns_tool_records(assistant): + client, path, contexts, release = assistant + active = conversation(client, path)['conversationId'] + thread, original, captured = open_turn(client, path, active, 'OLD-标记') + finish(client, path, thread, original, captured) + assert conversation(client, path)['messages'][-1]['status'] == 'stopped' + + release.set() + revised = client.post(path + '/turns', json={'id': str(uuid4()), 'runtime': 'default', + 'conversationId': active, 'text': 'NEW-标记', 'revisionOf': original}) + assert error_of(revised) is None, error_of(revised) + new_turn = frames(revised)[0]['conversation']['messages'][-2] + assert new_turn.get('inheritedJobs'), 'the snapshot is written together with the new turn' + assert [job['callId'] for job in new_turn['inheritedJobs']] == ['call-known'] + from uuid import UUID + expected = str(agent.agent_command_id(UUID(original), 'call-known')) + assert [job['commandId'] for job in new_turn['inheritedJobs']] == [expected] + + +def test_inherited_jobs_resolves_the_job_receipt_by_call_id(): + """The snapshot carries the idempotency key and, when one exists, the job.""" + from types import SimpleNamespace + from uuid import UUID + + turn = str(uuid4()) + reply_id = str(agent.uuid5(UUID(turn), 'assistant')) + messages = [ + {'id': turn, 'role': 'user', 'text': 'OLD'}, + {'id': reply_id, 'role': 'assistant', 'status': 'stopped', + 'tools': [{'id': 'call-done', 'name': 'generate', 'status': 'running'}, + {'id': 'call-lost', 'name': 'generate', 'status': 'failed'}]}, + ] + job = SimpleNamespace(id=uuid4(), agentRunId=turn, agentCallId='call-done', status='succeeded', + asset=None, errorDetails=None) + snapshot = agent.inherited_jobs(messages, turn, [job]) + + done = next(item for item in snapshot if item['callId'] == 'call-done') + lost = next(item for item in snapshot if item['callId'] == 'call-lost') + # The accepted job is resolved and its status wins over the stale tool record. + assert done['jobId'] == str(job.id) and done['status'] == 'succeeded' + assert done['commandId'] == str(agent.agent_command_id(UUID(turn), 'call-done')) + # A call that never produced a job keeps its command id and reports no job. + assert lost['jobId'] is None and lost['status'] == 'failed' + assert lost['commandId'] == str(agent.agent_command_id(UUID(turn), 'call-lost')) + + +def test_a_running_turn_rejects_a_concurrent_submission(assistant): + """A second submit while a turn is running is refused before it streams.""" + client, path, contexts, release = assistant + active = conversation(client, path)['conversationId'] + thread, original, captured = open_turn(client, path, active, 'OLD-标记') + try: + blocked = client.post(path + '/turns', json={'id': str(uuid4()), 'runtime': 'default', + 'conversationId': active, 'text': 'concurrent', 'revisionOf': original}) + assert blocked.status_code == 409, blocked.text + finally: + finish(client, path, thread, original, captured) + # The refused submission left no trace. + texts = [message.get('text') for message in conversation(client, path)['messages']] + assert 'concurrent' not in texts + + +def test_the_revision_survives_reloading_the_conversation(assistant): + """Both attempts stay inspectable; the active path still excludes the old one.""" + client, path, contexts, release = assistant + active = conversation(client, path)['conversationId'] + thread, original, captured = open_turn(client, path, active, 'OLD-标记') + finish(client, path, thread, original, captured) + release.set() + revised_id = str(uuid4()) + revised = client.post(path + '/turns', json={'id': revised_id, 'runtime': 'default', + 'conversationId': active, 'text': 'NEW-标记', 'revisionOf': original}) + assert error_of(revised) is None, error_of(revised) + + reloaded = conversation(client, path) + users = [message for message in reloaded['messages'] if message['role'] == 'user'] + # The replaced request is kept for inspection, not rewritten. + assert [message['text'] for message in users] == ['OLD-标记', 'NEW-标记'] + assert next(message for message in users if message['id'] == revised_id)['revisionOf'] == original + assert reloaded['revision'] == conversation(client, path)['revision'] + + +def test_the_revised_attempt_keeps_attachments_of_the_edited_message(assistant): + client, path, contexts, release = assistant + active = conversation(client, path)['conversationId'] + base = path.removesuffix('/assistant') + image = BytesIO() + Image.new('RGB', (5, 4), 'purple').save(image, format='PNG') + handle = str(uuid4()) + assert client.put(base + '/uploads/' + handle, content=image.getvalue(), + headers={'X-Asset-Name': 'keep.png'}).status_code == 200 + imported = client.post(base + '/commands', json={'type': 'asset.import', + 'commandId': str(uuid4()), 'projectId': base.rsplit('/', 1)[-1], + 'payload': {'uploadHandle': handle, 'name': 'keep.png', 'expectedKind': 'image'}}) + assert imported.status_code == 200, imported.text + asset = imported.json()['changed'][0]['id'] + + thread, original, captured = open_turn(client, path, active, 'OLD-标记', assets=[asset]) + finish(client, path, thread, original, captured) + assert conversation(client, path)['messages'][-1]['status'] == 'stopped' + assert conversation(client, path)['messages'][-2]['assets'][0]['id'] == asset + + release.set() + revised = client.post(path + '/turns', json={'id': str(uuid4()), 'runtime': 'default', + 'conversationId': active, 'text': 'NEW-标记', 'revisionOf': original, + 'assets': [asset]}) + assert error_of(revised) is None, error_of(revised) + new_turn = frames(revised)[0]['conversation']['messages'][-2] + assert [item['id'] for item in new_turn.get('assets') or []] == [asset] + # The reference still reaches the runtime context of the revised attempt. + assert asset in json.dumps(contexts[-1], ensure_ascii=False)