Shared task board where people and AI coding agents work as teammates. Source-available, self-hostable.
Go
MUL-7464: fix(agents): recover completed builder drafts and align recovery feedback (#8514)
YYClaw83422dc262e3
diff --git a/packages/core/agents/builder-protocol.test.ts b/packages/core/agents/builder-protocol.test.tsindex 0293c50824..a95c5c5005 100644--- a/packages/core/agents/builder-protocol.test.ts+++ b/packages/core/agents/builder-protocol.test.ts@@ -1,3 +1,5 @@+// @vitest-environment node+import { describe, expect, it } from "vitest";import {decodeBuilderInput,@@ -26,6 +28,19 @@ const draft = (): AgentDraft => ({});describe("agent builder protocol", () => {+ it.each([+ "[]",+ '[{"name":"Reviewer"}]',+ '[{"instructions":"First line\nSecond line"}]',+ ])("rejects array payloads: %j", (payload) => {+ expect(+ parseBuilderDraft(`<agent_draft>${payload}</agent_draft>`),+ ).toBeNull();+ expect(+ parseBuilderDraft(`<agent_draft>${payload}`, { completed: true }),+ ).toBeNull();+ });+it("parses and hides the structured draft block", () => {const content ='Here is a first draft.\n<agent_draft>{"name":"Researcher","permission_scope":"workspace"}</agent_draft>';@@ -293,3 +308,52 @@ Return findings."}</agent_draft>`;});});});++describe("completed builder reply recovery", () => {+ const reply = 'Here is your draft.\n<agent_draft>{"name":"Poet","instructions":"# Role\\nWrite poetry."}';++ it("recovers a complete JSON object only after the reply completes", () => {+ expect(parseBuilderDraft(reply)).toBeNull();+ expect(parseBuilderDraft(reply, { completed: false })).toBeNull();+ expect(parseBuilderDraft(reply, { completed: true })).toEqual({+ name: "Poet",+ instructions: "# Role\nWrite poetry.",+ });+ });++ it("recovers an unclosed completed draft with literal string control characters", () => {+ const content = '<agent_draft>{"name":"诗仙李白","instructions":"第一行\n\n## 交流方式\r\n- 以第一人称对话。\t保持诗意。","permission_scope":"private"}';+ expect(parseBuilderDraft(content)).toBeNull();+ expect(parseBuilderDraft(content, { completed: false })).toBeNull();+ expect(parseBuilderDraft(content, { completed: true })).toEqual({+ name: "诗仙李白",+ instructions: "第一行\n\n## 交流方式\r\n- 以第一人称对话。\t保持诗意。",+ permission_scope: "private",+ });+ });++ it.each([+ '<agent_draft>{"name":"Poet"',+ '<agent_draft>{"instructions":"line one\nline two"',+ '<agent_draft>{"instructions":"line one\nline two"} trailing prose',+ '<agent_draft>{"name":"Poet",}',+ '<agent_draft>{"name":"Poet"} trailing prose',+ '<agent_draft>{"name":"Poet"}<agent_draft>{"name":"Other"}',+ '<agent_draft>[]',+ '<agent_draft>',+ '<agent_draft></agent_draft>',+ '<agent_draft>{"name":"Poet"}</agent_draft',+ '<agent_draft>null',+ '<agent_draft>"Poet"',+ '{"name":"Poet"}',+ ])("rejects malformed or ambiguous completed drafts: %s", (content) => {+ expect(parseBuilderDraft(content, { completed: true })).toBeNull();+ });++ it("preserves closed-block parsing and literal-newline repair", () => {+ expect(parseBuilderDraft('<agent_draft>{"instructions":"line one\nline two"}</agent_draft>'))+ .toEqual({ instructions: "line one\nline two" });+ expect(parseBuilderDraft(`${reply}</agent_draft>`, { completed: true }))+ .toEqual(parseBuilderDraft(`${reply}</agent_draft>`));+ });+});diff --git a/packages/core/agents/builder-protocol.ts b/packages/core/agents/builder-protocol.tsindex d072db9da1..abfe887495 100644--- a/packages/core/agents/builder-protocol.ts+++ b/packages/core/agents/builder-protocol.ts@@ -34,14 +34,32 @@ export interface BuilderDraftPayload {member_ids?: unknown;}-export function parseBuilderDraft(content: string): BuilderDraftPayload | null {+function isBuilderDraftPayload(value: unknown): value is BuilderDraftPayload {+ return value !== null && typeof value === "object" && !Array.isArray(value);+}++export function parseBuilderDraft(+ content: string,+ { completed = false }: { completed?: boolean } = {},+): BuilderDraftPayload | null {const match = content.match(/<agent_draft>([\s\S]*?)<\/agent_draft>/);- if (!match?.[1]) return null;+ if (!match?.[1]) {+ // Completed CLI replies can omit the closing tag and include literal+ // string control characters. Apply the same repair as closed blocks,+ // but never recover a live stream or truncate trailing text.+ if (!completed || content.includes("</agent_draft>")) return null;+ const parts = content.split("<agent_draft>");+ if (parts.length !== 2 || !parts[1]) return null;+ try {+ const value = JSON.parse(escapeJsonStringControlCharacters(parts[1]));+ return isBuilderDraftPayload(value) ? value : null;+ } catch {+ return null;+ }+ }try {const value = JSON.parse(match[1]);- return value && typeof value === "object"- ? (value as BuilderDraftPayload)- : null;+ return isBuilderDraftPayload(value) ? value : null;} catch {// Some CLI-backed models emit literal newlines in the Markdown// instructions string even when asked for compact JSON. Repair only JSON@@ -49,9 +67,7 @@ export function parseBuilderDraft(content: string): BuilderDraftPayload | null {// other syntax still have to pass JSON.parse.try {const value = JSON.parse(escapeJsonStringControlCharacters(match[1]));- return value && typeof value === "object"- ? (value as BuilderDraftPayload)- : null;+ return isBuilderDraftPayload(value) ? value : null;} catch {return null;}diff --git a/packages/views/agents/create/builder-conversation.tsx b/packages/views/agents/create/builder-conversation.tsxindex 2ac44698f4..711e1d78a2 100644--- a/packages/views/agents/create/builder-conversation.tsx+++ b/packages/views/agents/create/builder-conversation.tsx@@ -18,6 +18,7 @@ import type {import { Button } from "@multica/ui/components/ui/button";import { cn } from "@multica/ui/lib/utils";import { ChatInput } from "../../chat/components/chat-input";+import { CHAT_COLUMN, CHAT_GUTTER } from "../../chat/components/chat-column";import {ChatMessageList,ChatMessageSkeleton,@@ -228,12 +229,17 @@ export function BuilderConversation({)}{error ? (- <div- role="alert"- aria-live="polite"- className="mx-5 mb-3 rounded-md bg-destructive/5 px-3 py-2 text-body text-destructive"- >- {error}+ <div className={cn("mb-3", CHAT_GUTTER)}>+ <div+ role="alert"+ aria-live="polite"+ className={cn(+ CHAT_COLUMN,+ "rounded-md bg-destructive/5 px-3 py-2 text-body text-destructive",+ )}+ >+ {error}+ </div></div>) : null}diff --git a/packages/views/agents/create/builder-workspace.test.tsx b/packages/views/agents/create/builder-workspace.test.tsxnew file mode 100644index 0000000000..3320b4335c--- /dev/null+++ b/packages/views/agents/create/builder-workspace.test.tsx@@ -0,0 +1,224 @@+// @vitest-environment jsdom++import { useState, type ReactNode } from "react";+import { cleanup, fireEvent, screen, waitFor } from "@testing-library/react";+import { QueryClient, QueryClientProvider } from "@tanstack/react-query";+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";+import { EMPTY_AGENT_DRAFT, toStoredAgentDraft, type AgentDraft } from "@multica/core/agents";+import type { AgentBuilderSessionSummary, ChatMessage } from "@multica/core/types";+import type { SupportedLocale } from "@multica/core/i18n";+import { renderWithI18n } from "../../test/i18n";+import { BuilderWorkspace } from "./builder-workspace";++const h = vi.hoisted(() => ({+ messages: [] as ChatMessage[],+ pending: false,+ loading: false,+ settled: true,+ error: null as string | null,+ session: undefined as AgentBuilderSessionSummary | undefined,+ save: vi.fn().mockResolvedValue(undefined),+}));+vi.mock("@multica/core/api", () => ({+ api: { saveAgentBuilderDraft: h.save },+}));+vi.mock("./use-builder-session", () => ({+ useBuilderSession: () => ({+ messages: h.messages,+ pending: h.pending,+ messagesLoading: h.loading,+ error: h.error,+ }),+}));+vi.mock("./use-create-agent-form", () => ({+ useCreateAgentForm: () => {+ const [draft, setDraft] = useState({ ...EMPTY_AGENT_DRAFT, runtimeId: "local" });+ return {+ draft, setDraft, selectedRuntime: null,+ workspaceSkills: [], members: [], runtimes: [], draftReady: true,+ };+ },+}));+vi.mock("./use-create-agent-submit", () => ({+ useCreateAgentSubmit: () => ({ creating: false }),+}));+vi.mock("./agent-configuration-panel", () => ({+ AgentConfigurationPanel: ({ draft, onChange }: {+ draft: AgentDraft; onChange: (draft: AgentDraft) => void;+ }) => (+ <input aria-label="Agent name" value={draft.name}+ onChange={(event) => onChange({ ...draft, name: event.target.value })} />+ ),+}));+vi.mock("./builder-conversation", () => ({+ BuilderConversation: ({ error }: { error: string | null }) =>+ error ? <div role="alert">{error}</div> : null,+}));+vi.mock("./create-agent-footer", () => ({ CreateAgentFooter: () => null }));+vi.mock("react-resizable-panels", () => ({ useDefaultLayout: () => ({}) }));+vi.mock("@multica/ui/components/ui/resizable", () => ({+ ResizablePanelGroup: ({ children }: { children: ReactNode }) => <>{children}</>,+ ResizablePanel: ({ children }: { children: ReactNode }) => <>{children}</>,+ ResizableHandle: () => null,+}));++const guidance = "This reply could not fill the form. Ask the assistant to generate the draft again, or fill it in manually.";+const unclosed = '<agent_draft>{"name":"Poet","instructions":"# Role\nWrite poetry."}';+function reply(content: string, id = "reply-1"): ChatMessage {+ return {+ id, content, role: "assistant", chat_session_id: "session-1",+ task_id: "task-1", created_at: "2026-09-17T05:00:00Z",+ };+}+function workspace() {+ return <BuilderWorkspace sessionId="session-1" squadId={null}+ session={h.session} sessionSettled={h.settled} fallbackRuntimeId="local"+ onDiscarded={vi.fn()} onRuntimeLabel={vi.fn()} />;+}+function mount(locale: SupportedLocale = "en") {+ const qc = new QueryClient({ defaultOptions: { queries: { retry: false } } });+ const view = renderWithI18n(+ <QueryClientProvider client={qc}>{workspace()}</QueryClientProvider>,+ { locale },+ );+ return {+ ...view,+ refresh: () => view.rerender(+ <QueryClientProvider client={qc}>{workspace()}</QueryClientProvider>,+ ),+ };+}++describe("builder draft recovery wiring", () => {+ beforeEach(() => {+ h.messages = [];+ h.pending = false;+ h.loading = false;+ h.settled = true;+ h.error = null;+ h.session = undefined;+ h.save.mockClear();+ });+ afterEach(cleanup);++ it.each([unclosed, `${unclosed}</agent_draft>`])("waits for completion, fills once, and persists subsequent manual edits: %s", async (content) => {+ h.messages = [+ reply('<agent_draft>{"name":"Older draft"}</agent_draft>', "older"),+ reply(content),+ ];+ h.pending = true;+ const view = mount();+ expect(screen.getByLabelText("Agent name")).toHaveValue("");+ expect(screen.queryByRole("alert")).toBeNull();++ h.pending = false;+ view.refresh();+ await waitFor(() => expect(screen.getByLabelText("Agent name")).toHaveValue("Poet"));+ fireEvent.change(screen.getByLabelText("Agent name"), { target: { value: "Edited poet" } });+ h.messages = [...h.messages];+ view.refresh();+ expect(screen.getByLabelText("Agent name")).toHaveValue("Edited poet");+ expect(screen.queryByRole("alert")).toBeNull();+ h.pending = true;+ view.refresh();+ expect(screen.getByLabelText("Agent name")).toHaveValue("Edited poet");+ h.pending = false;+ view.refresh();+ expect(screen.getByLabelText("Agent name")).toHaveValue("Edited poet");+ view.unmount();+ expect(h.save).toHaveBeenLastCalledWith("session-1", expect.objectContaining({+ name: "Edited poet", applied_message_id: "reply-1",+ }));+ });++ it("shows recovery guidance for an invalid final reply and clears it on a valid retry", async () => {+ h.messages = [reply('<agent_draft>{"name":"Unfinished')];+ h.pending = true;+ const view = mount();+ expect(screen.queryByRole("alert")).toBeNull();+ h.pending = false;+ view.refresh();+ expect(screen.getByRole("alert")).toHaveTextContent(guidance);+ expect(screen.getByLabelText("Agent name")).toHaveValue("");++ h.messages = [...h.messages, reply(unclosed, "reply-2")];+ view.refresh();+ await waitFor(() => expect(screen.getByLabelText("Agent name")).toHaveValue("Poet"));+ expect(screen.queryByRole("alert")).toBeNull();+ });++ it.each([unclosed, `${unclosed}</agent_draft>`])("does not recover a failed turn or replace its existing failure presentation: %s", (content) => {+ h.messages = [{ ...reply(content), failure_reason: "agent_error" }];+ mount();+ expect(screen.getByLabelText("Agent name")).toHaveValue("");+ expect(screen.queryByRole("alert")).toBeNull();+ });++ it("preserves saved manual edits when reopening a recovered reply", async () => {+ h.messages = [reply(unclosed)];+ h.session = {+ session_id: "session-1", title: "Poet", runtime_id: "local",+ created_at: "", updated_at: "", last_message_at: "",+ last_message_content: unclosed, last_message_role: "assistant",+ draft: toStoredAgentDraft({ ...EMPTY_AGENT_DRAFT, name: "Saved edit" }, "reply-1"),+ };+ mount();+ await waitFor(() => expect(screen.getByLabelText("Agent name")).toHaveValue("Saved edit"));+ expect(screen.queryByRole("alert")).toBeNull();+ expect(h.save).not.toHaveBeenCalled();+ });++ it("waits for history and stored configuration before recovering a draft", async () => {+ h.messages = [reply(unclosed)];+ h.loading = true;+ h.settled = false;+ const view = mount();+ expect(screen.getByLabelText("Agent name")).toHaveValue("");+ h.loading = false;+ view.refresh();+ expect(screen.getByLabelText("Agent name")).toHaveValue("");+ h.settled = true;+ view.refresh();+ await waitFor(() => expect(screen.getByLabelText("Agent name")).toHaveValue("Poet"));+ });++ it("keeps transport errors visible ahead of draft guidance", () => {+ h.messages = [reply('<agent_draft>{"name":"Unfinished')];+ h.error = "Connection lost";+ mount();+ expect(screen.getByRole("alert")).toHaveTextContent("Connection lost");+ expect(screen.getByRole("alert")).not.toHaveTextContent(guidance);+ });++ it.each(["Stopped.", "No draft"])("does not warn for a reply without a draft block, including after reopening: %s", (content) => {+ h.messages = [reply(content)];+ const view = mount();+ expect(screen.queryByRole("alert")).toBeNull();+ view.unmount();+ mount();+ expect(screen.queryByRole("alert")).toBeNull();+ });++ it("does not warn for empty history, user messages, or no-response replies", () => {+ const view = mount();+ expect(screen.queryByRole("alert")).toBeNull();+ h.messages = [{ ...reply("Create a poet"), role: "user" }];+ view.refresh();+ expect(screen.queryByRole("alert")).toBeNull();+ h.messages = [{ ...reply(""), message_kind: "no_response" }];+ view.refresh();+ expect(screen.queryByRole("alert")).toBeNull();+ });++ it.each([+ ["en", "This reply could not fill the form."],+ ["zh-Hans", "本次回复未能填入表单。"],+ ["ja", "この返信からフォームを入力できませんでした。"],+ ["ko", "이 응답으로 양식을 채울 수 없습니다."],+ ["fr", "Cette réponse n’a pas permis de remplir le formulaire."],+ ] as const)("renders draft recovery guidance in %s", (locale, message) => {+ h.messages = [reply('<agent_draft>{"name":"Unfinished')];+ mount(locale);+ expect(screen.getByRole("alert")).toHaveTextContent(message);+ });+});diff --git a/packages/views/agents/create/builder-workspace.tsx b/packages/views/agents/create/builder-workspace.tsxindex 122d82e204..5d67d691e0 100644--- a/packages/views/agents/create/builder-workspace.tsx+++ b/packages/views/agents/create/builder-workspace.tsx@@ -181,11 +181,24 @@ export function BuilderWorkspace({// Realtime chat updates can mutate the cached messages array in place. Use// the latest structured message's scalar identity/content as effect inputs// so a draft is still applied when the array reference itself is unchanged.+ // These are durable replies from chat:done/history, not streaming chunks.+ // Wait until the active turn settles before recovering an unclosed block.+ const completed = !builder.pending && !builder.messagesLoading;+ const latestMessage = builder.messages.at(-1);+ const draftReplyInvalid =+ completed &&+ latestMessage?.role === "assistant" &&+ !latestMessage.failure_reason &&+ latestMessage.message_kind !== "no_response" &&+ latestMessage.content.includes("<agent_draft>") &&+ !parseBuilderDraft(latestMessage.content, { completed });const latestDraftMessage = [...builder.messages].reverse().find((message) =>- message.role === "assistant" && parseBuilderDraft(message.content),+ message.role === "assistant" &&+ !message.failure_reason &&+ parseBuilderDraft(message.content, { completed }),);const latestDraftMessageId = latestDraftMessage?.id;const latestDraftMessageContent = latestDraftMessage?.content;@@ -198,7 +211,7 @@ export function BuilderWorkspace({// Gated on the restore: merging a reply into the form before the stored// configuration lands would be overwritten a tick later, and the merge// would have been computed against an empty draft.- if (!restored) return;+ if (!restored || !completed) return;if (!latestDraftMessageId ||!latestDraftMessageContent ||@@ -206,7 +219,7 @@ export function BuilderWorkspace({) {return;}- const payload = parseBuilderDraft(latestDraftMessageContent);+ const payload = parseBuilderDraft(latestDraftMessageContent, { completed });if (!payload) return;markApplied(latestDraftMessageId);setDraft((current) =>@@ -221,6 +234,7 @@ export function BuilderWorkspace({}, [latestDraftMessageContent,latestDraftMessageId,+ completed,markApplied,memberIdSet,restored,@@ -312,7 +326,12 @@ export function BuilderWorkspace({onStop={() => void builder.stop()}restoreDraftRequest={builder.restoreDraftRequest}onRestoreDraftApplied={builder.handleRestoreDraftApplied}- error={builder.error}+ error={+ builder.error ||+ (draftReplyInvalid+ ? t(($) => $.creation_studio.builder.draft_parse_failed)+ : null)+ }/></ResizablePanel><ResizableHandle />diff --git a/packages/views/locales/en/agents.json b/packages/views/locales/en/agents.jsonindex b70531df0f..8f32330bb4 100644--- a/packages/views/locales/en/agents.json+++ b/packages/views/locales/en/agents.json@@ -339,6 +339,7 @@"setup_description": "This runtime powers setup and is the default for the new agent.","start": "Start conversation","connect_runtime": "Connect a runtime",+ "draft_parse_failed": "This reply could not fill the form. Ask the assistant to generate the draft again, or fill it in manually.","start_failed": "Could not start Agent Builder.","send_failed": "Could not send your message.","stop_failed": "Could not stop the current generation.",diff --git a/packages/views/locales/fr/agents.json b/packages/views/locales/fr/agents.jsonindex 56a4acf89c..77339e6ece 100644--- a/packages/views/locales/fr/agents.json+++ b/packages/views/locales/fr/agents.json@@ -339,6 +339,7 @@"setup_description": "Ce runtime sert à la configuration et sera celui du nouvel agent par défaut.","start": "Démarrer la conversation","connect_runtime": "Connecter un runtime",+ "draft_parse_failed": "Cette réponse n’a pas permis de remplir le formulaire. Demandez à l’agent de générer à nouveau le brouillon ou remplissez le formulaire manuellement.","start_failed": "Impossible de démarrer l'Agent Builder.","send_failed": "Impossible d'envoyer votre message.","stop_failed": "Impossible d'arrêter la génération en cours.",diff --git a/packages/views/locales/ja/agents.json b/packages/views/locales/ja/agents.jsonindex 94536f9ee8..3a65141709 100644--- a/packages/views/locales/ja/agents.json+++ b/packages/views/locales/ja/agents.json@@ -920,6 +920,7 @@"setup_description": "このランタイムは作成時の対話と、新しいエージェントの既定値に使われます。","start": "会話を開始","connect_runtime": "ランタイムを接続",+ "draft_parse_failed": "この返信からフォームを入力できませんでした。エージェントに下書きの再生成を依頼するか、手動で入力してください。","start_failed": "Agent Builder を開始できませんでした。","send_failed": "メッセージを送信できませんでした。","stop_failed": "現在の生成を停止できませんでした。",diff --git a/packages/views/locales/ko/agents.json b/packages/views/locales/ko/agents.jsonindex e80ea7760f..e772236a03 100644--- a/packages/views/locales/ko/agents.json+++ b/packages/views/locales/ko/agents.json@@ -920,6 +920,7 @@"setup_description": "이 런타임은 생성 대화에 사용되며 새 에이전트의 기본값이 됩니다.","start": "대화 시작","connect_runtime": "런타임 연결",+ "draft_parse_failed": "이 응답으로 양식을 채울 수 없습니다. 에이전트에게 초안을 다시 생성하도록 요청하거나 직접 입력하세요.","start_failed": "Agent Builder를 시작하지 못했습니다.","send_failed": "메시지를 보내지 못했습니다.","stop_failed": "현재 생성을 중지하지 못했습니다.",diff --git a/packages/views/locales/zh-Hans/agents.json b/packages/views/locales/zh-Hans/agents.jsonindex 54de8b7f27..3864b4cad0 100644--- a/packages/views/locales/zh-Hans/agents.json+++ b/packages/views/locales/zh-Hans/agents.json@@ -329,6 +329,7 @@"setup_description": "该运行时用于创建对话,并默认用于新智能体。","start": "开始对话","connect_runtime": "连接运行时",+ "draft_parse_failed": "本次回复未能填入表单。请让智能体重新生成草稿,或手动填写。","start_failed": "无法启动智能体构建器。","send_failed": "无法发送消息。","stop_failed": "无法停止当前生成任务。",