Skip to content

Automate browser based workflows with AI

Task V3: a code endpoint that answers without a code reads as "not yet", not an error (SKY-18390) (#8997)

Andrew Neilson5d647ec07615
diff --git a/skyvern-frontend/src/components/ui/confirm-dialog.test.tsx b/skyvern-frontend/src/components/ui/confirm-dialog.test.tsx
index ab6491ebf..8c6790688 100644
--- a/skyvern-frontend/src/components/ui/confirm-dialog.test.tsx
+++ b/skyvern-frontend/src/components/ui/confirm-dialog.test.tsx
@@ -15,24 +15,6 @@ function cancelButton() {
}
describe("ConfirmDialog", () => {
- it("renders the title, description, and standardized reversibility line", () => {
- render(
- <ConfirmDialog
- open
- onOpenChange={() => {}}
- title="Delete this credential?"
- description="The credential Prod API Key will be deleted."
- onConfirm={() => {}}
- />,
- );
-
- expect(screen.getByText("Delete this credential?")).toBeTruthy();
- expect(
- screen.getByText("The credential Prod API Key will be deleted."),
- ).toBeTruthy();
- expect(screen.getByText("This can't be undone.")).toBeTruthy();
- });
-
it("omits the reversibility line when reversible", () => {
render(
<ConfirmDialog
diff --git a/skyvern-frontend/src/routes/browserSessions/hooks/useProcessRecordingMutation.test.tsx b/skyvern-frontend/src/routes/browserSessions/hooks/useProcessRecordingMutation.test.tsx
index fd4ed14e6..e8d1775f8 100644
--- a/skyvern-frontend/src/routes/browserSessions/hooks/useProcessRecordingMutation.test.tsx
+++ b/skyvern-frontend/src/routes/browserSessions/hooks/useProcessRecordingMutation.test.tsx
@@ -335,8 +335,6 @@ describe("useProcessRecordingMutation telemetry", () => {
it.each([
["wpid-1", "success"],
- ["wpid-1", "error"],
- ["wpid-2", "success"],
["wpid-2", "error"],
])(
"resets the Done lifecycle after owner disposal to %s and a deferred %s",
@@ -401,11 +399,8 @@ describe("useProcessRecordingMutation telemetry", () => {
it.each([
["commitToken", "success"],
- ["commitToken", "error"],
- ["workflowPermanentId", "success"],
["workflowPermanentId", "error"],
["recordingAttemptId", "success"],
- ["recordingAttemptId", "error"],
] as const)(
"preserves a newer recording with a different %s after disposed %s",
async (identityField, outcome) => {
@@ -535,7 +530,7 @@ describe("useProcessRecordingMutation telemetry", () => {
},
);
- it.each(["success", "empty success", "error", "empty error"])(
+ it.each(["success", "empty error"])(
"ignores deferred recording %s after navigation to another editor",
async (outcome) => {
vi.useRealTimers();
diff --git a/skyvern-frontend/src/routes/credentials/CredentialsModal.test.tsx b/skyvern-frontend/src/routes/credentials/CredentialsModal.test.tsx
index 36a80e54a..8c9ac7df9 100644
--- a/skyvern-frontend/src/routes/credentials/CredentialsModal.test.tsx
+++ b/skyvern-frontend/src/routes/credentials/CredentialsModal.test.tsx
@@ -677,105 +677,91 @@ describe("CredentialsModal authenticator save errors", () => {
});
describe("CredentialsModal edit-mode inline test", () => {
- it.each(["success", "404"] as const)(
- "uses Member cleanup without interrupting save when cleanup returns %s",
- async (cleanupResult) => {
- // 1st POST: startTest's /credentials/test-login. 2nd POST: the real
- // credential's /credentials/{id}/update once Save is clicked.
- postMock
- .mockResolvedValueOnce({
- data: { credential_id: "temp-cred-id", workflow_run_id: "wr-1" },
- })
- .mockResolvedValueOnce({
- data: { credential_id: "real-cred-id", name: "Acme Login" },
- });
- getMock.mockResolvedValueOnce({
- data: {
- status: "completed",
- browser_profile_id: "new-profile-id",
- tested_url: "https://example.com/login",
- },
+ it("uses Member cleanup without interrupting save when cleanup returns 404", async () => {
+ // 1st POST: startTest's /credentials/test-login. 2nd POST: the real
+ // credential's /credentials/{id}/update once Save is clicked.
+ postMock
+ .mockResolvedValueOnce({
+ data: { credential_id: "temp-cred-id", workflow_run_id: "wr-1" },
+ })
+ .mockResolvedValueOnce({
+ data: { credential_id: "real-cred-id", name: "Acme Login" },
});
- patchMock.mockResolvedValue({ data: {} });
- if (cleanupResult === "404") {
- deleteMock.mockRejectedValueOnce(
- axiosErrorWithDetail("Credential not found", 404),
- );
- } else {
- deleteMock.mockResolvedValue({ data: {} });
- }
- const warning = vi.spyOn(console, "warn").mockImplementation(() => {});
-
- renderEditPasswordCredentialsModal(
- editingPasswordCredential,
- undefined,
- undefined,
- undefined,
- memberPermissions,
- );
+ getMock.mockResolvedValueOnce({
+ data: {
+ status: "completed",
+ browser_profile_id: "new-profile-id",
+ tested_url: "https://example.com/login",
+ },
+ });
+ patchMock.mockResolvedValue({ data: {} });
+ deleteMock.mockRejectedValueOnce(
+ axiosErrorWithDetail("Credential not found", 404),
+ );
+ const warning = vi.spyOn(console, "warn").mockImplementation(() => {});
- fireEvent.click(screen.getAllByLabelText("Edit credential values")[0]!);
- const passwordInput = document.querySelector('input[type="password"]');
- expect(passwordInput).toBeTruthy();
- fireEvent.change(passwordInput as HTMLInputElement, {
- target: { value: "rotated-password" },
- });
+ renderEditPasswordCredentialsModal(
+ editingPasswordCredential,
+ undefined,
+ undefined,
+ undefined,
+ memberPermissions,
+ );
- fireEvent.click(screen.getByRole("button", { name: "Test" }));
+ fireEvent.click(screen.getAllByLabelText("Edit credential values")[0]!);
+ const passwordInput = document.querySelector('input[type="password"]');
+ expect(passwordInput).toBeTruthy();
+ fireEvent.change(passwordInput as HTMLInputElement, {
+ target: { value: "rotated-password" },
+ });
- // Real 3s poll delay inside the component — wait for the button label
- // to flip once testStatus reaches "completed".
- await waitFor(
- () => {
- expect(screen.getByRole("button", { name: "Retest" })).toBeTruthy();
- },
- { timeout: 8000 },
- );
+ fireEvent.click(screen.getByRole("button", { name: "Test" }));
- // Uncheck "Save browser session" after the test completed — the checkbox
- // has no side effect on testStatus/testCredentialId, so this must not be
- // able to skip cleanup of the now-orphaned temp credential.
- fireEvent.click(
- screen.getByLabelText("Save browser session for future logins"),
- );
+ // Real 3s poll delay inside the component — wait for the button label
+ // to flip once testStatus reaches "completed".
+ await waitFor(
+ () => {
+ expect(screen.getByRole("button", { name: "Retest" })).toBeTruthy();
+ },
+ { timeout: 8000 },
+ );
- fireEvent.click(screen.getByRole("button", { name: "Update" }));
+ // Uncheck "Save browser session" after the test completed — the checkbox
+ // has no side effect on testStatus/testCredentialId, so this must not be
+ // able to skip cleanup of the now-orphaned temp credential.
+ fireEvent.click(
+ screen.getByLabelText("Save browser session for future logins"),
+ );
- await waitFor(() => {
- expect(deleteMock).toHaveBeenCalledWith(
- "/credentials/temp-cred-id/temporary",
- );
- });
- if (cleanupResult === "404") {
- expect(warning).toHaveBeenCalledWith(
- "Credential cleanup returned 404; it may already be gone or no longer be eligible for cleanup.",
- );
- } else {
- expect(warning).not.toHaveBeenCalledWith(
- "Credential cleanup returned 404; it may already be gone or no longer be eligible for cleanup.",
- );
- }
- await waitFor(() => {
- expect(postMock).toHaveBeenCalledWith(
- "/credentials/real-cred-id/update",
- expect.objectContaining({
- credential: expect.objectContaining({
- password: "rotated-password",
- }),
+ fireEvent.click(screen.getByRole("button", { name: "Update" }));
+
+ await waitFor(() => {
+ expect(deleteMock).toHaveBeenCalledWith(
+ "/credentials/temp-cred-id/temporary",
+ );
+ });
+ expect(warning).toHaveBeenCalledWith(
+ "Credential cleanup returned 404; it may already be gone or no longer be eligible for cleanup.",
+ );
+ await waitFor(() => {
+ expect(postMock).toHaveBeenCalledWith(
+ "/credentials/real-cred-id/update",
+ expect.objectContaining({
+ credential: expect.objectContaining({
+ password: "rotated-password",
}),
- );
- });
+ }),
+ );
+ });
- // The bug this guards against: the old code renamed the throwaway temp
- // credential in place of updating the real one. renameCredentialMutation
- // is the only path that PATCHes a credential by the *temp* id — assert
- // it never fired.
- for (const call of patchMock.mock.calls) {
- expect(call[0]).not.toBe("/credentials/temp-cred-id");
- }
- },
- 15_000,
- );
+ // The bug this guards against: the old code renamed the throwaway temp
+ // credential in place of updating the real one. renameCredentialMutation
+ // is the only path that PATCHes a credential by the *temp* id — assert
+ // it never fired.
+ for (const call of patchMock.mock.calls) {
+ expect(call[0]).not.toBe("/credentials/temp-cred-id");
+ }
+ }, 15_000);
it("shows only the partial-save toast, not a success toast, when the metadata PATCH fails", async () => {
postMock.mockResolvedValueOnce({
diff --git a/skyvern-frontend/src/routes/tasks/create/PromptBox.test.tsx b/skyvern-frontend/src/routes/tasks/create/PromptBox.test.tsx
index d5080f9ba..7111cdc26 100644
--- a/skyvern-frontend/src/routes/tasks/create/PromptBox.test.tsx
+++ b/skyvern-frontend/src/routes/tasks/create/PromptBox.test.tsx
@@ -1000,8 +1000,6 @@ describe("PromptBox", () => {
// the server's billing guidance behind a generic toast.
test.each([
{ handoff: false, status: 402 },
- { handoff: true, status: 402 },
- { handoff: false, status: 422 },
{ handoff: true, status: 422 },
])(
"surfaces the server detail on a $status (handoff=$handoff)",
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 15224a0fd..098bc0ec7 100644
--- a/skyvern-frontend/src/routes/workflows/copilot/WorkflowCopilotChat.historyRace.test.tsx
+++ b/skyvern-frontend/src/routes/workflows/copilot/WorkflowCopilotChat.historyRace.test.tsx
@@ -2107,8 +2107,6 @@ describe("WorkflowCopilotChat — recovery poll after a non-terminal stream clos
it.each([
["unchanged", "credential"],
- ["advanced", "credential"],
- ["unchanged", "question"],
["advanced", "question"],
] as const)(
"Reject before turn_start retains recovery until the %s canonical outcome settles after a %s lookup",
@@ -2473,14 +2471,8 @@ describe("WorkflowCopilotChat — recovery poll after a non-terminal stream clos
}
it.each([
- ["mid-stream", null],
["after the drop", null],
- ["none", null],
["none", "verified_goal_satisfied"],
- ["mid-stream", "verified_goal_satisfied"],
- ["none", "timeout"],
- ["mid-stream", "timeout"],
- ["none", "turn_halt:browser_session_lost"],
["mid-stream", "turn_halt:browser_session_lost"],
] as const)(
"keeps a recovered turn's staged proposal and canvas (remount: %s, terminal_reason: %s)",
@@ -2495,7 +2487,7 @@ describe("WorkflowCopilotChat — recovery poll after a non-terminal stream clos
},
);
- it.each(["cancelled", "copilot_recoverable_failure", "user_cancelled"])(
+ it.each(["cancelled", "copilot_recoverable_failure"])(
"still rolls back a turn recovered after a remount whose terminal_reason is %s",
async (terminalReason) => {
const restore = await recoverStagedTurn("mid-stream", { terminalReason });
diff --git a/skyvern-frontend/src/routes/workflows/copilot/WorkflowCopilotChat.reviewGate.test.tsx b/skyvern-frontend/src/routes/workflows/copilot/WorkflowCopilotChat.reviewGate.test.tsx
index 2e636db2a..4d110e9d4 100644
--- a/skyvern-frontend/src/routes/workflows/copilot/WorkflowCopilotChat.reviewGate.test.tsx
+++ b/skyvern-frontend/src/routes/workflows/copilot/WorkflowCopilotChat.reviewGate.test.tsx
@@ -2161,19 +2161,12 @@ describe("WorkflowCopilotChat — g2 review gate", () => {
},
);
- it.each(
- [
- "question",
- "credential",
- "external question",
- "external credential",
- ].flatMap((path) =>
- ["Keep my edits", "Apply and discard my edits"].map((choice) => [
- path,
- choice,
- ]),
- ),
- )(
+ it.each([
+ ["question", "Keep my edits"],
+ ["credential", "Apply and discard my edits"],
+ ["external question", "Apply and discard my edits"],
+ ["external credential", "Keep my edits"],
+ ])(
"protects local inputs before claiming delayed %s history: %s",
async (path, choice) => {
changesState.hasChanges = false;
@@ -2932,8 +2925,6 @@ describe("WorkflowCopilotChat — g2 review gate", () => {
it.each([
{ action: "Retry", expired: true },
{ action: "Reload", expired: true },
- { action: "Reject", expired: true },
- { action: "Retry", expired: false },
{ action: "Reject", expired: false },
])(
"settles an unannounced turn through $action (deadline expired: $expired)",
@@ -3863,11 +3854,8 @@ describe("WorkflowCopilotChat — g2 review gate", () => {
it.each([
["error", true],
- ["error", false],
- ["response", true],
["response", false],
["cancel", true],
- ["cancel", false],
] as const)(
"checks canonical before a %s snapshot restore (auto-accept committed: %s)",
async (terminal, committed) => {
@@ -11200,45 +11188,340 @@ describe("WorkflowCopilotChat — g2 review gate", () => {
expect(useWorkflowYamlEditorStore.getState().lockKind).toBeNull();
});
- describe.each(["editor", "debugger"] as const)(
- "late canonical recovery on the %s route",
- (route) => {
- beforeEach(() => {
- saveData.workflow.title = saveData.title;
+ describe("late canonical recovery on the editor route", () => {
+ beforeEach(() => {
+ saveData.workflow.title = saveData.title;
+ });
+ async function discardRecoveryDraft() {
+ await act(async () => {
+ fireEvent.click(
+ screen.getByRole("button", { name: "Apply and discard my edits" }),
+ );
+ await vi.advanceTimersByTimeAsync(0);
});
- async function discardRecoveryDraft() {
- await act(async () => {
- fireEvent.click(
- screen.getByRole("button", { name: "Apply and discard my edits" }),
+ }
+ async function severStream(withTurnId = true) {
+ const apply = vi.fn();
+ const view = await renderChat({
+ route: "editor",
+ docked: true,
+ onWorkflowUpdate: apply,
+ });
+ const saveRegistration = renderHook(() => {
+ const nodes = editorNodes;
+ const revision = useWorkflowYamlEditorStore((state) => state.revision);
+ const parameters = useWorkflowParametersStore(
+ (state) => state.parameters,
+ );
+ useEffect(() => {
+ // FlowRenderer registers a new save callback after graph/store updates render.
+ const current = {
+ ...saveData,
+ blocks: getWorkflowBlocks(nodes, []),
+ };
+ useWorkflowHasChangesStore.getState().setGetSaveData(() => current);
+ }, [nodes, revision, parameters]);
+ });
+ const saved = { current: saveData.workflow };
+ historyGet.mockImplementation((path: string) =>
+ Promise.resolve(
+ path === "/workflows/wpid_1"
+ ? { data: saved.current }
+ : historyResponse,
+ ),
+ );
+ const submittedBlocks = useWorkflowHasChangesStore
+ .getState()
+ .getSaveData()!.blocks;
+ await submit("edit the workflow");
+ vi.useFakeTimers();
+ await act(async () => {
+ if (withTurnId) {
+ streamCalls[0]!.onMessage({
+ type: "turn_start",
+ turn_id: "turn-1",
+ mode: "build",
+ turn_index: 0,
+ });
+ streamCalls[0]!.onMessage({
+ type: "workflow_draft",
+ block_labels: [],
+ workflow: proposedWorkflowPayload(),
+ });
+ }
+ });
+ if (withTurnId) {
+ act(() => saveRegistration.rerender());
+ expect(
+ useWorkflowHasChangesStore.getState().getSaveData()!.blocks,
+ ).not.toEqual(submittedBlocks);
+ }
+ await act(async () =>
+ streamCalls[0]!.reject(new Error("connection dropped")),
+ );
+ expect(historyGet).toHaveBeenCalledWith(
+ "/workflows/wpid_1",
+ expect.objectContaining({ signal: expect.any(AbortSignal) }),
+ );
+ expect(
+ useWorkflowYamlEditorStore.getState().copilotAcceptance,
+ ).not.toBeNull();
+ expect(setEditorNodes).not.toHaveBeenCalled();
+ if (withTurnId) {
+ expect(editorNodes.find((node) => node.id === "loop")).toBeUndefined();
+ } else {
+ expect(
+ editorNodes.find((node) => node.id === "loop")?.data,
+ ).toMatchObject({
+ loopValue: "unsaved_items",
+ loopVariableReference: "{{ item }}",
+ });
+ }
+ apply.mockClear();
+ vi.mocked(toast).mockClear();
+ return { apply, saved, view };
+ }
+
+ it.each([false, true])(
+ "retains recovery through timeout and Retry until reconciliation or Reject (resumed=%s)",
+ async (resumed) => {
+ changesState.hasChanges = true;
+ const { saved, view } = await severStream();
+ if (resumed) {
+ view.unmount();
+ await renderChat({ route: "editor", docked: true, isOpen: false });
+ }
+ const expectControls = () => {
+ expect(screen.getByRole("button", { name: "Retry" })).toBeTruthy();
+ expect(screen.getByRole("button", { name: "Reject" })).toBeTruthy();
+ expect(
+ useWorkflowYamlEditorStore.getState().copilotAcceptance,
+ ).not.toBeNull();
+ };
+ await advance(1_500_000);
+ expectControls();
+ expect(screen.getByRole("alert").textContent).toContain(
+ "Could not confirm",
+ );
+ await act(async () =>
+ fireEvent.click(screen.getByRole("button", { name: "Retry" })),
+ );
+ expectControls();
+ const retainedNodes = structuredClone(editorNodes);
+ act(editLoop);
+ expect(editorNodes).toEqual(retainedNodes);
+ finishOnServer(saved);
+ await advance(2_000);
+ if (resumed) await discardRecoveryDraft();
+ expect(editorNodes.find((node) => node.id === "loop")).toBeUndefined();
+ expect(screen.queryByRole("alert")).toBeNull();
+ expect(
+ useWorkflowYamlEditorStore.getState().copilotAcceptance,
+ ).toBeNull();
+ },
+ );
+
+ it("keeps Reject reachable in a closed chat after an unchanged Retry and another timeout", async () => {
+ changesState.hasChanges = true;
+ const { view } = await severStream(false);
+ view.unmount();
+ const recovery = canonicalRecoveriesByWorkflow.get("wpid_1")!;
+ const snapshot = recovery.rollback?.snapshot;
+ await renderChat({ route: "editor", docked: true, isOpen: false });
+ expect(screen.queryByRole("textbox")).toBeNull();
+ expect(screen.getByRole("button", { name: "Reject" })).toBeTruthy();
+ await advance(1_500_000);
+ await act(async () =>
+ fireEvent.click(screen.getByRole("button", { name: "Retry" })),
+ );
+ expect(recovery.rollback?.snapshot).toEqual(snapshot);
+ await advance(1_500_000);
+ historyGet.mockImplementation((path: string) =>
+ path === "/workflows/wpid_1"
+ ? new Promise(() => {})
+ : Promise.resolve(historyResponse),
+ );
+ await act(async () =>
+ fireEvent.click(screen.getByRole("button", { name: "Reject" })),
+ );
+ expect(screen.getByRole("alert").textContent).toContain(
+ "Cancelling the Copilot turn",
+ );
+ expect(
+ useWorkflowYamlEditorStore.getState().copilotAcceptance,
+ ).not.toBeNull();
+ expect(recovery.rollback?.snapshot).toEqual(snapshot);
+ expect(cancelPost).toHaveBeenCalledWith(
+ "/workflow/copilot/cancel",
+ {
+ cancel_token: recovery.poll!.requestId,
+ workflow_copilot_chat_id: "chat-1",
+ source: "stop_button",
+ },
+ { timeout: 5_000 },
+ );
+ expect(
+ editorNodes.find((node) => node.id === "loop")?.data,
+ ).toMatchObject({ loopValue: "unsaved_items" });
+ });
+
+ it.each(["poll", "resume", "retry"] as const)(
+ "bounds a hung canonical read from %s and ignores its stale response",
+ async (source) => {
+ changesState.hasChanges = true;
+ const { saved, view } = await severStream(false);
+ historyResponse.data.request_turn_id = "turn-1";
+ finishTurnHistory();
+ let resolveOldRead!: (value: unknown) => void;
+ let readSignal: AbortSignal | undefined;
+ historyGet.mockImplementation(
+ (path: string, options?: { signal?: AbortSignal }) =>
+ path === "/workflows/wpid_1"
+ ? new Promise((resolve) => {
+ if (!readSignal) {
+ readSignal = options?.signal;
+ resolveOldRead = resolve;
+ }
+ })
+ : Promise.resolve(historyResponse),
+ );
+ if (source === "resume") {
+ view.unmount();
+ await renderChat({ route: "editor", docked: true });
+ } else if (source === "retry") {
+ await act(async () =>
+ fireEvent.click(screen.getByRole("button", { name: "Retry" })),
);
- await vi.advanceTimersByTimeAsync(0);
+ }
+ await advance(source === "retry" ? 0 : 2_000);
+ expect(readSignal?.aborted).toBe(false);
+ await advance(4_999);
+ expect(readSignal?.aborted).toBe(false);
+ await advance(1);
+ expect(readSignal?.aborted).toBe(true);
+ await advance(1_500_000);
+ expect(readSignal?.aborted).toBe(true);
+ expect(screen.getByRole("button", { name: "Reject" })).toBeTruthy();
+ finishOnServer(saved);
+ historyGet.mockImplementation((path: string) =>
+ Promise.resolve(
+ path === "/workflows/wpid_1"
+ ? { data: saved.current }
+ : historyResponse,
+ ),
+ );
+ await act(async () =>
+ fireEvent.click(screen.getByRole("button", { name: "Retry" })),
+ );
+ await advance(0);
+ if (source === "resume") await discardRecoveryDraft();
+ expect(editorNodes.find((node) => node.id === "loop")).toBeUndefined();
+ expect(
+ useWorkflowYamlEditorStore.getState().copilotAcceptance,
+ ).toBeNull();
+ await act(async () => resolveOldRead({ data: saveData.workflow }));
+ expect(screen.queryByRole("alert")).toBeNull();
+ expect(editorNodes.find((node) => node.id === "loop")).toBeUndefined();
+ },
+ );
+
+ it("evicts the least recently visited detached recovery", async () => {
+ changesState.hasChanges = true;
+ const { view } = await severStream(false);
+ view.unmount();
+ const recovery = canonicalRecoveriesByWorkflow.get("wpid_1")!;
+ for (let index = 2; index <= 20; index += 1) {
+ canonicalRecoveriesByWorkflow.set(`wpid_${index}`, {
+ ...recovery,
+ workflowPermanentId: `wpid_${index}`,
});
}
- async function severStream(withTurnId = true) {
+ const revisit = await renderChat({
+ route: "editor",
+ docked: true,
+ isOpen: false,
+ });
+ revisit.unmount();
+ canonicalRecoveriesByWorkflow.set("wpid_21", {
+ ...recovery,
+ workflowPermanentId: "wpid_21",
+ });
+ const newest = await renderChat({
+ route: "editor",
+ docked: true,
+ isOpen: false,
+ workflowPermanentId: "wpid_21",
+ });
+ newest.unmount();
+ expect(canonicalRecoveriesByWorkflow.size).toBe(20);
+ expect(canonicalRecoveriesByWorkflow.has("wpid_2")).toBe(false);
+ expect(canonicalRecoveriesByWorkflow.has("wpid_1")).toBe(true);
+ expect(canonicalRecoveriesByWorkflow.has("wpid_21")).toBe(true);
+ });
+
+ function finishOnServer(saved: { current: WorkflowSaveData["workflow"] }) {
+ historyResponse.data.request_turn_id = "turn-1";
+ saved.current = {
+ ...saveData.workflow,
+ workflow_id: "wf_committed",
+ version: 2,
+ workflow_definition: { blocks: [], parameters: [] },
+ };
+ historyResponse.data.chat_history = [
+ {
+ sender: "ai",
+ content: "Saved the workflow.",
+ created_at: "2026-09-11T00:00:00Z",
+ turn_outcome: {
+ copilot_turn_id: "turn-1",
+ terminal_reason: null,
+ },
+ },
+ ];
+ }
+
+ async function advance(ms: number) {
+ await act(async () => vi.advanceTimersByTimeAsync(ms));
+ }
+
+ function editLoop() {
+ if (refuseMutationDuringYamlCommit()) return;
+ editorNodes = editorNodes.map((node) =>
+ node.id === "loop"
+ ? ({
+ ...node,
+ data: { ...node.data, loopValue: "later_user_items" },
+ } as AppNode)
+ : node,
+ );
+ useWorkflowHasChangesStore.getState().setHasChanges(true);
+ }
+
+ it.each([
+ { interruption: "stream drop", titleFrameReceived: true },
+ { interruption: "navigation", titleFrameReceived: false },
+ ])(
+ "waits for the terminal row after a title-only write and $interruption before releasing the editor (title frame received=$titleFrameReceived)",
+ async ({ interruption, titleFrameReceived }) => {
+ changesState.hasChanges = true;
+ saveData.workflow.version = 1;
+ saveData.workflow.modified_at = "2026-09-11T00:00:00Z";
const apply = vi.fn();
const view = await renderChat({
- route,
+ route: "editor",
docked: true,
onWorkflowUpdate: apply,
});
- const saveRegistration = renderHook(() => {
- const nodes = editorNodes;
- const revision = useWorkflowYamlEditorStore(
- (state) => state.revision,
- );
- const parameters = useWorkflowParametersStore(
- (state) => state.parameters,
- );
- useEffect(() => {
- // FlowRenderer registers a new save callback after graph/store updates render.
- const current = {
- ...saveData,
- blocks: getWorkflowBlocks(nodes, []),
- };
- useWorkflowHasChangesStore.getState().setGetSaveData(() => current);
- }, [nodes, revision, parameters]);
- });
- const saved = { current: saveData.workflow };
+ await submit("edit the workflow");
+ const call = streamCalls[0]!;
+ vi.useFakeTimers();
+ const saved = {
+ current: {
+ ...saveData.workflow,
+ title: "Saved name",
+ modified_at: "2026-09-11T00:00:01Z",
+ },
+ };
historyGet.mockImplementation((path: string) =>
Promise.resolve(
path === "/workflows/wpid_1"
@@ -11246,317 +11529,261 @@ describe("WorkflowCopilotChat — g2 review gate", () => {
: historyResponse,
),
);
- const submittedBlocks = useWorkflowHasChangesStore
- .getState()
- .getSaveData()!.blocks;
- await submit("edit the workflow");
- vi.useFakeTimers();
await act(async () => {
- if (withTurnId) {
- streamCalls[0]!.onMessage({
- type: "turn_start",
- turn_id: "turn-1",
- mode: "build",
- turn_index: 0,
- });
- streamCalls[0]!.onMessage({
- type: "workflow_draft",
- block_labels: [],
- workflow: proposedWorkflowPayload(),
+ call.onMessage({
+ type: "turn_start",
+ turn_id: "turn-1",
+ mode: "build",
+ turn_index: 0,
+ });
+ if (titleFrameReceived) {
+ call.onMessage({
+ type: "title_update",
+ workflow_permanent_id: "wpid_1",
+ title: "Saved name",
});
}
});
- if (withTurnId) {
- act(() => saveRegistration.rerender());
+ if (interruption === "stream drop") {
+ await act(async () => call.reject(new Error("connection dropped")));
+ } else {
+ await act(async () => view.unmount());
+ expect(
+ canonicalRecoveriesByWorkflow.get("wpid_1")?.rollback
+ ?.titlePersisted,
+ ).toBe(titleFrameReceived);
expect(
- useWorkflowHasChangesStore.getState().getSaveData()!.blocks,
- ).not.toEqual(submittedBlocks);
+ canonicalRecoveriesByWorkflow.get("wpid_1")?.rollback
+ ?.workflowPersisted,
+ ).toBe(false);
+ await renderChat({
+ route: "editor",
+ docked: true,
+ onWorkflowUpdate: apply,
+ });
}
- await act(async () =>
- streamCalls[0]!.reject(new Error("connection dropped")),
- );
- expect(historyGet).toHaveBeenCalledWith(
- "/workflows/wpid_1",
- expect.objectContaining({ signal: expect.any(AbortSignal) }),
- );
+ if (vi.isFakeTimers()) await advance(2_000);
expect(
useWorkflowYamlEditorStore.getState().copilotAcceptance,
).not.toBeNull();
- expect(setEditorNodes).not.toHaveBeenCalled();
- if (withTurnId) {
- expect(
- editorNodes.find((node) => node.id === "loop"),
- ).toBeUndefined();
- } else {
- expect(
- editorNodes.find((node) => node.id === "loop")?.data,
- ).toMatchObject({
- loopValue: "unsaved_items",
- loopVariableReference: "{{ item }}",
- });
- }
- apply.mockClear();
- vi.mocked(toast).mockClear();
- return { apply, saved, view };
- }
-
- it.each([false, true])(
- "retains recovery through timeout and Retry until reconciliation or Reject (resumed=%s)",
- async (resumed) => {
- changesState.hasChanges = true;
- const { saved, view } = await severStream();
- if (resumed) {
- view.unmount();
- await renderChat({ route, docked: true, isOpen: false });
- }
- const expectControls = () => {
- expect(screen.getByRole("button", { name: "Retry" })).toBeTruthy();
- expect(screen.getByRole("button", { name: "Reject" })).toBeTruthy();
- expect(
- useWorkflowYamlEditorStore.getState().copilotAcceptance,
- ).not.toBeNull();
- };
- await advance(1_500_000);
- expectControls();
- expect(screen.getByRole("alert").textContent).toContain(
- "Could not confirm",
- );
- await act(async () =>
- fireEvent.click(screen.getByRole("button", { name: "Retry" })),
- );
- expectControls();
- const retainedNodes = structuredClone(editorNodes);
- act(editLoop);
- expect(editorNodes).toEqual(retainedNodes);
- finishOnServer(saved);
- await advance(2_000);
- if (resumed) await discardRecoveryDraft();
- expect(
- editorNodes.find((node) => node.id === "loop"),
- ).toBeUndefined();
- expect(screen.queryByRole("alert")).toBeNull();
- expect(
- useWorkflowYamlEditorStore.getState().copilotAcceptance,
- ).toBeNull();
- },
- );
-
- it("keeps Reject reachable in a closed chat after an unchanged Retry and another timeout", async () => {
- changesState.hasChanges = true;
- const { view } = await severStream(false);
- view.unmount();
- const recovery = canonicalRecoveriesByWorkflow.get("wpid_1")!;
- const snapshot = recovery.rollback?.snapshot;
- await renderChat({ route, docked: true, isOpen: false });
- expect(screen.queryByRole("textbox")).toBeNull();
- expect(screen.getByRole("button", { name: "Reject" })).toBeTruthy();
- await advance(1_500_000);
- await act(async () =>
- fireEvent.click(screen.getByRole("button", { name: "Retry" })),
- );
- expect(recovery.rollback?.snapshot).toEqual(snapshot);
- await advance(1_500_000);
- historyGet.mockImplementation((path: string) =>
- path === "/workflows/wpid_1"
- ? new Promise(() => {})
- : Promise.resolve(historyResponse),
- );
- await act(async () =>
- fireEvent.click(screen.getByRole("button", { name: "Reject" })),
- );
- expect(screen.getByRole("alert").textContent).toContain(
- "Cancelling the Copilot turn",
- );
- expect(
- useWorkflowYamlEditorStore.getState().copilotAcceptance,
- ).not.toBeNull();
- expect(recovery.rollback?.snapshot).toEqual(snapshot);
- expect(cancelPost).toHaveBeenCalledWith(
- "/workflow/copilot/cancel",
- {
- cancel_token: recovery.poll!.requestId,
- workflow_copilot_chat_id: "chat-1",
- source: "stop_button",
- },
- { timeout: 5_000 },
- );
- expect(
- editorNodes.find((node) => node.id === "loop")?.data,
- ).toMatchObject({ loopValue: "unsaved_items" });
- });
+ const owner =
+ useWorkflowYamlEditorStore.getState().editorOwner ??
+ createYamlCommitOwner("wpid_1");
+ registerEditorOwner(owner);
+ const reservation =
+ useWorkflowYamlEditorStore.getState().copilotAcceptance;
+ expect(reservation).not.toBeNull();
+ expect(beginSaveTransaction(owner)).toBe(false);
+ expect(screen.getByRole("alert")).toBeTruthy();
+ expect(apply).not.toHaveBeenCalled();
- it.each(["poll", "resume", "retry"] as const)(
- "bounds a hung canonical read from %s and ignores its stale response",
- async (source) => {
- changesState.hasChanges = true;
- const { saved, view } = await severStream(false);
- historyResponse.data.request_turn_id = "turn-1";
- finishTurnHistory();
- let resolveOldRead!: (value: unknown) => void;
- let readSignal: AbortSignal | undefined;
- historyGet.mockImplementation(
- (path: string, options?: { signal?: AbortSignal }) =>
- path === "/workflows/wpid_1"
- ? new Promise((resolve) => {
- if (!readSignal) {
- readSignal = options?.signal;
- resolveOldRead = resolve;
- }
- })
- : Promise.resolve(historyResponse),
- );
- if (source === "resume") {
- view.unmount();
- await renderChat({ route, docked: true });
- } else if (source === "retry") {
- await act(async () =>
- fireEvent.click(screen.getByRole("button", { name: "Retry" })),
- );
- }
- await advance(source === "retry" ? 0 : 2_000);
- expect(readSignal?.aborted).toBe(false);
- await advance(4_999);
- expect(readSignal?.aborted).toBe(false);
- await advance(1);
- expect(readSignal?.aborted).toBe(true);
- await advance(1_500_000);
- expect(readSignal?.aborted).toBe(true);
- expect(screen.getByRole("button", { name: "Reject" })).toBeTruthy();
- finishOnServer(saved);
- historyGet.mockImplementation((path: string) =>
- Promise.resolve(
- path === "/workflows/wpid_1"
- ? { data: saved.current }
- : historyResponse,
- ),
- );
+ if (interruption === "navigation") {
await act(async () =>
- fireEvent.click(screen.getByRole("button", { name: "Retry" })),
+ useCopilotHeaderStore.getState().controls!.onNewChat(),
);
- await advance(0);
- if (source === "resume") await discardRecoveryDraft();
- expect(
- editorNodes.find((node) => node.id === "loop"),
- ).toBeUndefined();
- expect(
- useWorkflowYamlEditorStore.getState().copilotAcceptance,
- ).toBeNull();
- await act(async () => resolveOldRead({ data: saveData.workflow }));
- expect(screen.queryByRole("alert")).toBeNull();
- expect(
- editorNodes.find((node) => node.id === "loop"),
- ).toBeUndefined();
- },
- );
-
- it("evicts the least recently visited detached recovery", async () => {
- changesState.hasChanges = true;
- const { view } = await severStream(false);
- view.unmount();
- const recovery = canonicalRecoveriesByWorkflow.get("wpid_1")!;
- for (let index = 2; index <= 20; index += 1) {
- canonicalRecoveriesByWorkflow.set(`wpid_${index}`, {
- ...recovery,
- workflowPermanentId: `wpid_${index}`,
- });
}
- const revisit = await renderChat({
- route,
- docked: true,
- isOpen: false,
- });
- revisit.unmount();
- canonicalRecoveriesByWorkflow.set("wpid_21", {
- ...recovery,
- workflowPermanentId: "wpid_21",
- });
- const newest = await renderChat({
- route,
- docked: true,
- isOpen: false,
- workflowPermanentId: "wpid_21",
- });
- newest.unmount();
- expect(canonicalRecoveriesByWorkflow.size).toBe(20);
- expect(canonicalRecoveriesByWorkflow.has("wpid_2")).toBe(false);
- expect(canonicalRecoveriesByWorkflow.has("wpid_1")).toBe(true);
- expect(canonicalRecoveriesByWorkflow.has("wpid_21")).toBe(true);
- });
-
- function finishOnServer(saved: {
- current: WorkflowSaveData["workflow"];
- }) {
- historyResponse.data.request_turn_id = "turn-1";
- saved.current = {
- ...saveData.workflow,
- workflow_id: "wf_committed",
- version: 2,
- workflow_definition: { blocks: [], parameters: [] },
- };
historyResponse.data.chat_history = [
{
sender: "ai",
- content: "Saved the workflow.",
- created_at: "2026-09-11T00:00:00Z",
+ content: "Another turn finished.",
+ created_at: "2026-09-11T00:00:02Z",
turn_outcome: {
- copilot_turn_id: "turn-1",
+ copilot_turn_id: "turn-other",
terminal_reason: null,
},
},
];
- }
-
- async function advance(ms: number) {
- await act(async () => vi.advanceTimersByTimeAsync(ms));
- }
+ await advance(2_000);
+ expect(historyGet).toHaveBeenCalledWith(
+ "/workflow/copilot/chat-history",
+ expect.objectContaining({
+ params: { workflow_copilot_chat_id: "chat-1" },
+ }),
+ );
+ expect(apply).not.toHaveBeenCalled();
+ expect(screen.getByRole("alert")).toBeTruthy();
+ expect(useWorkflowYamlEditorStore.getState().copilotAcceptance).toBe(
+ reservation,
+ );
- function editLoop() {
- if (refuseMutationDuringYamlCommit()) return;
- editorNodes = editorNodes.map((node) =>
- node.id === "loop"
- ? ({
- ...node,
- data: { ...node.data, loopValue: "later_user_items" },
- } as AppNode)
- : node,
+ historyGet.mockClear();
+ finishOnServer(saved);
+ await advance(5_000);
+ expect(historyGet.mock.calls.map(([path]) => path)).toEqual([
+ "/workflow/copilot/chat-history",
+ "/workflows/wpid_1",
+ ]);
+ if (interruption === "navigation") await discardRecoveryDraft();
+ expect(apply).toHaveBeenCalledExactlyOnceWith(
+ saved.current,
+ expect.objectContaining({ persisted: true, applied: true }),
);
- useWorkflowHasChangesStore.getState().setHasChanges(true);
- }
+ if (interruption === "navigation") {
+ expect(
+ useCopilotHeaderStore.getState().controls!.currentChatId,
+ ).toBeNull();
+ if (interruption === "navigation")
+ expect(screen.queryByText("Saved the workflow.")).toBeNull();
+ else expect(screen.getByText("Saved the workflow.")).toBeTruthy();
+ }
+ expect(screen.queryByRole("alert")).toBeNull();
+ expect(
+ useWorkflowYamlEditorStore.getState().copilotAcceptance,
+ ).toBeNull();
+ expect(beginSaveTransaction(owner)).toBe(true);
+ expect(
+ buildWorkflowSaveRequest({
+ ...saveData,
+ blocks: getWorkflowBlocks(editorNodes, []),
+ }).workflow_definition.blocks,
+ ).toEqual(saved.current.workflow_definition.blocks);
+ finishSaveTransaction(owner);
+ historyGet.mockClear();
+ await advance(30_000);
+ expect(historyGet).not.toHaveBeenCalled();
+ },
+ );
- it.each([
- { interruption: "stream drop", titleFrameReceived: true },
- { interruption: "navigation", titleFrameReceived: true },
- { interruption: "stream drop", titleFrameReceived: false },
- { interruption: "navigation", titleFrameReceived: false },
- ])(
- "waits for the terminal row after a title-only write and $interruption before releasing the editor (title frame received=$titleFrameReceived)",
- async ({ interruption, titleFrameReceived }) => {
- changesState.hasChanges = true;
- saveData.workflow.version = 1;
- saveData.workflow.modified_at = "2026-09-11T00:00:00Z";
- const apply = vi.fn();
- const view = await renderChat({
- route,
- docked: true,
- onWorkflowUpdate: apply,
- });
- await submit("edit the workflow");
- const call = streamCalls[0]!;
- vi.useFakeTimers();
- const saved = {
- current: {
- ...saveData.workflow,
- title: "Saved name",
- modified_at: "2026-09-11T00:00:01Z",
+ it("retains the submitted draft and refuses edits until the late server workflow resolves", async () => {
+ changesState.hasChanges = true;
+ const { saved } = await severStream();
+ const owner =
+ useWorkflowYamlEditorStore.getState().editorOwner ??
+ createYamlCommitOwner("wpid_1");
+ registerEditorOwner(owner);
+ expect(beginSaveTransaction(owner)).toBe(false);
+ const retainedNodes = structuredClone(editorNodes);
+ act(editLoop);
+ expect(editorNodes).toEqual(retainedNodes);
+ expect(screen.getByRole("button", { name: "Reject" })).toBeTruthy();
+ finishOnServer(saved);
+ await advance(2_000);
+ expect(editorNodes.find((node) => node.id === "loop")).toBeUndefined();
+ expect(
+ useWorkflowYamlEditorStore.getState().copilotAcceptance,
+ ).toBeNull();
+ expect(beginSaveTransaction(owner)).toBe(true);
+ finishSaveTransaction(owner);
+ });
+
+ it.each(["new chat", "history"] as const)(
+ "continues canonical recovery after switching to %s without replacing the selected chat",
+ async (destination) => {
+ changesState.hasChanges = true;
+ const { apply, saved } = await severStream();
+ const controls = useCopilotHeaderStore.getState().controls!;
+ const selectedHistory = {
+ ...historyResponse.data,
+ workflow_copilot_chat_id: "chat-other",
+ chat_history: [
+ {
+ sender: "ai",
+ content: "Selected history",
+ created_at: "2026-09-11T00:00:00Z",
},
- };
- historyGet.mockImplementation((path: string) =>
+ ],
+ };
+ historyGet.mockImplementation(
+ (
+ path: string,
+ config?: { params?: { workflow_copilot_chat_id?: string } },
+ ) =>
Promise.resolve(
path === "/workflows/wpid_1"
? { data: saved.current }
- : historyResponse,
+ : config?.params?.workflow_copilot_chat_id === "chat-other"
+ ? { data: selectedHistory }
+ : historyResponse,
),
- );
+ );
+ expect(controls.disabled).toBe(false);
+ await act(async () => {
+ if (destination === "new chat") controls.onNewChat();
+ else
+ controls.onSelectChat({
+ workflow_copilot_chat_id: "chat-other",
+ workflow_permanent_id: "wpid_1",
+ title: "Another chat",
+ created_at: "2026-09-11T00:00:00Z",
+ modified_at: "2026-09-11T00:00:00Z",
+ });
+ });
+ const selectedChat = destination === "new chat" ? null : "chat-other";
+ expect(useCopilotHeaderStore.getState().controls!.currentChatId).toBe(
+ selectedChat,
+ );
+ historyGet.mockClear();
+ finishOnServer(saved);
+ await advance(2_000);
+ expect(historyGet).toHaveBeenCalledWith(
+ "/workflows/wpid_1",
+ expect.objectContaining({ signal: expect.any(AbortSignal) }),
+ );
+ expect(apply).toHaveBeenCalledExactlyOnceWith(
+ saved.current,
+ expect.objectContaining({ persisted: true, applied: true }),
+ );
+ expect(useCopilotHeaderStore.getState().controls!.currentChatId).toBe(
+ selectedChat,
+ );
+ expect(screen.queryByText("Saved the workflow.")).toBeNull();
+ if (destination === "history")
+ expect(screen.getByText("Selected history")).toBeTruthy();
+ historyGet.mockClear();
+ await advance(30_000);
+ expect(historyGet).not.toHaveBeenCalled();
+ },
+ );
+
+ it("refuses edits while the late canonical read owns the reservation", async () => {
+ changesState.hasChanges = true;
+ const { apply, saved } = await severStream();
+ finishOnServer(saved);
+ let resolveRead!: (value: unknown) => void;
+ historyGet.mockImplementation((path: string) =>
+ path === "/workflows/wpid_1"
+ ? new Promise((resolve) => {
+ resolveRead = resolve;
+ })
+ : Promise.resolve(historyResponse),
+ );
+ await advance(2_000);
+ expect(resolveRead).toBeTypeOf("function");
+ const retainedNodes = structuredClone(editorNodes);
+ act(editLoop);
+ expect(editorNodes).toEqual(retainedNodes);
+ expect(toast).toHaveBeenCalledExactlyOnceWith({
+ title: "Wait for the Copilot change to finish",
+ variant: "destructive",
+ });
+ historyGet.mockImplementation((path: string) =>
+ Promise.resolve(
+ path === "/workflows/wpid_1"
+ ? { data: saved.current }
+ : historyResponse,
+ ),
+ );
+ await act(async () => resolveRead({ data: saved.current }));
+ expect(apply).toHaveBeenCalledExactlyOnceWith(
+ saved.current,
+ expect.objectContaining({ persisted: true, applied: true }),
+ );
+ expect(
+ useWorkflowYamlEditorStore.getState().copilotAcceptance,
+ ).toBeNull();
+ });
+
+ it.each([false, true])(
+ "parks a live turn on navigation and reconciles its commit before saving (turn started=%s)",
+ async (turnStarted) => {
+ changesState.hasChanges = true;
+ const view = await renderChat({ route: "editor", docked: true });
+ const queryKey = ["workflow", "wpid_1"];
+ queryClient.setQueryData(queryKey, saveData.workflow);
+ const submittedSnapshot = structuredClone(editorNodes);
+ await submit("edit the workflow");
+ const call = streamCalls[0]!;
+ if (turnStarted) {
await act(async () => {
call.onMessage({
type: "turn_start",
@@ -11564,739 +11791,492 @@ describe("WorkflowCopilotChat — g2 review gate", () => {
mode: "build",
turn_index: 0,
});
- if (titleFrameReceived) {
- call.onMessage({
- type: "title_update",
- workflow_permanent_id: "wpid_1",
- title: "Saved name",
- });
- }
});
- if (interruption === "stream drop") {
- await act(async () => call.reject(new Error("connection dropped")));
- } else {
- await act(async () => view.unmount());
- expect(
- canonicalRecoveriesByWorkflow.get("wpid_1")?.rollback
- ?.titlePersisted,
- ).toBe(titleFrameReceived);
- expect(
- canonicalRecoveriesByWorkflow.get("wpid_1")?.rollback
- ?.workflowPersisted,
- ).toBe(false);
- await renderChat({ route, docked: true, onWorkflowUpdate: apply });
- }
- if (vi.isFakeTimers()) await advance(2_000);
- expect(
- useWorkflowYamlEditorStore.getState().copilotAcceptance,
- ).not.toBeNull();
- const owner =
- useWorkflowYamlEditorStore.getState().editorOwner ??
- createYamlCommitOwner("wpid_1");
- registerEditorOwner(owner);
- const reservation =
- useWorkflowYamlEditorStore.getState().copilotAcceptance;
- expect(reservation).not.toBeNull();
- expect(beginSaveTransaction(owner)).toBe(false);
- expect(screen.getByRole("alert")).toBeTruthy();
- expect(apply).not.toHaveBeenCalled();
+ }
+ await act(async () => view.unmount());
+ const parked = canonicalRecoveriesByWorkflow.get("wpid_1");
+ expect(parked).toMatchObject({
+ resumed: true,
+ baseline: saveData.workflow,
+ preservedSettings: saveData.settings,
+ poll: {
+ chatId: "chat-1",
+ turnId: turnStarted ? "turn-1" : null,
+ requestId: expect.any(String),
+ },
+ rollback: { snapshot: { nodes: submittedSnapshot } },
+ });
+ const otherWorkflow = await renderChat({
+ route: "editor",
+ docked: true,
+ workflowPermanentId: "wpid_other",
+ });
+ expect(
+ useWorkflowYamlEditorStore.getState().copilotAcceptance,
+ ).toBeNull();
+ const saved = { current: saveData.workflow };
+ finishOnServer(saved);
+ await act(async () => {
+ call.onMessage(proposalResponse("Buffered old response."));
+ });
+ expect(screen.queryByText("Buffered old response.")).toBeNull();
+ otherWorkflow.unmount();
- if (interruption === "navigation") {
- await act(async () =>
- useCopilotHeaderStore.getState().controls!.onNewChat(),
- );
- }
+ const returnedWorkflow = await queryClient.fetchQuery({
+ queryKey,
+ queryFn: async () => saved.current,
+ });
+ expect(returnedWorkflow.workflow_id).toBe("wf_committed");
+ let resolveRead!: (response: { data: WorkflowApiResponse }) => void;
+ const read = new Promise<{ data: WorkflowApiResponse }>((resolve) => {
+ resolveRead = resolve;
+ });
+ historyGet.mockImplementation((path: string) =>
+ path === "/workflows/wpid_1"
+ ? read
+ : Promise.resolve(historyResponse),
+ );
+ vi.useFakeTimers();
+ await renderChat({ route: "editor", docked: true });
+ const owner =
+ useWorkflowYamlEditorStore.getState().editorOwner ??
+ createYamlCommitOwner("wpid_1");
+ registerEditorOwner(owner);
+ expect(beginSaveTransaction(owner)).toBe(false);
+ expect(screen.getByRole("button", { name: "Retry" })).toBeTruthy();
+ expect(screen.getByRole("button", { name: "Reject" })).toBeTruthy();
+ await act(async () => resolveRead({ data: saved.current }));
+ expect(screen.getByRole("alert")).toBeTruthy();
+ expect(beginSaveTransaction(owner)).toBe(false);
+ await advance(2_000);
+ await discardRecoveryDraft();
+ expect(screen.queryByRole("alert")).toBeNull();
+ expect(beginSaveTransaction(owner)).toBe(true);
+ const request = buildWorkflowSaveRequest({
+ ...saveData,
+ blocks: getWorkflowBlocks(editorNodes, []),
+ });
+ expect(request.workflow_definition.blocks).toEqual(
+ saved.current.workflow_definition.blocks,
+ );
+ expect(editorNodes.find((node) => node.id === "loop")).toBeUndefined();
+ finishSaveTransaction(owner);
+ },
+ );
+
+ it.each(["updated", "unchanged", "interrupted"] as const)(
+ "resumes recovery after workflow navigation without losing local edits (%s canonical outcome)",
+ async (outcome) => {
+ changesState.hasChanges = true;
+ saveData.workflow.workflow_definition = {
+ blocks: [],
+ parameters: [],
+ };
+ const { view, apply, saved } = await severStream();
+ view.unmount();
+ expect(
+ useWorkflowYamlEditorStore.getState().copilotAcceptance,
+ ).toBeNull();
+ historyGet.mockClear();
+ await advance(3_000);
+ expect(historyGet).not.toHaveBeenCalled();
+
+ vi.useRealTimers();
+ const otherWorkflow = await renderChat({
+ route: "editor",
+ docked: true,
+ workflowPermanentId: "wpid_other",
+ });
+ expect(
+ useWorkflowYamlEditorStore.getState().copilotAcceptance,
+ ).toBeNull();
+ expect(historyGet).not.toHaveBeenCalledWith("/workflows/wpid_1");
+ otherWorkflow.unmount();
+ historyGet.mockClear();
+ const revisitedApply = vi.fn();
+ await renderChat({
+ route: "editor",
+ docked: true,
+ onWorkflowUpdate: revisitedApply,
+ });
+ if (vi.isFakeTimers()) await advance(2_000);
+ expect(
+ useWorkflowYamlEditorStore.getState().copilotAcceptance,
+ ).not.toBeNull();
+ expect(
+ useWorkflowYamlEditorStore.getState().copilotAcceptance,
+ ).not.toBeNull();
+ expect(revisitedApply).not.toHaveBeenCalled();
+ act(editLoop);
+ expect(
+ editorNodes.find((node) => node.id === "loop")?.data,
+ ).toMatchObject({
+ loopValue: "unsaved_items",
+ });
+
+ const baseline = saved.current;
+ finishOnServer(saved);
+ if (outcome !== "updated") saved.current = baseline;
+ if (outcome === "interrupted") {
historyResponse.data.chat_history = [
{
sender: "ai",
- content: "Another turn finished.",
- created_at: "2026-09-11T00:00:02Z",
+ content: "Turn interrupted.",
+ created_at: "2026-09-11T00:00:00Z",
turn_outcome: {
- copilot_turn_id: "turn-other",
- terminal_reason: null,
+ copilot_turn_id: "turn-1",
+ terminal_reason: "interrupted",
},
},
];
- await advance(2_000);
- expect(historyGet).toHaveBeenCalledWith(
- "/workflow/copilot/chat-history",
- expect.objectContaining({
- params: { workflow_copilot_chat_id: "chat-1" },
- }),
+ }
+ if (outcome === "interrupted") {
+ vi.useFakeTimers();
+ await act(async () =>
+ fireEvent.click(screen.getByRole("button", { name: "Retry" })),
);
- expect(apply).not.toHaveBeenCalled();
- expect(screen.getByRole("alert")).toBeTruthy();
- expect(useWorkflowYamlEditorStore.getState().copilotAcceptance).toBe(
- reservation,
+ await advance(120_000);
+ expect(revisitedApply).not.toHaveBeenCalled();
+ expect(
+ useWorkflowYamlEditorStore.getState().copilotAcceptance,
+ ).not.toBeNull();
+ finishTurnHistory();
+ await act(async () =>
+ fireEvent.click(screen.getByRole("button", { name: "Retry" })),
);
-
- historyGet.mockClear();
- finishOnServer(saved);
- await advance(5_000);
- expect(historyGet.mock.calls.map(([path]) => path)).toEqual([
- "/workflow/copilot/chat-history",
- "/workflows/wpid_1",
- ]);
- if (interruption === "navigation") await discardRecoveryDraft();
- expect(apply).toHaveBeenCalledExactlyOnceWith(
+ expect(revisitedApply).not.toHaveBeenCalled();
+ expect(
+ useWorkflowYamlEditorStore.getState().copilotAcceptance,
+ ).not.toBeNull();
+ await advance(2_000);
+ }
+ if (outcome !== "interrupted") {
+ vi.useFakeTimers();
+ await act(async () => {
+ fireEvent.click(screen.getByRole("button", { name: "Retry" }));
+ await vi.advanceTimersByTimeAsync(2_000);
+ });
+ }
+ expect(revisitedApply).not.toHaveBeenCalled();
+ const generation = useWorkflowHasChangesStore.getState().saveGeneration;
+ if (outcome === "updated") {
+ expect(
+ screen.getByRole("button", { name: "Keep my edits" }),
+ ).toBeTruthy();
+ await act(async () => {
+ fireEvent.click(
+ screen.getByRole("button", {
+ name: "Apply and discard my edits",
+ }),
+ );
+ await vi.advanceTimersByTimeAsync(2_000);
+ });
+ } else {
+ expect(
+ screen.queryByRole("button", { name: "Keep my edits" }),
+ ).toBeNull();
+ }
+ if (outcome === "updated") {
+ expect(revisitedApply).toHaveBeenCalledExactlyOnceWith(
saved.current,
expect.objectContaining({ persisted: true, applied: true }),
);
- if (interruption === "navigation") {
- expect(
- useCopilotHeaderStore.getState().controls!.currentChatId,
- ).toBeNull();
- if (interruption === "navigation")
- expect(screen.queryByText("Saved the workflow.")).toBeNull();
- else expect(screen.getByText("Saved the workflow.")).toBeTruthy();
- }
- expect(screen.queryByRole("alert")).toBeNull();
expect(
- useWorkflowYamlEditorStore.getState().copilotAcceptance,
- ).toBeNull();
- expect(beginSaveTransaction(owner)).toBe(true);
+ editorNodes.find((node) => node.id === "loop"),
+ ).toBeUndefined();
+ } else {
+ expect(revisitedApply).not.toHaveBeenCalled();
expect(
- buildWorkflowSaveRequest({
- ...saveData,
- blocks: getWorkflowBlocks(editorNodes, []),
- }).workflow_definition.blocks,
- ).toEqual(saved.current.workflow_definition.blocks);
- finishSaveTransaction(owner);
- historyGet.mockClear();
- await advance(30_000);
- expect(historyGet).not.toHaveBeenCalled();
- },
- );
+ editorNodes.find((node) => node.id === "loop")?.data,
+ ).toMatchObject({ loopValue: "unsaved_items" });
+ expect(useWorkflowHasChangesStore.getState().saveGeneration).toBe(
+ generation,
+ );
+ expect(toast).not.toHaveBeenCalledWith(
+ expect.objectContaining({
+ description: expect.stringContaining("saved on the server"),
+ }),
+ );
+ }
+ expect(apply).not.toHaveBeenCalled();
+ expect(
+ useWorkflowYamlEditorStore.getState().copilotAcceptance,
+ ).toBeNull();
+ },
+ );
- it("retains the submitted draft and refuses edits until the late server workflow resolves", async () => {
+ it.each(["late commit", "budget", "save in progress"] as const)(
+ "retains the pre-turn recovery reservation and deadline across unmount: %s",
+ async (outcome) => {
changesState.hasChanges = true;
- const { saved } = await severStream();
+ const { view, saved } = await severStream(false);
+ const originalReservation =
+ useWorkflowYamlEditorStore.getState().copilotAcceptance;
+ view.unmount();
+ const persisted = canonicalRecoveriesByWorkflow.get("wpid_1")!;
+ expect(persisted.poll?.turnId).toBeNull();
+ expect(persisted.poll?.requestId).toBeTruthy();
+ const poll = { ...persisted.poll! };
+ expect(
+ useWorkflowYamlEditorStore.getState().copilotAcceptance,
+ ).toBeNull();
const owner =
useWorkflowYamlEditorStore.getState().editorOwner ??
createYamlCommitOwner("wpid_1");
- registerEditorOwner(owner);
- expect(beginSaveTransaction(owner)).toBe(false);
- const retainedNodes = structuredClone(editorNodes);
+ if (outcome === "save in progress") {
+ registerEditorOwner(owner);
+ expect(beginSaveTransaction(owner)).toBe(true);
+ }
+ const apply = vi.fn();
+ const revisited = await renderChat({
+ route: "editor",
+ docked: true,
+ onWorkflowUpdate: apply,
+ });
+ if (outcome === "save in progress") {
+ expect(useWorkflowYamlEditorStore.getState().lockKind).toBe("save");
+ await act(async () => finishSaveTransaction(owner));
+ }
+ const resumedReservation =
+ useWorkflowYamlEditorStore.getState().copilotAcceptance;
+ expect(resumedReservation).not.toBeNull();
+ expect(resumedReservation).not.toBe(originalReservation);
+ expect(beginYamlCommit(createYamlCommitOwner("wpid_1"))).toBe(false);
act(editLoop);
- expect(editorNodes).toEqual(retainedNodes);
- expect(screen.getByRole("button", { name: "Reject" })).toBeTruthy();
- finishOnServer(saved);
- await advance(2_000);
- expect(editorNodes.find((node) => node.id === "loop")).toBeUndefined();
expect(
- useWorkflowYamlEditorStore.getState().copilotAcceptance,
- ).toBeNull();
- expect(beginSaveTransaction(owner)).toBe(true);
- finishSaveTransaction(owner);
- });
-
- it.each(["new chat", "history"] as const)(
- "continues canonical recovery after switching to %s without replacing the selected chat",
- async (destination) => {
- changesState.hasChanges = true;
- const { apply, saved } = await severStream();
- const controls = useCopilotHeaderStore.getState().controls!;
- const selectedHistory = {
- ...historyResponse.data,
- workflow_copilot_chat_id: "chat-other",
- chat_history: [
- {
- sender: "ai",
- content: "Selected history",
- created_at: "2026-09-11T00:00:00Z",
- },
- ],
- };
- historyGet.mockImplementation(
- (
- path: string,
- config?: { params?: { workflow_copilot_chat_id?: string } },
- ) =>
- Promise.resolve(
- path === "/workflows/wpid_1"
- ? { data: saved.current }
- : config?.params?.workflow_copilot_chat_id === "chat-other"
- ? { data: selectedHistory }
- : historyResponse,
- ),
- );
- expect(controls.disabled).toBe(false);
- await act(async () => {
- if (destination === "new chat") controls.onNewChat();
- else
- controls.onSelectChat({
- workflow_copilot_chat_id: "chat-other",
- workflow_permanent_id: "wpid_1",
- title: "Another chat",
- created_at: "2026-09-11T00:00:00Z",
- modified_at: "2026-09-11T00:00:00Z",
- });
- });
- const selectedChat = destination === "new chat" ? null : "chat-other";
- expect(useCopilotHeaderStore.getState().controls!.currentChatId).toBe(
- selectedChat,
+ editorNodes.find((node) => node.id === "loop")?.data,
+ ).toMatchObject({
+ loopValue: "unsaved_items",
+ });
+ revisited.unmount();
+ expect(canonicalRecoveriesByWorkflow.get("wpid_1")?.poll).toEqual(poll);
+ await renderChat({
+ route: "editor",
+ docked: true,
+ onWorkflowUpdate: apply,
+ });
+ if (outcome === "budget") {
+ await advance(Math.max(0, poll.deadline - Date.now() - 1));
+ expect(
+ useWorkflowYamlEditorStore.getState().copilotAcceptance,
+ ).not.toBeNull();
+ await advance(1);
+ expect(apply).not.toHaveBeenCalled();
+ expect(
+ useWorkflowYamlEditorStore.getState().copilotAcceptance,
+ ).not.toBeNull();
+ finishOnServer(saved);
+ await act(async () =>
+ fireEvent.click(screen.getByRole("button", { name: "Retry" })),
);
- historyGet.mockClear();
+ await advance(0);
+ await discardRecoveryDraft();
+ } else {
finishOnServer(saved);
await advance(2_000);
- expect(historyGet).toHaveBeenCalledWith(
- "/workflows/wpid_1",
- expect.objectContaining({ signal: expect.any(AbortSignal) }),
- );
+ await discardRecoveryDraft();
expect(apply).toHaveBeenCalledExactlyOnceWith(
saved.current,
expect.objectContaining({ persisted: true, applied: true }),
);
- expect(useCopilotHeaderStore.getState().controls!.currentChatId).toBe(
- selectedChat,
- );
- expect(screen.queryByText("Saved the workflow.")).toBeNull();
- if (destination === "history")
- expect(screen.getByText("Selected history")).toBeTruthy();
- historyGet.mockClear();
- await advance(30_000);
- expect(historyGet).not.toHaveBeenCalled();
- },
- );
-
- it("refuses edits while the late canonical read owns the reservation", async () => {
- changesState.hasChanges = true;
- const { apply, saved } = await severStream();
- finishOnServer(saved);
- let resolveRead!: (value: unknown) => void;
- historyGet.mockImplementation((path: string) =>
- path === "/workflows/wpid_1"
- ? new Promise((resolve) => {
- resolveRead = resolve;
- })
- : Promise.resolve(historyResponse),
- );
- await advance(2_000);
- expect(resolveRead).toBeTypeOf("function");
- const retainedNodes = structuredClone(editorNodes);
- act(editLoop);
- expect(editorNodes).toEqual(retainedNodes);
- expect(toast).toHaveBeenCalledExactlyOnceWith({
- title: "Wait for the Copilot change to finish",
- variant: "destructive",
- });
- historyGet.mockImplementation((path: string) =>
- Promise.resolve(
- path === "/workflows/wpid_1"
- ? { data: saved.current }
- : historyResponse,
- ),
- );
- await act(async () => resolveRead({ data: saved.current }));
- expect(apply).toHaveBeenCalledExactlyOnceWith(
- saved.current,
- expect.objectContaining({ persisted: true, applied: true }),
- );
+ }
expect(
useWorkflowYamlEditorStore.getState().copilotAcceptance,
).toBeNull();
+ expect(screen.getByText("Saved the workflow.")).toBeTruthy();
+ },
+ );
+
+ it("keeps resumed recovery locked when a finished turn's canonical read fails", async () => {
+ changesState.hasChanges = true;
+ const { view, saved } = await severStream();
+ view.unmount();
+ finishOnServer(saved);
+ let readFails = true;
+ historyGet.mockImplementation((path: string) =>
+ path === "/workflows/wpid_1"
+ ? readFails
+ ? Promise.reject(new Error("canonical unavailable"))
+ : Promise.resolve({ data: saved.current })
+ : Promise.resolve(historyResponse),
+ );
+ const apply = vi.fn();
+ await renderChat({
+ route: "editor",
+ docked: true,
+ onWorkflowUpdate: apply,
});
+ await advance(2_000);
+ expect(apply).not.toHaveBeenCalled();
+ expect(
+ useWorkflowYamlEditorStore.getState().copilotAcceptance,
+ ).not.toBeNull();
+ expect(screen.getByRole("button", { name: "Retry" })).toBeTruthy();
+ readFails = false;
+ await advance(3_000);
+ await discardRecoveryDraft();
+ expect(apply).toHaveBeenCalledExactlyOnceWith(
+ saved.current,
+ expect.objectContaining({ persisted: true, applied: true }),
+ );
+ expect(
+ useWorkflowYamlEditorStore.getState().copilotAcceptance,
+ ).toBeNull();
+ });
- it.each([false, true])(
- "parks a live turn on navigation and reconciles its commit before saving (turn started=%s)",
- async (turnStarted) => {
- changesState.hasChanges = true;
- const view = await renderChat({ route, docked: true });
- const queryKey = ["workflow", "wpid_1"];
- queryClient.setQueryData(queryKey, saveData.workflow);
- const submittedSnapshot = structuredClone(editorNodes);
- await submit("edit the workflow");
- const call = streamCalls[0]!;
- if (turnStarted) {
- await act(async () => {
- call.onMessage({
- type: "turn_start",
- turn_id: "turn-1",
- mode: "build",
- turn_index: 0,
- });
- });
- }
- await act(async () => view.unmount());
- const parked = canonicalRecoveriesByWorkflow.get("wpid_1");
- expect(parked).toMatchObject({
- resumed: true,
- baseline: saveData.workflow,
- preservedSettings: saveData.settings,
- poll: {
- chatId: "chat-1",
- turnId: turnStarted ? "turn-1" : null,
- requestId: expect.any(String),
- },
- rollback: { snapshot: { nodes: submittedSnapshot } },
- });
- const otherWorkflow = await renderChat({
- route,
- docked: true,
- workflowPermanentId: "wpid_other",
- });
- expect(
- useWorkflowYamlEditorStore.getState().copilotAcceptance,
- ).toBeNull();
- const saved = { current: saveData.workflow };
- finishOnServer(saved);
- await act(async () => {
- call.onMessage(proposalResponse("Buffered old response."));
- });
- expect(screen.queryByText("Buffered old response.")).toBeNull();
- otherWorkflow.unmount();
-
- const returnedWorkflow = await queryClient.fetchQuery({
- queryKey,
- queryFn: async () => saved.current,
- });
- expect(returnedWorkflow.workflow_id).toBe("wf_committed");
- let resolveRead!: (response: { data: WorkflowApiResponse }) => void;
- const read = new Promise<{ data: WorkflowApiResponse }>((resolve) => {
- resolveRead = resolve;
- });
- historyGet.mockImplementation((path: string) =>
- path === "/workflows/wpid_1"
- ? read
- : Promise.resolve(historyResponse),
- );
- vi.useFakeTimers();
- await renderChat({ route, docked: true });
- const owner =
- useWorkflowYamlEditorStore.getState().editorOwner ??
- createYamlCommitOwner("wpid_1");
- registerEditorOwner(owner);
- expect(beginSaveTransaction(owner)).toBe(false);
- expect(screen.getByRole("button", { name: "Retry" })).toBeTruthy();
- expect(screen.getByRole("button", { name: "Reject" })).toBeTruthy();
- await act(async () => resolveRead({ data: saved.current }));
- expect(screen.getByRole("alert")).toBeTruthy();
- expect(beginSaveTransaction(owner)).toBe(false);
- await advance(2_000);
- await discardRecoveryDraft();
- expect(screen.queryByRole("alert")).toBeNull();
- expect(beginSaveTransaction(owner)).toBe(true);
- const request = buildWorkflowSaveRequest({
- ...saveData,
- blocks: getWorkflowBlocks(editorNodes, []),
- });
- expect(request.workflow_definition.blocks).toEqual(
- saved.current.workflow_definition.blocks,
- );
- expect(
- editorNodes.find((node) => node.id === "loop"),
- ).toBeUndefined();
- finishSaveTransaction(owner);
- },
+ it("retains a timed-out resumed recovery until Retry resolves canonical state", async () => {
+ changesState.hasChanges = true;
+ const view = await renderChat({ route: "editor", docked: true });
+ await submit("edit the workflow");
+ const call = streamCalls[0]!;
+ historyGet.mockImplementation((path: string) =>
+ path === "/workflows/wpid_1"
+ ? Promise.reject(new Error("canonical unavailable"))
+ : Promise.resolve(historyResponse),
);
-
- it.each(["updated", "unchanged", "interrupted"] as const)(
- "resumes recovery after workflow navigation without losing local edits (%s canonical outcome)",
- async (outcome) => {
- changesState.hasChanges = true;
- saveData.workflow.workflow_definition = {
- blocks: [],
- parameters: [],
- };
- const { view, apply, saved } = await severStream();
- view.unmount();
- expect(
- useWorkflowYamlEditorStore.getState().copilotAcceptance,
- ).toBeNull();
- historyGet.mockClear();
- await advance(3_000);
- expect(historyGet).not.toHaveBeenCalled();
-
- vi.useRealTimers();
- const otherWorkflow = await renderChat({
- route,
- docked: true,
- workflowPermanentId: "wpid_other",
- });
- expect(
- useWorkflowYamlEditorStore.getState().copilotAcceptance,
- ).toBeNull();
- expect(historyGet).not.toHaveBeenCalledWith("/workflows/wpid_1");
- otherWorkflow.unmount();
- historyGet.mockClear();
- const revisitedApply = vi.fn();
- await renderChat({
- route,
- docked: true,
- onWorkflowUpdate: revisitedApply,
- });
- if (vi.isFakeTimers()) await advance(2_000);
- expect(
- useWorkflowYamlEditorStore.getState().copilotAcceptance,
- ).not.toBeNull();
- expect(
- useWorkflowYamlEditorStore.getState().copilotAcceptance,
- ).not.toBeNull();
- expect(revisitedApply).not.toHaveBeenCalled();
- act(editLoop);
- expect(
- editorNodes.find((node) => node.id === "loop")?.data,
- ).toMatchObject({
- loopValue: "unsaved_items",
- });
-
- const baseline = saved.current;
- finishOnServer(saved);
- if (outcome !== "updated") saved.current = baseline;
- if (outcome === "interrupted") {
- historyResponse.data.chat_history = [
- {
- sender: "ai",
- content: "Turn interrupted.",
- created_at: "2026-09-11T00:00:00Z",
- turn_outcome: {
- copilot_turn_id: "turn-1",
- terminal_reason: "interrupted",
- },
- },
- ];
- }
- if (outcome === "interrupted") {
- vi.useFakeTimers();
- await act(async () =>
- fireEvent.click(screen.getByRole("button", { name: "Retry" })),
- );
- await advance(120_000);
- expect(revisitedApply).not.toHaveBeenCalled();
- expect(
- useWorkflowYamlEditorStore.getState().copilotAcceptance,
- ).not.toBeNull();
- finishTurnHistory();
- await act(async () =>
- fireEvent.click(screen.getByRole("button", { name: "Retry" })),
- );
- expect(revisitedApply).not.toHaveBeenCalled();
- expect(
- useWorkflowYamlEditorStore.getState().copilotAcceptance,
- ).not.toBeNull();
- await advance(2_000);
- }
- if (outcome !== "interrupted") {
- vi.useFakeTimers();
- await act(async () => {
- fireEvent.click(screen.getByRole("button", { name: "Retry" }));
- await vi.advanceTimersByTimeAsync(2_000);
- });
- }
- expect(revisitedApply).not.toHaveBeenCalled();
- const generation =
- useWorkflowHasChangesStore.getState().saveGeneration;
- if (outcome === "updated") {
- expect(
- screen.getByRole("button", { name: "Keep my edits" }),
- ).toBeTruthy();
- await act(async () => {
- fireEvent.click(
- screen.getByRole("button", {
- name: "Apply and discard my edits",
- }),
- );
- await vi.advanceTimersByTimeAsync(2_000);
- });
- } else {
- expect(
- screen.queryByRole("button", { name: "Keep my edits" }),
- ).toBeNull();
- }
- if (outcome === "updated") {
- expect(revisitedApply).toHaveBeenCalledExactlyOnceWith(
- saved.current,
- expect.objectContaining({ persisted: true, applied: true }),
- );
- expect(
- editorNodes.find((node) => node.id === "loop"),
- ).toBeUndefined();
- } else {
- expect(revisitedApply).not.toHaveBeenCalled();
- expect(
- editorNodes.find((node) => node.id === "loop")?.data,
- ).toMatchObject({ loopValue: "unsaved_items" });
- expect(useWorkflowHasChangesStore.getState().saveGeneration).toBe(
- generation,
- );
- expect(toast).not.toHaveBeenCalledWith(
- expect.objectContaining({
- description: expect.stringContaining("saved on the server"),
- }),
- );
- }
- expect(apply).not.toHaveBeenCalled();
- expect(
- useWorkflowYamlEditorStore.getState().copilotAcceptance,
- ).toBeNull();
- },
+ vi.useFakeTimers();
+ await act(async () => call.reject(new Error("connection dropped")));
+ view.unmount();
+ const deadline =
+ canonicalRecoveriesByWorkflow.get("wpid_1")!.poll!.deadline;
+ const apply = vi.fn();
+ await renderChat({
+ route: "editor",
+ docked: true,
+ onWorkflowUpdate: apply,
+ });
+ const reservation =
+ useWorkflowYamlEditorStore.getState().copilotAcceptance;
+ expect(reservation).not.toBeNull();
+ await advance(Math.max(0, deadline - Date.now()));
+ expect(screen.getByRole("alert").textContent).toContain(
+ "Could not confirm whether Copilot saved changes",
+ );
+ expect(screen.getByRole("button", { name: "Retry" })).toBeTruthy();
+ expect(useWorkflowYamlEditorStore.getState().copilotAcceptance).toBe(
+ reservation,
+ );
+ expect(beginYamlCommit(createYamlCommitOwner("wpid_1"))).toBe(false);
+ historyGet.mockClear();
+ await advance(30_000);
+ expect(historyGet).not.toHaveBeenCalled();
+ const canonical = {
+ ...saveData.workflow,
+ workflow_id: "wf_saved",
+ version: 2,
+ };
+ historyGet.mockImplementation((path: string) =>
+ Promise.resolve(
+ path === "/workflows/wpid_1" ? { data: canonical } : historyResponse,
+ ),
+ );
+ finishTurnHistory();
+ await act(async () =>
+ fireEvent.click(screen.getByRole("button", { name: "Retry" })),
+ );
+ await advance(0);
+ await discardRecoveryDraft();
+ expect(apply).toHaveBeenCalledWith(
+ canonical,
+ expect.objectContaining({ persisted: true, applied: true }),
);
+ expect(screen.queryByRole("alert")).toBeNull();
+ expect(
+ useWorkflowYamlEditorStore.getState().copilotAcceptance,
+ ).toBeNull();
+ });
- it.each(["late commit", "budget", "save in progress"] as const)(
- "retains the pre-turn recovery reservation and deadline across unmount: %s",
- async (outcome) => {
- changesState.hasChanges = true;
- const { view, saved } = await severStream(false);
- const originalReservation =
- useWorkflowYamlEditorStore.getState().copilotAcceptance;
- view.unmount();
- const persisted = canonicalRecoveriesByWorkflow.get("wpid_1")!;
- expect(persisted.poll?.turnId).toBeNull();
- expect(persisted.poll?.requestId).toBeTruthy();
- const poll = { ...persisted.poll! };
- expect(
- useWorkflowYamlEditorStore.getState().copilotAcceptance,
- ).toBeNull();
- const owner =
- useWorkflowYamlEditorStore.getState().editorOwner ??
- createYamlCommitOwner("wpid_1");
- if (outcome === "save in progress") {
- registerEditorOwner(owner);
- expect(beginSaveTransaction(owner)).toBe(true);
- }
- const apply = vi.fn();
- const revisited = await renderChat({
- route,
- docked: true,
- onWorkflowUpdate: apply,
- });
- if (outcome === "save in progress") {
- expect(useWorkflowYamlEditorStore.getState().lockKind).toBe("save");
- await act(async () => finishSaveTransaction(owner));
- }
- const resumedReservation =
- useWorkflowYamlEditorStore.getState().copilotAcceptance;
- expect(resumedReservation).not.toBeNull();
- expect(resumedReservation).not.toBe(originalReservation);
- expect(beginYamlCommit(createYamlCommitOwner("wpid_1"))).toBe(false);
+ it.each([false, true])(
+ "retries canonical before turn_start while refusing edits and unrelated history (edit attempted=%s)",
+ async (edited) => {
+ changesState.hasChanges = true;
+ const { apply, saved } = await severStream(false);
+ historyGet.mockClear();
+ if (edited) {
act(editLoop);
expect(
editorNodes.find((node) => node.id === "loop")?.data,
).toMatchObject({
loopValue: "unsaved_items",
});
- revisited.unmount();
- expect(canonicalRecoveriesByWorkflow.get("wpid_1")?.poll).toEqual(
- poll,
- );
- await renderChat({ route, docked: true, onWorkflowUpdate: apply });
- if (outcome === "budget") {
- await advance(Math.max(0, poll.deadline - Date.now() - 1));
- expect(
- useWorkflowYamlEditorStore.getState().copilotAcceptance,
- ).not.toBeNull();
- await advance(1);
- expect(apply).not.toHaveBeenCalled();
- expect(
- useWorkflowYamlEditorStore.getState().copilotAcceptance,
- ).not.toBeNull();
- finishOnServer(saved);
- await act(async () =>
- fireEvent.click(screen.getByRole("button", { name: "Retry" })),
- );
- await advance(0);
- await discardRecoveryDraft();
- } else {
- finishOnServer(saved);
- await advance(2_000);
- await discardRecoveryDraft();
- expect(apply).toHaveBeenCalledExactlyOnceWith(
- saved.current,
- expect.objectContaining({ persisted: true, applied: true }),
- );
- }
- expect(
- useWorkflowYamlEditorStore.getState().copilotAcceptance,
- ).toBeNull();
- expect(screen.getByText("Saved the workflow.")).toBeTruthy();
- },
- );
-
- it("keeps resumed recovery locked when a finished turn's canonical read fails", async () => {
- changesState.hasChanges = true;
- const { view, saved } = await severStream();
- view.unmount();
- finishOnServer(saved);
- let readFails = true;
- historyGet.mockImplementation((path: string) =>
- path === "/workflows/wpid_1"
- ? readFails
- ? Promise.reject(new Error("canonical unavailable"))
- : Promise.resolve({ data: saved.current })
- : Promise.resolve(historyResponse),
- );
- const apply = vi.fn();
- await renderChat({ route, docked: true, onWorkflowUpdate: apply });
+ }
await advance(2_000);
+ expect(historyGet).toHaveBeenCalledWith(
+ "/workflow/copilot/chat-history",
+ expect.objectContaining({
+ params: expect.objectContaining({
+ request_cancel_token: streamCalls[0]!.body.cancel_token,
+ }),
+ }),
+ );
expect(apply).not.toHaveBeenCalled();
- expect(
- useWorkflowYamlEditorStore.getState().copilotAcceptance,
- ).not.toBeNull();
- expect(screen.getByRole("button", { name: "Retry" })).toBeTruthy();
- readFails = false;
+ finishOnServer(saved);
await advance(3_000);
- await discardRecoveryDraft();
expect(apply).toHaveBeenCalledExactlyOnceWith(
saved.current,
- expect.objectContaining({ persisted: true, applied: true }),
+ expect.objectContaining({
+ persisted: true,
+ applied: true,
+ }),
);
+ expect(screen.getByText("Saved the workflow.")).toBeTruthy();
expect(
- useWorkflowYamlEditorStore.getState().copilotAcceptance,
+ screen.queryByText(
+ "The connection dropped, so Copilot is checking whether this turn finished.",
+ ),
).toBeNull();
- });
-
- it("retains a timed-out resumed recovery until Retry resolves canonical state", async () => {
- changesState.hasChanges = true;
- const view = await renderChat({ route, docked: true });
- await submit("edit the workflow");
- const call = streamCalls[0]!;
- historyGet.mockImplementation((path: string) =>
- path === "/workflows/wpid_1"
- ? Promise.reject(new Error("canonical unavailable"))
- : Promise.resolve(historyResponse),
- );
- vi.useFakeTimers();
- await act(async () => call.reject(new Error("connection dropped")));
- view.unmount();
- const deadline =
- canonicalRecoveriesByWorkflow.get("wpid_1")!.poll!.deadline;
- const apply = vi.fn();
- await renderChat({ route, docked: true, onWorkflowUpdate: apply });
- const reservation =
- useWorkflowYamlEditorStore.getState().copilotAcceptance;
- expect(reservation).not.toBeNull();
- await advance(Math.max(0, deadline - Date.now()));
- expect(screen.getByRole("alert").textContent).toContain(
- "Could not confirm whether Copilot saved changes",
- );
- expect(screen.getByRole("button", { name: "Retry" })).toBeTruthy();
- expect(useWorkflowYamlEditorStore.getState().copilotAcceptance).toBe(
- reservation,
- );
- expect(beginYamlCommit(createYamlCommitOwner("wpid_1"))).toBe(false);
historyGet.mockClear();
await advance(30_000);
expect(historyGet).not.toHaveBeenCalled();
- const canonical = {
- ...saveData.workflow,
- workflow_id: "wf_saved",
- version: 2,
- };
- historyGet.mockImplementation((path: string) =>
- Promise.resolve(
- path === "/workflows/wpid_1"
- ? { data: canonical }
- : historyResponse,
- ),
- );
- finishTurnHistory();
- await act(async () =>
- fireEvent.click(screen.getByRole("button", { name: "Retry" })),
- );
- await advance(0);
- await discardRecoveryDraft();
- expect(apply).toHaveBeenCalledWith(
- canonical,
- expect.objectContaining({ persisted: true, applied: true }),
- );
- expect(screen.queryByRole("alert")).toBeNull();
- expect(
- useWorkflowYamlEditorStore.getState().copilotAcceptance,
- ).toBeNull();
- });
-
- it.each([false, true])(
- "retries canonical before turn_start while refusing edits and unrelated history (edit attempted=%s)",
- async (edited) => {
- changesState.hasChanges = true;
- const { apply, saved } = await severStream(false);
- historyGet.mockClear();
- if (edited) {
- act(editLoop);
- expect(
- editorNodes.find((node) => node.id === "loop")?.data,
- ).toMatchObject({
- loopValue: "unsaved_items",
- });
- }
- await advance(2_000);
- expect(historyGet).toHaveBeenCalledWith(
- "/workflow/copilot/chat-history",
- expect.objectContaining({
- params: expect.objectContaining({
- request_cancel_token: streamCalls[0]!.body.cancel_token,
- }),
- }),
- );
- expect(apply).not.toHaveBeenCalled();
- finishOnServer(saved);
- await advance(3_000);
- expect(apply).toHaveBeenCalledExactlyOnceWith(
- saved.current,
- expect.objectContaining({
- persisted: true,
- applied: true,
- }),
- );
- expect(screen.getByText("Saved the workflow.")).toBeTruthy();
- expect(
- screen.queryByText(
- "The connection dropped, so Copilot is checking whether this turn finished.",
- ),
- ).toBeNull();
- historyGet.mockClear();
- await advance(30_000);
- expect(historyGet).not.toHaveBeenCalled();
- },
- );
+ },
+ );
- it("bounds canonical retries without turn_start", async () => {
- changesState.hasChanges = true;
- const { apply } = await severStream(false);
- historyGet.mockClear();
- await advance(2_000);
- expect(historyGet).toHaveBeenCalledWith(
- "/workflow/copilot/chat-history",
- expect.objectContaining({
- params: expect.objectContaining({
- request_cancel_token: streamCalls[0]!.body.cancel_token,
- }),
+ it("bounds canonical retries without turn_start", async () => {
+ changesState.hasChanges = true;
+ const { apply } = await severStream(false);
+ historyGet.mockClear();
+ await advance(2_000);
+ expect(historyGet).toHaveBeenCalledWith(
+ "/workflow/copilot/chat-history",
+ expect.objectContaining({
+ params: expect.objectContaining({
+ request_cancel_token: streamCalls[0]!.body.cancel_token,
}),
- );
- await advance(1_500_000);
- const reads = historyGet.mock.calls.length;
- expect(reads).toBeGreaterThan(1);
- expect(reads).toBeLessThan(60);
- await advance(1_500_000);
- expect(historyGet).toHaveBeenCalledTimes(reads);
- expect(apply).not.toHaveBeenCalled();
- });
+ }),
+ );
+ await advance(1_500_000);
+ const reads = historyGet.mock.calls.length;
+ expect(reads).toBeGreaterThan(1);
+ expect(reads).toBeLessThan(60);
+ await advance(1_500_000);
+ expect(historyGet).toHaveBeenCalledTimes(reads);
+ expect(apply).not.toHaveBeenCalled();
+ });
- it("discards a canonical retry response after unmount before turn_start", async () => {
- changesState.hasChanges = true;
- const { view, apply, saved } = await severStream(false);
- finishOnServer(saved);
- let resolveRead!: (value: unknown) => void;
- historyGet.mockImplementation(
- () =>
- new Promise((resolve) => {
- resolveRead = resolve;
- }),
- );
- await advance(2_000);
- expect(resolveRead).toBeTypeOf("function");
- view.unmount();
- await act(async () => resolveRead({ data: saved.current }));
- expect(apply).not.toHaveBeenCalled();
- expect(
- useWorkflowYamlEditorStore.getState().copilotAcceptance,
- ).toBeNull();
- historyGet.mockClear();
- await advance(1_500_000);
- expect(historyGet).not.toHaveBeenCalled();
- });
- },
- );
+ it("discards a canonical retry response after unmount before turn_start", async () => {
+ changesState.hasChanges = true;
+ const { view, apply, saved } = await severStream(false);
+ finishOnServer(saved);
+ let resolveRead!: (value: unknown) => void;
+ historyGet.mockImplementation(
+ () =>
+ new Promise((resolve) => {
+ resolveRead = resolve;
+ }),
+ );
+ await advance(2_000);
+ expect(resolveRead).toBeTypeOf("function");
+ view.unmount();
+ await act(async () => resolveRead({ data: saved.current }));
+ expect(apply).not.toHaveBeenCalled();
+ expect(
+ useWorkflowYamlEditorStore.getState().copilotAcceptance,
+ ).toBeNull();
+ historyGet.mockClear();
+ await advance(1_500_000);
+ expect(historyGet).not.toHaveBeenCalled();
+ });
+ });
it("retains request-id recovery through an uncorrelated canonical advance before turn_start", async () => {
changesState.hasChanges = true;
@@ -13217,62 +13197,6 @@ describe("WorkflowCopilotChat — g2 review gate", () => {
expect(useWorkflowYamlEditorStore.getState().copilotAcceptance).toBeNull();
});
- it.each(["server", "missing-chat", "failed-server"])(
- "restores headers on manual Accept through %s",
- async (mode) => {
- changesState.hasChanges = true;
- saveData.settings.cdpConnectHeaders = '{"Authorization":"accept-cdp"}';
- saveData.settings.extraHttpHeaders = '{"X-Token":"accept-extra"}';
- const snapshot = structuredClone(saveData.settings);
- let editorSettings = snapshot;
- await renderChat({
- onWorkflowUpdate: (workflow, options) => {
- editorSettings = options?.settings ?? apiWorkflowToSettings(workflow);
- saveData.settings = editorSettings;
- changesState.setHasChanges(!options?.persisted);
- },
- });
- await submit("edit the workflow");
- await act(async () => {
- streamCalls[0]!.onMessage({
- type: "turn_start",
- turn_id: "turn-1",
- mode: "build",
- turn_index: 0,
- });
- streamCalls[0]!.onMessage(
- proposalResponse("Draft ready.", {
- workflow_copilot_chat_id: mode === "missing-chat" ? "" : "chat-1",
- }),
- );
- streamCalls[0]!.resolve();
- });
- if (mode === "missing-chat") {
- historyResponse.data.workflow_copilot_chat_id = null;
- } else if (mode === "failed-server") {
- cancelPost.mockRejectedValueOnce({ response: { status: 422 } });
- } else {
- cancelPost.mockResolvedValueOnce({
- data: proposedWorkflowPayload({
- extra_http_headers: null,
- cdp_connect_headers: { Authorization: "***" },
- }),
- });
- }
- await act(async () =>
- fireEvent.click(screen.getByRole("button", { name: "Accept" })),
- );
- expect(editorSettings).toMatchObject({
- cdpConnectHeaders: snapshot.cdpConnectHeaders,
- extraHttpHeaders: snapshot.extraHttpHeaders,
- totpIdentifier: snapshot.totpIdentifier,
- totpVerificationUrl: snapshot.totpVerificationUrl,
- });
- if (mode === "success")
- expect(changesState.setHasChanges).toHaveBeenLastCalledWith(true);
- },
- );
-
it.each(["unresolved chat", "HTTP rejection"])(
"keeps a failed local Accept reserved after %s until Retry applies it",
async (mode) => {
@@ -13302,66 +13226,6 @@ describe("WorkflowCopilotChat — g2 review gate", () => {
},
);
- it("A42 enables later questions when the answer POST settles after recovery", async () => {
- changesState.hasChanges = true;
- changesState.hasChanges = false;
- let loadHistory!: (value: unknown) => void;
- historyGet.mockImplementationOnce(
- () =>
- new Promise((resolve) => {
- loadHistory = resolve;
- }),
- );
- await renderChat();
- vi.useFakeTimers();
- await act(async () => loadHistory({ data: pausedHistory() }));
- let finishAnswer!: (value: unknown) => void;
- cancelPost.mockImplementationOnce(
- () =>
- new Promise((resolve) => {
- finishAnswer = resolve;
- }),
- );
- await act(async () =>
- fireEvent.click(screen.getByRole("button", { name: "Skip" })),
- );
- const canonical = {
- ...saveData.workflow,
- ...proposedWorkflowPayload({ workflow_id: "wf_resumed" }),
- };
- historyGet.mockImplementation((path: string) =>
- Promise.resolve({
- data: path === "/workflows/wpid_1" ? canonical : completedHistory(),
- }),
- );
- await act(async () => vi.advanceTimersByTimeAsync(2_000));
- expect(useWorkflowYamlEditorStore.getState().copilotAcceptance).toBeNull();
- await act(async () =>
- finishAnswer({ data: { ...recoveredQuestion(), status: "resolved" } }),
- );
- vi.useRealTimers();
- await submit("continue");
- await act(async () =>
- streamCalls[0]!.onMessage({
- type: "question_required",
- turn_id: "turn-next",
- workflow_copilot_chat_id: "chat-1",
- cancel_token: "next-token",
- interactions: [
- {
- ...recoveredQuestion(),
- interaction_id: "question-next",
- turn_id: "turn-next",
- },
- ],
- }),
- );
- expect(
- (screen.getByRole("button", { name: "Skip" }) as HTMLButtonElement)
- .disabled,
- ).toBe(false);
- });
-
it.each(["question", "credential"])(
"A42 recovery Reject sends the original %s cancellation token and chat",
async (kind) => {
@@ -13400,295 +13264,6 @@ describe("WorkflowCopilotChat — g2 review gate", () => {
},
);
- it.each(
- [
- "question",
- "credential",
- "external question",
- "external credential",
- ].flatMap((path) =>
- ["Keep my edits", "Apply and discard my edits"].map((choice) => [
- path,
- choice,
- ]),
- ),
- )(
- "A42 protects local inputs before claiming delayed %s history: %s",
- async (path, choice) => {
- changesState.hasChanges = true;
- changesState.hasChanges = false;
- let historyLoaded!: (value: unknown) => void;
- historyGet.mockImplementationOnce(
- () =>
- new Promise((resolve) => {
- historyLoaded = resolve;
- }),
- );
- const apply = vi.fn(() =>
- useWorkflowParametersStore.getState().setParameters([]),
- );
- const owner = createYamlCommitOwner("wpid_1");
- registerEditorOwner(owner);
- await renderChat({ onWorkflowUpdate: apply });
- const input = {
- key: "local_input",
- parameterType: "context" as const,
- sourceParameterKey: "source",
- };
- useWorkflowParametersStore.getState().setParameters([input]);
- useWorkflowTitleStore.getState().setTitle("Local title");
- useWorkflowYamlEditorStore.getState().open("title: Baseline");
- useWorkflowYamlEditorStore.getState().setDraft("title: Local YAML");
- changesState.hasChanges = true;
- vi.useFakeTimers();
- await act(async () =>
- historyLoaded({
- data: pausedHistory(
- path?.includes("credential") ? "credential" : "question",
- ),
- }),
- );
- if (!path?.startsWith("external")) {
- cancelPost.mockResolvedValueOnce({
- data: { ...recoveredQuestion(), status: "resolved" },
- });
- await act(async () =>
- fireEvent.click(
- screen.getByRole("button", {
- name: path === "credential" ? "Skip for now" : "Skip",
- }),
- ),
- );
- }
- const canonical = {
- ...saveData.workflow,
- ...proposedWorkflowPayload({
- workflow_id: "wf_resumed",
- title: "New Workflow",
- workflow_definition: { parameters: [], blocks: [] },
- }),
- };
- historyGet.mockImplementation((path: string) =>
- Promise.resolve({
- data: path === "/workflows/wpid_1" ? canonical : completedHistory(),
- }),
- );
- await act(async () => vi.advanceTimersByTimeAsync(2_000));
- expect(apply).not.toHaveBeenCalled();
- expect(useWorkflowParametersStore.getState().parameters).toEqual([input]);
- expect(useWorkflowTitleStore.getState().title).toBe("Local title");
- expect(useWorkflowYamlEditorStore.getState().draft).toBe(
- "title: Local YAML",
- );
- expect(beginSaveTransaction(owner)).toBe(false);
- await act(async () => {
- fireEvent.click(screen.getByRole("button", { name: choice }));
- await vi.advanceTimersByTimeAsync(0);
- });
- expect(
- useWorkflowYamlEditorStore.getState().copilotAcceptance,
- ).toBeNull();
- if (choice === "Keep my edits") {
- expect(apply).not.toHaveBeenCalled();
- expect(useWorkflowParametersStore.getState().parameters).toEqual([
- input,
- ]);
- expect(useWorkflowTitleStore.getState().title).toBe("Local title");
- expect(useWorkflowYamlEditorStore.getState().draft).toBe(
- "title: Local YAML",
- );
- } else {
- expect(apply).toHaveBeenCalledWith(
- canonical,
- expect.objectContaining({ persisted: true }),
- );
- expect(useWorkflowParametersStore.getState().parameters).toEqual([]);
- expect(useWorkflowTitleStore.getState().title).toBe(canonical.title);
- const yaml = useWorkflowYamlEditorStore.getState();
- expect(parse(yaml.draft)).toMatchObject({ title: canonical.title });
- expect(yaml.entrySnapshot).toBe(yaml.draft);
- expect(yaml.stale).toBe(false);
- }
- },
- );
-
- it.each(["canonical", "proposal"])(
- "A42 retains uncertain Accept only while the %s read fails, then Retry settles",
- async (failedRead) => {
- changesState.hasChanges = true;
- const canonical = {
- ...saveData.workflow,
- ...proposedWorkflowPayload({ workflow_id: "wf_accepted", version: 2 }),
- };
- historyResponse.data.proposed_workflow = canonical;
- const apply = vi.fn();
- await renderChat({ onWorkflowUpdate: apply });
- const accept = await screen.findByRole(
- "button",
- { name: "Accept" },
- { timeout: 10_000 },
- );
- const owner = createYamlCommitOwner("wpid_1");
- registerEditorOwner(owner);
- cancelPost.mockRejectedValueOnce(new Error("Accept response lost"));
- historyGet.mockImplementation((path: string) => {
- if ((path === "/workflows/wpid_1") === (failedRead === "canonical"))
- return Promise.reject(new Error("read unavailable"));
- return Promise.resolve(
- path === "/workflows/wpid_1" ? { data: canonical } : historyResponse,
- );
- });
- vi.useFakeTimers();
- await act(async () => fireEvent.click(accept));
- await act(async () => vi.advanceTimersByTimeAsync(1_500_000));
- expect(apply).not.toHaveBeenCalled();
- expect(beginSaveTransaction(owner)).toBe(false);
- expect(screen.getByRole("button", { name: "Reload" })).toBeTruthy();
- await act(async () => {
- fireEvent.click(
- within(
- screen.getByText(/Could not confirm whether Copilot saved changes/)
- .parentElement!,
- ).getByRole("button", { name: "Retry" }),
- );
- await vi.advanceTimersByTimeAsync(0);
- });
- expect(cancelPost).toHaveBeenCalledTimes(1);
- expect(beginSaveTransaction(owner)).toBe(false);
- historyResponse.data.proposed_workflow = null;
- historyGet.mockImplementation((path: string) =>
- Promise.resolve(
- path === "/workflows/wpid_1" ? { data: canonical } : historyResponse,
- ),
- );
- await act(async () => {
- fireEvent.click(screen.getByRole("button", { name: "Retry" }));
- await vi.advanceTimersByTimeAsync(0);
- });
- expect(apply).toHaveBeenCalledExactlyOnceWith(
- canonical,
- expect.objectContaining({ persisted: true }),
- );
- expect(cancelPost).toHaveBeenCalledTimes(1);
- expect(
- useWorkflowYamlEditorStore.getState().copilotAcceptance,
- ).toBeNull();
- expect(beginSaveTransaction(owner)).toBe(true);
- },
- );
-
- it.each([
- "interrupted commit",
- "legacy commit",
- "legacy unchanged",
- "500 unchanged",
- "cleared unchanged",
- "pending newer commit",
- ])(
- "A42 settles uncertain Accept only from a recorded outcome: %s",
- async (outcome) => {
- changesState.hasChanges = true;
- const baseline = {
- ...saveData.workflow,
- version: 1,
- modified_at: "2026-09-01T00:00:00Z",
- };
- saveData.workflow = baseline;
- const canonical = {
- ...baseline,
- ...proposedWorkflowPayload({ workflow_id: "wf_accepted" }),
- version: 2,
- modified_at: "2026-09-02T00:00:00Z",
- };
- historyResponse.data.proposed_workflow = canonical;
- if (!outcome.startsWith("legacy")) {
- historyResponse.data.proposed_workflow_metadata = {
- owner_turn_id: "turn-recovered",
- revision: 1,
- canonical_fingerprint: "baseline",
- disposition: "review_untested",
- workflow_run_id: null,
- };
- historyResponse.data.chat_history = pausedHistory().chat_history;
- }
- const apply = vi.fn();
- await renderChat({ onWorkflowUpdate: apply });
- const accept = await screen.findByRole(
- "button",
- { name: "Accept" },
- { timeout: 10_000 },
- );
- const owner = createYamlCommitOwner("wpid_1");
- registerEditorOwner(owner);
- cancelPost.mockRejectedValueOnce(
- Object.assign(new Error("accept failed"), {
- response: { status: 500 },
- }),
- );
- const committed =
- outcome.endsWith("commit") || outcome === "cleared unchanged";
- const saved = outcome === "cleared unchanged" ? baseline : canonical;
- const accepted = outcome === "interrupted commit";
- if (accepted) historyResponse.data.accepted_turn_ids = ["turn-recovered"];
- historyGet.mockImplementation((path: string) =>
- Promise.resolve(
- path === "/workflows/wpid_1"
- ? { data: committed ? saved : baseline }
- : historyResponse,
- ),
- );
- historyGet.mockClear();
- vi.useFakeTimers();
- await act(async () => fireEvent.click(accept));
- expect(apply).not.toHaveBeenCalled();
- expect(historyGet).not.toHaveBeenCalled();
- expect(beginSaveTransaction(owner)).toBe(false);
- if (committed && outcome !== "pending newer commit")
- historyResponse.data.proposed_workflow = null;
- await act(async () => vi.advanceTimersByTimeAsync(2_000));
- if (!accepted) {
- expect(
- screen.queryByText("Accepted and saved to the workflow"),
- ).toBeNull();
- if (!committed || outcome === "pending newer commit") {
- expect(historyGet.mock.calls.map(([path]) => path)).toEqual([
- "/workflow/copilot/chat-history",
- ]);
- expect(apply).not.toHaveBeenCalled();
- expect(beginSaveTransaction(owner)).toBe(false);
- expect(screen.getByRole("button", { name: "Retry" })).toBeTruthy();
- }
- return;
- }
- expect(historyGet.mock.calls.map(([path]) => path)).toEqual([
- "/workflow/copilot/chat-history",
- "/workflows/wpid_1",
- ]);
- expect(historyGet.mock.calls[0]?.[1]?.params).toEqual({
- workflow_copilot_chat_id: "chat-1",
- });
- if (committed)
- expect(apply).toHaveBeenCalledWith(
- saved,
- expect.objectContaining({ persisted: true }),
- );
- else {
- expect(apply).not.toHaveBeenCalled();
- expect(toast).toHaveBeenCalledWith(
- expect.objectContaining({
- title: "Accept failed",
- variant: "destructive",
- }),
- );
- expect(screen.getByRole("button", { name: "Accept" })).toBeTruthy();
- }
- expect(
- useWorkflowYamlEditorStore.getState().copilotAcceptance,
- ).toBeNull();
- expect(beginSaveTransaction(owner)).toBe(true);
- },
- );
-
it.each(["legacy", "metadata"])(
"releases a %s proposal with local edits after Accept returns 400",
async (kind) => {
@@ -14463,11 +14038,7 @@ describe("A46 Accept recovery", () => {
it.each([
[409, "Workflow changed after this proposal", true],
- [409, "Copilot proposal changed; reload required", true],
- [409, "Copilot proposal metadata is invalid; reload required", true],
[400, "No proposed workflow to apply", true],
- [400, "Proposed workflow has no copilot YAML to apply", true],
- [400, "Proposed copilot YAML is invalid: invalid value", true],
[404, "Chat not found", true],
[409, "Copilot proposal is already being accepted", false],
[500, "Workflow changed after this proposal", false],
@@ -16128,8 +15699,6 @@ describe("editor-state rollback lifecycle", () => {
it.each([
{ titleFrameReceived: true, definitionCommitted: false },
- { titleFrameReceived: false, definitionCommitted: false },
- { titleFrameReceived: true, definitionCommitted: true },
{ titleFrameReceived: false, definitionCommitted: true },
])(
"reconciles a terminal title-only canonical advance without losing the snapshot (title frame=$titleFrameReceived, definition committed=$definitionCommitted)",
diff --git a/skyvern-frontend/src/routes/workflows/editor/WorkflowEditor.test.tsx b/skyvern-frontend/src/routes/workflows/editor/WorkflowEditor.test.tsx
index 9d784c45f..08b8e0104 100644
--- a/skyvern-frontend/src/routes/workflows/editor/WorkflowEditor.test.tsx
+++ b/skyvern-frontend/src/routes/workflows/editor/WorkflowEditor.test.tsx
@@ -4465,14 +4465,10 @@ describe("A49 metadata authorship through editor actions", () => {
});
}
- test.each(
- [false, true].flatMap((recover) =>
- ["Keep my edits", "Apply and discard my edits"].map((choice) => ({
- recover,
- choice,
- })),
- ),
- )(
+ test.each([
+ { recover: false, choice: "Keep my edits" },
+ { recover: true, choice: "Apply and discard my edits" },
+ ])(
"A53 model input after a proposal uses $choice (recovery: $recover)",
async ({ recover, choice }) => {
integration.canvas = true;
@@ -5388,7 +5384,7 @@ describe("A49 metadata authorship through editor actions", () => {
},
);
- test.each(["", "not-a-url", "http://", "://missing-scheme", "http://[::1"])(
+ test.each(["", "http://", "http://[::1"])(
"YAML-to-Visual rejects a custom proxy URL without a host (%j)",
async (url) => {
mountEditor();
@@ -5421,13 +5417,10 @@ describe("A49 metadata authorship through editor actions", () => {
test.each([
"http://user:[email protected]:8080",
- "http://proxy.example.com:8080",
"socks5://u:[email protected]:1080",
"http://user:p%40ss%[email protected]:8080",
"//proxy.example.com:8080",
"http://[2001:db8::1]:3128",
- "http://[::1]:8080",
- "http://[::1]",
])(
"YAML-to-Visual commits a custom proxy URL with a host and withholds it from Copilot (%s)",
async (url) => {
diff --git a/skyvern-frontend/src/routes/workflows/editor/sortable/perf.test.ts b/skyvern-frontend/src/routes/workflows/editor/sortable/perf.test.ts
index d27495203..68da86a5a 100644
--- a/skyvern-frontend/src/routes/workflows/editor/sortable/perf.test.ts
+++ b/skyvern-frontend/src/routes/workflows/editor/sortable/perf.test.ts
@@ -1,5 +1,4 @@
import { describe, expect, test } from "vitest";
-import type { Edge } from "@xyflow/react";
import { ProxyLocation } from "@/api/types";
@@ -148,21 +147,6 @@ function withMeasured(nodes: Array<AppNode>): Array<AppNode> {
}));
}
-function buildMeasuredLayoutFixture(blockCount: number): {
- nodes: Array<AppNode>;
- edges: Array<Edge>;
-} {
- const { nodes, edges } = getElements(
- buildFlatFixture(blockCount),
- DEFAULT_SETTINGS,
- true,
- );
- return {
- nodes: withMeasured(nodes),
- edges,
- };
-}
-
function median(samples: Array<number>): number {
const sorted = [...samples].sort((a, b) => a - b);
const mid = Math.floor(sorted.length / 2);
@@ -190,30 +174,6 @@ function reportBench(label: string, samples: Array<number>): void {
);
}
-function sampleLayoutMedian({
- label,
- nodes,
- edges,
- sampleCount = 5,
-}: {
- label: string;
- nodes: Array<AppNode>;
- edges: Array<Edge>;
- sampleCount?: number;
-}): number {
- for (let i = 0; i < 2; i++) layout(nodes, edges);
-
- const samples: Array<number> = [];
- for (let i = 0; i < sampleCount; i++) {
- const start = performance.now();
- layout(nodes, edges);
- samples.push(performance.now() - start);
- }
-
- reportBench(label, samples);
- return median(samples);
-}
-
describe("SKY-9065 perf benchmarks (50+ block workflow)", () => {
test("layout() on a 50-block flat fixture stays under the 100ms AC budget", () => {
const blocks = buildFlatFixture(50);
@@ -289,49 +249,6 @@ describe("SKY-9065 perf benchmarks (50+ block workflow)", () => {
}
});
- test("layout() scales through 1000 blocks without explosive growth", () => {
- const oneHundred = buildMeasuredLayoutFixture(100);
- const twoHundred = buildMeasuredLayoutFixture(200);
- const fiveHundred = buildMeasuredLayoutFixture(500);
- const oneThousand = buildMeasuredLayoutFixture(1000);
-
- const oneHundredMed = sampleLayoutMedian({
- label: "layout(100 blocks) [large scaling test]",
- ...oneHundred,
- });
- const twoHundredMed = sampleLayoutMedian({
- label: "layout(200 blocks) [large scaling test]",
- ...twoHundred,
- });
- const fiveHundredMed = sampleLayoutMedian({
- label: "layout(500 blocks) [large scaling test]",
- ...fiveHundred,
- });
- const oneThousandMed = sampleLayoutMedian({
- label: "layout(1000 blocks) [large scaling test]",
- ...oneThousand,
- });
-
- expect(Number.isFinite(oneHundredMed)).toBe(true);
- expect(Number.isFinite(twoHundredMed)).toBe(true);
- expect(Number.isFinite(fiveHundredMed)).toBe(true);
- expect(Number.isFinite(oneThousandMed)).toBe(true);
-
- // Large-N runs are intentionally ratio-gated rather than hard
- // wall-clock-gated: shared CI hosts vary too much for stable ms
- // budgets, but a sudden order-of-magnitude jump still catches the
- // "massive workflow" regression this benchmark exists to prevent.
- if (oneHundredMed > 0) {
- expect(twoHundredMed / oneHundredMed).toBeLessThan(8);
- }
- if (twoHundredMed > 0) {
- expect(fiveHundredMed / twoHundredMed).toBeLessThan(12);
- }
- if (fiveHundredMed > 0) {
- expect(oneThousandMed / fiveHundredMed).toBeLessThan(8);
- }
- }, 30_000);
-
test("scope walking + drop classification on 50 blocks runs well under one frame", () => {
const blocks = buildFlatFixture(50);
const { nodes: rawNodes, edges } = getElements(
diff --git a/skyvern-frontend/src/routes/workflows/hooks/useWorkflowRunQuery.test.tsx b/skyvern-frontend/src/routes/workflows/hooks/useWorkflowRunQuery.test.tsx
index e256e0d76..99d25a25c 100644
--- a/skyvern-frontend/src/routes/workflows/hooks/useWorkflowRunQuery.test.tsx
+++ b/skyvern-frontend/src/routes/workflows/hooks/useWorkflowRunQuery.test.tsx
@@ -63,7 +63,9 @@ async function outageAcrossFailedPolls(
polls: number,
): Promise<{ gaps: number[]; intervals: Array<number | false> }> {
const client = new QueryClient({
- defaultOptions: { queries: { retry: retryTransientNetworkFailures } },
+ defaultOptions: {
+ queries: { retry: retryTransientNetworkFailures, retryDelay: 0 },
+ },
});
let succeed = true;
const observer = new QueryObserver(client, {
diff --git a/skyvern/config.py b/skyvern/config.py
index 104c86347..3766b09d8 100644
--- a/skyvern/config.py
+++ b/skyvern/config.py
@@ -494,7 +494,8 @@ class Settings(BaseSettings):
BITWARDEN_TIMEOUT_SECONDS: int = 60
# A cold `bw login` downloads and decrypts the whole vault, so it is categorically slower than the
# reads behind it and needs its own budget. Runs arriving as a batch each start on their own pod and
- # pay that login concurrently, which pushes it well past a budget sized for a read.
+ # pay that login concurrently, which pushes it well past a budget sized for a read. The unlock that
+ # follows an API-key login gets the same budget.
BITWARDEN_LOGIN_TIMEOUT_SECONDS: int = 180
BITWARDEN_MAX_RETRIES: int = 3
BITWARDEN_MAX_JITTER_SECONDS: float = 2.0
diff --git a/skyvern/forge/agent.py b/skyvern/forge/agent.py
index 381d107cc..ce83a4700 100644
--- a/skyvern/forge/agent.py
+++ b/skyvern/forge/agent.py
@@ -3964,6 +3964,11 @@ class ForgeAgent:
# than an inference from the task row, which cannot distinguish it from the unconditional
# handlers that clean up on an already-final row too.
cleanup_skipped_by_handler = False
+ # Set before the browser is acquired so a download the task's first navigation starts is covered too.
+ download_timeout_context = context
+ prev_download_timeout = download_timeout_context.download_timeout
+ if engine == RunEngine.skyvern_v3:
+ download_timeout_context.download_timeout = task.download_timeout
try:
if download_baseline_files is None and task.workflow_run_id:
list_files_before = list_files_in_directory(
@@ -4757,6 +4762,7 @@ class ForgeAgent:
context.task_id = None
context.navigation_goal = None
context.navigation_payload = None
+ download_timeout_context.download_timeout = prev_download_timeout
@staticmethod
def _latest_download_failure_status(steps: list[Step]) -> int | None:
diff --git a/skyvern/forge/sdk/core/skyvern_context.py b/skyvern/forge/sdk/core/skyvern_context.py
index fab5f9a2d..4ba06039b 100644
--- a/skyvern/forge/sdk/core/skyvern_context.py
+++ b/skyvern/forge/sdk/core/skyvern_context.py
@@ -711,6 +711,9 @@ class SkyvernContext:
navigation_payload: dict[str, Any] | list | str | None = None
complete_criterion_is_untrusted: bool = False
download_suffix: str | None = None
+ # Explicit download_timeout of the Task V3 block or task now running; the browser download listener
+ # reads it when a download starts, so it also covers the initial navigation and a relaunched browser.
+ download_timeout: float | None = None
# Keep source names with exact CDP targets; finalization must not infer provenance from affixes.
download_suffix_applied_files: dict[str, tuple[str, str]] = field(default_factory=dict, repr=False)
totp_codes: dict[str, str | None] = field(default_factory=dict)
diff --git a/skyvern/forge/sdk/services/bitwarden.py b/skyvern/forge/sdk/services/bitwarden.py
index b2dffdafc..587f07647 100644
--- a/skyvern/forge/sdk/services/bitwarden.py
+++ b/skyvern/forge/sdk/services/bitwarden.py
@@ -69,9 +69,11 @@ def _login_timeout_seconds(timeout: int) -> int:
return max(timeout, settings.BITWARDEN_LOGIN_TIMEOUT_SECONDS)
-def _attempt_deadline_seconds(timeout: int) -> int:
- """One attempt is a login plus the reads behind it, so it gets both budgets rather than twice one."""
- return _login_timeout_seconds(timeout) + timeout
+def _attempt_deadline_seconds(timeout: int, identity: "_VaultIdentity") -> int:
+ """One attempt is a cold session plus the reads behind it. An API-key session pays a cold unlock on
+ top of its login, so it gets a second cold budget; an email login prints a key it can unlock with."""
+ cold = _login_timeout_seconds(timeout)
+ return cold + timeout if identity.uses_email_auth else 2 * cold + timeout
# The CLI keeps its login state, tokens and encrypted vault copy in one data directory. Pointing each
@@ -814,8 +816,11 @@ class BitwardenService:
if identity.uses_email_auth and trust_login_key and login_key:
session.session_key = login_key
else:
+ # Under a batch the cold unlock after an API-key login runs as long as the login itself, so it
+ # gets the login's budget. An email fallback unlock keeps the read budget.
+ unlock_timeout = timeout if identity.uses_email_auth else login_timeout or timeout
session.session_key = await BitwardenService.unlock(
- identity.master_password, timeout=timeout, appdata_dir=session.appdata_dir
+ identity.master_password, timeout=unlock_timeout, appdata_dir=session.appdata_dir
)
if verify_sync:
# The sync inside `bw login` swallows its own failure; `bw sync` reports one.
@@ -1147,12 +1152,15 @@ class BitwardenService:
await BitwardenService._apply_jitter()
login_timeout = _login_timeout_seconds(timeout)
+ attempt_deadline = _attempt_deadline_seconds(
+ timeout, _VaultIdentity.resolve(client_id, client_secret, email, master_password)
+ )
for attempt in range(max_retries):
try:
- # A cold login gets `login_timeout` and every other CLI command gets `timeout`; the attempt
- # as a whole gets both, so one slow step cannot consume the other's budget and a dead vault
- # still fails in bounded time.
- async with asyncio.timeout(_attempt_deadline_seconds(timeout)):
+ # A cold login (and an API-key unlock) gets `login_timeout` and every other CLI command gets
+ # `timeout`; the attempt as a whole gets all of them, so one slow step cannot consume
+ # another's budget and a dead vault still fails in bounded time.
+ async with asyncio.timeout(attempt_deadline):
return await BitwardenService._get_secret_value_from_url(
client_id=client_id,
client_secret=client_secret,
@@ -1356,7 +1364,8 @@ class BitwardenService:
if not fail_reasons:
await BitwardenService._apply_jitter()
try:
- async with asyncio.timeout(_attempt_deadline_seconds(timeout)):
+ vault_identity = _VaultIdentity.resolve(client_id, client_secret, email, master_password)
+ async with asyncio.timeout(_attempt_deadline_seconds(timeout, vault_identity)):
return await BitwardenService._get_sensitive_information_from_identity(
client_id=client_id,
client_secret=client_secret,
@@ -1672,7 +1681,9 @@ class BitwardenService:
if not fail_reasons:
await BitwardenService._apply_jitter()
try:
- async with asyncio.timeout(_attempt_deadline_seconds(settings.BITWARDEN_TIMEOUT_SECONDS)):
+ timeout = settings.BITWARDEN_TIMEOUT_SECONDS
+ vault_identity = _VaultIdentity.resolve(client_id, client_secret, email, master_password)
+ async with asyncio.timeout(_attempt_deadline_seconds(timeout, vault_identity)):
return await BitwardenService._get_credit_card_data(
client_id=client_id,
client_secret=client_secret,
@@ -1682,7 +1693,8 @@ class BitwardenService:
collection_id=collection_id,
item_id=item_id,
email=email,
- login_timeout=_login_timeout_seconds(settings.BITWARDEN_TIMEOUT_SECONDS),
+ timeout=timeout,
+ login_timeout=_login_timeout_seconds(timeout),
)
except BitwardenAccessDeniedError as e:
raise e
diff --git a/skyvern/forge/sdk/workflow/models/block.py b/skyvern/forge/sdk/workflow/models/block.py
index d95ae7719..f08812609 100644
--- a/skyvern/forge/sdk/workflow/models/block.py
+++ b/skyvern/forge/sdk/workflow/models/block.py
@@ -1763,9 +1763,18 @@ class Block(BaseModel, abc.ABC):
self._output_recorded_this_execution = False
workflow_run_block_id = None
engine: RunEngine | None = None
+ # Scoped to the whole block so a download its own navigation starts is covered, not just its task loop.
+ download_timeout_context = skyvern_context.current()
+ prev_download_timeout = download_timeout_context.download_timeout if download_timeout_context else None
try:
if isinstance(self, BaseTaskBlock):
engine = self.resolve_engine(workflow_run_id)
+ if (
+ engine == RunEngine.skyvern_v3
+ and download_timeout_context is not None
+ and not download_timeout_context.script_mode
+ ):
+ download_timeout_context.download_timeout = self.download_timeout
workflow_run_block = await app.DATABASE.observer.create_workflow_run_block(
workflow_run_id=workflow_run_id,
@@ -1944,6 +1953,9 @@ class Block(BaseModel, abc.ABC):
organization_id=organization_id,
error_codes=error_codes or None,
)
+ finally:
+ if download_timeout_context is not None:
+ download_timeout_context.download_timeout = prev_download_timeout
@abc.abstractmethod
def get_all_parameters(
diff --git a/skyvern/forge/taskv3/auth_tools.py b/skyvern/forge/taskv3/auth_tools.py
index f49d03f63..13db118a4 100644
--- a/skyvern/forge/taskv3/auth_tools.py
+++ b/skyvern/forge/taskv3/auth_tools.py
@@ -171,10 +171,11 @@ def _time_left(remaining_seconds: float) -> str:
return f"about {remaining_seconds / 60.0:.1f} minutes of polling time remain"
-def _code_not_yet(remaining_seconds: float) -> str:
+def _code_not_yet(remaining_seconds: float, webhook_answers: str | None = None) -> str:
if _budget_spent(remaining_seconds):
- return _CODE_BUDGET_SPENT
- return f"no verification code has arrived yet; {_time_left(remaining_seconds)}."
+ return f"{_CODE_BUDGET_SPENT} It answered: {webhook_answers}." if webhook_answers else _CODE_BUDGET_SPENT
+ answers = f" ({webhook_answers})" if webhook_answers else ""
+ return f"no verification code has arrived yet{answers}; {_time_left(remaining_seconds)}."
def _code_source_error(detail: str, remaining_seconds: float) -> str:
@@ -638,7 +639,9 @@ def build_auth_tools(
state.arm(reason, tool)
return ToolResult.error(message, data=data)
- def _not_yet(expected_otp_type: OTPType, detail: str, elapsed_seconds: float, *, errored: bool) -> ToolResult:
+ def _not_yet(
+ expected_otp_type: OTPType, detail: str, elapsed_seconds: float, *, webhook_answers: str | None
+ ) -> ToolResult:
"""A slice that timed out with nothing to hand over. `elapsed_seconds` is this slice's wait, which
the caller's `finally` has not yet added to the running spend."""
spent = state.polling_spent_seconds + elapsed_seconds
@@ -656,8 +659,10 @@ def build_auth_tools(
)
spent_out = _budget_spent(remaining)
if expected_otp_type == OTPType.TOTP:
- text = _code_source_error(detail, remaining) if errored else _code_not_yet(remaining)
- return _code_answer(text, arm=VerificationFailure.BUDGET_EXHAUSTED if spent_out else None)
+ return _code_answer(
+ _code_not_yet(remaining, webhook_answers),
+ arm=VerificationFailure.BUDGET_EXHAUSTED if spent_out else None,
+ )
state.awaiting_link_since = state.link_wait_since = time.monotonic()
if spent_out:
return _failed(
@@ -753,7 +758,7 @@ def build_auth_tools(
empty_answer_streak = 0
if exc.webhook_diagnostics:
detail = f"{detail}: {exc.webhook_diagnostics}"
- return _not_yet(expected_otp_type, detail, elapsed, errored=bool(exc.webhook_diagnostics))
+ return _not_yet(expected_otp_type, detail, elapsed, webhook_answers=exc.webhook_diagnostics)
except Exception as exc:
LOG.warning(
"task_v3 verification tool lookup failed",
diff --git a/skyvern/webeye/browser_factory.py b/skyvern/webeye/browser_factory.py
index 1f6ad4765..f2810bc9b 100644
--- a/skyvern/webeye/browser_factory.py
+++ b/skyvern/webeye/browser_factory.py
@@ -444,16 +444,21 @@ def set_download_file_listener(
context = current()
workflow_run_id = (context.workflow_run_id if context else None) or kwargs.get("workflow_run_id")
task_id = (context.task_id if context else None) or kwargs.get("task_id")
+ # Read when the download starts, not when the context is built: one browser serves many tasks.
+ timeout_seconds = (
+ download_timeout or (context.download_timeout if context else None) or BROWSER_DOWNLOAD_TIMEOUT
+ )
try:
# Route path() through resolve_artifact_path so a timeout can never cancel a shared
# artifact future (see resolve_artifact_path). Everything after the await is synchronous
# filesystem work, so it does not need to run under a timeout.
- resolved_path = await resolve_artifact_path(download, download_timeout or BROWSER_DOWNLOAD_TIMEOUT)
+ resolved_path = await resolve_artifact_path(download, timeout_seconds)
if resolved_path is None:
LOG.error(
"timeout to download file, going to cancel the download",
workflow_run_id=workflow_run_id,
task_id=task_id,
+ timeout_seconds=timeout_seconds,
)
mark_download_cancelled_by_skyvern(download)
await download.cancel()
diff --git a/tests/unit/browser_extension/test_mcp_glue.py b/tests/unit/browser_extension/test_mcp_glue.py
index d65491992..fb36358ce 100644
--- a/tests/unit/browser_extension/test_mcp_glue.py
+++ b/tests/unit/browser_extension/test_mcp_glue.py
@@ -698,13 +698,9 @@ def test_default_extension_pair_exposes_cancel_pending() -> None:
assert "--cancel-pending" in registered_options
[email protected]("flag", [None, "0", "1"])
-def test_extension_broker_commands_are_registered_unconditionally(flag: str | None) -> None:
+def test_extension_broker_commands_are_registered_unconditionally() -> None:
environment = os.environ.copy()
- if flag is None:
- environment.pop("SKYVERN_BROWSER_EXTENSION_BROKER", None)
- else:
- environment["SKYVERN_BROWSER_EXTENSION_BROKER"] = flag
+ environment["SKYVERN_BROWSER_EXTENSION_BROKER"] = "0"
script = (
"import json; "
"from skyvern.cli.commands.browser import browser_app; "
diff --git a/tests/unit/forge/sdk/db/test_workflow_runs_repository.py b/tests/unit/forge/sdk/db/test_workflow_runs_repository.py
index a888a45f0..c85048b16 100644
--- a/tests/unit/forge/sdk/db/test_workflow_runs_repository.py
+++ b/tests/unit/forge/sdk/db/test_workflow_runs_repository.py
@@ -288,26 +288,43 @@ async def test_prepare_next_attempt_reopens_the_task_run_mirror(sqlite_db: Agent
@pytest.mark.asyncio
[email protected]("strategy", ["round_robin", "random"])
@pytest.mark.parametrize(
- "seed_source, pool_size, sequential, retained_session, retained_address, replacement_address, resets_seed",
+ "strategy, seed_source, pool_size, sequential, retained_session, retained_address, replacement_address, resets_seed",
[
- (BrowserSeedSource.credential, 2, False, None, None, None, True),
- (BrowserSeedSource.own_memory, 2, False, None, None, None, True),
- (BrowserSeedSource.credential, 1, False, None, None, None, False),
- (BrowserSeedSource.own_memory, 1, False, None, None, None, False),
- (BrowserSeedSource.credential, 2, True, None, None, None, False),
- (BrowserSeedSource.override, 2, False, None, None, None, False),
- (BrowserSeedSource.picked, 2, False, None, None, None, False),
- (BrowserSeedSource.fresh, 2, False, None, None, None, False),
- (BrowserSeedSource.credential, 2, False, "explicit", None, None, False),
- (BrowserSeedSource.own_memory, 2, False, "explicit", None, None, False),
- (BrowserSeedSource.credential, 2, False, "forced", None, None, False),
- (BrowserSeedSource.own_memory, 2, False, "forced", None, None, False),
- (BrowserSeedSource.credential, 2, False, None, "retained-cdp.example.test", None, False),
- (BrowserSeedSource.own_memory, 2, False, None, "retained-cdp.example.test", None, False),
- (BrowserSeedSource.credential, 2, False, None, "retained-cdp.example.test", "healthy-cdp.example.test", True),
- (BrowserSeedSource.own_memory, 2, False, None, "retained-cdp.example.test", "healthy-cdp.example.test", True),
+ ("random", BrowserSeedSource.credential, 2, False, None, None, None, True),
+ *[
+ ("round_robin", *case)
+ for case in [
+ (BrowserSeedSource.credential, 2, False, None, None, None, True),
+ (BrowserSeedSource.own_memory, 2, False, None, None, None, True),
+ (BrowserSeedSource.credential, 1, False, None, None, None, False),
+ (BrowserSeedSource.credential, 2, True, None, None, None, False),
+ (BrowserSeedSource.override, 2, False, None, None, None, False),
+ (BrowserSeedSource.picked, 2, False, None, None, None, False),
+ (BrowserSeedSource.fresh, 2, False, None, None, None, False),
+ (BrowserSeedSource.credential, 2, False, "explicit", None, None, False),
+ (BrowserSeedSource.credential, 2, False, "forced", None, None, False),
+ (BrowserSeedSource.credential, 2, False, None, "retained-cdp.example.test", None, False),
+ (
+ BrowserSeedSource.credential,
+ 2,
+ False,
+ None,
+ "retained-cdp.example.test",
+ "healthy-cdp.example.test",
+ True,
+ ),
+ (
+ BrowserSeedSource.own_memory,
+ 2,
+ False,
+ None,
+ "retained-cdp.example.test",
+ "healthy-cdp.example.test",
+ True,
+ ),
+ ]
+ ],
],
)
async def test_prepare_next_attempt_invalidates_only_rotated_credential_seed(
@@ -2156,34 +2173,30 @@ async def _seed_run_identifier_runs(sqlite_db: AgentDB, *, with_task_runs: bool)
await session.commit()
[email protected](("search_key", "expected_run_id"), _RUN_IDENTIFIER_SEARCH_CASES)
@pytest.mark.asyncio
-async def test_get_all_runs_v2_search_key_matches_run_identifiers(
- sqlite_db: AgentDB, search_key: str, expected_run_id: str
-) -> None:
+async def test_get_all_runs_v2_search_key_matches_run_identifiers(sqlite_db: AgentDB) -> None:
await _seed_run_identifier_runs(sqlite_db, with_task_runs=True)
- rows = await sqlite_db.workflow_runs.get_all_runs_v2(organization_id="org_test", search_key=search_key)
-
- assert {row["run_id"] for row in rows} == {expected_run_id}
+ for search_key, expected_run_id in _RUN_IDENTIFIER_SEARCH_CASES:
+ rows = await sqlite_db.workflow_runs.get_all_runs_v2(organization_id="org_test", search_key=search_key)
+ assert {row["run_id"] for row in rows} == {expected_run_id}, search_key
[email protected](("search_key", "expected_run_id"), _RUN_IDENTIFIER_SEARCH_CASES)
@pytest.mark.asyncio
async def test_get_workflow_runs_for_workflow_permanent_id_search_key_matches_run_identifiers(
- sqlite_db: AgentDB, search_key: str, expected_run_id: str
+ sqlite_db: AgentDB,
) -> None:
# Covers the shared WorkflowRunModel filter behind the per-workflow runs table, /workflows/runs,
# and the orphan fallback leg of the global runs list.
await _seed_run_identifier_runs(sqlite_db, with_task_runs=False)
- runs = await sqlite_db.workflow_runs.get_workflow_runs_for_workflow_permanent_id(
- workflow_permanent_id="wpid_test",
- organization_id="org_test",
- search_key=search_key,
- )
-
- assert {run.workflow_run_id for run in runs} == {expected_run_id}
+ for search_key, expected_run_id in _RUN_IDENTIFIER_SEARCH_CASES:
+ runs = await sqlite_db.workflow_runs.get_workflow_runs_for_workflow_permanent_id(
+ workflow_permanent_id="wpid_test",
+ organization_id="org_test",
+ search_key=search_key,
+ )
+ assert {run.workflow_run_id for run in runs} == {expected_run_id}, search_key
@pytest.mark.asyncio
diff --git a/tests/unit/forge/sdk/test_artifact_content_range.py b/tests/unit/forge/sdk/test_artifact_content_range.py
index b08f4a011..adde34ceb 100644
--- a/tests/unit/forge/sdk/test_artifact_content_range.py
+++ b/tests/unit/forge/sdk/test_artifact_content_range.py
@@ -333,8 +333,7 @@ class TestArtifactContentFromS3:
assert all(amount is not None for amount, _ in storage_bodies.reads)
assert sum(size for _, size in storage_bodies.reads) == len(body)
- @pytest.mark.parametrize("range_header", [None, "bytes=5-14"])
- @pytest.mark.parametrize("kind", ["bundle-member", "compressed-har"])
+ @pytest.mark.parametrize(("kind", "range_header"), [("bundle-member", None), ("compressed-har", "bytes=5-14")])
def test_decoded_artifacts_keep_their_whole_object_semantics(
self,
monkeypatch: pytest.MonkeyPatch,
diff --git a/tests/unit/forge/sdk/test_workflow_schedules_routes.py b/tests/unit/forge/sdk/test_workflow_schedules_routes.py
index a0883808a..8e8525474 100644
--- a/tests/unit/forge/sdk/test_workflow_schedules_routes.py
+++ b/tests/unit/forge/sdk/test_workflow_schedules_routes.py
@@ -158,8 +158,11 @@ def _iso(value: datetime) -> str:
@pytest.mark.asyncio
[email protected]("interval_seconds", [72 * HOUR, 5 * HOUR], ids=["72h", "5h"])
[email protected]("explicit_first_fire_at", [None, datetime(2026, 10, 31, 9, 17, tzinfo=UTC)])
+ ("interval_seconds", "explicit_first_fire_at"),
+ [(72 * HOUR, None), (5 * HOUR, datetime(2026, 10, 31, 9, 17, tzinfo=UTC))],
+ ids=["72h-derived-anchor", "5h-explicit-anchor"],
+)
async def test_create_interval_schedule_anchors_one_interval_out_unless_a_future_first_fire_is_given(
schedules_client: httpx.AsyncClient,
agent_db: AgentDB,
@@ -266,11 +269,10 @@ async def test_update_keeps_the_anchor_across_interval_edits_and_reanchors_when_
@pytest.mark.asyncio
[email protected]("entry", ["rest", "mcp"])
@pytest.mark.parametrize(
- "first_fire_at",
- ["9800-01-01T00:00:00+00:00", "9999-12-31T23:00:00-05:00"],
- ids=["ticks-overflow", "anchor-overflows-in-utc"],
+ ("entry", "first_fire_at"),
+ [("rest", "9800-01-01T00:00:00+00:00"), ("mcp", "9999-12-31T23:00:00-05:00")],
+ ids=["ticks-overflow-rest", "anchor-overflows-in-utc-mcp"],
)
async def test_first_fire_at_too_far_out_to_compute_ticks_is_a_field_named_422_that_writes_nothing(
schedules_client: httpx.AsyncClient,
diff --git a/tests/unit/test_agent_protocol_idempotency.py b/tests/unit/test_agent_protocol_idempotency.py
index d18691a67..c0794fefa 100644
--- a/tests/unit/test_agent_protocol_idempotency.py
+++ b/tests/unit/test_agent_protocol_idempotency.py
@@ -51,7 +51,6 @@ IDEMPOTENCY_KEY_ERROR_DETAIL = "Idempotency-Key must contain 1 to 255 visible AS
REJECTED_IDEMPOTENCY_KEYS = {
"empty": "",
- "single_space": " ",
"whitespace_only": " ",
"tab": "\t",
"trailing_newline": "replay-key\n",
@@ -181,8 +180,8 @@ async def test_create_workflow_rejects_malformed_idempotency_key_before_any_work
@pytest.mark.asyncio
@pytest.mark.parametrize(
"payload",
- [{}, {"yaml_definition": None, "json_definition": None}, {"yaml_definition": ""}],
- ids=["empty_body", "explicit_nulls", "empty_yaml"],
+ [{"yaml_definition": None, "json_definition": None}, {"yaml_definition": ""}],
+ ids=["explicit_nulls", "empty_yaml"],
)
async def test_create_workflow_without_definition_returns_422(
payload: dict[str, Any],
@@ -926,44 +925,36 @@ async def test_failed_workflow_save_does_not_schedule_saved_hook_before_commit(
await database.engine.dispose()
+_MASKED_HEADERS = {"X-Test": "***", "X-New": "***"}
+
+
@pytest.mark.asyncio
@pytest.mark.parametrize(
("entrypoint", "field_name", "supplied", "expected"),
[
- (entrypoint, field_name, supplied, expected)
- for field_name, supplied, expected in (
- [
- (field, supplied, expected)
- for field in ("extra_http_headers", "cdp_connect_headers")
- for supplied, expected in [
- ({}, {"X-Test": "stored-value"}),
- ({"value": None}, {}),
- ({"value": {}}, {}),
- ({"value": {"X-New": "new-value"}}, {"X-New": "new-value"}),
- (
- {"value": {"X-Test": "***", "X-New": "***"}},
- {"X-Test": "***", "X-New": "***"}
- if field == "extra_http_headers"
- else {"X-Test": "stored-value"},
- ),
- ]
- ]
- + [
- (field, supplied, expected)
- for field, stored, replacement in [
- ("totp_identifier", "stored-identifier", "new-identifier"),
- ("totp_verification_url", "https://example.test/stored-totp", "https://example.test/new-totp"),
- ("webhook_callback_url", "https://example.test/stored-hook", "https://example.test/new-hook"),
- ("proxy_location", {"url": "http://proxy.example.test:8080"}, "RESIDENTIAL"),
- ]
- for supplied, expected in [({}, stored), ({"value": None}, None), ({"value": replacement}, replacement)]
- ]
- )
- for entrypoint in (
- ["put", "json", "auto_accept", "manual_accept", "legacy_proposal", "manual_accept_updated_headers"]
- if field_name == "extra_http_headers"
- else ["put", "json"]
- )
+ ("put", "extra_http_headers", {}, {"X-Test": "stored-value"}),
+ ("put", "extra_http_headers", {"value": None}, {}),
+ ("put", "extra_http_headers", {"value": {}}, {}),
+ ("put", "extra_http_headers", {"value": {"X-New": "new-value"}}, {"X-New": "new-value"}),
+ ("put", "extra_http_headers", {"value": _MASKED_HEADERS}, _MASKED_HEADERS),
+ ("json", "extra_http_headers", {}, {"X-Test": "stored-value"}),
+ ("json", "extra_http_headers", {"value": _MASKED_HEADERS}, _MASKED_HEADERS),
+ *[
+ (entrypoint, "extra_http_headers", supplied, expected)
+ for entrypoint in ("auto_accept", "manual_accept", "legacy_proposal", "manual_accept_updated_headers")
+ for supplied, expected in (({}, {"X-Test": "stored-value"}), ({"value": _MASKED_HEADERS}, _MASKED_HEADERS))
+ ],
+ ("put", "cdp_connect_headers", {}, {"X-Test": "stored-value"}),
+ ("put", "cdp_connect_headers", {"value": _MASKED_HEADERS}, {"X-Test": "stored-value"}),
+ ("json", "cdp_connect_headers", {"value": None}, {}),
+ ("put", "proxy_location", {}, {"url": "http://proxy.example.test:8080"}),
+ ("put", "proxy_location", {"value": None}, None),
+ ("put", "proxy_location", {"value": "RESIDENTIAL"}, "RESIDENTIAL"),
+ ("json", "totp_identifier", {}, "stored-identifier"),
+ ("put", "totp_verification_url", {}, "https://example.test/stored-totp"),
+ ("json", "totp_verification_url", {"value": None}, None),
+ ("put", "webhook_callback_url", {}, "https://example.test/stored-hook"),
+ ("json", "webhook_callback_url", {"value": "https://example.test/new-hook"}, "https://example.test/new-hook"),
],
)
async def test_workflow_setting_presence_preserves_persisted_values(
diff --git a/tests/unit/test_background_task_executor.py b/tests/unit/test_background_task_executor.py
index 8c7e5805d..fee201c2f 100644
--- a/tests/unit/test_background_task_executor.py
+++ b/tests/unit/test_background_task_executor.py
@@ -836,11 +836,19 @@ async def test_in_process_retry_continues_after_interim_payload_failure(
@pytest.mark.asyncio
[email protected]("sweep", ["background", "cloud"])
[email protected]("current_status", ["running", "completed"])
[email protected]("artifact_link", ["task", "step", "block", "time"])
[email protected]("latest_has_screenshot", [False, True])
[email protected]("latest_has_recording", [False, True])
+ ("artifact_link", "sweep", "current_status", "latest_has_screenshot", "latest_has_recording"),
+ [
+ ("task", "background", "running", False, False),
+ ("task", "cloud", "completed", True, True),
+ ("step", "background", "running", True, True),
+ ("step", "cloud", "completed", False, False),
+ ("block", "background", "completed", False, True),
+ ("block", "cloud", "running", True, False),
+ ("time", "background", "completed", True, False),
+ ("time", "cloud", "running", False, True),
+ ],
+)
async def test_recovered_interim_payload_describes_target_attempt(
interim_retry_db: AgentDB,
monkeypatch: pytest.MonkeyPatch,
@@ -4244,24 +4252,20 @@ async def test_concurrent_prepared_recovery_dispatches_only_claim_winner(
@pytest.mark.asyncio
@pytest.mark.parametrize(
- "entrance, escaped_exception",
- [("in_process", False), ("in_process", True), ("recovery_pending", False), ("recovery_prepared", False)],
-)
- "lane, outcome",
+ "entrance, escaped_exception, lane, outcome",
[
- ("browser_session_id", "clear"),
- ("browser_address", "clear"),
- ("sequential_credential_id", "clear"),
- ("sequential_key", "clear"),
- ("reuse_bound_key", "clear"),
- ("run_sequentially", "clear"),
- ("depends_on_workflow_run_id", "clear"),
- ("sequential_credential_id", "cancel"),
- ("sequential_credential_id", "task_cancel"),
- ("sequential_credential_id", "timeout"),
- ("sequential_credential_id", "query_error"),
- ("none", "clear"),
+ ("in_process", False, "browser_session_id", "clear"),
+ ("in_process", False, "sequential_credential_id", "cancel"),
+ ("in_process", False, "none", "clear"),
+ ("in_process", True, "browser_address", "clear"),
+ ("in_process", True, "sequential_credential_id", "task_cancel"),
+ ("in_process", True, "run_sequentially", "clear"),
+ ("recovery_pending", False, "sequential_credential_id", "clear"),
+ ("recovery_pending", False, "sequential_credential_id", "timeout"),
+ ("recovery_pending", False, "depends_on_workflow_run_id", "clear"),
+ ("recovery_prepared", False, "sequential_key", "clear"),
+ ("recovery_prepared", False, "reuse_bound_key", "clear"),
+ ("recovery_prepared", False, "sequential_credential_id", "query_error"),
],
)
async def test_in_process_retry_reacquires_serialized_lane(
diff --git a/tests/unit/test_bitwarden_login.py b/tests/unit/test_bitwarden_login.py
index cfa330f3d..720fa2156 100644
--- a/tests/unit/test_bitwarden_login.py
+++ b/tests/unit/test_bitwarden_login.py
@@ -2,9 +2,11 @@ import asyncio
import json
import os
import sys
+from types import SimpleNamespace
from unittest.mock import AsyncMock, MagicMock
import pytest
+import tldextract
from pydantic import ValidationError
from structlog.testing import capture_logs
@@ -678,54 +680,268 @@ def test_retry_backoff_is_full_jitter_with_doubling_cap(monkeypatch: pytest.Monk
assert delays == [20.0, 40.0, 60.0, 60.0, 60.0]
-async def test_cold_login_gets_its_own_budget_beyond_the_read_timeout(monkeypatch: pytest.MonkeyPatch) -> None:
- """A cold `bw login` downloads the whole vault, so it outlives the budget sized for the reads
- behind it. Under a batch it regularly needs more than that, and killing it there fails the run
- before it starts (SKY-18666)."""
- read_timeout = 0.2
- login_seconds = 0.6
- monkeypatch.setattr(bitwarden_module.settings, "BITWARDEN_LOGIN_TIMEOUT_SECONDS", 5.0)
- monkeypatch.setattr(bitwarden_module.settings, "BITWARDEN_MAX_JITTER_SECONDS", 0.0)
- await bitwarden_module._cli_sessions.clear()
-
- budgets: dict[str, float] = {}
-
- async def fake_run_command(
- command: list[str], additional_env: dict | None = None, timeout: float = 60
- ) -> RunCommandResult:
+# Scaled budgets for the cold-session tests: a read gets `_READ`, a cold login (and an API-key unlock)
+# gets `_COLD`. The API-key attempt is then capped at 2 * _COLD + _READ, an email attempt at _COLD + _READ.
+_READ = 0.3
+_COLD = 0.9
+_ITEM_ID = "11111111-1111-1111-1111-111111111111"
+
+
+class _TimedVaultProcess:
+ """A fake `bw` process that takes a scripted time to answer, so real `run_command` timeouts apply."""
+
+ def __init__(self, step: str, seconds: float, stdout: str, gate: asyncio.Event | None = None) -> None:
+ self.step = step
+ self.seconds = seconds
+ self.stdout = stdout
+ self.gate = gate
+ self.returncode: int | None = None
+ self.pid = 4243
+ self.killed = False
+ self.waited = False
+
+ async def communicate(self) -> tuple[bytes, bytes]:
+ if self.gate is not None:
+ self.gate.set()
+ await asyncio.sleep(self.seconds)
+ self.returncode = 0
+ return self.stdout.encode(), b""
+
+ def kill(self) -> None:
+ self.killed = True
+ self.returncode = -9
+
+ async def wait(self) -> int | None:
+ self.waited = True
+ return self.returncode
+
+
+class _TimedVaultCli:
+ """Installs `_TimedVaultProcess` behind `asyncio.create_subprocess_exec` and records every process."""
+
+ def __init__(self, monkeypatch: pytest.MonkeyPatch, seconds: dict[str, float], read_stdout: str) -> None:
+ self.seconds = seconds
+ self.read_stdout = read_stdout
+ self.login_stdout = "You are logged in!"
+ self.processes: list[_TimedVaultProcess] = []
+ self.unlock_started = asyncio.Event()
+ monkeypatch.setattr(asyncio, "create_subprocess_exec", self._exec)
+ monkeypatch.setattr(bitwarden_module, "_cli_sessions", bitwarden_module._CliSessionCache())
+ monkeypatch.setattr(bitwarden_module.settings, "BITWARDEN_LOGIN_TIMEOUT_SECONDS", _COLD)
+ monkeypatch.setattr(bitwarden_module.settings, "BITWARDEN_TIMEOUT_SECONDS", _READ)
+ monkeypatch.setattr(bitwarden_module.settings, "BITWARDEN_MAX_JITTER_SECONDS", 0.0)
+ # A configured global email turns every request into an email login; these tests choose their own.
+ monkeypatch.setattr(bitwarden_module.settings, "BITWARDEN_EMAIL", None)
+ # The default domain extractor fetches the public suffix list on its first call, blocking the event
+ # loop for most of a second inside the timed attempt. Use the bundled list, loaded before the clock.
+ extractor = tldextract.TLDExtract(suffix_list_urls=(), cache_dir=None)
+ extractor("https://example.test")
+ monkeypatch.setattr(bitwarden_module, "tldextract", SimpleNamespace(extract=extractor))
+
+ async def _exec(self, *command: str, **kwargs: object) -> _TimedVaultProcess:
step = command[1]
- budgets[step] = timeout
- if step == "login":
- await asyncio.sleep(login_seconds)
- if timeout < login_seconds:
- raise asyncio.TimeoutError
- return RunCommandResult(stdout="You are logged in!", stderr="", returncode=0)
- if step == "unlock":
- return RunCommandResult(
- stdout='Your vault is now unlocked!\nBW_SESSION="session-key"', stderr="", returncode=0
- )
- return RunCommandResult(stdout=json.dumps(_cli_item()), stderr="", returncode=0)
+ stdout = {
+ "login": self.login_stdout,
+ "unlock": 'Your vault is now unlocked!\nBW_SESSION="session-key"',
+ }.get(step, self.read_stdout)
+ gate = self.unlock_started if step == "unlock" else None
+ process = _TimedVaultProcess(step, self.seconds.get(step, 0.0), stdout, gate)
+ self.processes.append(process)
+ return process
- monkeypatch.setattr(BitwardenService, "run_command", fake_run_command)
+ def steps(self) -> list[str]:
+ return [process.step for process in self.processes]
+
+ @staticmethod
+ def sessions() -> int:
+ return len(bitwarden_module._cli_sessions._sessions)
+
+
+def _login_list_stdout() -> str:
+ return json.dumps([_cli_item()])
+
+
+def _identity_list_stdout() -> str:
+ item = _cli_item()
+ item["fields"] = [{"name": "first_name", "value": "Ada", "type": 0}]
+ return json.dumps([item])
+
+
+async def _fetch_password_by_id(**overrides: object) -> dict[str, str]:
+ kwargs: dict = {
+ "client_id": "client-id",
+ "client_secret": "client-secret",
+ "master_password": "master-password",
+ "bw_organization_id": None,
+ "bw_collection_ids": None,
+ "collection_id": "coll-1",
+ "item_id": _ITEM_ID,
+ "max_retries": 1,
+ "timeout": _READ,
+ }
+ kwargs.update(overrides)
+ return await BitwardenService.get_secret_value_from_url(**kwargs)
+
+
+async def _fetch_password_by_url() -> dict[str, str]:
+ return await BitwardenService.get_secret_value_from_url(
+ client_id="client-id",
+ client_secret="client-secret",
+ master_password="master-password",
+ bw_organization_id=None,
+ bw_collection_ids=None,
+ url="https://example.test/login",
+ collection_id="coll-1",
+ max_retries=1,
+ timeout=_READ,
+ )
+
+
+async def _fetch_identity() -> dict[str, str]:
+ return await BitwardenService.get_sensitive_information_from_identity(
+ client_id="client-id",
+ client_secret="client-secret",
+ master_password="master-password",
+ bw_organization_id=None,
+ bw_collection_ids=None,
+ collection_id="coll-1",
+ identity_key="identity",
+ identity_fields=["first_name"],
+ remaining_retries=0,
+ timeout=_READ,
+ fail_reasons=[],
+ )
+
+
+async def _fetch_card() -> dict[str, str]:
+ return await BitwardenService.get_credit_card_data(
+ client_id="client-id",
+ client_secret="client-secret",
+ master_password="master-password",
+ bw_organization_id=None,
+ bw_collection_ids=None,
+ collection_id="coll-1",
+ item_id=_ITEM_ID,
+ remaining_retries=0,
+ fail_reasons=[],
+ )
+
+
+ ("fetch", "read_step", "read_stdout", "field", "expected"),
+ [
+ (_fetch_password_by_id, "get", json.dumps(_cli_item()), "BW_PASSWORD", "example-password"),
+ (_fetch_password_by_url, "list", _login_list_stdout(), "BW_PASSWORD", "example-password"),
+ (_fetch_identity, "list", _identity_list_stdout(), "first_name", "Ada"),
+ (
+ _fetch_card,
+ "get",
+ json.dumps(_cli_item(BitwardenItemType.CREDIT_CARD)),
+ "BW_CREDIT_CARD_NUMBER",
+ "4111111111111111",
+ ),
+ ],
+ ids=["password-by-id", "password-by-url", "identity", "card"],
+)
+async def test_a_slow_cold_api_key_login_and_unlock_both_fit_one_attempt(
+ monkeypatch: pytest.MonkeyPatch, fetch, read_step: str, read_stdout: str, field: str, expected: str
+) -> None:
+ """Under a batch, a cold API-key session pays a slow `bw login` and then a slow `bw unlock`; each runs
+ past a read's budget and together they run past login + read. Both get the cold budget, and the
+ attempt has room for login, unlock and the read behind them (SKY-18666)."""
+ cli = _TimedVaultCli(monkeypatch, {"login": 0.6, "unlock": 0.6, read_step: 0.15}, read_stdout)
+
+ credential = await fetch()
+
+ assert credential[field] == expected
+ assert cli.steps() == ["login", "unlock", read_step]
+ assert not any(process.killed for process in cli.processes)
+
+
+async def test_a_slow_read_still_fails_at_the_read_budget(monkeypatch: pytest.MonkeyPatch) -> None:
+ cli = _TimedVaultCli(monkeypatch, {"login": 0.05, "unlock": 0.05, "get": 0.6}, json.dumps(_cli_item()))
+
+ with pytest.raises(bitwarden_module.BitwardenListItemsError, match="TimeoutError"):
+ await _fetch_password_by_id()
+
+ read = cli.processes[-1]
+ assert read.step == "get" and read.killed and read.waited
- try:
- credential = await BitwardenService.get_secret_value_from_url(
- client_id="client-id",
- client_secret="client-secret",
- master_password="master-password",
- bw_organization_id="org-id",
- bw_collection_ids=None,
- item_id="11111111-1111-1111-1111-111111111111",
- timeout=read_timeout,
- )
- finally:
- await bitwarden_module._cli_sessions.clear()
- assert credential["BW_PASSWORD"] == "example-password"
- # The login outlives the read budget; the reads keep theirs so a hung read still fails fast.
- assert budgets["login"] == 5.0
- assert budgets["get"] == read_timeout
+async def test_the_attempt_deadline_still_ends_a_cold_api_key_session_stuck_behind_the_command_queue(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ cli = _TimedVaultCli(monkeypatch, {"login": 0.6, "unlock": 0.6, "get": 0.15}, json.dumps(_cli_item()))
+ queue = asyncio.Semaphore(1)
+ monkeypatch.setattr(bitwarden_module, "_cli_command_semaphore", queue)
+ await queue.acquire()
+ asyncio.get_running_loop().call_later(1.0, queue.release)
+
+ with pytest.raises(bitwarden_module.BitwardenListItemsError, match="TimeoutError"):
+ await _fetch_password_by_id()
+
+ active = cli.processes[-1]
+ assert active.killed and active.waited
+ assert cli.sessions() == 0
+
+
[email protected]("email_source", ["request", "settings"])
+async def test_an_email_session_keeps_its_login_plus_read_attempt(
+ monkeypatch: pytest.MonkeyPatch, email_source: str
+) -> None:
+ """Only an API-key session has an unlock to pay for. An email session, including one whose email comes
+ from the configured fallback, keeps the login + read attempt and unlocks on the read budget."""
+ cli = _TimedVaultCli(monkeypatch, {"login": 0.75, "unlock": 0.25, "get": 0.25}, json.dumps(_cli_item()))
+ overrides: dict = {}
+ if email_source == "request":
+ overrides["email"] = "[email protected]"
+ else:
+ monkeypatch.setattr(bitwarden_module.settings, "BITWARDEN_EMAIL", "[email protected]")
+
+ with pytest.raises(bitwarden_module.BitwardenListItemsError, match="TimeoutError"):
+ await _fetch_password_by_id(**overrides)
+
+ assert cli.steps() == ["login", "unlock", "get"]
+ assert cli.processes[-1].killed and cli.processes[-1].waited
+
+
+async def test_cancelling_a_cold_unlock_propagates_without_retry_and_drops_the_session(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ cli = _TimedVaultCli(monkeypatch, {"login": 0.0, "unlock": 10.0, "get": 0.0}, json.dumps(_cli_item()))
+ fetch = asyncio.create_task(_fetch_password_by_id(max_retries=3))
+ await asyncio.wait_for(cli.unlock_started.wait(), timeout=5)
+
+ fetch.cancel()
+ with pytest.raises(asyncio.CancelledError):
+ await fetch
+
+ assert cli.steps() == ["login", "unlock"]
+ assert cli.processes[-1].killed and cli.processes[-1].waited
+ assert cli.sessions() == 0
+
+
+async def test_cancelling_a_fetch_queued_for_the_cli_propagates_without_retry(monkeypatch: pytest.MonkeyPatch) -> None:
+ cli = _TimedVaultCli(monkeypatch, {}, json.dumps(_cli_item()))
+ queue = asyncio.Semaphore(1)
+ monkeypatch.setattr(bitwarden_module, "_cli_command_semaphore", queue)
+ await queue.acquire()
+ fetch = asyncio.create_task(_fetch_password_by_id(max_retries=3))
+ await asyncio.sleep(0.05)
+
+ fetch.cancel()
+ with pytest.raises(asyncio.CancelledError):
+ await fetch
+
+ assert cli.processes == []
+ assert cli.sessions() == 0
+ queue.release()
@pytest.mark.asyncio
diff --git a/tests/unit/test_browser_action_preflight.py b/tests/unit/test_browser_action_preflight.py
index 681fa9c14..90b61a1ba 100644
--- a/tests/unit/test_browser_action_preflight.py
+++ b/tests/unit/test_browser_action_preflight.py
@@ -679,7 +679,10 @@ class TestDialogAcceptBoundary:
def test_dialog_accepts_exist_only_in_the_dialog_handler(self) -> None:
accepting: dict[str, int] = {}
for path in self._python_files():
- tree = ast.parse(path.read_text())
+ source = path.read_text()
+ if "dialog" not in source:
+ continue
+ tree = ast.parse(source)
count = sum(
1
for node in ast.walk(tree)
@@ -699,7 +702,10 @@ class TestDialogAcceptBoundary:
def test_dialog_listener_registrations_are_pinned(self) -> None:
registering: list[str] = []
for path in self._python_files():
- tree = ast.parse(path.read_text())
+ source = path.read_text()
+ if "dialog" not in source:
+ continue
+ tree = ast.parse(source)
for node in ast.walk(tree):
if (
isinstance(node, ast.Call)
diff --git a/tests/unit/test_code_block_sandbox.py b/tests/unit/test_code_block_sandbox.py
index 50b6cdc70..75157d457 100644
--- a/tests/unit/test_code_block_sandbox.py
+++ b/tests/unit/test_code_block_sandbox.py
@@ -3075,6 +3075,7 @@ class TestCodeBlockMagicLink:
from skyvern.forge.sdk.workflow.models import block as block_module
_patch_context_resolution(monkeypatch, wrc)
+ monkeypatch.setattr(settings, "BROWSER_ACTION_TIMEOUT_MS", 0)
async def fake_get_workflow_run(*args: object, **kwargs: object) -> _FakeWorkflowRun:
return _FakeWorkflowRun()
diff --git a/tests/unit/test_copilot_credential_pause.py b/tests/unit/test_copilot_credential_pause.py
index 27887db38..ffefc3af8 100644
--- a/tests/unit/test_copilot_credential_pause.py
+++ b/tests/unit/test_copilot_credential_pause.py
@@ -844,7 +844,7 @@ async def test_invalid_credential_id_degrades_instead_of_crashing(monkeypatch: p
monkeypatch.setattr(credential_pause_module, "CREDENTIAL_RESPONSE_POLL_SECONDS", 0.01)
stream = _make_stream()
- config = CopilotConfig(credential_pause_enabled=True, credential_pause_timeout_seconds=5)
+ config = CopilotConfig(credential_pause_enabled=True, credential_pause_timeout_seconds=1)
resume_msgs = await maybe_credential_pause(ctx, _fake_result(), stream, config)
diff --git a/tests/unit/test_copilot_layering.py b/tests/unit/test_copilot_layering.py
deleted file mode 100644
index ac2688944..000000000
--- a/tests/unit/test_copilot_layering.py
+++ /dev/null
@@ -1,16 +0,0 @@
-"""Layering guards: the copilot domain package must not depend on the HTTP routes layer."""
-
-import subprocess
-import sys
-
-
-def test_importing_copilot_tools_does_not_load_routes() -> None:
- script = (
- "import sys\n"
- "import skyvern.forge.sdk.copilot.tools\n"
- "loaded = sorted(m for m in sys.modules if m.startswith('skyvern.forge.sdk.routes'))\n"
- "assert not loaded, f'copilot.tools pulled in routes modules: {loaded}'\n"
- )
- # Timeout so a pathological import hang fails loudly instead of stalling the run.
- result = subprocess.run([sys.executable, "-c", script], capture_output=True, text=True, timeout=120)
- assert result.returncode == 0, f"stdout:\n{result.stdout}\nstderr:\n{result.stderr}"
diff --git a/tests/unit/test_copilot_scout_act_observe.py b/tests/unit/test_copilot_scout_act_observe.py
index 981a91a03..0d106c6e0 100644
--- a/tests/unit/test_copilot_scout_act_observe.py
+++ b/tests/unit/test_copilot_scout_act_observe.py
@@ -92,6 +92,7 @@ _LANDING_URL = "https://example.com/results"
@pytest.fixture(autouse=True)
def _page_evidence_fingerprint_key(monkeypatch: pytest.MonkeyPatch) -> None:
monkeypatch.setattr(settings, "SECRET_KEY", "test-page-evidence-key")
+ monkeypatch.setattr(settings, "COPILOT_SCOUT_ACT_OBSERVE_RECAPTURE_DELAY_SECONDS", 0.05)
_SCHEMA_LESS_PACKET_KEYS = {
diff --git a/tests/unit/test_download_dir_rebind.py b/tests/unit/test_download_dir_rebind.py
index 0ab423f8f..3d1147dca 100644
--- a/tests/unit/test_download_dir_rebind.py
+++ b/tests/unit/test_download_dir_rebind.py
@@ -538,11 +538,46 @@ async def test_listener_timeout_cancels_and_marks_download() -> None:
await asyncio.sleep(0)
+ ("explicit", "task_timeout", "cancelled"),
+ [(None, 5.0, False), (0.001, 5.0, True), (None, None, True)],
+ ids=["task_timeout_set_after_registration", "explicit_kwarg_wins", "no_task_timeout_uses_default"],
+)
+async def test_listener_reads_the_task_download_timeout_when_the_download_starts(
+ explicit: float | None, task_timeout: float | None, cancelled: bool
+) -> None:
+ async def slow_path() -> Path:
+ await asyncio.sleep(0.05)
+ return Path("not-on-disk")
+
+ download = MagicMock()
+ download.path = AsyncMock(side_effect=slow_path)
+ download.cancel = AsyncMock()
+ run_context = SkyvernContext(workflow_run_id="wr_priv", task_id="task_priv")
+
+ with patch("skyvern.webeye.browser_factory.BROWSER_DOWNLOAD_TIMEOUT", 0.001):
+ await _run_listener(
+ download,
+ download_timeout=explicit,
+ run_context=run_context,
+ context_timeout_after_registration=task_timeout,
+ )
+
+ assert download.cancel.await_count == (1 if cancelled else 0)
+
+
_SENTINEL_STEM = "zz-sentinel-suggested-stem"
_SENTINEL_QUERY_NAME = "zz-sentinel-query-stem"
-async def _run_listener(download: MagicMock, *, download_timeout: float | None = None) -> list[dict[str, object]]:
+async def _run_listener(
+ download: MagicMock,
+ *,
+ download_timeout: float | None = None,
+ run_context: SkyvernContext | None = None,
+ context_timeout_after_registration: float | None = None,
+) -> list[dict[str, object]]:
events: list[dict[str, object]] = []
def capture(_msg: str, **kwargs: object) -> None:
@@ -558,6 +593,8 @@ async def _run_listener(download: MagicMock, *, download_timeout: float | None =
workflow_run_id="wr_priv",
task_id="task_priv",
)
+ if run_context is not None:
+ run_context.download_timeout = context_timeout_after_registration
page = MagicMock()
page_handlers: dict[str, object] = {}
@@ -565,7 +602,7 @@ async def _run_listener(download: MagicMock, *, download_timeout: float | None =
captured_handler["handler"](page)
with (
- patch("skyvern.webeye.browser_factory.current", return_value=None),
+ patch("skyvern.webeye.browser_factory.current", return_value=run_context),
patch("skyvern.webeye.browser_factory.LOG.info", side_effect=capture),
patch("skyvern.webeye.browser_factory.LOG.debug", side_effect=capture),
):
diff --git a/tests/unit/test_download_file_action_handler.py b/tests/unit/test_download_file_action_handler.py
index 80b09c250..9c43c7b2f 100644
--- a/tests/unit/test_download_file_action_handler.py
+++ b/tests/unit/test_download_file_action_handler.py
@@ -1,12 +1,10 @@
import asyncio
import contextlib
-import gc
import io
import logging
import os
import tempfile
import time
-import warnings
from collections.abc import Callable, Iterator
from datetime import UTC, datetime
from pathlib import Path
@@ -7801,37 +7799,6 @@ async def test_provider_poll_cancellation_propagates_without_recording_error() -
list_signal_files.assert_not_awaited()
-async def test_download_progress_sampler_closed_before_its_first_step_is_not_orphaned(tmp_path: Path) -> None:
- """A download that finishes without suspending closes the sampler in the event-loop iteration it was
- started in. Under the OTel asyncio instrumentor that cancel dropped the polling coroutine un-awaited,
- which reaches the logs as an error-tier "never awaited" RuntimeWarning on every such download.
- """
- # The instrumentor ships in the cloud dependency group only, so OSS CI skips this test.
- instrumentation = pytest.importorskip("opentelemetry.instrumentation.asyncio")
- partial = tmp_path / f"download{BROWSER_DOWNLOADING_SUFFIX}"
- partial.write_bytes(b"x")
- sampler = _DownloadProgressSampler(tmp_path, None, set())
-
- instrumentor = instrumentation.AsyncioInstrumentor()
- instrumentor.instrument()
- try:
- with warnings.catch_warnings(record=True) as caught:
- warnings.simplefilter("always")
- sampler.start_if_partial_seen([str(partial)])
- await sampler.aclose()
- # The sampler still references its cancelled task; the warning is raised only when that is collected.
- del sampler
- for _ in range(5):
- await asyncio.sleep(0)
- gc.collect()
- await asyncio.sleep(0)
- finally:
- instrumentor.uninstrument()
-
- assert [str(entry.message) for entry in caught if "never awaited" in str(entry.message)] == []
-
-
@pytest.mark.asyncio
async def test_download_progress_sampler_cancelled_while_closing_still_stops_its_task(tmp_path: Path) -> None:
"""A second cancellation landing while aclose() yields must not leave the polling task running forever."""
diff --git a/tests/unit/test_external_cdp_sessions.py b/tests/unit/test_external_cdp_sessions.py
index b321e5899..93e0bf01f 100644
--- a/tests/unit/test_external_cdp_sessions.py
+++ b/tests/unit/test_external_cdp_sessions.py
@@ -975,8 +975,18 @@ async def test_a_failed_close_at_the_deadline_is_retried_until_the_row_is_final(
@pytest.mark.asyncio
[email protected]("run_type", ["task", "workflow_run"])
[email protected]("loss", ["expired", "killed", "closed", "vanished"])
+ ("loss", "run_type"),
+ [
+ ("expired", "workflow_run"),
+ ("killed", "task"),
+ ("killed", "workflow_run"),
+ ("closed", "task"),
+ ("closed", "workflow_run"),
+ ("vanished", "task"),
+ ("vanished", "workflow_run"),
+ ],
+)
async def test_the_next_step_after_losing_a_registration_fails_with_that_fact_and_launches_nothing(
stack: SimpleNamespace, run_type: str, loss: str
) -> None:
diff --git a/tests/unit/test_mcp_observe_execute.py b/tests/unit/test_mcp_observe_execute.py
index 5a84c06b9..b7c5567d7 100644
--- a/tests/unit/test_mcp_observe_execute.py
+++ b/tests/unit/test_mcp_observe_execute.py
@@ -3,7 +3,6 @@
from __future__ import annotations
import asyncio
-import gc
from types import SimpleNamespace
from typing import Any
from unittest.mock import AsyncMock, MagicMock, PropertyMock, call
@@ -1927,15 +1926,6 @@ class TestSkyvernExecuteMCP:
assert committed is False
assert session_manager.get_session_ref("e0", session_id=ctx.session_id) is None
- def test_page_identity_key_never_reused_after_gc(self) -> None:
- """Identity tokens must not be reissued to a new page even if id() is reused."""
- page = _make_page()
- old_key = session_manager.page_ref_key(page)
- del page
- gc.collect()
- new_page = _make_page()
- assert session_manager.page_ref_key(new_page) != old_key
-
@pytest.mark.asyncio
async def test_stale_observe_commit_is_discarded_after_clear(self) -> None:
ctx = BrowserContext(mode="cloud_session", session_id="pbs_stale_gen")
diff --git a/tests/unit/test_mcp_response_distillation.py b/tests/unit/test_mcp_response_distillation.py
index c9d2abedb..7430f6ef1 100644
--- a/tests/unit/test_mcp_response_distillation.py
+++ b/tests/unit/test_mcp_response_distillation.py
@@ -639,15 +639,14 @@ def test_extraction_default_verbosity_supports_full_and_summary() -> None:
"from skyvern.cli.mcp_tools.browser import skyvern_extract; "
"print(inspect.signature(skyvern_extract).parameters['verbosity'].default)"
)
- for selected in ("full", "summary"):
- completed = subprocess.run(
- [sys.executable, "-c", script],
- check=True,
- capture_output=True,
- text=True,
- env={**os.environ, env_name: selected},
- )
- assert completed.stdout.strip().splitlines()[-1] == selected
+ completed = subprocess.run(
+ [sys.executable, "-c", script],
+ check=True,
+ capture_output=True,
+ text=True,
+ env={**os.environ, env_name: "summary"},
+ )
+ assert completed.stdout.strip().splitlines()[-1] == "summary"
def test_url_query_spans_do_not_synthesize_anchor_pairs() -> None:
diff --git a/tests/unit/test_multi_field_totp.py b/tests/unit/test_multi_field_totp.py
index 5e23d45e4..c2621cef0 100644
--- a/tests/unit/test_multi_field_totp.py
+++ b/tests/unit/test_multi_field_totp.py
@@ -1906,7 +1906,7 @@ async def test_group_fill_fallback_navigation_before_final_box_fails(monkeypatch
("phase", "remount_kind"),
[
(phase, kind)
- for phase in ("stream", "stream_error", "stream_missing", "fallback")
+ for phase in ("stream", "fallback")
for kind in (
"identical",
"different",
@@ -1923,6 +1923,7 @@ async def test_group_fill_fallback_navigation_before_final_box_fails(monkeypatch
"dashboard",
)
]
+ + [(phase, kind) for phase in ("stream_error", "stream_missing") for kind in ("identical", "different", "gone")]
+ [
("stream", "all_live"),
("fallback", "all_live"),
@@ -2492,7 +2493,7 @@ def test_partial_totp_plan_requires_explicit_planner_intent(response: dict[str,
assert agent_module._planner_confirmed_verification_code_intent(response) is expected
[email protected]("filled", [False, True])
[email protected](("filled", "code_source"), [(False, "secret"), (True, "external")])
@pytest.mark.parametrize(
"plan_kind",
[
@@ -2514,7 +2515,6 @@ def test_partial_totp_plan_requires_explicit_planner_intent(response: dict[str,
"leading-navigation",
],
)
[email protected]("code_source", ["secret", "external"])
@pytest.mark.asyncio
async def test_execute_step_rebound_group_requires_expected_value(
monkeypatch: pytest.MonkeyPatch,
diff --git a/tests/unit/test_run_service.py b/tests/unit/test_run_service.py
index f8134cdf9..96459ee62 100644
--- a/tests/unit/test_run_service.py
+++ b/tests/unit/test_run_service.py
@@ -1,5 +1,4 @@
import asyncio
-import gc
from datetime import UTC, datetime
from typing import Any
from unittest.mock import AsyncMock
@@ -155,28 +154,6 @@ async def test_cancelled_waiter_does_not_cancel_the_shared_build(build: _GatedBu
assert run_service._IN_FLIGHT == {}
-def test_failed_build_whose_waiters_all_left_is_not_reported_as_unretrieved(build: _GatedBuild) -> None:
- reported: list[str] = []
-
- async def every_waiter_leaves_then_the_build_fails() -> None:
- asyncio.get_running_loop().set_exception_handler(lambda _loop, context: reported.append(context["message"]))
- build.error = RuntimeError("db down")
- polls = [asyncio.create_task(_get()) for _ in range(3)]
- await _settle()
- for poll in polls:
- poll.cancel()
- await asyncio.gather(*polls, return_exceptions=True)
- build.release.set()
- await _settle()
-
- # asyncio reports an unretrieved exception when the task is finalized, so the loop must be gone first.
- asyncio.run(every_waiter_leaves_then_the_build_fails())
- gc.collect()
-
- assert reported == []
- assert run_service._IN_FLIGHT == {}
-
-
@pytest.mark.asyncio
async def test_completed_build_is_not_reused_by_the_next_poll(build: _GatedBuild) -> None:
build.release.set()
diff --git a/tests/unit/test_script_skyvern_page.py b/tests/unit/test_script_skyvern_page.py
index add396555..765e16949 100644
--- a/tests/unit/test_script_skyvern_page.py
+++ b/tests/unit/test_script_skyvern_page.py
@@ -3149,6 +3149,7 @@ class TestScriptSkyvernPageMagicLink:
monkeypatch.setattr(module, "poll_otp_value", fake_poll)
monkeypatch.setattr(module, "render_template", fake_render)
+ monkeypatch.setattr(module, "default_navigation_settle", AsyncMock())
monkeypatch.setattr(module.settings, "ALLOWED_HOSTS", ["portal.example.com"])
page = SimpleNamespace(goto=fake_goto, fill=fake_fill)
diff --git a/tests/unit/test_span_exception_redaction.py b/tests/unit/test_span_exception_redaction.py
index d0b4a1c6d..7aced3dd2 100644
--- a/tests/unit/test_span_exception_redaction.py
+++ b/tests/unit/test_span_exception_redaction.py
@@ -149,8 +149,14 @@ def _bare_span_start_sites() -> list[str]:
if path == helper:
continue
try:
- tree = ast.parse(path.read_text(encoding="utf-8"))
- except (SyntaxError, UnicodeDecodeError):
+ source = path.read_text(encoding="utf-8")
+ except UnicodeDecodeError:
+ continue
+ if "start_as_current_span" not in source:
+ continue
+ try:
+ tree = ast.parse(source)
+ except SyntaxError:
continue
for node in ast.walk(tree):
if (
@@ -184,8 +190,14 @@ def _bare_record_exception_sites() -> list[str]:
if path == helper:
continue
try:
- tree = ast.parse(path.read_text(encoding="utf-8"))
- except (SyntaxError, UnicodeDecodeError):
+ source = path.read_text(encoding="utf-8")
+ except UnicodeDecodeError:
+ continue
+ if "record_exception" not in source:
+ continue
+ try:
+ tree = ast.parse(source)
+ except SyntaxError:
continue
for node in ast.walk(tree):
if (
diff --git a/tests/unit/test_step_archive_accumulator.py b/tests/unit/test_step_archive_accumulator.py
index f79dec03f..b8b7e4e44 100644
--- a/tests/unit/test_step_archive_accumulator.py
+++ b/tests/unit/test_step_archive_accumulator.py
@@ -5,9 +5,7 @@ utility without touching S3 or the database.
"""
import asyncio
-import gc
import io
-import weakref
import zipfile
from unittest.mock import AsyncMock, MagicMock, patch
@@ -804,7 +802,6 @@ class TestWaitForUploadAiotasksCleanup:
hanging = asyncio.create_task(hang())
manager.upload_aiotasks_map["k"].extend([failed, hanging])
- ref = weakref.ref(failed)
wait_task = asyncio.create_task(manager.wait_for_upload_aiotasks(["k"]))
await asyncio.sleep(0.01)
@@ -815,10 +812,6 @@ class TestWaitForUploadAiotasksCleanup:
assert "k" not in manager.upload_aiotasks_map
assert all(failed is not t for lst in manager.upload_aiotasks_map.values() for t in lst)
- del failed
- gc.collect()
- assert ref() is None # traceback + byte payload no longer reachable through the map
-
await asyncio.gather(hanging, return_exceptions=True) # settle the gather-cancelled task
@pytest.mark.asyncio
diff --git a/tests/unit/test_taskv3_auth_tools.py b/tests/unit/test_taskv3_auth_tools.py
index b5833d61e..c2b018af2 100644
--- a/tests/unit/test_taskv3_auth_tools.py
+++ b/tests/unit/test_taskv3_auth_tools.py
@@ -736,8 +736,7 @@ async def test_get_verification_code_tail_shorter_than_a_poll_interval_counts_as
tools, _ = auth_tools.build_auth_tools(_task(totp_verification_url="https://totp.example"))
first = await tools[0].handler({})
second = await tools[0].handler({})
- assert "returned an error" in first.content and "http_status=204x3" in first.content
- assert "no polling time remains" in first.content
+ assert first.content == f"{auth_tools._CODE_BUDGET_SPENT} It answered: http_status=204x3."
assert second.content == auth_tools._CODE_BUDGET_SPENT
assert resolver_calls == 1
@@ -1836,7 +1835,7 @@ _STATUS_CASES: list[tuple[str, Any, str]] = [
(
"webhook_answering_http_500",
NoTOTPVerificationCodeFound(task_id="tsk_1", webhook_diagnostics="http_status=500x12"),
- "returned an error (NoTOTPVerificationCodeFound: http_status=500x12); about",
+ "no verification code has arrived yet (http_status=500x12); about",
),
(
"transport_error",
diff --git a/tests/unit/test_taskv3_loop.py b/tests/unit/test_taskv3_loop.py
index 7f16a0954..6d26e0fca 100644
--- a/tests/unit/test_taskv3_loop.py
+++ b/tests/unit/test_taskv3_loop.py
@@ -6101,7 +6101,7 @@ def _main_would_fire(sequence: list[tuple[str, str, str]], threshold: int) -> bo
return False
[email protected]("seed", range(200))
[email protected]("seed", range(50))
def test_live_stall_firing_is_a_subset_of_the_per_tool_counter(seed: int) -> None:
# The central claim of keying per probe: the loop never terminates a run the per-tool counter
# would have let live. Enumerated over random probe sequences, because seven hand-picked
@@ -6119,7 +6119,7 @@ def test_live_stall_firing_is_a_subset_of_the_per_tool_counter(seed: int) -> Non
break
[email protected]("seed", range(200))
[email protected]("seed", range(50))
def test_imminent_is_exactly_whether_one_more_read_of_some_probe_trips_live(seed: int) -> None:
# ``next_snapshot_can_trip`` is pinned by simulation, not by restating its formula: after every
# prefix, it must equal "re-reading SOME probe once, returning what it last returned, reaches
@@ -7900,7 +7900,7 @@ async def test_a_failing_pending_probe_fails_open() -> None:
@pytest.mark.asyncio
[email protected]("seed", range(200))
[email protected]("seed", range(50))
async def test_every_live_verdict_is_preceded_by_exactly_one_warning_on_its_tool_streak(seed: int) -> None:
# The warning reads the per-tool counter because that counter moves by exactly one per read:
# any live verdict needs tool_identical >= terminate > nudge on the same streak, so the streak
diff --git a/tests/unit/test_workflow_block_engine.py b/tests/unit/test_workflow_block_engine.py
index 6bc6047e3..799a4bb3c 100644
--- a/tests/unit/test_workflow_block_engine.py
+++ b/tests/unit/test_workflow_block_engine.py
@@ -474,6 +474,51 @@ async def test_execute_safe_persists_the_resolved_engine(scoped_context: Skyvern
assert persisted_engine == RunEngine.skyvern_v3
+ ("override", "script_mode", "fails", "seen"),
+ [
+ (RunEngine.skyvern_v3, False, False, 30.0),
+ (RunEngine.skyvern_v3, False, True, 30.0),
+ (None, False, False, 7.0),
+ (RunEngine.skyvern_v3, True, False, 7.0),
+ ],
+ ids=["v3_block", "v3_block_that_fails", "v1_block_unchanged", "script_mode_unchanged"],
+)
+async def test_a_v3_block_scopes_its_download_timeout_to_the_whole_block(
+ scoped_context: SkyvernContext,
+ override: RunEngine | None,
+ script_mode: bool,
+ fails: bool,
+ seen: float,
+) -> None:
+ # The browser's download listener reads this value when a download starts, including one the block's own
+ # navigation starts before the task loop; it must be the outer value again once the block ends.
+ scoped_context.workflow_block_engine_resolved_run_id = "wr_scope"
+ scoped_context.workflow_block_engine_override = override
+ scoped_context.script_mode = script_mode
+ scoped_context.download_timeout = 7.0
+ block = _make_block(TaskBlock, label="scope_block", download_timeout=30.0)
+ observed: list[float | None] = []
+
+ async def run_block(*_args: Any, **_kwargs: Any) -> BlockResult:
+ observed.append(scoped_context.download_timeout)
+ if fails:
+ raise RuntimeError("block failed")
+ return _block_result()
+
+ with (
+ patch("skyvern.forge.sdk.workflow.models.block.app") as mock_app,
+ patch.object(BaseTaskBlock, "execute", new_callable=AsyncMock, side_effect=run_block),
+ patch.object(Block, "_generate_workflow_run_block_description", new_callable=AsyncMock),
+ ):
+ _setup_mocks(mock_app)
+ await block.execute_safe(workflow_run_id="wr_scope")
+
+ assert observed == [seen]
+ assert scoped_context.download_timeout == 7.0
+
+
class _EngineCaptured(BaseException):
"""Raised from the create_workflow_run_block mock once the dispatched engine is captured.
diff --git a/tests/unit/test_workflow_run_parameter_batching.py b/tests/unit/test_workflow_run_parameter_batching.py
index 9608956e8..a548058c9 100644
--- a/tests/unit/test_workflow_run_parameter_batching.py
+++ b/tests/unit/test_workflow_run_parameter_batching.py
@@ -1779,36 +1779,41 @@ async def test_run_submission_carries_user_agent_platform_through_real_prepare_a
@pytest.mark.asyncio
[email protected]("route", ["run", "legacy"])
@pytest.mark.parametrize(
- ("parameters", "detail"),
+ ("route", "parameters", "detail"),
[
pytest.param(
+ "run",
{"login": "cred_deleted", "email": "[email protected]"},
"Invalid credential ID: cred_deleted. Failed to resolve to a valid credential.",
id="invalid-credential-id",
),
pytest.param(
+ "legacy",
{"login": "cred_live"},
"Missing value for parameter email in workflow {wpid}",
id="missing-parameter",
),
pytest.param(
+ "run",
{"email": "[email protected]", "count": "three"},
"Invalid workflow parameter. Expected parameter type: integer. Value: three.",
id="invalid-parameter-value",
),
pytest.param(
+ "legacy",
{"logn": "cred_live", "email": "[email protected]"},
"The run request sent parameter(s) this workflow does not declare: logn.",
id="misdirected-credential-key",
),
pytest.param(
+ "run",
{"login": "cred_live", "email": "[email protected]", "vault_item": "not-a-uuid"},
"Invalid workflow parameter. Expected parameter type: Bitwarden item ID (UUID). Value: not-a-uuid.",
id="invalid-bitwarden-item-id",
),
pytest.param(
+ "legacy",
{"login": "cred_live", "email": "[email protected]", "account": "cred_unlisted"},
"Credential override for parameter account must be one of the configured rotation or fallback credentials.",
id="credential-override-outside-the-pool",
@@ -1841,12 +1846,14 @@ async def test_run_submission_refuses_unusable_parameters_without_writing_a_run(
@pytest.mark.asyncio
[email protected]("route", ["run", "legacy"])
@pytest.mark.parametrize(
- ("parameters", "deleted_credential_id"),
+ ("route", "parameters", "deleted_credential_id"),
[
- pytest.param({"login": "cred_spare", "email": "[email protected]"}, "cred_live", id="stored-credential-deleted"),
pytest.param(
+ "run", {"login": "cred_spare", "email": "[email protected]"}, "cred_live", id="stored-credential-deleted"
+ ),
+ pytest.param(
+ "legacy",
{"login": "cred_live", "email": "[email protected]", "account": "cred_spare"},
"cred_spare",
id="override-credential-deleted",
diff --git a/tests/unit/webeye/test_action_deadline.py b/tests/unit/webeye/test_action_deadline.py
index f039d378d..532942b96 100644
--- a/tests/unit/webeye/test_action_deadline.py
+++ b/tests/unit/webeye/test_action_deadline.py
@@ -1,8 +1,6 @@
from __future__ import annotations
import asyncio
-import gc
-import warnings
import pytest
@@ -11,38 +9,6 @@ from skyvern.webeye import action_deadline
from skyvern.webeye.action_deadline import cancellable_driver_call
-async def test_a_caller_cancelled_before_the_call_takes_its_first_step_still_starts_it() -> None:
- """The OTel asyncio instrumentor (cloud workers) drops the coroutine of a task cancelled before its first step,
- and CPython reports that as an error-level "never awaited" warning on every such cancellation."""
- entered = asyncio.Event()
-
- async def call() -> None:
- entered.set()
- await asyncio.sleep(30)
-
- instrumentation = pytest.importorskip("opentelemetry.instrumentation.asyncio")
- instrumentor = instrumentation.AsyncioInstrumentor()
- # Finalized here rather than inside the recording window: garbage an earlier test left behind.
- gc.collect()
- instrumentor.instrument()
- try:
- with warnings.catch_warnings(record=True) as caught:
- warnings.simplefilter("always")
- with pytest.raises(TimeoutError):
- async with asyncio.timeout(0):
- await cancellable_driver_call(call)
- for _ in range(5):
- await asyncio.sleep(0)
- gc.collect()
- await asyncio.sleep(0)
- finally:
- instrumentor.uninstrument()
-
- assert [str(entry.message) for entry in caught if "never awaited" in str(entry.message)] == []
- assert entered.is_set()
-
-
@pytest.mark.asyncio
async def test_each_deadline_rearm_reaches_a_call_that_ignored_the_first_cancellation(
monkeypatch: pytest.MonkeyPatch,
diff --git a/tests/unit/workflow/test_code_block_recorder.py b/tests/unit/workflow/test_code_block_recorder.py
index c0899e40c..51cb94ae2 100644
--- a/tests/unit/workflow/test_code_block_recorder.py
+++ b/tests/unit/workflow/test_code_block_recorder.py
@@ -4419,39 +4419,6 @@ async def test_locator_probe_reraises_cancellation() -> None:
await _probe_code_block()._probe_failed_locator_count(_CancelLocator())
-async def test_locator_probe_consumes_a_late_failing_count_after_timeout() -> None:
- import gc
-
- # A driver reply that lands after the bounded wait (a navigation that destroys the execution
- # context) must be retrieved by the probe, not left as an unretrieved-future error -- the exact
- # signal this telemetry measures. Without the detached-task consume wiring, the late task
- # exception is logged by asyncio at GC; this asserts it is not.
- loop = asyncio.get_running_loop()
- captured: list[dict[str, Any]] = []
- previous = loop.get_exception_handler()
- loop.set_exception_handler(lambda _loop, ctx: captured.append(ctx))
-
- class _LateNavFailLocator:
- async def count(self) -> int:
- try:
- await asyncio.sleep(3600)
- except asyncio.CancelledError:
- raise RuntimeError("Execution context was destroyed, most likely because of a navigation") from None
-
- try:
- result = await _probe_code_block()._probe_failed_locator_count(_LateNavFailLocator())
- assert result == (None, "timeout")
- for _ in range(3):
- await asyncio.sleep(0)
- gc.collect()
- await asyncio.sleep(0)
- finally:
- loop.set_exception_handler(previous)
-
- assert not any("never retrieved" in str(ctx.get("message", "")) for ctx in captured)
-
-
@pytest.mark.asyncio
async def test_operation_attribution_event_allowlist_and_privacy() -> None:
from structlog.testing import capture_logs