Skip to content

Automate browser based workflows with AI

Recover a copilot reply when the chat stream drops without a final message (SKY-15412) (#8437)

Andrew Neilson8c759de539f2
diff --git a/docs/cloud/building-agents/run-from-code.mdx b/docs/cloud/building-agents/run-from-code.mdx
index 6197ea00c..6aae2f1db 100644
--- a/docs/cloud/building-agents/run-from-code.mdx
+++ b/docs/cloud/building-agents/run-from-code.mdx
@@ -277,7 +277,7 @@ from skyvern import Skyvern
async def main():
client = Skyvern(api_key=os.getenv("SKYVERN_API_KEY"))
- result = await client.agent.create_workflow_schedule(
+ result = await client.schedules.create(
workflow_permanent_id="wpid_123456789",
cron_expression="0 9 * * 1-5",
timezone="America/New_York",
@@ -327,13 +327,13 @@ curl -X POST "https://api.skyvern.com/api/v1/workflows/wpid_123456789/schedules"
<CodeGroup>
```python Python
# Disable
-await client.agent.disable_workflow_schedule(
+await client.schedules.disable(
workflow_permanent_id="wpid_123456789",
workflow_schedule_id="wfs_abc123"
)
# Re-enable
-await client.agent.enable_workflow_schedule(
+await client.schedules.enable(
workflow_permanent_id="wpid_123456789",
workflow_schedule_id="wfs_abc123"
)
@@ -356,7 +356,7 @@ Permanently remove a schedule. This cannot be undone. Runs that were already tri
<CodeGroup>
```python Python
-await client.agent.delete_workflow_schedule_route(
+await client.schedules.delete(
workflow_permanent_id="wpid_123456789",
workflow_schedule_id="wfs_abc123"
)
diff --git a/docs/snippets/core-concepts-content.mdx b/docs/snippets/core-concepts-content.mdx
index abae38c7d..0dbf53020 100644
--- a/docs/snippets/core-concepts-content.mdx
+++ b/docs/snippets/core-concepts-content.mdx
@@ -188,7 +188,7 @@ A Schedule runs an agent automatically on a recurring basis. You define a cron e
<CodeGroup>
```python Python
-result = await client.agent.create_workflow_schedule(
+result = await client.schedules.create(
workflow_permanent_id="wpid_abc123",
cron_expression="0 9 * * 1-5", # Weekdays at 9 AM
timezone="America/New_York",
diff --git a/skyvern-frontend/src/routes/workflows/copilot/WorkflowCopilotChat.historyRace.test.tsx b/skyvern-frontend/src/routes/workflows/copilot/WorkflowCopilotChat.historyRace.test.tsx
index 7b9678fd7..737920c4e 100644
--- a/skyvern-frontend/src/routes/workflows/copilot/WorkflowCopilotChat.historyRace.test.tsx
+++ b/skyvern-frontend/src/routes/workflows/copilot/WorkflowCopilotChat.historyRace.test.tsx
@@ -20,16 +20,54 @@ type HistoryData = {
auto_accept: boolean;
};
+type StreamCall = {
+ onMessage: (payload: unknown) => boolean;
+ resolve: () => void;
+ reject: (error: unknown) => void;
+};
+
// Only chat-history GETs are deferred (held here so a test controls
-// isLoadingHistory); every other GET resolves immediately.
-const { postStreaming, cancelPost, historyQueue, boolFlags } = vi.hoisted(
- () => ({
- postStreaming: vi.fn(() => new Promise<void>(() => {})),
+// isLoadingHistory); every other GET resolves immediately. Streams are held
+// open too, so a test drives each one to its own ending.
+const {
+ streamCalls,
+ postStreaming,
+ cancelPost,
+ historyQueue,
+ historyRejects,
+ historyParams,
+ workflowGets,
+ hasLocalChanges,
+ historySignals,
+ boolFlags,
+ routeWpid,
+ announceRef,
+} = vi.hoisted(() => {
+ const calls: StreamCall[] = [];
+ return {
+ streamCalls: calls,
+ postStreaming: vi.fn(
+ (
+ _path: string,
+ _body: unknown,
+ onMessage: (payload: unknown) => boolean,
+ ) =>
+ new Promise<void>((resolve, reject) => {
+ calls.push({ onMessage, resolve, reject });
+ }),
+ ),
cancelPost: vi.fn().mockResolvedValue({}),
historyQueue: [] as Array<(resp: { data: HistoryData }) => void>,
+ historyRejects: [] as Array<(reason?: unknown) => void>,
+ workflowGets: [] as string[],
+ hasLocalChanges: { current: false },
+ historyParams: [] as Array<Record<string, unknown> | undefined>,
+ historySignals: [] as Array<AbortSignal | undefined>,
boolFlags: { current: {} as Record<string, boolean> },
- }),
-);
+ routeWpid: { current: "wpid_1" },
+ announceRef: { current: null as ((message: unknown) => void) | null },
+ };
+});
vi.mock("@/api/sse", () => ({
getSseClient: vi.fn().mockResolvedValue({ postStreaming }),
@@ -37,14 +75,26 @@ vi.mock("@/api/sse", () => ({
vi.mock("@/api/AxiosClient", () => ({
getClient: vi.fn().mockResolvedValue({
- get: vi.fn((path: string) => {
- if (path === "/workflow/copilot/chat-history") {
- return new Promise((resolve) => {
- historyQueue.push(resolve as (resp: { data: HistoryData }) => void);
- });
- }
- return Promise.resolve({ data: [] });
- }),
+ get: vi.fn(
+ (
+ path: string,
+ config?: { params?: Record<string, unknown>; signal?: AbortSignal },
+ ) => {
+ if (path === "/workflow/copilot/chat-history") {
+ historyParams.push(config?.params);
+ historySignals.push(config?.signal);
+ return new Promise((resolve, reject) => {
+ historyQueue.push(resolve as (resp: { data: HistoryData }) => void);
+ historyRejects.push(reject);
+ });
+ }
+ if (path.startsWith("/workflows/")) {
+ workflowGets.push(path);
+ return Promise.resolve({ data: { workflow_permanent_id: "wpid_1" } });
+ }
+ return Promise.resolve({ data: [] });
+ },
+ ),
post: cancelPost,
}),
}));
@@ -60,7 +110,7 @@ vi.mock("react-router-dom", async (importOriginal) => {
return {
...actual,
useParams: () => ({
- workflowPermanentId: "wpid_1",
+ workflowPermanentId: routeWpid.current,
workflowRunId: undefined,
}),
useSearchParams: () => [new URLSearchParams(), vi.fn()],
@@ -75,8 +125,8 @@ vi.mock("react-router-dom", async (importOriginal) => {
};
});
-vi.mock("@/store/WorkflowHasChangesStore", () => ({
- useWorkflowHasChangesStore: () => ({
+vi.mock("@/store/WorkflowHasChangesStore", () => {
+ const useWorkflowHasChangesStore = () => ({
getSaveData: () => ({
title: "Test WF",
workflow: {
@@ -92,13 +142,29 @@ vi.mock("@/store/WorkflowHasChangesStore", () => ({
blocks: [],
workflowDefinitionVersion: 1,
}),
- }),
-}));
+ });
+ // The real store is a zustand store; the recovery re-read reads hasChanges
+ // off getState() so it never overwrites unsaved local edits.
+ useWorkflowHasChangesStore.getState = () => ({
+ hasChanges: hasLocalChanges.current,
+ });
+ return { useWorkflowHasChangesStore };
+});
vi.mock("@/routes/workflows/hooks/useWorkflowRunQuery", () => ({
useWorkflowRunQuery: () => ({ data: undefined }),
}));
+vi.mock("./useRunLifecycleAnnouncements", () => ({
+ useRunLifecycleAnnouncements: ({
+ announce,
+ }: {
+ announce: (message: unknown) => void;
+ }) => {
+ announceRef.current = announce;
+ },
+}));
+
// The real selector needs an infinite-query + debounced Popover; a plain button
// standing in for "pick a different past chat" is enough to drive the switch.
vi.mock("./WorkflowCopilotHistory", () => ({
@@ -115,8 +181,11 @@ vi.mock("./WorkflowCopilotHistory", () => ({
),
}));
+import capturedHistory from "./recoveryPoll.chatHistory.fixture.json";
import { WorkflowCopilotChat } from "./WorkflowCopilotChat";
+const normalize = (value: string): string => value.replace(/\s+/g, " ").trim();
+
const narrativePayload = (
overrides: Record<string, unknown> = {},
): Record<string, unknown> => ({
@@ -183,20 +252,22 @@ function chatUi(props: {
async function renderChat(
props: Parameters<typeof chatUi>[0] = {},
-): Promise<void> {
+): Promise<ReturnType<typeof render>> {
let portalTarget: HTMLElement | undefined;
if (props.docked) {
portalTarget = document.createElement("div");
document.body.appendChild(portalTarget);
portalTargets.push(portalTarget);
}
- render(chatUi({ ...props, portalTarget }));
+ const result = render(chatUi({ ...props, portalTarget }));
await waitFor(() => expect(screen.getByRole("textbox")).toBeTruthy());
+ return result;
}
async function flushHistory(data: HistoryData): Promise<void> {
await waitFor(() => expect(historyQueue.length).toBeGreaterThan(0));
const resolve = historyQueue.shift()!;
+ historyRejects.shift();
await act(async () => {
resolve({ data });
await Promise.resolve();
@@ -217,14 +288,22 @@ async function submit(value: string): Promise<void> {
beforeEach(() => {
HTMLElement.prototype.scrollIntoView = vi.fn();
HTMLElement.prototype.scrollTo = vi.fn();
+ streamCalls.length = 0;
postStreaming.mockClear();
cancelPost.mockClear();
cancelPost.mockResolvedValue({});
historyQueue.length = 0;
+ historyRejects.length = 0;
+ historyParams.length = 0;
+ workflowGets.length = 0;
+ hasLocalChanges.current = false;
boolFlags.current = {};
+ routeWpid.current = "wpid_1";
+ announceRef.current = null;
});
afterEach(() => {
+ vi.useRealTimers();
cleanup();
portalTargets.splice(0).forEach((el) => el.remove());
});
@@ -333,3 +412,714 @@ describe("WorkflowCopilotChat — queued prompt survives initial history load (i
);
});
});
+
+// The server keeps the copilot handler running after a client disconnect, so a
+// stream that closes with no terminal frame usually still ends in a persisted
+// assistant row. The fixture is the last turn of a captured chat-history response.
+describe("WorkflowCopilotChat — recovery poll after a non-terminal stream close", () => {
+ const capturedAiRow =
+ capturedHistory.chat_history[capturedHistory.chat_history.length - 1]!;
+ const turnId = capturedAiRow.turn_outcome!.copilot_turn_id;
+ // Markdown renders away, and the row runs to a bulleted summary, so only its
+ // opening line is matched against normalized rendered text.
+ const capturedAiText = normalize(
+ capturedAiRow.content.replace(/[`*]/g, "").split(/\n/)[0]!,
+ );
+ const interruptedText = "This turn was interrupted before it could finish.";
+
+ function renderedText(): string {
+ return normalize(document.body.textContent ?? "");
+ }
+
+ function historyWithRow(row: Record<string, unknown>): HistoryData {
+ return {
+ workflow_copilot_chat_id: capturedHistory.workflow_copilot_chat_id,
+ chat_history: [...capturedHistory.chat_history.slice(0, -1), row],
+ proposed_workflow: null,
+ auto_accept: false,
+ };
+ }
+
+ // The server's own clock, deliberately far behind the client's: correlation
+ // must not depend on comparing it to Date.now().
+ function recoveredHistory(): HistoryData {
+ return historyWithRow({
+ ...capturedAiRow,
+ created_at: "2025-01-01T00:00:00",
+ });
+ }
+
+ function interruptedHistory(): HistoryData {
+ return historyWithRow({
+ sender: "ai",
+ content: interruptedText,
+ created_at: "2025-01-01T00:00:00",
+ narrative_payload: null,
+ turn_outcome: {
+ response_kind: "recover",
+ terminal_reason: "interrupted",
+ copilot_turn_id: turnId,
+ },
+ });
+ }
+
+ // A reply persisted with no turn outcome at all: nothing to correlate on but
+ // its position and its clock.
+ function untaggedHistory(): HistoryData {
+ return historyWithRow({
+ ...capturedAiRow,
+ created_at: new Date(Date.now() + 60_000).toISOString().replace("Z", ""),
+ turn_outcome: null,
+ });
+ }
+
+ // Another tab's turn, persisted after this send: newest row, wrong turn.
+ function otherTurnHistory(): HistoryData {
+ return historyWithRow({
+ ...capturedAiRow,
+ created_at: new Date(Date.now() + 60_000).toISOString().replace("Z", ""),
+ turn_outcome: { ...capturedAiRow.turn_outcome, copilot_turn_id: "other" },
+ });
+ }
+
+ async function emitTurnStart(index = 0): Promise<void> {
+ await act(async () => {
+ streamCalls[index]!.onMessage({
+ type: "turn_start",
+ turn_id: turnId,
+ turn_index: index,
+ timestamp: "2026-09-02T06:33:30Z",
+ });
+ await Promise.resolve();
+ });
+ }
+
+ async function startTurn(
+ chatId: string | null = "chat-1",
+ ): Promise<ReturnType<typeof render>> {
+ const handle = await renderChat();
+ await flushHistory(historyData({ workflow_copilot_chat_id: chatId }));
+ await submit("build me a flow");
+ await waitFor(() => expect(streamCalls.length).toBe(1));
+ await emitTurnStart();
+ vi.useFakeTimers();
+ return handle;
+ }
+
+ async function advance(ms: number): Promise<void> {
+ await act(async () => {
+ await vi.advanceTimersByTimeAsync(ms);
+ });
+ }
+
+ async function closeStreamWithoutTerminal(index = 0): Promise<void> {
+ await act(async () => {
+ streamCalls[index]!.reject(
+ new Error("SSE stream ended without terminal event"),
+ );
+ await Promise.resolve();
+ });
+ }
+
+ async function emitTerminalResponse(index = 0): Promise<void> {
+ await act(async () => {
+ streamCalls[index]!.onMessage({
+ type: "response",
+ workflow_copilot_chat_id: "chat-1",
+ message: "All done.",
+ updated_workflow: null,
+ response_time: "2026-08-16T02:02:13Z",
+ proposal_disposition: "no_proposal",
+ });
+ streamCalls[index]!.resolve();
+ await Promise.resolve();
+ });
+ }
+
+ async function resolveNextHistory(data: HistoryData): Promise<void> {
+ expect(historyQueue.length).toBeGreaterThan(0);
+ const resolve = historyQueue.shift()!;
+ historyRejects.shift();
+ await act(async () => {
+ resolve({ data });
+ await Promise.resolve();
+ });
+ }
+
+ it("renders the assistant row the server persisted, replacing the error bubble", async () => {
+ await startTurn();
+ await closeStreamWithoutTerminal();
+ expect(
+ screen.getByText(
+ "The connection dropped, so Copilot is checking whether this turn finished.",
+ ),
+ ).toBeTruthy();
+ expect(
+ screen.queryByText("Sorry, I encountered an error. Please try again."),
+ ).toBeNull();
+ expect(historyQueue.length).toBe(0);
+
+ await advance(2_000);
+ await resolveNextHistory(recoveredHistory());
+
+ expect(renderedText()).toContain(capturedAiText);
+ expect(
+ screen.queryByText(
+ "The connection dropped, so Copilot is checking whether this turn finished.",
+ ),
+ ).toBeNull();
+ });
+
+ it("recovers a brand-new chat's first turn, whose id never arrived", async () => {
+ await startTurn(null);
+ await closeStreamWithoutTerminal();
+
+ await advance(2_000);
+ expect(historyParams[historyParams.length - 1]).toEqual({
+ workflow_permanent_id: "wpid_1",
+ });
+
+ await resolveNextHistory(recoveredHistory());
+ expect(renderedText()).toContain(capturedAiText);
+ });
+
+ it("keeps polling while the only assistant row belongs to another turn", async () => {
+ await startTurn();
+ await closeStreamWithoutTerminal();
+
+ await advance(2_000);
+ await resolveNextHistory(otherTurnHistory());
+ expect(renderedText()).not.toContain(capturedAiText);
+
+ await advance(3_000);
+ await resolveNextHistory(recoveredHistory());
+ expect(renderedText()).toContain(capturedAiText);
+ });
+
+ it("keeps reading past the reconcile threshold and lets the real reply supersede the interrupted row", async () => {
+ await startTurn();
+ await closeStreamWithoutTerminal();
+
+ // Each pass is one poll cycle; 45 of them carry virtual time past the
+ // server's ~1320s reconcile threshold with nothing persisted yet.
+ const startedAt = Date.now();
+ for (let i = 0; i < 45; i += 1) {
+ await advance(30_000);
+ await resolveNextHistory(historyData({ chat_history: [] }));
+ }
+ expect(Date.now() - startedAt).toBeGreaterThan(1_320_000);
+
+ await advance(30_000);
+ await resolveNextHistory(interruptedHistory());
+ expect(renderedText()).toContain(interruptedText);
+
+ await advance(30_000);
+ await resolveNextHistory(recoveredHistory());
+ expect(renderedText()).toContain(capturedAiText);
+ });
+
+ it("reads on its own timer only, and stops once the budget elapses", async () => {
+ await startTurn();
+ await closeStreamWithoutTerminal();
+
+ await act(async () => {
+ window.dispatchEvent(new Event("focus"));
+ document.dispatchEvent(new Event("visibilitychange"));
+ await Promise.resolve();
+ });
+ expect(historyQueue.length).toBe(0);
+
+ // Each pass is one poll cycle; enough of them carry virtual time past the
+ // poll's own 1_500_000ms budget with nothing ever persisted. The budget
+ // fires on its own timer, so the last cycle stops mid-loop rather than
+ // after a fixed count.
+ const startedAt = Date.now();
+ let reads = 0;
+ for (let i = 0; i < 64; i += 1) {
+ await advance(30_000);
+ if (historyQueue.length === 0) {
+ break;
+ }
+ await resolveNextHistory(historyData({ chat_history: [] }));
+ reads += 1;
+ }
+ expect(reads).toBeGreaterThan(40);
+ expect(Date.now() - startedAt).toBeGreaterThanOrEqual(1_500_000);
+
+ await advance(300_000);
+ await act(async () => {
+ window.dispatchEvent(new Event("focus"));
+ document.dispatchEvent(new Event("visibilitychange"));
+ await Promise.resolve();
+ });
+ expect(historyQueue.length).toBe(0);
+ });
+
+ it("keeps an earlier turn's recovery alive across a later send", async () => {
+ await startTurn();
+ await closeStreamWithoutTerminal();
+
+ await submit("another one");
+ for (let i = 0; i < 20 && streamCalls.length < 2; i += 1) {
+ await advance(10);
+ }
+ expect(streamCalls.length).toBe(2);
+ await emitTerminalResponse(1);
+
+ await advance(2_000);
+ await resolveNextHistory(recoveredHistory());
+ expect(renderedText()).toContain(capturedAiText);
+ });
+
+ it("does not re-read history when the stream ends on a terminal frame", async () => {
+ await startTurn();
+ await emitTerminalResponse();
+
+ await advance(30_000);
+ expect(historyQueue.length).toBe(0);
+ });
+
+ it("does not re-read history when the user stopped the turn", async () => {
+ await startTurn();
+ await act(async () => {
+ fireEvent.keyDown(document, { key: "Escape" });
+ await Promise.resolve();
+ });
+ expect(cancelPost).toHaveBeenCalledWith(
+ "/workflow/copilot/cancel",
+ expect.anything(),
+ );
+ await closeStreamWithoutTerminal();
+
+ await advance(30_000);
+ expect(historyQueue.length).toBe(0);
+ });
+
+ it("does not re-read history for a stream that never announced a turn", async () => {
+ // Without a turn id there is nothing to correlate a row against, so the
+ // poll must not arm at all rather than match on position.
+ await renderChat();
+ await flushHistory(historyData());
+ await submit("build me a flow");
+ await waitFor(() => expect(streamCalls.length).toBe(1));
+ vi.useFakeTimers();
+ await closeStreamWithoutTerminal();
+
+ await advance(30_000);
+ expect(historyQueue.length).toBe(0);
+ });
+
+ it("gives up and shows the plain failure once reads keep failing", async () => {
+ await startTurn();
+ await closeStreamWithoutTerminal();
+ expect(renderedText()).toContain(
+ "Copilot is checking whether this turn finished",
+ );
+
+ // The usual cause of a severed stream is a client that lost the network, so
+ // every recovery read fails too; it must not hold the notice for 25 minutes.
+ for (let i = 0; i < 3; i += 1) {
+ await advance(30_000);
+ expect(historyQueue.length).toBeGreaterThan(0);
+ historyQueue.shift();
+ const failRead = historyRejects.shift()!;
+ await act(async () => {
+ failRead(new Error("offline"));
+ await Promise.resolve();
+ });
+ }
+
+ await advance(120_000);
+ expect(historyQueue.length).toBe(0);
+ expect(renderedText()).not.toContain(
+ "Copilot is checking whether this turn finished",
+ );
+ expect(renderedText()).toContain("Sorry, I encountered an error");
+ });
+
+ it("does not re-read history for a turn whose chat the user left mid-stream", async () => {
+ await startTurn();
+ await act(async () => {
+ fireEvent.click(screen.getByText("mock-select-history-chat"));
+ await Promise.resolve();
+ });
+ const switchLoad = historyQueue.shift()!;
+ await act(async () => {
+ switchLoad({
+ data: historyData({ workflow_copilot_chat_id: "chat_other" }),
+ });
+ await Promise.resolve();
+ });
+ await closeStreamWithoutTerminal();
+
+ await advance(30_000);
+ expect(historyQueue.length).toBe(0);
+ });
+
+ it("stops the poll when the route moves to another workflow", async () => {
+ const handle = await startTurn();
+ await closeStreamWithoutTerminal();
+
+ routeWpid.current = "wpid_2";
+ await act(async () => {
+ handle.rerender(chatUi({}));
+ await Promise.resolve();
+ });
+ await advance(1);
+ await resolveNextHistory(
+ historyData({ workflow_copilot_chat_id: "chat_other_workflow" }),
+ );
+
+ await advance(30_000);
+ expect(historyQueue.length).toBe(0);
+ });
+
+ it("arms the poll on the connected-account refresh, which is the same severed stream", async () => {
+ await renderChat();
+ await flushHistory(
+ historyData({
+ chat_history: [
+ {
+ sender: "ai",
+ content: "Which account should I use?",
+ created_at: "2026-07-15T00:00:00Z",
+ narrative_payload: narrativePayload({ turnId: "turn-choice" }),
+ turn_outcome: {
+ response_kind: "clarify",
+ connected_account_choices: [
+ {
+ connection_id: "conn_12345678",
+ name: "Work account",
+ state: "active",
+ email_address: "[email protected]",
+ },
+ ],
+ },
+ },
+ ],
+ }),
+ );
+
+ await act(async () => {
+ fireEvent.click(screen.getByRole("button", { name: /Work account/ }));
+ });
+ await waitFor(() => expect(streamCalls.length).toBe(1));
+ await emitTurnStart();
+ vi.useFakeTimers();
+ await closeStreamWithoutTerminal();
+
+ // The catch branch's own in-place refresh reads once, far too early.
+ await resolveNextHistory(historyData({ chat_history: [] }));
+
+ await advance(2_000);
+ await resolveNextHistory(recoveredHistory());
+ expect(renderedText()).toContain(capturedAiText);
+ });
+
+ it("does not arm when a chat switch lands during the connected-account refresh", async () => {
+ await renderChat();
+ await flushHistory(
+ historyData({
+ chat_history: [
+ {
+ sender: "ai",
+ content: "Which account should I use?",
+ created_at: "2026-07-15T00:00:00Z",
+ narrative_payload: narrativePayload({ turnId: "turn-choice" }),
+ turn_outcome: {
+ response_kind: "clarify",
+ connected_account_choices: [
+ {
+ connection_id: "conn_12345678",
+ name: "Work account",
+ state: "active",
+ email_address: "[email protected]",
+ },
+ ],
+ },
+ },
+ ],
+ }),
+ );
+
+ await act(async () => {
+ fireEvent.click(screen.getByRole("button", { name: /Work account/ }));
+ });
+ await waitFor(() => expect(streamCalls.length).toBe(1));
+ await emitTurnStart();
+ vi.useFakeTimers();
+ await closeStreamWithoutTerminal();
+
+ // The refresh forgives its own single generation bump. Here the user also
+ // leaves for another chat while it is still awaiting, so the turn belongs
+ // to a chat that is no longer on screen and must not arm.
+ await act(async () => {
+ fireEvent.click(screen.getByText("mock-select-history-chat"));
+ await Promise.resolve();
+ });
+ while (historyQueue.length > 0) {
+ await act(async () => {
+ historyQueue.shift()!({
+ data: historyData({ workflow_copilot_chat_id: "chat_other" }),
+ });
+ await Promise.resolve();
+ });
+ }
+
+ await advance(30_000);
+ expect(historyQueue.length).toBe(0);
+ });
+
+ it("recovers a reply the server persisted with no turn outcome", async () => {
+ await startTurn();
+ await closeStreamWithoutTerminal();
+
+ await advance(2_000);
+ await resolveNextHistory(untaggedHistory());
+ expect(renderedText()).toContain(capturedAiText);
+
+ await advance(30_000);
+ expect(historyQueue.length).toBe(0);
+ });
+
+ it("will not adopt an untagged row while polling by workflow id", async () => {
+ // No chat id means the read resolves "the workflow's latest chat", which can
+ // be another tab's. An untagged row there carries nothing tying it to this
+ // turn, so only an id match may end the poll.
+ await startTurn(null);
+ await closeStreamWithoutTerminal();
+
+ await advance(2_000);
+ expect(historyParams[historyParams.length - 1]).toEqual({
+ workflow_permanent_id: "wpid_1",
+ });
+ await resolveNextHistory(untaggedHistory());
+ expect(renderedText()).not.toContain(capturedAiText);
+
+ await advance(3_000);
+ await resolveNextHistory(recoveredHistory());
+ expect(renderedText()).toContain(capturedAiText);
+ });
+
+ it("aborts the read in flight when the budget elapses", async () => {
+ await startTurn();
+ await closeStreamWithoutTerminal();
+
+ await advance(2_000);
+ const inFlight = historySignals[historySignals.length - 1];
+ expect(inFlight?.aborted).toBe(false);
+
+ // Past the budget with the read still unresolved: the deadline must reach
+ // the request, not just the timer that scheduled it.
+ await advance(1_500_000);
+ expect(inFlight?.aborted).toBe(true);
+
+ // The aborted read rejects; that rejection must not reschedule the ladder.
+ await act(async () => {
+ historyQueue.shift();
+ await Promise.resolve();
+ });
+ await advance(30_000);
+ expect(historyQueue.length).toBe(0);
+ });
+
+ it("stays on the chat it first resolved when polling by workflow id", async () => {
+ await startTurn(null);
+ await closeStreamWithoutTerminal();
+
+ await advance(2_000);
+ expect(historyParams[historyParams.length - 1]).toEqual({
+ workflow_permanent_id: "wpid_1",
+ });
+ // Another tab can create a newer chat, and "the workflow's latest" would
+ // then resolve away from this turn's chat for every later read.
+ await resolveNextHistory(
+ historyData({
+ workflow_copilot_chat_id: "chat_of_this_turn",
+ chat_history: [],
+ }),
+ );
+
+ await advance(3_000);
+ expect(historyParams[historyParams.length - 1]).toEqual({
+ workflow_copilot_chat_id: "chat_of_this_turn",
+ });
+ });
+
+ it("does not apply history fetched before a send that came and went", async () => {
+ await startTurn();
+ await closeStreamWithoutTerminal();
+
+ await advance(2_000);
+ expect(historyQueue.length).toBe(1);
+ const staleRead = historyQueue.shift()!;
+
+ // A whole send begins and ends while that read is outstanding, so the
+ // in-flight flag is false at both ends of it.
+ await submit("another one");
+ for (let i = 0; i < 20 && streamCalls.length < 2; i += 1) {
+ await advance(10);
+ }
+ expect(streamCalls.length).toBe(2);
+ await act(async () => {
+ streamCalls[1]!.resolve();
+ await Promise.resolve();
+ });
+
+ await act(async () => {
+ staleRead({ data: recoveredHistory() });
+ await Promise.resolve();
+ });
+ // Applying it would rebuild the transcript without the send that just ran.
+ expect(renderedText()).toContain("another one");
+
+ await advance(30_000);
+ expect(historyQueue.length).toBeGreaterThan(0);
+ });
+
+ it("drops the refreshing notice when the budget runs out", async () => {
+ await startTurn();
+ await closeStreamWithoutTerminal();
+ expect(renderedText()).toContain(
+ "Copilot is checking whether this turn finished",
+ );
+
+ for (let i = 0; i < 64; i += 1) {
+ await advance(30_000);
+ if (historyQueue.length === 0) {
+ break;
+ }
+ await resolveNextHistory(historyData({ chat_history: [] }));
+ }
+
+ // Recovery has stopped, so a notice saying it is still refreshing is stale.
+ expect(renderedText()).not.toContain(
+ "Copilot is checking whether this turn finished",
+ );
+ expect(renderedText()).toContain("Sorry, I encountered an error");
+ });
+
+ it("stops watching for a supersede well short of the budget", async () => {
+ await startTurn();
+ await closeStreamWithoutTerminal();
+
+ // A turn cancelled by a worker drain writes this row and never finishes, so
+ // waiting out the budget would have every open chat polling through a
+ // deploy.
+ await advance(2_000);
+ await resolveNextHistory(interruptedHistory());
+ expect(renderedText()).toContain(interruptedText);
+
+ let reads = 0;
+ for (let i = 0; i < 30; i += 1) {
+ await advance(30_000);
+ if (historyQueue.length === 0) {
+ break;
+ }
+ await resolveNextHistory(interruptedHistory());
+ reads += 1;
+ }
+ expect(reads).toBeLessThan(10);
+ expect(historyQueue.length).toBe(0);
+ });
+
+ it("re-reads the workflow once a recovered turn lands", async () => {
+ await startTurn();
+ await closeStreamWithoutTerminal();
+
+ await advance(2_000);
+ await resolveNextHistory(recoveredHistory());
+ expect(renderedText()).toContain(capturedAiText);
+
+ // The turn may have committed a build the editor never saw, and its terminal
+ // frame never arrived to apply it; a stale graph here is what a later save
+ // would write back over the commit.
+ await act(async () => {
+ await Promise.resolve();
+ });
+ expect(workflowGets.some((url) => url === "/workflows/wpid_1")).toBe(true);
+ });
+
+ it("leaves the workflow alone when the editor has unsaved edits", async () => {
+ hasLocalChanges.current = true;
+ await startTurn();
+ await closeStreamWithoutTerminal();
+
+ await advance(2_000);
+ await resolveNextHistory(recoveredHistory());
+ expect(renderedText()).toContain(capturedAiText);
+
+ await act(async () => {
+ await Promise.resolve();
+ });
+ // Losing edits the user can see is worse than the stale graph being fixed.
+ expect(workflowGets).toEqual([]);
+ });
+
+ it("re-arming the same turn replaces its ladder instead of adding one", async () => {
+ await startTurn();
+ await closeStreamWithoutTerminal();
+
+ await submit("another one");
+ for (let i = 0; i < 20 && streamCalls.length < 2; i += 1) {
+ await advance(10);
+ }
+ expect(streamCalls.length).toBe(2);
+ await emitTurnStart(1);
+ await closeStreamWithoutTerminal(1);
+
+ await advance(2_500);
+ expect(historyQueue.length).toBe(1);
+ });
+
+ it("keeps this chat's run-lifecycle lines when the recovered row lands", async () => {
+ await startTurn();
+ await closeStreamWithoutTerminal();
+ await act(async () => {
+ announceRef.current!({
+ id: "run-lifecycle-wr_1-start",
+ sender: "ai",
+ kind: "run_lifecycle",
+ content: "Run started - watching it now.",
+ });
+ await Promise.resolve();
+ });
+
+ await advance(2_000);
+ await resolveNextHistory(recoveredHistory());
+
+ expect(renderedText()).toContain(capturedAiText);
+ expect(screen.getByText("Run started - watching it now.")).toBeTruthy();
+ });
+
+ it("discards a response that lands after the user switched chats", async () => {
+ await startTurn();
+ await closeStreamWithoutTerminal();
+ await advance(2_000);
+ expect(historyQueue.length).toBe(1);
+ const stalePoll = historyQueue.shift()!;
+
+ await act(async () => {
+ fireEvent.click(screen.getByText("mock-select-history-chat"));
+ await Promise.resolve();
+ });
+ const switchLoad = historyQueue.shift()!;
+ await act(async () => {
+ switchLoad({
+ data: historyData({
+ workflow_copilot_chat_id: "chat_other",
+ chat_history: [aiHistoryMessage(null, "Other chat reply.")],
+ }),
+ });
+ await Promise.resolve();
+ });
+
+ await act(async () => {
+ stalePoll({ data: recoveredHistory() });
+ await Promise.resolve();
+ });
+
+ expect(screen.getByText("Other chat reply.")).toBeTruthy();
+ expect(renderedText()).not.toContain(capturedAiText);
+ });
+});
diff --git a/skyvern-frontend/src/routes/workflows/copilot/WorkflowCopilotChat.queue.test.tsx b/skyvern-frontend/src/routes/workflows/copilot/WorkflowCopilotChat.queue.test.tsx
index 02c4595e7..99cd281a1 100644
--- a/skyvern-frontend/src/routes/workflows/copilot/WorkflowCopilotChat.queue.test.tsx
+++ b/skyvern-frontend/src/routes/workflows/copilot/WorkflowCopilotChat.queue.test.tsx
@@ -818,7 +818,9 @@ describe("WorkflowCopilotChat — keep the chat live during a turn", () => {
// Resetting the narrative stops the progress/elapsed indicator from
// ticking forever beside the error message.
expect(screen.queryAllByRole("status")).toHaveLength(0);
- expect(screen.getByText(/I encountered an error/)).toBeTruthy();
+ expect(
+ screen.getByText(/Copilot is checking whether this turn finished/),
+ ).toBeTruthy();
});
it("renders a response-only error narrative payload as halted", async () => {
diff --git a/skyvern-frontend/src/routes/workflows/copilot/WorkflowCopilotChat.tsx b/skyvern-frontend/src/routes/workflows/copilot/WorkflowCopilotChat.tsx
index a7aee1c61..53eb52e77 100644
--- a/skyvern-frontend/src/routes/workflows/copilot/WorkflowCopilotChat.tsx
+++ b/skyvern-frontend/src/routes/workflows/copilot/WorkflowCopilotChat.tsx
@@ -40,6 +40,7 @@ import { getSseClient } from "@/api/sse";
import {
WorkflowCopilotCancelRequest,
WorkflowCopilotCancelSource,
+ WorkflowCopilotChatHistoryMessage,
WorkflowCopilotChatHistoryResponse,
WorkflowCopilotDesignEndUpdate,
WorkflowCopilotDesignStartUpdate,
@@ -135,6 +136,30 @@ import { TooltipProvider } from "@/components/ui/tooltip";
// Cap on retained per-turn snap-back snapshots. A typical session has a
// handful of turns; this ceiling guards a runaway long-running chat.
const MAX_TURN_SNAPSHOTS = 20;
+// A stream that closes with no terminal frame is usually a lost client
+// connection while the server handler runs on to persist the real reply, so the
+// ladder is sized to the server's own turn budget rather than to a short wait.
+const RECOVERY_POLL_DELAYS_MS = [2_000, 3_000, 5_000, 8_000, 12_000, 20_000];
+const RECOVERY_POLL_STEADY_MS = 30_000;
+// The server's RECONCILE_ABANDON_AFTER_SECONDS is 1_320_000ms. The margin holds
+// several 30s reads past it, so a turn whose reply was never persisted reaches
+// both the read that produces its interrupted row and the later one that picks
+// up the real reply if the turn finishes after all.
+const RECOVERY_POLL_BUDGET_MS = 1_500_000;
+const INTERRUPTED_TERMINAL_REASON = "interrupted";
+const SEND_FAILED_MESSAGE = "Sorry, I encountered an error. Please try again.";
+// A severed stream is usually the client losing the network, so recovery reads
+// fail too. Few enough that an offline user gets the plain failure back in
+// seconds; more than one so a single blip does not end a live recovery.
+const RECOVERY_POLL_FAILURE_CEILING = 3;
+// Reads spent watching for the real reply to replace an interrupted row. A turn
+// cancelled operationally never produces one, so this is bounded well short of
+// the budget.
+const RECOVERY_POLL_SUPERSEDE_READS = 4;
+// Says only what is true: the composer stays enabled while this is showing, so
+// it must not claim a retry is being held back.
+const RECOVERY_IN_PROGRESS_MESSAGE =
+ "The connection dropped, so Copilot is checking whether this turn finished.";
const TEST_END_TO_END_PROMPT = "Test this workflow end to end.";
// Cadence for re-fetching a live test run's recorded actions. Mirrors the
@@ -210,6 +235,41 @@ const STOP_NOT_SENT_NOTICE =
const STOP_ORBIT_GRADIENT =
"conic-gradient(from 0deg, rgba(120,170,255,.08) 0deg, rgba(120,170,255,.08) 120deg, rgba(150,195,255,.55) 250deg, #dbeaff 330deg, rgba(120,170,255,.08) 360deg)";
+function parseServerStamp(createdAt: string): number {
+ const stamp = /(Z|[+-]\d{2}:?\d{2})$/.test(createdAt)
+ ? createdAt
+ : `${createdAt}Z`;
+ const parsed = Date.parse(stamp);
+ return Number.isFinite(parsed) ? parsed : NaN;
+}
+
+function findRecoveredRow(
+ history: WorkflowCopilotChatHistoryMessage[],
+ turnId: string,
+ untaggedBaseline: number | null,
+): WorkflowCopilotChatHistoryMessage | null {
+ const byTurnId = history.find(
+ (message) =>
+ message.sender === "ai" &&
+ message.turn_outcome?.copilot_turn_id === turnId,
+ );
+ if (byTurnId) {
+ return byTurnId;
+ }
+ // turn_outcome is optional on a persisted row, so a reply written without one
+ // carries no id to match. The baseline is a server stamp so both sides of this
+ // comparison come from the same clock; a client clock here let skew adopt
+ // another turn's row or suppress our own.
+ if (untaggedBaseline === null) {
+ return null;
+ }
+ const last = history[history.length - 1];
+ if (!last || last.sender !== "ai" || last.turn_outcome?.copilot_turn_id) {
+ return null;
+ }
+ return parseServerStamp(last.created_at) > untaggedBaseline ? last : null;
+}
+
function isPictographic(glyph: string): boolean {
try {
return /\p{Extended_Pictographic}/u.test(glyph);
@@ -827,6 +887,10 @@ export function WorkflowCopilotChat({
// rapid double-submit would run a stale closure and start a second stream;
// this ref is set before the first await and read at the top of handleSend.
const inFlightRef = useRef(false);
+ // Counts sends rather than tracking one in progress: a send that both starts
+ // and finishes inside a recovery read leaves inFlightRef false at either end
+ // of it, and applying history fetched before that send would drop its turn.
+ const sendEpoch = useRef(0);
// This latch closes the same-render double-click window before React can
// publish isLoading. Once a selection queues behind another turn, isLoading
// keeps every account row disabled until that queue drains.
@@ -867,6 +931,12 @@ export function WorkflowCopilotChat({
// Backend cancel watcher polls Redis: a turn can complete normally between
// the cancel POST and the watcher firing, so the frontend must remember it.
const cancelInFlightController = useRef<AbortController | null>(null);
+ const recoveryPolls = useRef(new Map<string, () => void>());
+ const recoveryGeneration = useRef(0);
+ // The poll is declared before the reconcile it calls on a recovered row.
+ const reconcileCanonicalWorkflowRef = useRef<(() => Promise<void>) | null>(
+ null,
+ );
const [workflowCopilotChatId, setWorkflowCopilotChatId] = useState<
string | null
>(null);
@@ -909,6 +979,7 @@ export function WorkflowCopilotChat({
}, [workflowCopilotChatId]);
useEffect(() => {
const activePolls = actionPollRef.current;
+ const activeRecoveryPolls = recoveryPolls.current;
return () => {
streamingAbortController.current?.abort();
activePolls.forEach((timer) => clearInterval(timer));
@@ -925,6 +996,9 @@ export function WorkflowCopilotChat({
clearTimeout(gateFlashTimer.current);
gateFlashTimer.current = null;
}
+ recoveryGeneration.current += 1;
+ activeRecoveryPolls.forEach((stop) => stop());
+ activeRecoveryPolls.clear();
};
}, []);
const [size, setSize] = useState({
@@ -1445,6 +1519,7 @@ export function WorkflowCopilotChat({
}, []);
const handleNewChat = () => {
+ stopRecoveryPolls();
setMessages([]);
updateQueuedPrompt(null);
setWorkflowCopilotChatId(null);
@@ -1513,9 +1588,209 @@ export function WorkflowCopilotChat({
[],
);
+ const stopRecoveryPolls = useCallback(() => {
+ // Bumping the generation also discards responses already in flight, which
+ // clearTimeout alone cannot cancel.
+ recoveryGeneration.current += 1;
+ recoveryPolls.current.forEach((stop) => stop());
+ recoveryPolls.current.clear();
+ }, []);
+
+ const startRecoveryPoll = useCallback(
+ (chatId: string | null, turnId: string) => {
+ if (!workflowPermanentId) {
+ return;
+ }
+ const generation = recoveryGeneration.current;
+ const deadline = Date.now() + RECOVERY_POLL_BUDGET_MS;
+ let timer: ReturnType<typeof setTimeout> | null = null;
+ let step = 0;
+ let appliedContent: string | null = null;
+ // Latching an id below makes later reads consistent, but an id resolved
+ // from "the workflow's latest chat" is not proof the chat is this turn's,
+ // so what gates the untagged fallback is how the poll started.
+ const scopedToKnownChat = chatId !== null;
+ let untaggedBaseline: number | null = null;
+ let inFlight: AbortController | null = null;
+ let deadlineTimer: ReturnType<typeof setTimeout> | null = null;
+ let consecutiveFailures = 0;
+ let supersedeReadsLeft = RECOVERY_POLL_SUPERSEDE_READS;
+ let stopped = false;
+
+ const clearTimer = () => {
+ if (timer !== null) {
+ clearTimeout(timer);
+ timer = null;
+ }
+ // Without this a hung request outlives the budget and unmount cleanup,
+ // which clear only the timer.
+ inFlight?.abort();
+ inFlight = null;
+ };
+ function finish() {
+ stopped = true;
+ clearTimer();
+ if (deadlineTimer !== null) {
+ clearTimeout(deadlineTimer);
+ deadlineTimer = null;
+ }
+ if (recoveryPolls.current.get(turnId) === finish) {
+ recoveryPolls.current.delete(turnId);
+ }
+ }
+
+ // Ending without the turn's row leaves a notice describing work that has
+ // stopped, so it reverts to the plain failure it replaced.
+ function giveUp() {
+ finish();
+ setMessages((prev) =>
+ prev.map((message) =>
+ message.content === RECOVERY_IN_PROGRESS_MESSAGE
+ ? { ...message, content: SEND_FAILED_MESSAGE }
+ : message,
+ ),
+ );
+ }
+
+ recoveryPolls.current.get(turnId)?.();
+ recoveryPolls.current.set(turnId, finish);
+ // A read that never returns leaves schedule() unreached, so the budget
+ // needs a timer of its own or the deadline can never fire.
+ deadlineTimer = setTimeout(giveUp, RECOVERY_POLL_BUDGET_MS);
+
+ function schedule() {
+ clearTimer();
+ // finish() aborts the in-flight read, which surfaces in tick's catch;
+ // without this the rejection would reschedule a stopped poll.
+ if (stopped || Date.now() >= deadline) {
+ finish();
+ return;
+ }
+ const delay = RECOVERY_POLL_DELAYS_MS[step] ?? RECOVERY_POLL_STEADY_MS;
+ step += 1;
+ timer = setTimeout(() => {
+ timer = null;
+ void tick();
+ }, delay);
+ }
+
+ async function tick() {
+ if (recoveryGeneration.current !== generation) {
+ finish();
+ return;
+ }
+ const sendEpochBeforeRead = sendEpoch.current;
+ try {
+ const client = await getClient(credentialGetter, "sans-api-v1");
+ const controller = new AbortController();
+ inFlight = controller;
+ const response = await client.get<WorkflowCopilotChatHistoryResponse>(
+ "/workflow/copilot/chat-history",
+ {
+ params: chatId
+ ? { workflow_copilot_chat_id: chatId }
+ : { workflow_permanent_id: workflowPermanentId },
+ signal: controller.signal,
+ },
+ );
+ if (inFlight === controller) {
+ inFlight = null;
+ }
+ // Without a chat id the read resolves "the workflow's latest chat",
+ // which another tab can move by creating a newer one. Latching the
+ // first id keeps every later read on the chat this turn recovered in.
+ if (chatId === null && response.data.workflow_copilot_chat_id) {
+ chatId = response.data.workflow_copilot_chat_id;
+ }
+ if (recoveryGeneration.current !== generation) {
+ finish();
+ return;
+ }
+ if (untaggedBaseline === null) {
+ // Polling by workflow_permanent_id can resolve to another tab's
+ // chat, so an untagged row there is not ours to adopt. The last row
+ // is excluded so a reply that landed before this first read can
+ // still clear the baseline it would otherwise have set.
+ untaggedBaseline = !scopedToKnownChat
+ ? Number.POSITIVE_INFINITY
+ : response.data.chat_history
+ .slice(0, -1)
+ .reduce((newest, message) => {
+ const stamp = parseServerStamp(message.created_at);
+ return stamp > newest ? stamp : newest;
+ }, Number.NEGATIVE_INFINITY);
+ }
+ const row = findRecoveredRow(
+ response.data.chat_history,
+ turnId,
+ untaggedBaseline,
+ );
+ if (row) {
+ // Applying history while a later turn streams would wipe its
+ // optimistic rows, so leave the row for a tick after that send.
+ // The epoch covers a send that began and ended within this read,
+ // which leaves inFlightRef false at both ends of it.
+ if (
+ inFlightRef.current ||
+ sendEpoch.current !== sendEpochBeforeRead
+ ) {
+ schedule();
+ return;
+ }
+ if (row.content !== appliedContent) {
+ appliedContent = row.content;
+ applyHistoryResponse(response.data);
+ }
+ // An interrupted row is replaced by the real reply if the turn
+ // later finishes, so only a finished row ends the poll.
+ if (
+ row.turn_outcome?.terminal_reason !== INTERRUPTED_TERMINAL_REASON
+ ) {
+ void reconcileCanonicalWorkflowRef.current?.();
+ finish();
+ return;
+ }
+ // A turn cancelled operationally (a worker drain) writes this row
+ // and never finishes, so waiting out the budget would have every
+ // open chat polling in lockstep through a deploy. The user already
+ // has a truthful row; only a few reads are spent on a supersede.
+ supersedeReadsLeft -= 1;
+ if (supersedeReadsLeft <= 0) {
+ finish();
+ return;
+ }
+ }
+ } catch (error) {
+ console.warn("Copilot recovery poll failed:", error);
+ if (recoveryGeneration.current !== generation) {
+ finish();
+ return;
+ }
+ // The usual cause of a severed stream is the client losing the
+ // network, and then every read fails too. Rescheduling through that
+ // holds the notice for the whole budget and withholds the error the
+ // user used to get at once, so a run of failures ends the poll.
+ consecutiveFailures += 1;
+ if (consecutiveFailures >= RECOVERY_POLL_FAILURE_CEILING) {
+ giveUp();
+ return;
+ }
+ schedule();
+ return;
+ }
+ consecutiveFailures = 0;
+ schedule();
+ }
+
+ schedule();
+ },
+ [applyHistoryResponse, credentialGetter, workflowPermanentId],
+ );
+
const loadChatInPlace = useCallback(
async (chatId: string) => {
if (!workflowPermanentId) return;
+ stopRecoveryPolls();
setIsLoadingHistory(true);
updateQueuedPrompt(null);
setRejectedTurnIds(new Set());
@@ -1551,6 +1826,7 @@ export function WorkflowCopilotChat({
credentialGetter,
workflowPermanentId,
applyHistoryResponse,
+ stopRecoveryPolls,
updateQueuedPrompt,
repin,
],
@@ -1616,6 +1892,31 @@ export function WorkflowCopilotChat({
[onWorkflowUpdate],
);
+ // A turn that auto-committed a build applies it from the terminal frame. A
+ // recovered turn never had that frame, so the editor can still hold the graph
+ // from before the drop and a later save would write it back over the commit.
+ // Reading canonical is the same thing the reload used to do.
+ const reconcileCanonicalWorkflow = useCallback(async () => {
+ if (!workflowPermanentId) {
+ return;
+ }
+ // Unsaved local edits outrank a stale graph: overwriting them would lose
+ // work the user can see, which is worse than the staleness being fixed.
+ if (useWorkflowHasChangesStore.getState().hasChanges) {
+ return;
+ }
+ try {
+ const client = await getClient(credentialGetter);
+ const response = await client.get<WorkflowApiResponse>(
+ `/workflows/${workflowPermanentId}`,
+ );
+ applyWorkflowUpdate(response.data, { persisted: true, applied: true });
+ } catch (error) {
+ console.warn("Failed to re-read the workflow after recovery:", error);
+ }
+ }, [applyWorkflowUpdate, credentialGetter, workflowPermanentId]);
+ reconcileCanonicalWorkflowRef.current = reconcileCanonicalWorkflow;
+
// Records the accepted turn (for the "Applied changes" relabel) before
// clearing the pending-gate handle, shared by all three accept outcomes.
const markProposalAccepted = () => {
@@ -1869,6 +2170,7 @@ export function WorkflowCopilotChat({
useEffect(() => {
if (!workflowPermanentId) {
+ stopRecoveryPolls();
setMessages([]);
updateQueuedPrompt(null);
setWorkflowCopilotChatId(null);
@@ -1883,6 +2185,9 @@ export function WorkflowCopilotChat({
if (historyLoadedForRef.current === workflowPermanentId) {
return;
}
+ // Reached only when this workflow's transcript is about to replace another's,
+ // so a poll armed against the outgoing chat must not apply history here.
+ stopRecoveryPolls();
let isMounted = true;
@@ -1919,6 +2224,7 @@ export function WorkflowCopilotChat({
}, [
credentialGetter,
repin,
+ stopRecoveryPolls,
updateQueuedPrompt,
workflowPermanentId,
applyHistoryResponse,
@@ -2199,6 +2505,7 @@ export function WorkflowCopilotChat({
}
setIsLoading(true);
inFlightRef.current = true;
+ sendEpoch.current += 1;
// Stamped here, before the awaits below consume messageAudioBlob
// and blockBuildTargetLabelRef.
lastTurnRef.current = {
@@ -2222,6 +2529,18 @@ export function WorkflowCopilotChat({
const abortController = new AbortController();
streamingAbortController.current?.abort();
streamingAbortController.current = abortController;
+ // A chat switch or New chat during the stream bumps this, which is how a
+ // turn whose chat the user left is kept from arming a recovery re-read.
+ let sendGeneration = recoveryGeneration.current;
+ let streamTurnId: string | null = null;
+ let streamChatId: string | null = null;
+ let sawTerminalFrame = false;
+ const shouldArmRecovery = () =>
+ streamTurnId !== null &&
+ !sawTerminalFrame &&
+ !abortController.signal.aborted &&
+ cancelInFlightController.current !== abortController &&
+ recoveryGeneration.current === sendGeneration;
setStopArmed(false);
if (stopArmTimer.current !== null) {
@@ -2637,6 +2956,11 @@ export function WorkflowCopilotChat({
map.delete(oldest);
}
latestTurnId.current = payload.turn_id;
+ streamTurnId = payload.turn_id;
+ // The chat this turn belongs to, read while the server is
+ // announcing it. Reading the ref at arming time instead would
+ // bind the poll to whatever chat the user switched to since.
+ streamChatId = workflowCopilotChatIdRef.current;
applyStoredNarrativeEvent(payload, EMPTY_NARRATIVE);
return false;
}
@@ -2671,11 +2995,13 @@ export function WorkflowCopilotChat({
}
case "response": {
const frozenNarrative = applyStoredNarrativeEvent(payload);
+ sawTerminalFrame = true;
handleResponse(payload, frozenNarrative);
return true;
}
case "error": {
const frozenNarrative = applyStoredNarrativeEvent(payload);
+ sawTerminalFrame = true;
handleError(payload, frozenNarrative);
return true;
}
@@ -2693,16 +3019,28 @@ export function WorkflowCopilotChat({
if (options.idempotencyKey !== undefined && workflowCopilotChatId) {
toast({
title: "Checking account selection",
- description:
- "The connection dropped, so Copilot is refreshing this chat before allowing a retry.",
+ description: RECOVERY_IN_PROGRESS_MESSAGE,
variant: "destructive",
});
+ const generationBeforeRefresh = recoveryGeneration.current;
await loadChatInPlace(workflowCopilotChatId);
+ // loadChatInPlace stops recovery polls; forgive its own bump so this
+ // severed stream still arms, but not a chat the user actually left.
+ // It bumps exactly once, so a larger jump means a switch landed
+ // during the await and this turn must not arm.
+ if (
+ generationBeforeRefresh === sendGeneration &&
+ recoveryGeneration.current === generationBeforeRefresh + 1
+ ) {
+ sendGeneration = recoveryGeneration.current;
+ }
} else {
const errorMessage: ChatMessage = {
id: Date.now().toString(),
sender: "ai",
- content: "Sorry, I encountered an error. Please try again.",
+ content: shouldArmRecovery()
+ ? RECOVERY_IN_PROGRESS_MESSAGE
+ : SEND_FAILED_MESSAGE,
};
setMessages((prev) => [...prev, errorMessage]);
}
@@ -2711,6 +3049,10 @@ export function WorkflowCopilotChat({
setNarrative(EMPTY_NARRATIVE);
setLivePauseFrame(null);
} finally {
+ // Read before the clears below null cancelInFlightController. A soft Stop
+ // sets it synchronously and only aborts 15s later, so the abort signal
+ // alone would let a user cancel arm the recovery poll.
+ const armRecovery = shouldArmRecovery();
if (streamingAbortController.current === abortController) {
streamingAbortController.current = null;
inFlightRef.current = false;
@@ -2739,6 +3081,12 @@ export function WorkflowCopilotChat({
stopAllRecordedActionsPolls();
releaseTurnRun();
buildFollowEngaged.current = false;
+ if (armRecovery && streamTurnId !== null) {
+ startRecoveryPoll(
+ streamChatId ?? workflowCopilotChatIdRef.current,
+ streamTurnId,
+ );
+ }
}
},
[
@@ -2769,6 +3117,7 @@ export function WorkflowCopilotChat({
requiresLiveBrowser,
resyncProposalFromChatRow,
rollbackPendingTerminalContinuation,
+ startRecoveryPoll,
stopSpeech,
takeSpeechAudioBlob,
updateQueuedPrompt,
diff --git a/skyvern-frontend/src/routes/workflows/copilot/recoveryPoll.chatHistory.fixture.json b/skyvern-frontend/src/routes/workflows/copilot/recoveryPoll.chatHistory.fixture.json
new file mode 100644
index 000000000..cec884fbd
--- /dev/null
+++ b/skyvern-frontend/src/routes/workflows/copilot/recoveryPoll.chatHistory.fixture.json
@@ -0,0 +1,260 @@
+{
+ "workflow_copilot_chat_id": "wcc_569717148492103912",
+ "chat_history": [
+ {
+ "sender": "user",
+ "content": "Open the analytics console at http://localhost:8918/analytics_console/houndline/ and log in with the saved mock-portal-login credential, then tell me what you see on the dashboard.",
+ "audio_artifact_id": null,
+ "turn_outcome": null,
+ "narrative_payload": null,
+ "created_at": "2026-09-03T01:42:06.188855"
+ },
+ {
+ "sender": "ai",
+ "content": "Successfully signed in and opened the Houndline **APM** dashboard. The workflow was updated and its latest test completed successfully.\n\nWhat the dashboard shows:\n\n- **Welcome to APM, Demo** — a real-time view of services, dependencies, and performance.\n- **2 low-priority recommendations** for `acme-api`:\n - N+1 database queries on `POST /v1/run/orders`\n - N+1 database queries on `acme.db.bulk_create_artifacts`\n- A prompt to **review 2 recommendations** to improve services.\n- **Service overview**:\n - Service: `acme-api`\n - Last deploy: `2h ago`\n - Requests: `8.5 req/s`\n - Error rate: `< 0.1%`\n - P95 latency: `546ms`\n- Overall status: **All Systems Operational**.",
+ "audio_artifact_id": null,
+ "turn_outcome": {
+ "response_kind": "build",
+ "reason_code": "",
+ "actuation_obligation_key": "",
+ "normalized_reply_signature": "58654c39b8a9f7ad",
+ "tool_calls": [
+ "get_block_schema",
+ "inspect_page_for_composition",
+ "update_and_run_blocks",
+ "update_and_run_blocks"
+ ],
+ "terminal_reason": null,
+ "blocked_signatures": [],
+ "copilot_effective_mode": "code",
+ "copilot_code_available": true,
+ "copilot_last_code_build_failed": false,
+ "copilot_pending_capability": null,
+ "copilot_turn_id": "e0598835b41941e8b493f4bd73a72282",
+ "idempotency_digest": null,
+ "unresolved_runtime_failure": null,
+ "connected_account_choices": null
+ },
+ "narrative_payload": {
+ "turnId": "e0598835b41941e8b493f4bd73a72282",
+ "turnIndex": 19,
+ "responseType": "REPLY",
+ "cancelled": false,
+ "proposalDisposition": "review_untested",
+ "responseKind": "build",
+ "terminalEnvelope": {
+ "next_state": "proposal_pending",
+ "verified": false,
+ "workflow_applied": false,
+ "run_verdict": "not_evaluated",
+ "run_id": "wr_570013487120619226",
+ "run_completed": true,
+ "blocks_run_this_turn": 1,
+ "run_display_reason": null,
+ "run_output_report": "Recorded output from the latest completed run: {\"open_portal_output\":{\"current_url\":\"http://localhost:8918,\"dashboard_text\":\"🐕\\nHOUNDLINE\\nScout AI\\nDashboards\\nMonitoring\\nDeveloper Portal\\nIncident Response\\nAutomation\\nInfrastructure\\nCloud Cost\\nAPM\\nDigital Experience\\nSoftware Delivery\\nSecurity\\nData Observability\\nAI Observability\\nErrors\\nMetrics\\nLogs\\nIntegrations\\n*****\\nAcme Labs\\n✨ Ask Scout\\nWelcome to APM, Demo\\n\\nGet a real-time view of your system's services, dependencies, and performance.\\n\\nWhat needs your attention\\n💡 Recommendations\\n🔍 Anomalies\\n⚠ Error Tracking\\nLOW\\nRECOMMENDATIONS\\n\\nN+1 Queries on Database on POST /v1/run/orders.\\n\\nacme-api\\nLOW\\nRECOMMENDATIONS\\n\\nN+1 Queries on Database on acme.db.bulk_create_artifacts.\\n\\nacme-api\\nREVIEW\\n\\nReview 2 recommendations to improve services\\n\\nView Recommendations →\\nYour system at a glance\\n▦ Services\\n{ } Endpoints\\nService List\\nView in Software Catalog →\\n1h  Past 1 Hour\\nenv:* ▾\\nSERVICE\\tLAST DEPLOY\\tREQUESTS\\tERROR RATE\\tP95 LATENCY\\n★ acme-api\\t2h ago\\t8.5 req/s\\t< 0.1%\\t546ms\\nCopyright Houndline, Inc. 2026 - Master Subscription Agreement - Privacy Policy - Cookie Policy - ● All Systems Operati...",
+ "blocker_reason": null,
+ "halt_kind": null,
+ "user_action_required": false,
+ "attempted": "Successfully signed in and opened the Houndline **APM** dashboard. The workflow was updated and its latest test completed successfully.\n\nWhat the dashboard shows:\n\n- **Welcome to APM, Demo** — a real-time view of services, dependencies, and performance.\n- **2 low-priority recommendations** for `acme-api`:\n - N+1 database queries on `POST /v1/run/orders`\n - N+1 database queries on `acme.db.bulk_create_artifacts`\n- A prompt to **review 2 recommendations** to improve services.\n- **Service overview**:\n - Service: `acme-api`\n - Last deploy: `2h ago`\n - Requests: `8.5 req/s`\n - Error rate: `< 0.1%`\n - P95 latency: `546ms`\n- Overall status: **All Systems Operational**.",
+ "response_kind": "update",
+ "terminal_cause": null,
+ "failed_operation": null,
+ "connect_failure": null,
+ "proposal_present": true,
+ "interruption": null,
+ "rendered_from_envelope": false,
+ "envelope_version": 1
+ },
+ "designStarted": true,
+ "designEnded": true,
+ "draft": {
+ "blockCount": 1,
+ "blockLabels": ["open_portal"],
+ "summary": null
+ },
+ "blocks": [
+ {
+ "label": "open_portal",
+ "workflowRunBlockId": "wrb_570013487120619236",
+ "blockType": "code",
+ "state": "completed",
+ "lastSeenIteration": 3,
+ "activity": [],
+ "startedAt": null,
+ "endedAt": "2026-09-03T01:43:32.819437+00:00",
+ "outcome": "not_evaluated",
+ "outcomeRole": "recorded"
+ }
+ ],
+ "terminal": "response",
+ "terminalMessage": "Successfully signed in and opened the Houndline **APM** dashboard. The workflow was updated and its latest test completed successfully.\n\nWhat the dashboard shows:\n\n- **Welcome to APM, Demo** — a real-time view of services, dependencies, and performance.\n- **2 low-priority recommendations** for `acme-api`:\n - N+1 database queries on `POST /v1/run/orders`\n - N+1 database queries on `acme.db.bulk_create_artifacts`\n- A prompt to **review 2 recommendations** to improve services.\n- **Service overview**:\n - Service: `acme-api`\n - Last deploy: `2h ago`\n - Requests: `8.5 req/s`\n - Error rate: `< 0.1%`\n - P95 latency: `546ms`\n- Overall status: **All Systems Operational**.",
+ "narrativeSummary": "Successfully signed in and opened the Houndline **APM** dashboard. The workflow was updated and its latest test completed successfully.\n\nWhat the dashboard shows:\n\n- **Welcome to APM, Demo** — a real-time view of services, dependencies, and performance.\n- **2 low-priority recommendations** for `acme-api`:\n - N+1 database queries on `POST /v1/run/orders`\n - N+1 database queries on `acme.db.bulk_create_artifacts`\n- A prompt to **review 2 recommendations** to improve services.\n- **Service overview**:\n - Service: `acme-api`\n - Last deploy: `2h ago`\n - Requests: `8.5 req/s`\n - Error rate: `< 0.1%`\n - P95 latency: `546ms`\n- Overall status: **All Systems Operational**.",
+ "priorBlockCount": 1,
+ "designActivity": [
+ {
+ "kind": "tool_call",
+ "text": "Checking workflow block options…",
+ "iteration": 0,
+ "toolName": "get_block_schema",
+ "displayLabel": "Checking workflow block options",
+ "id": "tc-call_9vQKRhvUQG3xVfxp0m06fscv",
+ "timestamp": "2026-09-03T01:42:12.271211+00:00"
+ },
+ {
+ "kind": "tool_result",
+ "text": "Schema for code",
+ "iteration": 0,
+ "toolName": "get_block_schema",
+ "displayLabel": "Checking workflow block options",
+ "success": true,
+ "id": "tr-call_9vQKRhvUQG3xVfxp0m06fscv",
+ "timestamp": "2026-09-03T01:42:12.300512+00:00"
+ },
+ {
+ "kind": "tool_call",
+ "text": "Inspecting the page…",
+ "iteration": 1,
+ "toolName": "inspect_page_for_composition",
+ "displayLabel": "Inspecting the page",
+ "id": "tc-call_CrsGML84zGIK94lMw8iEtomG",
+ "timestamp": "2026-09-03T01:42:16.087406+00:00"
+ },
+ {
+ "kind": "tool_result",
+ "text": "Inspected the page (2 form field(s))",
+ "iteration": 1,
+ "toolName": "inspect_page_for_composition",
+ "displayLabel": "Inspecting the page",
+ "success": true,
+ "id": "tr-call_CrsGML84zGIK94lMw8iEtomG",
+ "timestamp": "2026-09-03T01:42:26.507371+00:00"
+ },
+ {
+ "kind": "tool_call",
+ "text": "Testing workflow…",
+ "iteration": 2,
+ "toolName": "update_and_run_blocks",
+ "displayLabel": "Testing workflow",
+ "id": "tc-call_TYmr7z1dGpYjh6o2bWru5oyS",
+ "timestamp": "2026-09-03T01:42:56.764978+00:00"
+ },
+ {
+ "kind": "tool_result",
+ "text": "I need to adjust the workflow's code so it can run safely before testing.",
+ "iteration": 2,
+ "toolName": "update_and_run_blocks",
+ "displayLabel": "Testing workflow",
+ "success": false,
+ "id": "tr-call_TYmr7z1dGpYjh6o2bWru5oyS",
+ "timestamp": "2026-09-03T01:42:56.869866+00:00"
+ },
+ {
+ "kind": "narration",
+ "text": "Preparing to review the Houndline dashboard after signing in with the saved credential.",
+ "iteration": 1,
+ "activeLabel": "Accessing the Houndline analytics console",
+ "outcomeLabel": "Opened the Houndline analytics console",
+ "id": "n-1-2026-09-03T01:43:01.703371+00:00",
+ "timestamp": "2026-09-03T01:43:01.703371+00:00"
+ },
+ {
+ "kind": "tool_call",
+ "text": "Testing workflow…",
+ "iteration": 3,
+ "toolName": "update_and_run_blocks",
+ "displayLabel": "Testing workflow",
+ "id": "tc-call_0NaUaFbGX0ADjTS2HIKx1QcB",
+ "timestamp": "2026-09-03T01:43:27.522418+00:00"
+ },
+ {
+ "kind": "narration",
+ "text": "Ensuring the analytics console can sign in and display its dashboard.",
+ "iteration": 2,
+ "activeLabel": "Correcting dashboard login workflow",
+ "outcomeLabel": "Workflow test failed before dashboard access",
+ "id": "n-2-2026-09-03T01:43:31.472670+00:00",
+ "timestamp": "2026-09-03T01:43:31.472670+00:00"
+ },
+ {
+ "kind": "tool_result",
+ "text": "Updated the workflow and ran it: completed",
+ "iteration": 3,
+ "toolName": "update_and_run_blocks",
+ "displayLabel": "Testing workflow",
+ "success": true,
+ "codeDiffs": [
+ {
+ "label": "open_portal",
+ "added": 15,
+ "removed": 0,
+ "patch": "@@ -0,0 +1,15 @@\n+await page.goto(\"http://localhost:8918/analytics_console/houndline/\", wait_until=\"domcontentloaded\")\n+login_field = page.locator(\"#username\")\n+if await login_field.is_visible():\n+ await login_field.fill(str(houndline_login.username))\n+ await page.locator(\"#password\").fill(str(houndline_login.password))\n+ await page.locator(\"button[aria-label=\\\"Log in\\\"]\").click()\n+dashboard_anchor = page.get_by_text(\"Welcome to APM\", exact=False)\n+await dashboard_anchor.wait_for(state=\"visible\", timeout=30000)\n+dashboard_text = await page.locator(\"body\").inner_text()\n+service_rows = await page.locator(\"text=acme-api\").all_text_contents()\n+return {\n+ \"current_url\": page.url,\n+ \"dashboard_text\": dashboard_text,\n+ \"service_rows\": service_rows\n+}"
+ }
+ ],
+ "id": "tr-call_0NaUaFbGX0ADjTS2HIKx1QcB",
+ "timestamp": "2026-09-03T01:43:45.969052+00:00"
+ },
+ {
+ "kind": "narration",
+ "text": "Confirming the saved login reaches the Houndline dashboard and exposes its current analytics.",
+ "iteration": 3,
+ "activeLabel": "Checking the Houndline analytics dashboard",
+ "outcomeLabel": "Completed a Houndline dashboard workflow test",
+ "id": "n-3-2026-09-03T01:43:51.187352+00:00",
+ "timestamp": "2026-09-03T01:43:51.187352+00:00"
+ }
+ ],
+ "startedAt": "2026-09-03T01:42:07.764818+00:00",
+ "endedAt": "2026-09-03T01:43:57.097993+00:00",
+ "review": {
+ "blocks": [
+ {
+ "label": "open_portal",
+ "blockType": "code",
+ "change": "changed",
+ "neverTested": false,
+ "coverage": "current_source"
+ }
+ ],
+ "duplicateWrites": []
+ },
+ "testedBlockFingerprints": {
+ "log_in": [
+ "71d34dd767440a21ffda45d6a2bca252d3390cf811755f082a2592b7cc49abb4"
+ ],
+ "open_portal": [
+ "11b371486db0b6c43e01c6a10d1e191ec7e38cd39e2cb924c84ef9752a374791",
+ "1a0d3278fe857dcc88c62497f3a24255f4c0bce23e52af9328cc68521078d19c",
+ "1d956c8c34da13844d175b9392163e2206b99eb0fc8ef86e2478134a4271f836",
+ "249f4650110b5e985ecdb236702a13b598f59bdec3b58e7dff13b2ae49e8bb69",
+ "5025521c94e0c56dea2dc39112bdbaf5e965d996882a07a6b2bc945c4c607d64",
+ "5c5d7cf8df64b8e6b600d0a6011d21ad76f6fa728398c0d46cef7aca338a3b62",
+ "610551c5f1b4c490b514f00703cef40ef666c490d9538aaafaf75e808a00b1f7",
+ "7dfa7cc6754df430e98f379cf5dfa581be060f79a11bdf11c7e63181f346c05b",
+ "828ab3bea0ea4507056afb9dfbe8b96046cf9f80cad1b097394ef971db56d9e9",
+ "984c8837f4fda6f31f537d9523c5572f408a093d4420e3d79df833fa4548d8de",
+ "a96c6ecc398001f0eb2dfa477f5d7b1f887077b2d00e73fb4d103bc4aa1efc81",
+ "ba2fa95e7275f243d64bf5d86f57b521ab7d2d2f66d42b012bbe5577f26e0160",
+ "bc3775dcff59c284e7f2aa87e47e9cafa10698ade7b05376d7f790206d02d2b5",
+ "c759099de1360e89c0e3c42d93fdbc0ea051e271418594666b0d4f61bb086db9",
+ "d453f2b65a58174119c0d34957b31c39261d74b70e015e838f8c765f0a78dd14",
+ "d9d832b2c78115811e538ccfa5b33309c5439184d826a92a9e93c56679e3a00c",
+ "ebd4cdaec6c2064e806c80766dbf6ac41186675293286b789569dc761c8e998c"
+ ]
+ },
+ "turnFacts": {
+ "factsAvailable": true,
+ "evaluationState": "not_evaluated",
+ "runId": "wr_570013487120619226",
+ "runCompleted": true,
+ "terminalCause": null,
+ "blocksRunThisTurn": 1,
+ "authoredBlockCount": 1,
+ "matchingSourceBlockCount": 1,
+ "ranCleanOnCurrentSource": true
+ }
+ },
+ "created_at": "2026-09-03T01:43:57.145980"
+ }
+ ],
+ "auto_accept": false
+}
diff --git a/skyvern-frontend/src/routes/workflows/copilot/workflowCopilotTypes.ts b/skyvern-frontend/src/routes/workflows/copilot/workflowCopilotTypes.ts
index 95522d526..5ca22fe17 100644
--- a/skyvern-frontend/src/routes/workflows/copilot/workflowCopilotTypes.ts
+++ b/skyvern-frontend/src/routes/workflows/copilot/workflowCopilotTypes.ts
@@ -78,6 +78,10 @@ export interface WorkflowCopilotChatHistoryMessage {
turn_outcome?: {
response_kind?: string | null;
connected_account_choices?: ConnectedAccountChoice[] | null;
+ // Server-minted id of the turn that wrote this row; the same id the
+ // turn_start frame carries, so a client can correlate a row to its own send.
+ copilot_turn_id?: string | null;
+ terminal_reason?: string | null;
} | null;
narrative_payload?: Record<string, unknown> | null;
}
diff --git a/skyvern/forge/sdk/workflow/models/block.py b/skyvern/forge/sdk/workflow/models/block.py
index 713f8c528..78afd74f1 100644
--- a/skyvern/forge/sdk/workflow/models/block.py
+++ b/skyvern/forge/sdk/workflow/models/block.py
@@ -728,6 +728,19 @@ def build_block_failure_output(failure_reason: str, error_codes: Sequence[str])
}
+def user_defined_failure_category(error: UserDefinedError) -> list[dict[str, Any]]:
+ """A declared error code is the workflow author's own verdict on why the run stopped.
+ ``_resolve_block_terminal_outcome`` prefers a block output's ``failure_category`` over
+ keyword classification, so carrying it here keeps the run out of UNKNOWN."""
+ return [
+ {
+ "category": error.error_code,
+ "confidence_float": error.confidence_float,
+ "reasoning": error.reasoning,
+ }
+ ]
+
+
def build_user_defined_error_output(error_code: str, reasoning: str) -> dict[str, Any]:
"""<label>_output payload for a declared ErrorCode raise (SKY-13668): a UserDefinedError
entry with confidence 1.0, matching UserDefinedError's own serialized shape."""
@@ -736,6 +749,7 @@ def build_user_defined_error_output(error_code: str, reasoning: str) -> dict[str
"status": BlockStatus.failed.value,
"failure_reason": reasoning,
"errors": [error.model_dump(mode="json")],
+ "failure_category": user_defined_failure_category(error),
}
diff --git a/skyvern/forge/sdk/workflow/models/code_block_recording.py b/skyvern/forge/sdk/workflow/models/code_block_recording.py
index 9cabcf1e2..80a16d954 100644
--- a/skyvern/forge/sdk/workflow/models/code_block_recording.py
+++ b/skyvern/forge/sdk/workflow/models/code_block_recording.py
@@ -72,6 +72,20 @@ def _null_redacted_scalars(original: Any, masked: Any) -> Any:
return masked
+def _withhold_values(payload: dict[str, Any]) -> dict[str, Any]:
+ # Fail-closed redaction cannot say which leaves are parameter values, so every leaf is withheld:
+ # strings keep the typed field satisfied, anything else nulls so a default cannot restore it.
+ # Only field names survive as keys; nested keys can be page-derived text, so nested dicts collapse.
+ def withhold(value: Any) -> Any:
+ if isinstance(value, dict):
+ return {}
+ if isinstance(value, list):
+ return [withhold(item) for item in value]
+ return "" if isinstance(value, str) else None
+
+ return {field: withhold(value) for field, value in payload.items()}
+
+
def _page_closed(page: Page) -> bool | None:
# Separates "page was already gone" from "page was alive but hung" — a screenshot TimeoutError
# alone cannot tell them apart. Must not raise: the caller is an except handler whose remaining
@@ -284,7 +298,7 @@ class CodeBlockActionRecording:
masked = app.AGENT_FUNCTION.redact_codeblock_parameter_values(masked, self._redaction_parameters)
# A matching bool/number becomes a string placeholder, which typed Action fields reject.
# Null it recursively so subclass defaults cannot silently restore user-controlled values.
- masked = _null_redacted_scalars(payload, masked) if isinstance(masked, dict) else {}
+ masked = _null_redacted_scalars(payload, masked) if isinstance(masked, dict) else _withhold_values(payload)
response = masked.get("response")
if isinstance(response, str):
masked["response"] = response[:RECORDED_FAILURE_RESPONSE_MAX_CHARS]
diff --git a/tests/unit/test_code_block_downstream_sinks.py b/tests/unit/test_code_block_downstream_sinks.py
index 10c1e337a..d3565e72c 100644
--- a/tests/unit/test_code_block_downstream_sinks.py
+++ b/tests/unit/test_code_block_downstream_sinks.py
@@ -22,6 +22,7 @@ from skyvern.forge.sdk.workflow.models.block import (
from skyvern.forge.sdk.workflow.models.parameter import OutputParameter, ParameterType
from skyvern.forge.sdk.workflow.models.workflow import WorkflowRun, WorkflowRunStatus
from skyvern.forge.sdk.workflow.service import WorkflowService
+from skyvern.schemas.workflows import BlockResult, BlockStatus
from skyvern.services import webhook_service
LONG_CREDENTIAL = "templated-password-very-long-13668"
@@ -256,3 +257,32 @@ async def test_inline_code_containment_gate_disabled_would_leak_to_every_sink(
for payload in (await _sink_payloads(monkeypatch, captured)).values():
# Presence must come from an attacker-visible string, not an accidental numeric metadata match.
assert any(CODE_CREDENTIAL in text for text in _string_values(payload))
+
+
+async def test_declared_error_code_becomes_the_run_failure_category() -> None:
+ """SKY-15564: a declared ErrorCode raise is the author's own verdict on why the run stopped,
+ so the run must inherit it instead of falling through to the keyword classifier's UNKNOWN."""
+ declared_output = await _inline_failure_output(error_code=SAFE_CODE, reasoning="Invoice not published yet")
+ block = CodeBlock(label="code_1", code="pass", output_parameter=_output_parameter())
+
+ def outcome(output: dict[str, Any]) -> tuple[Any, Any, Any]:
+ return WorkflowService._resolve_block_terminal_outcome(
+ block=block,
+ block_result=BlockResult(
+ success=False,
+ status=BlockStatus.failed,
+ failure_reason="Invoice not published yet",
+ output_parameter=_output_parameter(),
+ output_parameter_value=output,
+ ),
+ )
+
+ _, _, declared_category = outcome(declared_output)
+ assert declared_category == [
+ {"category": SAFE_CODE, "confidence_float": 1.0, "reasoning": "Invoice not published yet"}
+ ]
+
+ # An undeclared failure carries no verdict, so the classifier must still be the one to decide.
+ _, _, undeclared_category = outcome(build_block_failure_output(GENERIC_REASONING, ["user_code_error"]))
+ assert undeclared_category is None
diff --git a/tests/unit/test_workflow_copilot_route.py b/tests/unit/test_workflow_copilot_route.py
index d5e5ac7c0..3e0af87c9 100644
--- a/tests/unit/test_workflow_copilot_route.py
+++ b/tests/unit/test_workflow_copilot_route.py
@@ -17,7 +17,9 @@ from __future__ import annotations
import contextlib
import json
+import re
from datetime import UTC, datetime, timedelta, timezone
+from pathlib import Path
from types import SimpleNamespace
from typing import Any
from unittest.mock import AsyncMock, MagicMock
@@ -4597,3 +4599,18 @@ async def test_a_request_without_an_eval_entrypoint_url_reaches_the_agent_path_u
await workflow_copilot_chat_post(anon_request, _make_chat_request(), organization)
assert new_copilot_mock.await_args.kwargs["eval_entrypoint_url"] is None
+
+
+def test_the_client_recovery_budget_still_outlasts_the_server_abandon_threshold() -> None:
+ """The client's poll budget is a literal in WorkflowCopilotChat.tsx, while the threshold it has to
+ outlast is derived from two env-configurable settings. Raising either without raising the literal
+ would silently strand every recovered turn, so the drift fails here instead."""
+ source = Path("skyvern-frontend/src/routes/workflows/copilot/WorkflowCopilotChat.tsx").read_text()
+ match = re.search(r"const RECOVERY_POLL_BUDGET_MS = ([\d_]+);", source)
+ assert match, "RECOVERY_POLL_BUDGET_MS not found; update this guard if the constant was renamed"
+
+ budget_seconds = int(match.group(1).replace("_", "")) / 1000
+ assert budget_seconds > RECONCILE_ABANDON_AFTER_SECONDS, (
+ f"client recovery budget {budget_seconds}s no longer outlasts the server's "
+ f"{RECONCILE_ABANDON_AFTER_SECONDS}s abandon threshold: a recovered turn would never be read"
+ )
diff --git a/tests/unit/workflow/test_code_block_escalation.py b/tests/unit/workflow/test_code_block_escalation.py
index 924f64791..74126225d 100644
--- a/tests/unit/workflow/test_code_block_escalation.py
+++ b/tests/unit/workflow/test_code_block_escalation.py
@@ -1100,6 +1100,14 @@ async def test_inline_declared_error_without_download_keeps_typed_output(monkeyp
],
"failure_reason": "report generation failed",
"status": "failed",
+ # SKY-15564: the run inherits the declared code instead of the classifier's UNKNOWN.
+ "failure_category": [
+ {
+ "category": "report_unavailable",
+ "confidence_float": 1.0,
+ "reasoning": "report generation failed",
+ }
+ ],
}
assert result.output_parameter_value == expected_output
assert "downloaded_files" not in result.output_parameter_value