diff --git a/.gitignore b/.gitignore index 791b20f0a..3846e52d4 100644 --- a/.gitignore +++ b/.gitignore @@ -1,4 +1,4 @@ -node_modules/ +node_modules dist/ .DS_Store diff --git a/apps/api/src/opendirector_api/agent.py b/apps/api/src/opendirector_api/agent.py index 37fb0ca47..a8817a9aa 100644 --- a/apps/api/src/opendirector_api/agent.py +++ b/apps/api/src/opendirector_api/agent.py @@ -74,6 +74,81 @@ 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. + + Only the identity of the inherited calls is written here, because only that + cannot change. Job status, its asset and its error belong to the job record: + a copy taken at the moment the new turn is written goes stale as soon as the + job progresses, and an expanded view that reads it would report a state that + is no longer true. Readers that want the current state query the job by the + ids kept here; a missing or failed lookup must not be read as proof that + resubmitting a side-effectful call is safe. + """ + 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}) + return snapshot def draft_content_is_empty(content): @@ -163,7 +238,8 @@ 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, finish_turn_id: UUID | None = None, edited_documents: dict[str, int] | None = None, - before_begin=None, agent_session: str | None = None) -> dict: + before_begin=None, expected_revision: int | None = None, + agent_session: str | None = None) -> dict: finish_mono, finish_at = (_monotonic(), _utc_now()) if finish is not None else (None, None) mutating = draft is not None or begin is not None or finish is not None with self.projects.local.transaction() as db: @@ -190,6 +266,16 @@ def update(self, project_id: UUID, session: str | None = None, *, draft: Draft | for conversation in [value, *value.get('archivedConversations', [])] for message in conversation['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() if agent_session is not None: @@ -199,7 +285,8 @@ def update(self, project_id: UUID, session: str | None = None, *, draft: Draft | value['messages'].append({'id': reply_id, 'role': 'assistant', 'text': '', 'status': 'streaming', 'startedAt': _utc_now(), **{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: # Unlike job results, directly published files can later be deleted. @@ -278,6 +365,16 @@ def queue(self, project_id: UUID, session: str, message: dict, conversation_id: for conversation in [value, *value.get('archivedConversations', [])] for item in conversation['messages']): raise ProjectError('这条消息已接受,请读取对话,不要重复发送。', 409) + expected = message.pop('expectedRevision', None) + if expected is not None and expected != value.get('revision', 0): + raise ProjectError('对话已在别处更新,请刷新后重试。', 409) + revision_of = message.get('revisionOf') + if revision_of is not None: + blocked = revision_error(value['messages'], str(revision_of)) + if blocked: + raise ProjectError(blocked, 409) + message['inheritedJobs'] = inherited_jobs(value['messages'], str(revision_of), + self.projects.snapshot(project_id).jobs) if 'queueSeq' in value: value['_queueSeq'] = value.pop('queueSeq') value['_queueSeq'] = value.get('_queueSeq', 0) + 1 @@ -316,7 +413,8 @@ def dispatch(self, project_id: UUID, session: str | None = None, 'id': reply_id, 'role': 'assistant', 'text': '', 'status': 'streaming', 'startedAt': _utc_now(), **{key: pending[key] for key in ('model', 'runtime') if key in pending}}) - value.update(draft='', draftContent=None, assets=[], skills=[]) + value.update(draft='', draftContent=None, assets=[], skills=[], + revision=value.get('revision', 0) + 1) durable_json(file, value) # Same boundary as update(begin): the clock starts once the write succeeded, inside the transaction. with self._started_lock: @@ -728,6 +826,8 @@ async def prepare(project_id: UUID, value: Turn, session: str, accept_language: 'modelSelections': dict(value.modelSelections), 'model': model, 'modelIsCliDefault': model_is_cli_default, 'thinking': value.thinking, 'status': 'complete', + **({'revisionOf': str(value.revisionOf)} if value.revisionOf is not None else {}), + **({'expectedRevision': value.expectedRevision} if value.expectedRevision is not None else {}), **({'modelConfigId': str(value.modelId)} if value.modelId else {})}} async def plan_for(project_id: UUID, message: dict, session: str, directory: Path, accept_language: str | None) -> dict: @@ -786,12 +886,13 @@ async def renew_session() -> None: chain.conversation_id = UUID(saved['conversationId']) chain.events.put({'type': 'start', 'conversation': saved}) renewal = asyncio.create_task(renew_session()) - previous_sources = {source['id']: source for reply in saved['messages'][:-2] + active = active_messages(saved['messages']) + previous_sources = {source['id']: source for reply in active[:-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]: + for reply in active[:-1]: content = reply['text'] or '(empty reply)' bound = [TurnReference.model_validate(ref).observation() for ref in reply.get('turnReferences', [])] if bound: @@ -816,7 +917,7 @@ async def renew_session() -> None: model_selections=plan['model_selections'], runtime_model=message.get('runtimeModel'), skills=plan['available'], conversation_id=chain.conversation_id, edited_documents=edited_documents, turn_references=tuple(TurnReference.model_validate(ref) for ref in message.get('turnReferences', [])), - earlier_references=tuple(TurnReference.model_validate(ref) for reply in saved['messages'][:-2] + earlier_references=tuple(TurnReference.model_validate(ref) for reply in active[:-2] for ref in reply.get('turnReferences', []))) async with aclosing(runtimes.stream(run)) as stream: async for event in stream: diff --git a/scripts/ci/python_shards.json b/scripts/ci/python_shards.json index 56d52ff47..4c02ec3f2 100644 --- a/scripts/ci/python_shards.json +++ b/scripts/ci/python_shards.json @@ -19,6 +19,7 @@ "tests/test_assistant_conversation_trace.py", "tests/test_assistant_conversations.py", "tests/test_assistant_queue.py", + "tests/test_assistant_revision.py", "tests/test_cli.py", "tests/test_cli_discovery.py", "tests/test_deepseek_engine.py", diff --git a/src/backend/chat.ts b/src/backend/chat.ts index 0223ea3e1..58a4a9819 100644 --- a/src/backend/chat.ts +++ b/src/backend/chat.ts @@ -70,7 +70,15 @@ export interface ChatSource { url: string; title: string; } +export interface InheritedJob { + commandId: string; + callId: string; + name: string; + jobId: string | null; +} export interface ChatMessage { + revisionOf?: string; + inheritedJobs?: InheritedJob[]; publishedTimelines?: { projectId: string; eventCursor?: number; @@ -91,6 +99,7 @@ export interface ChatMessage { content?: ReferenceContent | null; status: "complete" | "streaming" | "stopped" | "interrupted"; assets?: ChatAsset[]; + skills?: string[]; model?: string | null; modelIsCliDefault?: boolean; runtimeModel?: string | null; @@ -135,6 +144,7 @@ export interface ChatDraft { } export interface Conversation extends ChatDraft { messages: ChatMessage[]; + revision?: number; } export function draftContentIsEmpty( @@ -177,6 +187,8 @@ export const streamedText = ( export interface ChatRequest { conversationId?: string; id: string; + revisionOf?: string; + expectedRevision?: number; modelId?: string; text: string; content?: ReferenceContent | null; diff --git a/src/canvas/AssistantPanel.tsx b/src/canvas/AssistantPanel.tsx index 58f6f6149..b9199e08f 100644 --- a/src/canvas/AssistantPanel.tsx +++ b/src/canvas/AssistantPanel.tsx @@ -1,6 +1,12 @@ import { useEffect, useLayoutEffect, useRef, useState } from "react"; import openDirectorLogo from "../assets/open_director_logo.png"; -import { runtimeModels, type AssistantModelSelection, type ChatAsset, type ModelSelections } from "../backend/chat"; +import { + runtimeModels, + type AssistantModelSelection, + type ChatAsset, + type ChatMessage, + type ModelSelections, +} from "../backend/chat"; import { assistantModelSelection } from "./agentPreferences"; import { creationClient } from "../backend/creationClient.ts"; import { fingerprint } from "../backend/generation.ts"; @@ -61,6 +67,10 @@ function kindOf(asset: ChatAsset) { : "text"; } +function submittedJobs(message: ChatMessage) { + return (message.inheritedJobs ?? []).filter((job) => job.jobId); +} + /** Shared conversation and composer for chat creation and the canvas assistant. */ export function AssistantPanel({ documentId, @@ -499,6 +509,12 @@ export function AssistantPanel({ )} {value.messages.map((message, index) => { const previous = value.messages[index - 1]; + const next = value.messages[index + 1]; + 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, @@ -604,6 +620,33 @@ export function AssistantPanel({ {t("assistant.panel.trace")} ↗ )} + {editable && ( + + )} + {!!submittedJobs(message).length && ( +
+ + {t("assistant.panel.inheritedJobs", { + count: submittedJobs(message).length, + })} + + +
+ )} {message.role === "user" && !!message.assets?.length && } {(message.status === "stopped" || message.status === "interrupted") && ( @@ -617,7 +660,15 @@ export function AssistantPanel({ ); })} -
+
+ {chat.editing && ( +
+ {t("assistant.panel.editingNotice")} + +
+ )} {readOnly && projectAssetsButton} {chat.error && (
diff --git a/src/canvas/assistant-panel.css b/src/canvas/assistant-panel.css index ccb538459..15dde5fc8 100644 --- a/src/canvas/assistant-panel.css +++ b/src/canvas/assistant-panel.css @@ -352,6 +352,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 100644 index 000000000..39e95497a --- /dev/null +++ b/src/canvas/chatTurnRequest.ts @@ -0,0 +1,59 @@ +import { assistantModelSelection } from "./agentPreferences.ts"; +import type { + AgentRuntime, + Conversation, + ModelSelections, + Thinking, +} from "../backend/chat.ts"; +import type { ReferenceContent } from "./chatReferenceContent"; + +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[]; + revisionOf?: string; + expectedRevision?: number; +} + +export function turnRequest( + input: Conversation, + { + id, + modelId, + editing, + revision, + }: { + id: string; + modelId?: string; + editing: ChatEditing | null; + revision?: number; + }, +): TurnRequest { + return { + id, + conversationId: input.conversationId, + ...assistantModelSelection(input, modelId), + text: input.draft, + content: input.draftContent, + assets: input.assets.map((asset) => asset.id), + 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 6886ff7a5..75e5a3f75 100644 --- a/src/canvas/useAssistantChat.ts +++ b/src/canvas/useAssistantChat.ts @@ -19,6 +19,7 @@ import { stopChat, type ChatAsset, type Conversation, + type ChatMessage, type ModelSelections, conversationIsEmpty, } from "../backend/chat"; @@ -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,27 @@ export const attachment = ({ size, fingerprint, }: ChatAsset): ChatAsset => ({ id, name, type, size, fingerprint }); +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 { + } +}; + const empty = (): Conversation => ({ messages: [], draft: "", @@ -94,6 +117,7 @@ export function useAssistantChat( const [threadsLoading, setThreadsLoading] = useState(false); const [threadsError, setThreadsError] = useState(""); const [changing, setChanging] = useState(false); + const [editing, setEditing] = useState(null); const switching = useRef(false); const [error, setError] = useState(""); const displayError = (text: string) => @@ -467,25 +491,78 @@ export function useAssistantChat( ) return; const input = current.current; - await follow(crypto.randomUUID(), async (id, signal, onEvent) => { + const revising = editing; + 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, - ...assistantModelSelection(input, agent?.id), - text: input.draft, - content: input.draftContent, - assets: input.assets.map((asset) => asset.id), - modelSelections: input.modelSelections, - skills: input.skills ?? [], - }, + turnRequest(input, { + id: turn, + modelId: agent?.id, + editing: revising, + revision: input.revision, + }), signal, onEvent, t, ); }); + if (revising && input.conversationId) + rememberPendingTurnId(input.conversationId); + if (revising) setEditing(null); + }; + 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, + 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(""); + }; + 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) => { @@ -535,6 +612,7 @@ export function useAssistantChat( draftContent: event.conversation.draftContent, assets: event.conversation.assets, skills: event.conversation.skills, + revision: event.conversation.revision, messages: event.conversation.messages.map((message) => message.status === "streaming" ? { @@ -711,6 +789,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 54947276f..268237317 100644 --- a/src/i18n/messages/en-US/assistant.ts +++ b/src/i18n/messages/en-US/assistant.ts @@ -58,6 +58,11 @@ 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.inheritedJobNotSubmitted": "not submitted", "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 4790b4645..10e165545 100644 --- a/src/i18n/messages/zh-CN/assistant.ts +++ b/src/i18n/messages/zh-CN/assistant.ts @@ -57,6 +57,11 @@ 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.inheritedJobNotSubmitted": "未提交", "assistant.panel.interrupted": "回复已中断", "assistant.panel.send": "发送消息", "assistant.panel.stop": "停止回复", diff --git a/tests/assistantRevision.test.ts b/tests/assistantRevision.test.ts new file mode 100644 index 000000000..3d7c06d75 --- /dev/null +++ b/tests/assistantRevision.test.ts @@ -0,0 +1,55 @@ +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); + 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/browser/assistant_revision.mjs b/tests/browser/assistant_revision.mjs new file mode 100644 index 000000000..dfb15c211 --- /dev/null +++ b/tests/browser/assistant_revision.mjs @@ -0,0 +1,160 @@ +import assert from "node:assert/strict"; +import { launchBrowser } from "./engine.mjs"; + +const base = process.env.CREATION_WEB_URL ?? "http://127.0.0.1:5179"; +const headers = { + "X-OpenDirector-Request": "1", + "X-OpenDirector-Session": crypto.randomUUID(), +}; +async function api(path, value) { + const response = await fetch(base + "/api" + path, { + headers: { ...headers, "Content-Type": "application/json" }, + ...(value ? { method: "POST", body: JSON.stringify(value) } : {}), + }); + assert.ok(response.ok, await response.clone().text()); + return response.json(); +} +async function until(read, matches, label) { + const deadline = Date.now() + 15000; + while (true) { + const value = await read(); + if (matches(value)) return value; + assert.ok(Date.now() < deadline, `${label}: ${JSON.stringify(value)}`); + await new Promise((resolve) => setTimeout(resolve, 100)); + } +} +const health = await api("/creation-test-health"); +assert.equal(health.isolated, true); +assert.equal(health.assistantFixture, true); +const projectId = crypto.randomUUID(); +await api(`/creation/projects/${projectId}/commands`, { + type: "project.create", + projectId, + commandId: crypto.randomUUID(), + payload: { name: `修订 ${crypto.randomUUID().slice(0, 8)}` }, +}); +const path = `/creation/projects/${projectId}/assistant`; + +const browser = await launchBrowser(); +try { + const page = await browser.newPage({ + locale: "zh-CN", + viewport: { width: 1440, height: 1000 }, + }); + page.setDefaultTimeout(15000); + const errors = []; + page.on("pageerror", (error) => errors.push(error.message)); + await page.route(/\/assistant\/runtimes(?:\?.*)?$/, (route) => + route.fulfill({ + json: [ + { + id: "default", + label: "Default", + group: "default", + modelSource: "settings", + available: true, + status: "ready", + modelOverride: false, + supportsSkills: true, + }, + ], + }), + ); + await page.addInitScript((id) => { + localStorage.setItem("opendirector.lastUnifiedFilesystemProject", id); + localStorage.setItem("opendirector.modelSetup.v1", "dismissed"); + localStorage.setItem("opendirector.locale.v1", "zh-CN"); + }, projectId); + await page.goto(base); + await page.getByText("已保存到本机", { exact: true }).waitFor({ state: "attached" }); + const panel = page.getByRole("complementary", { name: "AI 对话", exact: true }); + const editor = panel.getByRole("textbox", { name: "消息内容", exact: true }); + const editorText = async () => + (await editor.textContent()).replaceAll("\u200b", ""); + await page.locator('[data-testid="canvas-workspace"][aria-busy="false"]').waitFor(); + const openChat = page.getByRole("button", { + name: "与 AI 对话", + exact: true, + expanded: false, + }); + if (await openChat.isVisible()) await openChat.click(); + await editor.waitFor(); + await until( + () => api(path), + (value) => !!value.modelSelections.agent, + "Default model must be saved", + ); + + await api("/creation-test-assistant-gate", { open: false }); + await editor.fill("第一版:海边短片"); + await panel.getByRole("button", { name: "发送消息", exact: true }).click(); + await panel.getByText("已收到创作要求。", { exact: false }).waitFor(); + const streaming = await until( + () => api(path), + (value) => value.messages.at(-1)?.status === "streaming", + "Reply must stream", + ); + const original = streaming.messages[0].id; + + await panel.getByRole("button", { name: "停止回复", exact: true }).click(); + await until( + () => api(path), + (value) => + value.messages.at(-1)?.status === "stopped" && + value.activeTurnId === undefined, + "Stop must persist", + ); + await panel.getByText("已停止回复", { exact: true }).waitFor(); + const editButton = panel.getByRole("button", { name: "编辑并重发", exact: true }); + await editButton.waitFor(); + assert.equal(await panel.getByRole("button", { name: "编辑并重发", exact: true }).count(), 1); + + await editButton.click(); + await panel.getByText("正在编辑已停止的消息,发送后会作为新的尝试。", { exact: true }).waitFor(); + assert.equal(await editorText(), "第一版:海边短片"); + + await panel.getByRole("button", { name: "取消编辑", exact: true }).click(); + assert.equal(await editorText(), ""); + assert.equal(await panel.getByText("正在编辑已停止的消息,发送后会作为新的尝试。", { exact: true }).count(), 0); + + await editButton.click(); + await editor.fill("第二版:森林短片"); + await api("/creation-test-assistant-gate", { open: true }); + const submit = page.waitForRequest( + (request) => + request.method() === "POST" && + request.url().endsWith(`${path}/turns`), + ); + await panel.getByRole("button", { name: "发送消息", exact: true }).click(); + const body = (await submit).postDataJSON(); + assert.equal(body.revisionOf, original, "the edit names the stopped turn"); + assert.equal(typeof body.expectedRevision, "number", "the edit carries the conversation revision"); + assert.equal(body.text, "第二版:森林短片"); + + const revised = await until( + () => api(path), + (value) => + value.messages.length === 4 && + value.messages.at(-1)?.status === "complete", + "The revised attempt must finish", + ); + assert.deepEqual( + revised.messages.map((message) => message.text), + ["第一版:海边短片", "已收到创作要求。", "第二版:森林短片", "已收到创作要求。这是隔离测试回复。"], + "both attempts stay in history", + ); + assert.equal(revised.messages[2].revisionOf, original); + const contexts = (await api("/creation-test-health")).assistantContexts; + const seen = JSON.stringify(contexts.at(-1)); + assert.ok(seen.includes("第二版:森林短片"), "the revised text reaches the runtime"); + assert.ok(!seen.includes("第一版:海边短片"), "the replaced request leaves the active path"); + assert.equal( + await panel.getByRole("button", { name: "编辑并重发", exact: true }).count(), + 0, + "a completed reply cannot be revised", + ); + assert.deepEqual(errors, [], `page errors: ${errors.join("; ")}`); + console.log(JSON.stringify({ passed: true, checks: 12 })); +} finally { + await browser.close(); +} diff --git a/tests/browser/manifest.json b/tests/browser/manifest.json index 44e28ae4a..ca6220479 100644 --- a/tests/browser/manifest.json +++ b/tests/browser/manifest.json @@ -105,6 +105,16 @@ ], "note": "Needs --assistant-fixture services; holds the fixture gate." }, + { + "file": "assistant_revision.mjs", + "fixture": true, + "previewSafe": true, + "lanes": [ + "extendedFixture", + "production" + ], + "note": "Needs --assistant-fixture services; stops a reply, edits and resends it, and checks the request identity and the active path." + }, { "file": "prompt_optimizer_workspace.mjs", "previewSafe": true, diff --git a/tests/test_assistant_revision.py b/tests/test_assistant_revision.py new file mode 100644 index 000000000..68f83ac19 --- /dev/null +++ b/tests/test_assistant_revision.py @@ -0,0 +1,303 @@ +"""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 = [] + release = threading.Event() + + async def stream(self, run): + contexts.append(run.messages) + 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 + 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') + assert done['jobId'] == str(job.id) + assert done['commandId'] == str(agent.agent_command_id(UUID(turn), 'call-done')) + assert lost['jobId'] is None + assert lost['commandId'] == str(agent.agent_command_id(UUID(turn), 'call-lost')) + for item in snapshot: + assert set(item) == {'commandId', 'callId', 'name', 'jobId'}, item + + +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) + 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'] + 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] + assert asset in json.dumps(contexts[-1], ensure_ascii=False)