Automate browser based workflows with AI
Python aiapiautomationbrowserbrowser-automationcomputergptllmplaywrightpowerautomatepuppeteerpythonrpaseleniumvisionworkflow
Keep a Copilot proposal across a server restart (SKY-15853) (#8528)
Andrew Neilson8d13919545aa
diff --git a/skyvern-frontend/src/routes/workflows/copilot/WorkflowCopilotChat.reviewGate.test.tsx b/skyvern-frontend/src/routes/workflows/copilot/WorkflowCopilotChat.reviewGate.test.tsxindex f66eb8053..5aff3a242 100644--- a/skyvern-frontend/src/routes/workflows/copilot/WorkflowCopilotChat.reviewGate.test.tsx+++ b/skyvern-frontend/src/routes/workflows/copilot/WorkflowCopilotChat.reviewGate.test.tsx@@ -43,6 +43,20 @@ const { streamCalls, postStreaming, cancelPost, historyGet, historyResponse } =workflow_copilot_chat_id: "chat-1" as string | null,chat_history: [] as unknown[],proposed_workflow: null as Record<string, unknown> | null,+ proposed_workflow_metadata: null as {+ owner_turn_id: string;+ revision: number;+ canonical_fingerprint: string;+ disposition: "review_untested";+ workflow_run_id: string | null;+ } | null,+ proposed_workflow_run: null as {+ workflow_run_id: string;+ status: string | null;+ available: boolean;+ failure_reason: string | null;+ outputs: Array<{ output_parameter_id: string; value: unknown }>;+ } | null,auto_accept: false,},};@@ -292,6 +306,8 @@ beforeEach(() => {workflow_copilot_chat_id: "chat-1",chat_history: [],proposed_workflow: null,+ proposed_workflow_metadata: null,+ proposed_workflow_run: null,auto_accept: false,};});@@ -310,6 +326,142 @@ describe("WorkflowCopilotChat — g2 review gate", () => {expect(streamCalls[0]!.body.keep_pending_proposal).toBe(false);});+ it("interrupted_draft resyncs a stale typed Accept without applying it locally", async () => {+ await renderChat();+ await submit("build me a workflow");+ await waitFor(() => expect(postStreaming).toHaveBeenCalledTimes(1));+ await act(async () => {+ streamCalls[0]!.onMessage(+ proposalResponse("Draft ready.", {+ proposed_workflow_metadata: {+ owner_turn_id: "turn-1",+ revision: 1,+ canonical_fingerprint: "canonical-1",+ disposition: "review_untested",+ workflow_run_id: null,+ },+ }),+ );+ streamCalls[0]!.resolve();+ });++ historyResponse.data.proposed_workflow = proposedWorkflowPayload({+ title: "Newer draft",+ });+ historyResponse.data.proposed_workflow_metadata = {+ owner_turn_id: "turn-2",+ revision: 1,+ canonical_fingerprint: "canonical-1",+ disposition: "review_untested",+ workflow_run_id: null,+ };+ cancelPost.mockRejectedValueOnce({ response: { status: 409 } });+ await act(async () => {+ fireEvent.click(screen.getByRole("button", { name: "Accept" }));+ });++ await waitFor(() => expect(historyGet).toHaveBeenCalled());+ expect(cancelPost).toHaveBeenCalledWith(+ "/workflow/copilot/apply-proposed-workflow",+ expect.objectContaining({ owner_turn_id: "turn-1", revision: 1 }),+ );+ expect(screen.getByRole("button", { name: "Accept" })).toBeTruthy();+ });++ it("retains and resyncs a typed proposal when atomic Accept fails", async () => {+ await renderChat();+ await submit("build me a workflow");+ await waitFor(() => expect(postStreaming).toHaveBeenCalledTimes(1));+ await act(async () => {+ streamCalls[0]!.onMessage(+ proposalResponse("Draft ready.", {+ proposed_workflow_metadata: {+ owner_turn_id: "turn-1",+ revision: 1,+ canonical_fingerprint: "canonical-1",+ disposition: "review_untested",+ workflow_run_id: null,+ },+ }),+ );+ streamCalls[0]!.resolve();+ });+ historyResponse.data.proposed_workflow = proposedWorkflowPayload();+ historyResponse.data.proposed_workflow_metadata = {+ owner_turn_id: "turn-1",+ revision: 1,+ canonical_fingerprint: "canonical-1",+ disposition: "review_untested",+ workflow_run_id: null,+ };+ cancelPost.mockRejectedValueOnce({ response: { status: 500 } });++ await act(async () => {+ fireEvent.click(screen.getByRole("button", { name: "Accept" }));+ });++ await waitFor(() => expect(historyGet).toHaveBeenCalled());+ expect(cancelPost).toHaveBeenCalledTimes(1);+ expect(screen.getByRole("button", { name: "Accept" })).toBeTruthy();+ });++ it("does not locally accept a typed proposal when its chat cannot be resolved", async () => {+ historyResponse.data.workflow_copilot_chat_id = null;+ historyResponse.data.proposed_workflow = proposedWorkflowPayload();+ historyResponse.data.proposed_workflow_metadata = {+ owner_turn_id: "turn-1",+ revision: 1,+ canonical_fingerprint: "canonical-1",+ disposition: "review_untested",+ workflow_run_id: null,+ };+ await renderChat();++ await act(async () => {+ fireEvent.click(screen.getByRole("button", { name: "Accept" }));+ });++ expect(cancelPost).not.toHaveBeenCalled();+ expect(screen.getByRole("button", { name: "Accept" })).toBeTruthy();+ });++ it("interrupted_draft reload shows an actionable candidate and its exact run result", async () => {+ // A hard kill can leave only the submitted user row. MessageItem does not+ // render footers on user bubbles, so the durable candidate needs a+ // standalone review gate until an assistant-owned row exists.+ historyResponse.data.chat_history = [+ {+ sender: "user",+ content: "build the candidate",+ created_at: "2026-09-08T12:00:00Z",+ },+ ];+ historyResponse.data.proposed_workflow = proposedWorkflowPayload({+ title: "Recovered draft",+ });+ historyResponse.data.proposed_workflow_metadata = {+ owner_turn_id: "turn-interrupted",+ revision: 3,+ canonical_fingerprint: "canonical-1",+ disposition: "review_untested",+ workflow_run_id: "wr-exact",+ };+ historyResponse.data.proposed_workflow_run = {+ workflow_run_id: "wr-exact",+ status: "completed",+ available: true,+ failure_reason: null,+ outputs: [{ output_parameter_id: "op-metric", value: { metric: "42" } }],+ };++ await renderChat();++ expect(await screen.findByText("Associated test: completed")).toBeTruthy();+ expect(screen.getByText(/op-metric:.*42/)).toBeTruthy();+ expect(screen.getByRole("button", { name: "Accept" })).toBeTruthy();+ expect(screen.getByRole("button", { name: "Reject" })).toBeTruthy();+ });+it("restores an actionable gate via the chip after a bypassed proposal (old code: buttons vanish forever)", async () => {await renderChat();diff --git a/skyvern-frontend/src/routes/workflows/copilot/WorkflowCopilotChat.tsx b/skyvern-frontend/src/routes/workflows/copilot/WorkflowCopilotChat.tsxindex bfc90cb22..96d208284 100644--- a/skyvern-frontend/src/routes/workflows/copilot/WorkflowCopilotChat.tsx+++ b/skyvern-frontend/src/routes/workflows/copilot/WorkflowCopilotChat.tsx@@ -44,6 +44,8 @@ import { getSseClient } from "@/api/sse";import {CopilotAttachedFile,WorkflowCopilotCancelRequest,+ CopilotProposalMetadata,+ CopilotProposalRunFacts,WorkflowCopilotCancelSource,WorkflowCopilotChatHistoryMessage,WorkflowCopilotChatHistoryResponse,@@ -555,6 +557,22 @@ const getLatestDiffCardTurnId = (messages: ChatMessage[]): string | null => {return null;};+const getLatestDiffCardTurnIdFromHistory = (+ messages: WorkflowCopilotChatHistoryMessage[],+): string | null => {+ for (let index = messages.length - 1; index >= 0; index -= 1) {+ const message = messages[index];+ const narrative = hydrateHistoryNarrative(+ message?.narrative_payload,+ message?.turn_outcome,+ );+ if (narrative?.turnId && shouldShowDiffCard(narrative)) {+ return narrative.turnId;+ }+ }+ return null;+};+// messages.length - 1 with any trailing run_lifecycle lines skipped, so// proposal actions keep attaching to the last real turn.const findLastTurnIndex = (messages: ChatMessage[]): number => {@@ -859,6 +877,27 @@ interface TurnSnapshot {hadStagedDraft: boolean;}+function ProposalRunFactsLine({ facts }: { facts: CopilotProposalRunFacts }) {+ if (!facts.available) {+ return (+ <p className="text-xs text-muted-foreground">+ Associated test run unavailable. No other run was substituted.+ </p>+ );+ }+ return (+ <div className="space-y-1 text-xs text-muted-foreground">+ <p>Associated test: {facts.status ?? "status unavailable"}</p>+ {facts.failure_reason ? <p>{facts.failure_reason}</p> : null}+ {facts.outputs.map((output) => (+ <p key={output.output_parameter_id}>+ {output.output_parameter_id}: {JSON.stringify(output.value)}+ </p>+ ))}+ </div>+ );+}+const AUTO_SEND_TIMEOUT_MS = 5000;const DEFAULT_WINDOW_WIDTH = 600;@@ -952,6 +991,10 @@ export function WorkflowCopilotChat({const [workPlan, setWorkPlan] = useState<string[]>([]);const [proposedWorkflow, setProposedWorkflow] =useState<WorkflowApiResponse | null>(null);+ const [pendingProposalMetadata, setPendingProposalMetadata] =+ useState<CopilotProposalMetadata | null>(null);+ const [pendingProposalRun, setPendingProposalRun] =+ useState<CopilotProposalRunFacts | null>(null);// Owning turn of the current proposedWorkflow. Kept alongside it (never// merged into one object) so the gate can re-attach to its owning message.const [pendingProposalTurnId, setPendingProposalTurnId] = useState<@@ -1777,6 +1820,8 @@ export function WorkflowCopilotChat({discardQueuedPrompt();setWorkflowCopilotChatId(null);setProposedWorkflow(null);+ setPendingProposalMetadata(null);+ setPendingProposalRun(null);setPendingProposalTurnId(null);setAutoAccept(false);setWorkPlan([]);@@ -1833,7 +1878,8 @@ export function WorkflowCopilotChat({if (rehydratedRunId) rememberTurnOwnedRun(rehydratedRunId);}const restoredPendingProposalTurnId = data.proposed_workflow- ? getLatestDiffCardTurnId(historyMessages)+ ? (data.proposed_workflow_metadata?.owner_turn_id ??+ getLatestDiffCardTurnId(historyMessages)): null;latestTurnId.current = restoredPendingProposalTurnId;// History never carries run_lifecycle lines (local-only); carry them@@ -1846,6 +1892,8 @@ export function WorkflowCopilotChat({]);setWorkflowCopilotChatId(data.workflow_copilot_chat_id);setProposedWorkflow(data.proposed_workflow ?? null);+ setPendingProposalMetadata(data.proposed_workflow_metadata ?? null);+ setPendingProposalRun(data.proposed_workflow_run ?? null);setPendingProposalTurnId(data.proposed_workflow ? restoredPendingProposalTurnId : null,);@@ -2277,12 +2325,23 @@ export function WorkflowCopilotChat({}if (!chatId) {+ if (pendingProposalMetadata) {+ toast({+ title: "Accept failed",+ description:+ "Copilot could not verify the current proposal. Please try again.",+ variant: "destructive",+ });+ return;+ }// No chat id: apply locally and best-effort clear the server proposal so reload doesn't resurrect it.if (!applyWorkflowUpdate(workflow, { applied: true })) {return;}markProposalAccepted();setProposedWorkflow(null);+ setPendingProposalMetadata(null);+ setPendingProposalRun(null);if (alwaysAccept) {setAutoAccept(true);}@@ -2297,6 +2356,8 @@ export function WorkflowCopilotChat({{workflow_copilot_chat_id: chatId,auto_accept: alwaysAccept,+ owner_turn_id: pendingProposalMetadata?.owner_turn_id ?? null,+ revision: pendingProposalMetadata?.revision ?? null,} as WorkflowCopilotApplyProposedWorkflowRequest,);// persisted=true loads as clean baseline; without it, Save would create a duplicate version.@@ -2307,10 +2368,31 @@ export function WorkflowCopilotChat({}markProposalAccepted();setProposedWorkflow(null);+ setPendingProposalMetadata(null);+ setPendingProposalRun(null);if (alwaysAccept) {setAutoAccept(true);}} catch (applyError) {+ if (getErrorStatus(applyError) === 409) {+ await resyncProposalFromChatRow();+ toast({+ title: "Proposal changed",+ description:+ "Copilot reloaded the current proposal. Review it before applying.",+ });+ return;+ }+ if (pendingProposalMetadata) {+ await resyncProposalFromChatRow();+ toast({+ title: "Accept failed",+ description:+ "Copilot kept the current proposal for review. Please try again.",+ variant: "destructive",+ });+ return;+ }// Atomic accept can fail if the server-side proposal is missing// _copilot_yaml (SKY-9310 — V1 path didn't stash it). Fall back to the// pre-#10568 client-side apply so users aren't blocked while a backend@@ -2329,6 +2411,8 @@ export function WorkflowCopilotChat({}markProposalAccepted();setProposedWorkflow(null);+ setPendingProposalMetadata(null);+ setPendingProposalRun(null);if (alwaysAccept) {setAutoAccept(true);}@@ -2336,7 +2420,10 @@ export function WorkflowCopilotChat({}};- const handleRejectWorkflow = () => {+ const handleRejectWorkflow = async () => {+ if (!(await clearProposedWorkflow(false))) {+ return;+ }// The staged proposal was rendered onto the canvas mid-turn (via// WORKFLOW_DRAFT). Reject must revert the canvas to the pre-submit// canvas state captured client-side at submit time.@@ -2352,8 +2439,9 @@ export function WorkflowCopilotChat({setRejectedTurnIds((prev) => new Set(prev).add(turnId));}setProposedWorkflow(null);+ setPendingProposalMetadata(null);+ setPendingProposalRun(null);setPendingProposalTurnId(null);- void clearProposedWorkflow(false);};const getErrorStatus = (error: unknown): number | undefined => {@@ -2672,15 +2760,25 @@ export function WorkflowCopilotChat({);const nextProposal = response.data.proposed_workflow ?? null;setProposedWorkflow(nextProposal);- if (!nextProposal) {- setPendingProposalTurnId(null);- }+ setPendingProposalMetadata(+ response.data.proposed_workflow_metadata ?? null,+ );+ setPendingProposalRun(response.data.proposed_workflow_run ?? null);+ setPendingProposalTurnId((currentTurnId) =>+ nextProposal+ ? (response.data.proposed_workflow_metadata?.owner_turn_id ??+ getLatestDiffCardTurnIdFromHistory(response.data.chat_history) ??+ currentTurnId)+ : null,+ );} catch (error) {console.error("Failed to resync pending proposal:", error);}}, [credentialGetter]);- const clearProposedWorkflow = async (autoAcceptValue: boolean) => {+ const clearProposedWorkflow = async (+ autoAcceptValue: boolean,+ ): Promise<boolean> => {const clearProposalByChatId = async (chatId: string) => {const client = await getClient(credentialGetter, "sans-api-v1");await client.post<WorkflowCopilotClearProposedWorkflowRequest>(@@ -2688,6 +2786,8 @@ export function WorkflowCopilotChat({{workflow_copilot_chat_id: chatId,auto_accept: autoAcceptValue,+ owner_turn_id: pendingProposalMetadata?.owner_turn_id ?? null,+ revision: pendingProposalMetadata?.revision ?? null,} as WorkflowCopilotClearProposedWorkflowRequest,);};@@ -2701,16 +2801,17 @@ export function WorkflowCopilotChat({"Failed to resolve chat ID before clearing proposal:",resolveError,);- return;+ return false;}}if (!chatId) {- return;+ return false;}try {await clearProposalByChatId(chatId);+ return true;} catch (error) {const status = getErrorStatus(error);if (status === 404) {@@ -2718,12 +2819,16 @@ export function WorkflowCopilotChat({const refreshedChatId = await fetchLatestChatId();if (refreshedChatId && refreshedChatId !== chatId) {await clearProposalByChatId(refreshedChatId);- return;+ return true;}} catch (retryError) {console.error("Retry to clear proposed workflow failed:", retryError);}}+ if (status === 409) {+ await resyncProposalFromChatRow();+ return false;+ }console.error("Failed to clear proposed workflow:", error);toast({title: "Copilot update failed",@@ -2732,12 +2837,15 @@ export function WorkflowCopilotChat({: "Failed to clear copilot proposal. Please try again.",variant: "destructive",});+ return false;}};const handleReviewWorkflow = (workflow: WorkflowApiResponse) => {onReviewWorkflow?.(workflow, () => {setProposedWorkflow(null);+ setPendingProposalMetadata(null);+ setPendingProposalRun(null);setPendingProposalTurnId(null);});};@@ -2755,6 +2863,8 @@ export function WorkflowCopilotChat({discardQueuedPrompt();setWorkflowCopilotChatId(null);setProposedWorkflow(null);+ setPendingProposalMetadata(null);+ setPendingProposalRun(null);setPendingProposalTurnId(null);setAutoAccept(false);setWorkPlan([]);@@ -3749,9 +3859,15 @@ export function WorkflowCopilotChat({// bypassed proposal — drop the stale handle so its gate cannot// reapply an outdated draft over what was just committed.setProposedWorkflow(null);+ setPendingProposalMetadata(null);+ setPendingProposalRun(null);setPendingProposalTurnId(null);} else if (response.updated_workflow) {setProposedWorkflow(response.updated_workflow);+ setPendingProposalMetadata(+ response.proposed_workflow_metadata ?? null,+ );+ setPendingProposalRun(null);setPendingProposalTurnId(responseTurnId);} else if (// Cancel/error terminal on a turn that produced staged content →@@ -3762,6 +3878,8 @@ export function WorkflowCopilotChat({) {applyWorkflowUpdate(responseEntry.snapshot);setProposedWorkflow(null);+ setPendingProposalMetadata(null);+ setPendingProposalRun(null);setPendingProposalTurnId(null);} else if (pendingProposalTurnId) {// No new draft this turn, but a bypassed proposal is still@@ -3773,6 +3891,12 @@ export function WorkflowCopilotChat({// proposals, the Accept/Reject card is the user's next gate;// canvas keeps the staged content until the user acts.setProposedWorkflow(response.updated_workflow ?? null);+ setPendingProposalMetadata(+ response.updated_workflow+ ? (response.proposed_workflow_metadata ?? null)+ : null,+ );+ setPendingProposalRun(null);setPendingProposalTurnId(null);}};@@ -3806,6 +3930,8 @@ export function WorkflowCopilotChat({if (errorEntry?.hadStagedDraft && errorEntry?.snapshot) {applyWorkflowUpdate(errorEntry.snapshot);setProposedWorkflow(null);+ setPendingProposalMetadata(null);+ setPendingProposalRun(null);setPendingProposalTurnId(null);}};@@ -4697,7 +4823,22 @@ export function WorkflowCopilotChat({? findLastIndexOfTurn(messages, pendingProposalTurnId): -1;const gateIndex = gateOwnerIndex >= 0 ? gateOwnerIndex : lastTurnIndex;- const gateOwnerNarrative = messages[gateIndex]?.narrative;+ const gateOwnerMessage = messages[gateIndex];+ const gateOwnerNarrative = gateOwnerMessage?.narrative;+ const gateOwnerRendersInline = Boolean(+ gateOwnerMessage &&+ gateOwnerMessage.sender === "ai" &&+ gateOwnerMessage.kind !== "run_lifecycle" &&+ gateOwnerMessage.kind !== "status_notice" &&+ !(+ gateOwnerNarrative &&+ !(+ shouldShowDiffCard(gateOwnerNarrative) ||+ (gateOwnerNarrative.turnId !== null &&+ gateOwnerNarrative.turnId === pendingProposalTurnId)+ )+ ),+ );// Mid-turn Accept would be clobbered by the in-flight turn's terminal// restore, so gate actions wait for idle.const gateActionable =@@ -5037,40 +5178,49 @@ export function WorkflowCopilotChat({),)}{showReviewGate ? (- <ReviewGateCard- turn={message.narrative}- pending={- index === gateIndex && Boolean(proposedWorkflow)- }- verdict={getReviewGateVerdict(- message.narrative,- proposedWorkflow,- )}- settled={- turnId && acceptedTurnIds.has(turnId)- ? "accepted"- : turnId && rejectedTurnIds.has(turnId)- ? "rejected"- : null- }- actionsEnabled={gateActionable}- onAccept={() =>- proposedWorkflow &&- handleAcceptWorkflow(proposedWorkflow)- }- onAlwaysAccept={() =>- proposedWorkflow &&- handleAcceptWorkflow(proposedWorkflow, true)- }- onReject={handleRejectWorkflow}- onReview={() =>- proposedWorkflow &&- handleReviewWorkflow(proposedWorkflow)- }- onTestEndToEnd={handleTestEndToEnd}- gateId={turnId ? `copilot-gate-${turnId}` : undefined}- flash={turnId !== null && turnId === gateFlashTurnId}- />+ <div className="space-y-2">+ {index === gateIndex && pendingProposalRun ? (+ <ProposalRunFactsLine facts={pendingProposalRun} />+ ) : null}+ <ReviewGateCard+ turn={message.narrative}+ pending={+ index === gateIndex && Boolean(proposedWorkflow)+ }+ verdict={getReviewGateVerdict(+ message.narrative,+ proposedWorkflow,+ )}+ settled={+ turnId && acceptedTurnIds.has(turnId)+ ? "accepted"+ : turnId && rejectedTurnIds.has(turnId)+ ? "rejected"+ : null+ }+ actionsEnabled={gateActionable}+ onAccept={() =>+ proposedWorkflow &&+ handleAcceptWorkflow(proposedWorkflow)+ }+ onAlwaysAccept={() =>+ proposedWorkflow &&+ handleAcceptWorkflow(proposedWorkflow, true)+ }+ onReject={handleRejectWorkflow}+ onReview={() =>+ proposedWorkflow &&+ handleReviewWorkflow(proposedWorkflow)+ }+ onTestEndToEnd={handleTestEndToEnd}+ gateId={+ turnId ? `copilot-gate-${turnId}` : undefined+ }+ flash={+ turnId !== null && turnId === gateFlashTurnId+ }+ />+ </div>) : null}{!isLoadingHistory &&isLastMessage &&@@ -5207,29 +5357,34 @@ export function WorkflowCopilotChat({}footer={isGateOwnerOrLast ? (- <ReviewGateCard- pending- verdict={getReviewGateVerdict(- gateOwnerNarrative,- proposedWorkflow,- )}- settled={null}- actionsEnabled={gateActionable}- onAccept={() =>- proposedWorkflow &&- handleAcceptWorkflow(proposedWorkflow)- }- onAlwaysAccept={() =>- proposedWorkflow &&- handleAcceptWorkflow(proposedWorkflow, true)- }- onReject={handleRejectWorkflow}- onReview={() =>- proposedWorkflow &&- handleReviewWorkflow(proposedWorkflow)- }- onTestEndToEnd={handleTestEndToEnd}- />+ <div className="space-y-2">+ {pendingProposalRun ? (+ <ProposalRunFactsLine facts={pendingProposalRun} />+ ) : null}+ <ReviewGateCard+ pending+ verdict={getReviewGateVerdict(+ gateOwnerNarrative,+ proposedWorkflow,+ )}+ settled={null}+ actionsEnabled={gateActionable}+ onAccept={() =>+ proposedWorkflow &&+ handleAcceptWorkflow(proposedWorkflow)+ }+ onAlwaysAccept={() =>+ proposedWorkflow &&+ handleAcceptWorkflow(proposedWorkflow, true)+ }+ onReject={handleRejectWorkflow}+ onReview={() =>+ proposedWorkflow &&+ handleReviewWorkflow(proposedWorkflow)+ }+ onTestEndToEnd={handleTestEndToEnd}+ />+ </div>) : null}/>@@ -5240,6 +5395,26 @@ export function WorkflowCopilotChat({.map(renderQuestionCard);return [...questions, rendered];})}+ {proposedWorkflow && !gateOwnerRendersInline ? (+ <div className="space-y-2">+ {pendingProposalRun ? (+ <ProposalRunFactsLine facts={pendingProposalRun} />+ ) : null}+ <ReviewGateCard+ pending+ verdict={getReviewGateVerdict(undefined, proposedWorkflow)}+ settled={null}+ actionsEnabled={gateActionable}+ onAccept={() => handleAcceptWorkflow(proposedWorkflow)}+ onAlwaysAccept={() =>+ handleAcceptWorkflow(proposedWorkflow, true)+ }+ onReject={handleRejectWorkflow}+ onReview={() => handleReviewWorkflow(proposedWorkflow)}+ onTestEndToEnd={handleTestEndToEnd}+ />+ </div>+ ) : null}{questionInteractions.filter((item) =>diff --git a/skyvern-frontend/src/routes/workflows/copilot/workflowCopilotTypes.ts b/skyvern-frontend/src/routes/workflows/copilot/workflowCopilotTypes.tsindex 9a56cb633..efe1494fc 100644--- a/skyvern-frontend/src/routes/workflows/copilot/workflowCopilotTypes.ts+++ b/skyvern-frontend/src/routes/workflows/copilot/workflowCopilotTypes.ts@@ -171,10 +171,31 @@ export interface WorkflowCopilotChatHistoryResponse {workflow_copilot_chat_id: string | null;chat_history: WorkflowCopilotChatHistoryMessage[];proposed_workflow?: WorkflowApiResponse | null;+ proposed_workflow_metadata?: CopilotProposalMetadata | null;+ proposed_workflow_run?: CopilotProposalRunFacts | null;auto_accept?: boolean | null;work_plan?: string[];}+export interface CopilotProposalMetadata {+ owner_turn_id: string;+ revision: number;+ canonical_fingerprint: string;+ disposition: ProposalDisposition | "accepting";+ workflow_run_id?: string | null;+}++export interface CopilotProposalRunFacts {+ workflow_run_id: string;+ status?: string | null;+ available: boolean;+ failure_reason?: string | null;+ outputs: Array<{+ output_parameter_id: string;+ value: unknown;+ }>;+}+export interface WorkflowCopilotChatSummary {workflow_copilot_chat_id: string;workflow_permanent_id: string;@@ -190,11 +211,15 @@ export interface WorkflowCopilotChatSummary {export interface WorkflowCopilotClearProposedWorkflowRequest {workflow_copilot_chat_id: string;auto_accept: boolean;+ owner_turn_id?: string | null;+ revision?: number | null;}export interface WorkflowCopilotApplyProposedWorkflowRequest {workflow_copilot_chat_id: string;auto_accept: boolean;+ owner_turn_id?: string | null;+ revision?: number | null;}export interface WorkflowCopilotAudioUploadResponse {@@ -236,6 +261,7 @@ export interface WorkflowCopilotStreamResponseUpdate {response_type?: CopilotResponseType;proposal_disposition: ProposalDisposition;workflow_applied?: boolean;+ proposed_workflow_metadata?: CopilotProposalMetadata | null;// Cancel forces explicit review.cancelled?: boolean;// Optional so the FE tolerates an older backend that does not emit thediff --git a/skyvern/forge/sdk/copilot/agent.py b/skyvern/forge/sdk/copilot/agent.pyindex d13de0702..a523313c3 100644--- a/skyvern/forge/sdk/copilot/agent.py+++ b/skyvern/forge/sdk/copilot/agent.py@@ -221,7 +221,10 @@ from skyvern.forge.sdk.copilot.tools.run_execution import (run_workflow_end_to_end,)from skyvern.forge.sdk.copilot.tools.scouting import hydrate_prior_carried_trajectory-from skyvern.forge.sdk.copilot.tools.workflow_update import restore_pending_workflow_proposal+from skyvern.forge.sdk.copilot.tools.workflow_update import (+ publish_workflow_candidate,+ restore_pending_workflow_proposal,+)from skyvern.forge.sdk.copilot.tracing_setup import _copilot_model_name, ensure_tracing_initialized, is_tracing_enabledfrom skyvern.forge.sdk.copilot.turn_context import TurnContextAssembler, TurnContextInputs, TurnContextPacketfrom skyvern.forge.sdk.copilot.turn_halt import (@@ -249,6 +252,7 @@ from skyvern.forge.sdk.copilot.workflow_yaml import (stored_block_code,stored_workflow_yaml,)+from skyvern.forge.sdk.db.exceptions import CopilotProposalConflictErrorfrom skyvern.forge.sdk.schemas.copilot_turn_outcome import (ConnectedAccountChoice,ConnectedAccountChoiceReference,@@ -2034,6 +2038,9 @@ def _make_agent_result(result = AgentResult(global_llm_context=final_context, turn_outcome=turn_outcome, **kwargs)if ctx is not None:result.resolved_model = ctx.resolved_model+ result.proposal_owner_turn_id = ctx.proposal_owner_turn_id+ result.proposal_revision = ctx.proposal_revision+ result.proposal_workflow_run_id = ctx.proposal_workflow_run_idresult.clear_persisted_completion_contract = ctx.clear_persisted_completion_contractresult.work_plan = ctx.work_plan if ctx.work_plan is None else list(ctx.work_plan)if ctx.eval_mode == CopilotEvalMode.BROWSER_ABLATION:@@ -3745,23 +3752,47 @@ async def _translate_to_agent_result(# REPLACE_WORKFLOW above; the explicit guard here defends against future# refactors that re-emit REPLACE_WORKFLOW post-rendering.if resp_type == "REPLACE_WORKFLOW" and last_workflow is not ctx.last_workflow and not blocker_active:- ctx.last_workflow = last_workflow- ctx.last_workflow_yaml = last_workflow_yaml- ctx.runner_code_block_associations_by_label = runner_code_block_associations(last_workflow_yaml or "")- ctx.last_test_ok = None- ctx.last_full_workflow_test_ok = False- clear_active_run_evidence_on_workflow_edit(ctx)- # Inline REPLACE_WORKFLOW is untested by construction; emit a draft- # envelope without staging onto ctx so terminal auto-accept can't fire,- # and suppress the workflow payload so the canvas does not render it.- if last_workflow is not None and ctx.stream is not None:- try:- await maybe_emit_design_end(ctx.stream, ctx)- await emit_workflow_draft(ctx.stream, ctx, last_workflow, include_workflow=False)- except Exception as emit_err:- LOG.warning("copilot_narrative_inline_replace_emit_failed", error=str(emit_err))- ctx.design_start_emitted = False- ctx.design_end_emitted = False+ async with ctx.proposal_mutation_lock:+ publication_conflict: CopilotProposalConflictError | None = None+ if last_workflow is not None and last_workflow_yaml is not None:+ try:+ last_workflow_yaml = await publish_workflow_candidate(+ ctx, workflow=last_workflow, workflow_yaml=last_workflow_yaml+ )+ except CopilotProposalConflictError as conflict:+ publication_conflict = conflict+ if publication_conflict is not None:+ # Nothing was stored, so the prior candidate stays on ctx and the reply says so+ # rather than presenting a draft the next turn cannot find.+ LOG.info(+ "copilot_inline_replace_candidate_publication_conflict",+ workflow_permanent_id=ctx.workflow_permanent_id,+ error=str(publication_conflict),+ )+ user_response = _with_inline_reject_note(+ user_response,+ "The pending proposal changed while this draft was being saved, so it was not stored. "+ "Ask me to make the change again.",+ )+ resp_type = "REPLY"+ last_workflow = ctx.last_workflow+ last_workflow_yaml = ctx.last_workflow_yaml+ else:+ ctx.last_workflow = last_workflow+ ctx.last_workflow_yaml = last_workflow_yaml+ ctx.runner_code_block_associations_by_label = runner_code_block_associations(last_workflow_yaml or "")+ ctx.last_test_ok = None+ ctx.last_full_workflow_test_ok = False+ clear_active_run_evidence_on_workflow_edit(ctx)+ # Inline REPLACE_WORKFLOW is untested by construction; emit only after custody succeeds.+ if last_workflow is not None and ctx.stream is not None:+ try:+ await maybe_emit_design_end(ctx.stream, ctx)+ await emit_workflow_draft(ctx.stream, ctx, last_workflow, include_workflow=False)+ except Exception as emit_err: # noqa: BLE001 - narrative emission is best-effort after durable custody.+ LOG.warning("copilot_narrative_inline_replace_emit_failed", error=str(emit_err))+ ctx.design_start_emitted = False+ ctx.design_end_emitted = False# An unverified edit/run sits in ``last_workflow`` after a recorded# failure — surface the verified prior shape and skip the failure rewrite@@ -5110,23 +5141,43 @@ async def _run_copilot_turn_impl(label: set(fingerprints) for label, fingerprints in (prior_executed_block_fingerprints or {}).items()},)- await restore_pending_workflow_proposal(ctx)+ if chat_request.product_action == "diagnose_run":+ await restore_pending_workflow_proposal(+ ctx,+ required_workflow_run_id=chat_request.workflow_run_id,+ )+ else:+ await restore_pending_workflow_proposal(ctx)await hydrate_work_plan(ctx)chat_request.workflow_yaml = ctx.workflow_yamlsafe_workflow_yaml = redact_raw_secrets_for_prompt(ctx.workflow_yaml or "")# Before the turn acts: a repair opened about a failed run inherits that run's identity and the# browser it used, so a tool asked to look at the run has something to look at from the first# call rather than only after this turn has run something itself.- repair_origin_binding = await seed_repair_origin_run(ctx, workflow_run_id=chat_request.workflow_run_id)+ # The run the caller named wins; a restored candidate's exact run is the fallback.+ associated_run_id = chat_request.workflow_run_id or ctx.proposal_workflow_run_id+ repair_origin_binding = await seed_repair_origin_run(ctx, workflow_run_id=associated_run_id)+ if ctx.proposal_workflow_run_id is not None and associated_run_id == ctx.proposal_workflow_run_id:+ # Exact candidate ownership wins over the generic latest-final-run fallback even when+ # the run has no retained browser or row details are no longer available.+ ctx.last_run_blocks_workflow_run_id = associated_run_id# The same run, read as the packet a same-turn test would have produced. The route's own# rendering of these blocks carries no error code and no failing line. Every message sent from# a run page carries that run's id, so this reads the run once it is over — a run that reports# success can still be the one the user is complaining about.- prior_run_packet = (- await hydrate_prior_run_packet(ctx, workflow_run_id=chat_request.workflow_run_id)- if repair_origin_binding.finished- else None- )+ prior_run_packet = None+ if associated_run_id and (ctx.proposal_workflow_run_id == associated_run_id or repair_origin_binding.finished):+ prior_run_packet = await hydrate_prior_run_packet(ctx, workflow_run_id=associated_run_id)+ if prior_run_packet is None and ctx.proposal_workflow_run_id == associated_run_id:+ prior_run_packet = {+ "run": {+ "workflow_run_id": associated_run_id,+ "status": "unavailable",+ },+ "omission_notices": [+ "The proposal's exact associated run is unavailable; no other run was substituted."+ ],+ }LOG.info("copilot_block_authoring_policy_resolved",diff --git a/skyvern/forge/sdk/copilot/context.py b/skyvern/forge/sdk/copilot/context.pyindex b8bec2852..5dec74bd6 100644--- a/skyvern/forge/sdk/copilot/context.py+++ b/skyvern/forge/sdk/copilot/context.py@@ -1052,6 +1052,9 @@ class AgentResult:staged_workflow_yaml: str | None = Nonestaged_workflow: Workflow | None = Nonehas_staged_proposal: bool = False+ proposal_owner_turn_id: str | None = None+ proposal_revision: int | None = None+ proposal_workflow_run_id: str | None = Nonecode_artifact_metadata: dict[str, dict[str, Any]] | None = Noneexecuted_block_fingerprints: dict[str, set[str]] = field(default_factory=dict)# Legacy marker for turns that wrote canonical before snapshot isolation.@@ -1308,6 +1311,13 @@ class CopilotContext(AgentContext):staged_workflow_yaml: str | None = Nonestaged_workflow: Workflow | None = Nonehas_staged_proposal: bool = False+ # A single in-process writer at a time; the row-level CAS below this lock is the+ # cross-process fence. The token is replaced only after a durable publication.+ proposal_mutation_lock: asyncio.Lock = field(default_factory=asyncio.Lock, repr=False)+ proposal_owner_turn_id: str | None = None+ proposal_revision: int | None = None+ proposal_canonical_fingerprint: str | None = None+ proposal_workflow_run_id: str | None = None# The chat row's setting, not the turn's commit decision: the route can still refuse to apply a# staged draft at turn end. None on entrypoints that load no chat row.auto_accept: bool | None = Nonediff --git a/skyvern/forge/sdk/copilot/tools/run_execution.py b/skyvern/forge/sdk/copilot/tools/run_execution.pyindex 9bbadf795..11d8bde82 100644--- a/skyvern/forge/sdk/copilot/tools/run_execution.py+++ b/skyvern/forge/sdk/copilot/tools/run_execution.py@@ -1602,6 +1602,28 @@ def _workflow_parameters(workflow: Workflow | None) -> list[Any]:ExecutionSnapshotProvenance = Literal["canonical", "staged"]+class _ExecutionSourceFacts(TypedDict):+ source_kind: ExecutionSnapshotProvenance+ workflow_id: str+ block_code_sha256: dict[str, str]+++def _execution_source_facts(+ workflow: Workflow,+ *,+ provenance: ExecutionSnapshotProvenance,+) -> _ExecutionSourceFacts:+ return {+ "source_kind": provenance,+ "workflow_id": workflow.workflow_id,+ "block_code_sha256": {+ block.label: hashlib.sha256(block.code.encode("utf-8")).hexdigest()+ for block in get_all_blocks(workflow.workflow_definition.blocks)+ if isinstance(block, CodeBlock)+ },+ }++@dataclass(frozen=True)class CopilotExecutionSnapshot:"""One provenance-closed workflow definition and the rows a run binds against."""@@ -1624,6 +1646,8 @@ class _RunExecution:source_at_start: Workflow | Noneunbound_keys: list[str]explicit_blank: bool+ proposal_owner_turn_id: str | None = None+ proposal_revision: int | None = Noneoutcome: RecordedRunOutcome | None = Nonebuild_outcome: RecordedBuildTestOutcome | None = None@@ -1636,15 +1660,10 @@ class _ExecutionResult(dict[str, Any]):super().__init__(result)self.execution = executiondata = self.setdefault("data", {})- data["execution_source"] = {- "source_kind": execution.snapshot.provenance,- "workflow_id": execution.snapshot.workflow.workflow_id,- "block_code_sha256": {- block.label: hashlib.sha256(block.code.encode("utf-8")).hexdigest()- for block in get_all_blocks(execution.snapshot.workflow.workflow_definition.blocks)- if isinstance(getattr(block, "code", None), str)- },- }+ data["execution_source"] = _execution_source_facts(+ execution.snapshot.workflow,+ provenance=execution.snapshot.provenance,+ )if execution.explicit_blank:data["browser_start"] = {"kind": "separate_blank_context",@@ -3052,6 +3071,8 @@ async def _run_blocks_and_collect_debug(if execution_snapshot is not Noneelse source_at_start),+ proposal_owner_turn_id=ctx.proposal_owner_turn_id if snapshot.provenance == "staged" else None,+ proposal_revision=ctx.proposal_revision if snapshot.provenance == "staged" else None,unbound_keys=[],explicit_blank=explicit_blank,)@@ -3424,6 +3445,45 @@ async def _run_blocks_and_collect_debug("error": "The prepared run did not retain the requested blank browser; execution was not started.",}+ if (+ ctx.workflow_copilot_chat_id+ and execution.proposal_owner_turn_id is not None+ and execution.proposal_revision is not None+ ):+ try:+ async with ctx.proposal_mutation_lock:+ await app.DATABASE.workflow_params.bind_workflow_copilot_candidate_run(+ organization_id=ctx.organization_id,+ workflow_copilot_chat_id=ctx.workflow_copilot_chat_id,+ expected_owner_turn_id=execution.proposal_owner_turn_id,+ expected_revision=execution.proposal_revision,+ expected_workflow_yaml=execution.workflow_yaml,+ workflow_run_id=workflow_run.workflow_run_id,+ )+ if (+ ctx.proposal_owner_turn_id == execution.proposal_owner_turn_id+ and ctx.proposal_revision == execution.proposal_revision+ and execution.source_is_current(ctx)+ ):+ ctx.proposal_workflow_run_id = workflow_run.workflow_run_id+ except Exception: # noqa: BLE001 - any custody failure must stop dispatch.+ await app.WORKFLOW_SERVICE.mark_workflow_run_as_failed_if_not_final(+ workflow_run_id=workflow_run.workflow_run_id,+ failure_reason="The Copilot proposal changed before its test run started.",+ )+ if dispatch_draft_workflow_id is not None:+ await _delete_dispatch_draft(dispatch_draft_workflow_id, ctx.organization_id)+ dispatch_draft_workflow_id = None+ LOG.info(+ "copilot candidate run bind lost",+ workflow_run_id=workflow_run.workflow_run_id,+ proposal_owner_turn_id=execution.proposal_owner_turn_id,+ proposal_revision=execution.proposal_revision,+ )+ return {+ "ok": False,+ "error": "The pending Copilot proposal changed before the test started; reload and try again.",+ }ctx.dispatched_run_ids_this_turn.add(workflow_run.workflow_run_id)# The ordinary Track-A producer owns this registry at run creation. Keeping the run id and@@ -4181,6 +4241,8 @@ async def _get_run_results("action_trace_summary": action_trace_summary,"action_observations": action_observations,}+ if run_workflow is not None and workflow_run_id == ctx.proposal_workflow_run_id:+ result_data["execution_source"] = _execution_source_facts(run_workflow, provenance="staged")_attach_block_fact_projection(result_data,blocks,diff --git a/skyvern/forge/sdk/copilot/tools/workflow_update.py b/skyvern/forge/sdk/copilot/tools/workflow_update.pyindex d6aa804ba..3dff44c81 100644--- a/skyvern/forge/sdk/copilot/tools/workflow_update.py+++ b/skyvern/forge/sdk/copilot/tools/workflow_update.py@@ -38,6 +38,7 @@ from skyvern.forge.sdk.copilot.build_test_outcome import (record_build_test_outcome,recorded_outcome_from_author_time_reject,)+from skyvern.forge.sdk.copilot.canonical_ownership import workflow_content_fingerprintfrom skyvern.forge.sdk.copilot.code_block_preflight import (advisory_code_block_diagnostics,scanner_advisory_diagnostics,@@ -54,6 +55,7 @@ from skyvern.forge.sdk.copilot.config import BlockAuthoringPolicyfrom skyvern.forge.sdk.copilot.context import (CodeAuthoringRepairContext,CopilotContext,+ ProposalDisposition,)from skyvern.forge.sdk.copilot.credential_fill_fields import CredentialFillFieldfrom skyvern.forge.sdk.copilot.google_connection_notice import (@@ -111,14 +113,24 @@ from skyvern.forge.sdk.copilot.workflow_yaml import (reconcile_workflow_completion_contract,redact_credentials_in_workflow_yaml,runner_code_block_associations,+ with_workflow_yaml_title,)+from skyvern.forge.sdk.db.exceptions import CopilotProposalConflictError+from skyvern.forge.sdk.schemas.workflow_copilot import copilot_proposal_metadatafrom skyvern.forge.sdk.services import google_oauth_servicefrom skyvern.forge.sdk.workflow.exceptions import BaseWorkflowHTTPException, InsecureCodeDetectedfrom skyvern.forge.sdk.workflow.models.block import CodeBlockfrom skyvern.forge.sdk.workflow.models.workflow import Workflowfrom skyvern.forge.sdk.workflow.runtime_completion import contract_from_code_artifact_metadatafrom skyvern.schemas.proxy_location import runtime_proxy_location-from skyvern.schemas.workflows import BlockType+from skyvern.schemas.workflows import (+ BLOCK_YAML_SUBCLASSES,+ BlockType,+ CodeBlockYAML,+ ForLoopBlockYAML,+ WhileLoopBlockYAML,+ WorkflowCreateYAMLRequest,+)from skyvern.utils.templating import get_missing_variablesfrom skyvern.utils.url_validators import validate_webhook_url@@ -3856,8 +3868,42 @@ def _author_time_findings(return findings-async def restore_pending_workflow_proposal(ctx: CopilotContext) -> None:- """Restore only the server's pending proposal, never a prior canonical YAML fallback."""+def _normalized_canvas_for_proposal_restore(+ workflow_yaml: str,+ *,+ inherited_code_version: int | None = None,+) -> WorkflowCreateYAMLRequest:+ """Normalize editor-only empty code outlines before comparing canvas custody.++ The editor submits ``steps: []`` while a persisted code block round-trips that+ same absence as ``steps: null``. Both execute identically, so this representational+ difference must not make an unchanged canonical canvas suppress proposal recovery.+ """+ normalized = _normalize_copilot_yaml(workflow_yaml)+ normalized.webhook_callback_url = normalized.webhook_callback_url or None+ normalized.extra_http_headers = normalized.extra_http_headers or None+ normalized.mask_secrets = bool(normalized.mask_secrets)+ if normalized.code_version is None:+ normalized.code_version = inherited_code_version++ def normalize_blocks(blocks: Sequence[BLOCK_YAML_SUBCLASSES]) -> None:+ for block in blocks:+ if isinstance(block, CodeBlockYAML):+ block.steps = block.steps or None+ block.parameter_keys = block.parameter_keys or None+ elif isinstance(block, (ForLoopBlockYAML, WhileLoopBlockYAML)) and block.loop_blocks:+ normalize_blocks(block.loop_blocks)++ normalize_blocks(normalized.workflow_definition.blocks)+ return normalized+++async def restore_pending_workflow_proposal(+ ctx: CopilotContext,+ *,+ required_workflow_run_id: str | None = None,+) -> None:+ """Restore only the server's pending proposal, optionally constrained to its exact run."""if ctx.staged_workflow is not None or not ctx.workflow_copilot_chat_id:returnchat = await app.DATABASE.workflow_params.get_workflow_copilot_chat_by_id(@@ -3869,6 +3915,42 @@ async def restore_pending_workflow_proposal(ctx: CopilotContext) -> None:proposal = chat.proposed_workflowif not isinstance(proposal, dict):return+ metadata = copilot_proposal_metadata(proposal)+ if metadata is not None:+ # The token records the revision this turn observed, not the one it adopted. A turn that+ # declines the candidate's content still has to supersede it when the model authors an edit,+ # so every early return below this point keeps the token.+ ctx.proposal_owner_turn_id = metadata.owner_turn_id+ ctx.proposal_revision = metadata.revision+ ctx.proposal_canonical_fingerprint = metadata.canonical_fingerprint+ if required_workflow_run_id is not None and (+ metadata is None or metadata.workflow_run_id != required_workflow_run_id+ ):+ LOG.info(+ "copilot_pending_proposal_restore_rejected",+ reason="associated_run_mismatch",+ workflow_permanent_id=ctx.workflow_permanent_id,+ required_workflow_run_id=required_workflow_run_id,+ proposal_workflow_run_id=metadata.workflow_run_id if metadata is not None else None,+ )+ return+ if metadata is not None:+ canonical = await app.DATABASE.workflows.get_workflow_by_permanent_id(+ workflow_permanent_id=ctx.workflow_permanent_id,+ organization_id=ctx.organization_id,+ )+ observed_fingerprint = (+ workflow_content_fingerprint(canonical.model_dump(mode="json")) if canonical is not None else None+ )+ if canonical is None or observed_fingerprint != metadata.canonical_fingerprint:+ LOG.info(+ "copilot_pending_proposal_restore_rejected",+ reason="canonical_fingerprint_mismatch",+ workflow_permanent_id=ctx.workflow_permanent_id,+ expected_canonical_fingerprint=metadata.canonical_fingerprint,+ observed_canonical_fingerprint=observed_fingerprint,+ )+ returnworkflow_yaml = proposal.get("_copilot_yaml")if not isinstance(workflow_yaml, str) or not workflow_yaml:return@@ -3876,11 +3958,23 @@ async def restore_pending_workflow_proposal(ctx: CopilotContext) -> None:# An explicit canvas edit remains the model's input to the normal update tool.# Only restore over the persisted canvas or the same pending proposal.try:- submitted = _normalize_copilot_yaml(ctx.workflow_yaml)known_sources = [workflow_yaml]if ctx.persisted_workflow_yaml:known_sources.append(ctx.persisted_workflow_yaml)- if all(submitted != _normalize_copilot_yaml(source) for source in known_sources):+ source_canvases = [_normalized_canvas_for_proposal_restore(source) for source in known_sources]+ if all(+ _normalized_canvas_for_proposal_restore(+ ctx.workflow_yaml,+ inherited_code_version=source.code_version,+ )+ != source+ for source in source_canvases+ ):+ LOG.info(+ "copilot_pending_proposal_restore_rejected",+ reason="canvas_custody_mismatch",+ workflow_permanent_id=ctx.workflow_permanent_id,+ )returnexcept (yaml.YAMLError, ValidationError):return@@ -3923,6 +4017,59 @@ async def restore_pending_workflow_proposal(ctx: CopilotContext) -> None:ctx.workflow_yaml = workflow_yamlctx.last_workflow = workflowctx.last_workflow_yaml = workflow_yaml+ if metadata is not None:+ ctx.proposal_workflow_run_id = metadata.workflow_run_id+++def _candidate_proposal_data(workflow: Workflow, workflow_yaml: str, ctx: CopilotContext) -> dict[str, Any]:+ proposal = dict(workflow.model_dump(mode="json"))+ proposal["_copilot_yaml"] = workflow_yaml+ proposal["_copilot_unvalidated"] = True+ if ctx.code_artifact_metadata:+ proposal["_copilot_code_artifact_metadata"] = ctx.code_artifact_metadata+ return proposal+++async def publish_workflow_candidate(+ ctx: CopilotContext,+ *,+ workflow: Workflow,+ workflow_yaml: str,+ disposition: ProposalDisposition = "review_untested",+) -> str:+ """Durably publish admitted bytes before they become staged or visible.++ Returns the bytes that were stored. Accept reparses them without going back through+ ``_process_workflow_yaml``, so the title is resolved here — once, before the first durable+ write — and callers stage what was stored so every later equality check compares like with like.+ """+ if not ctx.workflow_copilot_chat_id:+ return workflow_yaml+ workflow_yaml = with_workflow_yaml_title(workflow_yaml, workflow.title)+ canonical = await app.DATABASE.workflows.get_workflow_by_permanent_id(+ workflow_permanent_id=ctx.workflow_permanent_id,+ organization_id=ctx.organization_id,+ )+ if canonical is None:+ raise RuntimeError("Canonical workflow disappeared before candidate publication")+ updated_chat = await app.DATABASE.workflow_params.publish_workflow_copilot_candidate(+ organization_id=ctx.organization_id,+ workflow_copilot_chat_id=ctx.workflow_copilot_chat_id,+ proposal=_candidate_proposal_data(workflow, workflow_yaml, ctx),+ owner_turn_id=ctx.turn_id,+ canonical_fingerprint=workflow_content_fingerprint(canonical.model_dump(mode="json")),+ disposition=disposition,+ expected_owner_turn_id=ctx.proposal_owner_turn_id,+ expected_revision=ctx.proposal_revision,+ )+ metadata = copilot_proposal_metadata(updated_chat.proposed_workflow)+ if metadata is None:+ raise RuntimeError("Candidate publication returned no ownership token")+ ctx.proposal_owner_turn_id = metadata.owner_turn_id+ ctx.proposal_revision = metadata.revision+ ctx.proposal_canonical_fingerprint = metadata.canonical_fingerprint+ ctx.proposal_workflow_run_id = metadata.workflow_run_id+ return workflow_yamlasync def _update_workflow(@@ -4175,10 +4322,38 @@ async def _update_workflow(# Runs materialize this proposal as their own version. The saved workflow# remains unchanged until Accept, including parameter and setting edits.- ctx.staged_workflow_yaml = workflow_yaml- ctx.staged_workflow = workflow- ctx.has_staged_proposal = True- ctx.workflow_yaml = workflow_yaml+ if isinstance(ctx, CopilotContext):+ # The durable write and the staged fields it backs move together, so a parallel tool+ # call cannot read a staged draft the store has not accepted.+ async with ctx.proposal_mutation_lock:+ try:+ workflow_yaml = await publish_workflow_candidate(+ ctx, workflow=workflow, workflow_yaml=workflow_yaml+ )+ except CopilotProposalConflictError as conflict:+ LOG.info(+ "copilot_candidate_publication_conflict",+ workflow_permanent_id=ctx.workflow_permanent_id,+ proposal_owner_turn_id=ctx.proposal_owner_turn_id,+ proposal_revision=ctx.proposal_revision,+ error=str(conflict),+ )+ return {+ "ok": False,+ "error": (+ "The pending proposal changed while this edit was being saved, so nothing was written. "+ "Read the current workflow again before re-submitting this edit."+ ),+ }+ ctx.staged_workflow_yaml = workflow_yaml+ ctx.staged_workflow = workflow+ ctx.has_staged_proposal = True+ ctx.workflow_yaml = workflow_yaml+ else:+ ctx.staged_workflow_yaml = workflow_yaml+ ctx.staged_workflow = workflow+ ctx.has_staged_proposal = True+ ctx.workflow_yaml = workflow_yamlif isinstance(ctx, CopilotContext):ctx.runner_code_block_associations_by_label = runner_code_block_associations(workflow_yaml,diff --git a/skyvern/forge/sdk/db/exceptions.py b/skyvern/forge/sdk/db/exceptions.pyindex e74196e77..6bebe0654 100644--- a/skyvern/forge/sdk/db/exceptions.py+++ b/skyvern/forge/sdk/db/exceptions.py@@ -36,6 +36,10 @@ class DuplicateCopilotTurnError(Exception):self.turn_id = turn_id+class CopilotProposalConflictError(Exception):+ """The candidate changed after the caller read its owner/revision token."""++class ScheduleLimitExceededError(Exception):"""Raised when attempting to create a schedule that would exceed the org-wide tier limit."""diff --git a/skyvern/forge/sdk/db/repositories/workflow_parameters.py b/skyvern/forge/sdk/db/repositories/workflow_parameters.pyindex e03958817..6fa5866e4 100644--- a/skyvern/forge/sdk/db/repositories/workflow_parameters.py+++ b/skyvern/forge/sdk/db/repositories/workflow_parameters.py@@ -21,12 +21,13 @@ from skyvern.forge.sdk.copilot.ask_user import (resolve_question_response,)from skyvern.forge.sdk.copilot.completion_criteria_store import criteria_from_json, criterion_authority_projection-from skyvern.forge.sdk.copilot.context import TurnNarrativePayload+from skyvern.forge.sdk.copilot.context import ProposalDisposition, TurnNarrativePayloadfrom skyvern.forge.sdk.db._error_handling import db_operationfrom skyvern.forge.sdk.db._sentinels import _UNSETfrom skyvern.forge.sdk.db.base_alchemy_db import read_with_disconnect_recoveryfrom skyvern.forge.sdk.db.base_repository import BaseRepositoryfrom skyvern.forge.sdk.db.exceptions import (+ CopilotProposalConflictError,DatabaseConnectionUnavailableError,DuplicateCopilotTurnError,NotFoundError,@@ -65,14 +66,18 @@ from skyvern.forge.sdk.schemas.copilot_turn_outcome import TurnOutcomefrom skyvern.forge.sdk.schemas.task_generations import TaskGenerationfrom skyvern.forge.sdk.schemas.tasks import Task, TaskStatusfrom skyvern.forge.sdk.schemas.workflow_copilot import (+ COPILOT_PROPOSAL_METADATA_KEY,CopilotAttachedFile,+ CopilotCandidateDisposition,CopilotPendingTurn,+ CopilotProposalMetadata,NonAdoptableCriteriaSet,WorkflowCopilotChat,WorkflowCopilotChatMessage,WorkflowCopilotChatSender,WorkflowCopilotChatSummary,WorkflowCopilotCompletionCriteriaSet,+ copilot_proposal_metadata,)from skyvern.forge.sdk.trace import tracedfrom skyvern.forge.sdk.workflow.models.parameter import (@@ -719,12 +724,19 @@ class WorkflowParametersRepository(BaseRepository):select(WorkflowCopilotChatModel).where(WorkflowCopilotChatModel.organization_id == organization_id).where(WorkflowCopilotChatModel.workflow_copilot_chat_id == workflow_copilot_chat_id)+ .with_for_update())).first()if not chat:return Noneif proposed_workflow is not _UNSET:+ # Callers here read the chat before they write it. An owned candidate published in+ # between owns the row, and only its own compare-and-set may replace it.+ if copilot_proposal_metadata(chat.proposed_workflow) is not None and (+ copilot_proposal_metadata(proposed_workflow) is None+ ):+ raise CopilotProposalConflictError("Copilot proposal is owned by a newer candidate")chat.proposed_workflow = proposed_workflowif auto_accept is not None:chat.auto_accept = auto_accept@@ -735,6 +747,223 @@ class WorkflowParametersRepository(BaseRepository):await session.refresh(chat)return WorkflowCopilotChat.model_validate(chat)+ async def _locked_copilot_chat(+ self, session: AsyncSession, organization_id: str, workflow_copilot_chat_id: str+ ) -> WorkflowCopilotChatModel:+ chat = (+ await session.scalars(+ select(WorkflowCopilotChatModel)+ .where(WorkflowCopilotChatModel.organization_id == organization_id)+ .where(WorkflowCopilotChatModel.workflow_copilot_chat_id == workflow_copilot_chat_id)+ .with_for_update()+ )+ ).first()+ if chat is None:+ raise NotFoundError(f"workflow copilot chat {workflow_copilot_chat_id}")+ return chat++ @staticmethod+ def _require_candidate_token(+ proposal: object, expected_owner_turn_id: str | None, expected_revision: int | None+ ) -> CopilotProposalMetadata | None:+ current = copilot_proposal_metadata(proposal)+ if current is None:+ if isinstance(proposal, Mapping) and COPILOT_PROPOSAL_METADATA_KEY in proposal:+ raise CopilotProposalConflictError("Copilot proposal metadata is invalid")+ if expected_owner_turn_id is not None or expected_revision is not None:+ raise CopilotProposalConflictError("Copilot proposal changed")+ return None+ if current.owner_turn_id != expected_owner_turn_id or current.revision != expected_revision:+ raise CopilotProposalConflictError("Copilot proposal changed")+ return current++ @db_operation("publish_workflow_copilot_candidate", expected_errors=(CopilotProposalConflictError,))+ async def publish_workflow_copilot_candidate(+ self,+ organization_id: str,+ workflow_copilot_chat_id: str,+ *,+ proposal: dict[str, Any],+ owner_turn_id: str,+ canonical_fingerprint: str,+ disposition: ProposalDisposition,+ expected_owner_turn_id: str | None,+ expected_revision: int | None,+ ) -> WorkflowCopilotChat:+ async with self.Session() as session:+ chat = await self._locked_copilot_chat(session, organization_id, workflow_copilot_chat_id)+ current = self._require_candidate_token(chat.proposed_workflow, expected_owner_turn_id, expected_revision)+ if current is not None and current.claim_is_live(datetime.now(timezone.utc)):+ # The accept between its claim and its canonical write is committing bytes it has+ # already read; replacing them underneath it would make it write a stale workflow.+ raise CopilotProposalConflictError("Copilot proposal is being accepted")+ revision = current.revision + 1 if current is not None and current.owner_turn_id == owner_turn_id else 1+ metadata = CopilotProposalMetadata(+ owner_turn_id=owner_turn_id,+ revision=revision,+ canonical_fingerprint=canonical_fingerprint,+ disposition=disposition,+ )+ chat.proposed_workflow = {+ **proposal,+ COPILOT_PROPOSAL_METADATA_KEY: metadata.model_dump(mode="json"),+ }+ await session.commit()+ await session.refresh(chat)+ return WorkflowCopilotChat.model_validate(chat)++ @db_operation("enrich_workflow_copilot_candidate", expected_errors=(CopilotProposalConflictError,))+ async def enrich_workflow_copilot_candidate(+ self,+ organization_id: str,+ workflow_copilot_chat_id: str,+ *,+ proposal: dict[str, Any],+ expected_owner_turn_id: str,+ expected_revision: int,+ disposition: ProposalDisposition,+ ) -> WorkflowCopilotChat:+ async with self.Session() as session:+ chat = await self._locked_copilot_chat(session, organization_id, workflow_copilot_chat_id)+ current = self._require_candidate_token(chat.proposed_workflow, expected_owner_turn_id, expected_revision)+ if current is None or not isinstance(chat.proposed_workflow, dict):+ raise CopilotProposalConflictError("Copilot proposal changed")+ if current.claim_is_live(datetime.now(timezone.utc)):+ raise CopilotProposalConflictError("Copilot proposal is being accepted")+ if chat.proposed_workflow.get("_copilot_yaml") != proposal.get("_copilot_yaml"):+ raise CopilotProposalConflictError("Copilot proposal bytes changed")+ current_workflow = {+ key: value for key, value in chat.proposed_workflow.items() if not key.startswith("_copilot_")+ }+ proposed_workflow = {key: value for key, value in proposal.items() if not key.startswith("_copilot_")}+ if current_workflow != proposed_workflow:+ raise CopilotProposalConflictError("Copilot proposal content changed")+ metadata = current.model_copy(update={"disposition": disposition})+ chat.proposed_workflow = {+ **proposal,+ COPILOT_PROPOSAL_METADATA_KEY: metadata.model_dump(mode="json"),+ }+ await session.commit()+ await session.refresh(chat)+ return WorkflowCopilotChat.model_validate(chat)++ @db_operation("bind_workflow_copilot_candidate_run", expected_errors=(CopilotProposalConflictError,))+ async def bind_workflow_copilot_candidate_run(+ self,+ organization_id: str,+ workflow_copilot_chat_id: str,+ *,+ expected_owner_turn_id: str,+ expected_revision: int,+ expected_workflow_yaml: str,+ workflow_run_id: str,+ ) -> WorkflowCopilotChat:+ async with self.Session() as session:+ chat = await self._locked_copilot_chat(session, organization_id, workflow_copilot_chat_id)+ current = self._require_candidate_token(chat.proposed_workflow, expected_owner_turn_id, expected_revision)+ if current is None or not isinstance(chat.proposed_workflow, dict):+ raise CopilotProposalConflictError("Copilot proposal changed")+ if current.claim_is_live(datetime.now(timezone.utc)):+ raise CopilotProposalConflictError("Copilot proposal is being accepted")+ if chat.proposed_workflow.get("_copilot_yaml") != expected_workflow_yaml:+ raise CopilotProposalConflictError("Copilot proposal bytes changed")+ metadata = current.model_copy(update={"workflow_run_id": workflow_run_id})+ chat.proposed_workflow = {+ **chat.proposed_workflow,+ COPILOT_PROPOSAL_METADATA_KEY: metadata.model_dump(mode="json"),+ }+ await session.commit()+ await session.refresh(chat)+ return WorkflowCopilotChat.model_validate(chat)++ @db_operation("claim_workflow_copilot_candidate", expected_errors=(CopilotProposalConflictError,))+ async def claim_workflow_copilot_candidate(+ self,+ organization_id: str,+ workflow_copilot_chat_id: str,+ *,+ expected_owner_turn_id: str,+ expected_revision: int,+ ) -> WorkflowCopilotChat:+ async with self.Session() as session:+ chat = await self._locked_copilot_chat(session, organization_id, workflow_copilot_chat_id)+ current = self._require_candidate_token(chat.proposed_workflow, expected_owner_turn_id, expected_revision)+ if (+ current is None+ or not isinstance(chat.proposed_workflow, dict)+ or current.claim_is_live(datetime.now(timezone.utc))+ ):+ raise CopilotProposalConflictError("Copilot proposal changed")+ metadata = current.model_copy(update={"disposition": "accepting", "claimed_at": datetime.now(timezone.utc)})+ chat.proposed_workflow = {+ **chat.proposed_workflow,+ COPILOT_PROPOSAL_METADATA_KEY: metadata.model_dump(mode="json"),+ }+ await session.commit()+ await session.refresh(chat)+ return WorkflowCopilotChat.model_validate(chat)++ @db_operation("release_workflow_copilot_candidate_claim", expected_errors=(CopilotProposalConflictError,))+ async def release_workflow_copilot_candidate_claim(+ self,+ organization_id: str,+ workflow_copilot_chat_id: str,+ *,+ expected_owner_turn_id: str,+ expected_revision: int,+ expected_claimed_at: datetime | None,+ disposition: ProposalDisposition,+ ) -> WorkflowCopilotChat:+ async with self.Session() as session:+ chat = await self._locked_copilot_chat(session, organization_id, workflow_copilot_chat_id)+ current = self._require_candidate_token(chat.proposed_workflow, expected_owner_turn_id, expected_revision)+ # The token names the candidate and survives a takeover, so only the claim timestamp+ # tells one holder's claim from its successor's.+ if (+ current is None+ or not isinstance(chat.proposed_workflow, dict)+ or current.disposition != "accepting"+ or current.claimed_at != expected_claimed_at+ ):+ raise CopilotProposalConflictError("Copilot proposal claim changed")+ metadata = current.model_copy(update={"disposition": disposition, "claimed_at": None})+ chat.proposed_workflow = {+ **chat.proposed_workflow,+ COPILOT_PROPOSAL_METADATA_KEY: metadata.model_dump(mode="json"),+ }+ await session.commit()+ await session.refresh(chat)+ return WorkflowCopilotChat.model_validate(chat)++ @db_operation("clear_workflow_copilot_candidate", expected_errors=(CopilotProposalConflictError,))+ async def clear_workflow_copilot_candidate(+ self,+ organization_id: str,+ workflow_copilot_chat_id: str,+ *,+ expected_owner_turn_id: str | None,+ expected_revision: int | None,+ expected_disposition: CopilotCandidateDisposition | None = None,+ expected_claimed_at: datetime | None = None,+ auto_accept: bool | None = None,+ ) -> WorkflowCopilotChat:+ async with self.Session() as session:+ chat = await self._locked_copilot_chat(session, organization_id, workflow_copilot_chat_id)+ current = self._require_candidate_token(chat.proposed_workflow, expected_owner_turn_id, expected_revision)+ if current is not None and (+ (expected_disposition is None and current.claim_is_live(datetime.now(timezone.utc)))+ or (expected_disposition is not None and current.disposition != expected_disposition)+ # A claim the caller named must still be the one it took; see release above.+ or (expected_claimed_at is not None and current.claimed_at != expected_claimed_at)+ ):+ raise CopilotProposalConflictError("Copilot proposal disposition changed")+ chat.proposed_workflow = None+ if auto_accept is not None:+ chat.auto_accept = auto_accept+ await session.commit()+ await session.refresh(chat)+ return WorkflowCopilotChat.model_validate(chat)+@db_operation("create_workflow_copilot_chat_message")async def create_workflow_copilot_chat_message(self,diff --git a/skyvern/forge/sdk/routes/workflow_copilot.py b/skyvern/forge/sdk/routes/workflow_copilot.pyindex d234ec2a4..21135b8b6 100644--- a/skyvern/forge/sdk/routes/workflow_copilot.py+++ b/skyvern/forge/sdk/routes/workflow_copilot.py@@ -3,6 +3,7 @@ import contextlibimport contextvarsimport hashlibimport hmac+import jsonimport reimport uuidfrom collections.abc import Iterator@@ -77,16 +78,24 @@ from skyvern.forge.sdk.copilot.workflow_yaml import _repair_next_block_label_chafrom skyvern.forge.sdk.copilot.workflow_yaml import with_workflow_yaml_titlefrom skyvern.forge.sdk.core import skyvern_contextfrom skyvern.forge.sdk.core.event_source_stream import EventSourceStream, FastAPIEventSourceStream-from skyvern.forge.sdk.db.exceptions import DatabaseConnectionUnavailableError, DuplicateCopilotTurnError, NotFoundError+from skyvern.forge.sdk.db.exceptions import (+ CopilotProposalConflictError,+ DatabaseConnectionUnavailableError,+ DuplicateCopilotTurnError,+ NotFoundError,+)from skyvern.forge.sdk.routes.routers import base_routerfrom skyvern.forge.sdk.schemas.copilot_turn_outcome import PersistedCopilotComposerMode, ResponseKind, TurnOutcomefrom skyvern.forge.sdk.schemas.organizations import Organizationfrom skyvern.forge.sdk.schemas.workflow_copilot import (+ COPILOT_PROPOSAL_METADATA_KEY,TURN_OPENER_SENDERS,CopilotAttachedFile,CopilotCancelSource,CopilotFailureKind,CopilotPendingTurn,+ CopilotProposalMetadata,+ CopilotProposalRunFacts,WorkflowCopilotApplyProposedWorkflowRequest,WorkflowCopilotAudioUploadResponse,WorkflowCopilotBrowserAblationResponseUpdate,@@ -107,6 +116,7 @@ from skyvern.forge.sdk.schemas.workflow_copilot import (WorkflowCopilotStreamResponseUpdate,WorkflowYAMLConversionRequest,WorkflowYAMLConversionResponse,+ copilot_proposal_metadata,)from skyvern.forge.sdk.services import org_auth_servicefrom skyvern.forge.sdk.workflow.exceptions import BaseWorkflowHTTPException@@ -643,11 +653,41 @@ def _build_recoverable_route_agent_result(async def _clear_proposed_workflow(chat: Any) -> None:- await app.DATABASE.workflow_params.update_workflow_copilot_chat(- organization_id=chat.organization_id,- workflow_copilot_chat_id=chat.workflow_copilot_chat_id,- proposed_workflow=None,- )+ metadata = copilot_proposal_metadata(chat.proposed_workflow)+ if metadata is not None or (+ isinstance(chat.proposed_workflow, dict) and COPILOT_PROPOSAL_METADATA_KEY in chat.proposed_workflow+ ):+ try:+ await app.DATABASE.workflow_params.clear_workflow_copilot_candidate(+ organization_id=chat.organization_id,+ workflow_copilot_chat_id=chat.workflow_copilot_chat_id,+ expected_owner_turn_id=metadata.owner_turn_id if metadata is not None else None,+ expected_revision=metadata.revision if metadata is not None else None,+ )+ except CopilotProposalConflictError:+ # The row moved on: whatever holds it now is newer than the proposal being cleared,+ # and clearing is not worth failing the turn the user is waiting on.+ LOG.info(+ "copilot_candidate_clear_conflict",+ workflow_copilot_chat_id=chat.workflow_copilot_chat_id,+ )+ return+ else:+ try:+ await app.DATABASE.workflow_params.update_workflow_copilot_chat(+ organization_id=chat.organization_id,+ workflow_copilot_chat_id=chat.workflow_copilot_chat_id,+ proposed_workflow=None,+ )+ except CopilotProposalConflictError:+ # The branch above was chosen from an in-memory read; the row gained an owned+ # candidate since, and that candidate is newer than the one being cleared.+ LOG.info(+ "copilot_candidate_clear_conflict",+ workflow_copilot_chat_id=chat.workflow_copilot_chat_id,+ branch="untyped",+ )+ return# Keep the in-memory chat in sync — a same-turn recovery retry reads# chat.proposed_workflow again and must not see the pre-write value.chat.proposed_workflow = None@@ -676,18 +716,132 @@ def _output_policy_blocked_final_response(agent_result: AgentResult) -> bool:return isinstance(diagnostics, dict) and diagnostics.get("final_output_policy_allowed") is False+def _client_sent_no_proposal_token(owner_turn_id: str | None, revision: int | None) -> bool:+ """Whether the caller predates proposal tokens entirely.++ A frontend deployed before this change never sends them, and one already open in a tab outlives+ the rollout. Such a client is acting on whatever the chat currently holds, which is how this+ endpoint behaved before tokens existed; the canonical and claim checks still apply.+ """+ return owner_turn_id is None and revision is None+++async def _proposal_ownership_is_current(chat: Any, agent_result: AgentResult) -> bool:+ """Whether the candidate this result authored is still the one the chat row holds.++ A turn that lost the candidate must not commit canonical state, so this is asked before the+ auto-accept write as well as before the proposal write.+ """+ if agent_result.proposal_owner_turn_id is None or agent_result.proposal_revision is None:+ return True+ current_chat = await app.DATABASE.workflow_params.get_workflow_copilot_chat_by_id(+ organization_id=chat.organization_id,+ workflow_copilot_chat_id=chat.workflow_copilot_chat_id,+ )+ if current_chat is None:+ raise NotFoundError(f"workflow copilot chat {chat.workflow_copilot_chat_id}")+ chat.proposed_workflow = current_chat.proposed_workflow+ current_metadata = copilot_proposal_metadata(current_chat.proposed_workflow)+ return (+ current_metadata is not None+ and current_metadata.owner_turn_id == agent_result.proposal_owner_turn_id+ and current_metadata.revision == agent_result.proposal_revision+ )+++def _discard_superseded_proposal(agent_result: AgentResult) -> None:+ agent_result.updated_workflow = None+ agent_result.has_staged_proposal = False+ agent_result.proposal_disposition = "no_proposal"+ agent_result.clear_proposed_workflow = False++async def _persist_proposed_workflow_state(chat: Any, agent_result: AgentResult, restored: bool, keep_pending_proposal: bool = False) -> None:updated_workflow = agent_result.updated_workflow+ if not await _proposal_ownership_is_current(chat, agent_result):+ _discard_superseded_proposal(agent_result)+ returnauto_accept_effective = _effective_auto_accept(chat.auto_accept, agent_result)if not auto_accept_effective and updated_workflow:proposed_workflow_data = _build_proposed_workflow_data(updated_workflow, agent_result)- await app.DATABASE.workflow_params.update_workflow_copilot_chat(- organization_id=chat.organization_id,- workflow_copilot_chat_id=chat.workflow_copilot_chat_id,- proposed_workflow=proposed_workflow_data,- )+ if agent_result.proposal_owner_turn_id is not None and agent_result.proposal_revision is not None:+ stored_metadata = copilot_proposal_metadata(chat.proposed_workflow)+ same_bytes = isinstance(chat.proposed_workflow, dict) and chat.proposed_workflow.get(+ "_copilot_yaml"+ ) == proposed_workflow_data.get("_copilot_yaml")+ if same_bytes:+ # Same candidate: keep the bytes publication stored and overlay only this turn's+ # markers. Those bytes carry the resolved title and Accept reparses them as they are.+ proposed_workflow_data = {+ **chat.proposed_workflow,+ **{key: value for key, value in proposed_workflow_data.items() if key.startswith("_copilot_")},+ }+ if _proposal_disposition(agent_result) != "review_untested":+ # The marker is only ever added, so a candidate published untested and since+ # tested would keep claiming otherwise — and the auto-accept cleanup deletes+ # whatever still carries it.+ proposed_workflow_data.pop("_copilot_unvalidated", None)+ try:+ if same_bytes or stored_metadata is None:+ updated_chat = await app.DATABASE.workflow_params.enrich_workflow_copilot_candidate(+ organization_id=chat.organization_id,+ workflow_copilot_chat_id=chat.workflow_copilot_chat_id,+ proposal=proposed_workflow_data,+ expected_owner_turn_id=agent_result.proposal_owner_turn_id,+ expected_revision=agent_result.proposal_revision,+ disposition=_proposal_disposition(agent_result),+ )+ else:+ # The turn's answer is a different workflow — a salvaged last-good shape after a+ # later edit failed. That is a new candidate, not a marker update, so it takes a+ # revision of its own; enriching would be refused for changing the bytes and+ # would leave the failed draft durable behind the card.+ updated_chat = await app.DATABASE.workflow_params.publish_workflow_copilot_candidate(+ organization_id=chat.organization_id,+ workflow_copilot_chat_id=chat.workflow_copilot_chat_id,+ proposal=proposed_workflow_data,+ owner_turn_id=agent_result.proposal_owner_turn_id,+ canonical_fingerprint=stored_metadata.canonical_fingerprint,+ disposition=_proposal_disposition(agent_result),+ expected_owner_turn_id=agent_result.proposal_owner_turn_id,+ expected_revision=agent_result.proposal_revision,+ )+ republished = copilot_proposal_metadata(updated_chat.proposed_workflow)+ if republished is not None:+ # The terminal frame carries this token, so it has to name the revision the+ # user is about to act on.+ agent_result.proposal_revision = republished.revision+ except CopilotProposalConflictError:+ # Losing this race means the stored candidate is already someone else's and is+ # already correct. The turn gives up its claim and still delivers its reply.+ LOG.info(+ "copilot_candidate_enrich_conflict",+ workflow_copilot_chat_id=chat.workflow_copilot_chat_id,+ proposal_owner_turn_id=agent_result.proposal_owner_turn_id,+ proposal_revision=agent_result.proposal_revision,+ )+ _discard_superseded_proposal(agent_result)+ return+ stored_proposal = updated_chat.proposed_workflow+ if stored_proposal is not None:+ proposed_workflow_data = stored_proposal+ else:+ try:+ await app.DATABASE.workflow_params.update_workflow_copilot_chat(+ organization_id=chat.organization_id,+ workflow_copilot_chat_id=chat.workflow_copilot_chat_id,+ proposed_workflow=proposed_workflow_data,+ )+ except CopilotProposalConflictError:+ LOG.info(+ "copilot_candidate_enrich_conflict",+ workflow_copilot_chat_id=chat.workflow_copilot_chat_id,+ branch="untyped",+ )+ _discard_superseded_proposal(agent_result)+ return# Keep the in-memory chat in sync — a same-turn recovery retry reads# chat.proposed_workflow again and must not see the pre-write value.chat.proposed_workflow = proposed_workflow_data@@ -1173,6 +1327,7 @@ async def _persist_cancel_turn(resolved_model=resolved_model,proposal_disposition=proposal_disposition,workflow_applied=workflow_applied,+ proposed_workflow_metadata=copilot_proposal_metadata(chat.proposed_workflow),cancelled=True,output_policy_diagnostics=output_policy_diagnostics,turn_id=response_turn_id,@@ -1208,7 +1363,6 @@ async def _finalise_normal_turn((e.g. proposed_workflow updated but no AI message persisted)."""user_response = agent_result.user_response- updated_workflow = agent_result.updated_workflowupdated_global_llm_context = agent_result.global_llm_contextidempotency_digest = _copilot_idempotency_digest(organization_id,@@ -1241,6 +1395,10 @@ async def _finalise_normal_turn(LOG.warning("copilot restore failed in _finalise_normal_turn", exc_info=True)restore_failed = True+ if not await _proposal_ownership_is_current(chat, agent_result):+ # This turn no longer owns the candidate, so it has no standing to commit canonical state.+ _discard_superseded_proposal(agent_result)+if _should_commit_staged_workflow(chat.auto_accept, agent_result):try:await _commit_staged_workflow(@@ -1267,6 +1425,10 @@ async def _finalise_normal_turn(# don't honor keep_pending_proposal against an unverified "nothing changed" state.keep_pending_proposal=chat_request.keep_pending_proposal and not restore_failed,)+ # Read after persisting, never before: persisting drops this turn's proposal when a newer+ # candidate owns the row, and the frame below must not pair a dropped draft with that+ # candidate's token.+ updated_workflow = agent_result.updated_workflowproposal_disposition = _proposal_disposition(agent_result)workflow_applied = _effective_auto_accept(chat.auto_accept, agent_result)narrative_payload = _with_terminal_narrative_metadata(@@ -1301,6 +1463,7 @@ async def _finalise_normal_turn("resolved_model": agent_result.resolved_model,"proposal_disposition": proposal_disposition,"workflow_applied": workflow_applied,+ "proposed_workflow_metadata": copilot_proposal_metadata(chat.proposed_workflow),"output_policy_diagnostics": agent_result.output_policy_diagnostics,"turn_id": agent_result.turn_id,"narrative_summary": narrative_summary,@@ -2685,7 +2848,14 @@ async def _restore_canonical_after_interrupted_turn(if workflow_content_fingerprint(current.model_dump(mode="json")) != entry.canonical_write_fingerprint:return False- if not (entry.keep_pending_proposal and entry.pre_turn_proposed_workflow is not None):+ current_chat = await app.DATABASE.workflow_params.get_workflow_copilot_chat_by_id(+ organization_id=organization_id,+ workflow_copilot_chat_id=chat.workflow_copilot_chat_id,+ )+ durable_proposal = current_chat.proposed_workflow if current_chat is not None else None+ if copilot_proposal_metadata(durable_proposal) is not None:+ chat.proposed_workflow = durable_proposal+ elif not (entry.keep_pending_proposal and entry.pre_turn_proposed_workflow is not None):stashed_draft = current.model_dump(mode="json")await app.DATABASE.workflow_params.update_workflow_copilot_chat(organization_id=organization_id,@@ -2813,6 +2983,65 @@ async def _reconcile_interrupted_copilot_turns(chat: WorkflowCopilotChat, organi)+MAX_PROPOSAL_OUTPUT_VALUE_CHARS = 2000+++def _bounded_output_value(value: Any) -> Any:+ """The card renders each output as one line, so a large extraction is only response weight."""+ try:+ serialized = json.dumps(value, default=str)+ except (TypeError, ValueError):+ return value+ if len(serialized) <= MAX_PROPOSAL_OUTPUT_VALUE_CHARS:+ return value+ return f"{serialized[:MAX_PROPOSAL_OUTPUT_VALUE_CHARS]}… truncated from {len(serialized)} characters"+++async def _history_proposal_state(+ chat: WorkflowCopilotChat | None, organization_id: str+) -> tuple[dict[str, Any] | None, CopilotProposalMetadata | None, CopilotProposalRunFacts | None]:+ if chat is None or not isinstance(chat.proposed_workflow, dict):+ return None, None, None+ metadata = copilot_proposal_metadata(chat.proposed_workflow)+ if metadata is None:+ return chat.proposed_workflow, None, None+ # A live claim is reported, not hidden. A server that dies mid-accept leaves the claim behind+ # for the length of the lease, and withholding the card for that long is the invisible-work+ # problem this store exists to remove; Accept meanwhile answers 409 and the client refetches.+ canonical = await app.DATABASE.workflows.get_workflow_by_permanent_id(+ workflow_permanent_id=chat.workflow_permanent_id,+ organization_id=organization_id,+ )+ if (+ canonical is None+ or workflow_content_fingerprint(canonical.model_dump(mode="json")) != metadata.canonical_fingerprint+ ):+ return None, None, None+ run_facts = None+ if metadata.workflow_run_id is not None:+ run = await app.DATABASE.workflow_runs.get_workflow_run(+ workflow_run_id=metadata.workflow_run_id,+ organization_id=organization_id,+ )+ available = run is not None and run.workflow_permanent_id == chat.workflow_permanent_id+ output_rows = (+ await app.DATABASE.workflow_runs.get_workflow_run_output_parameters(metadata.workflow_run_id)+ if available+ else []+ )+ run_facts = CopilotProposalRunFacts(+ workflow_run_id=metadata.workflow_run_id,+ status=str(run.status) if available else None,+ available=available,+ failure_reason=run.failure_reason if available else None,+ outputs=[+ {"output_parameter_id": row.output_parameter_id, "value": _bounded_output_value(row.value)}+ for row in output_rows+ ],+ )+ return chat.proposed_workflow, metadata, run_facts++@base_router.get("/workflow/copilot/chat-history", include_in_schema=False)async def workflow_copilot_chat_history(credential_recovery_token: str | None = Header(None, alias="X-Copilot-Credential-Recovery-Token"),@@ -2848,6 +3077,9 @@ async def workflow_copilot_chat_history()else:chat_messages = []+ proposed_workflow, proposed_workflow_metadata, proposed_workflow_run = await _history_proposal_state(+ chat, organization.organization_id+ )return WorkflowCopilotChatHistoryResponse(pending_credential_requests=await pending_credential_requests(organization.organization_id,@@ -2885,7 +3117,9 @@ async def workflow_copilot_chat_history(None,),chat_history=await _history_with_resolved_attachments(chat_messages, organization.organization_id),- proposed_workflow=chat.proposed_workflow if chat else None,+ proposed_workflow=proposed_workflow,+ proposed_workflow_metadata=proposed_workflow_metadata,+ proposed_workflow_run=proposed_workflow_run,auto_accept=chat.auto_accept if chat else None,work_plan=chat.work_plan if chat else [],)@@ -3057,14 +3291,29 @@ async def workflow_copilot_clear_proposed_workflow(clear_request: WorkflowCopilotClearProposedWorkflowRequest,organization: Organization = Depends(org_auth_service.get_current_org),) -> None:- updated_chat = await app.DATABASE.workflow_params.update_workflow_copilot_chat(- organization_id=organization.organization_id,- workflow_copilot_chat_id=clear_request.workflow_copilot_chat_id,- proposed_workflow=None,- auto_accept=clear_request.auto_accept,- )- if not updated_chat:+ expected_owner_turn_id = clear_request.owner_turn_id+ expected_revision = clear_request.revision+ if _client_sent_no_proposal_token(expected_owner_turn_id, expected_revision):+ chat = await app.DATABASE.workflow_params.get_workflow_copilot_chat_by_id(+ organization_id=organization.organization_id,+ workflow_copilot_chat_id=clear_request.workflow_copilot_chat_id,+ )+ stored = copilot_proposal_metadata(chat.proposed_workflow) if chat is not None else None+ if stored is not None:+ expected_owner_turn_id = stored.owner_turn_id+ expected_revision = stored.revision+ try:+ await app.DATABASE.workflow_params.clear_workflow_copilot_candidate(+ organization_id=organization.organization_id,+ workflow_copilot_chat_id=clear_request.workflow_copilot_chat_id,+ expected_owner_turn_id=expected_owner_turn_id,+ expected_revision=expected_revision,+ auto_accept=clear_request.auto_accept,+ )+ except NotFoundError:raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="Chat not found")+ except CopilotProposalConflictError:+ raise HTTPException(status_code=status.HTTP_409_CONFLICT, detail="Copilot proposal changed; reload required")@base_router.post("/workflow/copilot/apply-proposed-workflow", include_in_schema=False)@@ -3084,6 +3333,42 @@ async def workflow_copilot_apply_proposed_workflow(if not proposal:raise HTTPException(status_code=status.HTTP_400_BAD_REQUEST, detail="No proposed workflow to apply")+ metadata = copilot_proposal_metadata(proposal)+ if isinstance(proposal, dict) and COPILOT_PROPOSAL_METADATA_KEY in proposal and metadata is None:+ raise HTTPException(+ status_code=status.HTTP_409_CONFLICT,+ detail="Copilot proposal metadata is invalid; reload required",+ )+ original_disposition: ProposalDisposition | None = None+ if metadata is not None:+ untokenized_client = _client_sent_no_proposal_token(apply_request.owner_turn_id, apply_request.revision)+ if not untokenized_client and (+ apply_request.owner_turn_id != metadata.owner_turn_id or apply_request.revision != metadata.revision+ ):+ raise HTTPException(+ status_code=status.HTTP_409_CONFLICT, detail="Copilot proposal changed; reload required"+ )+ canonical = await app.DATABASE.workflows.get_workflow_by_permanent_id(+ workflow_permanent_id=chat.workflow_permanent_id,+ organization_id=organization.organization_id,+ )+ if (+ canonical is None+ or workflow_content_fingerprint(canonical.model_dump(mode="json")) != metadata.canonical_fingerprint+ ):+ raise HTTPException(status_code=status.HTTP_409_CONFLICT, detail="Workflow changed after this proposal")+ if metadata.claim_is_live(datetime.now(UTC)):+ raise HTTPException(+ status_code=status.HTTP_409_CONFLICT, detail="Copilot proposal is already being accepted"+ )+ # A lapsed claim is being taken over, so the disposition to restore on failure is the+ # reviewable one this accept started from, never the dead claim's own marker.+ original_disposition = (+ "review_untested"+ if metadata.disposition == "accepting"+ else cast(ProposalDisposition, metadata.disposition)+ )+copilot_yaml = proposal.get("_copilot_yaml") if isinstance(proposal, dict) else Noneif not copilot_yaml:raise HTTPException(@@ -3120,22 +3405,63 @@ async def workflow_copilot_apply_proposed_workflow(detail=f"Proposed copilot YAML is invalid: {e}",)- new_workflow = await app.WORKFLOW_SERVICE.create_workflow_from_request(- organization=organization,- request=yaml_request,- workflow_permanent_id=chat.workflow_permanent_id,- edited_by="copilot",- validate_code_block_templates=False,- )+ claimed_at: datetime | None = None+ if metadata is not None:+ try:+ claimed = await app.DATABASE.workflow_params.claim_workflow_copilot_candidate(+ organization_id=organization.organization_id,+ workflow_copilot_chat_id=chat.workflow_copilot_chat_id,+ expected_owner_turn_id=metadata.owner_turn_id,+ expected_revision=metadata.revision,+ )+ claimed_metadata = copilot_proposal_metadata(claimed.proposed_workflow)+ claimed_at = claimed_metadata.claimed_at if claimed_metadata is not None else None+ except CopilotProposalConflictError:+ raise HTTPException(+ status_code=status.HTTP_409_CONFLICT, detail="Copilot proposal changed; reload required"+ )try:- # Best-effort: a 500 here would invite a retry that creates a duplicate version.- await app.DATABASE.workflow_params.update_workflow_copilot_chat(- organization_id=organization.organization_id,- workflow_copilot_chat_id=chat.workflow_copilot_chat_id,- proposed_workflow=None,- auto_accept=apply_request.auto_accept,+ new_workflow = await app.WORKFLOW_SERVICE.create_workflow_from_request(+ organization=organization,+ request=yaml_request,+ workflow_permanent_id=chat.workflow_permanent_id,+ edited_by="copilot",+ validate_code_block_templates=False,)+ except Exception:+ if metadata is not None and original_disposition is not None:+ with contextlib.suppress(Exception):+ # A failed release must not replace the create failure the caller needs to see.+ await app.DATABASE.workflow_params.release_workflow_copilot_candidate_claim(+ organization_id=organization.organization_id,+ workflow_copilot_chat_id=chat.workflow_copilot_chat_id,+ expected_owner_turn_id=metadata.owner_turn_id,+ expected_revision=metadata.revision,+ expected_claimed_at=claimed_at,+ disposition=original_disposition,+ )+ raise++ try:+ # Best-effort: a 500 here would invite a retry that creates a duplicate version.+ if metadata is not None:+ await app.DATABASE.workflow_params.clear_workflow_copilot_candidate(+ organization_id=organization.organization_id,+ workflow_copilot_chat_id=chat.workflow_copilot_chat_id,+ expected_owner_turn_id=metadata.owner_turn_id,+ expected_revision=metadata.revision,+ expected_disposition="accepting",+ expected_claimed_at=claimed_at,+ auto_accept=apply_request.auto_accept,+ )+ else:+ await app.DATABASE.workflow_params.update_workflow_copilot_chat(+ organization_id=organization.organization_id,+ workflow_copilot_chat_id=chat.workflow_copilot_chat_id,+ proposed_workflow=None,+ auto_accept=apply_request.auto_accept,+ )except Exception:LOG.warning("Failed to clear copilot proposal after applying it; new workflow version was created",@@ -3143,6 +3469,23 @@ async def workflow_copilot_apply_proposed_workflow(new_workflow_id=new_workflow.workflow_id,exc_info=True,)+ if metadata is not None and original_disposition is not None:+ try:+ await app.DATABASE.workflow_params.release_workflow_copilot_candidate_claim(+ organization_id=organization.organization_id,+ workflow_copilot_chat_id=chat.workflow_copilot_chat_id,+ expected_owner_turn_id=metadata.owner_turn_id,+ expected_revision=metadata.revision,+ expected_claimed_at=claimed_at,+ disposition=original_disposition,+ )+ except Exception:+ LOG.warning(+ "Failed to release copilot proposal claim after post-create cleanup failure",+ workflow_copilot_chat_id=chat.workflow_copilot_chat_id,+ new_workflow_id=new_workflow.workflow_id,+ exc_info=True,+ )return new_workflowdiff --git a/skyvern/forge/sdk/schemas/workflow_copilot.py b/skyvern/forge/sdk/schemas/workflow_copilot.pyindex cbb60daf2..dfc635701 100644--- a/skyvern/forge/sdk/schemas/workflow_copilot.py+++ b/skyvern/forge/sdk/schemas/workflow_copilot.py@@ -1,9 +1,18 @@from dataclasses import dataclass-from datetime import datetime+from datetime import datetime, timedeltafrom enum import StrEnumfrom typing import Annotated, Any, Literal-from pydantic import BaseModel, BeforeValidator, ConfigDict, Field, SecretStr, StringConstraints, field_validator+from pydantic import (+ BaseModel,+ BeforeValidator,+ ConfigDict,+ Field,+ JsonValue,+ SecretStr,+ StringConstraints,+ field_validator,+)from skyvern.forge.sdk.copilot.ask_user import QuestionInteraction, QuestionResponsefrom skyvern.forge.sdk.copilot.code_write_diff import CodeWriteDiff@@ -15,6 +24,66 @@ from skyvern.forge.sdk.schemas.copilot_turn_outcome import (TurnOutcome,)+COPILOT_PROPOSAL_METADATA_KEY = "_copilot_proposal"+CopilotCandidateDisposition = Literal[+ "no_proposal",+ "auto_applicable",+ "review_untested",+ "review_tested",+ "accepting",+]+++# An accept holds the candidate exclusively between its claim and its canonical write, so nothing+# can slip a newer candidate underneath the bytes it already read. The claim expires because the+# same outage that kills an accept mid-flight also kills the write that would release it.+COPILOT_PROPOSAL_CLAIM_LEASE = timedelta(minutes=5)+++class CopilotProposalMetadata(BaseModel):+ """CAS token and exact run ownership for one durable Copilot candidate."""++ model_config = ConfigDict(extra="forbid")++ owner_turn_id: str+ revision: int = Field(ge=1)+ canonical_fingerprint: str+ disposition: CopilotCandidateDisposition+ workflow_run_id: str | None = None+ claimed_at: datetime | None = None++ def claim_is_live(self, now: datetime) -> bool:+ if self.disposition != "accepting":+ return False+ if self.claimed_at is None:+ return False+ return now - self.claimed_at < COPILOT_PROPOSAL_CLAIM_LEASE+++class CopilotProposalRunOutput(BaseModel):+ output_parameter_id: str+ value: JsonValue+++class CopilotProposalRunFacts(BaseModel):+ workflow_run_id: str+ status: str | None = None+ available: bool+ failure_reason: str | None = None+ outputs: list[CopilotProposalRunOutput] = Field(default_factory=list)+++def copilot_proposal_metadata(value: object) -> CopilotProposalMetadata | None:+ if not isinstance(value, dict):+ return None+ raw = value.get(COPILOT_PROPOSAL_METADATA_KEY)+ if not isinstance(raw, dict):+ return None+ try:+ return CopilotProposalMetadata.model_validate(raw)+ except ValueError:+ return None+class CopilotPendingTurn(BaseModel):"""Durable write-ahead marker for one in-flight copilot turn.@@ -320,6 +389,8 @@ class WorkflowCopilotCredentialResponseRequest(BaseModel):class WorkflowCopilotClearProposedWorkflowRequest(BaseModel):workflow_copilot_chat_id: str = Field(..., description="The chat ID to update")auto_accept: bool = Field(..., description="Whether to auto-accept future workflow updates")+ owner_turn_id: str | None = Field(None, description="Owner token returned with a typed proposal")+ revision: int | None = Field(None, ge=1, description="Revision token returned with a typed proposal")class WorkflowCopilotApplyProposedWorkflowRequest(BaseModel):@@ -328,6 +399,8 @@ class WorkflowCopilotApplyProposedWorkflowRequest(BaseModel):False,description="If true, flip the chat to auto-accept mode so future turns persist directly without review",)+ owner_turn_id: str | None = Field(None, description="Owner token returned with a typed proposal")+ revision: int | None = Field(None, ge=1, description="Revision token returned with a typed proposal")class WorkflowCopilotChatHistoryMessage(BaseModel):@@ -421,6 +494,7 @@ class WorkflowCopilotStreamResponseUpdate(BaseModel):False,description="True when the backend already committed this terminal workflow proposal.",)+ proposed_workflow_metadata: CopilotProposalMetadata | None = Nonecancelled: bool = Field(False,description="When true, this RESPONSE was emitted by a user cancel; clients must not auto-apply.",@@ -717,6 +791,8 @@ class WorkflowCopilotChatHistoryResponse(BaseModel):workflow_copilot_chat_id: str | None = Field(None, description="Latest chat ID for the workflow")chat_history: list[WorkflowCopilotChatHistoryMessage] = Field(default_factory=list, description="Chat messages")proposed_workflow: dict | None = Field(None, description="Latest workflow proposed by the copilot")+ proposed_workflow_metadata: CopilotProposalMetadata | None = None+ proposed_workflow_run: CopilotProposalRunFacts | None = Noneauto_accept: bool | None = Field(None, description="Whether copilot auto-accepts workflow updates")work_plan: list[str] = Field(default_factory=list, description="Latest work plan the copilot model wrote")diff --git a/tests/unit/copilot_route_test_support.py b/tests/unit/copilot_route_test_support.pyindex a14d75bdc..ea0ab3257 100644--- a/tests/unit/copilot_route_test_support.py+++ b/tests/unit/copilot_route_test_support.py@@ -87,6 +87,12 @@ def setup_new_copilot_mocks(agent_result.cancellation_last_recorded_phase = Noneif not hasattr(agent_result, "cancellation_workflow_run_id"):agent_result.cancellation_workflow_run_id = None+ if not hasattr(agent_result, "proposal_owner_turn_id"):+ agent_result.proposal_owner_turn_id = None+ if not hasattr(agent_result, "proposal_revision"):+ agent_result.proposal_revision = None+ if not hasattr(agent_result, "proposal_workflow_run_id"):+ agent_result.proposal_workflow_run_id = Noneif not hasattr(original_workflow, "modified_at"):original_workflow.modified_at = datetime(2026, 4, 14, tzinfo=timezone.utc)if not hasattr(original_workflow, "model_dump"):diff --git a/tests/unit/copilot_test_helpers.py b/tests/unit/copilot_test_helpers.pyindex eb05ce10a..e633162ec 100644--- a/tests/unit/copilot_test_helpers.py+++ b/tests/unit/copilot_test_helpers.py@@ -190,6 +190,7 @@ def install_get_run_results_harness(workflow_permanent_id="wpid-1",copilot_total_timeout_exceeded=False,last_run_blocks_workflow_run_id=None,+ proposal_workflow_run_id=None,dispatched_run_ids_this_turn=set(),)diff --git a/tests/unit/test_copilot_agent_helpers.py b/tests/unit/test_copilot_agent_helpers.pyindex d3d629e02..4158a051a 100644--- a/tests/unit/test_copilot_agent_helpers.py+++ b/tests/unit/test_copilot_agent_helpers.py@@ -8,7 +8,7 @@ from collections.abc import Callablefrom datetime import datetime, timezonefrom pathlib import Pathfrom types import SimpleNamespace-from typing import Any, ClassVar+from typing import Any, ClassVar, Selffrom unittest.mock import AsyncMock, MagicMockimport httpx@@ -246,6 +246,137 @@ def _challenge_failure_ctx() -> CopilotContext:)+ (+ "product_action",+ "request_run_id",+ "expected_restore_run_id",+ "expected_workflow_yaml",+ "expected_run_id",+ "expected_proposal_run_id",+ ),+ [+ pytest.param(+ None,+ None,+ None,+ "title: Candidate\n",+ "wr_candidate",+ "wr_candidate",+ id="ordinary-continuation",+ ),+ pytest.param(+ None,+ "wr_diagnose",+ None,+ "title: Candidate\n",+ "wr_diagnose",+ "wr_candidate",+ id="ordinary-continuation-from-a-run-page",+ ),+ pytest.param(+ "diagnose_run",+ "wr_candidate",+ "wr_candidate",+ "title: Candidate\n",+ "wr_candidate",+ "wr_candidate",+ id="matching-diagnose-run",+ ),+ pytest.param(+ "diagnose_run",+ "wr_diagnose",+ "wr_diagnose",+ "title: Canonical\n",+ "wr_diagnose",+ None,+ id="explicit-diagnose-run",+ ),+ ],+)+async def test_interrupted_draft_turn_restoration_and_run_hydration_stay_coherent(+ monkeypatch: pytest.MonkeyPatch,+ product_action: str | None,+ request_run_id: str | None,+ expected_restore_run_id: str | None,+ expected_workflow_yaml: str,+ expected_run_id: str,+ expected_proposal_run_id: str | None,+) -> None:+ class FakeMCPServerManager:+ def __init__(self, servers: list[object]) -> None:+ self.active_servers = servers++ async def __aenter__(self) -> Self:+ return self++ async def __aexit__(self, exc_type: object, exc: object, tb: object) -> None:+ return None++ restored_run_ids: list[str | None] = []+ seeded: list[tuple[str | None, str, str | None]] = []+ hydrated: list[tuple[str, str, str | None]] = []++ async def restore_proposal(ctx: CopilotContext, *, required_workflow_run_id: str | None = None) -> None:+ restored_run_ids.append(required_workflow_run_id)+ if required_workflow_run_id is None or required_workflow_run_id == "wr_candidate":+ ctx.workflow_yaml = "title: Candidate\n"+ ctx.proposal_workflow_run_id = "wr_candidate"++ async def seed_run(ctx: CopilotContext, *, workflow_run_id: str | None) -> SimpleNamespace:+ seeded.append((workflow_run_id, ctx.workflow_yaml, ctx.proposal_workflow_run_id))+ return SimpleNamespace(finished=True)++ async def hydrate_run(ctx: CopilotContext, *, workflow_run_id: str) -> None:+ hydrated.append((workflow_run_id, ctx.workflow_yaml, ctx.proposal_workflow_run_id))++ monkeypatch.setattr(agent_module, "restore_pending_workflow_proposal", restore_proposal)+ monkeypatch.setattr(agent_module, "seed_repair_origin_run", seed_run)+ monkeypatch.setattr(agent_module, "hydrate_prior_run_packet", hydrate_run)+ monkeypatch.setattr(agent_module, "_resolve_live_browser_session_id", AsyncMock(return_value=None))+ monkeypatch.setattr("agents.mcp.MCPServerManager", FakeMCPServerManager)+ monkeypatch.setattr(+ "skyvern.forge.sdk.copilot.model_resolver.resolve_model_config",+ lambda _handler, **_kwargs: ("model-primary", object(), "PRIMARY", True),+ )+ monkeypatch.setattr(+ "skyvern.forge.sdk.copilot.enforcement.run_with_enforcement",+ AsyncMock(return_value=_fake_run_result({"type": "REPLY", "user_response": "ok"})),+ )+ build_context = MagicMock(wraps=agent_module._build_user_context)+ monkeypatch.setattr(agent_module, "_build_user_context", build_context)++ result = await agent_module.run_copilot_agent(+ stream=MagicMock(),+ organization_id="org-1",+ chat_request=WorkflowCopilotChatRequest(+ message="continue",+ workflow_id="wf-1",+ workflow_permanent_id="wfp-1",+ workflow_copilot_chat_id="chat-1",+ workflow_run_id=request_run_id,+ workflow_yaml="title: Canonical\n",+ browser_session_id=None,+ product_action=product_action,+ ),+ chat_history=[],+ global_llm_context=None,+ llm_api_handler=SimpleNamespace(llm_key="PRIMARY"),+ raw_secret_safety_handler=AsyncMock(+ return_value={"version": "1", "state": "clean", "handling": "none", "citations": []}+ ),+ api_key="sk-test",+ config=CopilotConfig(),+ )++ assert result.user_response == "ok"+ assert restored_run_ids == [expected_restore_run_id]+ assert seeded == [(expected_run_id, expected_workflow_yaml, expected_proposal_run_id)]+ assert hydrated == [(expected_run_id, expected_workflow_yaml, expected_proposal_run_id)]+ assert build_context.call_args.kwargs["workflow_yaml"] == expected_workflow_yaml++class TestFailedTestResponseNormalization:def test_paused_run_reply_is_not_rewritten_into_a_failed_test(self) -> None:from skyvern.forge.sdk.copilot.agent import _rewrite_failed_test_response@@ -3156,6 +3287,93 @@ class TestTranslateToAgentResultGating:assert agent_result.workflow_yaml is Noneassert agent_result.response_type == "REPLACE_WORKFLOW"+ def test_interrupted_draft_inline_replace_persists_before_emission(self, monkeypatch) -> None:+ prior = SimpleNamespace(name="prior")+ replacement = SimpleNamespace(name="replacement")+ monkeypatch.setattr(+ "skyvern.forge.sdk.copilot.tools._process_workflow_yaml",+ AsyncMock(return_value=replacement),+ )+ order: list[str] = []+ publish = AsyncMock(side_effect=lambda *_args, **_kwargs: order.append("persist"))+ emit = AsyncMock(side_effect=lambda *_args, **_kwargs: order.append("emit"))+ monkeypatch.setattr(agent_module, "publish_workflow_candidate", publish)+ monkeypatch.setattr(agent_module, "maybe_emit_design_end", AsyncMock())+ monkeypatch.setattr(agent_module, "emit_workflow_draft", emit)+ ctx = _ctx(+ workflow_copilot_chat_id="wcc-test",+ stream=MagicMock(),+ last_workflow=prior,+ last_workflow_yaml="title: Prior",+ request_policy=RequestPolicy(allow_update_workflow=True, allow_run_blocks=True),+ )++ asyncio.run(+ agent_module._translate_to_agent_result(+ _fake_run_result(+ {+ "type": "REPLACE_WORKFLOW",+ "user_response": "Here is the replacement.",+ "workflow_yaml": "title: Replacement",+ }+ ),+ ctx,+ global_llm_context=None,+ chat_request=_chat_request(),+ organization_id="org-1",+ )+ )++ assert order == ["persist", "emit"]+ publish.assert_awaited_once_with(+ ctx,+ workflow=replacement,+ workflow_yaml="title: Replacement",+ )++ def test_interrupted_draft_inline_replace_write_failure_emits_nothing(self, monkeypatch) -> None:+ prior = SimpleNamespace(name="prior")+ replacement = SimpleNamespace(name="replacement")+ monkeypatch.setattr(+ "skyvern.forge.sdk.copilot.tools._process_workflow_yaml",+ AsyncMock(return_value=replacement),+ )+ monkeypatch.setattr(+ agent_module,+ "publish_workflow_candidate",+ AsyncMock(side_effect=RuntimeError("database unavailable")),+ )+ emit = AsyncMock()+ monkeypatch.setattr(agent_module, "emit_workflow_draft", emit)+ ctx = _ctx(+ workflow_copilot_chat_id="wcc-test",+ stream=MagicMock(),+ last_workflow=prior,+ last_workflow_yaml="title: Prior",+ request_policy=RequestPolicy(allow_update_workflow=True, allow_run_blocks=True),+ )++ with pytest.raises(RuntimeError, match="database unavailable"):+ asyncio.run(+ agent_module._translate_to_agent_result(+ _fake_run_result(+ {+ "type": "REPLACE_WORKFLOW",+ "user_response": "Here is the replacement.",+ "workflow_yaml": "title: Replacement",+ }+ ),+ ctx,+ global_llm_context=None,+ chat_request=_chat_request(),+ organization_id="org-1",+ )+ )++ assert ctx.last_workflow is prior+ assert ctx.last_workflow_yaml == "title: Prior"+ emit.assert_not_awaited()+def test_inline_replace_workflow_uses_request_policy_authority(self, monkeypatch) -> None:replacement = SimpleNamespace(name="diagnose-repair")process_mock = AsyncMock(return_value=replacement)diff --git a/tests/unit/test_copilot_build_test_outcome.py b/tests/unit/test_copilot_build_test_outcome.pyindex 234532162..dc7b96ee6 100644--- a/tests/unit/test_copilot_build_test_outcome.py+++ b/tests/unit/test_copilot_build_test_outcome.py@@ -2,6 +2,7 @@ from __future__ import annotationsimport asyncioimport copy+import hashlibimport jsonfrom collections.abc import AsyncIteratorfrom contextlib import asynccontextmanager@@ -92,6 +93,7 @@ from skyvern.forge.sdk.copilot.tools.run_execution import (build_test_evidence_packet,)from skyvern.forge.sdk.copilot.workflow_yaml import runner_code_block_associations+from skyvern.forge.sdk.db.exceptions import CopilotProposalConflictErrorfrom skyvern.forge.sdk.schemas.copilot_turn_outcome import ResponseKind, TurnOutcome, UnresolvedRuntimeFailurefrom skyvern.forge.sdk.schemas.persistent_browser_sessions import PersistentBrowserSessionfrom skyvern.forge.sdk.workflow.models.block import CodeBlock@@ -1891,6 +1893,7 @@ async def test_failed_run_complete_fact_packet_reaches_ordinary_repair_input(monkeypatch: pytest.MonkeyPatch,) -> None:ctx = _locator_packet_ctx()+ ctx.proposal_workflow_run_id = "wr_failed_complete_packet"now = datetime(2026, 8, 28, tzinfo=UTC)output_parameter = OutputParameter(output_parameter_id="out_records",@@ -1901,10 +1904,17 @@ async def test_failed_run_complete_fact_packet_reaches_ordinary_repair_input(modified_at=now,)run_workflow = SimpleNamespace(+ workflow_id="wf_run_snapshot",organization_id=ctx.organization_id,workflow_definition=SimpleNamespace(parameters=[output_parameter],- blocks=[SimpleNamespace(label="collect_records", block_type="CODE", output_parameter=output_parameter)],+ blocks=[+ CodeBlock(+ label="collect_records",+ output_parameter=output_parameter,+ code='return {"records": [{"name": "bounded result"}]}',+ )+ ],),)run = SimpleNamespace(@@ -2007,6 +2017,13 @@ async def test_failed_run_complete_fact_packet_reaches_ordinary_repair_input("value_complete": True,}]+ assert hydrated["run"]["execution_source"] == {+ "source_kind": "staged",+ "workflow_id": "wf_run_snapshot",+ "block_code_sha256": {+ "collect_records": hashlib.sha256(b'return {"records": [{"name": "bounded result"}]}').hexdigest()+ },+ }assert '"status": "failed"' in ordinary_inputassert '"workflow_run_id": "wr_failed_complete_packet"' in ordinary_inputassert '"output_parameter_id": "out_records"' in ordinary_input@@ -2023,6 +2040,15 @@ async def test_failed_run_complete_fact_packet_reaches_ordinary_repair_input(assert "repairable_failure" not in system_inputassert "wr_failed_complete_packet" not in system_input+ nonassociated_ctx = _locator_packet_ctx()+ nonassociated_ctx.proposal_workflow_run_id = "wr_different_proposal"+ nonassociated = await run_execution_module.hydrate_prior_run_packet(+ nonassociated_ctx,+ workflow_run_id="wr_failed_complete_packet",+ )+ assert nonassociated is not None+ assert "execution_source" not in nonassociated["run"]+def test_unavailable_registered_output_rows_do_not_become_false_missing_output_facts() -> None:ctx = _locator_packet_ctx()@@ -5745,6 +5771,76 @@ async def test_the_repaired_block_executes_and_the_run_owns_the_outputs_it_was_aassert run_owned == [after_output], "the corrected run does not hand back the output its code produced"+async def test_candidate_run_bind_uses_the_call_owned_source_and_token(+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ ctx = await handback_ctx(monkeypatch, polled_status="completed", block_status="completed")+ ctx.workflow_copilot_chat_id = "chat-1"+ ctx.proposal_owner_turn_id = "turn-source"+ ctx.proposal_revision = 3+ ctx.staged_workflow_yaml = HANDBACK_WORKFLOW_YAML+ captured: dict[str, object] = {}++ async def bind_candidate_run(**kwargs: object) -> None:+ captured.update(kwargs)+ raise CopilotProposalConflictError("candidate changed")++ async def prepare_workflow(**_kwargs: object) -> SimpleNamespace:+ ctx.proposal_owner_turn_id = "turn-newer"+ ctx.proposal_revision = 1+ ctx.staged_workflow = ctx.staged_workflow.model_copy(update={"title": "Newer candidate"})+ return SimpleNamespace(+ workflow_run_id="wr_source",+ workflow_id="w_source",+ browser_session_id="pbs_run",+ sequential_credential_id=None,+ )++ forge_app.DATABASE.workflow_params.bind_workflow_copilot_candidate_run = bind_candidate_run+ forge_app.DATABASE.workflows.soft_delete_workflow_by_id = AsyncMock()+ forge_app.WORKFLOW_SERVICE.mark_workflow_run_as_failed_if_not_final = AsyncMock()+ monkeypatch.setattr(workflow_service_module, "prepare_workflow", prepare_workflow)++ result = await _run_blocks_and_collect_debug({"block_labels": ["extract_heading"], "parameters": {}}, ctx)++ assert result == {+ "ok": False,+ "error": "The pending Copilot proposal changed before the test started; reload and try again.",+ }+ assert captured["expected_owner_turn_id"] == "turn-source"+ assert captured["expected_revision"] == 3+ assert captured["expected_workflow_yaml"] == HANDBACK_WORKFLOW_YAML+++async def test_canonical_run_does_not_bind_a_stale_proposal_token(+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ harness = await install_run_blocks_harness(+ monkeypatch,+ workflow_yaml=HANDBACK_WORKFLOW_YAML,+ polled_status="completed",+ terminal_blocks=[terminal_extraction_block("completed")],+ )+ bind_candidate_run = AsyncMock()+ forge_app.DATABASE.workflow_params.bind_workflow_copilot_candidate_run = bind_candidate_run+ ctx = make_copilot_ctx(+ browser_session_id="pbs_chat",+ workflow_copilot_chat_id="chat-1",+ proposal_owner_turn_id="turn-stale",+ proposal_revision=2,+ )+ ctx.frontier_resume_session_id = "pbs_run"++ result = await _run_blocks_and_collect_debug({"block_labels": ["extract_heading"], "parameters": {}}, ctx)++ assert result["ok"] is True, result+ assert result["data"]["execution_source"]["source_kind"] == "canonical"+ bind_candidate_run.assert_not_awaited()+ assert harness["executor_cancelled"] is False++@pytest.mark.asyncioasync def test_completed_run_is_recorded_before_the_browser_enrichment_await(monkeypatch: pytest.MonkeyPatch,diff --git a/tests/unit/test_workflow_copilot_route.py b/tests/unit/test_workflow_copilot_route.pyindex de4e07f08..b3f57a1b9 100644--- a/tests/unit/test_workflow_copilot_route.py+++ b/tests/unit/test_workflow_copilot_route.py@@ -50,7 +50,7 @@ from skyvern.forge.sdk.copilot.interruption import (InterruptedTurnFacts,)from skyvern.forge.sdk.copilot.turn_outcome import build_minimal_turn_outcome-from skyvern.forge.sdk.db.exceptions import DatabaseConnectionUnavailableError+from skyvern.forge.sdk.db.exceptions import CopilotProposalConflictError, DatabaseConnectionUnavailableErrorfrom skyvern.forge.sdk.db.repositories.workflow_parameters import (_completed_turn_id_for_idempotency_digest,_pending_turn_id_for_idempotency_digest,@@ -67,13 +67,16 @@ from skyvern.forge.sdk.routes.workflow_copilot import ()from skyvern.forge.sdk.schemas.copilot_turn_outcome import ConnectedAccountChoice, ResponseKind, TurnOutcomefrom skyvern.forge.sdk.schemas.workflow_copilot import (+ COPILOT_PROPOSAL_METADATA_KEY,CopilotAttachedFile,CopilotPendingTurn,+ WorkflowCopilotApplyProposedWorkflowRequest,WorkflowCopilotBrowserAblationResponseUpdate,WorkflowCopilotChat,WorkflowCopilotChatMessage,WorkflowCopilotChatRequest,WorkflowCopilotChatSender,+ WorkflowCopilotClearProposedWorkflowRequest,WorkflowCopilotStreamErrorUpdate,WorkflowCopilotStreamResponseUpdate,)@@ -622,6 +625,194 @@ async def test_finalise_normal_turn_is_not_applied_without_a_proposal_on_auto_acassert persisted_payload is not None+async def test_auto_accept_does_not_commit_canonical_for_a_superseded_candidate(+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ """A turn that lost the candidate has no standing to write the saved workflow, and auto-accept+ writes canonical before the proposal write ever runs."""+ newer = {+ "workflow_id": "wf-newer",+ COPILOT_PROPOSAL_METADATA_KEY: {+ "owner_turn_id": "turn-newer",+ "revision": 1,+ "canonical_fingerprint": "fp",+ "disposition": "review_untested",+ },+ }+ chat = SimpleNamespace(+ organization_id="org-1",+ workflow_copilot_chat_id="chat-1",+ proposed_workflow=newer,+ auto_accept=True,+ )+ original_workflow = SimpleNamespace(workflow_id="wf-canonical")+ agent_result = AgentResult(+ user_response="done",+ updated_workflow=MagicMock(),+ global_llm_context=None,+ response_type="REPLACE_WORKFLOW",+ narrative_payload=_narrative_payload(),+ staged_workflow=MagicMock(),+ has_staged_proposal=True,+ )+ agent_result.proposal_owner_turn_id = "turn-stale"+ agent_result.proposal_revision = 1+ _, workflow_params = setup_new_copilot_mocks(monkeypatch, chat, original_workflow, agent_result)+ workflow_params.get_workflow_copilot_chat_by_id = AsyncMock(return_value=SimpleNamespace(proposed_workflow=newer))+ commit = AsyncMock()+ monkeypatch.setattr(workflow_copilot_route, "_commit_staged_workflow", commit)+ stream = MagicMock(send=AsyncMock(return_value=True))++ await workflow_copilot_route._finalise_normal_turn(+ stream=stream,+ chat=chat,+ organization_id="org-1",+ original_workflow=original_workflow,+ chat_request=_make_chat_request(),+ agent_result=agent_result,+ )++ commit.assert_not_awaited()+ response_frame = stream.send.await_args.args[0]+ assert response_frame.updated_workflow is None+++async def test_a_superseded_turn_ships_no_draft_beside_the_winning_token(+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ """The review card has to show what Accept will apply, so a turn that lost the candidate must+ not stream its own draft next to the winner's token."""+ newer = {+ "workflow_id": "wf-newer",+ COPILOT_PROPOSAL_METADATA_KEY: {+ "owner_turn_id": "turn-newer",+ "revision": 2,+ "canonical_fingerprint": "fp",+ "disposition": "review_untested",+ },+ }+ chat = SimpleNamespace(+ organization_id="org-1",+ workflow_copilot_chat_id="chat-1",+ proposed_workflow=newer,+ auto_accept=False,+ )+ original_workflow = SimpleNamespace(workflow_id="wf-canonical")+ agent_result = AgentResult(+ user_response="done",+ updated_workflow=MagicMock(),+ global_llm_context=None,+ response_type="REPLACE_WORKFLOW",+ narrative_payload=_narrative_payload(),+ )+ agent_result.proposal_owner_turn_id = "turn-stale"+ agent_result.proposal_revision = 1+ _, workflow_params = setup_new_copilot_mocks(monkeypatch, chat, original_workflow, agent_result)+ workflow_params.get_workflow_copilot_chat_by_id = AsyncMock(return_value=SimpleNamespace(proposed_workflow=newer))+ stream = MagicMock(send=AsyncMock(return_value=True))++ await workflow_copilot_route._finalise_normal_turn(+ stream=stream,+ chat=chat,+ organization_id="org-1",+ original_workflow=original_workflow,+ chat_request=_make_chat_request(),+ agent_result=agent_result,+ )++ frame = stream.send.await_args.args[0]+ assert frame.updated_workflow is None+ assert frame.proposal_disposition == "no_proposal"+++async def test_a_candidate_claimed_mid_turn_does_not_cost_the_user_the_reply(+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ """Clicking Accept while a turn is still running makes its finalizing write lose the token.+ That is a write failure to report, not a turn to end."""+ stored = {+ "workflow_id": "wf-1",+ COPILOT_PROPOSAL_METADATA_KEY: {+ "owner_turn_id": "turn-a",+ "revision": 1,+ "canonical_fingerprint": "fp",+ "disposition": "accepting",+ },+ }+ chat = SimpleNamespace(+ organization_id="org-1",+ workflow_copilot_chat_id="chat-1",+ proposed_workflow=stored,+ auto_accept=False,+ )+ original_workflow = SimpleNamespace(workflow_id="wf-canonical")+ agent_result = AgentResult(+ user_response="here is the change you asked for",+ updated_workflow=MagicMock(),+ global_llm_context=None,+ response_type="REPLACE_WORKFLOW",+ narrative_payload=_narrative_payload(),+ )+ agent_result.proposal_owner_turn_id = "turn-a"+ agent_result.proposal_revision = 1+ _, workflow_params = setup_new_copilot_mocks(monkeypatch, chat, original_workflow, agent_result)+ workflow_params.get_workflow_copilot_chat_by_id = AsyncMock(return_value=SimpleNamespace(proposed_workflow=stored))+ workflow_params.enrich_workflow_copilot_candidate = AsyncMock(+ side_effect=CopilotProposalConflictError("Copilot proposal is being accepted")+ )+ stream = MagicMock(send=AsyncMock(return_value=True))++ await workflow_copilot_route._finalise_normal_turn(+ stream=stream,+ chat=chat,+ organization_id="org-1",+ original_workflow=original_workflow,+ chat_request=_make_chat_request(),+ agent_result=agent_result,+ )++ frame = stream.send.await_args.args[0]+ assert frame.message == "here is the change you asked for"+ assert frame.updated_workflow is None+++async def test_a_client_without_proposal_tokens_can_still_reject(+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ """A frontend deployed before this change never sends tokens, and one already open outlives the+ rollout. Refusing it would leave the user unable to dismiss a proposal at all."""+ stored = {+ "workflow_id": "wf-1",+ COPILOT_PROPOSAL_METADATA_KEY: {+ "owner_turn_id": "turn-a",+ "revision": 3,+ "canonical_fingerprint": "fp",+ "disposition": "review_untested",+ },+ }+ clear = AsyncMock()+ monkeypatch.setattr(+ app.DATABASE,+ "workflow_params",+ SimpleNamespace(+ get_workflow_copilot_chat_by_id=AsyncMock(return_value=SimpleNamespace(proposed_workflow=stored)),+ clear_workflow_copilot_candidate=clear,+ ),+ )++ await workflow_copilot_route.workflow_copilot_clear_proposed_workflow(+ WorkflowCopilotClearProposedWorkflowRequest(workflow_copilot_chat_id="chat-1", auto_accept=False),+ SimpleNamespace(organization_id="org-1"),+ )++ assert clear.await_args.kwargs["expected_owner_turn_id"] == "turn-a"+ assert clear.await_args.kwargs["expected_revision"] == 3++def test_chat_history_serves_a_saved_envelope_back_untouched() -> None:now = datetime.now(timezone.utc)payload = {@@ -2832,6 +3023,9 @@ async def test_persist_state_keeps_verified_review_tested_proposal(monkeypatch:canonical_was_persisted_due_to_param_change=False,executed_block_fingerprints={},has_staged_proposal=False,+ proposal_owner_turn_id=None,+ proposal_revision=None,+ proposal_workflow_run_id=None,)await workflow_copilot_route._persist_proposed_workflow_state(chat, agent_result, restored=False)@@ -2854,6 +3048,9 @@ def _make_bypassed_proposal_agent_result(**overrides: object) -> SimpleNamespacehas_staged_proposal=False,output_policy_diagnostics=None,executed_block_fingerprints={},+ proposal_owner_turn_id=None,+ proposal_revision=None,+ proposal_workflow_run_id=None,)fields.update(overrides)return SimpleNamespace(**fields)@@ -3226,6 +3423,152 @@ def _fingerprint_of(workflow: Workflow) -> str:return workflow_content_fingerprint(workflow.model_dump(mode="json"))+async def test_apply_rejects_malformed_typed_proposal_before_canonical_write(+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ proposal = {+ "_copilot_yaml": "title: Candidate\nworkflow_definition:\n parameters: []\n blocks: []\n",+ COPILOT_PROPOSAL_METADATA_KEY: {"owner_turn_id": "turn-1", "revision": 0},+ }+ chat = SimpleNamespace(+ workflow_copilot_chat_id="chat-1",+ workflow_permanent_id="wpid-1",+ proposed_workflow=proposal,+ )+ monkeypatch.setattr(+ app.DATABASE,+ "workflow_params",+ SimpleNamespace(get_workflow_copilot_chat_by_id=AsyncMock(return_value=chat)),+ )+ create_workflow = AsyncMock()+ monkeypatch.setattr(app, "WORKFLOW_SERVICE", SimpleNamespace(create_workflow_from_request=create_workflow))++ with pytest.raises(HTTPException) as exc_info:+ await workflow_copilot_route.workflow_copilot_apply_proposed_workflow(+ WorkflowCopilotApplyProposedWorkflowRequest(+ workflow_copilot_chat_id="chat-1",+ owner_turn_id=None,+ revision=None,+ ),+ SimpleNamespace(organization_id="org-1"),+ )++ assert exc_info.value.status_code == 409+ create_workflow.assert_not_awaited()+++async def test_apply_rejects_typed_proposal_with_mismatched_owner_revision(+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ proposal = {+ "_copilot_yaml": "title: Candidate\n",+ COPILOT_PROPOSAL_METADATA_KEY: {+ "owner_turn_id": "turn-owner",+ "revision": 2,+ "canonical_fingerprint": "canonical",+ "disposition": "review_untested",+ },+ }+ chat = SimpleNamespace(+ workflow_copilot_chat_id="chat-1",+ workflow_permanent_id="wpid-1",+ proposed_workflow=proposal,+ )+ monkeypatch.setattr(+ app.DATABASE,+ "workflow_params",+ SimpleNamespace(get_workflow_copilot_chat_by_id=AsyncMock(return_value=chat)),+ )+ create_workflow = AsyncMock()+ monkeypatch.setattr(app, "WORKFLOW_SERVICE", SimpleNamespace(create_workflow_from_request=create_workflow))++ with pytest.raises(HTTPException) as exc_info:+ await workflow_copilot_route.workflow_copilot_apply_proposed_workflow(+ WorkflowCopilotApplyProposedWorkflowRequest(+ workflow_copilot_chat_id="chat-1",+ owner_turn_id="turn-other",+ revision=2,+ ),+ SimpleNamespace(organization_id="org-1"),+ )++ assert exc_info.value.status_code == 409+ create_workflow.assert_not_awaited()+++async def test_apply_releases_the_candidate_claim_when_post_create_clear_fails(+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ canonical = _make_copilot_workflow("Canonical", _NOW)+ candidate = _make_copilot_workflow("Candidate", _NOW + timedelta(seconds=1))+ candidate_yaml = "title: Candidate\nworkflow_definition:\n parameters: []\n blocks: []\n"+ proposal = {+ "_copilot_yaml": candidate_yaml,+ COPILOT_PROPOSAL_METADATA_KEY: {+ "owner_turn_id": "turn-owner",+ "revision": 2,+ "canonical_fingerprint": _fingerprint_of(canonical),+ "disposition": "review_tested",+ },+ }+ chat = SimpleNamespace(+ workflow_copilot_chat_id="chat-1",+ workflow_permanent_id="wpid-1",+ proposed_workflow=proposal,+ )+ release_claim = AsyncMock()+ claimed_at = _NOW + timedelta(seconds=2)+ claimed_chat = SimpleNamespace(+ proposed_workflow={+ **proposal,+ COPILOT_PROPOSAL_METADATA_KEY: {+ **proposal[COPILOT_PROPOSAL_METADATA_KEY],+ "disposition": "accepting",+ "claimed_at": claimed_at.isoformat(),+ },+ }+ )+ workflow_params = SimpleNamespace(+ get_workflow_copilot_chat_by_id=AsyncMock(return_value=chat),+ claim_workflow_copilot_candidate=AsyncMock(return_value=claimed_chat),+ clear_workflow_copilot_candidate=AsyncMock(side_effect=RuntimeError("transient clear failure")),+ release_workflow_copilot_candidate_claim=release_claim,+ )+ monkeypatch.setattr(app.DATABASE, "workflow_params", workflow_params)+ monkeypatch.setattr(+ app.DATABASE,+ "workflows",+ SimpleNamespace(get_workflow_by_permanent_id=AsyncMock(return_value=canonical)),+ )+ monkeypatch.setattr(+ app,+ "WORKFLOW_SERVICE",+ SimpleNamespace(create_workflow_from_request=AsyncMock(return_value=candidate)),+ )++ result = await workflow_copilot_route.workflow_copilot_apply_proposed_workflow(+ WorkflowCopilotApplyProposedWorkflowRequest(+ workflow_copilot_chat_id="chat-1",+ owner_turn_id="turn-owner",+ revision=2,+ ),+ SimpleNamespace(organization_id="org-1"),+ )++ assert result is candidate+ release_claim.assert_awaited_once_with(+ organization_id="org-1",+ workflow_copilot_chat_id="chat-1",+ expected_owner_turn_id="turn-owner",+ expected_revision=2,+ expected_claimed_at=claimed_at,+ disposition="review_tested",+ )++def _make_pending_turn(turn_id: str, age_seconds: float, **overrides: Any) -> CopilotPendingTurn:return CopilotPendingTurn(turn_id=turn_id,@@ -3765,6 +4108,95 @@ async def test_chat_history_leaves_a_young_pending_turn_alone(monkeypatch: pytesassert "turn-a" in chat.pending_turns+async def test_interrupted_draft_history_returns_owner_and_exact_run_facts(+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ canonical = _make_copilot_workflow("Saved", _NOW)+ proposal = canonical.model_dump(mode="json")+ proposal["title"] = "Durable candidate"+ proposal["_copilot_yaml"] = "title: Durable candidate\n"+ proposal[COPILOT_PROPOSAL_METADATA_KEY] = {+ "owner_turn_id": "turn-draft",+ "revision": 2,+ "canonical_fingerprint": _fingerprint_of(canonical),+ "disposition": "review_untested",+ "workflow_run_id": "wr-exact",+ }+ chat = _make_persisted_chat([], proposed_workflow=proposal)+ store, _ = _install_reconcile_store(monkeypatch, chat, canonical=canonical)+ store.add_message(WorkflowCopilotChatSender.USER, "build the candidate")+ run = SimpleNamespace(+ workflow_permanent_id="wpid-1",+ status=WorkflowRunStatus.completed,+ failure_reason=None,+ )+ output = SimpleNamespace(output_parameter_id="op-metric", value={"metric": "42"})+ app.DATABASE.workflow_runs = SimpleNamespace(+ get_workflow_run=AsyncMock(return_value=run),+ get_workflow_run_output_parameters=AsyncMock(return_value=[output]),+ )++ response = await _load_history()++ assert response.proposed_workflow is not None+ assert response.proposed_workflow["_copilot_yaml"] == "title: Durable candidate\n"+ assert response.proposed_workflow_metadata is not None+ assert response.proposed_workflow_metadata.owner_turn_id == "turn-draft"+ assert response.proposed_workflow_metadata.revision == 2+ assert response.proposed_workflow_run is not None+ assert response.proposed_workflow_run.workflow_run_id == "wr-exact"+ assert response.proposed_workflow_run.status == "completed"+ assert response.proposed_workflow_run.outputs[0].value == {"metric": "42"}+++async def test_interrupted_draft_stale_finalization_does_not_replace_newer_candidate(+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ current_proposal = {+ "title": "Newer candidate",+ "_copilot_yaml": "title: Newer candidate\n",+ COPILOT_PROPOSAL_METADATA_KEY: {+ "owner_turn_id": "turn-new",+ "revision": 1,+ "canonical_fingerprint": "canonical",+ "disposition": "review_untested",+ },+ }+ chat = SimpleNamespace(+ organization_id="org-1",+ workflow_copilot_chat_id="chat-1",+ auto_accept=False,+ proposed_workflow={"title": "Old candidate"},+ )+ workflow_params = SimpleNamespace(+ get_workflow_copilot_chat_by_id=AsyncMock(return_value=SimpleNamespace(proposed_workflow=current_proposal)),+ enrich_workflow_copilot_candidate=AsyncMock(),+ clear_workflow_copilot_candidate=AsyncMock(),+ update_workflow_copilot_chat=AsyncMock(),+ )+ monkeypatch.setattr(app.DATABASE, "workflow_params", workflow_params)+ stale_result = AgentResult(+ user_response="draft ready",+ updated_workflow=_make_copilot_workflow("Old candidate", _NOW),+ global_llm_context=None,+ workflow_yaml="title: Old candidate\n",+ proposal_disposition="review_untested",+ proposal_owner_turn_id="turn-old",+ proposal_revision=1,+ has_staged_proposal=True,+ )++ await workflow_copilot_route._persist_proposed_workflow_state(chat, stale_result, restored=False)++ assert chat.proposed_workflow == current_proposal+ assert stale_result.updated_workflow is None+ workflow_params.enrich_workflow_copilot_candidate.assert_not_awaited()+ workflow_params.clear_workflow_copilot_candidate.assert_not_awaited()+ workflow_params.update_workflow_copilot_chat.assert_not_awaited()++@pytest.mark.asyncioasync def test_chat_history_shows_the_user_message_while_the_turn_is_still_running(monkeypatch: pytest.MonkeyPatch,@@ -5291,3 +5723,226 @@ async def test_restore_records_only_a_rollback_that_landed(update.assert_awaited_once()assert marker[0] is not update_fails+++async def test_a_salvaged_last_good_workflow_replaces_the_candidate_it_is_shown_instead_of(+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ """When a later edit fails testing, the turn answers with the last verified shape. The stored+ candidate has to become that shape too: the card renders what the turn returned, and Accept+ reparses what was stored."""+ stored_failing_candidate = {+ "workflow_id": "wf-1",+ "_copilot_yaml": "title: Failing edit\n",+ COPILOT_PROPOSAL_METADATA_KEY: {+ "owner_turn_id": "turn-a",+ "revision": 1,+ "canonical_fingerprint": "fp",+ "disposition": "review_untested",+ },+ }+ chat = SimpleNamespace(+ organization_id="org-1",+ workflow_copilot_chat_id="chat-1",+ workflow_permanent_id="wpid-1",+ proposed_workflow=stored_failing_candidate,+ auto_accept=False,+ )+ salvaged = MagicMock()+ salvaged.model_dump = MagicMock(return_value={"workflow_id": "wf-salvaged", "title": "Last verified"})+ salvaged.title = "Last verified"+ agent_result = AgentResult(+ user_response="kept the verified shape",+ updated_workflow=salvaged,+ global_llm_context=None,+ response_type="REPLACE_WORKFLOW",+ workflow_yaml="title: Last verified\n",+ )+ agent_result.proposal_owner_turn_id = "turn-a"+ agent_result.proposal_revision = 1+ republished = {+ **{"workflow_id": "wf-salvaged", "title": "Last verified", "_copilot_yaml": "title: Last verified\n"},+ COPILOT_PROPOSAL_METADATA_KEY: {+ "owner_turn_id": "turn-a",+ "revision": 2,+ "canonical_fingerprint": "fp",+ "disposition": "review_untested",+ },+ }+ enrich = AsyncMock()+ publish = AsyncMock(return_value=SimpleNamespace(proposed_workflow=republished))+ monkeypatch.setattr(+ app.DATABASE,+ "workflow_params",+ SimpleNamespace(+ get_workflow_copilot_chat_by_id=AsyncMock(+ return_value=SimpleNamespace(proposed_workflow=stored_failing_candidate)+ ),+ enrich_workflow_copilot_candidate=enrich,+ publish_workflow_copilot_candidate=publish,+ update_workflow_copilot_chat=AsyncMock(),+ ),+ )++ await workflow_copilot_route._persist_proposed_workflow_state(chat, agent_result, restored=False)++ # Enrichment refuses changed bytes (see the repository scenario test), so the salvaged workflow+ # has to go through publication and take a revision of its own.+ enrich.assert_not_awaited()+ persisted = publish.await_args.kwargs["proposal"]+ assert persisted["_copilot_yaml"] == "title: Last verified\n"+ assert persisted["workflow_id"] == "wf-salvaged"+ # The terminal frame carries this token, so it must name the revision the user will act on.+ assert agent_result.proposal_revision == 2+++async def test_history_still_shows_a_candidate_whose_accept_died_holding_its_claim(+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ """A server that dies mid-accept leaves the claim behind for the length of the lease. The ticket+ requires a retained candidate to stay reviewable when interrupted, so withholding the card for+ that whole window is the disappearance this store exists to remove."""+ canonical = _make_copilot_workflow("Base", _NOW)+ stored = {+ "workflow_id": "wf-1",+ "_copilot_yaml": "title: Base\n",+ COPILOT_PROPOSAL_METADATA_KEY: {+ "owner_turn_id": "turn-a",+ "revision": 1,+ "canonical_fingerprint": _fingerprint_of(canonical),+ "disposition": "accepting",+ "claimed_at": _NOW.isoformat(),+ },+ }+ chat = SimpleNamespace(+ organization_id="org-1",+ workflow_copilot_chat_id="chat-1",+ workflow_permanent_id="wpid-1",+ proposed_workflow=stored,+ auto_accept=False,+ )+ monkeypatch.setattr(+ app.DATABASE,+ "workflows",+ SimpleNamespace(get_workflow_by_permanent_id=AsyncMock(return_value=canonical)),+ )+ monkeypatch.setattr(+ workflow_copilot_route,+ "datetime",+ SimpleNamespace(now=lambda tz=None: _NOW, fromisoformat=datetime.fromisoformat),+ )++ proposal, metadata, _run = await workflow_copilot_route._history_proposal_state(chat, "org-1")++ assert proposal is stored+ assert metadata is not None and metadata.disposition == "accepting"+++async def test_a_large_run_output_is_bounded_before_it_reaches_every_history_response(+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ """The card renders each output as a single line, and this response is read on every recovery,+ so an unbounded extraction is pure weight on the path the candidate is recovered through."""+ canonical = _make_copilot_workflow("Base", _NOW)+ stored = {+ "workflow_id": "wf-1",+ "_copilot_yaml": "title: Base\n",+ COPILOT_PROPOSAL_METADATA_KEY: {+ "owner_turn_id": "turn-a",+ "revision": 1,+ "canonical_fingerprint": _fingerprint_of(canonical),+ "disposition": "review_tested",+ "workflow_run_id": "wr-1",+ },+ }+ chat = SimpleNamespace(+ organization_id="org-1",+ workflow_copilot_chat_id="chat-1",+ workflow_permanent_id="wpid-1",+ proposed_workflow=stored,+ auto_accept=False,+ )+ monkeypatch.setattr(+ app.DATABASE,+ "workflows",+ SimpleNamespace(get_workflow_by_permanent_id=AsyncMock(return_value=canonical)),+ )+ monkeypatch.setattr(+ app.DATABASE,+ "workflow_runs",+ SimpleNamespace(+ get_workflow_run=AsyncMock(+ return_value=SimpleNamespace(status="completed", failure_reason=None, workflow_permanent_id="wpid-1")+ ),+ get_workflow_run_output_parameters=AsyncMock(+ return_value=[+ SimpleNamespace(output_parameter_id="op-small", value={"metric": "42"}),+ SimpleNamespace(output_parameter_id="op-large", value={"rows": ["x" * 50] * 500}),+ ]+ ),+ ),+ )++ _proposal, _metadata, run_facts = await workflow_copilot_route._history_proposal_state(chat, "org-1")++ assert run_facts is not None+ by_id = {row.output_parameter_id: row.value for row in run_facts.outputs}+ assert by_id["op-small"] == {"metric": "42"}+ assert isinstance(by_id["op-large"], str) and "truncated from" in by_id["op-large"]+++async def test_enriching_a_tested_candidate_drops_the_untested_marker(+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ """The marker is only ever added at publication. Left on a candidate that has since been tested,+ it both understates the card and makes the auto-accept cleanup delete a proposal that earned its+ test."""+ stored = {+ "workflow_id": "wf-1",+ "_copilot_yaml": "title: Draft\n",+ "_copilot_unvalidated": True,+ COPILOT_PROPOSAL_METADATA_KEY: {+ "owner_turn_id": "turn-a",+ "revision": 1,+ "canonical_fingerprint": "fp",+ "disposition": "review_untested",+ },+ }+ chat = SimpleNamespace(+ organization_id="org-1",+ workflow_copilot_chat_id="chat-1",+ workflow_permanent_id="wpid-1",+ proposed_workflow=stored,+ auto_accept=False,+ )+ tested = MagicMock()+ tested.model_dump = MagicMock(return_value={"workflow_id": "wf-1", "title": "Draft"})+ tested.title = "Draft"+ agent_result = AgentResult(+ user_response="tested it",+ updated_workflow=tested,+ global_llm_context=None,+ response_type="REPLACE_WORKFLOW",+ workflow_yaml="title: Draft\n",+ proposal_disposition="review_tested",+ )+ agent_result.proposal_owner_turn_id = "turn-a"+ agent_result.proposal_revision = 1+ enrich = AsyncMock(return_value=SimpleNamespace(proposed_workflow=None))+ monkeypatch.setattr(+ app.DATABASE,+ "workflow_params",+ SimpleNamespace(+ get_workflow_copilot_chat_by_id=AsyncMock(return_value=SimpleNamespace(proposed_workflow=stored)),+ enrich_workflow_copilot_candidate=enrich,+ update_workflow_copilot_chat=AsyncMock(),+ ),+ )++ await workflow_copilot_route._persist_proposed_workflow_state(chat, agent_result, restored=False)++ assert "_copilot_unvalidated" not in enrich.await_args.kwargs["proposal"]