Automate browser based workflows with AI
Python aiapiautomationbrowserbrowser-automationcomputergptllmplaywrightpowerautomatepuppeteerpythonrpaseleniumvisionworkflow
SKY-10643: fix cancelled Copilot draft terminal state (#6387)
Andrew Neilsonfb92fd6b1eae
diff --git a/skyvern-frontend/src/routes/workflows/copilot/NarrativeView.test.ts b/skyvern-frontend/src/routes/workflows/copilot/NarrativeView.test.tsindex 5a5b59330..1ef76be4e 100644--- a/skyvern-frontend/src/routes/workflows/copilot/NarrativeView.test.ts+++ b/skyvern-frontend/src/routes/workflows/copilot/NarrativeView.test.ts@@ -444,6 +444,31 @@ describe("applyNarrativeEvent — terminal", () => {expect(effectiveMode(s)).toBe("clarify");});+ it("preserves cancelled responses with drafts as response terminals", () => {+ let s = applyNarrativeEvent(EMPTY_NARRATIVE, turnStart());+ s = applyNarrativeEvent(+ s,+ workflowDraft({+ block_count: 2,+ block_labels: ["open_page", "add_to_cart"],+ }),+ );+ s = applyNarrativeEvent(+ s,+ response({+ cancelled: true,+ message:+ "Cancelled. I have a draft workflow you can keep -- accept it to save, or discard.",+ proposal_disposition: "review_untested",+ }),+ );++ expect(s.terminal).toBe("response");+ expect(s.draft?.blockCount).toBe(2);+ expect(s.blocks.map((b) => b.state)).toEqual(["drafted", "drafted"]);+ expect(effectiveMode(s)).toBe("build");+ });+it("response closes design even when design_end was never emitted (CORR-3)", () => {let s = applyNarrativeEvent(EMPTY_NARRATIVE, designStart());expect(s.designEnded).toBe(false);diff --git a/skyvern-frontend/src/routes/workflows/copilot/NarrativeView.tsx b/skyvern-frontend/src/routes/workflows/copilot/NarrativeView.tsxindex 7c51db1d7..4f0c72f63 100644--- a/skyvern-frontend/src/routes/workflows/copilot/NarrativeView.tsx+++ b/skyvern-frontend/src/routes/workflows/copilot/NarrativeView.tsx@@ -422,6 +422,7 @@ interface TurnSummary {glyph: string;isFail: boolean;isQA: boolean;+ isStoppedWithDraft: boolean;}function asksUserForInput(turn: TurnNarrativeState): boolean {@@ -452,22 +453,30 @@ function computeTurnSummary(turn: TurnNarrativeState): TurnSummary {mode === "refuse";const hasDrafts = (turn.draft?.blockCount ?? 0) > 0;const hasEdited = (turn.priorBlockCount ?? 0) > 0 && hasDrafts;-- const headline = isFail- ? "Run halted"- : needsInput- ? "Question"- : isQA- ? mode === "refuse"- ? "Declined"- : mode === "clarify"- ? "Question"- : "Answered"- : hasEdited- ? "Applied edits and re-tested"- : hasDrafts- ? "Built and tested the workflow"- : "Completed the run";+ const hasReviewableDraft =+ hasDrafts &&+ (turn.proposalDisposition === "review_untested" ||+ turn.proposalDisposition === "review_tested" ||+ (turn.cancelled && turn.proposalDisposition !== "no_proposal"));+ const isStoppedWithDraft = hasReviewableDraft && (isFail || turn.cancelled);++ const headline = isStoppedWithDraft+ ? "Stopped with a draft"+ : isFail+ ? "Run halted"+ : needsInput+ ? "Question"+ : isQA+ ? mode === "refuse"+ ? "Declined"+ : mode === "clarify"+ ? "Question"+ : "Answered"+ : hasEdited+ ? "Applied edits and re-tested"+ : hasDrafts+ ? "Built and tested the workflow"+ : "Completed the run";const stats: string[] = [];const turnElapsed = formatElapsed(turn.startedAt, turn.endedAt);@@ -481,13 +490,21 @@ function computeTurnSummary(turn: TurnNarrativeState): TurnSummary {if (failed) stats.push(`${failed} failed`);}+ const accent = isStoppedWithDraft+ ? "qa"+ : isFail+ ? "fail"+ : isQA+ ? "qa"+ : "ok";return {headline,stats,- accent: isFail ? "fail" : isQA ? "qa" : "ok",- glyph: isFail ? "✕" : isQA ? "✦" : "✓",+ accent,+ glyph: isStoppedWithDraft ? "!" : isFail ? "✕" : isQA ? "✦" : "✓",isFail,isQA,+ isStoppedWithDraft,};}@@ -572,7 +589,9 @@ function RollupCard({ turn, summary, onExpand }: RollupCardProps) {closing ? (<divclassName={`mt-0.5 text-[12.5px] leading-[1.5] ${- summary.isFail ? "text-rose-200/90" : "text-slate-400"+ summary.isFail && !summary.isStoppedWithDraft+ ? "text-rose-200/90"+ : "text-slate-400"}`}>{closing}diff --git a/skyvern-frontend/src/routes/workflows/copilot/WorkflowCopilotChat.queue.test.tsx b/skyvern-frontend/src/routes/workflows/copilot/WorkflowCopilotChat.queue.test.tsxindex d9cd4bcce..c87225c82 100644--- a/skyvern-frontend/src/routes/workflows/copilot/WorkflowCopilotChat.queue.test.tsx+++ b/skyvern-frontend/src/routes/workflows/copilot/WorkflowCopilotChat.queue.test.tsx@@ -18,21 +18,41 @@ type StreamCall = {resolve: () => void;reject: (error: unknown) => void;};-const { streamCalls, postStreaming, cancelPost } = vi.hoisted(() => {- const calls: StreamCall[] = [];- const post = vi.fn().mockResolvedValue({});- const streaming = vi.fn(- (- _path: string,- body: { message: string },- onMessage: (payload: unknown) => boolean,- ) =>- new Promise<void>((resolve, reject) => {- calls.push({ body, onMessage, resolve, reject });- }),- );- return { streamCalls: calls, postStreaming: streaming, cancelPost: post };-});+const { streamCalls, postStreaming, cancelPost, historyResponse } = vi.hoisted(+ () => {+ const calls: StreamCall[] = [];+ const post = vi.fn().mockResolvedValue({});+ const streaming = vi.fn(+ (+ _path: string,+ body: { message: string },+ onMessage: (payload: unknown) => boolean,+ ) =>+ new Promise<void>((resolve, reject) => {+ calls.push({ body, onMessage, resolve, reject });+ }),+ );+ const history = {+ data: {+ workflow_copilot_chat_id: null as string | null,+ chat_history: [] as {+ sender: "user" | "ai";+ content: string;+ created_at: string;+ narrative_payload?: Record<string, unknown> | null;+ }[],+ proposed_workflow: null as Record<string, unknown> | null,+ auto_accept: false,+ },+ };+ return {+ streamCalls: calls,+ postStreaming: streaming,+ cancelPost: post,+ historyResponse: history,+ };+ },+);vi.mock("@/api/sse", () => ({getSseClient: vi.fn().mockResolvedValue({ postStreaming }),@@ -40,14 +60,7 @@ vi.mock("@/api/sse", () => ({vi.mock("@/api/AxiosClient", () => ({getClient: vi.fn().mockResolvedValue({- get: vi.fn().mockResolvedValue({- data: {- workflow_copilot_chat_id: null,- chat_history: [],- proposed_workflow: null,- auto_accept: false,- },- }),+ get: vi.fn().mockImplementation(() => Promise.resolve(historyResponse)),post: cancelPost,}),}));@@ -124,6 +137,15 @@ const turnStart = () => ({timestamp: "2026-05-25T00:00:00Z",});+const workflowDraft = () => ({+ type: "workflow_draft" as const,+ block_count: 2,+ block_labels: ["open_page", "add_to_cart"],+ summary: "two block workflow",+ timestamp: "2026-05-25T00:00:03Z",+ workflow: { workflow_id: "wf_draft" },+});+async function renderChat() {const view = render(<WorkflowCopilotChat />);// Let the mount-time chat-history fetch settle.@@ -161,6 +183,12 @@ beforeEach(() => {streamCalls.length = 0;postStreaming.mockClear();cancelPost.mockClear();+ historyResponse.data = {+ workflow_copilot_chat_id: null,+ chat_history: [],+ proposed_workflow: null,+ auto_accept: false,+ };});afterEach(() => {@@ -285,6 +313,160 @@ describe("WorkflowCopilotChat — keep the chat live during a turn", () => {expect(screen.queryByText("Completed the run")).toBeNull();});+ it("keeps proposal actions after user-cancelled turns with staged drafts", async () => {+ await renderChat();+ await submit("build me a workflow");+ await waitFor(() => expect(postStreaming).toHaveBeenCalledTimes(1));++ const call = streamCalls[0];+ if (!call) throw new Error("no pending stream to complete");++ await act(async () => {+ call.onMessage(turnStart());+ call.onMessage(workflowDraft());+ call.onMessage({+ ...terminalResponse(+ "Cancelled. I have a draft workflow you can keep -- accept it to save, or discard.",+ ),+ updated_workflow: { workflow_id: "wf_draft" },+ proposal_disposition: "review_untested",+ cancelled: true,+ });+ call.resolve();+ });++ expect(screen.getByText("Stopped with a draft")).toBeTruthy();+ expect(screen.queryByText("Run halted")).toBeNull();+ expect(screen.getByRole("button", { name: "Review" })).toBeTruthy();+ expect(screen.getByRole("button", { name: "Accept" })).toBeTruthy();+ expect(screen.getByRole("button", { name: "Reject" })).toBeTruthy();+ });++ it("shows budget-halted draft turns as reviewable draft state", async () => {+ await renderChat();+ await submit("build me a workflow");+ await waitFor(() => expect(postStreaming).toHaveBeenCalledTimes(1));++ const call = streamCalls[0];+ if (!call) throw new Error("no pending stream to complete");++ await act(async () => {+ call.onMessage(turnStart());+ call.onMessage(workflowDraft());+ call.onMessage({+ type: "block_progress",+ workflow_run_block_id: "wrb_add_to_cart",+ block_label: "add_to_cart",+ block_type: "task",+ status: "canceled",+ iteration: 1,+ timestamp: "2026-05-25T00:00:04Z",+ });+ call.onMessage({+ ...terminalResponse(+ "The draft made progress but the test exceeded its tool budget. Review the draft before accepting it.",+ ),+ updated_workflow: { workflow_id: "wf_draft" },+ proposal_disposition: "review_untested",+ });+ call.resolve();+ });++ expect(screen.getByText("Stopped with a draft")).toBeTruthy();+ expect(screen.queryByText("Run halted")).toBeNull();+ expect(screen.getByRole("button", { name: "Review" })).toBeTruthy();+ expect(screen.getByRole("button", { name: "Accept" })).toBeTruthy();+ expect(screen.getByRole("button", { name: "Reject" })).toBeTruthy();+ });++ it("does not show proposal actions after cancelled turns without a draft", async () => {+ await renderChat();+ await submit("build me a workflow");+ await waitFor(() => expect(postStreaming).toHaveBeenCalledTimes(1));++ const call = streamCalls[0];+ if (!call) throw new Error("no pending stream to complete");++ await act(async () => {+ call.onMessage(turnStart());+ call.onMessage({+ ...terminalResponse("Cancelled by user."),+ proposal_disposition: "no_proposal",+ cancelled: true,+ });+ call.resolve();+ });++ expect(screen.queryByRole("button", { name: "Review" })).toBeNull();+ expect(screen.queryByRole("button", { name: "Accept" })).toBeNull();+ expect(screen.queryByRole("button", { name: "Reject" })).toBeNull();+ });++ it("hydrates cancelled pending draft controls from chat history", async () => {+ historyResponse.data = {+ workflow_copilot_chat_id: "chat-1",+ chat_history: [+ {+ sender: "user",+ content: "build me a workflow",+ created_at: "2026-05-25T00:00:00Z",+ },+ {+ sender: "ai",+ content:+ "Cancelled. I have a draft workflow you can keep -- accept it to save, or discard.",+ created_at: "2026-05-25T00:00:05Z",+ narrative_payload: {+ turnId: "turn-1",+ turnIndex: 0,+ mode: "build",+ responseType: "REPLY",+ cancelled: true,+ proposalDisposition: "review_untested",+ designStarted: true,+ designEnded: true,+ draft: {+ blockCount: 2,+ blockLabels: ["open_page", "add_to_cart"],+ summary: null,+ },+ blocks: [+ {+ workflowRunBlockId: "",+ label: "open_page",+ blockType: "goto_url",+ state: "drafted",+ lastSeenIteration: 0,+ activity: [],+ startedAt: null,+ endedAt: null,+ },+ ],+ terminal: "response",+ terminalMessage:+ "Cancelled. I have a draft workflow you can keep -- accept it to save, or discard.",+ narrativeSummary:+ "Cancelled. I have a draft workflow you can keep -- accept it to save, or discard.",+ priorBlockCount: null,+ designActivity: [],+ startedAt: "2026-05-25T00:00:00Z",+ endedAt: "2026-05-25T00:00:05Z",+ },+ },+ ],+ proposed_workflow: { workflow_id: "wf_draft" },+ auto_accept: false,+ };++ await renderChat();++ expect(screen.getByText("Stopped with a draft")).toBeTruthy();+ expect(screen.queryByText("Run halted")).toBeNull();+ expect(screen.getByRole("button", { name: "Review" })).toBeTruthy();+ expect(screen.getByRole("button", { name: "Accept" })).toBeTruthy();+ expect(screen.getByRole("button", { name: "Reject" })).toBeTruthy();+ });+it("renders an ASK_QUESTION response payload as a question", async () => {await renderChat();await submit("build a lookup workflow");diff --git a/skyvern-frontend/src/routes/workflows/copilot/WorkflowCopilotChat.tsx b/skyvern-frontend/src/routes/workflows/copilot/WorkflowCopilotChat.tsxindex ac5ff63fc..e89cadfd2 100644--- a/skyvern-frontend/src/routes/workflows/copilot/WorkflowCopilotChat.tsx+++ b/skyvern-frontend/src/routes/workflows/copilot/WorkflowCopilotChat.tsx@@ -47,6 +47,7 @@ import { shouldAutoApplyWorkflowResponse } from "./proposalDisposition";import { NarrativeView } from "./NarrativeView";import {EMPTY_NARRATIVE,+ NarrativeEvent,TurnNarrativeState,applyNarrativeEvent,hydrateNarrativeFromPayload,@@ -306,6 +307,15 @@ export function WorkflowCopilotChat({useEffect(() => {narrativeRef.current = narrative;}, [narrative]);+ const applyStoredNarrativeEvent = useCallback(+ (event: NarrativeEvent, base?: TurnNarrativeState) => {+ const next = applyNarrativeEvent(base ?? narrativeRef.current, event);+ narrativeRef.current = next;+ setNarrative(next);+ return next;+ },+ [],+ );const [isLoadingHistory, setIsLoadingHistory] = useState(false);const streamingAbortController = useRef<AbortController | null>(null);// Synchronous in-flight gate. State (isLoading) lags a render behind, so a@@ -1001,6 +1011,7 @@ export function WorkflowCopilotChat({const handleResponse = (response: WorkflowCopilotStreamResponseUpdate,+ responseNarrative?: TurnNarrativeState,) => {// Stream completed; a Cancel click after this point should no-op.pendingCancelToken.current = null;@@ -1011,19 +1022,20 @@ export function WorkflowCopilotChat({// Read via narrativeRef because this callback was closed over at// handleSend time (pre-turn_start), so the React state binding is// stale here.- const liveNarrative = narrativeRef.current;+ const liveNarrative = responseNarrative ?? narrativeRef.current;const hasNarrativePayload =response.narrative_payload !== null &&typeof response.narrative_payload === "object";const frozenNarrative: TurnNarrativeState | undefined =- liveNarrative.turnId !== null || hasNarrativePayload+ responseNarrative ??+ (liveNarrative.turnId !== null || hasNarrativePayload? applyNarrativeEvent(liveNarrative.turnId !== null? liveNarrative: EMPTY_NARRATIVE,response,)- : undefined;+ : undefined);const aiMessage: ChatMessage = {id: Date.now().toString(),@@ -1050,6 +1062,8 @@ export function WorkflowCopilotChat({)) {applyWorkflowUpdate(response.updated_workflow);+ } else if (response.updated_workflow) {+ setProposedWorkflow(response.updated_workflow);} else if (// Cancel/error terminal on a turn that produced staged content →// snap canvas back to the pre-submit client snapshot.@@ -1067,13 +1081,17 @@ export function WorkflowCopilotChat({}};- const handleError = (payload: WorkflowCopilotStreamErrorUpdate) => {+ const handleError = (+ payload: WorkflowCopilotStreamErrorUpdate,+ errorNarrative?: TurnNarrativeState,+ ) => {pendingCancelToken.current = null;- const liveNarrative = narrativeRef.current;+ const liveNarrative = errorNarrative ?? narrativeRef.current;const frozenNarrative: TurnNarrativeState | undefined =- liveNarrative.turnId !== null+ errorNarrative ??+ (liveNarrative.turnId !== null? applyNarrativeEvent(liveNarrative, payload)- : undefined;+ : undefined);const errorMessage: ChatMessage = {id: Date.now().toString(),sender: "ai",@@ -1117,7 +1135,7 @@ export function WorkflowCopilotChat({case "tool_result":case "narration":case "block_progress":- setNarrative((prev) => applyNarrativeEvent(prev, payload));+ applyStoredNarrativeEvent(payload);return false;case "turn_start": {// Move the pre-submit canvas snapshot into the per-turn@@ -1135,14 +1153,12 @@ export function WorkflowCopilotChat({map.delete(oldest);}latestTurnId.current = payload.turn_id;- setNarrative(() =>- applyNarrativeEvent(EMPTY_NARRATIVE, payload),- );+ applyStoredNarrativeEvent(payload, EMPTY_NARRATIVE);return false;}case "design_start":case "design_end":- setNarrative((prev) => applyNarrativeEvent(prev, payload));+ applyStoredNarrativeEvent(payload);return false;case "workflow_draft": {// Render the staged workflow on the canvas mid-turn. Only@@ -1159,17 +1175,19 @@ export function WorkflowCopilotChat({}}}- setNarrative((prev) => applyNarrativeEvent(prev, payload));+ applyStoredNarrativeEvent(payload);return false;}- case "response":- setNarrative((prev) => applyNarrativeEvent(prev, payload));- handleResponse(payload);+ case "response": {+ const frozenNarrative = applyStoredNarrativeEvent(payload);+ handleResponse(payload, frozenNarrative);return true;- case "error":- setNarrative((prev) => applyNarrativeEvent(prev, payload));- handleError(payload);+ }+ case "error": {+ const frozenNarrative = applyStoredNarrativeEvent(payload);+ handleError(payload, frozenNarrative);return true;+ }default:return false;}@@ -1208,6 +1226,7 @@ export function WorkflowCopilotChat({}},[+ applyStoredNarrativeEvent,applyWorkflowUpdate,autoAccept,credentialGetter,diff --git a/skyvern-frontend/src/routes/workflows/copilot/narrativeState.ts b/skyvern-frontend/src/routes/workflows/copilot/narrativeState.tsindex a7d3f2e57..4a102bef7 100644--- a/skyvern-frontend/src/routes/workflows/copilot/narrativeState.ts+++ b/skyvern-frontend/src/routes/workflows/copilot/narrativeState.ts@@ -5,6 +5,7 @@import {CopilotResponseType,+ ProposalDisposition,WorkflowCopilotBlockProgressUpdate,WorkflowCopilotDesignEndUpdate,WorkflowCopilotDesignStartUpdate,@@ -91,6 +92,8 @@ export interface TurnNarrativeState {terminal: "response" | "error" | null;terminalMessage: string | null;narrativeSummary: string | null;+ cancelled: boolean;+ proposalDisposition: ProposalDisposition | null;// Block count of the canonical workflow at turn entry. Drives the edit-// vs-build chip derivation; the snap-back source is captured client-side// at submit so unsaved local canvas edits survive.@@ -116,6 +119,8 @@ export const EMPTY_NARRATIVE: TurnNarrativeState = Object.freeze({terminal: null,terminalMessage: null,narrativeSummary: null,+ cancelled: false,+ proposalDisposition: null,priorBlockCount: null,startedAt: null,endedAt: null,@@ -411,6 +416,9 @@ export function applyNarrativeEvent(return {...hydrated,responseType: event.response_type ?? hydrated.responseType,+ cancelled: event.cancelled ?? hydrated.cancelled,+ proposalDisposition:+ event.proposal_disposition ?? hydrated.proposalDisposition,terminalMessage: hydrated.terminalMessage ?? event.message,narrativeSummary:hydrated.narrativeSummary ??@@ -435,6 +443,8 @@ export function applyNarrativeEvent(return {...prev,responseType: event.response_type ?? prev.responseType,+ cancelled: event.cancelled ?? false,+ proposalDisposition: event.proposal_disposition,designEnded: true,terminal: "response",terminalMessage: event.message,@@ -521,6 +531,14 @@ export function hydrateNarrativeFromPayload(rawResponseType === "REPLACE_WORKFLOW"? rawResponseType: null;+ const rawProposalDisposition = payload.proposalDisposition;+ const proposalDisposition: ProposalDisposition | null =+ rawProposalDisposition === "no_proposal" ||+ rawProposalDisposition === "auto_applicable" ||+ rawProposalDisposition === "review_untested" ||+ rawProposalDisposition === "review_tested"+ ? rawProposalDisposition+ : null;const draftRaw = payload.draft;const draft =draftRaw && typeof draftRaw === "object"@@ -607,6 +625,8 @@ export function hydrateNarrativeFromPayload(turnIndex,mode: mode as TurnNarrativeState["mode"],responseType,+ cancelled: payload.cancelled === true,+ proposalDisposition,designStarted: true,designEnded: true,draft,diff --git a/skyvern/forge/sdk/copilot/context.py b/skyvern/forge/sdk/copilot/context.pyindex 47f149aac..3ded29029 100644--- a/skyvern/forge/sdk/copilot/context.py+++ b/skyvern/forge/sdk/copilot/context.py@@ -54,6 +54,8 @@ class TurnNarrativePayload(TypedDict):turnIndex: intmode: strresponseType: NotRequired[ResponseType]+ cancelled: NotRequired[bool]+ proposalDisposition: NotRequired[ProposalDisposition]designStarted: booldesignEnded: booldraft: NarrativeDraft | Nonediff --git a/skyvern/forge/sdk/routes/workflow_copilot.py b/skyvern/forge/sdk/routes/workflow_copilot.pyindex aa64e0b13..b923c7037 100644--- a/skyvern/forge/sdk/routes/workflow_copilot.py+++ b/skyvern/forge/sdk/routes/workflow_copilot.py@@ -326,6 +326,21 @@ def _make_error_narrative_payload(turn_id: str | None, turn_index: int | None, m}+def _with_terminal_narrative_metadata(+ narrative_payload: TurnNarrativePayload | None,+ *,+ cancelled: bool,+ proposal_disposition: ProposalDisposition,+) -> TurnNarrativePayload | None:+ if narrative_payload is None:+ return None+ return {+ **narrative_payload,+ "cancelled": cancelled,+ "proposalDisposition": proposal_disposition,+ }++def _build_recoverable_route_agent_result(error: BaseException,*,@@ -458,6 +473,13 @@ async def _persist_cancel_turn(narrative_summary = agent_result.narrative_summarynarrative_payload = agent_result.narrative_payload+ proposal_disposition = _proposal_disposition(agent_result)+ narrative_payload = _with_terminal_narrative_metadata(+ narrative_payload,+ cancelled=True,+ proposal_disposition=proposal_disposition,+ )+await asyncio.shield(app.DATABASE.workflow_params.create_workflow_copilot_chat_message(organization_id=chat.organization_id,@@ -477,7 +499,6 @@ async def _persist_cancel_turn(narrative_payload=narrative_payload,))- proposal_disposition = _proposal_disposition(agent_result)try:await asyncio.shield(stream.send(@@ -559,6 +580,12 @@ async def _finalise_normal_turn(raiseawait _persist_proposed_workflow_state(chat, agent_result, restored)+ proposal_disposition = _proposal_disposition(agent_result)+ narrative_payload = _with_terminal_narrative_metadata(+ agent_result.narrative_payload,+ cancelled=False,+ proposal_disposition=proposal_disposition,+ )await app.DATABASE.workflow_params.create_workflow_copilot_chat_message(organization_id=chat.organization_id,@@ -574,10 +601,9 @@ async def _finalise_normal_turn(content=user_response,global_llm_context=updated_global_llm_context,turn_outcome=agent_result.turn_outcome,- narrative_payload=agent_result.narrative_payload,+ narrative_payload=narrative_payload,)- proposal_disposition = _proposal_disposition(agent_result)await stream.send(WorkflowCopilotStreamResponseUpdate(type=WorkflowCopilotStreamMessageType.RESPONSE,@@ -591,7 +617,7 @@ async def _finalise_normal_turn(output_policy_diagnostics=agent_result.output_policy_diagnostics,turn_id=agent_result.turn_id,narrative_summary=agent_result.narrative_summary,- narrative_payload=agent_result.narrative_payload,+ narrative_payload=narrative_payload,))diff --git a/tests/unit/test_workflow_copilot_route.py b/tests/unit/test_workflow_copilot_route.pyindex 494cdf342..10fd664aa 100644--- a/tests/unit/test_workflow_copilot_route.py+++ b/tests/unit/test_workflow_copilot_route.py@@ -45,6 +45,38 @@ def _make_chat_request() -> WorkflowCopilotChatRequest:)+def test_terminal_narrative_metadata_preserves_payload_and_adds_contract_fields() -> None:+ payload = {+ "turnId": "turn-1",+ "turnIndex": 0,+ "mode": "build",+ "designStarted": True,+ "designEnded": True,+ "draft": {"blockCount": 1, "blockLabels": ["open_page"], "summary": None},+ "blocks": [],+ "terminal": "response",+ "terminalMessage": "Cancelled.",+ "narrativeSummary": "Cancelled.",+ "priorBlockCount": None,+ "designActivity": [],+ "startedAt": "2026-05-25T00:00:00Z",+ "endedAt": "2026-05-25T00:00:05Z",+ }++ enriched = workflow_copilot_route._with_terminal_narrative_metadata(+ payload,+ cancelled=True,+ proposal_disposition="review_untested",+ )++ assert enriched is not None+ assert enriched["cancelled"] is True+ assert enriched["proposalDisposition"] == "review_untested"+ assert enriched["draft"] == payload["draft"]+ assert "cancelled" not in payload+ assert "proposalDisposition" not in payload++def _install_fake_create(monkeypatch: pytest.MonkeyPatch) -> dict[str, object]:"""Capture the stream handler that the route hands to EventSourceStream."""captured: dict[str, object] = {}