Skip to content

Automate browser based workflows with AI

Accept a list of run statuses on the analytics status filter (#8304)

Aaron Perez632be27d6130
diff --git a/docs/developers/optimization/chrome-extension.mdx b/docs/developers/optimization/chrome-extension.mdx
index 4a7ad5eda..c3016ea8b 100644
--- a/docs/developers/optimization/chrome-extension.mdx
+++ b/docs/developers/optimization/chrome-extension.mdx
@@ -23,7 +23,7 @@ profile, so an extension is the only way to automate that browser directly.
## Requirements
-- Chrome 125 or later
+- Chrome 138 or later
- A local Skyvern MCP server connected over stdio
Hosted MCP is not supported yet.
@@ -39,8 +39,9 @@ and prints the remaining steps:
skyvern browser extension-install
```
-Then enable **Developer mode**, click **Load unpacked**, and select the printed directory. Start your extension-mode MCP
-server and run `skyvern browser extension-pair` to open the pairing page.
+Then enable **Developer mode**, click **Load unpacked**, and select the printed directory. Open **Details** for
+**Skyvern Agent** and enable **Allow User Scripts**. Start your extension-mode MCP server and run
+`skyvern browser extension-pair` to open the pairing page.
For manual setup:
@@ -54,6 +55,7 @@ For manual setup:
3. Enable **Developer mode**.
4. Click **Load unpacked**.
5. Select the directory printed by the command.
+6. Open the extension's **Details** page and enable **Allow User Scripts**.
---
@@ -166,9 +168,15 @@ Skyvern's scope includes:
- Tabs Skyvern creates and adds to **Skyvern Controlled**
- Popups opened by a controlled tab and added to **Skyvern Controlled**
-When Skyvern attaches to a controlled tab, Chrome displays its debugger infobar; Skyvern never hides it. Clicking
-**Cancel** in that infobar immediately revokes access to the tab, and Skyvern does not automatically reattach. Skyvern
-also never closes or restarts your Chrome browser.
+The extension requests access to HTTP and HTTPS pages so `skyvern_evaluate` can run caller-supplied JavaScript through
+Chrome's User Scripts API. This direct path runs in the page's main context without depending on the page's content
+security policy. It verifies the exact tab-group identity before and after each command. The broker can keep
+`about:blank` as a controlled root tab while it waits for navigation, but direct evaluation refuses `about:blank` and
+every other non-HTTP(S) URL.
+
+Debugger-based commands display Chrome's debugger infobar; Skyvern never hides it. Clicking **Cancel** in that infobar
+immediately revokes debugger access to the tab, and Skyvern does not automatically reattach. Main-context JavaScript
+commands do not attach the debugger or display its infobar. Skyvern never closes or restarts your Chrome browser.
The extension connects outbound to a bridge bound only to `127.0.0.1`. The default endpoint is
`ws://127.0.0.1:19777/extension/v1`. On macOS and Linux, a persistent daemon owns this listener and MCP processes reach
@@ -185,7 +193,6 @@ The extension refuses to control `chrome://`, `chrome-untrusted://`, `chrome-ext
- Downloads and file-chooser management are not supported yet.
- Incognito windows are not supported.
- Opening DevTools for a controlled tab detaches Skyvern and revokes access to that tab.
-- The current broker generation admits one local Skyvern MCP client at a time.
- Hosted Skyvern MCP cannot use the extension yet.
- Chrome internal pages, extension pages, DevTools, local files, the Chrome Web Store, and the other restricted targets
listed above cannot be controlled.
diff --git a/skyvern-frontend/src/api/AxiosClient.test.ts b/skyvern-frontend/src/api/AxiosClient.test.ts
index 0f37e0aeb..cce4812cc 100644
--- a/skyvern-frontend/src/api/AxiosClient.test.ts
+++ b/skyvern-frontend/src/api/AxiosClient.test.ts
@@ -555,6 +555,70 @@ describe("UI session refresh", () => {
});
});
+describe("request-scoped authentication", () => {
+ beforeEach(() => {
+ vi.resetModules();
+ window.sessionStorage.clear();
+ });
+
+ afterEach(() => {
+ window.sessionStorage.clear();
+ });
+
+ it("keeps the credential snapshot after shared client defaults change", async () => {
+ const { getClient, getClientWithRequestHeaders, setApiKeyHeader } =
+ await import("./AxiosClient");
+ setApiKeyHeader("api-key-a");
+ const requestA = await getClientWithRequestHeaders(async () => "token-a");
+ setApiKeyHeader("api-key-b");
+ await getClient(async () => "token-b");
+ const adapter = vi.fn<AxiosAdapter>(async (config) => ({
+ data: { ok: true },
+ status: 200,
+ statusText: "OK",
+ headers: {},
+ config,
+ }));
+ requestA.client.defaults.adapter = adapter;
+
+ await requestA.client.get("/scoped", { headers: requestA.headers });
+
+ const headers = adapter.mock.calls[0]?.[0].headers;
+ expect(headers?.get("Authorization")).toBe("Bearer token-a");
+ expect(headers?.get("X-API-Key")).toBe("api-key-a");
+ });
+ it("waits for the runtime API key before snapshotting request headers", async () => {
+ const token = "scoped-boot-race-session-canary";
+ let releaseMint: (response: Response) => void = () => {};
+ const mint = new Promise<Response>((resolve) => {
+ releaseMint = resolve;
+ });
+ vi.stubGlobal(
+ "fetch",
+ vi.fn(() => mint),
+ );
+
+ const { getClientWithRequestHeaders, initializeUiSession } =
+ await import("./AxiosClient");
+ void initializeUiSession();
+
+ const requestPromise = getClientWithRequestHeaders(async () => null);
+
+ releaseMint(
+ new Response(
+ JSON.stringify({
+ token,
+ expires_at: Math.floor(Date.now() / 1000) + 3600,
+ }),
+ { status: 200, headers: { "content-type": "application/json" } },
+ ),
+ );
+ const request = await requestPromise;
+
+ expect(request.headers.get("X-API-Key")).toBe(token);
+ });
+});
+
describe("open-source application entrypoint", () => {
beforeEach(() => {
vi.resetModules();
diff --git a/skyvern-frontend/src/api/AxiosClient.ts b/skyvern-frontend/src/api/AxiosClient.ts
index 5fb07d6dd..07a4854ae 100644
--- a/skyvern-frontend/src/api/AxiosClient.ts
+++ b/skyvern-frontend/src/api/AxiosClient.ts
@@ -9,7 +9,7 @@ import {
whenRuntimeCredentialReady,
} from "@/util/env";
import { useAuthIssueStore } from "@/store/AuthIssueStore";
-import axios, { type InternalAxiosRequestConfig } from "axios";
+import axios, { AxiosHeaders, type InternalAxiosRequestConfig } from "axios";
type ApiVersion = "sans-api-v1" | "v1" | "v2";
@@ -330,24 +330,24 @@ export function removeApiKeyHeader({
removeHeaderForAllClients("X-API-Key");
}
+function getClientForVersion(version: ApiVersion) {
+ switch (version) {
+ case "sans-api-v1":
+ return clientSansApiV1;
+ case "v1":
+ return client;
+ case "v2":
+ return v2Client;
+ default: {
+ throw new Error(`Unknown version: ${version}`);
+ }
+ }
+}
+
async function getClient(
credentialGetter: CredentialGetter | null,
version: ApiVersion = "v1",
) {
- const get = () => {
- switch (version) {
- case "sans-api-v1":
- return clientSansApiV1;
- case "v1":
- return client;
- case "v2":
- return v2Client;
- default: {
- throw new Error(`Unknown version: ${version}`);
- }
- }
- };
-
// Both auth headers are sent intentionally: Authorization (Bearer token from
// the credential getter, e.g. Clerk) is used for user-session auth, while
// X-API-Key is used for org-level API key auth. The backend accepts either
@@ -371,9 +371,24 @@ async function getClient(
removeApiKeyHeader({ clearStoredKey: false });
}
- return get();
+ return getClientForVersion(version);
+}
+
+async function getClientWithRequestHeaders(
+ credentialGetter: CredentialGetter | null,
+ version: ApiVersion = "v1",
+) {
+ const credential = credentialGetter ? await credentialGetter() : null;
+ if (!credential) {
+ await whenRuntimeCredentialReady();
+ }
+ const apiKey = getRuntimeApiKey();
+ const headers = new AxiosHeaders();
+ headers.set("Authorization", credential ? `Bearer ${credential}` : null);
+ headers.set("X-API-Key", apiKey ?? null);
+ return { client: getClientForVersion(version), headers };
}
export type CredentialGetter = () => Promise<string | null>;
-export { getClient, artifactApiClient };
+export { artifactApiClient, getClient, getClientWithRequestHeaders };
diff --git a/skyvern-frontend/src/api/types.ts b/skyvern-frontend/src/api/types.ts
index ca484ed13..b43977ed4 100644
--- a/skyvern-frontend/src/api/types.ts
+++ b/skyvern-frontend/src/api/types.ts
@@ -180,7 +180,6 @@ export type TaskApiResponse = {
screenshot_url: string | null;
recording_url: string | null;
recording_archived?: boolean;
- browser_console_log_url?: string | null;
failure_reason: string | null;
failure_category: Array<FailureCategory> | null;
webhook_failure_reason: string | null;
diff --git a/skyvern-frontend/src/components/BrowserStream.test.tsx b/skyvern-frontend/src/components/BrowserStream.test.tsx
index 8c0c24693..c5e121f3b 100644
--- a/skyvern-frontend/src/components/BrowserStream.test.tsx
+++ b/skyvern-frontend/src/components/BrowserStream.test.tsx
@@ -99,7 +99,6 @@ const mocks = vi.hoisted(() => {
pendingEvents: [],
reset: vi.fn(),
setIsRecording: vi.fn(),
- setMessageSocket: vi.fn(),
};
return {
diff --git a/skyvern-frontend/src/components/onboarding/CopilotCTAStep.tsx b/skyvern-frontend/src/components/onboarding/CopilotCTAStep.tsx
index c49e92a88..41db6859e 100644
--- a/skyvern-frontend/src/components/onboarding/CopilotCTAStep.tsx
+++ b/skyvern-frontend/src/components/onboarding/CopilotCTAStep.tsx
@@ -28,7 +28,7 @@ import {
getSetupTime,
} from "./templateUtils";
-const SURFACE = "dashboard" as const;
+const SURFACE = "discover" as const;
const INTENT_PLACEHOLDERS: Record<string, string> = {
fill_forms: "Describe the form you want to fill out...",
diff --git a/skyvern-frontend/src/components/onboarding/GetStartedModal.questionnaire.test.tsx b/skyvern-frontend/src/components/onboarding/GetStartedModal.questionnaire.test.tsx
new file mode 100644
index 000000000..a2bc23526
--- /dev/null
+++ b/skyvern-frontend/src/components/onboarding/GetStartedModal.questionnaire.test.tsx
@@ -0,0 +1,589 @@
+// @vitest-environment jsdom
+import { StrictMode, useState } from "react";
+import {
+ act,
+ cleanup,
+ fireEvent,
+ render,
+ screen,
+ waitFor,
+} from "@testing-library/react";
+import { MemoryRouter } from "react-router-dom";
+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
+import type {
+ ConfirmedPatch,
+ ConfirmedWriteResult,
+ LegacyOnboardingStatePatch,
+ OnboardingState,
+ OnboardingStateResponse,
+ QuestionnairePatchV1,
+ QuestionnaireStateV1,
+} from "@/store/onboarding/types";
+import { OnboardingContext } from "@/store/onboarding/useOnboardingState";
+import { GetStartedModal } from "./GetStartedModal";
+
+const mocks = vi.hoisted(() => ({
+ userId: "user-a",
+ confirmed: vi.fn<(patch: ConfirmedPatch) => Promise<ConfirmedWriteResult>>(),
+ createWorkflow: vi.fn(),
+ telemetry: {
+ registerVariant: vi.fn(),
+ flowStarted: vi.fn(),
+ modalOpened: vi.fn(),
+ modalSkipped: vi.fn(),
+ questionnaireShown: vi.fn<(input: unknown) => boolean>(() => true),
+ questionnaireCompleted: vi.fn(),
+ questionnaireSkipped: vi.fn(),
+ questionnaireUpdated: vi.fn(),
+ },
+}));
+
+vi.mock("posthog-js/react", () => ({
+ useFeatureFlagVariantKey: () => "template-first",
+}));
+vi.mock("@clerk/clerk-react", () => ({
+ useAuth: () => ({ userId: mocks.userId }),
+}));
+vi.mock("@/routes/workflows/hooks/useGlobalWorkflowsQuery", () => ({
+ useGlobalWorkflowsQuery: () => ({ data: [], isLoading: false }),
+}));
+vi.mock("@/routes/workflows/hooks/useCreateWorkflowMutation", () => ({
+ useCreateWorkflowMutation: () => ({
+ mutate: mocks.createWorkflow,
+ isPending: false,
+ }),
+}));
+vi.mock("@/util/onboarding/OnboardingTelemetry", () => ({
+ OnboardingTelemetry: mocks.telemetry,
+}));
+vi.mock("./CopilotCTAStep", () => ({
+ CopilotCTAStep: () => null,
+}));
+vi.mock("./QuestionnaireDetailsStep", () => ({
+ QuestionnaireDetailsStep: ({
+ completionAction,
+ expectedRevision,
+ externalError,
+ isPending,
+ onAction,
+ onBack,
+ }: {
+ completionAction: "complete" | "update";
+ expectedRevision: number;
+ externalError?: string | null;
+ isPending: boolean;
+ onAction: (patch: QuestionnairePatchV1) => Promise<void>;
+ onBack: () => void;
+ }) => {
+ const answerPatch = {
+ version: 1 as const,
+ mutation_id: `mutation-${completionAction}-${expectedRevision}`,
+ expected_revision: expectedRevision,
+ action: completionAction,
+ role: "developer" as const,
+ company_context: "startup" as const,
+ scale_intent: "exploring" as const,
+ referral_source: "search" as const,
+ };
+ return (
+ <div>
+ <span>{`details-${completionAction}-${expectedRevision}`}</span>
+ {externalError ? <div role="alert">{externalError}</div> : null}
+ <button
+ type="button"
+ disabled={isPending}
+ onClick={() => void onAction(answerPatch)}
+ >
+ details-submit
+ </button>
+ <button type="button" onClick={onBack}>
+ details-back
+ </button>
+ </div>
+ );
+ },
+}));
+
+const baseState: OnboardingState = {
+ tour_completed_at: null,
+ modal_dismissed_at: null,
+ first_save_at: null,
+ first_run_at: null,
+ ab_variant: "template-first",
+ user_intent: null,
+ questionnaire: null,
+ questionnaire_prompted_at: null,
+ seen_canvas: null,
+ seen_node_adder: null,
+ seen_sidebar: null,
+ seen_save_run: null,
+};
+
+function questionnaire(
+ overrides: Partial<QuestionnaireStateV1> = {},
+): QuestionnaireStateV1 {
+ return {
+ version: 1,
+ response_id: "response",
+ revision: 1,
+ last_mutation_id: "mutation-complete-0",
+ status: "completed",
+ role: "developer",
+ company_context: "startup",
+ scale_intent: "exploring",
+ referral_source: "search",
+ completed_at: "2026-01-01T00:00:00Z",
+ skipped_at: null,
+ deferred_at: null,
+ updated_at: "2026-01-01T00:00:00Z",
+ defer_prompt_count: 0,
+ ...overrides,
+ };
+}
+
+function response(
+ overrides: Partial<OnboardingState> = {},
+): OnboardingStateResponse {
+ return {
+ onboarding_state: { ...baseState, ...overrides },
+ launch_date_at_signup: "2026-01-01T00:00:00Z",
+ recovery_guidance_assignment: null,
+ };
+}
+
+const promptedAt = "2026-08-27T00:00:00Z";
+const reservedResponse = (overrides: Partial<OnboardingState> = {}) => ({
+ ...response({ ...overrides, questionnaire_prompted_at: promptedAt }),
+ questionnaire_prompt_result: {
+ status: "reserved" as const,
+ prompted_at: promptedAt,
+ },
+});
+
+function deferred<T>() {
+ let resolve!: (value: T) => void;
+ let reject!: (reason?: unknown) => void;
+ const promise = new Promise<T>((resolvePromise, rejectPromise) => {
+ resolve = resolvePromise;
+ reject = rejectPromise;
+ });
+ return { promise, reject, resolve };
+}
+
+function TestModal({
+ initialState = baseState,
+ editorState,
+}: {
+ initialState?: OnboardingState;
+ editorState?: Partial<
+ Pick<
+ OnboardingState,
+ | "modal_dismissed_at"
+ | "first_save_at"
+ | "questionnaire_prompted_at"
+ | "questionnaire"
+ >
+ >;
+}) {
+ const [state, setState] = useState(initialState);
+ function updateState(patch: LegacyOnboardingStatePatch) {
+ setState((current) => ({
+ ...current,
+ ...patch,
+ questionnaire: current.questionnaire,
+ }));
+ }
+ async function updateStateConfirmed(patch: ConfirmedPatch) {
+ const next = await mocks.confirmed(patch);
+ if ("onboarding_state" in next) {
+ setState(next.onboarding_state);
+ }
+ return next;
+ }
+ return (
+ <MemoryRouter>
+ <OnboardingContext.Provider
+ value={{
+ state: editorState ? { ...state, ...editorState } : state,
+ isLoading: false,
+ updateState,
+ updateStateConfirmed,
+ isNewUser: true,
+ abVariant: "template-first",
+ recoveryGuidanceAssignment: null,
+ }}
+ >
+ <GetStartedModal />
+ </OnboardingContext.Provider>
+ </MemoryRouter>
+ );
+}
+
+beforeEach(() => {
+ mocks.confirmed.mockResolvedValue(response({ user_intent: "fill_forms" }));
+ mocks.telemetry.questionnaireShown.mockReturnValue(true);
+ mocks.userId = "user-a";
+});
+
+afterEach(() => {
+ cleanup();
+ vi.clearAllMocks();
+ vi.restoreAllMocks();
+});
+
+describe("GetStartedModal", () => {
+ it("reserves once and dismisses recommendations without another write", async () => {
+ const reservation = deferred<ConfirmedWriteResult>();
+ const completion = deferred<OnboardingStateResponse>();
+ mocks.confirmed
+ .mockReturnValueOnce(reservation.promise)
+ .mockResolvedValueOnce(
+ response({
+ user_intent: "fill_forms",
+ questionnaire_prompted_at: promptedAt,
+ }),
+ )
+ .mockReturnValueOnce(completion.promise);
+ const view = render(
+ <StrictMode>
+ <TestModal />
+ </StrictMode>,
+ );
+ await waitFor(() => expect(mocks.confirmed).toHaveBeenCalledOnce());
+ view.rerender(
+ <StrictMode>
+ <TestModal />
+ </StrictMode>,
+ );
+ expect(mocks.confirmed).toHaveBeenCalledWith({
+ questionnaire_prompt: { version: 1, action: "reserve" },
+ });
+ await act(async () => reservation.resolve(reservedResponse()));
+ expect(mocks.telemetry.questionnaireShown).toHaveBeenCalledWith(
+ expect.objectContaining({ primaryIntent: null, promptReason: "initial" }),
+ );
+ fireEvent.click(
+ await screen.findByRole("button", { name: /Fill out forms/ }),
+ );
+ fireEvent.click(screen.getByRole("button", { name: "Continue" }));
+ fireEvent.click(await screen.findByText("details-submit"));
+ await waitFor(() => expect(mocks.confirmed).toHaveBeenCalledTimes(3));
+ expect(mocks.telemetry.questionnaireCompleted).not.toHaveBeenCalled();
+ fireEvent.keyDown(document, { key: "Escape" });
+ fireEvent.click(screen.getByRole("button", { name: "Close" }));
+ expect(mocks.confirmed).toHaveBeenCalledTimes(3);
+ expect(screen.getByRole("dialog")).toBeTruthy();
+ await act(async () =>
+ completion.resolve(
+ response({
+ user_intent: "fill_forms",
+ questionnaire_prompted_at: promptedAt,
+ questionnaire: questionnaire(),
+ }),
+ ),
+ );
+ expect(mocks.telemetry.questionnaireCompleted).toHaveBeenCalledOnce();
+ expect(await screen.findByText("Your next three steps")).toBeTruthy();
+ expect(screen.getAllByRole("listitem")).toHaveLength(3);
+ expect(
+ screen.queryAllByText(/Pick a template to start|copilot-header/),
+ ).toEqual([]);
+
+ fireEvent.click(screen.getByRole("button", { name: "Skip" }));
+
+ expect(mocks.confirmed).toHaveBeenCalledTimes(3);
+ expect(mocks.telemetry.modalSkipped).toHaveBeenCalledOnce();
+ expect(screen.queryByRole("dialog")).toBeNull();
+ });
+
+ it("returns through a matching response, updates, and closes on action", async () => {
+ const completed = questionnaire();
+ const updated = questionnaire({
+ revision: 2,
+ last_mutation_id: "mutation-update-1",
+ });
+ const updateWrite = deferred<OnboardingStateResponse>();
+ mocks.confirmed
+ .mockResolvedValueOnce(reservedResponse())
+ .mockResolvedValueOnce(
+ response({
+ user_intent: "fill_forms",
+ questionnaire_prompted_at: promptedAt,
+ }),
+ )
+ .mockResolvedValueOnce(
+ response({
+ user_intent: "fill_forms",
+ questionnaire_prompted_at: promptedAt,
+ questionnaire: completed,
+ }),
+ )
+ .mockResolvedValueOnce(
+ response({
+ user_intent: "fill_forms",
+ questionnaire_prompted_at: promptedAt,
+ questionnaire: completed,
+ }),
+ )
+ .mockReturnValueOnce(updateWrite.promise);
+ render(<TestModal />);
+ fireEvent.click(
+ await screen.findByRole("button", { name: /Fill out forms/ }),
+ );
+ fireEvent.click(screen.getByRole("button", { name: "Continue" }));
+ fireEvent.click(await screen.findByText("details-submit"));
+ expect(await screen.findByText("Your next three steps")).toBeTruthy();
+
+ fireEvent.click(screen.getByRole("button", { name: "Back" }));
+ expect(await screen.findByText("details-update-1")).toBeTruthy();
+ fireEvent.click(screen.getByText("details-back"));
+ fireEvent.click(screen.getByRole("button", { name: "Continue" }));
+ expect(await screen.findByText("Your next three steps")).toBeTruthy();
+
+ fireEvent.click(screen.getByRole("button", { name: "Back" }));
+ fireEvent.click(await screen.findByText("details-submit"));
+ await waitFor(() => expect(mocks.confirmed).toHaveBeenCalledTimes(5));
+ fireEvent.keyDown(document, { key: "Escape" });
+ fireEvent.click(screen.getByRole("button", { name: "Close" }));
+ expect(screen.getByRole("dialog")).toBeTruthy();
+ expect(mocks.telemetry.modalSkipped).not.toHaveBeenCalled();
+ expect(mocks.telemetry.questionnaireUpdated).not.toHaveBeenCalled();
+ await act(async () =>
+ updateWrite.resolve(
+ response({
+ user_intent: "fill_forms",
+ questionnaire_prompted_at: promptedAt,
+ questionnaire: updated,
+ }),
+ ),
+ );
+ expect(await screen.findByText("Your next three steps")).toBeTruthy();
+ expect(mocks.confirmed.mock.calls[4]?.[0].questionnaire).toEqual(
+ expect.objectContaining({
+ action: "update",
+ expected_revision: 1,
+ }),
+ );
+ expect(mocks.telemetry.questionnaireUpdated).toHaveBeenCalledOnce();
+
+ fireEvent.click(screen.getByRole("link", { name: "Open integrations" }));
+
+ expect(mocks.confirmed).toHaveBeenCalledTimes(5);
+ expect(screen.queryByRole("dialog")).toBeNull();
+ });
+
+ it("closes when Intent Continue first sees a foreign response", async () => {
+ mocks.confirmed
+ .mockResolvedValueOnce(reservedResponse())
+ .mockResolvedValueOnce(
+ response({
+ user_intent: "fill_forms",
+ questionnaire_prompted_at: promptedAt,
+ questionnaire: questionnaire({ response_id: "foreign-response" }),
+ }),
+ );
+ render(<TestModal />);
+ fireEvent.click(
+ await screen.findByRole("button", { name: /Fill out forms/ }),
+ );
+ fireEvent.click(screen.getByRole("button", { name: "Continue" }));
+
+ await waitFor(() => expect(screen.queryByRole("dialog")).toBeNull());
+ expect(mocks.confirmed).toHaveBeenCalledTimes(2);
+ expect(screen.queryByText("Your next three steps")).toBeNull();
+ expect(
+ screen.queryAllByText(/Pick a template to start|copilot-header/),
+ ).toEqual([]);
+ });
+
+ it("reserves and opens the questionnaire for an initially dismissed editor", async () => {
+ const dismissedAt = "2026-01-01T00:00:00Z";
+ mocks.confirmed.mockResolvedValueOnce(
+ reservedResponse({ modal_dismissed_at: dismissedAt }),
+ );
+ render(
+ <TestModal
+ initialState={{ ...baseState, modal_dismissed_at: dismissedAt }}
+ />,
+ );
+ expect(await screen.findByRole("dialog")).toBeTruthy();
+ expect(mocks.confirmed).toHaveBeenCalledOnce();
+ expect(mocks.telemetry.questionnaireShown).toHaveBeenCalledOnce();
+ });
+
+ it("opens the reserved questionnaire when sessionStorage.getItem throws", async () => {
+ vi.spyOn(Storage.prototype, "getItem").mockImplementation(() => {
+ throw new Error("storage unavailable");
+ });
+ mocks.confirmed.mockResolvedValueOnce(reservedResponse());
+ render(<TestModal />);
+ expect(await screen.findByRole("dialog")).toBeTruthy();
+ expect(mocks.telemetry.questionnaireShown).toHaveBeenCalledOnce();
+ });
+
+ it("opens the reserved questionnaire when sessionStorage.setItem throws", async () => {
+ vi.spyOn(Storage.prototype, "getItem").mockReturnValue(null);
+ vi.spyOn(Storage.prototype, "setItem").mockImplementation(() => {
+ throw new Error("storage unavailable");
+ });
+ mocks.confirmed.mockResolvedValueOnce(reservedResponse());
+ render(<TestModal />);
+ expect(await screen.findByRole("dialog")).toBeTruthy();
+ expect(mocks.telemetry.questionnaireShown).toHaveBeenCalledOnce();
+ });
+
+ it("never reopens a legacy deferred response", async () => {
+ const deferredState = questionnaire({
+ status: "deferred",
+ completed_at: null,
+ deferred_at: "2026-01-01T00:00:00Z",
+ defer_prompt_count: 1,
+ });
+ const props = {
+ initialState: {
+ ...baseState,
+ user_intent: "fill_forms",
+ questionnaire: deferredState,
+ },
+ };
+ render(<TestModal {...props} />);
+ await act(async () => undefined);
+ expect(screen.queryByRole("dialog")).toBeNull();
+ expect(mocks.confirmed).not.toHaveBeenCalled();
+ });
+
+ it("keeps initial details open and announces a failed dialog close", async () => {
+ const closeWrite = deferred<ConfirmedWriteResult>();
+ mocks.confirmed
+ .mockResolvedValueOnce(reservedResponse())
+ .mockResolvedValueOnce(
+ response({
+ user_intent: "fill_forms",
+ questionnaire_prompted_at: promptedAt,
+ }),
+ )
+ .mockReturnValueOnce(closeWrite.promise);
+ render(<TestModal />);
+ fireEvent.click(
+ await screen.findByRole("button", { name: /Fill out forms/ }),
+ );
+ fireEvent.click(screen.getByRole("button", { name: "Continue" }));
+ expect(await screen.findByText("details-complete-0")).toBeTruthy();
+
+ fireEvent.click(screen.getByRole("button", { name: "Close" }));
+ await waitFor(() => expect(mocks.confirmed).toHaveBeenCalledTimes(3));
+ expect(screen.getByText("details-complete-0")).toBeTruthy();
+ await act(async () => closeWrite.reject(new Error("offline")));
+
+ expect((await screen.findByRole("alert")).textContent).toBe(
+ "We couldn't save your choice. Try again.",
+ );
+ expect(screen.getByText("details-complete-0")).toBeTruthy();
+ expect(screen.getByRole("dialog")).toBeTruthy();
+ });
+
+ it("persists initial Skip before telemetry and closing", async () => {
+ const write = deferred<OnboardingStateResponse>();
+ mocks.confirmed
+ .mockResolvedValueOnce(reservedResponse())
+ .mockReturnValueOnce(write.promise);
+ render(<TestModal />);
+ fireEvent.click(await screen.findByRole("button", { name: "Skip" }));
+ await waitFor(() => expect(mocks.confirmed).toHaveBeenCalledTimes(2));
+ const skipPatch =
+ mocks.confirmed.mock.calls[mocks.confirmed.mock.calls.length - 1]?.[0]
+ .questionnaire;
+ expect(skipPatch).toEqual(
+ expect.objectContaining({ expected_revision: 0, action: "skip" }),
+ );
+ if (!skipPatch) throw new Error("missing Skip patch");
+ expect(screen.getByRole("dialog")).toBeTruthy();
+ expect(mocks.telemetry.questionnaireSkipped).not.toHaveBeenCalled();
+ await act(async () =>
+ write.resolve(
+ response({
+ questionnaire_prompted_at: promptedAt,
+ questionnaire: questionnaire({
+ status: "skipped",
+ completed_at: null,
+ skipped_at: promptedAt,
+ last_mutation_id: skipPatch.mutation_id,
+ }),
+ }),
+ ),
+ );
+ expect(mocks.telemetry.questionnaireSkipped).toHaveBeenCalledWith(
+ expect.objectContaining({ responseId: "response", revision: 1 }),
+ );
+ expect(screen.queryByRole("dialog")).toBeNull();
+ });
+
+ it("ignores a reservation result after unmount", async () => {
+ const write = deferred<ConfirmedWriteResult>();
+ mocks.confirmed.mockReturnValueOnce(write.promise);
+ const view = render(<TestModal />);
+ await waitFor(() => expect(mocks.confirmed).toHaveBeenCalledOnce());
+ expect(screen.getByRole("dialog")).toBeTruthy();
+
+ view.unmount();
+ await act(async () => write.resolve(reservedResponse()));
+
+ expect(mocks.telemetry.questionnaireShown).not.toHaveBeenCalled();
+ });
+
+ it("resets reservation ownership when the Clerk user changes", async () => {
+ const firstUserReservation = deferred<ConfirmedWriteResult>();
+ mocks.confirmed
+ .mockReturnValueOnce(firstUserReservation.promise)
+ .mockResolvedValueOnce(reservedResponse());
+ const view = render(<TestModal />);
+ await waitFor(() => expect(mocks.confirmed).toHaveBeenCalledOnce());
+
+ mocks.userId = "user-b";
+ view.rerender(<TestModal />);
+ await waitFor(() => expect(mocks.confirmed).toHaveBeenCalledTimes(2));
+ expect(
+ await screen.findByText("What do you want to automate?"),
+ ).toBeTruthy();
+
+ await act(async () => firstUserReservation.resolve(reservedResponse()));
+ expect(mocks.telemetry.questionnaireShown).toHaveBeenCalledOnce();
+ });
+
+ it("closes an ineligible fallback after another tab reserves", async () => {
+ const write = deferred<ConfirmedWriteResult>();
+ mocks.confirmed.mockReturnValueOnce(write.promise);
+ const view = render(<TestModal />);
+ await waitFor(() => expect(mocks.confirmed).toHaveBeenCalledOnce());
+ view.rerender(
+ <TestModal editorState={{ questionnaire_prompted_at: promptedAt }} />,
+ );
+
+ await act(async () =>
+ write.resolve({
+ ...response(),
+ questionnaire_prompt_result: { status: "ineligible" },
+ }),
+ );
+
+ expect(screen.queryByRole("dialog")).toBeNull();
+ expect(screen.queryByText("Pick a template to start")).toBeNull();
+ expect(mocks.telemetry.questionnaireShown).not.toHaveBeenCalled();
+ });
+
+ it.each(["modal_dismissed_at", "first_save_at"] as const)(
+ "ignores a stale reservation when %s changes while pending",
+ async (field) => {
+ const write = deferred<ConfirmedWriteResult>();
+ mocks.confirmed.mockReturnValueOnce(write.promise);
+ const view = render(<TestModal />);
+ await waitFor(() => expect(mocks.confirmed).toHaveBeenCalledOnce());
+ view.rerender(
+ <TestModal editorState={{ [field]: "2026-01-01T00:00:00Z" }} />,
+ );
+ await act(async () => write.resolve(reservedResponse()));
+ expect(mocks.telemetry.questionnaireShown).not.toHaveBeenCalled();
+ expect(screen.queryByRole("dialog")).toBeNull();
+ },
+ );
+});
diff --git a/skyvern-frontend/src/components/onboarding/GetStartedModal.test.tsx b/skyvern-frontend/src/components/onboarding/GetStartedModal.test.tsx
index 06f73cd2b..e5aeb35fe 100644
--- a/skyvern-frontend/src/components/onboarding/GetStartedModal.test.tsx
+++ b/skyvern-frontend/src/components/onboarding/GetStartedModal.test.tsx
@@ -1,23 +1,46 @@
// @vitest-environment jsdom
-import { cleanup, fireEvent, render, screen } from "@testing-library/react";
-import { afterEach, describe, expect, it, vi } from "vitest";
-import type { OnboardingState } from "@/store/onboarding/types";
-
-const { mockUpdateState, mockMutate, mockTelemetry, mutationState, flagState } =
- vi.hoisted(() => ({
- mockUpdateState: vi.fn(),
- mockMutate: vi.fn(),
- mockTelemetry: {
- registerVariant: vi.fn(),
- flowStarted: vi.fn(),
- modalOpened: vi.fn(),
- abVariantAssigned: vi.fn(),
- modalSkipped: vi.fn(),
- modalTemplateSelected: vi.fn(),
- },
- mutationState: { isPending: false },
- flagState: { variant: "template-first" },
- }));
+import {
+ cleanup,
+ fireEvent,
+ render,
+ screen,
+ waitFor,
+} from "@testing-library/react";
+import { MemoryRouter } from "react-router-dom";
+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
+import type {
+ OnboardingState,
+ QuestionnaireStateV1,
+} from "@/store/onboarding/types";
+import { useFeatureFlag } from "@/hooks/useFeatureFlag";
+
+const {
+ mockUpdateState,
+ mockUpdateStateConfirmed,
+ mockMutate,
+ mockTelemetry,
+ mutationState,
+ flagState,
+ stateOverrides,
+} = vi.hoisted(() => ({
+ mockUpdateState: vi.fn(),
+ mockUpdateStateConfirmed: vi.fn(),
+ mockMutate: vi.fn(),
+ mockTelemetry: {
+ registerVariant: vi.fn(),
+ flowStarted: vi.fn(),
+ modalOpened: vi.fn(),
+ abVariantAssigned: vi.fn(),
+ modalSkipped: vi.fn(),
+ modalTemplateSelected: vi.fn(),
+ questionnaireShown: vi.fn(() => true),
+ },
+ mutationState: { isPending: false },
+ flagState: {
+ variant: "template-first" as string | boolean | undefined,
+ },
+ stateOverrides: { current: {} as Partial<OnboardingState> },
+}));
const baseState: OnboardingState = {
tour_completed_at: null,
@@ -25,24 +48,51 @@ const baseState: OnboardingState = {
first_save_at: null,
first_run_at: null,
ab_variant: "template-first",
- user_intent: "fill_forms",
+ user_intent: null,
+ questionnaire_prompted_at: null,
seen_canvas: null,
seen_node_adder: null,
seen_sidebar: null,
seen_save_run: null,
};
+const completedQuestionnaire = {
+ version: 1,
+ response_id: "response",
+ revision: 1,
+ last_mutation_id: "mutation",
+ status: "completed",
+ role: "developer",
+ company_context: "startup",
+ scale_intent: "exploring",
+ referral_source: "search",
+ completed_at: "2026-01-01T00:00:00Z",
+ skipped_at: null,
+ deferred_at: null,
+ updated_at: "2026-01-01T00:00:00Z",
+ defer_prompt_count: 0,
+} satisfies QuestionnaireStateV1;
+
vi.mock("posthog-js/react", () => ({
useFeatureFlagVariantKey: () => flagState.variant,
}));
+vi.mock("@clerk/clerk-react", () => ({
+ useAuth: () => ({ userId: "user-a" }),
+}));
+vi.mock("@/hooks/useFeatureFlag", () => ({
+ useFeatureFlag: vi.fn(),
+}));
vi.mock("@/store/onboarding/useOnboardingState", () => ({
useOnboardingState: () => ({
- state: { ...baseState, ab_variant: flagState.variant },
- isLoading: false,
- updateState: mockUpdateState,
+ state: {
+ ...baseState,
+ ...stateOverrides.current,
+ ab_variant: flagState.variant,
+ },
isNewUser: true,
- abVariant: flagState.variant,
+ updateState: mockUpdateState,
+ updateStateConfirmed: mockUpdateStateConfirmed,
}),
}));
@@ -57,9 +107,15 @@ vi.mock("./CopilotCTAStep", async () => {
props.onBusyChange?.(true);
}, [props]);
return (
- <button type="button" onClick={props.onSkip}>
- child-skip
- </button>
+ <>
+ <div>copilot-header</div>
+ <div>copilot-body</div>
+ <div>
+ <button type="button" onClick={props.onSkip}>
+ child-skip
+ </button>
+ </div>
+ </>
);
},
};
@@ -82,17 +138,101 @@ vi.mock("@/util/onboarding/OnboardingTelemetry", () => ({
import { GetStartedModal } from "./GetStartedModal";
+beforeEach(() => {
+ mockUpdateStateConfirmed.mockResolvedValue({
+ onboarding_state: { ...baseState, ...stateOverrides.current },
+ launch_date_at_signup: "2026-08-27T00:00:00Z",
+ recovery_guidance_assignment: null,
+ questionnaire_prompt_result: { status: "flag_disabled" },
+ });
+});
+
afterEach(() => {
cleanup();
vi.clearAllMocks();
mutationState.isPending = false;
flagState.variant = "template-first";
+ stateOverrides.current = {};
+});
+
+async function renderTemplatesStep() {
+ render(<GetStartedModal />, { wrapper: MemoryRouter });
+ fireEvent.click(
+ await screen.findByRole("button", { name: /Fill out forms/ }),
+ );
+ fireEvent.click(screen.getByRole("button", { name: "Continue" }));
+}
+
+describe("GetStartedModal progress", () => {
+ it("uses server-owned reservation state instead of a frontend questionnaire flag", async () => {
+ render(<GetStartedModal />, { wrapper: MemoryRouter });
+ expect(await screen.findByText("STEP 1 OF 2")).toBeTruthy();
+ expect(screen.getByRole("button", { name: "Close" })).toBeTruthy();
+ expect(screen.queryByText("STEP 1 OF 3")).toBeNull();
+ expect(vi.mocked(useFeatureFlag)).not.toHaveBeenCalled();
+ });
+
+ it.each([
+ [undefined, "ineligible"],
+ [false, "flag_disabled"],
+ ] as const)(
+ "renders no editor content when the editor flag is %s",
+ async (variant, status) => {
+ flagState.variant = variant;
+ mockUpdateStateConfirmed.mockResolvedValueOnce({
+ onboarding_state: baseState,
+ launch_date_at_signup: "2026-08-27T00:00:00Z",
+ recovery_guidance_assignment: null,
+ questionnaire_prompt_result: { status },
+ });
+ render(<GetStartedModal />, { wrapper: MemoryRouter });
+
+ await waitFor(() =>
+ expect(mockUpdateStateConfirmed).toHaveBeenCalledOnce(),
+ );
+ await waitFor(() => expect(screen.queryByRole("dialog")).toBeNull());
+ expect(screen.queryByText("What do you want to automate?")).toBeNull();
+ expect(screen.queryByText("Pick a template to start")).toBeNull();
+ expect(screen.queryByText("copilot-header")).toBeNull();
+ },
+ );
+
+ it("keeps editor-only final steps and existing responses closed", async () => {
+ stateOverrides.current = {
+ user_intent: "fill_forms",
+ questionnaire: null,
+ };
+ const { unmount } = render(<GetStartedModal />, {
+ wrapper: MemoryRouter,
+ });
+
+ expect(await screen.findByText("STEP 2 OF 2")).toBeTruthy();
+ expect(screen.getByText("FINAL STEP")).toBeTruthy();
+ expect(screen.queryByText("OPTIONAL")).toBeNull();
+ unmount();
+ mockUpdateStateConfirmed.mockClear();
+
+ stateOverrides.current = {
+ user_intent: "fill_forms",
+ questionnaire: completedQuestionnaire,
+ };
+ render(<GetStartedModal />, { wrapper: MemoryRouter });
+
+ expect(screen.queryByRole("dialog")).toBeNull();
+ expect(mockUpdateStateConfirmed).not.toHaveBeenCalled();
+ });
+
+ it("marks the editor second step as final", async () => {
+ await renderTemplatesStep();
+ expect(screen.getByText("STEP 2 OF 2")).toBeTruthy();
+ expect(screen.getByText("FINAL STEP")).toBeTruthy();
+ });
});
describe("GetStartedModal skip-while-creating guard", () => {
- it("blocks Skip while a template workflow creation is in flight", () => {
+ it("blocks Skip while a template workflow creation is in flight", async () => {
mutationState.isPending = true;
- render(<GetStartedModal hasWorkflows={false} isLoading={false} />);
+ await renderTemplatesStep();
const skip = screen.getByRole("button", { name: "Skip" });
expect((skip as HTMLButtonElement).disabled).toBe(true);
fireEvent.click(skip);
@@ -102,9 +242,9 @@ describe("GetStartedModal skip-while-creating guard", () => {
);
});
- it("dismisses on Skip when no creation is pending", () => {
+ it("dismisses on Skip when no creation is pending", async () => {
mutationState.isPending = false;
- render(<GetStartedModal hasWorkflows={false} isLoading={false} />);
+ await renderTemplatesStep();
fireEvent.click(screen.getByRole("button", { name: "Skip" }));
expect(mockTelemetry.modalSkipped).toHaveBeenCalledTimes(1);
expect(mockUpdateState).toHaveBeenCalledWith(
@@ -112,9 +252,13 @@ describe("GetStartedModal skip-while-creating guard", () => {
);
});
- it("ignores skip and Escape-close while the copilot step reports busy", () => {
+ it("ignores skip and Escape-close while the copilot step reports busy", async () => {
flagState.variant = "copilot-first";
- render(<GetStartedModal hasWorkflows={false} isLoading={false} />);
+ await renderTemplatesStep();
+ const chrome = screen.getByTestId("copilot-chrome");
+ expect(chrome.children).toHaveLength(3);
+ expect(screen.getByText("STEP 2 OF 2")).toBeTruthy();
+ expect(screen.getByText("FINAL STEP")).toBeTruthy();
fireEvent.click(screen.getByRole("button", { name: "child-skip" }));
fireEvent.keyDown(document, { key: "Escape" });
diff --git a/skyvern-frontend/src/components/onboarding/GetStartedModal.tsx b/skyvern-frontend/src/components/onboarding/GetStartedModal.tsx
index dfb6cbab3..36285710a 100644
--- a/skyvern-frontend/src/components/onboarding/GetStartedModal.tsx
+++ b/skyvern-frontend/src/components/onboarding/GetStartedModal.tsx
@@ -1,5 +1,7 @@
-import { useEffect, useRef, useState } from "react";
+import { ReloadIcon } from "@radix-ui/react-icons";
+import { useEffect, useLayoutEffect, useRef, useState } from "react";
import { useFeatureFlagVariantKey } from "posthog-js/react";
+import { useAuth } from "@clerk/clerk-react";
import {
Dialog,
DialogContent,
@@ -8,9 +10,16 @@ import {
DialogHeader,
DialogTitle,
} from "@/components/ui/dialog";
+import { Alert, AlertDescription } from "@/components/ui/alert";
import { Button } from "@/components/ui/button";
import { Skeleton } from "@/components/ui/skeleton";
import { useOnboardingState } from "@/store/onboarding/useOnboardingState";
+import {
+ isQuestionnaireUserIntentV1,
+ type QuestionnaireAnswersV1,
+ type QuestionnairePatchV1,
+ type QuestionnaireStateV1,
+} from "@/store/onboarding/types";
import { OnboardingTelemetry } from "@/util/onboarding/OnboardingTelemetry";
import { ClickIcon } from "@/components/icons/ClickIcon";
import { ExtractIcon } from "@/components/icons/ExtractIcon";
@@ -27,6 +36,11 @@ import {
getSetupTime,
} from "./templateUtils";
import { CopilotCTAStep } from "./CopilotCTAStep";
+import { QuestionnaireDetailsStep } from "./QuestionnaireDetailsStep";
+import { QuestionnaireNextStepsCard } from "./QuestionnaireNextStepsCard";
+import { OnboardingOptionRow } from "./OnboardingOptionRow";
+import { OnboardingStepProgress } from "./OnboardingStepProgress";
+import { OnboardingStepShell } from "./OnboardingStepShell";
import {
type ABVariant,
DEFAULT_VARIANT,
@@ -35,9 +49,20 @@ import {
EXPERIMENT,
} from "@/util/onboarding/experimentConfig";
-const SURFACE = "dashboard" as const;
+const SURFACE = "discover" as const;
-type Step = "intent" | "templates";
+type EditorStep = "intent" | "templates";
+type DiscoverOnboardingOwner =
+ | { kind: "deciding" }
+ | { kind: "questionnaire"; step: "intent" }
+ | { kind: "questionnaire"; step: "details" }
+ | {
+ kind: "questionnaire";
+ step: "recommendations";
+ answers: QuestionnaireAnswersV1;
+ }
+ | { kind: "editor" }
+ | { kind: "closed" };
type IntentOption = {
id: string;
@@ -73,11 +98,6 @@ const intentOptions: IntentOption[] = [
},
];
-type Props = {
- hasWorkflows: boolean;
- isLoading: boolean;
-};
-
function resolveVariant(
stateVariant: string | null | undefined,
flagVariant: string | boolean | undefined,
@@ -90,14 +110,67 @@ function resolveVariant(
: DEFAULT_VARIANT;
}
-function GetStartedModal({ hasWorkflows, isLoading }: Readonly<Props>) {
- const { state, updateState } = useOnboardingState();
+function answersFromQuestionnaire(
+ questionnaire: QuestionnaireStateV1 | null,
+): QuestionnaireAnswersV1 | null {
+ if (!questionnaire) return null;
+ const { role, company_context, scale_intent, referral_source } =
+ questionnaire;
+ return role && company_context && scale_intent && referral_source
+ ? { role, company_context, scale_intent, referral_source }
+ : null;
+}
+
+function questionnaireTerminalOwner(
+ questionnaire: QuestionnaireStateV1,
+): DiscoverOnboardingOwner {
+ const answers =
+ questionnaire.status === "completed"
+ ? answersFromQuestionnaire(questionnaire)
+ : null;
+ return answers
+ ? { kind: "questionnaire", step: "recommendations", answers }
+ : { kind: "closed" };
+}
+
+function GetStartedModalForUser() {
+ const { state, isLoading, isNewUser, updateState, updateStateConfirmed } =
+ useOnboardingState();
const flagVariant = useFeatureFlagVariantKey(EXPERIMENT.flagKey);
- const [step, setStep] = useState<Step>("intent");
+ const [owner, setOwner] = useState<DiscoverOnboardingOwner>({
+ kind: "deciding",
+ });
+ const questionnaireOwner = owner.kind === "questionnaire";
+ const [step, setStep] = useState<EditorStep>("intent");
const [selectedIntent, setSelectedIntent] = useState<string | null>(null);
+ const [questionnaire, setQuestionnaire] =
+ useState<QuestionnaireStateV1 | null>(null);
+ const [intentPending, setIntentPending] = useState(false);
+ const [questionnairePending, setQuestionnairePending] = useState(false);
+ const [intentError, setIntentError] = useState<string | null>(null);
const [copilotStepBusy, setCopilotStepBusy] = useState(false);
const openedRef = useRef(false);
const variantAssignedRef = useRef(false);
+ const confirmedEventsRef = useRef(new Set<string>());
+ const openVisitRef = useRef(0);
+ const isOpenRef = useRef(false);
+ const reservationStartedRef = useRef(false);
+ const reservationEditorStateRef = useRef<
+ readonly [string | null, string | null, string | null] | null
+ >(null);
+ const ownerGenerationRef = useRef(0);
+ const mountedRef = useRef(true);
+ const latestStateRef = useRef(state);
+ const questionnaireObservedDuringReservationRef = useRef(false);
+ latestStateRef.current = state;
+ const initialSkipMutationIdRef = useRef(crypto.randomUUID());
+
+ useEffect(() => {
+ mountedRef.current = true;
+ return () => {
+ mountedRef.current = false;
+ };
+ }, []);
const variant = resolveVariant(state?.ab_variant, flagVariant);
@@ -106,61 +179,344 @@ function GetStartedModal({ hasWorkflows, isLoading }: Readonly<Props>) {
const createWorkflowMutation = useCreateWorkflowMutation();
const onboardingEnabled = isABVariant(flagVariant);
-
- const isOpen =
+ const editorOpen =
+ owner.kind === "editor" &&
onboardingEnabled &&
- !isLoading &&
- !hasWorkflows &&
state !== null &&
state.modal_dismissed_at === null &&
- state.first_save_at === null;
-
- useEffect(() => {
- if (state?.user_intent && state.modal_dismissed_at === null) {
- setSelectedIntent(state.user_intent);
- setStep("templates");
+ state.first_save_at === null &&
+ state.questionnaire_prompted_at == null &&
+ state.questionnaire == null &&
+ (isOpenRef.current || isNewUser);
+ const reservationCandidate =
+ owner.kind === "deciding" &&
+ !isLoading &&
+ state !== null &&
+ state.questionnaire_prompted_at == null &&
+ state.questionnaire == null;
+ const decidingOpen = reservationCandidate;
+ const ownedOpen = questionnaireOwner || editorOpen;
+ const isOpen = decidingOpen || ownedOpen;
+ useLayoutEffect(() => {
+ if (ownedOpen && !isOpenRef.current) openVisitRef.current += 1;
+ isOpenRef.current = ownedOpen;
+ }, [ownedOpen]);
+ useLayoutEffect(() => {
+ if (!state) return;
+ const editorState = [
+ state.modal_dismissed_at,
+ state.first_save_at,
+ state.user_intent,
+ ] as const;
+ if (
+ owner.kind === "deciding" &&
+ reservationStartedRef.current &&
+ (state.questionnaire_prompted_at || state.questionnaire)
+ ) {
+ questionnaireObservedDuringReservationRef.current = true;
}
- }, [state?.user_intent, state?.modal_dismissed_at]);
+ const reservationEditorState = reservationEditorStateRef.current;
+ if (
+ owner.kind === "deciding" &&
+ reservationStartedRef.current &&
+ reservationEditorState &&
+ (editorState[0] !== reservationEditorState[0] ||
+ editorState[1] !== reservationEditorState[1])
+ ) {
+ ownerGenerationRef.current += 1;
+ setOwner({ kind: "closed" });
+ return;
+ }
+ if (owner.kind !== "deciding" || isLoading) {
+ return;
+ }
+ if (reservationStartedRef.current) {
+ return;
+ }
+ if (!reservationCandidate) {
+ setOwner({ kind: "closed" });
+ return;
+ }
+ reservationStartedRef.current = true;
+ reservationEditorStateRef.current = editorState;
+ const generation = ++ownerGenerationRef.current;
+ void updateStateConfirmed({
+ questionnaire_prompt: { version: 1, action: "reserve" },
+ })
+ .then((response) => {
+ if (!mountedRef.current || generation !== ownerGenerationRef.current)
+ return;
+ if ("code" in response) {
+ setOwner({ kind: "closed" });
+ return;
+ }
+ const result = response.questionnaire_prompt_result;
+ if (
+ result?.status === "reserved" &&
+ typeof result.prompted_at === "string" &&
+ result.prompted_at.length > 0
+ ) {
+ OnboardingTelemetry.questionnaireShown({
+ primaryIntent: null,
+ promptReason: "initial",
+ });
+ setOwner({ kind: "questionnaire", step: "intent" });
+ } else if (
+ result?.status === "flag_disabled" ||
+ result?.status === "ineligible"
+ ) {
+ const latestState = latestStateRef.current;
+ if (
+ questionnaireObservedDuringReservationRef.current ||
+ !latestState ||
+ latestState.questionnaire_prompted_at ||
+ latestState.questionnaire ||
+ latestState.modal_dismissed_at !== null ||
+ latestState.first_save_at !== null
+ ) {
+ setOwner({ kind: "closed" });
+ return;
+ }
+ const fallbackIntent =
+ latestState.user_intent ??
+ reservationEditorStateRef.current?.[2] ??
+ null;
+ if (fallbackIntent) {
+ setSelectedIntent(fallbackIntent);
+ setStep("templates");
+ }
+ setOwner({ kind: "editor" });
+ } else {
+ setOwner({ kind: "closed" });
+ }
+ })
+ .catch(() => {
+ if (mountedRef.current && generation === ownerGenerationRef.current) {
+ setOwner({ kind: "closed" });
+ }
+ });
+ }, [
+ isLoading,
+ owner.kind,
+ reservationCandidate,
+ state,
+ updateStateConfirmed,
+ ]);
useEffect(() => {
- if (isOpen && !openedRef.current) {
+ if (isOpen && owner.kind !== "deciding" && !openedRef.current) {
openedRef.current = true;
- OnboardingTelemetry.registerVariant(variant);
+ if (owner.kind === "editor") {
+ OnboardingTelemetry.registerVariant(variant);
+ }
OnboardingTelemetry.flowStarted(SURFACE);
OnboardingTelemetry.modalOpened(SURFACE);
}
- }, [isOpen, variant]);
+ }, [isOpen, owner.kind, variant]);
useEffect(() => {
- if (!state || state.ab_variant !== null || variantAssignedRef.current)
+ if (
+ owner.kind !== "editor" ||
+ !state ||
+ state.ab_variant !== null ||
+ variantAssignedRef.current
+ )
return;
// only persist a variant once the flag resolves to a real arm; an unloaded/disabled flag (pre-load, 0% rollout, rollback) must not bias the split
if (!isABVariant(flagVariant)) return;
variantAssignedRef.current = true;
updateState({ ab_variant: variant });
OnboardingTelemetry.abVariantAssigned(SURFACE, variant);
- }, [state, variant, flagVariant, updateState]);
+ }, [owner.kind, state, variant, flagVariant, updateState]);
function handleSelectIntent(intentId: string) {
+ if (intentPending) return;
setSelectedIntent(intentId);
}
- function handleContinue() {
- if (!selectedIntent) return;
- updateState({ user_intent: selectedIntent });
- setStep("templates");
+ async function handleContinue() {
+ if (!selectedIntent || intentPending) {
+ return;
+ }
+ setIntentError(null);
+ if (owner.kind === "editor") {
+ updateState({ user_intent: selectedIntent });
+ setStep("templates");
+ return;
+ }
+ if (
+ owner.kind !== "questionnaire" ||
+ !isQuestionnaireUserIntentV1(selectedIntent)
+ ) {
+ setIntentError("We couldn't save your choice. Try again.");
+ return;
+ }
+
+ const visitId = openVisitRef.current;
+ setIntentPending(true);
+ try {
+ const response = await updateStateConfirmed({
+ user_intent: selectedIntent,
+ });
+ if ("code" in response) {
+ throw new Error(`Intent confirmation failed: ${response.code}`);
+ }
+ if (!isOpenRef.current || visitId !== openVisitRef.current) {
+ return;
+ }
+ const nextState = response.onboarding_state;
+ if (!isQuestionnaireUserIntentV1(nextState.user_intent)) {
+ setOwner({ kind: "closed" });
+ return;
+ }
+ const confirmedQuestionnaire = nextState.questionnaire ?? null;
+ if (confirmedQuestionnaire !== null) {
+ if (questionnaire?.response_id !== confirmedQuestionnaire.response_id) {
+ setOwner({ kind: "closed" });
+ return;
+ }
+ setQuestionnaire(confirmedQuestionnaire);
+ setOwner(questionnaireTerminalOwner(confirmedQuestionnaire));
+ return;
+ }
+ setOwner({ kind: "questionnaire", step: "details" });
+ } catch {
+ if (isOpenRef.current && visitId === openVisitRef.current) {
+ setIntentError("We couldn't save your choice. Try again.");
+ }
+ } finally {
+ setIntentPending(false);
+ }
}
function handleBack() {
+ if (owner.kind === "questionnaire") {
+ setOwner(
+ owner.step === "recommendations"
+ ? { kind: "questionnaire", step: "details" }
+ : { kind: "questionnaire", step: "intent" },
+ );
+ return;
+ }
setStep("intent");
}
function handleSkip() {
- if (createWorkflowMutation.isPending || copilotStepBusy) return;
+ if (owner.kind === "deciding" || intentPending || questionnairePending)
+ return;
+ if (owner.kind === "questionnaire") {
+ if (questionnaire !== null) {
+ OnboardingTelemetry.modalSkipped(SURFACE);
+ updateState({ modal_dismissed_at: new Date().toISOString() });
+ setOwner({ kind: "closed" });
+ return;
+ }
+ setIntentError(null);
+ void handleQuestionnaireAction({
+ version: 1,
+ mutation_id: initialSkipMutationIdRef.current,
+ expected_revision: 0,
+ action: "skip",
+ }).catch(() =>
+ setIntentError("We couldn't save your choice. Try again."),
+ );
+ return;
+ }
+ if (createWorkflowMutation.isPending || copilotStepBusy) {
+ return;
+ }
OnboardingTelemetry.modalSkipped(SURFACE);
updateState({ modal_dismissed_at: new Date().toISOString() });
}
+ function emitQuestionnaireEvent(
+ patch: QuestionnairePatchV1,
+ previousQuestionnaire: QuestionnaireStateV1 | null,
+ nextQuestionnaire: QuestionnaireStateV1,
+ primaryIntent: string | null,
+ ) {
+ if (nextQuestionnaire.last_mutation_id !== patch.mutation_id) return;
+ const eventName = `onboarding_questionnaire_${
+ patch.action === "skip"
+ ? "skipped"
+ : patch.action === "complete"
+ ? "completed"
+ : "updated"
+ }`;
+ const eventKey = `${nextQuestionnaire.response_id}:${nextQuestionnaire.revision}:${eventName}`;
+ if (confirmedEventsRef.current.has(eventKey)) return;
+ if (patch.action === "skip") {
+ if (nextQuestionnaire.status !== "skipped") return;
+ confirmedEventsRef.current.add(eventKey);
+ OnboardingTelemetry.questionnaireSkipped({
+ responseId: nextQuestionnaire.response_id,
+ revision: nextQuestionnaire.revision,
+ disposition: "skip",
+ statusAfter: "skipped",
+ });
+ return;
+ }
+ if (!isQuestionnaireUserIntentV1(primaryIntent)) return;
+ const answers = answersFromQuestionnaire(nextQuestionnaire);
+ if (nextQuestionnaire.status !== "completed" || !answers) return;
+
+ if (patch.action === "complete") {
+ confirmedEventsRef.current.add(eventKey);
+ OnboardingTelemetry.questionnaireCompleted({
+ responseId: nextQuestionnaire.response_id,
+ revision: nextQuestionnaire.revision,
+ primaryIntent,
+ answers,
+ });
+ return;
+ }
+ if (!previousQuestionnaire) return;
+ confirmedEventsRef.current.add(eventKey);
+ OnboardingTelemetry.questionnaireUpdated({
+ responseId: nextQuestionnaire.response_id,
+ revision: nextQuestionnaire.revision,
+ primaryIntent,
+ previousStatus: previousQuestionnaire.status,
+ answers,
+ });
+ }
+
+ async function handleQuestionnaireAction(patch: QuestionnairePatchV1) {
+ if (!questionnaireOwner) {
+ throw new Error("Questionnaire visit is closed");
+ }
+ const visitId = openVisitRef.current;
+ const previousQuestionnaire = questionnaire;
+ setIntentError(null);
+ setQuestionnairePending(true);
+ try {
+ const response = await updateStateConfirmed({ questionnaire: patch });
+ if ("code" in response) {
+ throw new Error(`Questionnaire confirmation failed: ${response.code}`);
+ }
+ if (!isOpenRef.current || visitId !== openVisitRef.current) {
+ return;
+ }
+ const nextQuestionnaire = response.onboarding_state.questionnaire;
+ if (!nextQuestionnaire) {
+ throw new Error("Questionnaire confirmation was missing");
+ }
+ emitQuestionnaireEvent(
+ patch,
+ previousQuestionnaire,
+ nextQuestionnaire,
+ response.onboarding_state.user_intent,
+ );
+ setQuestionnaire(nextQuestionnaire);
+ setOwner(
+ patch.action === "skip"
+ ? { kind: "closed" }
+ : questionnaireTerminalOwner(nextQuestionnaire),
+ );
+ } finally {
+ setQuestionnairePending(false);
+ }
+ }
function handleTemplateSelect(template: WorkflowApiResponse) {
if (createWorkflowMutation.isPending) return;
OnboardingTelemetry.modalTemplateSelected(
@@ -173,8 +529,8 @@ function GetStartedModal({ hasWorkflows, isLoading }: Readonly<Props>) {
title: `${template.title} (copy)`,
});
// Completion telemetry fires from useCreateWorkflowMutation (it owns the
- // navigation that unmounts this modal); modal re-display is gated by
- // first_save_at + hasWorkflows, so no dismiss write is needed here.
+ // navigation that unmounts this modal); first_save_at prevents re-display,
+ // so no dismiss write is needed here.
createWorkflowMutation.mutate({ ...cloned, _via: "onboarding_template" });
}
@@ -182,17 +538,35 @@ function GetStartedModal({ hasWorkflows, isLoading }: Readonly<Props>) {
selectedIntent && globalTemplates.length > 0
? getTemplatesForIntent(globalTemplates, selectedIntent)
: [];
+ const stepCount = questionnaireOwner ? 3 : 2;
+ const view =
+ owner.kind === "questionnaire"
+ ? owner.step
+ : owner.kind === "editor" && editorOpen
+ ? step
+ : null;
return (
<Dialog open={isOpen} onOpenChange={() => handleSkip()}>
<DialogContent
- className="max-w-xl"
+ className="z-[2147480003] grid max-h-[calc(100dvh-2rem)] max-w-xl grid-rows-[minmax(0,1fr)] overflow-hidden overscroll-contain [&>button]:right-2 [&>button]:top-2 [&>button]:inline-flex [&>button]:size-11 [&>button]:touch-manipulation [&>button]:items-center [&>button]:justify-center [&>button]:motion-reduce:transition-none"
onPointerDownOutside={(e) => e.preventDefault()}
>
- {step === "intent" ? (
- <>
- <DialogHeader>
- <DialogTitle className="text-xl">
+ {view === null ? (
+ owner.kind === "deciding" && decidingOpen ? (
+ <DialogHeader className="pr-12">
+ <DialogTitle className="text-xl font-semibold">
+ Getting started
+ </DialogTitle>
+ <DialogDescription>
+ Checking your onboarding setup.
+ </DialogDescription>
+ </DialogHeader>
+ ) : null
+ ) : view === "intent" ? (
+ <OnboardingStepShell stepIndex={1} stepCount={stepCount}>
+ <DialogHeader className="pr-12">
+ <DialogTitle className="text-xl font-semibold">
What do you want to automate?
</DialogTitle>
<DialogDescription>
@@ -200,114 +574,142 @@ function GetStartedModal({ hasWorkflows, isLoading }: Readonly<Props>) {
change this later.
</DialogDescription>
</DialogHeader>
- <div className="grid grid-cols-2 gap-3 py-2">
- {intentOptions.map((option) => {
- const Icon = option.icon;
- const isSelected = selectedIntent === option.id;
- return (
- <button
- key={option.id}
- type="button"
- onClick={() => handleSelectIntent(option.id)}
- className={cn(
- "flex flex-col items-start gap-2 rounded-lg border p-4 text-left transition-colors hover:bg-muted/50",
- isSelected
- ? "border-primary bg-primary/5"
- : "border-border",
- )}
- >
- <Icon className="h-6 w-6 text-primary" />
- <div>
- <p className="text-sm font-medium">{option.label}</p>
- <p className="text-xs text-muted-foreground">
- {option.description}
- </p>
- </div>
- </button>
- );
- })}
+ <div className="flex min-h-0 flex-col gap-2 overflow-y-auto overscroll-contain pr-1">
+ {intentOptions.map((option) => (
+ <OnboardingOptionRow
+ key={option.id}
+ icon={option.icon}
+ label={option.label}
+ description={option.description}
+ selected={selectedIntent === option.id}
+ disabled={intentPending}
+ onClick={() => handleSelectIntent(option.id)}
+ />
+ ))}
</div>
- <DialogFooter className="gap-2 sm:gap-0">
- <Button variant="ghost" size="sm" onClick={handleSkip}>
+ {intentError ? (
+ <Alert role="status" aria-live="polite" variant="destructive">
+ <AlertDescription>{intentError}</AlertDescription>
+ </Alert>
+ ) : null}
+ <DialogFooter className="sticky bottom-0 z-10 -mx-6 -mb-6 flex-col gap-2 border-t border-border bg-background px-6 pb-[max(1rem,env(safe-area-inset-bottom))] pt-4 sm:flex-row sm:justify-between sm:gap-0 sm:space-x-0">
+ <Button
+ variant="ghost"
+ size="sm"
+ className="min-h-11 w-full min-w-11 touch-manipulation motion-reduce:transition-none sm:w-auto"
+ onClick={handleSkip}
+ disabled={intentPending}
+ >
Skip
</Button>
<Button
size="sm"
- disabled={!selectedIntent}
- onClick={handleContinue}
+ className="min-h-11 w-full min-w-11 touch-manipulation motion-reduce:transition-none sm:w-auto"
+ disabled={!selectedIntent || intentPending}
+ onClick={() => void handleContinue()}
>
+ {intentPending ? (
+ <ReloadIcon
+ aria-hidden
+ className="mr-2 size-4 animate-spin motion-reduce:animate-none"
+ />
+ ) : null}
Continue
</Button>
</DialogFooter>
- </>
- ) : variant === VARIANTS.COPILOT_FIRST ? (
- <CopilotCTAStep
- selectedIntent={selectedIntent!}
+ </OnboardingStepShell>
+ ) : owner.kind === "questionnaire" && owner.step === "details" ? (
+ <QuestionnaireDetailsStep
+ completionAction={questionnaire ? "update" : "complete"}
+ expectedRevision={questionnaire?.revision ?? 0}
+ initialAnswers={answersFromQuestionnaire(questionnaire)}
+ externalError={intentError}
+ isPending={questionnairePending}
+ onAction={handleQuestionnaireAction}
+ onBack={handleBack}
+ />
+ ) : owner.kind === "questionnaire" &&
+ owner.step === "recommendations" ? (
+ <QuestionnaireNextStepsCard
+ answers={owner.answers}
+ onAction={() => {
+ updateState({ modal_dismissed_at: new Date().toISOString() });
+ setOwner({ kind: "closed" });
+ }}
onBack={handleBack}
onSkip={handleSkip}
- onDismiss={() =>
- updateState({ modal_dismissed_at: new Date().toISOString() })
- }
- onBusyChange={setCopilotStepBusy}
/>
+ ) : variant === VARIANTS.COPILOT_FIRST ? (
+ <div className="grid min-h-0 grid-rows-[auto_minmax(0,1fr)] gap-4">
+ <OnboardingStepProgress
+ stepIndex={stepCount}
+ stepCount={stepCount}
+ chip="final"
+ />
+ <div
+ className={cn(
+ "grid min-h-0 grid-rows-[auto_minmax(0,1fr)_auto] gap-4 [&>div:first-child]:pr-12 [&>div:nth-child(2)]:min-h-0 [&>div:nth-child(2)]:overflow-y-auto [&>div:nth-child(2)]:overscroll-contain [&>div:nth-child(2)_.animate-spin]:motion-reduce:animate-none",
+ "[&>div:nth-child(2)>button]:min-h-[3.5rem] [&>div:nth-child(2)>button]:touch-manipulation [&>div:nth-child(2)>button]:flex-row [&>div:nth-child(2)>button]:flex-wrap [&>div:nth-child(2)>button]:items-center [&>div:nth-child(2)>button]:py-3 [&>div:nth-child(2)>button]:motion-reduce:transition-none [&>div:nth-child(2)>div]:h-[3.5rem] [&>div:nth-child(2)>p]:col-span-1 [&>div:nth-child(2)]:grid-cols-1",
+ "[&>div:nth-child(2)>button>div]:flex-1 [&>div:nth-child(2)>button>div]:basis-[calc(100%-2rem)] [&>div:nth-child(2)>button>div]:sm:basis-0 [&>div:nth-child(2)>button>svg]:h-5 [&>div:nth-child(2)>button>svg]:w-5 [&>div:nth-child(2)>button>svg]:shrink-0",
+ "[&>div:nth-child(2)>button>span]:basis-full [&>div:nth-child(2)>button>span]:pl-8 [&>div:nth-child(2)>button>span]:tabular-nums [&>div:nth-child(2)>button>span]:sm:ml-auto [&>div:nth-child(2)>button>span]:sm:basis-auto [&>div:nth-child(2)>button>span]:sm:pl-0 [&>div:nth-child(2)>button>span]:sm:text-right",
+ "[&>div:last-child]:sticky [&>div:last-child]:bottom-0 [&>div:last-child]:z-10 [&>div:last-child]:-mx-6 [&>div:last-child]:-mb-6 [&>div:last-child]:border-t [&>div:last-child]:border-border [&>div:last-child]:bg-background [&>div:last-child]:px-6 [&>div:last-child]:pb-[max(1rem,env(safe-area-inset-bottom))] [&>div:last-child]:pt-4",
+ "[&>div:last-child_button]:min-h-11 [&>div:last-child_button]:w-full [&>div:last-child_button]:min-w-11 [&>div:last-child_button]:touch-manipulation [&>div:last-child_button]:motion-reduce:transition-none [&>div:last-child_button]:sm:w-auto",
+ )}
+ data-testid="copilot-chrome"
+ >
+ <CopilotCTAStep
+ selectedIntent={selectedIntent!}
+ onBack={handleBack}
+ onSkip={handleSkip}
+ onDismiss={() =>
+ updateState({ modal_dismissed_at: new Date().toISOString() })
+ }
+ onBusyChange={setCopilotStepBusy}
+ />
+ </div>
+ </div>
) : (
- <>
- <DialogHeader>
- <DialogTitle className="text-xl">
+ <OnboardingStepShell
+ stepIndex={stepCount}
+ stepCount={stepCount}
+ chip="final"
+ >
+ <DialogHeader className="pr-12">
+ <DialogTitle className="text-xl font-semibold">
Pick a template to start
</DialogTitle>
<DialogDescription>
Choose a pre-built workflow and customize it in the editor.
</DialogDescription>
</DialogHeader>
- <div className="grid grid-cols-2 gap-3 py-2">
+ <div className="flex min-h-0 flex-col gap-2 overflow-y-auto overscroll-contain pr-1">
{templatesLoading ? (
Array.from({ length: 4 }).map((_, i) => (
- <Skeleton key={i} className="h-28 rounded-lg" />
+ <Skeleton key={i} className="h-[3.5rem] rounded-lg" />
))
) : filteredTemplates.length > 0 ? (
- filteredTemplates.map((template) => {
- const Icon = getTemplateIcon(template);
- return (
- <button
- key={template.workflow_permanent_id}
- type="button"
- disabled={createWorkflowMutation.isPending}
- onClick={() => handleTemplateSelect(template)}
- className={cn(
- "flex flex-col items-start gap-2 rounded-lg border border-border p-4 text-left transition-colors",
- "hover:border-primary hover:bg-primary/5",
- createWorkflowMutation.isPending &&
- "pointer-events-none opacity-50",
- )}
- >
- <Icon className="h-6 w-6 text-primary" />
- <div className="min-w-0 self-stretch">
- <p className="truncate text-sm font-medium">
- {template.title}
- </p>
- {template.description && (
- <p className="line-clamp-2 text-xs text-muted-foreground">
- {template.description}
- </p>
- )}
- </div>
- <span className="text-xs text-muted-foreground">
- ~{getSetupTime(template)} setup
- </span>
- </button>
- );
- })
+ filteredTemplates.map((template) => (
+ <OnboardingOptionRow
+ key={template.workflow_permanent_id}
+ icon={getTemplateIcon(template)}
+ label={template.title}
+ description={template.description}
+ meta={`~${getSetupTime(template)} setup`}
+ disabled={createWorkflowMutation.isPending}
+ onClick={() => handleTemplateSelect(template)}
+ />
+ ))
) : (
- <p className="col-span-2 py-8 text-center text-sm text-muted-foreground">
+ <p className="py-8 text-center text-sm text-muted-foreground">
No templates available yet.
</p>
)}
</div>
- <DialogFooter className="gap-2 sm:gap-0">
+ <DialogFooter className="sticky bottom-0 z-10 -mx-6 -mb-6 flex-col gap-2 border-t border-border bg-background px-6 pb-[max(1rem,env(safe-area-inset-bottom))] pt-4 sm:flex-row sm:justify-between sm:gap-0 sm:space-x-0">
<Button
variant="ghost"
size="sm"
+ className="min-h-11 w-full min-w-11 touch-manipulation motion-reduce:transition-none sm:w-auto"
onClick={handleBack}
disabled={createWorkflowMutation.isPending}
>
@@ -316,17 +718,23 @@ function GetStartedModal({ hasWorkflows, isLoading }: Readonly<Props>) {
<Button
variant="ghost"
size="sm"
+ className="min-h-11 w-full min-w-11 touch-manipulation motion-reduce:transition-none sm:w-auto"
onClick={handleSkip}
disabled={createWorkflowMutation.isPending}
>
Skip
</Button>
</DialogFooter>
- </>
+ </OnboardingStepShell>
)}
</DialogContent>
</Dialog>
);
}
+function GetStartedModal() {
+ const { userId } = useAuth();
+ return <GetStartedModalForUser key={userId ?? "signed-out"} />;
+}
+
export { GetStartedModal };
diff --git a/skyvern-frontend/src/components/onboarding/OnboardingOptionRow.tsx b/skyvern-frontend/src/components/onboarding/OnboardingOptionRow.tsx
new file mode 100644
index 000000000..c6c830457
--- /dev/null
+++ b/skyvern-frontend/src/components/onboarding/OnboardingOptionRow.tsx
@@ -0,0 +1,60 @@
+import type { ComponentType, ReactNode } from "react";
+import { cn } from "@/util/utils";
+
+type Props = {
+ icon?: ComponentType<{ className?: string }>;
+ label: string;
+ description?: string;
+ meta?: ReactNode;
+ selected?: boolean;
+ disabled?: boolean;
+ onClick: () => void;
+};
+
+function OnboardingOptionRow(props: Readonly<Props>) {
+ const {
+ icon: Icon,
+ label,
+ description,
+ meta,
+ selected,
+ disabled,
+ onClick,
+ } = props;
+ return (
+ <button
+ type="button"
+ aria-pressed={selected}
+ disabled={disabled}
+ onClick={onClick}
+ className={cn(
+ "flex min-h-[3.5rem] w-full touch-manipulation flex-wrap items-center gap-x-3 gap-y-1 rounded-lg border px-4 py-3 text-left transition-colors focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 focus-visible:ring-offset-background motion-reduce:transition-none",
+ selected
+ ? "border-2 border-primary bg-primary/5 px-[15px] py-[11px]"
+ : "border-border hover:border-primary/60 hover:bg-muted/50",
+ disabled && "pointer-events-none opacity-50",
+ )}
+ >
+ {Icon ? (
+ <span aria-hidden="true" className="shrink-0">
+ <Icon className="h-5 w-5 text-primary" />
+ </span>
+ ) : null}
+ <div className="min-w-0 flex-1 basis-[calc(100%-2rem)] sm:basis-0">
+ <p className="truncate text-sm font-medium">{label}</p>
+ {description ? (
+ <p className="line-clamp-2 text-xs text-muted-foreground">
+ {description}
+ </p>
+ ) : null}
+ </div>
+ {meta ? (
+ <span className="basis-full pl-8 text-xs tabular-nums text-muted-foreground sm:ml-auto sm:basis-auto sm:pl-0 sm:text-right">
+ {meta}
+ </span>
+ ) : null}
+ </button>
+ );
+}
+
+export { OnboardingOptionRow };
diff --git a/skyvern-frontend/src/components/onboarding/OnboardingProgressCard.test.tsx b/skyvern-frontend/src/components/onboarding/OnboardingProgressCard.test.tsx
new file mode 100644
index 000000000..edc788386
--- /dev/null
+++ b/skyvern-frontend/src/components/onboarding/OnboardingProgressCard.test.tsx
@@ -0,0 +1,63 @@
+import { fireEvent, render, screen } from "@testing-library/react";
+import { MemoryRouter } from "react-router-dom";
+import { expect, it, vi } from "vitest";
+import { OnboardingProgressCard } from "./OnboardingProgressCard";
+
+const forbiddenCopy =
+ /heuristic|reward|credential|api|mcp|channel|schedule|questionnaire|social|follow|role|company|referral|credits?|points?|survey/i;
+it.each([
+ [
+ 0,
+ false,
+ "first_agent_created",
+ "Use the working example",
+ "#working-example-heading",
+ "How to build an agent",
+ "https://www.skyvern.com/docs/cloud/building-agents/build-an-agent",
+ ],
+ [
+ 1,
+ true,
+ "first_successful_run",
+ "Run agent",
+ "/agents",
+ "How to run an agent",
+ "https://www.skyvern.com/docs/cloud/building-agents/run-an-agent",
+ ],
+] as const)(
+ "renders %s progress with its primary destination",
+ (
+ completedCount,
+ firstMilestoneComplete,
+ nextActionKey,
+ primaryLabel,
+ href,
+ resourceLabel,
+ resourceHref,
+ ) => {
+ const onDismiss = vi.fn();
+ render(
+ <OnboardingProgressCard
+ state="active"
+ completedCount={completedCount}
+ firstMilestoneComplete={firstMilestoneComplete}
+ nextActionKey={nextActionKey}
+ isPending={false}
+ onDismiss={onDismiss}
+ />,
+ { wrapper: href === "/agents" ? MemoryRouter : undefined },
+ );
+ const primaryLink = screen.getByRole("link", { name: primaryLabel });
+ expect(primaryLink.getAttribute("href")).toBe(href);
+ const resourceLink = screen.getByRole("link", { name: resourceLabel });
+ expect(resourceLink.getAttribute("href")).toBe(resourceHref);
+ expect(screen.getByRole("region").textContent).not.toMatch(forbiddenCopy);
+ if (firstMilestoneComplete) {
+ expect(screen.getByText("Complete:").className).toContain("sr-only");
+ } else {
+ expect(screen.queryByText("Complete:")).toBeNull();
+ }
+ fireEvent.click(screen.getByRole("button", { name: "Hide setup" }));
+ expect(onDismiss).toHaveBeenCalledTimes(1);
+ },
+);
diff --git a/skyvern-frontend/src/components/onboarding/OnboardingProgressCard.tsx b/skyvern-frontend/src/components/onboarding/OnboardingProgressCard.tsx
new file mode 100644
index 000000000..ca04b066d
--- /dev/null
+++ b/skyvern-frontend/src/components/onboarding/OnboardingProgressCard.tsx
@@ -0,0 +1,191 @@
+import { ReloadIcon } from "@radix-ui/react-icons";
+
+import { Link } from "react-router-dom";
+import { Button } from "@/components/ui/button";
+
+type ProgressActionKey = "first_agent_created" | "first_successful_run";
+
+type ActiveProgressCardProps = {
+ state: "active";
+ completedCount: 0 | 1;
+ nextActionKey: ProgressActionKey;
+ firstMilestoneComplete: boolean;
+ isPending: boolean;
+ onDismiss: () => void;
+};
+
+type DismissedProgressCardProps = {
+ state: "dismissed";
+ isPending: boolean;
+ onRestore: () => void;
+};
+
+type OnboardingProgressCardProps =
+ | ActiveProgressCardProps
+ | DismissedProgressCardProps;
+
+const primaryActions = {
+ first_agent_created: {
+ label: "Use the working example",
+ href: "#working-example-heading",
+ resourceLabel: "How to build an agent",
+ resourceHref:
+ "https://www.skyvern.com/docs/cloud/building-agents/build-an-agent",
+ },
+ first_successful_run: {
+ label: "Run agent",
+ href: "/agents",
+ resourceLabel: "How to run an agent",
+ resourceHref:
+ "https://www.skyvern.com/docs/cloud/building-agents/run-an-agent",
+ },
+} satisfies Record<
+ ProgressActionKey,
+ {
+ label: string;
+ href: string;
+ resourceLabel: string;
+ resourceHref: string;
+ }
+>;
+
+function OnboardingProgressCard(props: OnboardingProgressCardProps) {
+ const activeProgress = props.state === "active" ? props : null;
+ const primaryAction = activeProgress
+ ? primaryActions[activeProgress.nextActionKey]
+ : null;
+ const firstMilestoneComplete =
+ activeProgress?.firstMilestoneComplete === true;
+ const handleVisibilityChange = () => {
+ if (props.isPending) return;
+ if (props.state === "active") {
+ props.onDismiss();
+ return;
+ }
+ props.onRestore();
+ };
+
+ return (
+ <div
+ className={
+ activeProgress
+ ? "relative rounded-lg border border-border bg-card px-4 py-4 shadow-sm sm:px-5"
+ : "flex justify-end"
+ }
+ >
+ <Button
+ type="button"
+ variant={props.isPending ? "disabled" : "ghost"}
+ className={`h-11 touch-manipulation text-muted-foreground hover:text-foreground ${
+ activeProgress ? "absolute right-4 top-4 sm:right-5" : ""
+ }`}
+ aria-disabled={props.isPending}
+ aria-busy={props.isPending}
+ onClick={handleVisibilityChange}
+ >
+ {props.isPending && (
+ <ReloadIcon
+ aria-hidden="true"
+ className="mr-2 h-4 w-4 motion-safe:animate-spin motion-reduce:animate-none"
+ />
+ )}
+ {activeProgress ? "Hide setup" : "Resume setup"}
+ </Button>
+
+ {activeProgress && primaryAction && (
+ <section
+ aria-labelledby="onboarding-progress-heading"
+ aria-busy={activeProgress.isPending}
+ >
+ <header className="pr-28">
+ <h2
+ id="onboarding-progress-heading"
+ className="text-base font-semibold tracking-tight"
+ >
+ Build your first agent
+ </h2>
+ <p className="mt-1 text-sm text-muted-foreground">
+ <span className="font-semibold text-foreground">
+ {activeProgress.completedCount} of 2
+ </span>{" "}
+ complete
+ </p>
+ </header>
+
+ <ol
+ aria-label="Setup milestones"
+ className="mt-4 grid gap-2 sm:grid-cols-2"
+ >
+ <li className="flex min-h-11 items-center gap-2 rounded-md border border-border/70 bg-muted/20 px-3 py-2 text-sm">
+ <span
+ aria-hidden="true"
+ className={`flex size-6 shrink-0 items-center justify-center rounded-full text-xs font-semibold ${
+ firstMilestoneComplete
+ ? "bg-badge-success text-foreground"
+ : "border border-border text-muted-foreground"
+ }`}
+ >
+ {firstMilestoneComplete ? "✓" : "1"}
+ </span>
+ <span
+ className={
+ firstMilestoneComplete
+ ? "text-muted-foreground"
+ : "font-medium text-foreground"
+ }
+ >
+ {firstMilestoneComplete && (
+ <span className="sr-only">Complete: </span>
+ )}
+ Create your first agent
+ </span>
+ </li>
+ <li className="flex min-h-11 items-center gap-2 rounded-md border border-border/70 bg-muted/20 px-3 py-2 text-sm">
+ <span
+ aria-hidden="true"
+ className="flex size-6 shrink-0 items-center justify-center rounded-full border border-border text-muted-foreground"
+ >
+ 2
+ </span>
+ <span className="font-medium text-foreground">
+ Run your first agent
+ </span>
+ </li>
+ </ol>
+
+ <div className="mt-4 flex flex-col items-start gap-2 sm:flex-row sm:items-center">
+ <Button
+ asChild
+ className="h-11 w-full touch-manipulation sm:w-auto"
+ >
+ {activeProgress.nextActionKey === "first_successful_run" ? (
+ <Link to={primaryAction.href}>{primaryAction.label}</Link>
+ ) : (
+ <a
+ href={primaryAction.href}
+ onClick={() => {
+ document
+ .getElementById("working-example-heading")
+ ?.focus({ preventScroll: true });
+ }}
+ >
+ {primaryAction.label}
+ </a>
+ )}
+ </Button>
+ <a
+ href={primaryAction.resourceHref}
+ target="_blank"
+ rel="noopener noreferrer"
+ className="inline-flex min-h-11 items-center rounded-md px-3 text-sm font-medium text-muted-foreground underline underline-offset-4 transition-colors hover:text-foreground focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-ring"
+ >
+ {primaryAction.resourceLabel}
+ </a>
+ </div>
+ </section>
+ )}
+ </div>
+ );
+}
+
+export { OnboardingProgressCard };
diff --git a/skyvern-frontend/src/components/onboarding/OnboardingStepProgress.test.tsx b/skyvern-frontend/src/components/onboarding/OnboardingStepProgress.test.tsx
new file mode 100644
index 000000000..81448fac8
--- /dev/null
+++ b/skyvern-frontend/src/components/onboarding/OnboardingStepProgress.test.tsx
@@ -0,0 +1,47 @@
+// @vitest-environment jsdom
+import { cleanup, render, screen } from "@testing-library/react";
+import { afterEach, describe, expect, it } from "vitest";
+import { OnboardingStepProgress } from "./OnboardingStepProgress";
+
+afterEach(cleanup);
+
+function expectDots(count: number, activeIndex: number) {
+ const dots = screen.getByTestId("onboarding-step-dots").children;
+ expect(dots).toHaveLength(count);
+ expect(
+ Array.from(dots).filter(
+ (dot) => dot.getAttribute("data-active") === "true",
+ ),
+ ).toHaveLength(1);
+ expect(dots[activeIndex]?.getAttribute("data-active")).toBe("true");
+}
+
+describe("OnboardingStepProgress", () => {
+ it("renders two steps without a chip", () => {
+ render(<OnboardingStepProgress stepIndex={1} stepCount={2} />);
+
+ expectDots(2, 0);
+ expect(screen.getByText("STEP 1 OF 2")).toBeTruthy();
+ expect(screen.queryByText("OPTIONAL")).toBeNull();
+ expect(screen.queryByText("FINAL STEP")).toBeNull();
+ });
+
+ it("renders one mutually exclusive chip across three steps", () => {
+ const { rerender } = render(
+ <OnboardingStepProgress stepIndex={2} stepCount={3} chip="optional" />,
+ );
+
+ expectDots(3, 1);
+ expect(screen.getByText("STEP 2 OF 3")).toBeTruthy();
+ expect(screen.getByText("OPTIONAL")).toBeTruthy();
+ expect(screen.queryByText("FINAL STEP")).toBeNull();
+
+ rerender(
+ <OnboardingStepProgress stepIndex={3} stepCount={3} chip="final" />,
+ );
+ expectDots(3, 2);
+ expect(screen.getByText("STEP 3 OF 3")).toBeTruthy();
+ expect(screen.getByText("FINAL STEP")).toBeTruthy();
+ expect(screen.queryByText("OPTIONAL")).toBeNull();
+ });
+});
diff --git a/skyvern-frontend/src/components/onboarding/OnboardingStepProgress.tsx b/skyvern-frontend/src/components/onboarding/OnboardingStepProgress.tsx
new file mode 100644
index 000000000..8b6970a71
--- /dev/null
+++ b/skyvern-frontend/src/components/onboarding/OnboardingStepProgress.tsx
@@ -0,0 +1,53 @@
+import { cn } from "@/util/utils";
+
+type Props = {
+ stepIndex: number;
+ stepCount: number;
+ chip?: "optional" | "final";
+};
+
+function OnboardingStepProgress({
+ stepIndex,
+ stepCount,
+ chip,
+}: Readonly<Props>) {
+ return (
+ <div className="flex flex-wrap items-center gap-x-3 gap-y-2 pr-12">
+ <div
+ aria-hidden="true"
+ data-testid="onboarding-step-dots"
+ className="flex items-center gap-1"
+ >
+ {Array.from({ length: stepCount }, (_, index) => (
+ <span
+ key={index}
+ data-active={index === stepIndex - 1 ? "true" : "false"}
+ className={cn(
+ "h-1.5 rounded-full",
+ index === stepIndex - 1
+ ? "w-6 bg-primary"
+ : "w-1.5 bg-muted-foreground/40",
+ )}
+ />
+ ))}
+ </div>
+ <span className="rounded-md bg-muted px-2 py-1 text-[11px] font-medium uppercase tabular-nums tracking-wider text-muted-foreground">
+ STEP {stepIndex} OF {stepCount}
+ </span>
+ {chip ? (
+ <span
+ className={cn(
+ "ml-auto rounded-md px-2 py-1 text-[11px] font-medium uppercase tracking-wider",
+ chip === "final"
+ ? "border border-primary text-primary"
+ : "bg-muted text-muted-foreground",
+ )}
+ >
+ {chip === "final" ? "FINAL STEP" : "OPTIONAL"}
+ </span>
+ ) : null}
+ </div>
+ );
+}
+
+export { OnboardingStepProgress };
diff --git a/skyvern-frontend/src/components/onboarding/OnboardingStepShell.tsx b/skyvern-frontend/src/components/onboarding/OnboardingStepShell.tsx
new file mode 100644
index 000000000..ad8e79078
--- /dev/null
+++ b/skyvern-frontend/src/components/onboarding/OnboardingStepShell.tsx
@@ -0,0 +1,25 @@
+import type { ReactNode } from "react";
+import { OnboardingStepProgress } from "./OnboardingStepProgress";
+
+type Props = {
+ stepIndex: number;
+ stepCount: number;
+ chip?: "optional" | "final";
+ children: ReactNode;
+};
+
+function OnboardingStepShell(props: Readonly<Props>) {
+ const { stepIndex, stepCount, chip, children } = props;
+ return (
+ <div className="grid min-h-0 grid-rows-[auto_auto_minmax(0,1fr)_auto_auto] gap-4">
+ <OnboardingStepProgress
+ stepIndex={stepIndex}
+ stepCount={stepCount}
+ chip={chip}
+ />
+ {children}
+ </div>
+ );
+}
+
+export { OnboardingStepShell };
diff --git a/skyvern-frontend/src/components/onboarding/QuestionnaireDetailsStep.test.tsx b/skyvern-frontend/src/components/onboarding/QuestionnaireDetailsStep.test.tsx
new file mode 100644
index 000000000..bea0233a1
--- /dev/null
+++ b/skyvern-frontend/src/components/onboarding/QuestionnaireDetailsStep.test.tsx
@@ -0,0 +1,259 @@
+import {
+ cleanup,
+ fireEvent,
+ render,
+ screen,
+ waitFor,
+} from "@testing-library/react";
+import { afterEach, describe, expect, it, type Mock, vi } from "vitest";
+import { Dialog, DialogContent } from "@/components/ui/dialog";
+import type {
+ QuestionnaireAnswersV1,
+ QuestionnairePatchV1,
+} from "@/store/onboarding/types";
+import { QuestionnaireDetailsStep } from "./QuestionnaireDetailsStep";
+
+const ANSWERS: QuestionnaireAnswersV1 = {
+ role: "developer",
+ company_context: "personal_or_individual",
+ scale_intent: "exploring",
+ referral_source: "search",
+};
+const LABELS = [
+ "What best describes your role?",
+ "What kind of organization are you part of?",
+ "How do you plan to use Skyvern?",
+ "How did you hear about Skyvern?",
+];
+
+type Action = (patch: QuestionnairePatchV1) => Promise<void>;
+
+function renderDetails({
+ action = "complete",
+ revision = 0,
+ initialAnswers = null,
+ externalError = null,
+ isPending = false,
+ onAction = vi.fn<Action>().mockResolvedValue(),
+ onBack = vi.fn(),
+}: {
+ action?: "complete" | "update";
+ revision?: number;
+ initialAnswers?: QuestionnaireAnswersV1 | null;
+ externalError?: string | null;
+ isPending?: boolean;
+ onAction?: Mock<Action>;
+ onBack?: () => void;
+} = {}) {
+ render(
+ <Dialog open>
+ <DialogContent>
+ <QuestionnaireDetailsStep
+ completionAction={action}
+ expectedRevision={revision}
+ initialAnswers={initialAnswers}
+ externalError={externalError}
+ isPending={isPending}
+ onAction={onAction}
+ onBack={onBack}
+ />
+ </DialogContent>
+ </Dialog>,
+ );
+ return { onAction, onBack };
+}
+
+function selectAll() {
+ screen.getAllByRole("combobox").forEach((control) => {
+ fireEvent.click(control);
+ fireEvent.click(screen.getAllByRole("option")[0]!);
+ });
+}
+
+function submitted(onAction: Mock<Action>): QuestionnairePatchV1 {
+ const patch = onAction.mock.calls[onAction.mock.calls.length - 1]?.[0];
+ if (!patch) throw new Error("Expected questionnaire submission");
+ return patch;
+}
+
+afterEach(() => {
+ cleanup();
+ vi.clearAllMocks();
+});
+
+describe("QuestionnaireDetailsStep", () => {
+ it("renders direction A as one optional labelled form", () => {
+ const { onBack } = renderDetails();
+ expect(
+ screen.getByRole("heading", { name: "Tell us about your setup" }),
+ ).toBeTruthy();
+ expect(
+ screen.getByText(/Optional\. Your answers help us recommend/),
+ ).toBeTruthy();
+ expect(screen.queryByText(/About 30 seconds/)).toBeNull();
+ expect(screen.getAllByRole("combobox")).toHaveLength(4);
+ LABELS.forEach((label) =>
+ expect(screen.getByLabelText(label)).toBeTruthy(),
+ );
+ expect(screen.queryByRole("textbox")).toBeNull();
+ fireEvent.click(screen.getByRole("button", { name: "Back" }));
+ expect(onBack).toHaveBeenCalledOnce();
+ });
+
+ it("keeps an incomplete Complete action focusable and explains why it cannot submit", () => {
+ const { onAction } = renderDetails();
+ const submit = screen.getByRole("button", {
+ name: "Complete and continue",
+ });
+ const hint = screen.getByText(
+ "Answer every question to complete and continue.",
+ );
+
+ expect(submit).toHaveProperty("disabled", false);
+ expect(submit.getAttribute("aria-disabled")).toBe("true");
+ expect(submit.getAttribute("aria-describedby")).toBe(hint.id);
+ expect(submit.classList.contains("cursor-not-allowed")).toBe(true);
+ expect(submit.classList.contains("opacity-50")).toBe(true);
+ submit.focus();
+ expect(document.activeElement).toBe(submit);
+ fireEvent.click(submit);
+ expect(onAction).not.toHaveBeenCalled();
+ });
+
+ it("natively disables Complete while a submission is pending", () => {
+ renderDetails({ isPending: true });
+ expect(
+ screen.getByRole("button", { name: "Complete and continue" }),
+ ).toHaveProperty("disabled", true);
+ });
+
+ it("announces a parent close error without leaving details", () => {
+ renderDetails({
+ externalError: "We couldn't save your choice. Try again.",
+ });
+ expect(screen.getByRole("alert").textContent).toBe(
+ "We couldn't save your choice. Try again.",
+ );
+ expect(
+ screen.getByRole("heading", { name: "Tell us about your setup" }),
+ ).toBeTruthy();
+ });
+
+ it("prefers a new close error over a stale submit error", async () => {
+ const onAction = vi
+ .fn<(patch: QuestionnairePatchV1) => Promise<void>>()
+ .mockRejectedValue(new Error("offline"));
+ const view = render(
+ <Dialog open>
+ <DialogContent>
+ <QuestionnaireDetailsStep
+ completionAction="complete"
+ expectedRevision={0}
+ initialAnswers={null}
+ externalError={null}
+ isPending={false}
+ onAction={onAction}
+ onBack={vi.fn()}
+ />
+ </DialogContent>
+ </Dialog>,
+ );
+ selectAll();
+ fireEvent.click(
+ screen.getByRole("button", { name: "Complete and continue" }),
+ );
+ expect((await screen.findByRole("alert")).textContent).toBe(
+ "We couldn't save your details. Try again.",
+ );
+
+ view.rerender(
+ <Dialog open>
+ <DialogContent>
+ <QuestionnaireDetailsStep
+ completionAction="complete"
+ expectedRevision={0}
+ initialAnswers={null}
+ externalError="We couldn't save your choice. Try again."
+ isPending={false}
+ onAction={onAction}
+ onBack={vi.fn()}
+ />
+ </DialogContent>
+ </Dialog>,
+ );
+ expect(screen.getByRole("alert").textContent).toBe(
+ "We couldn't save your choice. Try again.",
+ );
+ });
+
+ it.each([
+ ["complete", 0, null],
+ ["update", 3, ANSWERS],
+ ] as const)(
+ "submits %s with all answers and the exact revision",
+ async (action, revision, initialAnswers) => {
+ const onAction = vi
+ .fn<(patch: QuestionnairePatchV1) => Promise<void>>()
+ .mockResolvedValue();
+ renderDetails({ action, revision, initialAnswers, onAction });
+ const submit = screen.getByRole("button", {
+ name: "Complete and continue",
+ });
+ if (!initialAnswers) {
+ selectAll();
+ }
+ fireEvent.click(submit);
+ await waitFor(() => expect(onAction).toHaveBeenCalledOnce());
+ expect(submitted(onAction)).toEqual({
+ version: 1,
+ mutation_id: expect.any(String),
+ action,
+ expected_revision: revision,
+ ...ANSWERS,
+ });
+ },
+ );
+
+ it("submits answer-free Skip without a defer control", async () => {
+ const onAction = vi
+ .fn<(patch: QuestionnairePatchV1) => Promise<void>>()
+ .mockResolvedValue();
+ renderDetails({ onAction });
+ expect(screen.queryByRole("button", { name: "Maybe later" })).toBeNull();
+ fireEvent.click(screen.getByRole("button", { name: "Skip" }));
+ await waitFor(() => expect(onAction).toHaveBeenCalledOnce());
+ expect(submitted(onAction)).toEqual({
+ version: 1,
+ mutation_id: expect.any(String),
+ expected_revision: 0,
+ action: "skip",
+ });
+ });
+
+ it("keeps selections and mutation identity for an exact retry only", async () => {
+ const onAction = vi
+ .fn<(patch: QuestionnairePatchV1) => Promise<void>>()
+ .mockRejectedValueOnce(new Error("offline"))
+ .mockResolvedValue(undefined);
+ renderDetails({ onAction });
+ selectAll();
+ const submit = screen.getByRole("button", {
+ name: "Complete and continue",
+ });
+ fireEvent.click(submit);
+ expect((await screen.findByRole("alert")).textContent).toBe(
+ "We couldn't save your details. Try again.",
+ );
+ const firstMutation = submitted(onAction).mutation_id;
+
+ fireEvent.click(submit);
+ await waitFor(() => expect(onAction).toHaveBeenCalledTimes(2));
+ expect(submitted(onAction).mutation_id).toBe(firstMutation);
+
+ fireEvent.click(screen.getAllByRole("combobox")[0]!);
+ fireEvent.click(screen.getAllByRole("option")[1]!);
+ fireEvent.click(submit);
+ await waitFor(() => expect(onAction).toHaveBeenCalledTimes(3));
+ expect(submitted(onAction).mutation_id).not.toBe(firstMutation);
+ });
+});
diff --git a/skyvern-frontend/src/components/onboarding/QuestionnaireDetailsStep.tsx b/skyvern-frontend/src/components/onboarding/QuestionnaireDetailsStep.tsx
new file mode 100644
index 000000000..bdcc0a6c2
--- /dev/null
+++ b/skyvern-frontend/src/components/onboarding/QuestionnaireDetailsStep.tsx
@@ -0,0 +1,355 @@
+import { ReloadIcon } from "@radix-ui/react-icons";
+import { useId, useRef, useState } from "react";
+import { cn } from "@/util/utils";
+import { Alert, AlertDescription } from "@/components/ui/alert";
+import { Button } from "@/components/ui/button";
+import {
+ DialogDescription,
+ DialogFooter,
+ DialogHeader,
+ DialogTitle,
+} from "@/components/ui/dialog";
+import { Label } from "@/components/ui/label";
+import {
+ Select,
+ SelectContent,
+ SelectItem,
+ SelectTrigger,
+ SelectValue,
+} from "@/components/ui/select";
+import { OnboardingStepShell } from "./OnboardingStepShell";
+import type {
+ QuestionnaireAnswersV1,
+ QuestionnaireCompanyContextV1,
+ QuestionnairePatchV1,
+ QuestionnaireReferralSourceV1,
+ QuestionnaireRoleV1,
+ QuestionnaireScaleIntentV1,
+} from "@/store/onboarding/types";
+
+type Option<Value extends string> = {
+ value: Value;
+ label: string;
+};
+
+type Selections = {
+ [Key in keyof QuestionnaireAnswersV1]: QuestionnaireAnswersV1[Key] | "";
+};
+
+type Props = {
+ completionAction: "complete" | "update";
+ expectedRevision: number;
+ initialAnswers?: QuestionnaireAnswersV1 | null;
+ externalError?: string | null;
+ isPending: boolean;
+ onAction: (patch: QuestionnairePatchV1) => Promise<void>;
+ onBack: () => void;
+};
+
+type SelectFieldProps<Value extends string> = {
+ id: string;
+ label: string;
+ placeholder: string;
+ value: Value | "";
+ choices: readonly Option<Value>[];
+ disabled: boolean;
+ onValueChange: (value: Value) => void;
+};
+
+function optionsFromLabels<Value extends string>(
+ labels: Record<Value, string>,
+): readonly Option<Value>[] {
+ return (Object.keys(labels) as Value[]).map((value) => ({
+ value,
+ label: labels[value],
+ }));
+}
+
+const ROLE_LABELS: Record<QuestionnaireRoleV1, string> = {
+ developer: "Developer",
+ technical_operator: "Technical operator",
+ business_operator: "Business operator",
+ product_manager: "Product manager",
+ founder_or_executive: "Founder or executive",
+ other: "Other",
+ prefer_not_to_say: "Prefer not to say",
+};
+const ROLE_OPTIONS = optionsFromLabels(ROLE_LABELS);
+
+const COMPANY_CONTEXT_LABELS: Record<QuestionnaireCompanyContextV1, string> = {
+ personal_or_individual: "Personal or individual",
+ startup: "Startup",
+ agency_or_services: "Agency or services",
+ established_company: "Established company",
+ education_or_research: "Education or research",
+ other: "Other",
+ prefer_not_to_say: "Prefer not to say",
+};
+const COMPANY_CONTEXT_OPTIONS = optionsFromLabels(COMPANY_CONTEXT_LABELS);
+
+const SCALE_INTENT_LABELS: Record<QuestionnaireScaleIntentV1, string> = {
+ exploring: "Exploring",
+ single_workflow: "A single workflow",
+ recurring_individual: "Recurring individual workflows",
+ team_or_multi_workflow: "Team or multiple workflows",
+ production_high_volume: "Production or high volume",
+ unsure: "Unsure",
+};
+const SCALE_INTENT_OPTIONS = optionsFromLabels(SCALE_INTENT_LABELS);
+
+const REFERRAL_SOURCE_LABELS: Record<QuestionnaireReferralSourceV1, string> = {
+ search: "Search",
+ social: "Social media",
+ ai_assistant: "AI assistant",
+ friend_or_colleague: "Friend or colleague",
+ video: "Video",
+ blog_or_article: "Blog or article",
+ event_or_community: "Event or community",
+ podcast: "Podcast",
+ other: "Other",
+ prefer_not_to_say: "Prefer not to say",
+};
+const REFERRAL_SOURCE_OPTIONS = optionsFromLabels(REFERRAL_SOURCE_LABELS);
+
+function selectedAnswers(
+ selections: Selections,
+): QuestionnaireAnswersV1 | null {
+ const { role, company_context, scale_intent, referral_source } = selections;
+ return role && company_context && scale_intent && referral_source
+ ? { role, company_context, scale_intent, referral_source }
+ : null;
+}
+
+function QuestionnaireSelect<Value extends string>({
+ id,
+ label,
+ placeholder,
+ value,
+ choices,
+ disabled,
+ onValueChange,
+}: Readonly<SelectFieldProps<Value>>) {
+ function selectValue(nextValue: string) {
+ const choice = choices.find((candidate) => candidate.value === nextValue);
+ if (choice) {
+ onValueChange(choice.value);
+ }
+ }
+
+ return (
+ <div className="grid gap-2">
+ <Label htmlFor={id} className="text-sm leading-snug">
+ {label}
+ </Label>
+ <Select value={value} onValueChange={selectValue} disabled={disabled}>
+ <SelectTrigger
+ id={id}
+ className="min-h-11 w-full touch-manipulation bg-background text-foreground motion-reduce:transition-none"
+ >
+ <SelectValue placeholder={placeholder} />
+ </SelectTrigger>
+ <SelectContent className="z-[2147480004]">
+ {choices.map((choice) => (
+ <SelectItem
+ key={choice.value}
+ value={choice.value}
+ className="min-h-11 touch-manipulation motion-reduce:transition-none"
+ >
+ {choice.label}
+ </SelectItem>
+ ))}
+ </SelectContent>
+ </Select>
+ </div>
+ );
+}
+
+function QuestionnaireDetailsStep({
+ completionAction,
+ expectedRevision,
+ initialAnswers,
+ externalError,
+ isPending,
+ onAction,
+ onBack,
+}: Readonly<Props>) {
+ const fieldPrefix = useId();
+ const incompleteHintId = `${fieldPrefix}-incomplete-hint`;
+ const [selections, setSelections] = useState<Selections>(() => ({
+ role: initialAnswers?.role ?? "",
+ company_context: initialAnswers?.company_context ?? "",
+ scale_intent: initialAnswers?.scale_intent ?? "",
+ referral_source: initialAnswers?.referral_source ?? "",
+ }));
+ const [pendingAction, setPendingAction] = useState<
+ QuestionnairePatchV1["action"] | null
+ >(null);
+ const [error, setError] = useState<string | null>(null);
+ const displayedError = externalError ?? error;
+ const pending = isPending || pendingAction !== null;
+ const mutationIdentityRef = useRef<{
+ payload: string;
+ mutationId: string;
+ } | null>(null);
+ const answers = selectedAnswers(selections);
+
+ function setSelection<Key extends keyof QuestionnaireAnswersV1>(
+ key: Key,
+ value: QuestionnaireAnswersV1[Key],
+ ) {
+ setSelections((current) => ({ ...current, [key]: value }));
+ }
+
+ function mutationIdFor(payload: string) {
+ const mutationId =
+ mutationIdentityRef.current?.payload === payload
+ ? mutationIdentityRef.current.mutationId
+ : crypto.randomUUID();
+ mutationIdentityRef.current = { payload, mutationId };
+ return mutationId;
+ }
+
+ async function submit(action: QuestionnairePatchV1["action"]) {
+ if (pending) return;
+
+ try {
+ const payload =
+ action === "skip"
+ ? { version: 1 as const, expected_revision: expectedRevision, action }
+ : answers && {
+ version: 1 as const,
+ expected_revision: expectedRevision,
+ action,
+ ...answers,
+ };
+ if (!payload) return;
+ const patch = {
+ ...payload,
+ mutation_id: mutationIdFor(JSON.stringify(payload)),
+ } as QuestionnairePatchV1;
+
+ setPendingAction(action);
+ setError(null);
+ await onAction(patch);
+ mutationIdentityRef.current = null;
+ } catch {
+ setError("We couldn't save your details. Try again.");
+ } finally {
+ setPendingAction(null);
+ }
+ }
+
+ return (
+ <OnboardingStepShell stepIndex={2} stepCount={3} chip="optional">
+ <DialogHeader className="pr-12">
+ <DialogTitle className="text-xl font-semibold">
+ Tell us about your setup
+ </DialogTitle>
+ <DialogDescription>
+ Optional. Your answers help us recommend templates and guidance. They
+ never limit what you can build.
+ </DialogDescription>
+ </DialogHeader>
+ <div className="grid gap-4 py-1 pr-1">
+ <QuestionnaireSelect
+ id={`${fieldPrefix}-role`}
+ label="What best describes your role?"
+ placeholder="Choose a role"
+ value={selections.role}
+ choices={ROLE_OPTIONS}
+ disabled={pending}
+ onValueChange={(value) => setSelection("role", value)}
+ />
+ <QuestionnaireSelect
+ id={`${fieldPrefix}-company-context`}
+ label="What kind of organization are you part of?"
+ placeholder="Choose an organization type"
+ value={selections.company_context}
+ choices={COMPANY_CONTEXT_OPTIONS}
+ disabled={pending}
+ onValueChange={(value) => setSelection("company_context", value)}
+ />
+ <QuestionnaireSelect
+ id={`${fieldPrefix}-scale-intent`}
+ label="How do you plan to use Skyvern?"
+ placeholder="Choose a usage pattern"
+ value={selections.scale_intent}
+ choices={SCALE_INTENT_OPTIONS}
+ disabled={pending}
+ onValueChange={(value) => setSelection("scale_intent", value)}
+ />
+ <QuestionnaireSelect
+ id={`${fieldPrefix}-referral-source`}
+ label="How did you hear about Skyvern?"
+ placeholder="Choose a source"
+ value={selections.referral_source}
+ choices={REFERRAL_SOURCE_OPTIONS}
+ disabled={pending}
+ onValueChange={(value) => setSelection("referral_source", value)}
+ />
+ </div>
+ {displayedError ? (
+ <Alert variant="destructive">
+ <AlertDescription>{displayedError}</AlertDescription>
+ </Alert>
+ ) : null}
+ {!answers ? (
+ <p id={incompleteHintId} className="text-sm text-muted-foreground">
+ Answer every question to complete and continue.
+ </p>
+ ) : null}
+ <DialogFooter className="sticky bottom-0 z-10 -mx-6 -mb-6 flex-col gap-2 border-t border-border bg-background px-6 pb-[max(1rem,env(safe-area-inset-bottom))] pt-4 sm:flex-row sm:justify-between sm:gap-0 sm:space-x-0">
+ <Button
+ type="button"
+ variant="ghost"
+ size="sm"
+ className="min-h-11 w-full min-w-11 touch-manipulation motion-reduce:transition-none sm:w-auto"
+ disabled={pending}
+ onClick={onBack}
+ >
+ Back
+ </Button>
+ {completionAction === "complete" ? (
+ <Button
+ type="button"
+ variant="ghost"
+ size="sm"
+ className="min-h-11 w-full min-w-11 touch-manipulation motion-reduce:transition-none sm:w-auto"
+ disabled={pending}
+ onClick={() => void submit("skip")}
+ >
+ {pendingAction === "skip" ? (
+ <ReloadIcon
+ aria-hidden
+ className="mr-2 size-4 animate-spin motion-reduce:animate-none"
+ />
+ ) : null}
+ Skip
+ </Button>
+ ) : null}
+ <Button
+ type="button"
+ size="sm"
+ className={cn(
+ "min-h-11 w-full min-w-11 touch-manipulation motion-reduce:transition-none sm:w-auto",
+ !answers && "cursor-not-allowed opacity-50",
+ )}
+ aria-describedby={!answers ? incompleteHintId : undefined}
+ aria-disabled={!answers || undefined}
+ disabled={pending}
+ onClick={() => void submit(completionAction)}
+ >
+ {pendingAction === completionAction ? (
+ <ReloadIcon
+ aria-hidden
+ className="mr-2 size-4 animate-spin motion-reduce:animate-none"
+ />
+ ) : null}
+ Complete and continue
+ </Button>
+ </DialogFooter>
+ </OnboardingStepShell>
+ );
+}
+
+export { QuestionnaireDetailsStep };
diff --git a/skyvern-frontend/src/components/onboarding/QuestionnaireNextStepsCard.test.tsx b/skyvern-frontend/src/components/onboarding/QuestionnaireNextStepsCard.test.tsx
new file mode 100644
index 000000000..a0675df77
--- /dev/null
+++ b/skyvern-frontend/src/components/onboarding/QuestionnaireNextStepsCard.test.tsx
@@ -0,0 +1,143 @@
+// @vitest-environment jsdom
+import {
+ cleanup,
+ fireEvent,
+ render,
+ screen,
+ within,
+} from "@testing-library/react";
+import { MemoryRouter } from "react-router-dom";
+import { afterEach, describe, expect, it, vi } from "vitest";
+import { Dialog, DialogContent } from "@/components/ui/dialog";
+import type { QuestionnaireAnswersV1 } from "@/store/onboarding/types";
+import { QuestionnaireNextStepsCard } from "./QuestionnaireNextStepsCard";
+
+const baseAnswers: QuestionnaireAnswersV1 = {
+ role: "developer",
+ company_context: "startup",
+ scale_intent: "exploring",
+ referral_source: "search",
+};
+
+function renderCard(answers: QuestionnaireAnswersV1 | null) {
+ const onAction = vi.fn();
+ const onBack = vi.fn();
+ const onSkip = vi.fn();
+ const view = render(
+ <MemoryRouter>
+ <Dialog open>
+ <DialogContent>
+ <QuestionnaireNextStepsCard
+ answers={answers}
+ onAction={onAction}
+ onBack={onBack}
+ onSkip={onSkip}
+ />
+ </DialogContent>
+ </Dialog>
+ </MemoryRouter>,
+ );
+ return { ...view, onAction, onBack, onSkip };
+}
+
+afterEach(cleanup);
+
+describe("QuestionnaireNextStepsCard", () => {
+ it("routes a technical explorer through integrations and a first run", () => {
+ const { onAction } = renderCard(baseAnswers);
+
+ const items = screen.getAllByRole("listitem");
+ expect(items).toHaveLength(3);
+ for (const item of items) {
+ const links = within(item).getAllByRole("link");
+ expect(links).toHaveLength(2);
+ expect(links[1]?.getAttribute("target")).toBe("_blank");
+ expect(links[1]?.getAttribute("rel")).toBe("noopener noreferrer");
+ }
+ expect(onAction).not.toHaveBeenCalled();
+ expect(screen.getByText("Start with a template")).toBeTruthy();
+ expect(screen.getByText("Connect Skyvern to your stack")).toBeTruthy();
+ expect(screen.getByText("Run and review your agent")).toBeTruthy();
+ expect(
+ screen
+ .getByRole("link", { name: "Browse templates" })
+ .getAttribute("href"),
+ ).toBe("/discover");
+ expect(
+ screen.getByRole("link", { name: "Set up MCP" }).getAttribute("href"),
+ ).toBe("https://www.skyvern.com/docs/cloud/getting-started/mcp");
+ expect(
+ screen
+ .getByRole("link", { name: "How to run an agent" })
+ .getAttribute("href"),
+ ).toBe("https://www.skyvern.com/docs/cloud/building-agents/run-an-agent");
+
+ fireEvent.click(screen.getByRole("link", { name: "Open integrations" }));
+ expect(onAction).toHaveBeenCalledTimes(1);
+ });
+
+ it.each([
+ "recurring_individual",
+ "team_or_multi_workflow",
+ "production_high_volume",
+ ] as const)(
+ "routes a business %s answer through credentials and scheduling",
+ (scaleIntent) => {
+ renderCard({
+ ...baseAnswers,
+ role: "business_operator",
+ company_context: "established_company",
+ scale_intent: scaleIntent,
+ referral_source: "friend_or_colleague",
+ });
+
+ expect(screen.getAllByRole("listitem")).toHaveLength(3);
+ expect(screen.getByText("Build a reusable agent")).toBeTruthy();
+ expect(screen.getByText("Add website credentials")).toBeTruthy();
+ expect(screen.getByText("Schedule repeat runs")).toBeTruthy();
+ expect(
+ screen
+ .getByRole("link", { name: "How credentials work" })
+ .getAttribute("href"),
+ ).toBe(
+ "https://www.skyvern.com/docs/cloud/managing-credentials/credentials-overview",
+ );
+ expect(
+ screen
+ .getByRole("link", { name: "How to schedule an agent" })
+ .getAttribute("href"),
+ ).toBe("https://www.skyvern.com/docs/cloud/building-agents/scheduling");
+ },
+ );
+
+ it("hides incomplete answers and defaults unknown persisted values safely", () => {
+ const callbacks = {
+ onAction: vi.fn(),
+ onBack: vi.fn(),
+ onSkip: vi.fn(),
+ };
+ const { container, rerender, unmount } = render(
+ <QuestionnaireNextStepsCard answers={null} {...callbacks} />,
+ );
+ expect(container.textContent).toBe("");
+
+ rerender(
+ <QuestionnaireNextStepsCard
+ answers={{ role: "developer" } as QuestionnaireAnswersV1}
+ {...callbacks}
+ />,
+ );
+ expect(container.textContent).toBe("");
+ unmount();
+
+ renderCard({
+ ...baseAnswers,
+ role: "future_role",
+ scale_intent: "future_scale",
+ future_answer: "ignored",
+ } as unknown as QuestionnaireAnswersV1);
+ expect(screen.getAllByRole("listitem")).toHaveLength(3);
+ expect(screen.getByText("Add website credentials")).toBeTruthy();
+ expect(screen.getByText("Run and review your agent")).toBeTruthy();
+ });
+});
diff --git a/skyvern-frontend/src/components/onboarding/QuestionnaireNextStepsCard.tsx b/skyvern-frontend/src/components/onboarding/QuestionnaireNextStepsCard.tsx
new file mode 100644
index 000000000..53a1fde26
--- /dev/null
+++ b/skyvern-frontend/src/components/onboarding/QuestionnaireNextStepsCard.tsx
@@ -0,0 +1,210 @@
+import { Link } from "react-router-dom";
+import { Button } from "@/components/ui/button";
+import {
+ DialogDescription,
+ DialogFooter,
+ DialogHeader,
+ DialogTitle,
+} from "@/components/ui/dialog";
+import type { QuestionnaireAnswersV1 } from "@/store/onboarding/types";
+import { OnboardingStepShell } from "./OnboardingStepShell";
+
+type NextStep = {
+ id: string;
+ title: string;
+ description: string;
+ actionLabel: string;
+ actionHref: string;
+ resourceLabel: string;
+ resourceHref: string;
+};
+
+type Props = {
+ answers: QuestionnaireAnswersV1 | null;
+ onAction: () => void;
+ onBack: () => void;
+ onSkip: () => void;
+};
+
+const resources = {
+ build: "https://www.skyvern.com/docs/cloud/building-agents/build-an-agent",
+ credentials:
+ "https://www.skyvern.com/docs/cloud/managing-credentials/credentials-overview",
+ mcp: "https://www.skyvern.com/docs/cloud/getting-started/mcp",
+ run: "https://www.skyvern.com/docs/cloud/building-agents/run-an-agent",
+ schedule: "https://www.skyvern.com/docs/cloud/building-agents/scheduling",
+} as const;
+
+function questionnaireNextSteps(
+ answers: QuestionnaireAnswersV1 | null,
+): readonly NextStep[] | null {
+ if (
+ !answers?.role ||
+ !answers.company_context ||
+ !answers.scale_intent ||
+ !answers.referral_source
+ ) {
+ return null;
+ }
+
+ const technicalRole =
+ answers.role === "developer" || answers.role === "technical_operator";
+ const scaledUse =
+ answers.scale_intent === "recurring_individual" ||
+ answers.scale_intent === "team_or_multi_workflow" ||
+ answers.scale_intent === "production_high_volume";
+
+ return [
+ scaledUse
+ ? {
+ id: "build-reusable",
+ title: "Build a reusable agent",
+ description: "Start from a template, then adapt it for repeat use.",
+ actionLabel: "Browse templates",
+ actionHref: "/discover",
+ resourceLabel: "How to build an agent",
+ resourceHref: resources.build,
+ }
+ : {
+ id: "start-template",
+ title: "Start with a template",
+ description: "Choose a template and tailor it to your first task.",
+ actionLabel: "Browse templates",
+ actionHref: "/discover",
+ resourceLabel: "How to build an agent",
+ resourceHref: resources.build,
+ },
+ technicalRole
+ ? {
+ id: "connect-stack",
+ title: "Connect Skyvern to your stack",
+ description:
+ "Use an integration to bring browser automation into your tools.",
+ actionLabel: "Open integrations",
+ actionHref: "/integrations",
+ resourceLabel: "Set up MCP",
+ resourceHref: resources.mcp,
+ }
+ : {
+ id: "add-credentials",
+ title: "Add website credentials",
+ description: "Save the logins your agent needs before its first run.",
+ actionLabel: "Open credentials",
+ actionHref: "/credentials",
+ resourceLabel: "How credentials work",
+ resourceHref: resources.credentials,
+ },
+ scaledUse
+ ? {
+ id: "schedule-runs",
+ title: "Schedule repeat runs",
+ description:
+ "Open your agent when you are ready to set a recurring schedule.",
+ actionLabel: "Open agents",
+ actionHref: "/agents",
+ resourceLabel: "How to schedule an agent",
+ resourceHref: resources.schedule,
+ }
+ : {
+ id: "run-agent",
+ title: "Run and review your agent",
+ description: "Open your agent, start a run, and review the result.",
+ actionLabel: "Open agents",
+ actionHref: "/agents",
+ resourceLabel: "How to run an agent",
+ resourceHref: resources.run,
+ },
+ ];
+}
+
+function QuestionnaireNextStepsCard({
+ answers,
+ onAction,
+ onBack,
+ onSkip,
+}: Readonly<Props>) {
+ const steps = questionnaireNextSteps(answers);
+ if (!steps) return null;
+
+ return (
+ <OnboardingStepShell stepIndex={3} stepCount={3} chip="final">
+ <DialogHeader className="pr-12">
+ <DialogTitle className="text-xl font-semibold">
+ Your next three steps
+ </DialogTitle>
+ <DialogDescription>
+ Based on the answers you just saved, here is a practical path to your
+ first successful run.
+ </DialogDescription>
+ </DialogHeader>
+ <ol
+ aria-label="Recommended next steps"
+ className="flex min-h-0 flex-col gap-3 overflow-y-auto overscroll-contain pr-1"
+ >
+ {steps.map((step, index) => (
+ <li
+ key={step.id}
+ className="rounded-lg border border-border bg-muted/20 p-3"
+ >
+ <div className="flex gap-3">
+ <span
+ aria-hidden="true"
+ className="flex size-7 shrink-0 items-center justify-center rounded-full border border-border text-xs font-semibold"
+ >
+ {index + 1}
+ </span>
+ <div className="min-w-0 flex-1">
+ <h3 className="text-sm font-semibold text-foreground">
+ {step.title}
+ </h3>
+ <p className="mt-1 text-sm text-muted-foreground">
+ {step.description}
+ </p>
+ <div className="mt-2 flex flex-col gap-1 sm:flex-row sm:items-center sm:gap-2">
+ <Button
+ asChild
+ variant="outline"
+ size="sm"
+ className="min-h-11 w-full touch-manipulation sm:w-auto"
+ >
+ <Link to={step.actionHref} onClick={onAction}>
+ {step.actionLabel}
+ </Link>
+ </Button>
+ <a
+ href={step.resourceHref}
+ target="_blank"
+ rel="noopener noreferrer"
+ className="inline-flex min-h-11 items-center rounded-md px-3 text-sm font-medium text-muted-foreground underline underline-offset-4 transition-colors hover:text-foreground focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-ring"
+ >
+ {step.resourceLabel}
+ </a>
+ </div>
+ </div>
+ </div>
+ </li>
+ ))}
+ </ol>
+ <DialogFooter className="sticky bottom-0 z-10 -mx-6 -mb-6 flex-col gap-2 border-t border-border bg-background px-6 pb-[max(1rem,env(safe-area-inset-bottom))] pt-4 sm:flex-row sm:justify-between sm:gap-0 sm:space-x-0">
+ <Button
+ variant="ghost"
+ size="sm"
+ className="min-h-11 w-full min-w-11 touch-manipulation sm:w-auto"
+ onClick={onBack}
+ >
+ Back
+ </Button>
+ <Button
+ variant="ghost"
+ size="sm"
+ className="min-h-11 w-full min-w-11 touch-manipulation sm:w-auto"
+ onClick={onSkip}
+ >
+ Skip
+ </Button>
+ </DialogFooter>
+ </OnboardingStepShell>
+ );
+}
+
+export { QuestionnaireNextStepsCard };
diff --git a/skyvern-frontend/src/components/onboarding/WorkingExampleInspector.test.tsx b/skyvern-frontend/src/components/onboarding/WorkingExampleInspector.test.tsx
new file mode 100644
index 000000000..0f13a9dc0
--- /dev/null
+++ b/skyvern-frontend/src/components/onboarding/WorkingExampleInspector.test.tsx
@@ -0,0 +1,35 @@
+import { fireEvent, render, screen } from "@testing-library/react";
+import { expect, it, vi } from "vitest";
+import { WorkingExampleInspector } from "./WorkingExampleInspector";
+
+it("shows provenance, structure, playback, and result before one safe copy", () => {
+ const onMakeCopy = vi.fn();
+ render(<WorkingExampleInspector isPending={false} onMakeCopy={onMakeCopy} />);
+ expect(screen.getByText("Example data, not your run")).toBeTruthy();
+ expect(
+ screen.getByRole("heading", { name: "Workflow structure" }),
+ ).toBeTruthy();
+ expect(screen.getByText("Visit a public page")).toBeTruthy();
+ expect(
+ screen.getByRole("heading", { name: "Example playback" }),
+ ).toBeTruthy();
+ expect(
+ screen.getByText("Opened https://www.skyvern.com/ in this static example."),
+ ).toBeTruthy();
+ expect(
+ screen.getByRole("heading", { name: "Synthetic example result" }),
+ ).toBeTruthy();
+ expect(screen.getByText("Product summary")).toBeTruthy();
+ expect(onMakeCopy).not.toHaveBeenCalled();
+ fireEvent.click(screen.getByRole("button", { name: "Make a copy" }));
+ expect(onMakeCopy).toHaveBeenCalledTimes(1);
+});
+
+it("disables a pending copy and prevents duplicate callback", () => {
+ const onMakeCopy = vi.fn();
+ render(<WorkingExampleInspector isPending onMakeCopy={onMakeCopy} />);
+ const button = screen.getByRole("button", { name: "Make a copy" });
+ expect(button.hasAttribute("disabled")).toBe(true);
+ fireEvent.click(button);
+ expect(onMakeCopy).not.toHaveBeenCalled();
+});
diff --git a/skyvern-frontend/src/components/onboarding/WorkingExampleInspector.tsx b/skyvern-frontend/src/components/onboarding/WorkingExampleInspector.tsx
new file mode 100644
index 000000000..7e85efc09
--- /dev/null
+++ b/skyvern-frontend/src/components/onboarding/WorkingExampleInspector.tsx
@@ -0,0 +1,102 @@
+import { ReloadIcon } from "@radix-ui/react-icons";
+
+import { Button } from "@/components/ui/button";
+import { onboardingExamplePresentation } from "@/routes/discover/onboardingExample";
+
+type WorkingExampleInspectorProps = {
+ isPending: boolean;
+ onMakeCopy: () => void;
+};
+
+function WorkingExampleInspector({
+ isPending,
+ onMakeCopy,
+}: WorkingExampleInspectorProps) {
+ const { title, provenance, structure, playback, result } =
+ onboardingExamplePresentation;
+
+ return (
+ <section
+ aria-labelledby="working-example-heading"
+ className="overflow-hidden rounded-lg border border-border bg-background"
+ >
+ <header className="flex flex-wrap items-start justify-between gap-3 border-b border-border px-5 py-4 sm:px-6">
+ <h2
+ id="working-example-heading"
+ tabIndex={-1}
+ className="text-base font-semibold"
+ >
+ {title}
+ </h2>
+ <p className="shrink-0 text-xs font-medium text-muted-foreground">
+ {provenance}
+ </p>
+ </header>
+ <div className="grid gap-5 p-5 sm:p-6 lg:grid-cols-3">
+ <div className="min-w-0">
+ <h3 className="text-sm font-semibold">Workflow structure</h3>
+ <ol className="mt-3 list-decimal space-y-3 pl-4 marker:text-muted-foreground">
+ {structure.map((step) => (
+ <li key={step.title} className="break-words pl-1">
+ <p className="text-sm font-medium">{step.title}</p>
+ <p className="mt-0.5 text-xs leading-5 text-muted-foreground">
+ {step.detail}
+ </p>
+ </li>
+ ))}
+ </ol>
+ </div>
+ <div className="min-w-0">
+ <h3 className="text-sm font-semibold">Example playback</h3>
+ <ol className="mt-3 list-decimal space-y-2 pl-4 marker:text-muted-foreground">
+ {playback.map((detail) => (
+ <li
+ key={detail}
+ className="break-words pl-1 text-xs leading-5 text-muted-foreground"
+ >
+ {detail}
+ </li>
+ ))}
+ </ol>
+ </div>
+ <div className="min-w-0">
+ <h3 className="text-sm font-semibold">{result.title}</h3>
+ <dl className="mt-3 divide-y divide-border rounded-md border border-border">
+ {result.fields.map(({ label, value }) => (
+ <div
+ key={label}
+ className="grid gap-1 px-3 py-2.5 sm:grid-cols-[7rem_1fr] sm:gap-3"
+ >
+ <dt className="break-words text-xs font-medium text-muted-foreground">
+ {label}
+ </dt>
+ <dd className="min-w-0 break-words text-xs leading-5">
+ {value}
+ </dd>
+ </div>
+ ))}
+ </dl>
+ </div>
+ </div>
+ <footer className="flex justify-end border-t border-border px-5 py-4 sm:px-6">
+ <Button
+ type="button"
+ className="h-11 w-full touch-manipulation sm:w-auto"
+ disabled={isPending}
+ aria-busy={isPending}
+ onClick={onMakeCopy}
+ >
+ {isPending && (
+ <ReloadIcon
+ aria-hidden="true"
+ className="mr-2 h-4 w-4 motion-safe:animate-spin motion-reduce:animate-none"
+ />
+ )}
+ Make a copy
+ </Button>
+ </footer>
+ </section>
+ );
+}
+
+export { WorkingExampleInspector };
diff --git a/skyvern-frontend/src/hooks/useContextualHints.test.tsx b/skyvern-frontend/src/hooks/useContextualHints.test.tsx
index 7c393a402..265245998 100644
--- a/skyvern-frontend/src/hooks/useContextualHints.test.tsx
+++ b/skyvern-frontend/src/hooks/useContextualHints.test.tsx
@@ -48,6 +48,7 @@ function makeCtx(
state: COMPLETED_STATE,
isLoading: false,
updateState: vi.fn(),
+ updateStateConfirmed: vi.fn(),
isNewUser: false,
abVariant: "template-first",
recoveryGuidanceAssignment: null,
@@ -110,6 +111,8 @@ describe("useContextualHints", () => {
surface: "editor",
hint_id: "add-another-block",
layer: 2,
+ organization_id: undefined,
+ step_id: "onboarding.hint_shown:v1",
});
});
@@ -167,6 +170,8 @@ describe("useContextualHints", () => {
surface: "editor",
hint_id: "add-another-block",
layer: 2,
+ organization_id: undefined,
+ step_id: "onboarding.hint_dismissed:v1",
});
});
});
diff --git a/skyvern-frontend/src/hooks/useContextualHints.ts b/skyvern-frontend/src/hooks/useContextualHints.ts
index c5adf382b..84e9811af 100644
--- a/skyvern-frontend/src/hooks/useContextualHints.ts
+++ b/skyvern-frontend/src/hooks/useContextualHints.ts
@@ -11,7 +11,7 @@ import {
} from "@/util/onboarding/contextualHints";
import type {
OnboardingState,
- OnboardingStatePatch,
+ LegacyOnboardingStatePatch,
} from "@/store/onboarding/types";
const SHOW_DELAY_MS = 800;
@@ -83,7 +83,7 @@ function useContextualHints(): void {
// resurrect a dismissed hint (show-once frequency cap).
onboarding?.updateState({
[hint.seenKey]: true,
- } as OnboardingStatePatch);
+ } as LegacyOnboardingStatePatch);
OnboardingTelemetry.hintShown(hint.surface, hint.id);
} catch {
activeHintRef.current = null;
diff --git a/skyvern-frontend/src/hooks/useEditorOnboardingTour.test.tsx b/skyvern-frontend/src/hooks/useEditorOnboardingTour.test.tsx
index 6b4f3871c..8ab5e738d 100644
--- a/skyvern-frontend/src/hooks/useEditorOnboardingTour.test.tsx
+++ b/skyvern-frontend/src/hooks/useEditorOnboardingTour.test.tsx
@@ -87,6 +87,7 @@ function makeContext(
state: DEFAULT_STATE,
isLoading: false,
updateState: vi.fn(),
+ updateStateConfirmed: vi.fn(),
isNewUser: false,
abVariant: null,
recoveryGuidanceAssignment: null,
diff --git a/skyvern-frontend/src/hooks/useEditorOnboardingTour.ts b/skyvern-frontend/src/hooks/useEditorOnboardingTour.ts
index 3b1ac1523..ea097a6f0 100644
--- a/skyvern-frontend/src/hooks/useEditorOnboardingTour.ts
+++ b/skyvern-frontend/src/hooks/useEditorOnboardingTour.ts
@@ -6,7 +6,7 @@ import { useProductTourStore } from "@/store/ProductTourStore";
import { useWorkflowPanelStore } from "@/store/WorkflowPanelStore";
import { OnboardingTelemetry } from "@/util/onboarding/OnboardingTelemetry";
import { EXPERIMENT, isABVariant } from "@/util/onboarding/experimentConfig";
-import type { OnboardingStatePatch } from "@/store/onboarding/types";
+import type { LegacyOnboardingStatePatch } from "@/store/onboarding/types";
const SURFACE = "editor" as const;
const LAYER = 1 as const;
@@ -81,13 +81,15 @@ function setNodeAdderNextVisible(visible: boolean): void {
}
}
-const SEEN_PATCHES: Record<(typeof STEP_NAMES)[number], OnboardingStatePatch> =
- {
- canvas: { seen_canvas: true },
- node_adder: { seen_node_adder: true },
- sidebar: { seen_sidebar: true },
- save_run: { seen_save_run: true },
- };
+const SEEN_PATCHES: Record<
+ (typeof STEP_NAMES)[number],
+ LegacyOnboardingStatePatch
+> = {
+ canvas: { seen_canvas: true },
+ node_adder: { seen_node_adder: true },
+ sidebar: { seen_sidebar: true },
+ save_run: { seen_save_run: true },
+};
// driver.js hands callbacks a shallow clone of the active step, so match by element selector, never by object identity.
function indexOfStep(steps: DriveStep[], step: DriveStep): number {
diff --git a/skyvern-frontend/src/hooks/useWorkflowStudioEnabled.ts b/skyvern-frontend/src/hooks/useWorkflowStudioEnabled.ts
index 8ed363946..a73d3c14e 100644
--- a/skyvern-frontend/src/hooks/useWorkflowStudioEnabled.ts
+++ b/skyvern-frontend/src/hooks/useWorkflowStudioEnabled.ts
@@ -4,6 +4,12 @@ import { WORKFLOW_STUDIO_FLAG } from "@/util/featureFlags";
// Client-side eval so the flag reflects per-user opt-in (PostHog person property),
// not the per-org server-evaluated path. Gates the whole studio redesign.
+// undefined means flags have not resolved yet — callers that act irreversibly on
+// "off" (e.g. URL rewrites) must distinguish it from a resolved false.
+export function useWorkflowStudioFlagState(): boolean | undefined {
+ return useFeatureFlagEnabled(WORKFLOW_STUDIO_FLAG);
+}
+
export function useWorkflowStudioEnabled(): boolean {
- return useFeatureFlagEnabled(WORKFLOW_STUDIO_FLAG) ?? false;
+ return useWorkflowStudioFlagState() ?? false;
}
diff --git a/skyvern-frontend/src/routes/browserSessions/BrowserSessionStream.test.tsx b/skyvern-frontend/src/routes/browserSessions/BrowserSessionStream.test.tsx
index bb565384a..c08fed488 100644
--- a/skyvern-frontend/src/routes/browserSessions/BrowserSessionStream.test.tsx
+++ b/skyvern-frontend/src/routes/browserSessions/BrowserSessionStream.test.tsx
@@ -27,12 +27,21 @@ const cdpInputState = vi.hoisted(() => ({
userIsControlling: false,
inputReady: false,
setUserIsControlling: undefined as ((value: boolean) => void) | undefined,
+ onInput: undefined as (() => void) | undefined,
}));
const telemetry = vi.hoisted(() => ({
captureRecordBrowser: vi.fn(),
}));
+const api = vi.hoisted(() => ({
+ get: vi.fn(async () => ({ data: {} })),
+}));
+
+vi.mock("@/api/AxiosClient", () => ({
+ getClient: async () => ({ get: api.get }),
+}));
+
vi.mock("@/util/env", () => ({
get newWssBaseUrl() {
return env.wssBaseUrl;
@@ -62,6 +71,7 @@ vi.mock("@/routes/streaming/useCdpInput", async (importOriginal) => {
cdpInputState.viewportHeight = viewportHeight;
cdpInputState.clipboardPasteEnabled = Boolean(options.onClipboardPaste);
cdpInputState.clipboardCopyEnabled = Boolean(options.onClipboardCopy);
+ cdpInputState.onInput = options.onInput;
const result = actual.useCdpInput(options);
cdpInputState.userIsControlling = result.userIsControlling;
cdpInputState.inputReady = result.inputReady;
diff --git a/skyvern-frontend/src/routes/browserSessions/BrowserSessionStream.tsx b/skyvern-frontend/src/routes/browserSessions/BrowserSessionStream.tsx
index 023a5cb9a..0b28f49c1 100644
--- a/skyvern-frontend/src/routes/browserSessions/BrowserSessionStream.tsx
+++ b/skyvern-frontend/src/routes/browserSessions/BrowserSessionStream.tsx
@@ -242,7 +242,6 @@ function BrowserSessionStream({
userIsControlling,
setUserIsControlling,
inputReady,
- inputRttMs,
containerRef,
handlers,
navigate,
@@ -258,8 +257,6 @@ function BrowserSessionStream({
onClipboardCopy:
exfiltrate && isMessageConnected ? onClipboardCopy : undefined,
});
- const inputRttMsRef = useRef(inputRttMs);
- inputRttMsRef.current = inputRttMs;
useEffect(() => {
const recordingStarted =
@@ -330,7 +327,6 @@ function BrowserSessionStream({
samples.length,
fps_min: Math.min(...samples),
sample_count: samples.length,
- input_rtt_ms: inputRttMsRef.current,
});
if (recordingHealthFlushTimerRef.current === flushTimer) {
recordingHealthFlushTimerRef.current = null;
@@ -385,10 +381,10 @@ function BrowserSessionStream({
return;
}
+ const url = `${newWssBaseUrl}/stream/browser_sessions/${browserSessionId}?${credentialParam}${forceCdp ? "&force_cdp=true" : ""}`;
+
socketRef.current?.close();
- const socket = new WebSocket(
- `${newWssBaseUrl}/stream/browser_sessions/${browserSessionId}?${credentialParam}${forceCdp ? "&force_cdp=true" : ""}`,
- );
+ const socket = new WebSocket(url);
socketRef.current = socket;
const isCurrentSocket = () => !cancelled && socketRef.current === socket;
diff --git a/skyvern-frontend/src/routes/browserSessions/hooks/useProcessRecordingMutation.test.tsx b/skyvern-frontend/src/routes/browserSessions/hooks/useProcessRecordingMutation.test.tsx
index 1072cbaff..94b326350 100644
--- a/skyvern-frontend/src/routes/browserSessions/hooks/useProcessRecordingMutation.test.tsx
+++ b/skyvern-frontend/src/routes/browserSessions/hooks/useProcessRecordingMutation.test.tsx
@@ -6,7 +6,6 @@ import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
import { WorkflowPermanentIdContext } from "@/routes/workflows/WorkflowPermanentIdContext";
-import { RECORD_BROWSER_V2_FLAG } from "@/util/featureFlags";
import {
useRecordingStore,
type OptimisticStep,
@@ -19,7 +18,6 @@ const mocks = vi.hoisted(() => ({
captureRecordBrowser: vi.fn(),
markRecordBrowserProcessed: vi.fn(),
post: vi.fn(),
- enabledFlags: new Set<string>(),
}));
vi.mock("@/api/AxiosClient", () => ({
@@ -33,7 +31,7 @@ vi.mock("@/hooks/useCredentialGetter", () => ({
}));
vi.mock("posthog-js/react", () => ({
- useFeatureFlagEnabled: (flag: string) => mocks.enabledFlags.has(flag),
+ useFeatureFlagEnabled: () => false,
}));
vi.mock("@/util/recordBrowserTelemetry", () => ({
@@ -63,37 +61,6 @@ const draftStep: RecordingDraftStep = {
parameter_keys: [],
};
-/** A message socket that answers the commit it is sent with a scripted reply. */
-function fakeMessageSocket() {
- const listeners = new Set<(event: MessageEvent) => void>();
- let reply: unknown = null;
- const socket = {
- readyState: WebSocket.OPEN,
- sent: [] as Array<unknown>,
- reply: (message: unknown) => {
- reply = message;
- },
- send: (payload: string) => {
- socket.sent.push(JSON.parse(payload));
- const event = new MessageEvent("message", {
- data: JSON.stringify(reply),
- });
- for (const listener of [...listeners]) {
- listener(event);
- }
- },
- addEventListener: (
- type: string,
- listener: (event: MessageEvent) => void,
- ) => (type === "message" ? listeners.add(listener) : undefined),
- removeEventListener: (
- _type: string,
- listener: (event: MessageEvent) => void,
- ) => listeners.delete(listener),
- };
- return socket as typeof socket & WebSocket;
-}
-
const optimisticStep: OptimisticStep = {
local_id: "optimistic-1",
action_kind: "click",
@@ -106,9 +73,7 @@ describe("useProcessRecordingMutation telemetry", () => {
vi.useFakeTimers({ shouldAdvanceTime: true });
vi.setSystemTime(1_000);
vi.clearAllMocks();
- mocks.enabledFlags.clear();
useRecordingStore.getState().reset();
- useRecordingStore.getState().setMessageSocket(null);
useRecordingStore.getState().setRecordingTransport("cdp");
useRecordingStore.getState().setIsRecording(true);
useRecordingStore.setState({ optimisticSteps: [optimisticStep] });
@@ -145,33 +110,4 @@ describe("useProcessRecordingMutation telemetry", () => {
},
);
});
-
- it("commits over the message socket instead of HTTP when record browser v2 is on", async () => {
- mocks.enabledFlags.add(RECORD_BROWSER_V2_FLAG);
- const blocks = [{ block_type: "action", label: "click_search" }];
- const socket = fakeMessageSocket();
- useRecordingStore.getState().setMessageSocket(socket);
- socket.reply({
- kind: "recording-committed",
- blocks,
- parameters: [],
- mode: "blocks",
- diagnostics: { rows: 2, facts: 1, dropped: 0, unlocatable: 0 },
- });
- const onSuccess = vi.fn();
- const { result } = renderHook(
- () =>
- useProcessRecordingMutation({ browserSessionId: "pbs-1", onSuccess }),
- { wrapper },
- );
-
- act(() => result.current.mutate({ draftSteps: [draftStep] }));
-
- await waitFor(() => expect(result.current.isSuccess).toBe(true));
- expect(socket.sent).toEqual([
- { kind: "recording-commit", mode: "auto", draft_steps: [draftStep] },
- ]);
- expect(mocks.post).not.toHaveBeenCalled();
- expect(onSuccess).toHaveBeenCalledWith({ blocks, parameters: [] });
- });
});
diff --git a/skyvern-frontend/src/routes/browserSessions/hooks/useProcessRecordingMutation.ts b/skyvern-frontend/src/routes/browserSessions/hooks/useProcessRecordingMutation.ts
index cdc5c2a9d..536f85fa4 100644
--- a/skyvern-frontend/src/routes/browserSessions/hooks/useProcessRecordingMutation.ts
+++ b/skyvern-frontend/src/routes/browserSessions/hooks/useProcessRecordingMutation.ts
@@ -5,12 +5,8 @@ import { useFeatureFlagEnabled } from "posthog-js/react";
import { getClient } from "@/api/AxiosClient";
import { toast } from "@/components/ui/use-toast";
import { useCredentialGetter } from "@/hooks/useCredentialGetter";
-import { commitRecordingOverMessageSocket } from "@/routes/streaming/useRecordingMessageChannel";
import { useWorkflowPermanentId } from "@/routes/workflows/WorkflowPermanentIdContext";
-import {
- RECORD_BROWSER_CODE_FIRST_FLAG,
- RECORD_BROWSER_V2_FLAG,
-} from "@/util/featureFlags";
+import { RECORD_BROWSER_CODE_FIRST_FLAG } from "@/util/featureFlags";
import {
useRecordingStore,
type RecordingDraftStep,
@@ -49,8 +45,6 @@ const useProcessRecordingMutation = ({
// Per-user opt-in preview; not enrolled reads as false (agent blocks).
const codeFirst =
useFeatureFlagEnabled(RECORD_BROWSER_CODE_FIRST_FLAG) ?? false;
- const recordBrowserV2 =
- useFeatureFlagEnabled(RECORD_BROWSER_V2_FLAG) ?? false;
const processRecordingMutation = useMutation({
mutationFn: async (
@@ -96,8 +90,6 @@ const useProcessRecordingMutation = ({
throw new Error(FAIL_QUIET_NO_EVENTS);
}
- // v2 captures nothing in the page, so there is no event stream to upload: with no
- // events this flushes nothing and returns [], and the draft steps are the recording.
const compressedChunks = await recordingStore.getCompressedChunks();
captureRecordBrowser("record_browser.process_attempted", {
@@ -106,20 +98,6 @@ const useProcessRecordingMutation = ({
draft_step_count: draftSteps?.length,
});
- if (recordBrowserV2) {
- // The v2 ledger lives on the pod holding the message socket, so the commit
- // rides that socket; "auto" renders code whenever every row is located, so
- // record_browser_code_first no longer changes what v2 produces.
- const committed = await commitRecordingOverMessageSocket({
- mode: "auto",
- draftSteps,
- });
- return {
- blocks: committed.blocks as Array<WorkflowBlock>,
- parameters: committed.parameters as Array<WorkflowParameter>,
- };
- }
-
const client = await getClient(credentialGetter, "sans-api-v1");
return client
.post<
diff --git a/skyvern-frontend/src/routes/discover/DiscoverPage.test.tsx b/skyvern-frontend/src/routes/discover/DiscoverPage.test.tsx
new file mode 100644
index 000000000..ec98f081c
--- /dev/null
+++ b/skyvern-frontend/src/routes/discover/DiscoverPage.test.tsx
@@ -0,0 +1,477 @@
+// @vitest-environment jsdom
+import { StrictMode, useState } from "react";
+import {
+ act,
+ cleanup,
+ fireEvent,
+ render,
+ screen,
+ waitFor,
+} from "@testing-library/react";
+import { MemoryRouter } from "react-router-dom";
+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
+import type {
+ ConfirmedPatch,
+ ConfirmedWriteResult,
+ OnboardingState,
+ QuestionnairePatchV1,
+ QuestionnaireStateV1,
+} from "@/store/onboarding/types";
+import { OnboardingContext } from "@/store/onboarding/useOnboardingState";
+import { DiscoverPage } from "./DiscoverPage";
+import { onboardingExampleRequest } from "./onboardingExample";
+
+type ProgressState = "active" | "dismissed" | "completed" | "ineligible";
+type ProgressActionKey = "first_agent_created" | "first_successful_run";
+
+const mocks = vi.hoisted(() => ({
+ confirmed: vi.fn<(patch: ConfirmedPatch) => Promise<ConfirmedWriteResult>>(),
+ progressState: null as ProgressState | null,
+ completedCount: 0 as 0 | 1,
+ firstMilestoneComplete: false,
+ nextActionKey: "first_agent_created" as ProgressActionKey,
+ createPending: false,
+ createWorkflow: vi.fn(),
+ progressPending: false,
+ dismiss: vi.fn(),
+ restore: vi.fn(),
+ telemetry: {
+ registerVariant: vi.fn(),
+ flowStarted: vi.fn(),
+ modalOpened: vi.fn(),
+ questionnaireShown: vi.fn<(input: unknown) => boolean>(() => true),
+ questionnaireCompleted: vi.fn(),
+ modalRenderError: vi.fn(),
+ },
+}));
+
+function progressForMocks() {
+ if (mocks.progressState === null) return null;
+ if (mocks.progressState !== "active") {
+ return { state: mocks.progressState };
+ }
+ return {
+ state: mocks.progressState,
+ completed_count: mocks.completedCount,
+ total_count: 2,
+ next_action_key: mocks.nextActionKey,
+ items: [
+ {
+ key: "first_agent_created",
+ completed_at: mocks.firstMilestoneComplete
+ ? "2026-08-20T12:00:00Z"
+ : null,
+ },
+ { key: "first_successful_run", completed_at: null },
+ ],
+ };
+}
+
+vi.mock("posthog-js/react", () => ({
+ useFeatureFlagVariantKey: () => "template-first",
+}));
+vi.mock("@clerk/clerk-react", () => ({
+ useAuth: () => ({ userId: "user-a" }),
+}));
+vi.mock("@/routes/workflows/hooks/useGlobalWorkflowsQuery", () => ({
+ useGlobalWorkflowsQuery: () => ({
+ data: [
+ {
+ workflow_permanent_id: "seeded-template",
+ title: "Seeded template",
+ description: "Template fixture",
+ workflow_definition: { blocks: [] },
+ },
+ ],
+ isLoading: false,
+ }),
+}));
+vi.mock("@/routes/workflows/hooks/useCreateWorkflowMutation", () => ({
+ useCreateWorkflowMutation: () => ({
+ mutate: mocks.createWorkflow,
+ isPending: mocks.createPending,
+ }),
+}));
+vi.mock("@/routes/tasks/create/PromptBox", () => ({
+ PromptBox: () => <div data-testid="discover-prompt">prompt</div>,
+}));
+vi.mock("./WorkflowTemplates", () => ({
+ WorkflowTemplates: () => (
+ <div data-testid="discover-templates">templates</div>
+ ),
+}));
+vi.mock("./useOnboardingProgress", () => ({
+ useOnboardingProgress: () => ({
+ progress: progressForMocks(),
+ isPending: mocks.progressPending,
+ dismiss: mocks.dismiss,
+ restore: mocks.restore,
+ }),
+}));
+vi.mock("@/components/onboarding/QuestionnaireDetailsStep", () => ({
+ QuestionnaireDetailsStep: ({
+ expectedRevision,
+ onAction,
+ }: {
+ expectedRevision: number;
+ onAction: (patch: QuestionnairePatchV1) => Promise<void>;
+ }) => (
+ <button
+ type="button"
+ onClick={() =>
+ void onAction({
+ version: 1,
+ mutation_id: `complete-${expectedRevision}`,
+ expected_revision: expectedRevision,
+ action: "complete",
+ role: "developer",
+ company_context: "startup",
+ scale_intent: "exploring",
+ referral_source: "search",
+ })
+ }
+ >
+ details-submit
+ </button>
+ ),
+}));
+vi.mock("@/util/onboarding/OnboardingTelemetry", () => ({
+ OnboardingTelemetry: mocks.telemetry,
+}));
+const baseState: OnboardingState = {
+ tour_completed_at: null,
+ modal_dismissed_at: null,
+ first_save_at: null,
+ first_run_at: null,
+ ab_variant: "template-first",
+ user_intent: null,
+ questionnaire: null,
+ questionnaire_prompted_at: null,
+ seen_canvas: null,
+ seen_node_adder: null,
+ seen_sidebar: null,
+ seen_save_run: null,
+};
+const questionnaire = (completed = false): QuestionnaireStateV1 => ({
+ version: 1,
+ response_id: "response",
+ revision: 1,
+ last_mutation_id: completed ? "complete-1" : "defer-1",
+ status: completed ? "completed" : "deferred",
+ role: completed ? "developer" : null,
+ company_context: completed ? "startup" : null,
+ scale_intent: completed ? "exploring" : null,
+ referral_source: completed ? "search" : null,
+ completed_at: completed ? "2026-01-01T00:00:00Z" : null,
+ skipped_at: null,
+ deferred_at: completed ? null : "2026-01-01T00:00:00Z",
+ updated_at: "2026-01-01T00:00:00Z",
+ defer_prompt_count: completed ? 0 : 1,
+});
+
+function deferred<T>() {
+ let resolve!: (value: T) => void;
+ const promise = new Promise<T>((resolvePromise) => {
+ resolve = resolvePromise;
+ });
+ return { promise, resolve };
+}
+
+function TestProvider({
+ initialState,
+ isNewUser = true,
+}: {
+ initialState: OnboardingState;
+ isNewUser?: boolean;
+}) {
+ const [state, setState] = useState(initialState);
+ return (
+ <OnboardingContext.Provider
+ value={{
+ state,
+ isLoading: false,
+ updateState: (patch) =>
+ setState((current) => ({ ...current, ...patch })),
+ updateStateConfirmed: async (patch) => {
+ const next = await mocks.confirmed(patch);
+ if ("onboarding_state" in next) {
+ setState(next.onboarding_state);
+ }
+ return next;
+ },
+ isNewUser,
+ abVariant: "template-first",
+ recoveryGuidanceAssignment: null,
+ }}
+ >
+ <MemoryRouter>
+ <DiscoverPage />
+ </MemoryRouter>
+ </OnboardingContext.Provider>
+ );
+}
+
+function renderDiscover(
+ initialState: OnboardingState,
+ strict = false,
+ isNewUser = true,
+) {
+ const page = (
+ <TestProvider initialState={initialState} isNewUser={isNewUser} />
+ );
+ return render(strict ? <StrictMode>{page}</StrictMode> : page);
+}
+
+beforeEach(() => {
+ sessionStorage.clear();
+ mocks.progressState = null;
+ mocks.createPending = false;
+ mocks.completedCount = 0;
+ mocks.firstMilestoneComplete = false;
+ mocks.nextActionKey = "first_agent_created";
+ mocks.progressPending = false;
+ mocks.confirmed.mockResolvedValue({
+ onboarding_state: baseState,
+ launch_date_at_signup: "2026-01-01T00:00:00Z",
+ recovery_guidance_assignment: null,
+ questionnaire_prompt_result: { status: "flag_disabled" },
+ });
+});
+afterEach(() => {
+ cleanup();
+ vi.clearAllMocks();
+});
+
+describe("DiscoverPage onboarding mount", () => {
+ it("preserves content order and mounts over seeded template data", async () => {
+ renderDiscover(baseState);
+ const content = screen.getByTestId("discover-templates").parentElement;
+ expect(content?.textContent).toBe(
+ "Create an agentpromptSkip — start with blank canvas →templates",
+ );
+ expect(await screen.findByRole("dialog")).toBeTruthy();
+ });
+
+ it("keeps Discover actions behind the modal while reservation is pending", async () => {
+ const reservation = deferred<ConfirmedWriteResult>();
+ mocks.confirmed.mockReturnValueOnce(reservation.promise);
+ const view = renderDiscover(baseState);
+ await waitFor(() => expect(mocks.confirmed).toHaveBeenCalledOnce());
+ const dialog = screen.getByRole("dialog");
+ expect(
+ screen.getByRole("heading", { name: "Getting started" }),
+ ).toBeTruthy();
+ expect(screen.getByText("Checking your onboarding setup.")).toBeTruthy();
+ expect(mocks.telemetry.modalOpened).not.toHaveBeenCalled();
+ expect(mocks.telemetry.questionnaireShown).not.toHaveBeenCalled();
+ const blankCanvas = screen.getByRole("button", {
+ name: /start with blank canvas/i,
+ hidden: true,
+ });
+
+ blankCanvas.focus();
+ await waitFor(() =>
+ expect(dialog.contains(document.activeElement)).toBe(true),
+ );
+ fireEvent.keyDown(document.activeElement!, { key: "Enter" });
+ expect(mocks.createWorkflow).not.toHaveBeenCalled();
+
+ view.unmount();
+ await act(async () =>
+ reservation.resolve({
+ onboarding_state: {
+ ...baseState,
+ questionnaire_prompted_at: "2026-08-27T00:00:00Z",
+ },
+ launch_date_at_signup: "2026-01-01T00:00:00Z",
+ recovery_guidance_assignment: null,
+ questionnaire_prompt_result: {
+ status: "reserved",
+ prompted_at: "2026-08-27T00:00:00Z",
+ },
+ }),
+ );
+ expect(mocks.telemetry.questionnaireShown).not.toHaveBeenCalled();
+ });
+
+ it("shields an eligible older-org user with a prior save", async () => {
+ const reservation = deferred<ConfirmedWriteResult>();
+ const firstSaveAt = "2026-08-20T00:00:00Z";
+ mocks.confirmed.mockReturnValueOnce(reservation.promise);
+ renderDiscover({ ...baseState, first_save_at: firstSaveAt }, false, false);
+ await waitFor(() => expect(mocks.confirmed).toHaveBeenCalledOnce());
+ const dialog = screen.getByRole("dialog");
+ const blankCanvas = screen.getByRole("button", {
+ name: /start with blank canvas/i,
+ hidden: true,
+ });
+ expect(
+ screen.getByRole("heading", { name: "Getting started" }),
+ ).toBeTruthy();
+
+ blankCanvas.focus();
+ await waitFor(() =>
+ expect(dialog.contains(document.activeElement)).toBe(true),
+ );
+ expect(mocks.createWorkflow).not.toHaveBeenCalled();
+
+ await act(async () =>
+ reservation.resolve({
+ onboarding_state: {
+ ...baseState,
+ first_save_at: firstSaveAt,
+ questionnaire_prompted_at: "2026-08-27T00:00:00Z",
+ },
+ launch_date_at_signup: "2026-01-01T00:00:00Z",
+ recovery_guidance_assignment: null,
+ questionnaire_prompt_result: {
+ status: "reserved",
+ prompted_at: "2026-08-27T00:00:00Z",
+ },
+ }),
+ );
+ expect(
+ await screen.findByRole("heading", {
+ name: "What do you want to automate?",
+ }),
+ ).toBeTruthy();
+ expect(mocks.telemetry.questionnaireShown).toHaveBeenCalledOnce();
+ });
+
+ it("renders without onboarding UI when no provider exists", () => {
+ render(<DiscoverPage />);
+ expect(screen.queryByRole("dialog")).toBeNull();
+ expect(mocks.telemetry.modalRenderError).not.toHaveBeenCalled();
+ });
+
+ it("routes stored intent into the editor fallback", async () => {
+ renderDiscover({ ...baseState, user_intent: "fill_forms" });
+ expect(await screen.findByText("Pick a template to start")).toBeTruthy();
+ });
+
+ it("keeps an established user without a pending questionnaire closed", async () => {
+ renderDiscover(
+ { ...baseState, user_intent: "fill_forms", questionnaire: null },
+ false,
+ false,
+ );
+ await waitFor(() => expect(mocks.confirmed).toHaveBeenCalledOnce());
+ await waitFor(() => expect(screen.queryByRole("dialog")).toBeNull());
+ expect(screen.queryByText("Getting started")).toBeNull();
+ });
+
+ it("keeps a completed questionnaire closed", () => {
+ renderDiscover({
+ ...baseState,
+ user_intent: "fill_forms",
+ questionnaire_prompted_at: "2026-08-27T00:00:00Z",
+ questionnaire: questionnaire(true),
+ });
+ expect(screen.queryByRole("dialog")).toBeNull();
+ expect(mocks.confirmed).not.toHaveBeenCalled();
+ });
+
+ it("never reopens a legacy deferred response", () => {
+ const deferredState = {
+ ...baseState,
+ user_intent: "fill_forms",
+ questionnaire: questionnaire(),
+ };
+ mocks.confirmed.mockResolvedValue({
+ onboarding_state: {
+ ...deferredState,
+ questionnaire: questionnaire(true),
+ },
+ launch_date_at_signup: "2026-01-01T00:00:00Z",
+ recovery_guidance_assignment: null,
+ });
+
+ renderDiscover(deferredState, true, false);
+ expect(screen.queryByText("Pick a template to start")).toBeNull();
+ expect(mocks.telemetry.questionnaireShown).not.toHaveBeenCalled();
+ expect(mocks.confirmed).not.toHaveBeenCalled();
+ });
+});
+
+describe("DiscoverPage progress surfaces", () => {
+ it("renders after PromptBox without an eager write, single-flights creation, and preserves focus on dismissal", () => {
+ mocks.progressState = "active";
+ const { container, rerender } = render(<DiscoverPage />);
+ expect(container.innerHTML).toMatch(
+ /<h1[^>]*>Create an agent<\/h1>.*prompt.*See how a workflow run is organized.*Build your first agent.*templates/s,
+ );
+ expect(mocks.createWorkflow).not.toHaveBeenCalled();
+
+ const workingExampleLink = screen.getByRole("link", {
+ name: "Use the working example",
+ });
+ const workingExampleHeading = screen.getByRole("heading", {
+ name: "See how a workflow run is organized",
+ });
+ expect(workingExampleLink.getAttribute("href")).toBe(
+ "#working-example-heading",
+ );
+ expect(workingExampleHeading.getAttribute("tabindex")).toBe("-1");
+ workingExampleLink.focus();
+ expect(document.activeElement).toBe(workingExampleLink);
+ fireEvent.keyDown(workingExampleLink, { key: "Enter" });
+ fireEvent.click(workingExampleLink);
+ expect(document.activeElement).toBe(workingExampleHeading);
+ const copy = screen.getByRole("button", { name: "Make a copy" });
+ const skip = screen.getByRole("button", {
+ name: /Skip — start with blank canvas/,
+ });
+ fireEvent.click(copy);
+ fireEvent.click(skip);
+ expect(mocks.createWorkflow).toHaveBeenCalledTimes(1);
+ expect(mocks.createWorkflow).toHaveBeenCalledWith(
+ {
+ ...onboardingExampleRequest,
+ _via: "onboarding_example",
+ },
+ { onSettled: expect.any(Function) },
+ );
+
+ mocks.createWorkflow.mock.calls[0]?.[1]?.onSettled?.();
+ fireEvent.click(skip);
+ expect(mocks.createWorkflow).toHaveBeenCalledTimes(2);
+
+ const hide = screen.getByRole("button", { name: "Hide setup" });
+ hide.focus();
+ fireEvent.click(hide);
+ expect(mocks.dismiss).toHaveBeenCalledTimes(1);
+
+ mocks.progressPending = true;
+ rerender(<DiscoverPage />);
+ const pendingHide = screen.getByRole("button", { name: "Hide setup" });
+ expect(pendingHide).toBe(hide);
+ expect(document.activeElement).toBe(pendingHide);
+ expect(pendingHide.getAttribute("aria-disabled")).toBe("true");
+ expect(pendingHide.hasAttribute("disabled")).toBe(false);
+ fireEvent.click(pendingHide);
+ expect(mocks.dismiss).toHaveBeenCalledTimes(1);
+
+ mocks.progressState = "dismissed";
+ mocks.progressPending = false;
+ rerender(<DiscoverPage />);
+ const resume = screen.getByRole("button", { name: "Resume setup" });
+ expect(resume).toBe(hide);
+ expect(document.activeElement).toBe(resume);
+ expect(
+ screen.queryByText("See how a workflow run is organized"),
+ ).toBeNull();
+ fireEvent.click(resume);
+ expect(mocks.restore).toHaveBeenCalledTimes(1);
+ });
+
+ it.each(["completed", "ineligible", null] as const)(
+ "retires all progress surfaces for %s progress",
+ (state) => {
+ mocks.progressState = state;
+ render(<DiscoverPage />);
+ expect(document.body.textContent).not.toMatch(
+ /Build your first agent|See how a workflow run is organized|Hide setup|Resume setup/,
+ );
+ },
+ );
+});
diff --git a/skyvern-frontend/src/routes/discover/DiscoverPage.tsx b/skyvern-frontend/src/routes/discover/DiscoverPage.tsx
index aa4ced68e..b32acae78 100644
--- a/skyvern-frontend/src/routes/discover/DiscoverPage.tsx
+++ b/skyvern-frontend/src/routes/discover/DiscoverPage.tsx
@@ -1,3 +1,8 @@
+import { useRef } from "react";
+import { GetStartedModal } from "@/components/onboarding/GetStartedModal";
+import { OnboardingErrorBoundary } from "@/components/onboarding/OnboardingErrorBoundary";
+import { OnboardingTelemetry } from "@/util/onboarding/OnboardingTelemetry";
+import { useOnboardingStateOptional } from "@/store/onboarding/useOnboardingState";
import { useFeatureFlag } from "@/hooks/useFeatureFlag";
import { PromptBox } from "../tasks/create/PromptBox";
import { WorkflowTemplates } from "./WorkflowTemplates";
@@ -5,37 +10,107 @@ import { useCreateWorkflowMutation } from "../workflows/hooks/useCreateWorkflowM
import { Button } from "@/components/ui/button";
import { ReloadIcon } from "@radix-ui/react-icons";
import { defaultWorkflowRequest } from "../workflows/defaultWorkflowRequest";
+import { WorkingExampleInspector } from "@/components/onboarding/WorkingExampleInspector";
+import { OnboardingProgressCard } from "@/components/onboarding/OnboardingProgressCard";
+import { useOnboardingProgress } from "./useOnboardingProgress";
+import { onboardingExampleRequest } from "./onboardingExample";
function DiscoverPage() {
const enableCopilotHandoff =
useFeatureFlag("ENABLE_DISCOVER_COPILOT_HANDOFF") === true;
const createWorkflowMutation = useCreateWorkflowMutation();
+ const createInFlight = useRef(false);
+ const {
+ progress,
+ isPending: onboardingProgressPending,
+ dismiss,
+ restore,
+ } = useOnboardingProgress();
+
+ const createWorkflow = (
+ request: Parameters<typeof createWorkflowMutation.mutate>[0],
+ ) => {
+ if (createInFlight.current || createWorkflowMutation.isPending) return;
+ createInFlight.current = true;
+ createWorkflowMutation.mutate(request, {
+ onSettled: () => {
+ createInFlight.current = false;
+ },
+ });
+ };
+
+ const handleExampleCopy = () => {
+ createWorkflow({
+ ...onboardingExampleRequest,
+ _via: "onboarding_example",
+ });
+ };
+
+ const onboarding = useOnboardingStateOptional();
return (
<div className="space-y-10">
+ <h1 className="sr-only">Create an agent</h1>
<div className="space-y-3">
<PromptBox enableCopilotHandoff={enableCopilotHandoff} />
<div className="flex justify-end">
<Button
variant="ghost"
size="sm"
- className="text-slate-400 hover:text-slate-200"
+ className="h-11 touch-manipulation text-muted-foreground hover:text-foreground"
disabled={createWorkflowMutation.isPending}
onClick={() =>
- createWorkflowMutation.mutate({
+ createWorkflow({
...defaultWorkflowRequest,
_via: "blank",
})
}
>
{createWorkflowMutation.isPending && (
- <ReloadIcon className="mr-2 h-3 w-3 animate-spin" />
+ <ReloadIcon
+ aria-hidden="true"
+ className="mr-2 h-3 w-3 motion-safe:animate-spin motion-reduce:animate-none"
+ />
)}
Skip — start with blank canvas →
</Button>
</div>
</div>
+ {progress?.state === "active" && (
+ <WorkingExampleInspector
+ isPending={createWorkflowMutation.isPending}
+ onMakeCopy={handleExampleCopy}
+ />
+ )}
+ {progress?.state === "active" &&
+ (progress.completed_count === 0 || progress.completed_count === 1) &&
+ progress.next_action_key !== null ? (
+ <OnboardingProgressCard
+ state="active"
+ completedCount={progress.completed_count}
+ firstMilestoneComplete={progress.items.some(
+ (item) =>
+ item.key === "first_agent_created" && item.completed_at !== null,
+ )}
+ nextActionKey={progress.next_action_key}
+ isPending={onboardingProgressPending}
+ onDismiss={dismiss}
+ />
+ ) : progress?.state === "dismissed" ? (
+ <OnboardingProgressCard
+ state="dismissed"
+ isPending={onboardingProgressPending}
+ onRestore={restore}
+ />
+ ) : null}
<WorkflowTemplates />
+ {onboarding ? (
+ <OnboardingErrorBoundary
+ onError={() => OnboardingTelemetry.modalRenderError("discover")}
+ >
+ <GetStartedModal />
+ </OnboardingErrorBoundary>
+ ) : null}
</div>
);
}
diff --git a/skyvern-frontend/src/routes/discover/WorkflowTemplates.tsx b/skyvern-frontend/src/routes/discover/WorkflowTemplates.tsx
index 604af3c8b..7561aa509 100644
--- a/skyvern-frontend/src/routes/discover/WorkflowTemplates.tsx
+++ b/skyvern-frontend/src/routes/discover/WorkflowTemplates.tsx
@@ -35,7 +35,7 @@ function WorkflowTemplates() {
return (
<div className="space-y-5">
- <h1 className="text-xl">Explore Agents</h1>
+ <h2 className="text-xl">Explore Agents</h2>
<Carousel
opts={{
align: "start",
diff --git a/skyvern-frontend/src/routes/discover/onboardingExample.test.ts b/skyvern-frontend/src/routes/discover/onboardingExample.test.ts
new file mode 100644
index 000000000..90af00081
--- /dev/null
+++ b/skyvern-frontend/src/routes/discover/onboardingExample.test.ts
@@ -0,0 +1,37 @@
+import { expect, it } from "vitest";
+import { RunEngine } from "@/api/types";
+import * as example from "./onboardingExample";
+const sensitiveKey =
+ /credential|session|profile|header|webhook|totp|(^|_)id($|_)/i;
+function assertNoSensitiveKeys(value: unknown): void {
+ if (Array.isArray(value)) return value.forEach(assertNoSensitiveKeys);
+ if (typeof value !== "object" || value === null) return;
+ Object.entries(value).forEach(([key, nested]) => {
+ expect(key).not.toMatch(sensitiveKey);
+ assertNoSensitiveKeys(nested);
+ });
+}
+it("keeps the copy payload to one passive public task", () => {
+ const { blocks } = example.onboardingExampleRequest.workflow_definition;
+ expect(blocks).toHaveLength(1);
+ const task = blocks[0]!;
+ expect(task).toMatchObject({
+ block_type: "task",
+ url: "https://www.skyvern.com/",
+ navigation_goal: null,
+ });
+ expect(task.engine).toBe(RunEngine.SkyvernV1);
+ assertNoSensitiveKeys(example.onboardingExampleRequest);
+});
+it("labels playback and result data as synthetic examples", () => {
+ const { provenance, playback, result } =
+ example.onboardingExamplePresentation;
+ expect(provenance).toBe("Example data, not your run");
+ expect(playback[0]).toMatch(/static example/);
+ expect(playback[2]).toMatch(/example result/);
+ expect(result.title).toMatch(/synthetic.*example/i);
+ expect(result.fields.map(({ label }) => label)).toEqual([
+ "Headline",
+ "Product summary",
+ ]);
+});
diff --git a/skyvern-frontend/src/routes/discover/onboardingExample.ts b/skyvern-frontend/src/routes/discover/onboardingExample.ts
new file mode 100644
index 000000000..1cf530954
--- /dev/null
+++ b/skyvern-frontend/src/routes/discover/onboardingExample.ts
@@ -0,0 +1,74 @@
+import { RunEngine } from "@/api/types";
+import type { WorkflowCreateYAMLRequest } from "@/routes/workflows/types/workflowYamlTypes";
+
+export const onboardingExamplePresentation = {
+ title: "See how a workflow run is organized",
+ provenance: "Example data, not your run",
+ structure: [
+ {
+ title: "Visit a public page",
+ detail: "Open Skyvern's public homepage without signing in.",
+ },
+ {
+ title: "Read public content",
+ detail: "Extract the headline and a short product summary.",
+ },
+ {
+ title: "Return structured data",
+ detail: "Keep the result to two short text fields.",
+ },
+ ],
+ playback: [
+ "Opened https://www.skyvern.com/ in this static example.",
+ "Read the public headline and product description.",
+ "Prepared the bounded example result shown below.",
+ ],
+ result: {
+ title: "Synthetic example result",
+ fields: [
+ {
+ label: "Headline",
+ value: "Automate browser-based work with AI",
+ },
+ {
+ label: "Product summary",
+ value:
+ "Skyvern runs browser workflows that interact with websites and extract structured data.",
+ },
+ ],
+ },
+} as const;
+
+export const onboardingExampleRequest = {
+ title: "Copyable example: Skyvern homepage summary",
+ description:
+ "Create a draft that reads public content from Skyvern's homepage.",
+ workflow_definition: {
+ parameters: [],
+ blocks: [
+ {
+ block_type: "task",
+ label: "Read Skyvern homepage",
+ url: "https://www.skyvern.com/",
+ navigation_goal: null,
+ data_extraction_goal:
+ "Extract the public headline and a short summary of what Skyvern does.",
+ data_schema: {
+ type: "object",
+ properties: {
+ headline: { type: "string", maxLength: 160 },
+ product_summary: { type: "string", maxLength: 320 },
+ },
+ required: ["headline", "product_summary"],
+ additionalProperties: false,
+ },
+ error_code_mapping: null,
+ disable_cache: false,
+ complete_criterion: null,
+ terminate_criterion: null,
+ include_action_history_in_verification: false,
+ engine: RunEngine.SkyvernV1,
+ },
+ ],
+ },
+} satisfies WorkflowCreateYAMLRequest;
diff --git a/skyvern-frontend/src/routes/discover/useOnboardingProgress.test.tsx b/skyvern-frontend/src/routes/discover/useOnboardingProgress.test.tsx
new file mode 100644
index 000000000..70147d748
--- /dev/null
+++ b/skyvern-frontend/src/routes/discover/useOnboardingProgress.test.tsx
@@ -0,0 +1,246 @@
+import type { ReactNode } from "react";
+import {
+ QueryClient,
+ QueryClientProvider,
+ QueryObserver,
+} from "@tanstack/react-query";
+import { act, renderHook, waitFor } from "@testing-library/react";
+import { beforeEach, expect, it, vi } from "vitest";
+const mocks = vi.hoisted<{
+ get: ReturnType<typeof vi.fn>;
+ flag: boolean | undefined;
+ org: string | undefined;
+ user: string | undefined;
+}>(() => ({
+ get: vi.fn(),
+ flag: true,
+ org: "org-test",
+ user: "user-test",
+}));
+vi.mock("@/api/AxiosClient", () => ({
+ getClient: () => Promise.resolve({ get: mocks.get }),
+}));
+vi.mock("@/hooks/useCredentialGetter", () => ({
+ useCredentialGetter: () => () => Promise.resolve("test-token"),
+}));
+vi.mock("@/hooks/useFeatureFlag", () => ({ useFeatureFlag: () => mocks.flag }));
+vi.mock("@/hooks/useUser", () => ({
+ useUser: () => ({
+ get: () => (mocks.user === undefined ? null : { id: mocks.user }),
+ }),
+}));
+vi.mock("@/store/ActiveOrgContext", async () => ({
+ ...(await vi.importActual<typeof import("@/store/ActiveOrgContext")>(
+ "@/store/ActiveOrgContext",
+ )),
+ useActiveOrgId: () => mocks.org,
+}));
+import { useOnboardingProgress } from "./useOnboardingProgress";
+const validPayload = () => ({
+ version: "onboarding_progress_v1",
+ state: "active",
+ completed_count: 0,
+ total_count: 2,
+ next_action_key: "first_agent_created",
+ items: [
+ { key: "first_agent_created", completed_at: null },
+ { key: "first_successful_run", completed_at: null },
+ ],
+});
+function renderProgress(client = new QueryClient()) {
+ const wrapper = ({ children }: { children: ReactNode }) => (
+ <QueryClientProvider client={client}>{children}</QueryClientProvider>
+ );
+ const hook = renderHook(() => useOnboardingProgress(), { wrapper });
+ return { client, ...hook };
+}
+beforeEach(() => {
+ vi.clearAllMocks();
+ mocks.flag = true;
+ mocks.org = "org-test";
+ mocks.user = "user-test";
+});
+it.each([
+ [false, "org-test", "user-test"],
+ [undefined, "org-test", "user-test"],
+ [true, undefined, "user-test"],
+ [true, "org-test", undefined],
+])("does not GET when onboarding progress is gated", (flag, org, user) => {
+ mocks.flag = flag;
+ mocks.org = org;
+ mocks.user = user;
+ renderProgress();
+ expect(mocks.get).not.toHaveBeenCalled();
+});
+it.each([
+ [validPayload(), "active"],
+ [{ ...validPayload(), version: "onboarding_progress_v0" }, null],
+])("parses valid V1 and hides malformed versions", async (data, expected) => {
+ mocks.flag = true;
+ mocks.org = "org-test";
+ mocks.user = "user-test";
+ mocks.get.mockResolvedValue({ data });
+ const { result } = renderProgress();
+ await waitFor(() => expect(mocks.get).toHaveBeenCalled());
+ await waitFor(() =>
+ expect(result.current.progress?.state ?? null).toBe(expected),
+ );
+});
+it("refetches fresh cached progress when Discover remounts", async () => {
+ const client = new QueryClient({
+ defaultOptions: {
+ queries: {
+ staleTime: 5 * 60 * 1_000,
+ },
+ },
+ });
+ const refreshedPayload = {
+ ...validPayload(),
+ completed_count: 1,
+ next_action_key: "first_successful_run",
+ items: [
+ {
+ key: "first_agent_created",
+ completed_at: "2026-08-20T12:00:00Z",
+ },
+ { key: "first_successful_run", completed_at: null },
+ ],
+ };
+ mocks.get
+ .mockResolvedValueOnce({ data: validPayload() })
+ .mockResolvedValueOnce({ data: refreshedPayload });
+
+ const firstMount = renderProgress(client);
+ await waitFor(() =>
+ expect(firstMount.result.current.progress?.completed_count).toBe(0),
+ );
+ expect(mocks.get).toHaveBeenCalledTimes(1);
+ firstMount.unmount();
+
+ const secondMount = renderProgress(client);
+ await waitFor(() => expect(mocks.get).toHaveBeenCalledTimes(2));
+ await waitFor(() =>
+ expect(secondMount.result.current.progress?.completed_count).toBe(1),
+ );
+ expect(secondMount.result.current.progress).toEqual(refreshedPayload);
+});
+it("isolates progress cache entries by authenticated user", async () => {
+ mocks.flag = true;
+ mocks.org = "org-test";
+ mocks.user = "user-a";
+ mocks.get.mockResolvedValue({ data: validPayload() });
+ const { client, rerender } = renderProgress();
+ await waitFor(() => expect(mocks.get).toHaveBeenCalledTimes(1));
+ expect(
+ client
+ .getQueryCache()
+ .findAll()
+ .map(({ queryKey }) => queryKey),
+ ).toContainEqual(["onboarding-progress", "user-a", "org-test"]);
+
+ mocks.user = "user-b";
+ rerender();
+ await waitFor(() => expect(mocks.get).toHaveBeenCalledTimes(2));
+ expect(
+ client
+ .getQueryCache()
+ .findAll()
+ .map(({ queryKey }) => queryKey),
+ ).toContainEqual(["onboarding-progress", "user-b", "org-test"]);
+});
+it("keeps forced out-of-order user responses isolated", async () => {
+ const userAPayload = validPayload();
+ const userBPayload = {
+ ...validPayload(),
+ completed_count: 1,
+ next_action_key: "first_successful_run",
+ items: [
+ {
+ key: "first_agent_created",
+ completed_at: "2026-08-20T12:00:00Z",
+ },
+ { key: "first_successful_run", completed_at: null },
+ ],
+ };
+ let resolveUserA: (response: { data: unknown }) => void = () => {
+ throw new Error("User A request did not initialize");
+ };
+ let resolveUserB: (response: { data: unknown }) => void = () => {
+ throw new Error("User B request did not initialize");
+ };
+ const userARequest = new Promise<{ data: unknown }>((resolve) => {
+ resolveUserA = resolve;
+ });
+ const userBRequest = new Promise<{ data: unknown }>((resolve) => {
+ resolveUserB = resolve;
+ });
+ mocks.get.mockReturnValueOnce(userARequest).mockReturnValueOnce(userBRequest);
+ mocks.user = "user-a";
+ const { client, result, rerender } = renderProgress();
+ const userAKey = ["onboarding-progress", "user-a", "org-test"] as const;
+ const userBKey = ["onboarding-progress", "user-b", "org-test"] as const;
+
+ await waitFor(() => expect(mocks.get).toHaveBeenCalledTimes(1));
+ const userAObserver = new QueryObserver(client, {
+ queryKey: userAKey,
+ enabled: false,
+ });
+ const unsubscribeUserA = userAObserver.subscribe(vi.fn());
+
+ mocks.user = "user-b";
+ rerender();
+ await waitFor(() => expect(mocks.get).toHaveBeenCalledTimes(2));
+ const pendingKeys = client
+ .getQueryCache()
+ .findAll()
+ .map(({ queryKey }) => queryKey);
+ expect(pendingKeys).toContainEqual(userAKey);
+ expect(pendingKeys).toContainEqual(userBKey);
+ expect(client.getQueryData(userAKey)).toBeUndefined();
+ expect(client.getQueryData(userBKey)).toBeUndefined();
+
+ await act(async () => {
+ resolveUserB({ data: userBPayload });
+ await userBRequest;
+ });
+ await waitFor(() => expect(result.current.progress?.completed_count).toBe(1));
+ expect(result.current.progress).toEqual(userBPayload);
+ expect(client.getQueryData(userBKey)).toEqual(userBPayload);
+ expect(client.getQueryData(userAKey)).toBeUndefined();
+
+ await act(async () => {
+ resolveUserA({ data: userAPayload });
+ await userARequest;
+ });
+ await waitFor(() =>
+ expect(client.getQueryData(userAKey)).toEqual(userAPayload),
+ );
+ expect(result.current.progress).toEqual(userBPayload);
+ expect(client.getQueryData(userBKey)).toEqual(userBPayload);
+ unsubscribeUserA();
+});
+const completedAt = "2026-08-20T12:00:00Z";
+it.each([
+ ["count mismatch", 1, "active", "first_agent_created", null, null],
+ ["run without agent", 1, "active", "first_successful_run", null, completedAt],
+ ["active with two/null next", 2, "active", null, completedAt, completedAt],
+ ["dismissed with next", 0, "dismissed", "first_agent_created", null, null],
+ ["completed with one", 1, "completed", null, completedAt, null],
+])("rejects contradictory %s progress", async (_name, ...row) => {
+ mocks.get.mockResolvedValue({
+ data: {
+ ...validPayload(),
+ completed_count: row[0],
+ state: row[1],
+ next_action_key: row[2],
+ items: [
+ { key: "first_agent_created", completed_at: row[3] },
+ { key: "first_successful_run", completed_at: row[4] },
+ ],
+ },
+ });
+ const { client } = renderProgress();
+ await waitFor(() =>
+ expect(client.getQueryCache().findAll()[0]?.state.data).toBeNull(),
+ );
+});
diff --git a/skyvern-frontend/src/routes/discover/useOnboardingProgress.ts b/skyvern-frontend/src/routes/discover/useOnboardingProgress.ts
new file mode 100644
index 000000000..aa0f9d875
--- /dev/null
+++ b/skyvern-frontend/src/routes/discover/useOnboardingProgress.ts
@@ -0,0 +1,156 @@
+import { getClient } from "@/api/AxiosClient";
+import { useCredentialGetter } from "@/hooks/useCredentialGetter";
+import { useFeatureFlag } from "@/hooks/useFeatureFlag";
+import { useUser } from "@/hooks/useUser";
+import {
+ getActiveOrgQueryKeyScope,
+ getOrgScopedQueryKey,
+ useActiveOrgId,
+} from "@/store/ActiveOrgContext";
+import { ONBOARDING_PROGRESS_FLAG } from "@/util/featureFlags";
+import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
+type ProgressActionKey = "first_agent_created" | "first_successful_run";
+type OnboardingProgressItemV1 = {
+ key: ProgressActionKey;
+ completed_at: string | null;
+};
+type OnboardingProgressV1 = {
+ version: "onboarding_progress_v1";
+ state: "ineligible" | "active" | "dismissed" | "completed";
+ completed_count: number;
+ total_count: 2;
+ next_action_key: ProgressActionKey | null;
+ items: [OnboardingProgressItemV1, OnboardingProgressItemV1];
+};
+const ISO_TIMESTAMP =
+ /^((?!0000)\d{4})-(0[1-9]|1[0-2])-(0[1-9]|[12]\d|3[01])T(?:[01]\d|2[0-3]):[0-5]\d:[0-5]\d(?:\.\d{1,6})?(?:Z|[+-](?:[01]\d|2[0-3]):[0-5]\d)$/;
+function isTimestampOrNull(value: unknown): value is string | null {
+ return (
+ value === null ||
+ (typeof value === "string" &&
+ ISO_TIMESTAMP.test(value) &&
+ new Date(`${value.slice(0, 10)}T00:00:00Z`).getUTCDate() ===
+ Number(value.slice(8, 10)))
+ );
+}
+function isRecord(value: unknown): value is Record<string, unknown> {
+ return typeof value === "object" && value !== null && !Array.isArray(value);
+}
+function parseItem(
+ value: unknown,
+ expectedKey: ProgressActionKey,
+): OnboardingProgressItemV1 | null {
+ if (
+ !isRecord(value) ||
+ Object.keys(value).length !== 2 ||
+ value.key !== expectedKey ||
+ !isTimestampOrNull(value.completed_at)
+ )
+ return null;
+ return { key: expectedKey, completed_at: value.completed_at };
+}
+function parseOnboardingProgress(value: unknown): OnboardingProgressV1 | null {
+ if (!isRecord(value) || Object.keys(value).length !== 6) return null;
+ const {
+ version,
+ state,
+ completed_count,
+ total_count,
+ next_action_key,
+ items,
+ } = value;
+ if (
+ version !== "onboarding_progress_v1" ||
+ (state !== "ineligible" &&
+ state !== "active" &&
+ state !== "dismissed" &&
+ state !== "completed") ||
+ typeof completed_count !== "number" ||
+ !Number.isInteger(completed_count) ||
+ completed_count < 0 ||
+ completed_count > 2 ||
+ total_count !== 2 ||
+ (next_action_key !== null &&
+ next_action_key !== "first_agent_created" &&
+ next_action_key !== "first_successful_run") ||
+ !Array.isArray(items) ||
+ items.length !== 2
+ )
+ return null;
+ const firstAgent = parseItem(items[0], "first_agent_created");
+ const firstRun = parseItem(items[1], "first_successful_run");
+ if (!firstAgent || !firstRun) return null;
+ const agentCompleted = firstAgent.completed_at !== null;
+ const runCompleted = firstRun.completed_at !== null;
+ const derivedCompletedCount = Number(agentCompleted) + Number(runCompleted);
+ const expectedActiveAction = agentCompleted
+ ? "first_successful_run"
+ : "first_agent_created";
+ if (
+ completed_count !== derivedCompletedCount ||
+ (runCompleted && !agentCompleted) ||
+ (state === "active" &&
+ (derivedCompletedCount === 2 ||
+ next_action_key !== expectedActiveAction)) ||
+ (state === "dismissed" &&
+ (derivedCompletedCount === 2 || next_action_key !== null)) ||
+ (state === "completed" &&
+ (derivedCompletedCount !== 2 || next_action_key !== null)) ||
+ (state === "ineligible" && next_action_key !== null)
+ )
+ return null;
+ return {
+ version,
+ state,
+ completed_count,
+ total_count,
+ next_action_key,
+ items: [firstAgent, firstRun],
+ };
+}
+function useOnboardingProgress() {
+ const credentialGetter = useCredentialGetter();
+ const activeOrgId = useActiveOrgId();
+ const activeUserId = useUser().get()?.id;
+ const queryClient = useQueryClient();
+ const enabled =
+ useFeatureFlag(ONBOARDING_PROGRESS_FLAG) === true &&
+ activeOrgId !== undefined &&
+ activeUserId !== undefined;
+ const queryKey = getOrgScopedQueryKey(
+ ["onboarding-progress", activeUserId],
+ getActiveOrgQueryKeyScope(activeOrgId),
+ );
+ const { data, isError } = useQuery<OnboardingProgressV1 | null>({
+ queryKey,
+ queryFn: async ({ signal }) => {
+ const client = await getClient(credentialGetter);
+ const response = await client.get<unknown>(
+ "/users/me/onboarding/progress",
+ { signal },
+ );
+ return parseOnboardingProgress(response.data);
+ },
+ enabled,
+ retry: false,
+ staleTime: 0,
+ refetchOnMount: "always",
+ refetchOnWindowFocus: "always",
+ });
+ const { isPending, mutate } = useMutation({
+ mutationFn: async (action: "dismiss" | "restore") => {
+ const client = await getClient(credentialGetter);
+ await client.post(`/users/me/onboarding/progress/${action}`, {
+ mutation_id: crypto.randomUUID(),
+ });
+ },
+ onSuccess: () => queryClient.invalidateQueries({ queryKey, exact: true }),
+ });
+ return {
+ progress: enabled && !isError ? (data ?? null) : null,
+ isPending,
+ dismiss: () => mutate("dismiss"),
+ restore: () => mutate("restore"),
+ };
+}
+export { useOnboardingProgress };
diff --git a/skyvern-frontend/src/routes/runs/RunRouter.test.tsx b/skyvern-frontend/src/routes/runs/RunRouter.test.tsx
index ee0f481fa..50bed24a9 100644
--- a/skyvern-frontend/src/routes/runs/RunRouter.test.tsx
+++ b/skyvern-frontend/src/routes/runs/RunRouter.test.tsx
@@ -1,7 +1,7 @@
// @vitest-environment jsdom
import { render, screen } from "@testing-library/react";
-import { MemoryRouter, Route, Routes } from "react-router-dom";
+import { MemoryRouter, Route, Routes, useLocation } from "react-router-dom";
import { beforeEach, describe, expect, test, vi } from "vitest";
import { useWorkflowPermanentId } from "@/routes/workflows/WorkflowPermanentIdContext";
@@ -22,7 +22,7 @@ const resolvedRun = {
};
const mocks = vi.hoisted(() => ({
- studioEnabled: vi.fn(() => true),
+ studioFlagState: vi.fn<() => boolean | undefined>(() => true),
taskV2: vi.fn(() => ({ data: undefined, isLoading: false })),
runQuery: vi.fn<
(options?: { workflowRunId?: string; enabled?: boolean }) => RunQueryResult
@@ -36,7 +36,8 @@ const mocks = vi.hoisted(() => ({
}));
vi.mock("@/hooks/useWorkflowStudioEnabled", () => ({
- useWorkflowStudioEnabled: () => mocks.studioEnabled(),
+ useWorkflowStudioFlagState: () => mocks.studioFlagState(),
+ useWorkflowStudioEnabled: () => mocks.studioFlagState() ?? false,
}));
vi.mock("@/routes/runs/useTaskV2Query", () => ({
useTaskV2Query: () => mocks.taskV2(),
@@ -58,6 +59,13 @@ vi.mock("@/routes/workflows/WorkflowRun", () => ({
WorkflowRun: () => <div data-testid="legacy">legacy</div>,
}));
+function LocationProbe() {
+ const location = useLocation();
+ return (
+ <div data-testid="location">{location.pathname + location.search}</div>
+ );
+}
+
function renderAt(entry: string) {
return render(
<MemoryRouter initialEntries={[entry]}>
@@ -65,6 +73,7 @@ function renderAt(entry: string) {
<Route path="/runs/:runId/*" element={<RunRouter />} />
<Route path="/agents/*" element={<div data-testid="redirected" />} />
</Routes>
+ <LocationProbe />
</MemoryRouter>,
);
}
@@ -85,7 +94,7 @@ function expectCenteredLoadingIndicator() {
describe("RunRouter", () => {
beforeEach(() => {
- mocks.studioEnabled.mockReturnValue(true);
+ mocks.studioFlagState.mockReturnValue(true);
mocks.taskV2.mockReturnValue({ data: undefined, isLoading: false });
mocks.runQuery.mockReturnValue({ data: resolvedRun, isLoading: false });
});
@@ -127,7 +136,7 @@ describe("RunRouter", () => {
});
test("studio off: keeps the legacy run view", () => {
- mocks.studioEnabled.mockReturnValue(false);
+ mocks.studioFlagState.mockReturnValue(false);
renderAt("/runs/wr_1");
expect(screen.getByTestId("legacy")).toBeTruthy();
expect(screen.queryByTestId("studio")).toBeNull();
@@ -141,7 +150,7 @@ describe("RunRouter", () => {
});
test("studio off: disables the run-resolver query so non-studio routes don't fetch a workflow run", () => {
- mocks.studioEnabled.mockReturnValue(false);
+ mocks.studioFlagState.mockReturnValue(false);
renderAt("/runs/wr_1");
expect(mocks.runQuery).toHaveBeenCalledWith(
expect.objectContaining({ enabled: false }),
@@ -154,6 +163,17 @@ describe("RunRouter", () => {
expect(screen.queryByTestId("studio")).toBeNull();
});
+ test("embed=true honors ?wr= even while the studio flag is unresolved", () => {
+ // Embed never renders the studio shell, so there is no URL state to protect
+ // and the redirect need not wait for the flag.
+ mocks.studioFlagState.mockReturnValue(undefined);
+ renderAt("/runs/wr_1?embed=true&wr=wr_2&active=act_9");
+ expect(screen.getByTestId("location").textContent).toBe(
+ "/runs/wr_2/overview?embed=true&active=act_9",
+ );
+ expect(screen.getByTestId("legacy")).toBeTruthy();
+ });
+
test("a permanently failed run fetch lands on 404, not an endless spinner", () => {
mocks.runQuery.mockReturnValue({
data: undefined,
@@ -166,6 +186,81 @@ describe("RunRouter", () => {
expect(screen.queryByTestId("legacy")).toBeNull();
});
+ test("studio off: a studio-shared link resolves to the ?wr= run, selection intact", () => {
+ // The studio switches runs by rewriting ?wr= and leaving the path alone, so
+ // its URLs can carry a stale run id in the path. Flag-off must land on the
+ // ?wr= run — straight onto the sub-path so the index redirect can't drop
+ // ?active= (the shared selection).
+ mocks.studioFlagState.mockReturnValue(false);
+ renderAt(
+ "/runs/wr_1?wr=wr_2&panes=editor,overview&active=act_9&selected-block=Payment",
+ );
+ expect(screen.getByTestId("location").textContent).toBe(
+ "/runs/wr_2/overview?panes=editor,overview&active=act_9&selected-block=Payment",
+ );
+ expect(screen.getByTestId("legacy")).toBeTruthy();
+ expect(screen.queryByTestId("studio")).toBeNull();
+ });
+
+ test("studio off: ?wr= naming the path run is not a redirect", () => {
+ mocks.studioFlagState.mockReturnValue(false);
+ renderAt("/runs/wr_1?wr=wr_1&active=act_9");
+ expect(screen.getByTestId("location").textContent).toBe(
+ "/runs/wr_1?wr=wr_1&active=act_9",
+ );
+ expect(screen.getByTestId("legacy")).toBeTruthy();
+ });
+
+ test("flag unresolved: no rewrite — a studio user's URL state must survive cold load", () => {
+ mocks.studioFlagState.mockReturnValue(undefined);
+ renderAt("/runs/wr_1?wr=wr_2&panes=editor,overview&active=act_9");
+ expect(screen.getByTestId("location").textContent).toBe(
+ "/runs/wr_1?wr=wr_2&panes=editor,overview&active=act_9",
+ );
+ expect(screen.getByTestId("legacy")).toBeTruthy();
+ });
+
+ test("studio off: /blocks maps to /overview and the studio-internal ?wrs=/?bl= are scrubbed", () => {
+ // /blocks immediately re-navigates to /overview without the search, and
+ // ?wrs=/?bl= are companions of the ?wr= being promoted into the path.
+ mocks.studioFlagState.mockReturnValue(false);
+ renderAt("/runs/wr_1/blocks?wr=wr_2&wrs=copilot&bl=Login&active=act_9");
+ expect(screen.getByTestId("location").textContent).toBe(
+ "/runs/wr_2/overview?active=act_9",
+ );
+ });
+
+ test("studio off: the splat is whitelisted — known sub-paths forward, anything else lands on overview", () => {
+ mocks.studioFlagState.mockReturnValue(false);
+ const first = renderAt("/runs/wr_1/recording?wr=wr_2");
+ expect(screen.getByTestId("location").textContent).toBe(
+ "/runs/wr_2/recording",
+ );
+ first.unmount();
+ renderAt("/runs/wr_1/%2E%2E%2Fagents?wr=wr_2&active=act_9");
+ expect(screen.getByTestId("location").textContent).toBe(
+ "/runs/wr_2/overview?active=act_9",
+ );
+ });
+
+ test("studio off: a malformed ?wr= is ignored, not spliced into the path", () => {
+ mocks.studioFlagState.mockReturnValue(false);
+ const wr = encodeURIComponent("wr_2/../../agents/wpid_x/studio");
+ renderAt(`/runs/wr_1?wr=${wr}`);
+ expect(screen.getByTestId("location").textContent).toBe(
+ `/runs/wr_1?wr=${wr}`,
+ );
+ expect(screen.getByTestId("legacy")).toBeTruthy();
+ });
+
+ test("studio on: the studio owns ?wr= — the path is never rewritten under it", () => {
+ renderAt("/runs/wr_1?wr=wr_2&panes=editor,overview");
+ expect(screen.getByTestId("studio").textContent).toBe("studio:wpid_123");
+ expect(screen.getByTestId("location").textContent).toBe(
+ "/runs/wr_1?wr=wr_2&panes=editor,overview",
+ );
+ });
+
test("a failed background poll keeps the studio view while the live run stays retained", () => {
// isError flips true when a 5s poll of a live run fails, but keepPreviousData
// still holds the matching run; the resolved run must win over the error so a
diff --git a/skyvern-frontend/src/routes/runs/RunRouter.tsx b/skyvern-frontend/src/routes/runs/RunRouter.tsx
index cc691cc40..3df0d2947 100644
--- a/skyvern-frontend/src/routes/runs/RunRouter.tsx
+++ b/skyvern-frontend/src/routes/runs/RunRouter.tsx
@@ -30,8 +30,22 @@ import { WorkflowsPageLayout } from "@/routes/workflows/WorkflowsPageLayout";
import { WorkflowEditor } from "@/routes/workflows/editor/WorkflowEditor";
import { WorkflowPermanentIdContext } from "@/routes/workflows/WorkflowPermanentIdContext";
import { useWorkflowRunWithWorkflowQuery } from "@/routes/workflows/hooks/useWorkflowRunWithWorkflowQuery";
-import { useWorkflowStudioEnabled } from "@/hooks/useWorkflowStudioEnabled";
+import { useWorkflowStudioFlagState } from "@/hooks/useWorkflowStudioEnabled";
import { useTaskV2Query } from "@/routes/runs/useTaskV2Query";
+import {
+ SYSTEM_RUN_FOCUS_PARAM,
+ toReadableSearch,
+} from "@/routes/workflows/studio/panes";
+
+// Sub-paths the ?wr= redirect below may forward; anything else (including the
+// self-redirecting blocks route and crafted splats) lands on overview.
+const REDIRECTABLE_RUN_SUBPATHS = new Set([
+ "overview",
+ "output",
+ "parameters",
+ "recording",
+ "code",
+]);
const loadingIndicator = (
<div
@@ -46,8 +60,9 @@ const loadingIndicator = (
);
function RunRouter() {
- const { runId } = useParams();
- const studioEnabled = useWorkflowStudioEnabled();
+ const { runId, "*": subPath } = useParams();
+ const studioFlagState = useWorkflowStudioFlagState();
+ const studioEnabled = studioFlagState ?? false;
const { data: task_v2, isLoading } = useTaskV2Query({
id: runId?.startsWith("tsk_v2") ? runId : undefined,
@@ -172,6 +187,34 @@ function RunRouter() {
);
}
+ // A studio URL carries the viewed run in ?wr= and a possibly stale one in the
+ // path, so honor ?wr= here — but only once the flag is known off (or under
+ // ?embed=true, which never renders the studio), since rewriting while flags
+ // resolve would strip a studio user's URL state. Land on the sub-path
+ // directly because the index and /blocks redirects drop the search (?active=
+ // must survive), and scrub ?wrs=/?bl=, studio-internal companions of ?wr=.
+ const sharedStudioRunId = searchParams.get("wr");
+ if (
+ runType === "workflow" &&
+ (studioFlagState === false || isEmbedded) &&
+ sharedStudioRunId !== null &&
+ /^wr_\w+$/.test(sharedStudioRunId) &&
+ sharedStudioRunId !== runId
+ ) {
+ const params = new URLSearchParams(searchParams);
+ params.delete("wr");
+ params.delete(SYSTEM_RUN_FOCUS_PARAM);
+ params.delete("bl");
+ const targetSubPath =
+ subPath && REDIRECTABLE_RUN_SUBPATHS.has(subPath) ? subPath : "overview";
+ return (
+ <Navigate
+ to={`/runs/${sharedStudioRunId}/${targetSubPath}${toReadableSearch(params)}`}
+ replace
+ />
+ );
+ }
+
return routes;
}
diff --git a/skyvern-frontend/src/routes/streaming/useCdpInput.test.ts b/skyvern-frontend/src/routes/streaming/useCdpInput.test.ts
index bc5254960..493df3307 100644
--- a/skyvern-frontend/src/routes/streaming/useCdpInput.test.ts
+++ b/skyvern-frontend/src/routes/streaming/useCdpInput.test.ts
@@ -209,7 +209,6 @@ describe("useCdpInput reconnects", () => {
});
afterEach(() => {
- vi.restoreAllMocks();
vi.useRealTimers();
vi.unstubAllGlobals();
});
@@ -224,30 +223,6 @@ describe("useCdpInput reconnects", () => {
expect(MockWebSocket.instances).toHaveLength(2);
});
- it("reports input RTT from a pong message", async () => {
- const { result } = renderHook(() =>
- useCdpInput({
- inputWsUrl: "wss://input.test",
- interactive: true,
- viewportWidth: 1280,
- viewportHeight: 720,
- }),
- );
- await act(async () => {
- await Promise.resolve();
- });
- expect(result.current.inputRttMs).toBeNull();
- vi.spyOn(performance, "now").mockReturnValue(250);
-
- act(() => {
- MockWebSocket.instances[0]!.emitMessage(
- JSON.stringify({ kind: "pong", t: 200 }),
- );
- });
-
- expect(result.current.inputRttMs).toBe(50);
- });
-
it("requires and sends a fresh take-control after reconnect", async () => {
const result = await renderControllingInputHook();
const firstSocket = MockWebSocket.instances[0]!;
diff --git a/skyvern-frontend/src/routes/streaming/useCdpInput.ts b/skyvern-frontend/src/routes/streaming/useCdpInput.ts
index d55ea0ab8..36e711e98 100644
--- a/skyvern-frontend/src/routes/streaming/useCdpInput.ts
+++ b/skyvern-frontend/src/routes/streaming/useCdpInput.ts
@@ -22,13 +22,13 @@ interface UseCdpInputOptions {
viewportHeight: number;
onClipboardPaste?: (text: string) => void;
onClipboardCopy?: () => void;
+ onInput?: () => void;
}
interface UseCdpInputReturn {
userIsControlling: boolean;
setUserIsControlling: (v: boolean) => void;
inputReady: boolean;
- inputRttMs: number | null;
containerRef: React.RefObject<HTMLDivElement>;
handlers: {
handleMouseDown: (e: React.MouseEvent<HTMLImageElement>) => void;
@@ -62,10 +62,10 @@ export function useCdpInput({
viewportHeight,
onClipboardPaste,
onClipboardCopy,
+ onInput,
}: UseCdpInputOptions): UseCdpInputReturn {
const [userIsControlling, setUserIsControlling] = useState(false);
const [inputReady, setInputReady] = useState(false);
- const [inputRttMs, setInputRttMs] = useState<number | null>(null);
const [navigateError, setNavigateError] = useState<string | null>(null);
const credentialGetter = useCredentialGetter();
const clientId = useClientIdStore((s) => s.clientId);
@@ -77,7 +77,6 @@ export function useCdpInput({
null,
);
const inputReconnectAttemptsRef = useRef(0);
- const inputPingTimerRef = useRef<ReturnType<typeof setInterval> | null>(null);
const inputStoppedRef = useRef(false);
const inputEventCountRef = useRef(0);
const wheelAccumulatorRef = useRef<{
@@ -100,8 +99,10 @@ export function useCdpInput({
const interceptedClipboardKeysRef = useRef(new Set<string>());
const onClipboardPasteRef = useRef(onClipboardPaste);
const onClipboardCopyRef = useRef(onClipboardCopy);
+ const onInputRef = useRef(onInput);
onClipboardPasteRef.current = onClipboardPaste;
onClipboardCopyRef.current = onClipboardCopy;
+ onInputRef.current = onInput;
useEffect(() => {
if (!interactive || !inputWsUrl) return;
@@ -109,17 +110,9 @@ export function useCdpInput({
inputStoppedRef.current = false;
inputReconnectAttemptsRef.current = 0;
- function clearInputPingTimer() {
- if (inputPingTimerRef.current) {
- clearInterval(inputPingTimerRef.current);
- inputPingTimerRef.current = null;
- }
- }
-
function connectInputWs(credentialParam: string) {
if (inputStoppedRef.current) return;
if (inputSocketRef.current) {
- clearInputPingTimer();
inputSocketRef.current.close();
}
const ws = new WebSocket(
@@ -130,14 +123,6 @@ export function useCdpInput({
ws.addEventListener("open", () => {
if (inputSocketRef.current !== ws) return;
console.log("[cdp-input] WebSocket connected");
- inputPingTimerRef.current = setInterval(() => {
- if (
- inputSocketRef.current === ws &&
- ws.readyState === WebSocket.OPEN
- ) {
- ws.send(JSON.stringify({ type: "ping", t: performance.now() }));
- }
- }, 5000);
if (userIsControllingRef.current) {
ws.send(JSON.stringify({ kind: "take-control" }));
}
@@ -160,9 +145,6 @@ export function useCdpInput({
ws.send(JSON.stringify({ kind: "take-control" }));
}
}
- if (msg.kind === "pong" && typeof msg.t === "number") {
- setInputRttMs(performance.now() - msg.t);
- }
if (msg.kind === "navigate-error") {
setNavigateError(
NAVIGATE_ERROR_MESSAGES[msg.reason] ??
@@ -176,9 +158,7 @@ export function useCdpInput({
ws.addEventListener("close", (event) => {
console.log("[cdp-input] WebSocket closed", event.code, event.reason);
if (inputSocketRef.current !== ws) return;
- clearInputPingTimer();
setInputReady(false);
- setInputRttMs(null);
userIsControllingRef.current = false;
setUserIsControlling(false);
inputSocketRef.current = null;
@@ -222,7 +202,6 @@ export function useCdpInput({
clearTimeout(inputReconnectTimerRef.current);
inputReconnectTimerRef.current = null;
}
- clearInputPingTimer();
if (inputSocketRef.current) {
inputSocketRef.current.close();
inputSocketRef.current = null;
@@ -351,6 +330,7 @@ export function useCdpInput({
console.log("[cdp-input] Sending:", payload.type, payload.eventType);
inputEventCountRef.current++;
}
+ onInputRef.current?.();
ws.send(JSON.stringify(payload));
}, []);
@@ -540,7 +520,6 @@ export function useCdpInput({
userIsControlling,
setUserIsControlling,
inputReady,
- inputRttMs,
containerRef,
handlers: {
handleMouseDown,
diff --git a/skyvern-frontend/src/routes/streaming/useRecordingMessageChannel.test.ts b/skyvern-frontend/src/routes/streaming/useRecordingMessageChannel.test.ts
index c0ac66e6b..7120f4260 100644
--- a/skyvern-frontend/src/routes/streaming/useRecordingMessageChannel.test.ts
+++ b/skyvern-frontend/src/routes/streaming/useRecordingMessageChannel.test.ts
@@ -7,10 +7,7 @@ import {
type RecordingDraftStep,
} from "@/store/useRecordingStore";
-import {
- commitRecordingOverMessageSocket,
- useRecordingMessageChannel,
-} from "./useRecordingMessageChannel";
+import { useRecordingMessageChannel } from "./useRecordingMessageChannel";
const mocks = vi.hoisted(() => ({
getWebSocketParams: vi.fn(async () => "client_id=client-test"),
@@ -34,48 +31,23 @@ class MockWebSocket {
onopen: ((event: Event) => void) | null = null;
onmessage: ((event: MessageEvent) => void) | null = null;
onclose: ((event: CloseEvent) => void) | null = null;
- readonly listeners = new Map<string, Set<(event: Event) => void>>();
constructor(readonly url: string) {
MockWebSocket.instances.push(this);
}
- addEventListener(type: string, listener: (event: never) => void) {
- const listeners = this.listeners.get(type) ?? new Set();
- listeners.add(listener as (event: Event) => void);
- this.listeners.set(type, listeners);
- }
-
- removeEventListener(type: string, listener: (event: never) => void) {
- this.listeners.get(type)?.delete(listener as (event: Event) => void);
- }
-
- listenerCount(type: string) {
- return this.listeners.get(type)?.size ?? 0;
- }
-
- private dispatch(type: string, event: Event) {
- for (const listener of [...(this.listeners.get(type) ?? [])]) {
- listener(event);
- }
- }
-
emitOpen() {
this.onopen?.(new Event("open"));
}
emitMessage(message: unknown) {
- const event = new MessageEvent("message", {
- data: JSON.stringify(message),
- });
- this.onmessage?.(event);
- this.dispatch("message", event);
+ this.onmessage?.(
+ new MessageEvent("message", { data: JSON.stringify(message) }),
+ );
}
emitClose(code = 1006) {
- const event = new CloseEvent("close", { code });
- this.onclose?.(event);
- this.dispatch("close", event);
+ this.onclose?.(new CloseEvent("close", { code }));
}
}
@@ -475,116 +447,3 @@ describe("useRecordingMessageChannel", () => {
});
});
});
-
-describe("commitRecordingOverMessageSocket", () => {
- beforeEach(() => {
- vi.clearAllMocks();
- MockWebSocket.instances = [];
- vi.stubGlobal("WebSocket", MockWebSocket);
- useRecordingStore.setState(initialRecordingState, true);
- useRecordingStore.getState().reset();
- });
-
- afterEach(() => {
- vi.unstubAllGlobals();
- useRecordingStore.setState(initialRecordingState, true);
- });
-
- async function connectedSocket() {
- renderHook(() =>
- useRecordingMessageChannel({
- browserSessionId: "pbs-1",
- enabled: true,
- exfiltrate: false,
- workflowPermanentId: null,
- clipboard: "none",
- }),
- );
- return openSocket();
- }
-
- const draftStep: RecordingDraftStep = {
- step_id: "step-1",
- action_kind: "click",
- block_type: "action",
- label: "Click submit",
- status: "ready",
- editable_fields: [],
- parameters: [],
- parameter_keys: [],
- };
-
- it("sends the commit and resolves on recording-committed", async () => {
- const socket = await connectedSocket();
-
- const committed = commitRecordingOverMessageSocket({
- mode: "auto",
- draftSteps: [draftStep],
- });
-
- expect(
- socket.send.mock.calls.map((call) => JSON.parse(String(call[0]))),
- ).toContainEqual({
- kind: "recording-commit",
- mode: "auto",
- draft_steps: [draftStep],
- });
-
- act(() =>
- socket.emitMessage({
- kind: "recording-committed",
- blocks: [{ block_type: "action" }],
- parameters: [],
- mode: "blocks",
- diagnostics: { rows: 2, facts: 1, dropped: 0, unlocatable: 0 },
- }),
- );
-
- await expect(committed).resolves.toMatchObject({
- mode: "blocks",
- blocks: [{ block_type: "action" }],
- });
- expect(socket.listenerCount("message")).toBe(0);
- expect(socket.listenerCount("close")).toBe(0);
- });
-
- it("rejects when the backend reports the commit failed", async () => {
- const socket = await connectedSocket();
-
- const committed = commitRecordingOverMessageSocket({
- mode: "auto",
- draftSteps: null,
- });
-
- act(() =>
- socket.emitMessage({
- kind: "error",
- failed_kind: "recording-commit",
- message: "Failed to render the recording.",
- }),
- );
-
- await expect(committed).rejects.toThrow("Failed to render the recording.");
- expect(socket.listenerCount("message")).toBe(0);
- });
-
- it("rejects when the socket closes before the commit comes back", async () => {
- const socket = await connectedSocket();
-
- const committed = commitRecordingOverMessageSocket({
- mode: "auto",
- draftSteps: null,
- });
-
- act(() => socket.emitClose());
-
- await expect(committed).rejects.toThrow(/closed/);
- expect(socket.listenerCount("close")).toBe(0);
- });
-
- it("rejects without a connected socket", async () => {
- await expect(
- commitRecordingOverMessageSocket({ mode: "auto", draftSteps: null }),
- ).rejects.toThrow(/not available/);
- });
-});
diff --git a/skyvern-frontend/src/routes/streaming/useRecordingMessageChannel.ts b/skyvern-frontend/src/routes/streaming/useRecordingMessageChannel.ts
index 1270c1b00..8692b2b10 100644
--- a/skyvern-frontend/src/routes/streaming/useRecordingMessageChannel.ts
+++ b/skyvern-frontend/src/routes/streaming/useRecordingMessageChannel.ts
@@ -6,7 +6,6 @@ import {
useRecordingStore,
type ExfiltratedEventConsoleParams,
type MessageInExfiltratedEvent,
- type RecordingDraftStep,
type RecordingInterpretationUpdate,
} from "@/store/useRecordingStore";
import { copyText } from "@/util/copyText";
@@ -106,7 +105,6 @@ const messageInKinds = [
"copied-text",
"error",
"exfiltrated-event",
- "recording-committed",
"recording-interpretation-update",
] as const;
@@ -131,23 +129,11 @@ interface MessageInRecordingInterpretationUpdate extends RecordingInterpretation
kind: "recording-interpretation-update";
}
-export interface RecordingCommitResult {
- blocks: Array<unknown>;
- parameters: Array<unknown>;
- mode: string;
- diagnostics: Record<string, number>;
-}
-
-interface MessageInRecordingCommitted extends RecordingCommitResult {
- kind: "recording-committed";
-}
-
type MessageIn =
| MessageInCopiedText
| MessageInError
| MessageInAskForClipboard
| MessageInExfiltratedEvent
- | MessageInRecordingCommitted
| MessageInRecordingInterpretationUpdate;
function getMessage(data: unknown): MessageIn | undefined {
@@ -225,9 +211,6 @@ function getMessage(data: unknown): MessageIn | undefined {
}
break;
}
- case "recording-committed": {
- return data as MessageInRecordingCommitted;
- }
case "recording-interpretation-update": {
// steps is optional: a delta update carries changed_steps instead. Only
// session_revision is required to accept the message.
@@ -425,10 +408,6 @@ function handleMessage(
store.add(message);
break;
}
- case "recording-committed": {
- // commitRecordingOverMessageSocket resolves this on its own listener.
- break;
- }
case "recording-interpretation-update": {
useRecordingStore.getState().applyInterpretationUpdate({
interpretation_session_id: message.interpretation_session_id,
@@ -448,72 +427,6 @@ function handleMessage(
}
}
-const COMMIT_TIMEOUT_MS = 60_000;
-
-// The v2 ledger is process-local to the pod holding this socket, so the commit rides
-// the socket rather than an HTTP POST that could land on another pod.
-export function commitRecordingOverMessageSocket(args: {
- mode: "blocks" | "auto";
- draftSteps: Array<RecordingDraftStep> | null;
-}): Promise<RecordingCommitResult> {
- const socket = useRecordingStore.getState().messageSocket;
- if (!socket || socket.readyState !== WebSocket.OPEN) {
- return Promise.reject(
- new Error("The recording connection is not available; try again."),
- );
- }
-
- return new Promise<RecordingCommitResult>((resolve, reject) => {
- const settle = (outcome: () => void) => {
- socket.removeEventListener("message", onMessage);
- socket.removeEventListener("close", onClose);
- clearTimeout(timer);
- outcome();
- };
-
- const onClose = () =>
- settle(() =>
- reject(
- new Error("The recording connection closed before it finished."),
- ),
- );
-
- const onMessage = (event: MessageEvent) => {
- let parsed: unknown;
- try {
- parsed = JSON.parse(event.data);
- } catch {
- return;
- }
- const message = getMessage(parsed);
- if (message?.kind === "recording-committed") {
- settle(() => resolve(message));
- } else if (
- message?.kind === "error" &&
- message.failed_kind === "recording-commit"
- ) {
- settle(() => reject(new Error(message.message)));
- }
- };
-
- const timer = setTimeout(
- () =>
- settle(() => reject(new Error("Timed out processing the recording."))),
- COMMIT_TIMEOUT_MS,
- );
-
- socket.addEventListener("message", onMessage);
- socket.addEventListener("close", onClose);
- socket.send(
- JSON.stringify({
- kind: "recording-commit",
- mode: args.mode,
- draft_steps: args.draftSteps,
- }),
- );
- });
-}
-
export function useRecordingMessageChannel(
options: UseRecordingMessageChannelOptions,
): UseRecordingMessageChannelResult {
@@ -605,10 +518,6 @@ export function useRecordingMessageChannel(
event: CloseEvent,
disconnectedSocket: WebSocket | null,
) => {
- const store = useRecordingStore.getState();
- if (store.messageSocket === disconnectedSocket) {
- store.setMessageSocket(null);
- }
if (
disconnectedSocket === null ||
messageSocketRef.current === disconnectedSocket
@@ -630,7 +539,6 @@ export function useRecordingMessageChannel(
ws.onopen = () => {
if (cancelled) return;
- useRecordingStore.getState().setMessageSocket(ws);
messageSocketRef.current = ws;
setIsMessageConnected(true);
setMessageSocket(ws);
@@ -688,9 +596,6 @@ export function useRecordingMessageChannel(
ws.send(JSON.stringify({ kind: "end-exfiltration" }));
beganRef.current = false;
}
- if (useRecordingStore.getState().messageSocket === ws) {
- useRecordingStore.getState().setMessageSocket(null);
- }
messageSocketRef.current = null;
try {
ws && ws.close();
diff --git a/skyvern-frontend/src/routes/tasks/detail/TaskDetails.tsx b/skyvern-frontend/src/routes/tasks/detail/TaskDetails.tsx
index 28434b6f2..8633f1c96 100644
--- a/skyvern-frontend/src/routes/tasks/detail/TaskDetails.tsx
+++ b/skyvern-frontend/src/routes/tasks/detail/TaskDetails.tsx
@@ -206,22 +206,6 @@ function TaskDetails() {
</div>
) : null;
- const browserConsoleLog = task?.browser_console_log_url ? (
- <div className="space-y-1">
- <Label>Browser Console Log</Label>
- <div>
- <a
- href={task.browser_console_log_url}
- target="_blank"
- rel="noopener noreferrer"
- className="text-sm underline underline-offset-4"
- >
- Download console log
- </a>
- </div>
- </div>
- ) : null;
-
return (
<div className="flex flex-col gap-8">
<header className="space-y-3">
@@ -362,7 +346,6 @@ function TaskDetails() {
{extractedInformation}
{failureReason}
{webhookFailureReason}
- {browserConsoleLog}
</>
)}
<SwitchBarNavigation
diff --git a/skyvern-frontend/src/routes/workflows/WorkflowRun.tsx b/skyvern-frontend/src/routes/workflows/WorkflowRun.tsx
index b5b97da71..d3ff8ba20 100644
--- a/skyvern-frontend/src/routes/workflows/WorkflowRun.tsx
+++ b/skyvern-frontend/src/routes/workflows/WorkflowRun.tsx
@@ -76,6 +76,7 @@ import { WorkflowRunStatusAlert } from "@/routes/workflows/workflowRun/WorkflowR
import { WorkflowRunVerificationCodeForm } from "@/routes/workflows/workflowRun/WorkflowRunVerificationCodeForm";
import { ScriptUpdateCard } from "@/routes/workflows/workflowRun/ScriptUpdateCard";
import { useFallbackEpisodesQuery } from "@/routes/workflows/hooks/useFallbackEpisodesQuery";
+import { usePageSlots } from "@/store/PageSlots";
import { useOnboardingStateOptional } from "@/store/onboarding/useOnboardingState";
import { useWorkflowStudioEnabled } from "@/hooks/useWorkflowStudioEnabled";
import { workflowEditorPath } from "@/routes/workflows/studioNavigation";
@@ -91,7 +92,7 @@ import {
type RecoveryGuidanceTelemetryContext,
} from "@/util/onboarding/recoveryGuidanceTelemetry";
import { RunTagsEditor } from "@/routes/tasks/components/tagging/RunTagsEditor";
-import { shouldPollForGeneratedCode } from "./utils";
+import { getRerunNavigationState, shouldPollForGeneratedCode } from "./utils";
const RECOVERY_GUIDANCE_TREATMENT_SURFACE_FLAG =
"RECOVERY_GUIDANCE_TREATMENT_SURFACE";
@@ -175,10 +176,12 @@ function WorkflowRun() {
const location = useLocation();
const studioEnabled = useWorkflowStudioEnabled();
const onboarding = useOnboardingStateOptional();
+ const { workflowRunMilestoneCard: WorkflowRunMilestoneCard } = usePageSlots();
const {
data: workflowRun,
isLoading: workflowRunIsLoading,
+ isPlaceholderData: workflowRunIsPlaceholder,
isFetched,
error,
} = useWorkflowRunWithWorkflowQuery();
@@ -817,6 +820,26 @@ function WorkflowRun() {
</div>
</header>
)}
+ {WorkflowRunMilestoneCard &&
+ workflowRun &&
+ !workflowRunIsPlaceholder &&
+ workflowRun.workflow_run_id === workflowRunId &&
+ workflowRun.status === Status.Completed ? (
+ <WorkflowRunMilestoneCard
+ workflowRunId={workflowRun.workflow_run_id}
+ rerun={
+ !isEmbedded &&
+ !isTaskv2Run &&
+ !isWorkflowDeleted &&
+ workflowPermanentId
+ ? {
+ to: `/agents/${workflowPermanentId}/run`,
+ state: getRerunNavigationState(workflowRun),
+ }
+ : undefined
+ }
+ />
+ ) : null}
{/* 2FA Verification Code Form - shown when workflow is waiting for a code */}
<WorkflowRunVerificationCodeForm />
{showOutputSection && (
diff --git a/skyvern-frontend/src/routes/workflows/WorkflowsFlat.tsx b/skyvern-frontend/src/routes/workflows/WorkflowsFlat.tsx
index c3941db89..2ca2f92a2 100644
--- a/skyvern-frontend/src/routes/workflows/WorkflowsFlat.tsx
+++ b/skyvern-frontend/src/routes/workflows/WorkflowsFlat.tsx
@@ -1,8 +1,4 @@
import { getClient } from "@/api/AxiosClient";
-import { GetStartedModal } from "@/components/onboarding/GetStartedModal";
-import { useOnboardingStateOptional } from "@/store/onboarding/useOnboardingState";
-import { OnboardingErrorBoundary } from "@/components/onboarding/OnboardingErrorBoundary";
-import { OnboardingTelemetry } from "@/util/onboarding/OnboardingTelemetry";
import { Button } from "@/components/ui/button";
import {
SelectionCheckboxCell,
@@ -343,24 +339,6 @@ function WorkflowsFlat() {
placeholderData: (previousData) => previousData,
});
- // unfiltered "owns any workflow" check; the filtered/paginated list above can read empty for a user who has workflows
- const { data: ownedWorkflows = [], isLoading: ownedWorkflowsLoading } =
- useQuery<Array<WorkflowApiResponse>>({
- queryKey: ["workflows", "exists"],
- queryFn: async () => {
- const client = await getClient(credentialGetter);
- const params = new URLSearchParams();
- params.append("page", "1");
- params.append("page_size", "1");
- params.append("only_workflows", "true");
- return client
- .get(`/workflows`, { params })
- .then((response) => response.data);
- },
- });
-
- const onboarding = useOnboardingStateOptional();
-
const { data: nextPageWorkflows } = useQuery<Array<WorkflowApiResponse>>({
queryKey: [
"workflows",
@@ -1352,17 +1330,6 @@ function WorkflowsFlat() {
<div data-hint="start-template">
<WorkflowTemplates />
</div>
-
- {onboarding ? (
- <OnboardingErrorBoundary
- onError={() => OnboardingTelemetry.modalRenderError("dashboard")}
- >
- <GetStartedModal
- hasWorkflows={ownedWorkflows.length > 0}
- isLoading={ownedWorkflowsLoading}
- />
- </OnboardingErrorBoundary>
- ) : null}
</div>
</div>
);
diff --git a/skyvern-frontend/src/routes/workflows/WorkflowsTree.tsx b/skyvern-frontend/src/routes/workflows/WorkflowsTree.tsx
index d46c43e42..e2c058e3c 100644
--- a/skyvern-frontend/src/routes/workflows/WorkflowsTree.tsx
+++ b/skyvern-frontend/src/routes/workflows/WorkflowsTree.tsx
@@ -1,8 +1,4 @@
import { getClient } from "@/api/AxiosClient";
-import { GetStartedModal } from "@/components/onboarding/GetStartedModal";
-import { useOnboardingStateOptional } from "@/store/onboarding/useOnboardingState";
-import { OnboardingErrorBoundary } from "@/components/onboarding/OnboardingErrorBoundary";
-import { OnboardingTelemetry } from "@/util/onboarding/OnboardingTelemetry";
import { Button } from "@/components/ui/button";
import { SelectionHeaderCheckboxCell } from "@/components/SelectionCheckbox";
import { useRowSelection } from "@/hooks/useRowSelection";
@@ -29,11 +25,7 @@ import {
ReloadIcon,
} from "@radix-ui/react-icons";
import { FolderIcon } from "@/components/icons/FolderIcon";
-import {
- useInfiniteQuery,
- useQuery,
- useQueryClient,
-} from "@tanstack/react-query";
+import { useInfiniteQuery, useQueryClient } from "@tanstack/react-query";
import React, {
useCallback,
useEffect,
@@ -345,24 +337,6 @@ function WorkflowsTree() {
[workflowsData],
);
- // unfiltered "owns any workflow" check; the filtered/paginated list above can read empty for a user who has workflows
- const { data: ownedWorkflows = [], isLoading: ownedWorkflowsLoading } =
- useQuery<Array<WorkflowApiResponse>>({
- queryKey: ["workflows", "exists"],
- queryFn: async () => {
- const client = await getClient(credentialGetter);
- const params = new URLSearchParams();
- params.append("page", "1");
- params.append("page_size", "1");
- params.append("only_workflows", "true");
- return client
- .get(`/workflows`, { params })
- .then((response) => response.data);
- },
- });
-
- const onboarding = useOnboardingStateOptional();
-
// Tag-key registry: supplies chip-hover descriptions and the filter's key list.
const { data: tagKeys = [] } = useTagKeysQuery({ enabled: taggingEnabled });
const tagDescriptions = useMemo(
@@ -1101,17 +1075,6 @@ function WorkflowsTree() {
<div data-hint="start-template">
<WorkflowTemplates />
</div>
-
- {onboarding ? (
- <OnboardingErrorBoundary
- onError={() => OnboardingTelemetry.modalRenderError("dashboard")}
- >
- <GetStartedModal
- hasWorkflows={ownedWorkflows.length > 0}
- isLoading={ownedWorkflowsLoading}
- />
- </OnboardingErrorBoundary>
- ) : null}
</div>
</div>
);
diff --git a/skyvern-frontend/src/routes/workflows/copilot/NarrativeView.checklist.test.tsx b/skyvern-frontend/src/routes/workflows/copilot/NarrativeView.checklist.test.tsx
index dc77295ed..98483a294 100644
--- a/skyvern-frontend/src/routes/workflows/copilot/NarrativeView.checklist.test.tsx
+++ b/skyvern-frontend/src/routes/workflows/copilot/NarrativeView.checklist.test.tsx
@@ -1,6 +1,12 @@
// @vitest-environment jsdom
-import { cleanup, fireEvent, render, screen } from "@testing-library/react";
+import {
+ cleanup,
+ fireEvent,
+ render,
+ screen,
+ waitFor,
+} from "@testing-library/react";
import { afterEach, describe, expect, it } from "vitest";
import { NarrativeView } from "./NarrativeView";
@@ -96,18 +102,11 @@ describe("NarrativeView — narrator content condensing (SKY-11971)", () => {
blocks: [runningBlock({ activity: retriedBlockActivity })],
});
- it("checklist (uxV1): folds the block's failed-then-retried tool activity into one row with an attempt count", () => {
- render(<NarrativeView turn={retriedTurn()} uxV1 />);
- expect(screen.queryByText("no results found")).toBeNull();
- expect(screen.getByText("top 5 titles + links")).toBeTruthy();
- expect(screen.getByText(/2 attempts/)).toBeTruthy();
- });
-
- it("legacy (uxV1 absent): renders every raw call/result row unfolded, exactly as before", () => {
+ it("folds retry status while retaining the exact failed attempt as evidence", () => {
render(<NarrativeView turn={retriedTurn()} />);
expect(screen.getByText("no results found")).toBeTruthy();
expect(screen.getByText("top 5 titles + links")).toBeTruthy();
- expect(screen.queryByText(/attempts/)).toBeNull();
+ expect(screen.getByText(/2 attempts/)).toBeTruthy();
});
});
@@ -152,8 +151,8 @@ const repairLoopTurn = (): TurnNarrativeState => ({
});
describe("NarrativeView — activity log", () => {
- it("flag on: the rollup renders the flat activity rows and drops the phase rail", () => {
- render(<NarrativeView turn={repairLoopTurn()} uxV1 />);
+ it("the rollup renders the flat activity rows and drops the phase rail", () => {
+ render(<NarrativeView turn={repairLoopTurn()} />);
expect(screen.queryByText("Explore site")).toBeNull();
expect(screen.queryByText("Draft code")).toBeNull();
expect(screen.queryByText("Test-run")).toBeNull();
@@ -161,8 +160,31 @@ describe("NarrativeView — activity log", () => {
expect(screen.getByText("Saved 2 blocks")).toBeTruthy();
});
- it("flag on: a failed run keeps the server's reason instead of a generic tool label", () => {
- render(<NarrativeView turn={repairLoopTurn()} uxV1 />);
+ it("moves focus between the terminal rollup and detail disclosures", async () => {
+ render(<NarrativeView turn={repairLoopTurn()} />);
+ const rollup = screen.getByRole("button", {
+ name: /Built and tested the workflow/,
+ });
+ expect(rollup.getAttribute("aria-expanded")).toBe("false");
+ expect(rollup.hasAttribute("aria-controls")).toBe(false);
+ fireEvent.click(rollup);
+
+ const collapse = screen.getByRole("button", { name: "Collapse turn" });
+ expect(collapse.getAttribute("aria-expanded")).toBe("true");
+ expect(
+ document.getElementById(collapse.getAttribute("aria-controls")!),
+ ).toBeTruthy();
+ await waitFor(() => expect(document.activeElement).toBe(collapse));
+
+ fireEvent.click(collapse);
+ const restored = screen.getByRole("button", {
+ name: /Built and tested the workflow/,
+ });
+ await waitFor(() => expect(document.activeElement).toBe(restored));
+ });
+
+ it("a failed run keeps the server's reason instead of a generic tool label", () => {
+ render(<NarrativeView turn={repairLoopTurn()} />);
expect(
screen.queryByText(
"The submit button stayed disabled after filling the form",
@@ -177,10 +199,8 @@ describe("NarrativeView — activity log", () => {
).toBeTruthy();
});
- it("flag on: an in-flight turn renders the same flat rows in happened-order", () => {
- render(
- <NarrativeView turn={{ ...repairLoopTurn(), terminal: null }} uxV1 />,
- );
+ it("an in-flight turn renders the same flat rows in happened-order", () => {
+ render(<NarrativeView turn={{ ...repairLoopTurn(), terminal: null }} />);
expect(screen.queryByText("Explore site")).toBeNull();
const rows = screen.getAllByText(/Opened the sign-in page|Saved 2 blocks/);
expect(rows.map((r) => r.textContent)).toEqual([
@@ -189,22 +209,20 @@ describe("NarrativeView — activity log", () => {
]);
});
- it("flag on: the rollup gutter reads the row kinds in happened-order", () => {
- render(<NarrativeView turn={repairLoopTurn()} uxV1 />);
+ it("the rollup gutter reads the row kinds in happened-order", () => {
+ render(<NarrativeView turn={repairLoopTurn()} />);
const gutter = screen.getAllByText(KIND_GLYPH_PATTERN);
expect(gutter.map((g) => g.textContent)).toEqual(["◎", "▷", "⟨⟩"]);
});
- it("flag on: the in-flight detail gutter reads the same row kinds", () => {
- render(
- <NarrativeView turn={{ ...repairLoopTurn(), terminal: null }} uxV1 />,
- );
+ it("the in-flight detail gutter reads the same row kinds", () => {
+ render(<NarrativeView turn={{ ...repairLoopTurn(), terminal: null }} />);
const gutter = screen.getAllByText(KIND_GLYPH_PATTERN);
expect(gutter.map((g) => g.textContent)).toEqual(["◎", "▷", "⟨⟩"]);
});
- it("flag on: the block card is the run row itself, ahead of the re-authoring row that follows it", () => {
- render(<NarrativeView turn={repairLoopTurn()} uxV1 />);
+ it("the block card is the run row itself, ahead of the re-authoring row that follows it", () => {
+ render(<NarrativeView turn={repairLoopTurn()} />);
const reauthoringRow = screen.getByText("Saved 2 blocks");
const cards = screen.getAllByRole("button", { name: /Block 1/ });
expect(cards.length).toBeGreaterThan(0);
@@ -216,8 +234,8 @@ describe("NarrativeView — activity log", () => {
}
});
- it("flag on: a block row wears the same row treatment as a step row", () => {
- render(<NarrativeView turn={repairLoopTurn()} uxV1 />);
+ it("a block row wears the same row treatment as a step row", () => {
+ render(<NarrativeView turn={repairLoopTurn()} />);
const blockRow = screen
.getAllByRole("button", { name: /Block 1/ })
.find((b) => b.className.includes("grid-cols-"));
@@ -238,7 +256,7 @@ describe("NarrativeView — activity log", () => {
expect(onScreen.textContent).not.toContain("done");
});
- it("flag on: a live row's clock reads wall time, not the span of its entries", () => {
+ it("a live row's clock reads wall time, not the span of its entries", () => {
const startedAt = new Date(Date.now() - 90_000).toISOString();
const turn = repairLoopTurn();
turn.terminal = null;
@@ -253,7 +271,7 @@ describe("NarrativeView — activity log", () => {
timestamp: startedAt,
}),
];
- render(<NarrativeView turn={turn} uxV1 />);
+ render(<NarrativeView turn={turn} />);
// One entry means first stamp === last stamp, so the recorded span is zero
// and the column sat at 0:00 for as long as the step took.
@@ -261,7 +279,7 @@ describe("NarrativeView — activity log", () => {
expect(screen.queryByText("0:00")).toBeNull();
});
- it("flag on: a run row still calling carries no success mark", () => {
+ it("a run row still calling carries no success mark", () => {
const turn = repairLoopTurn();
turn.terminal = null;
turn.designActivity = [
@@ -274,7 +292,7 @@ describe("NarrativeView — activity log", () => {
}),
];
turn.blocks = [];
- render(<NarrativeView turn={turn} uxV1 />);
+ render(<NarrativeView turn={turn} />);
// A mark reports an outcome. The row is mid-call, so it has none yet —
// before this, "not failed" was rendered as "succeeded".
@@ -287,8 +305,8 @@ describe("NarrativeView — activity log", () => {
expect(row!.textContent).not.toContain("✓");
});
- it("flag on: the kind reaches a screen reader as a word, not only as the glyph", () => {
- render(<NarrativeView turn={repairLoopTurn()} uxV1 />);
+ it("the kind reaches a screen reader as a word, not only as the glyph", () => {
+ render(<NarrativeView turn={repairLoopTurn()} />);
// The glyph is aria-hidden, so without this the kind is invisible to a
// screen reader — the phase rail pairs its puck with an sr-only word too.
expect(screen.getAllByText(/Looked at the page ·/).length).toBeGreaterThan(
@@ -298,7 +316,7 @@ describe("NarrativeView — activity log", () => {
expect(screen.getAllByText(/Wrote code ·/).length).toBeGreaterThan(0);
});
- it("flag on: a block-authoring row carries the authoring glyph", () => {
+ it("a block-authoring row carries the authoring glyph", () => {
const turn = repairLoopTurn();
turn.designActivity = [
activityEntry({
@@ -309,7 +327,7 @@ describe("NarrativeView — activity log", () => {
success: true,
}),
];
- render(<NarrativeView turn={turn} uxV1 />);
+ render(<NarrativeView turn={turn} />);
const gutter = screen.getAllByText(KIND_GLYPH_PATTERN);
expect(gutter.map((g) => g.textContent)).toEqual(["⟨⟩", "▷"]);
});
@@ -364,8 +382,8 @@ describe("NarrativeView — activity log", () => {
],
});
- it("flag on: three consecutive browse steps fold into one row carrying the step count", () => {
- render(<NarrativeView turn={groupedBrowseTurn()} uxV1 />);
+ it("three consecutive browse steps fold into one row carrying the step count", () => {
+ render(<NarrativeView turn={groupedBrowseTurn()} />);
const gutter = screen.getAllByText(KIND_GLYPH_PATTERN);
expect(gutter.map((g) => g.textContent)).toEqual(["◎"]);
expect(screen.getByText("Found the invoice list")).toBeTruthy();
@@ -380,8 +398,8 @@ describe("NarrativeView — activity log", () => {
expect(screen.queryByText("Opened the sign-in page")).toBeNull();
});
- it("flag on: only the last unresolved call is expanded while two are in flight", () => {
- render(<NarrativeView turn={twoInFlightTurn()} uxV1 />);
+ it("only the last unresolved call is expanded while two are in flight", () => {
+ render(<NarrativeView turn={twoInFlightTurn()} />);
expect(screen.getAllByRole("button", { expanded: true })).toHaveLength(1);
expect(screen.getByText("Checked the cart")).toBeTruthy();
@@ -389,8 +407,8 @@ describe("NarrativeView — activity log", () => {
expect(screen.getByRole("button", { expanded: false })).toBeTruthy();
});
- it("flag on: a finished browse row re-opens on click and folds again on the next", () => {
- render(<NarrativeView turn={groupedBrowseTurn()} uxV1 />);
+ it("a finished browse row re-opens on click and folds again on the next", () => {
+ render(<NarrativeView turn={groupedBrowseTurn()} />);
const row = screen.getByRole("button", { expanded: true });
fireEvent.click(row);
@@ -424,9 +442,7 @@ describe("NarrativeView — activity log", () => {
it.each([0, 7])(
"narration tagged iteration=%s renders inside the browse step, never as its own row",
(narrationIteration) => {
- render(
- <NarrativeView turn={narratedBrowseTurn(narrationIteration)} uxV1 />,
- );
+ render(<NarrativeView turn={narratedBrowseTurn(narrationIteration)} />);
expect(
screen.getAllByText(KIND_GLYPH_PATTERN).map((g) => g.textContent),
@@ -439,7 +455,7 @@ describe("NarrativeView — activity log", () => {
},
);
- it("flag on: a finished run row re-opens to the block's step list", () => {
+ it("a finished run row re-opens to the block's step list", () => {
const turn = repairLoopTurn();
turn.blocks = [
runningBlock({
@@ -464,18 +480,24 @@ describe("NarrativeView — activity log", () => {
],
}),
];
- render(<NarrativeView turn={turn} uxV1 />);
+ render(<NarrativeView turn={turn} />);
expect(screen.queryByText("Submitted the form")).toBeNull();
fireEvent.click(screen.getByRole("button", { name: /Block 1/ }));
expect(screen.getByText("Submitted the form")).toBeTruthy();
});
- it("flag on: a run row with no block renders a plain line and no block card", () => {
+ it("a run row with no block renders a plain line and no block card", () => {
const turn = repairLoopTurn();
turn.blocks = [];
- render(<NarrativeView turn={turn} uxV1 />);
+ render(<NarrativeView turn={turn} />);
expect(screen.queryByText("Block 1")).toBeNull();
+ expect(
+ screen.queryByText(
+ "The submit button stayed disabled after filling the form",
+ ),
+ ).toBeNull();
+ fireEvent.click(screen.getByRole("button", { name: /Testing workflow/ }));
expect(
screen.getByText(
"The submit button stayed disabled after filling the form",
@@ -483,7 +505,7 @@ describe("NarrativeView — activity log", () => {
).toBeTruthy();
});
- it("flag on: a run row with two blocks holds both cards behind one toggle", () => {
+ it("a run row with two blocks holds both cards behind one toggle", () => {
const turn = repairLoopTurn();
turn.blocks = [
runningBlock({ state: "completed", endedAt: "2026-06-10T00:00:10Z" }),
@@ -494,7 +516,7 @@ describe("NarrativeView — activity log", () => {
endedAt: "2026-06-10T00:00:12Z",
}),
];
- render(<NarrativeView turn={turn} uxV1 />);
+ render(<NarrativeView turn={turn} />);
expect(screen.queryAllByRole("button", { name: /Block 1/ })).toHaveLength(
0,
);
@@ -502,9 +524,7 @@ describe("NarrativeView — activity log", () => {
0,
);
- fireEvent.click(
- screen.getByRole("button", { name: /submit button stayed disabled/ }),
- );
+ fireEvent.click(screen.getByRole("button", { name: /Testing workflow/ }));
expect(
screen.getAllByRole("button", { name: /Block 1/ }).length,
).toBeGreaterThan(0);
@@ -513,7 +533,7 @@ describe("NarrativeView — activity log", () => {
).toBeGreaterThan(0);
});
- it("flag on: a drafted block never renders under a run row", () => {
+ it("a drafted block never renders under a run row", () => {
const turn = repairLoopTurn();
turn.blocks = [
runningBlock({
@@ -522,20 +542,91 @@ describe("NarrativeView — activity log", () => {
state: "drafted",
}),
];
- render(<NarrativeView turn={turn} uxV1 />);
+ render(<NarrativeView turn={turn} />);
const card = screen.getByText("Block 2");
- const runRow = screen.getByText(
- "The submit button stayed disabled after filling the form",
- );
+ const runRow = screen.getByText("Testing workflow");
expect(
runRow.compareDocumentPosition(card) & Node.DOCUMENT_POSITION_FOLLOWING,
).toBeTruthy();
});
- it("flag on: a hand-opened row stays open when a new row goes live, and resets next turn", () => {
- const { rerender } = render(
- <NarrativeView turn={twoInFlightTurn()} uxV1 />,
+ it("an empty drafted block cannot hide or open ahead of live work", () => {
+ const turn: TurnNarrativeState = {
+ ...EMPTY_NARRATIVE,
+ turnId: "turn-1",
+ turnIndex: 0,
+ designStarted: true,
+ terminal: null,
+ designActivity: [
+ activityEntry({
+ id: "tc-1",
+ kind: "tool_call",
+ toolName: "navigate_browser",
+ displayLabel: "Searching the catalogue",
+ timestamp: "2026-06-10T00:00:05Z",
+ }),
+ activityEntry({
+ id: "n-1",
+ kind: "narration",
+ text: "Finding the first matching item.",
+ iteration: 0,
+ timestamp: "2026-06-10T00:00:06Z",
+ }),
+ ],
+ blocks: [
+ runningBlock({
+ workflowRunBlockId: "",
+ label: "add_first_result",
+ state: "drafted",
+ startedAt: null,
+ }),
+ ],
+ };
+
+ const { container, rerender } = render(<NarrativeView turn={turn} />);
+ const liveRow = screen.getByRole("button", {
+ name: /Searching the catalogue/,
+ expanded: true,
+ });
+ const draftRow = screen.getByRole("button", {
+ name: /Add First Result/,
+ });
+
+ expect(liveRow).toBeTruthy();
+ expect(draftRow.getAttribute("aria-expanded")).toBeNull();
+ fireEvent.click(draftRow);
+ expect(draftRow.getAttribute("aria-expanded")).toBeNull();
+ expect(container.querySelectorAll(".border-l")).toHaveLength(1);
+
+ // The newest row still owns focus during a real between-call gap, but a
+ // contentless draft remains a plain row rather than an empty disclosure.
+ rerender(
+ <NarrativeView
+ turn={{
+ ...turn,
+ designActivity: [
+ activityEntry({
+ id: "tr-1",
+ kind: "tool_result",
+ toolName: "navigate_browser",
+ text: "Searched the catalogue",
+ success: true,
+ timestamp: "2026-06-10T00:00:06Z",
+ }),
+ ],
+ }}
+ />,
);
+ expect(
+ screen
+ .getByRole("button", { name: /Add First Result/ })
+ .getAttribute("aria-expanded"),
+ ).toBeNull();
+ expect(container.querySelectorAll(".border-l")).toHaveLength(0);
+ });
+
+ it("a hand-opened row stays open when a new row goes live, and resets next turn", () => {
+ const { rerender } = render(<NarrativeView turn={twoInFlightTurn()} />);
fireEvent.click(screen.getByRole("button", { expanded: false }));
expect(screen.getByText("Opened the sign-in page")).toBeTruthy();
@@ -569,7 +660,7 @@ describe("NarrativeView — activity log", () => {
iteration: 5,
}),
];
- rerender(<NarrativeView turn={advanced} uxV1 />);
+ rerender(<NarrativeView turn={advanced} />);
// The hand-opened row survives the advance...
expect(screen.getByText("Opened the sign-in page")).toBeTruthy();
@@ -577,12 +668,12 @@ describe("NarrativeView — activity log", () => {
expect(screen.getByText(/Testing workflow/)).toBeTruthy();
rerender(
- <NarrativeView turn={{ ...twoInFlightTurn(), turnId: "turn-2" }} uxV1 />,
+ <NarrativeView turn={{ ...twoInFlightTurn(), turnId: "turn-2" }} />,
);
expect(screen.queryByText("Opened the sign-in page")).toBeNull();
});
- it("flag on: a still-calling run row is headed by its live line, not a finished block's verdict", () => {
+ it("a still-calling run row is headed by its live line, not a finished block's verdict", () => {
const turn: TurnNarrativeState = {
...EMPTY_NARRATIVE,
turnId: "turn-1",
@@ -617,7 +708,7 @@ describe("NarrativeView — activity log", () => {
}),
],
};
- render(<NarrativeView turn={turn} uxV1 />);
+ render(<NarrativeView turn={turn} />);
const header = screen.getByRole("button", { expanded: true });
expect(header.textContent).toContain("Testing workflow");
@@ -625,15 +716,15 @@ describe("NarrativeView — activity log", () => {
expect(header.textContent).not.toContain("done");
});
- it("flag on: the step count folds away while the row is expanded", () => {
- render(<NarrativeView turn={groupedBrowseTurn()} uxV1 />);
+ it("the step count folds away while the row is expanded", () => {
+ render(<NarrativeView turn={groupedBrowseTurn()} />);
expect(screen.queryByText(/3 steps/)).toBeNull();
fireEvent.click(screen.getByRole("button", { expanded: true }));
expect(screen.getByText(/3 steps/)).toBeTruthy();
});
- it("flag on: a collapsed run row says how many blocks are folded inside it", () => {
+ it("a collapsed run row says how many blocks are folded inside it", () => {
const finished = (id: string, label: string): BlockState =>
runningBlock({
workflowRunBlockId: id,
@@ -676,7 +767,7 @@ describe("NarrativeView — activity log", () => {
}),
],
};
- render(<NarrativeView turn={turn} uxV1 />);
+ render(<NarrativeView turn={turn} />);
const rowHolding = screen
.getAllByRole("button")
@@ -691,7 +782,7 @@ describe("NarrativeView — activity log", () => {
expect(screen.queryByText(/· \d+ blocks?$/)).toBeNull();
});
- it("flag on: a block whose run row was evicted still renders inside a row at Done", () => {
+ it("a block whose run row was evicted still renders inside a row at Done", () => {
const turn: TurnNarrativeState = {
...EMPTY_NARRATIVE,
turnId: "turn-1",
@@ -712,7 +803,7 @@ describe("NarrativeView — activity log", () => {
}),
],
};
- render(<NarrativeView turn={turn} uxV1 />);
+ render(<NarrativeView turn={turn} />);
const gutter = screen.getAllByText(KIND_GLYPH_PATTERN);
expect(gutter.map((g) => g.textContent)).toEqual(["⟨⟩", "▷"]);
@@ -747,15 +838,15 @@ describe("NarrativeView — activity log", () => {
],
});
- it("flag on: clicking the live row folds it instead of pinning it open", () => {
- render(<NarrativeView turn={twoInFlightTurn()} uxV1 />);
+ it("clicking the live row folds it instead of pinning it open", () => {
+ render(<NarrativeView turn={twoInFlightTurn()} />);
const live = screen.getByRole("button", { expanded: true });
fireEvent.click(live);
expect(screen.queryAllByRole("button", { expanded: true })).toHaveLength(0);
});
- it("flag on: a finished run row is one line, not a line plus a summary", () => {
+ it("a finished run row is one line, not a line plus a summary", () => {
const turn = failedRunTurn();
turn.blocks = [
runningBlock({
@@ -774,7 +865,7 @@ describe("NarrativeView — activity log", () => {
],
}),
];
- render(<NarrativeView turn={turn} uxV1 />);
+ render(<NarrativeView turn={turn} />);
expect(screen.queryByText("Clicked the download link")).toBeNull();
fireEvent.click(screen.getByTitle(/Highlight download_block/));
@@ -799,7 +890,7 @@ describe("NarrativeView — activity log", () => {
}),
],
};
- const { rerender } = render(<NarrativeView turn={inFlight} uxV1 />);
+ const { rerender } = render(<NarrativeView turn={inFlight} />);
expect(screen.queryAllByRole("button")).toHaveLength(0);
expect(screen.getByText(/Testing workflow/)).toBeTruthy();
@@ -811,7 +902,7 @@ describe("NarrativeView — activity log", () => {
runningBlock({ workflowRunBlockId: "wrb_1", label: "download_block" }),
],
};
- rerender(<NarrativeView turn={withBlock} uxV1 />);
+ rerender(<NarrativeView turn={withBlock} />);
expect(screen.getByRole("button", { expanded: true })).toBeTruthy();
});
@@ -831,11 +922,11 @@ describe("NarrativeView — activity log", () => {
}),
],
};
- render(<NarrativeView turn={turn} uxV1 />);
+ render(<NarrativeView turn={turn} />);
expect(screen.queryAllByText(/Opening page/)).toHaveLength(1);
});
- it("keeps the server's failure text on a failed step even when the narrator titled it", () => {
+ it("uses the narrator's intent for a failed row and keeps the exact error in its detail", () => {
render(
<NarrativeView
turn={{
@@ -844,6 +935,7 @@ describe("NarrativeView — activity log", () => {
turnIndex: 0,
designStarted: true,
terminal: null,
+ designEnded: true,
designActivity: [
activityEntry({
id: "tr-f1",
@@ -861,20 +953,70 @@ describe("NarrativeView — activity log", () => {
activeLabel: "Running it",
outcomeLabel: "Ran it - everything passed",
}),
+ activityEntry({
+ id: "tr-next",
+ kind: "tool_result",
+ toolName: "navigate_browser",
+ text: "Opened a fresh browser",
+ success: true,
+ iteration: 1,
+ }),
],
}}
- uxV1
/>,
);
- // The narrator's outcome label is written before the step resolves, so on a
- // failure it can be a stale prediction. The server's text is the honest one.
+ // The outcome label is a stale prediction on failure. The collapsed row
+ // keeps the trustworthy intent, while the exact server error remains
+ // available one level deeper instead of becoming the primary headline.
+ expect(screen.getByText("Running it")).toBeTruthy();
+ expect(screen.getByText(/attempt failed/).className).not.toContain("rose");
+ expect(
+ screen.queryByText(
+ "The submit button stayed disabled after filling the form",
+ ),
+ ).toBeNull();
+ expect(screen.queryByText("Ran it - everything passed")).toBeNull();
+
+ fireEvent.click(screen.getByRole("button", { name: /Running it/ }));
expect(
screen.getByText(
"The submit button stayed disabled after filling the form",
),
).toBeTruthy();
- expect(screen.queryByText("Ran it - everything passed")).toBeNull();
+ });
+
+ it("keeps a focused retry failure neutral", () => {
+ render(
+ <NarrativeView
+ turn={{
+ ...EMPTY_NARRATIVE,
+ turnId: "turn-1",
+ turnIndex: 0,
+ designStarted: true,
+ terminal: null,
+ designActivity: [
+ activityEntry({
+ id: "tr-f1",
+ kind: "tool_result",
+ toolName: "get_page_evidence",
+ text: "The browser target crashed",
+ displayLabel: "Restoring access to the certification results",
+ success: false,
+ iteration: 1,
+ attempts: 2,
+ }),
+ ],
+ }}
+ />,
+ );
+
+ expect(
+ screen.getByText("Restoring access to the certification results")
+ .className,
+ ).not.toContain("rose");
+ expect(screen.getByText(/attempt failed/).className).not.toContain("rose");
+ expect(screen.getAllByText(/2 attempts/).length).toBeGreaterThan(0);
});
});
@@ -929,33 +1071,398 @@ const twoWriteTurn = (
});
describe("NarrativeView — code write diffs", () => {
- it("a streaming turn leaves every write's patch open, not just the newest", () => {
- render(<NarrativeView turn={twoWriteTurn()} uxV1 />);
+ it("shows an active write as a muted code peek that expands on click", () => {
+ render(
+ <NarrativeView
+ turn={{
+ ...EMPTY_NARRATIVE,
+ turnId: "turn-1",
+ turnIndex: 0,
+ designStarted: true,
+ terminal: null,
+ designActivity: [
+ activityEntry({
+ id: "tr-write",
+ kind: "tool_result",
+ toolName: "add_block",
+ text: "Added the cart block",
+ success: true,
+ iteration: 2,
+ codeDiffs: [
+ {
+ label: "add_to_cart",
+ added: 1,
+ removed: 0,
+ patch: "+await page.click('button.add-to-cart')",
+ },
+ ],
+ }),
+ activityEntry({
+ id: "tc-run",
+ kind: "tool_call",
+ toolName: "run_blocks_and_collect_debug",
+ displayLabel: "Testing the cart block",
+ iteration: 3,
+ }),
+ ],
+ }}
+ />,
+ );
- // Both patches are on screen: a newer write must not close the one a reader
- // is part-way through.
- expect(screen.getByText("-await page.click('#a')")).toBeTruthy();
- expect(screen.getByText("+await page.wait_for_timeout(500)")).toBeTruthy();
- expect(screen.getAllByRole("button", { name: "hide diff" }).length).toBe(2);
+ expect(screen.getByText(/Testing the cart block/)).toBeTruthy();
+ const peek = screen.getByRole("button", {
+ name: "Expand code changes for add_to_cart",
+ });
+ expect(peek.getAttribute("data-code-diff-peek")).toBe("true");
+ expect(peek.getAttribute("aria-expanded")).toBe("false");
+ expect(peek.className).toContain("max-h-");
+ expect(
+ screen.getByText("+await page.click('button.add-to-cart')").className,
+ ).toContain("!text-muted-foreground");
+ expect(peek.className).not.toContain("mask-image");
+ expect(screen.queryByRole("button", { name: "view diff" })).toBeNull();
+
+ fireEvent.click(peek);
+ const collapse = screen.getByRole("button", { name: "hide diff" });
+ expect(collapse).toBeTruthy();
+ expect(document.activeElement).toBe(collapse);
+ expect(
+ screen.getByText("+await page.click('button.add-to-cart')").className,
+ ).not.toContain("opacity-50");
+ });
+
+ it("shows an active repair's code before its tool result arrives", () => {
+ render(
+ <NarrativeView
+ turn={{
+ ...EMPTY_NARRATIVE,
+ turnId: "turn-1",
+ turnIndex: 0,
+ designStarted: true,
+ terminal: null,
+ draft: { blockCount: 1, blockLabels: ["add_to_cart"], summary: null },
+ blocks: [
+ runningBlock({
+ label: "add_to_cart",
+ activity: [
+ activityEntry({
+ id: "tc-repair",
+ kind: "tool_call",
+ toolName: "edit_block_and_run",
+ displayLabel: "Repairing and testing the cart block",
+ codeDiffs: [
+ {
+ label: "add_to_cart",
+ added: 1,
+ removed: 1,
+ patch: "-old line\n+new line",
+ },
+ ],
+ }),
+ ],
+ }),
+ ],
+ }}
+ />,
+ );
+
+ expect(
+ screen.getByRole("button", {
+ name: "Expand code changes for add_to_cart",
+ }),
+ ).toBeTruthy();
+ expect(screen.getByText("+new line")).toBeTruthy();
});
- it("hide diff closes one write's patch and leaves the other open", () => {
- render(<NarrativeView turn={twoWriteTurn()} uxV1 />);
+ it("pins the containing row when the active code peek is expanded", () => {
+ const write = activityEntry({
+ id: "tr-write",
+ kind: "tool_result",
+ toolName: "add_block",
+ text: "Added the cart block",
+ success: true,
+ iteration: 0,
+ codeDiffs: [
+ {
+ label: "add_to_cart",
+ added: 1,
+ removed: 0,
+ patch: "+await page.click('button.add-to-cart')",
+ },
+ ],
+ });
+ const initial = twoWriteTurn({ designActivity: [write] });
+ const { rerender } = render(<NarrativeView turn={initial} />);
- fireEvent.click(screen.getAllByRole("button", { name: "hide diff" })[1]!);
+ fireEvent.click(
+ screen.getByRole("button", {
+ name: "Expand code changes for add_to_cart",
+ }),
+ );
+ rerender(
+ <NarrativeView
+ turn={twoWriteTurn({
+ designActivity: [
+ write,
+ activityEntry({
+ id: "tr-browse",
+ kind: "tool_result",
+ toolName: "navigate_browser",
+ text: "Opened the cart",
+ success: true,
+ iteration: 1,
+ }),
+ ],
+ })}
+ />,
+ );
+ expect(screen.getByRole("button", { name: "hide diff" })).toBeTruthy();
+ expect(
+ screen.getByText("+await page.click('button.add-to-cart')"),
+ ).toBeTruthy();
+ });
+
+ it("clears live row and diff overrides when the turn becomes terminal", async () => {
+ const live = twoWriteTurn();
+ const { container, rerender } = render(<NarrativeView turn={live} />);
+ fireEvent.click(
+ screen.getByRole("button", {
+ name: "Expand code changes for download_step_v2",
+ }),
+ );
+ expect(screen.getByRole("button", { name: "hide diff" })).toBeTruthy();
+
+ rerender(<NarrativeView turn={{ ...live, terminal: "response" }} />);
+
+ expect(container.querySelector('[aria-expanded="true"]')).toBeNull();
+ expect(screen.queryByRole("button", { name: "hide diff" })).toBeNull();
expect(screen.queryByText("+await page.wait_for_timeout(500)")).toBeNull();
- // The closed row keeps its counts and gains the re-open control; the
- // untouched row is still showing its own patch.
+ await waitFor(() =>
+ expect(document.activeElement).toBe(
+ screen.getByRole("button", { name: /Repaired the download step/ }),
+ ),
+ );
+ });
+
+ it("restores a keyboard-focused activity row when a live turn becomes terminal", async () => {
+ const live = twoWriteTurn();
+ const { rerender } = render(<NarrativeView turn={live} />);
+ const peek = screen.getByRole("button", {
+ name: "Expand code changes for download_step_v2",
+ });
+ peek.focus();
+ expect(document.activeElement).toBe(peek);
+
+ rerender(<NarrativeView turn={{ ...live, terminal: "response" }} />);
+
+ await waitFor(() =>
+ expect(document.activeElement).toBe(
+ screen.getByRole("button", { name: /Repaired the download step/ }),
+ ),
+ );
+ });
+
+ it("shows an explanation control when the active patch was dropped", () => {
+ render(
+ <NarrativeView
+ turn={twoWriteTurn({
+ designActivity: [
+ activityEntry({
+ id: "tr-large",
+ kind: "tool_result",
+ toolName: "add_block",
+ text: "Added a large block",
+ success: true,
+ codeDiffs: [
+ {
+ label: "large_block",
+ added: 1200,
+ removed: 0,
+ patchDropped: true,
+ },
+ ],
+ }),
+ ],
+ })}
+ />,
+ );
+
+ expect(
+ screen.queryByRole("button", {
+ name: "Expand code changes for large_block",
+ }),
+ ).toBeNull();
+ expect(
+ (
+ screen.getByRole("button", {
+ name: "view diff",
+ }) as HTMLButtonElement
+ ).disabled,
+ ).toBe(true);
+ expect(
+ screen.getByTitle(
+ "The diff was too large to keep, so only its line counts were saved.",
+ ),
+ ).toBeTruthy();
+ });
+
+ it("keeps diff counts on a combined write and solo-block run row", () => {
+ render(
+ <NarrativeView
+ turn={{
+ ...twoWriteTurn({
+ designActivity: [
+ activityEntry({
+ id: "tr-write",
+ kind: "tool_result",
+ toolName: "add_block",
+ text: "Added the cart block",
+ success: true,
+ codeDiffs: [
+ {
+ label: "add_to_cart",
+ added: 4,
+ removed: 2,
+ patch: FIRST_PATCH,
+ },
+ ],
+ }),
+ activityEntry({
+ id: "tr-run",
+ kind: "tool_result",
+ toolName: "run_blocks_and_collect_debug",
+ text: "Tested the cart block",
+ success: true,
+ iteration: 1,
+ }),
+ ],
+ }),
+ blocks: [
+ runningBlock({
+ state: "completed",
+ outcome: "demonstrated",
+ label: "add_to_cart",
+ endedAt: "2026-06-10T00:00:08Z",
+ }),
+ ],
+ }}
+ />,
+ );
+
+ expect(screen.getAllByText("+4").length).toBeGreaterThan(0);
+ expect(screen.getAllByText("−2").length).toBeGreaterThan(0);
+ });
+
+ it("a streaming turn auto-opens only the newest write's patch", () => {
+ render(<NarrativeView turn={twoWriteTurn()} />);
+
+ expect(screen.queryByText("-await page.click('#a')")).toBeNull();
+ expect(screen.getByText(/await page\.goto\(URL\)/)).toBeTruthy();
+ expect(screen.queryByText("+await page.wait_for_timeout(500)")).toBeNull();
+ expect(screen.queryByRole("button", { name: "view diff" })).toBeNull();
+ expect(
+ screen.getAllByRole("button", { name: /Expand code changes/ }),
+ ).toHaveLength(1);
+ });
+
+ it("limits the active peek to its first lines but reveals the full patch", () => {
+ const patch = [
+ "@@ -1,7 +1,7 @@",
+ "-line one",
+ "+line one revised",
+ " line two",
+ " line three",
+ " line four",
+ "+line five",
+ ].join("\n");
+ render(
+ <NarrativeView
+ turn={twoWriteTurn({
+ designActivity: [
+ activityEntry({
+ id: "tr-long",
+ kind: "tool_result",
+ toolName: "edit_block_and_run",
+ text: "Updated the search block",
+ success: true,
+ codeDiffs: [
+ {
+ label: "search",
+ added: 2,
+ removed: 1,
+ patch,
+ },
+ ],
+ }),
+ ],
+ })}
+ />,
+ );
+
+ expect(screen.queryByText("+line five")).toBeNull();
+ fireEvent.click(
+ screen.getByRole("button", {
+ name: "Expand code changes for search",
+ }),
+ );
+ expect(screen.getByText("+line five")).toBeTruthy();
+ });
+
+ it("does not show the faded peek when the user manually re-opens a row", () => {
+ const { container } = render(<NarrativeView turn={twoWriteTurn()} />);
+ const currentRow = screen.getByRole("button", {
+ name: /Repaired the download step/,
+ });
+
+ expect(container.querySelector("[data-code-diff-peek]")).toBeTruthy();
+ fireEvent.click(currentRow);
+ fireEvent.click(currentRow);
+
+ expect(container.querySelector("[data-code-diff-peek]")).toBeNull();
+ expect(screen.getByRole("button", { name: "view diff" })).toBeTruthy();
+ });
+
+ it("a historical write reveals its patch only after the row and diff are opened", () => {
+ render(<NarrativeView turn={twoWriteTurn()} />);
+
+ fireEvent.click(
+ screen.getAllByRole("button", { name: /Saved and ran/ })[0]!,
+ );
+
+ expect(screen.queryByText("-await page.click('#a')")).toBeNull();
expect(screen.getAllByRole("button", { name: "view diff" }).length).toBe(1);
+ fireEvent.click(screen.getByRole("button", { name: "view diff" }));
expect(screen.getByText("-await page.click('#a')")).toBeTruthy();
+ expect(screen.getByText(/await page\.goto\(URL\)/)).toBeTruthy();
+ });
+
+ it("keeps collapsed diff counts quiet while preserving patch syntax colors", () => {
+ render(<NarrativeView turn={twoWriteTurn({ terminal: "response" })} />);
+
+ const addedCount = screen.getByText("+4");
+ const removedCount = screen.getByText("−2");
+ expect(addedCount.className).not.toContain("emerald");
+ expect(removedCount.className).not.toContain("rose");
+
+ fireEvent.click(
+ screen.getAllByRole("button", { name: /Saved and ran/ })[0]!,
+ );
+ fireEvent.click(screen.getAllByRole("button", { name: "view diff" })[0]!);
+ expect(screen.getByText("-await page.click('#a')").className).toContain(
+ "rose",
+ );
+ expect(screen.getByText("+await page.click('#b')").className).toContain(
+ "emerald",
+ );
});
it("at Done every write row is collapsed and view diff re-opens one", () => {
- render(
- <NarrativeView turn={twoWriteTurn({ terminal: "response" })} uxV1 />,
+ const { container } = render(
+ <NarrativeView turn={twoWriteTurn({ terminal: "response" })} />,
);
+ expect(container.querySelector("[data-code-diff-peek]")).toBeNull();
expect(screen.queryByText("+await page.wait_for_timeout(500)")).toBeNull();
// Counts stay on the collapsed row line; the patch is behind the expander.
expect(screen.getByText("+4")).toBeTruthy();
@@ -977,7 +1484,7 @@ describe("NarrativeView — code write diffs", () => {
return entry;
}),
};
- render(<NarrativeView turn={legacy} uxV1 />);
+ render(<NarrativeView turn={legacy} />);
expect(screen.getByText("Saved and ran the download step")).toBeTruthy();
expect(screen.queryByText("+4")).toBeNull();
@@ -1003,7 +1510,7 @@ describe("NarrativeView — code write diffs", () => {
},
],
};
- render(<NarrativeView turn={dropped} uxV1 />);
+ render(<NarrativeView turn={dropped} />);
expect(screen.getByText("+4")).toBeTruthy();
expect(screen.getByText("−2")).toBeTruthy();
@@ -1043,7 +1550,7 @@ describe("NarrativeView — code write diffs", () => {
],
});
expect(hydrated).not.toBeNull();
- render(<NarrativeView turn={hydrated!} uxV1 />);
+ render(<NarrativeView turn={hydrated!} />);
expect(screen.getByText("+4")).toBeTruthy();
expect(screen.getByText("−2")).toBeTruthy();
diff --git a/skyvern-frontend/src/routes/workflows/copilot/NarrativeView.collapse.test.tsx b/skyvern-frontend/src/routes/workflows/copilot/NarrativeView.collapse.test.tsx
index ec0b028e9..e9dc268ca 100644
--- a/skyvern-frontend/src/routes/workflows/copilot/NarrativeView.collapse.test.tsx
+++ b/skyvern-frontend/src/routes/workflows/copilot/NarrativeView.collapse.test.tsx
@@ -1,6 +1,12 @@
// @vitest-environment jsdom
-import { cleanup, fireEvent, render, screen } from "@testing-library/react";
+import {
+ cleanup,
+ fireEvent,
+ render,
+ screen,
+ within,
+} from "@testing-library/react";
import { afterEach, describe, expect, it } from "vitest";
import { NarrativeView } from "./NarrativeView";
@@ -138,19 +144,16 @@ describe("NarrativeView collapse default", () => {
expect(screen.getByText("Working…")).toBeTruthy();
});
- it.each([false, true])(
- "renders an interim completed row as neutral in uxV1=%s",
- (uxV1) => {
- render(<NarrativeView turn={interimRunTurn()} uxV1={uxV1} />);
+ it("renders an interim completed row as neutral", () => {
+ render(<NarrativeView turn={interimRunTurn()} />);
- const row = screen.getByTitle("Highlight block_1 on canvas");
- expect(row.textContent).toContain("ran");
- expect(row.textContent).not.toContain("!");
- expect(row.textContent).not.toContain("✓");
- expect(screen.queryByText(/Outcome not confirmed/)).toBeNull();
- expect(screen.queryByText(SHORT_OUTCOME_REASON)).toBeNull();
- },
- );
+ const row = screen.getByTitle("Highlight block_1 on canvas");
+ expect(row.textContent).toContain("ran");
+ expect(row.textContent).not.toContain("!");
+ expect(row.textContent).not.toContain("✓");
+ expect(screen.queryByText(/Outcome not confirmed/)).toBeNull();
+ expect(screen.queryByText(SHORT_OUTCOME_REASON)).toBeNull();
+ });
it.each([undefined, "adjudicated" as const])(
"keeps role=%s not-demonstrated rows amber",
@@ -250,7 +253,8 @@ describe("NarrativeView collapse default", () => {
expect(screen.getByText(HEADLINE)).toBeTruthy();
expect(screen.queryByText("Run halted")).toBeNull();
expect(screen.queryByText("Halted")).toBeNull();
- expect(screen.getAllByText("add_to_cart")).toHaveLength(1);
+ const changedSection = screen.getByText("What changed").parentElement!;
+ expect(within(changedSection).getAllByText("Add To Cart")).toHaveLength(1);
});
it("appends a truncated not-demonstrated reason to the collapsed subtitle", () => {
@@ -443,7 +447,7 @@ const askAfterScoutingTurn = (): TurnNarrativeState => ({
describe("NarrativeView rollup expand affordance", () => {
it("renders a pure needs-input ask as a plain, non-expandable card", () => {
- render(<NarrativeView turn={pureAskTurn()} uxV1 />);
+ render(<NarrativeView turn={pureAskTurn()} />);
expect(screen.getByText("Which login should I use?")).toBeTruthy();
expect(screen.queryByRole("button")).toBeNull();
@@ -451,7 +455,7 @@ describe("NarrativeView rollup expand affordance", () => {
});
it("keeps the chevron for an ask that follows scouting and reveals the thought stream on expand", () => {
- render(<NarrativeView turn={askAfterScoutingTurn()} uxV1 />);
+ render(<NarrativeView turn={askAfterScoutingTurn()} />);
const head = screen.getByRole("button");
expect(head.getAttribute("aria-expanded")).toBe("false");
@@ -473,13 +477,12 @@ describe("NarrativeView rollup expand affordance", () => {
});
it("gains the expand affordance when activity arrives after a content-free render", () => {
- const { rerender } = render(<NarrativeView turn={pureAskTurn()} uxV1 />);
+ const { rerender } = render(<NarrativeView turn={pureAskTurn()} />);
expect(screen.queryByRole("button")).toBeNull();
rerender(
<NarrativeView
turn={{ ...pureAskTurn(), blocks: [completedBlock("block_1")] }}
- uxV1
/>,
);
const head = screen.getByRole("button");
@@ -514,15 +517,17 @@ describe("a stopped block stays inspectable", () => {
it("names the stopped block in the collapsed rollup", () => {
render(<NarrativeView turn={stoppedTurn()} />);
- expect(screen.getByText("Stopped", { selector: "div" })).toBeTruthy();
- expect(screen.getByText("log_in")).toBeTruthy();
+ const stoppedSection = screen.getByText("Stopped", {
+ selector: "div",
+ }).parentElement!;
+ expect(within(stoppedSection).getByText("Log In")).toBeTruthy();
expect(screen.queryByText("Halted")).toBeNull();
});
// A non-solo run row keeps its block cards in the collapsed body, so the log
// is not a substitute for the summary list on a finished turn.
it("still names a stopped block on the activity-log surface", () => {
- render(<NarrativeView turn={stoppedTurn()} uxV1 />);
+ render(<NarrativeView turn={stoppedTurn()} />);
expect(screen.getByText("Stopped", { selector: "div" })).toBeTruthy();
});
@@ -564,7 +569,7 @@ describe("a stopped block stays inspectable", () => {
expect(screen.getAllByText(/download/i).length).toBeGreaterThan(0);
legacy.unmount();
- render(<NarrativeView turn={twoBlockTurn()} uxV1 />);
+ render(<NarrativeView turn={twoBlockTurn()} />);
expect(screen.getAllByText(/download/i).length).toBeGreaterThan(0);
});
@@ -594,7 +599,7 @@ describe("a stopped block stays inspectable", () => {
blocks: [completedBlock("download_report")],
});
- render(<NarrativeView turn={narratedRunTurn()} uxV1 />);
+ render(<NarrativeView turn={narratedRunTurn()} />);
expect(screen.getByText("Rewrote the download step")).toBeTruthy();
// The block itself is still named by the rollup's own list.
diff --git a/skyvern-frontend/src/routes/workflows/copilot/NarrativeView.reveal.test.tsx b/skyvern-frontend/src/routes/workflows/copilot/NarrativeView.reveal.test.tsx
index dfbfa5885..0769d0636 100644
--- a/skyvern-frontend/src/routes/workflows/copilot/NarrativeView.reveal.test.tsx
+++ b/skyvern-frontend/src/routes/workflows/copilot/NarrativeView.reveal.test.tsx
@@ -229,7 +229,6 @@ describe("NarrativeView — narration reveal", () => {
render(
<NarrativeView
turn={narrationTurn([toolCall("1", 1), narration(1, NOW - 500)])}
- uxV1
/>,
);
@@ -250,7 +249,6 @@ describe("NarrativeView — narration reveal", () => {
render(
<NarrativeView
turn={narrationTurn([toolCall("1", 1), narration(1, undefined)])}
- uxV1
/>,
);
@@ -263,7 +261,6 @@ describe("NarrativeView — narration reveal", () => {
render(
<NarrativeView
turn={narrationTurn([toolCall("1", 1), narration(1, undefined)])}
- uxV1
/>,
);
@@ -275,7 +272,6 @@ describe("NarrativeView — narration reveal", () => {
render(
<NarrativeView
turn={narrationTurn([toolCall("1", 1), narration(1, NOW - 500)])}
- uxV1
/>,
);
@@ -297,7 +293,6 @@ describe("NarrativeView — narration reveal", () => {
narration(1, NOW),
toolCall("2", 2, "edit_block"),
])}
- uxV1
/>,
);
diff --git a/skyvern-frontend/src/routes/workflows/copilot/NarrativeView.test.ts b/skyvern-frontend/src/routes/workflows/copilot/NarrativeView.test.ts
index 2d838e04f..40b06041c 100644
--- a/skyvern-frontend/src/routes/workflows/copilot/NarrativeView.test.ts
+++ b/skyvern-frontend/src/routes/workflows/copilot/NarrativeView.test.ts
@@ -220,6 +220,35 @@ describe("applyNarrativeEvent — design phase", () => {
expect(s.designActivity.some((e) => e.id === "tr-call-1")).toBe(false);
});
+ it("shows a repair patch while its active block is still running", () => {
+ const diffs = [
+ { label: "star_count", added: 4, removed: 2, patch: "@@\n-code\n+fixed" },
+ ];
+ let s = applyNarrativeEvent(
+ EMPTY_NARRATIVE,
+ blockProgress({ block_label: "star_count", status: "running" }),
+ );
+ s = applyNarrativeEvent(s, toolCall());
+
+ expect(s.blocks[0]?.activity[0]?.id).toBe("tc-call-1");
+ s = applyNarrativeEvent(
+ s,
+ workflowDraft({
+ block_count: 1,
+ block_labels: ["star_count"],
+ code_diffs: diffs,
+ tool_call_id: "call-1",
+ }),
+ );
+
+ // No tool_result yet: a repair nested under the active block must expose
+ // the write at the same early seam as an initial design-phase write.
+ expect(s.blocks[0]?.activity[0]?.codeDiffs).toMatchObject([
+ { label: "star_count", added: 4, removed: 2, patch: "@@\n-code\n+fixed" },
+ ]);
+ expect(s.designActivity.some((e) => e.id === "tr-call-1")).toBe(false);
+ });
+
it("a draft naming no call leaves the activity log untouched", () => {
// Older backends send no tool_call_id; the row must not guess which call to attach to.
let s = applyNarrativeEvent(EMPTY_NARRATIVE, toolCall());
@@ -453,6 +482,35 @@ describe("condenseActivityEntries", () => {
expect(condensed[0]).toMatchObject({ kind: "tool_result", success: true });
});
+ it("keeps the call timestamp when replacing it with its settled result", () => {
+ const condensed = condenseActivityEntries([
+ {
+ id: "tc-call-1",
+ kind: "tool_call",
+ text: "Opening page",
+ iteration: 0,
+ toolName: "navigate_browser",
+ timestamp: "2026-05-25T00:00:04Z",
+ },
+ {
+ id: "tr-call-1",
+ kind: "tool_result",
+ text: "The page did not open",
+ iteration: 0,
+ toolName: "navigate_browser",
+ success: false,
+ timestamp: "2026-05-25T00:00:24Z",
+ },
+ ]);
+
+ expect(condensed).toHaveLength(1);
+ expect(condensed[0]).toMatchObject({
+ kind: "tool_result",
+ activityStartedAt: "2026-05-25T00:00:04Z",
+ timestamp: "2026-05-25T00:00:24Z",
+ });
+ });
+
it("REGRESSION PIN: substitutes the humanized tool name for the backend's bare 'OK' fallback (celal QA catch)", () => {
// A tool with no dedicated backend summary falls back to a literal
// "OK" — condensing already removed the "<tool> · calling…" row that
@@ -524,6 +582,81 @@ describe("condenseActivityEntries", () => {
expect(condensed[0]).toMatchObject({ success: true, attempts: 3 });
});
+ it("keeps the first attempt's start across a folded retry chain", () => {
+ const condensed = condenseActivityEntries([
+ {
+ id: "tc-c1",
+ kind: "tool_call",
+ text: "Opening page",
+ iteration: 0,
+ toolName: "navigate_browser",
+ timestamp: "2026-05-25T00:00:04Z",
+ },
+ {
+ id: "tr-c1",
+ kind: "tool_result",
+ text: "The page did not open",
+ iteration: 0,
+ toolName: "navigate_browser",
+ success: false,
+ timestamp: "2026-05-25T00:00:24Z",
+ },
+ {
+ id: "tc-c2",
+ kind: "tool_call",
+ text: "Opening page",
+ iteration: 1,
+ toolName: "navigate_browser",
+ timestamp: "2026-05-25T00:00:29Z",
+ },
+ {
+ id: "tr-c2",
+ kind: "tool_result",
+ text: "Opened",
+ iteration: 1,
+ toolName: "navigate_browser",
+ success: true,
+ timestamp: "2026-05-25T00:00:49Z",
+ },
+ ]);
+
+ expect(condensed).toHaveLength(1);
+ expect(condensed[0]).toMatchObject({
+ attempts: 2,
+ activityStartedAt: "2026-05-25T00:00:04Z",
+ timestamp: "2026-05-25T00:00:49Z",
+ });
+ });
+
+ it("keeps overlapping same-tool siblings separate instead of calling them retries", () => {
+ const condensed = condenseActivityEntries([
+ {
+ id: "tr-a",
+ kind: "tool_result",
+ text: "The first call failed",
+ iteration: 0,
+ toolName: "navigate_browser",
+ success: false,
+ activityStartedAt: "2026-05-25T00:00:10Z",
+ timestamp: "2026-05-25T00:00:30Z",
+ },
+ {
+ id: "tr-b",
+ kind: "tool_result",
+ text: "The parallel call succeeded",
+ iteration: 1,
+ toolName: "navigate_browser",
+ success: true,
+ activityStartedAt: "2026-05-25T00:00:20Z",
+ timestamp: "2026-05-25T00:00:40Z",
+ },
+ ]);
+
+ expect(condensed).toHaveLength(2);
+ expect(condensed.map((entry) => entry.id)).toEqual(["tr-a", "tr-b"]);
+ expect(condensed.every((entry) => entry.attempts === undefined)).toBe(true);
+ });
+
it("folds a retry across a narration sitting between two attempts (narration never breaks the fold)", () => {
// Array position can't reliably tell "narration between attempts" from
// "narration mid-flight during the retry itself" (see the regression
@@ -999,13 +1132,13 @@ describe("hydrateNarrativeFromPayload — terminal adjudication fields", () => {
});
describe("computeTurnSummary — typed terminal adjudication", () => {
- it("renders the loop-guard clarify repro as a Question, not a green built-and-tested claim", () => {
+ it("renders the loop-guard clarify repro as needing input, not a green built-and-tested claim", () => {
const turn = hydrateNarrativeFromPayload(
reproClarifyPayload({ responseKind: "clarify" }),
);
expect(turn).toBeDefined();
const summary = computeTurnSummary(turn!);
- expect(summary.headline).toBe("Question");
+ expect(summary.headline).toBe("Needs your input");
expect(summary.accent).toBe("qa");
expect(summary.glyph).toBe("✦");
});
@@ -1039,7 +1172,7 @@ describe("computeTurnSummary — typed terminal adjudication", () => {
}),
);
- expect(summary.headline).toBe("Question");
+ expect(summary.headline).toBe("Needs your input");
expect(summary.accent).toBe("qa");
});
@@ -1059,7 +1192,7 @@ describe("computeTurnSummary — typed terminal adjudication", () => {
}),
);
- expect(summary.headline).toBe("Question");
+ expect(summary.headline).toBe("Needs your input");
expect(summary.accent).toBe("qa");
});
@@ -1136,7 +1269,7 @@ describe("computeTurnSummary — typed terminal adjudication", () => {
expect(summary.glyph).toBe("!");
});
- it("keeps the Question headline when response_type is ASK_QUESTION", () => {
+ it("keeps the Needs your input headline when response_type is ASK_QUESTION", () => {
const summary = computeTurnSummary(
buildTurn({
responseKind: "clarify",
@@ -1147,12 +1280,12 @@ describe("computeTurnSummary — typed terminal adjudication", () => {
},
}),
);
- expect(summary.headline).toBe("Question");
+ expect(summary.headline).toBe("Needs your input");
expect(summary.accent).toBe("qa");
expect(summary.glyph).toBe("✦");
});
- it("keeps the Question headline for ASK_QUESTION even when hydrated blocks carry not_demonstrated", () => {
+ it("keeps the Needs your input headline for ASK_QUESTION even when hydrated blocks carry not_demonstrated", () => {
const turn = hydrateNarrativeFromPayload(
reproClarifyPayload({
responseKind: "clarify",
@@ -1176,7 +1309,7 @@ describe("computeTurnSummary — typed terminal adjudication", () => {
)!;
expect(turn.lastRunOutcome).toBeNull();
const summary = computeTurnSummary(turn);
- expect(summary.headline).toBe("Question");
+ expect(summary.headline).toBe("Needs your input");
expect(summary.accent).toBe("qa");
expect(summary.glyph).toBe("✦");
});
@@ -1189,14 +1322,9 @@ describe("computeTurnSummary — typed terminal adjudication", () => {
responseType: "ASK_QUESTION",
});
const summary = computeTurnSummary(turn);
- expect(summary.headline).toBe("Question");
+ expect(summary.headline).toBe("Needs your input");
expect(summary.accent).toBe("qa");
expect(summary.glyph).toBe("✦");
-
- const uxSummary = computeTurnSummary(turn, { uxV1: true });
- expect(uxSummary.headline).toBe("Needs your input");
- expect(uxSummary.accent).toBe("qa");
- expect(uxSummary.glyph).toBe("✦");
});
it("keeps review disposition precedence over build-kind ASK_QUESTION", () => {
@@ -1231,7 +1359,7 @@ describe("computeTurnSummary — typed terminal adjudication", () => {
responseKind: "clarify",
}),
);
- expect(summary.headline).toBe("Question");
+ expect(summary.headline).toBe("Needs your input");
expect(summary.accent).toBe("qa");
expect(summary.glyph).toBe("✦");
});
@@ -1247,7 +1375,7 @@ describe("computeTurnSummary — typed terminal adjudication", () => {
turn.blocks.some((block) => block.outcome === "not_demonstrated"),
).toBe(false);
const summary = computeTurnSummary(turn);
- expect(summary.headline).toBe("Question");
+ expect(summary.headline).toBe("Needs your input");
expect(summary.accent).toBe("qa");
expect(summary.glyph).toBe("✦");
});
@@ -1268,14 +1396,14 @@ describe("computeTurnSummary — typed terminal adjudication", () => {
}),
)!;
const summary = computeTurnSummary(turn);
- expect(summary.headline).toBe("Question");
+ expect(summary.headline).toBe("Needs your input");
expect(summary.headline).not.toBe("Applied edits and re-tested");
expect(summary.accent).not.toBe("ok");
});
it.each([
- ["clarify", "Question"],
- ["recover", "Question"],
+ ["clarify", "Needs your input"],
+ ["recover", "Needs your input"],
["refuse", "Declined"],
["diagnose", "Answered"],
["answer", "Answered"],
@@ -1316,7 +1444,7 @@ describe("computeTurnSummary — typed terminal adjudication", () => {
it("does not infer a completed run from a build response kind alone", () => {
const summary = computeTurnSummary(buildTurn({ responseKind: "build" }));
- expect(summary.headline).toBe("Question");
+ expect(summary.headline).toBe("Needs your input");
});
it("keeps the prose question heuristic without a run fact", () => {
@@ -1327,7 +1455,7 @@ describe("computeTurnSummary — typed terminal adjudication", () => {
responseKind: "build",
}),
);
- expect(summary.headline).toBe("Question");
+ expect(summary.headline).toBe("Needs your input");
});
it("renders a clean completed build from its block lifecycle", () => {
@@ -1402,7 +1530,7 @@ describe("computeTurnSummary — typed terminal adjudication", () => {
terminalMessage: "Is that output format okay?",
});
- expect(computeTurnSummary(askTurn, { uxV1: true }).headline).toBe(
+ expect(computeTurnSummary(askTurn).headline).toBe(
"Workflow ready for review",
);
expect(getReviewGateVerdict(askTurn, null)).toBe("tested");
@@ -1446,15 +1574,14 @@ describe("computeTurnSummary — typed terminal adjudication", () => {
});
});
-describe("computeTurnSummary — uxV1 disposition-first reorder (SKY-12136)", () => {
- it("a pending untested draft outranks a non-build responseKind (old: Question)", () => {
+describe("computeTurnSummary — disposition-first reorder", () => {
+ it("a pending untested draft outranks a non-build responseKind", () => {
const turn = buildTurn({
responseKind: "clarify",
draft: draft3,
proposalDisposition: "review_untested",
});
- expect(computeTurnSummary(turn).headline).toBe("Question");
- const summary = computeTurnSummary(turn, { uxV1: true });
+ const summary = computeTurnSummary(turn);
expect(summary.headline).toBe("Draft needs review");
expect(summary.accent).toBe("qa");
expect(summary.glyph).toBe("!");
@@ -1467,7 +1594,6 @@ describe("computeTurnSummary — uxV1 disposition-first reorder (SKY-12136)", ()
draft: draft3,
proposalDisposition: "review_tested",
}),
- { uxV1: true },
);
expect(summary.headline).toBe("Workflow ready for review");
expect(summary.accent).toBe("qa");
@@ -1481,17 +1607,16 @@ describe("computeTurnSummary — uxV1 disposition-first reorder (SKY-12136)", ()
terminalMessage: "Could you provide the login details?",
});
expect(turn.responseKind).toBeNull();
- expect(computeTurnSummary(turn).headline).toBe("Question");
- const summary = computeTurnSummary(turn, { uxV1: true });
+ const summary = computeTurnSummary(turn);
expect(summary.headline).toBe("Draft needs review");
});
- it("old payload (hydrated, no responseKind) still gets the uxV1 draft-review reorder", () => {
+ it("old payload (hydrated, no responseKind) still gets the draft-review reorder", () => {
const turn = hydrateNarrativeFromPayload(
reproClarifyPayload({ proposalDisposition: "review_untested" }),
)!;
expect(turn.responseKind).toBeNull();
- const summary = computeTurnSummary(turn, { uxV1: true });
+ const summary = computeTurnSummary(turn);
expect(summary.headline).toBe("Draft needs review");
});
@@ -1501,7 +1626,6 @@ describe("computeTurnSummary — uxV1 disposition-first reorder (SKY-12136)", ()
responseKind: "clarify",
responseType: "ASK_QUESTION",
}),
- { uxV1: true },
);
expect(summary.headline).toBe("Needs your input");
expect(summary.accent).toBe("qa");
@@ -1513,17 +1637,15 @@ describe("computeTurnSummary — uxV1 disposition-first reorder (SKY-12136)", ()
["diagnose", "Answered"],
["answer", "Answered"],
] as const)(
- "leaves %s as %s under uxV1 — only the clarify/Question case renames",
+ "leaves %s as %s under the default summary behavior",
(kind, headline) => {
- const summary = computeTurnSummary(buildTurn({ responseKind: kind }), {
- uxV1: true,
- });
+ const summary = computeTurnSummary(buildTurn({ responseKind: kind }));
expect(summary.headline).toBe(headline);
expect(summary.accent).toBe("qa");
},
);
- it("isStoppedWithDraft keeps absolute precedence under uxV1 too", () => {
+ it("isStoppedWithDraft keeps absolute precedence", () => {
const summary = computeTurnSummary(
buildTurn({
cancelled: true,
@@ -1531,18 +1653,16 @@ describe("computeTurnSummary — uxV1 disposition-first reorder (SKY-12136)", ()
proposalDisposition: "review_untested",
responseKind: "build",
}),
- { uxV1: true },
);
expect(summary.headline).toBe("Stopped with a draft");
expect(summary.accent).toBe("qa");
});
- it("uxV1 fallback needsInput still renders Needs your input when no draft is pending", () => {
+ it("fallback needsInput renders Needs your input when no draft is pending", () => {
const turn = buildTurn({
terminalMessage: "Could you provide the login details?",
});
- expect(computeTurnSummary(turn).headline).toBe("Question");
- const summary = computeTurnSummary(turn, { uxV1: true });
+ const summary = computeTurnSummary(turn);
expect(summary.headline).toBe("Needs your input");
});
});
@@ -1554,7 +1674,7 @@ describe("hydrateHistoryNarrative — persisted turn_outcome graft", () => {
})!;
expect(turn.responseKind).toBe("clarify");
const summary = computeTurnSummary(turn);
- expect(summary.headline).toBe("Question");
+ expect(summary.headline).toBe("Needs your input");
expect(summary.accent).toBe("qa");
});
@@ -1603,7 +1723,7 @@ describe("applyNarrativeEvent — terminal adjudication on live frames", () => {
}),
);
expect(s.responseKind).toBe("clarify");
- expect(computeTurnSummary(s).headline).toBe("Question");
+ expect(computeTurnSummary(s).headline).toBe("Needs your input");
});
it("leaves both fields null on frames from an older backend", () => {
@@ -1855,7 +1975,6 @@ describe("a real cancel's backend payload still renders neutrally", () => {
const summaryFor = (responseKind: "build" | "answer" | "recover") =>
computeTurnSummary(
buildTurn({ cancelled: true, blocks: [], draft: null, responseKind }),
- { uxV1: true },
);
expect(summaryFor(priorKind)).toEqual(summaryFor("recover"));
@@ -1876,7 +1995,6 @@ describe("a real cancel's backend payload still renders neutrally", () => {
proposalDisposition: "review_untested",
responseKind,
}),
- { uxV1: true },
);
expect(summaryFor(priorKind)).toEqual(summaryFor("recover"));
diff --git a/skyvern-frontend/src/routes/workflows/copilot/NarrativeView.tsx b/skyvern-frontend/src/routes/workflows/copilot/NarrativeView.tsx
index 132b03ea6..238ae2e1b 100644
--- a/skyvern-frontend/src/routes/workflows/copilot/NarrativeView.tsx
+++ b/skyvern-frontend/src/routes/workflows/copilot/NarrativeView.tsx
@@ -1,8 +1,10 @@
import {
+ type Ref,
type ReactNode,
useCallback,
useEffect,
useMemo,
+ useRef,
useState,
} from "react";
@@ -322,12 +324,18 @@ function entryLine(
};
}
const ok = entry.success !== false;
+ const label =
+ title ?? entry.displayLabel ?? toolActivityDisplayLabel(entry.toolName);
return {
content: (
<>
- <span className={ok ? undefined : "text-rose-700 dark:text-rose-200"}>
- {ok ? (title ?? entry.text) : entry.text}
- </span>
+ <span>{ok ? (title ?? entry.text) : label}</span>
+ {!ok ? (
+ <span className="text-muted-foreground dark:text-slate-500">
+ {" "}
+ · attempt failed
+ </span>
+ ) : null}
<AttemptsBadge attempts={entry.attempts} />
</>
),
@@ -478,7 +486,6 @@ interface FBlockRunProps {
block: BlockState;
turnEnded: boolean;
onSelect?: (label: string) => void;
- uxV1?: boolean;
outcomeReasonFallback?: string | null;
// Narrator title for the row this card heads. The card's own status text and
// the rollup's block lists still name the block, so the title replaces only
@@ -492,26 +499,35 @@ interface FBlockRunProps {
rowGlyph?: React.ReactNode;
rowKindWord?: string;
rowTrailing?: React.ReactNode;
+ rowDiffCounts?: { added: number; removed: number };
// When the activity log owns this card's row, open/closed comes from there
// so the row and the card never disagree about a single click.
expansion?: { open: boolean; onToggle: () => void };
+ // Historical failed attempts stay quiet in the collapsed timeline. Their
+ // full failure treatment remains available in the expanded evidence.
+ quietFailure?: boolean;
+ // Activity-log context that should lead the block's own run evidence.
+ detailBeforeBlock?: React.ReactNode;
+ detailAfterBlock?: React.ReactNode;
}
function FBlockRun({
block,
turnEnded,
onSelect,
- uxV1,
outcomeReasonFallback,
rowTitle,
flat,
rowGlyph,
rowKindWord,
rowTrailing,
+ rowDiffCounts,
expansion,
+ quietFailure,
+ detailBeforeBlock,
+ detailAfterBlock,
}: FBlockRunProps) {
- const displayLabel =
- rowTitle ?? (uxV1 ? humanizeBlockLabel(block.label) : block.label);
+ const displayLabel = rowTitle ?? humanizeBlockLabel(block.label);
const palette = paletteFor(block.blockType);
const isRunning = block.state === "running";
const isCompleted = block.state === "completed";
@@ -530,6 +546,7 @@ function FBlockRun({
!isInterimNotDemonstrated;
const isOk = isBlockOk(block);
const isFail = block.state === "failed";
+ const prominentFailure = isFail && !quietFailure;
const isStopped = block.state === "stopped";
const isDraft = block.state === "drafted";
@@ -539,7 +556,7 @@ function FBlockRun({
? "border-emerald-400/60"
: isOutcomeNotShown
? "border-amber-400/60"
- : isFail
+ : prominentFailure
? "border-rose-400/60"
: "border-slate-500/60";
const accentText = isRunning
@@ -548,7 +565,7 @@ function FBlockRun({
? "text-emerald-700 dark:text-emerald-300"
: isOutcomeNotShown
? "text-amber-700 dark:text-amber-300"
- : isFail
+ : prominentFailure
? "text-rose-700 dark:text-rose-300"
: isVerifying || isRanNeutral
? "text-tertiary-foreground"
@@ -559,7 +576,7 @@ function FBlockRun({
? "bg-emerald-500/15"
: isOutcomeNotShown
? "bg-amber-500/15"
- : isFail
+ : prominentFailure
? "bg-rose-500/15"
: "bg-slate-elevation3";
@@ -603,13 +620,23 @@ function FBlockRun({
// stopped, so it should not demand attention the way a failure does. Under
// the activity log `expansion` supplies the open state and none of this
// applies — there, every finished row folds, a failure included.
+ const hasExpandableDetail =
+ detailBeforeBlock !== null && detailBeforeBlock !== undefined
+ ? true
+ : isRunning ||
+ block.activity.length > 0 ||
+ hasActions ||
+ isFail ||
+ isOutcomeNotShown ||
+ (detailAfterBlock !== null && detailAfterBlock !== undefined);
const toggleable =
- expansion !== undefined ||
- isOk ||
- isOutcomeNotShown ||
- isVerifying ||
- isRanNeutral ||
- isStopped;
+ hasExpandableDetail &&
+ (expansion !== undefined ||
+ isOk ||
+ isOutcomeNotShown ||
+ isVerifying ||
+ isRanNeutral ||
+ isStopped);
useTick(isRunning);
useFrameTick(hasActions && (replayingAction || elapsedReveal < totalMs));
const elapsed = formatElapsed(block.startedAt, block.endedAt);
@@ -668,9 +695,10 @@ function FBlockRun({
const onHeaderClick = () => {
onSelect?.(block.label);
+ if (!toggleable) return;
if (expansion) {
expansion.onToggle();
- } else if (toggleable) {
+ } else {
setUserOpen((v) => !(v === null ? defaultOpen : v));
}
};
@@ -695,6 +723,7 @@ function FBlockRun({
const blockDetail = (
<div className="flex flex-col gap-1.5 border-l border-border/60 py-1.5 pl-3">
+ {detailBeforeBlock}
{isRunning ? (
<span className="inline-flex w-fit items-center gap-1.5 rounded-full border border-blue-400/40 bg-blue-500/10 px-2 py-0.5 text-[11px] font-semibold text-blue-700 dark:text-blue-300">
<span className="h-[5px] w-[5px] animate-pulse rounded-full bg-blue-400" />
@@ -749,6 +778,7 @@ function FBlockRun({
</div>
</div>
) : null}
+ {detailAfterBlock}
</div>
);
@@ -765,7 +795,7 @@ function FBlockRun({
</>
}
onClick={onHeaderClick}
- expanded={expansion ? open : undefined}
+ expanded={toggleable && expansion ? open : undefined}
title={`Highlight ${block.label} on canvas`}
>
{displayLabel}
@@ -776,9 +806,18 @@ function FBlockRun({
</span>
)}
<span className="sr-only">{` · ${stateWord}`}</span>
+ {rowDiffCounts === undefined ? null : (
+ <span className="font-mono tabular-nums text-muted-foreground dark:text-slate-500">
+ <span>{" · "}</span>
+ <span>{`+${rowDiffCounts.added}`}</span>
+ <span className="pl-1">{`−${rowDiffCounts.removed}`}</span>
+ </span>
+ )}
</FLogLine>
<div className="pl-[28px]">{collapsedExtras}</div>
- {open ? <div className="pl-[28px]">{blockDetail}</div> : null}
+ {open && hasExpandableDetail ? (
+ <div className="pl-[28px]">{blockDetail}</div>
+ ) : null}
</div>
);
}
@@ -790,7 +829,7 @@ function FBlockRun({
className={`flex w-full items-start gap-3 px-1 py-1 text-left ${
toggleable ? "cursor-pointer" : "cursor-default"
}`}
- aria-expanded={expansion ? expansion.open : undefined}
+ aria-expanded={toggleable && expansion ? expansion.open : undefined}
onClick={onHeaderClick}
title={`Highlight ${block.label} on canvas`}
>
@@ -803,12 +842,8 @@ function FBlockRun({
<div className="flex min-w-0 flex-1 flex-col">
<div className="flex flex-wrap items-baseline gap-x-1.5 gap-y-0.5">
<span
- className={
- uxV1
- ? "text-[12.5px] font-semibold text-foreground"
- : "font-mono text-[12.5px] font-semibold text-foreground"
- }
- title={uxV1 ? block.label : undefined}
+ className="text-[12.5px] font-semibold text-foreground"
+ title={block.label}
>
{displayLabel}
</span>
@@ -836,7 +871,9 @@ function FBlockRun({
) : null}
</button>
- {open ? <div className="ml-9">{blockDetail}</div> : null}
+ {open && hasExpandableDetail ? (
+ <div className="ml-9">{blockDetail}</div>
+ ) : null}
</div>
);
}
@@ -845,10 +882,9 @@ interface FDesignRowProps {
done: boolean;
blockLabels: string[];
activity: ActivityEntry[];
- uxV1?: boolean;
}
-function FDesignRow({ done, blockLabels, activity, uxV1 }: FDesignRowProps) {
+function FDesignRow({ done, blockLabels, activity }: FDesignRowProps) {
const [userOpen, setUserOpen] = useState<boolean | null>(null);
const open = userOpen === null ? !done : userOpen;
const drafts = blockLabels.length;
@@ -913,13 +949,8 @@ function FDesignRow({ done, blockLabels, activity, uxV1 }: FDesignRowProps) {
glyphClass="text-emerald-700 dark:text-emerald-300"
>
<span className="text-muted-foreground">Drafted </span>
- <span
- className={
- uxV1 ? "text-foreground" : "font-mono text-foreground"
- }
- title={uxV1 ? label : undefined}
- >
- {uxV1 ? humanizeBlockLabel(label) : label}
+ <span className="text-foreground" title={label}>
+ {humanizeBlockLabel(label)}
</span>
</FSubRow>
))}
@@ -929,20 +960,6 @@ function FDesignRow({ done, blockLabels, activity, uxV1 }: FDesignRowProps) {
);
}
-function FWorkingHeader() {
- return (
- <div className="flex items-center gap-2 px-1 py-1">
- <Spinner />
- <span className="text-[12.5px] font-semibold text-foreground">
- Working…
- </span>
- <span className="text-[11px] text-muted-foreground">
- · building your workflow
- </span>
- </div>
- );
-}
-
export const COPILOT_ACK_LINES = [
"Reading your request…",
"Getting oriented…",
@@ -998,7 +1015,7 @@ interface FActivityLogProps {
turn: TurnNarrativeState;
turnEnded: boolean;
onBlockSelect?: (label: string) => void;
- uxV1?: boolean;
+ interactionRef?: { current: string | null };
}
// The kind gutter sits to the left of ActivityRow's own status column, so a
@@ -1008,22 +1025,45 @@ interface FActivityLogProps {
function FCodeWriteDiff({
diff,
open,
+ peek,
onToggle,
- uxV1,
}: {
diff: CodeWriteDiff;
open: boolean;
+ peek: boolean;
onToggle: () => void;
- uxV1?: boolean;
}) {
+ const expandedToggleRef = useRef<HTMLButtonElement>(null);
+ const restoreFocusAfterPeek = useRef(false);
+ useEffect(() => {
+ if (!open || !restoreFocusAfterPeek.current) return;
+ expandedToggleRef.current?.focus();
+ restoreFocusAfterPeek.current = false;
+ }, [open]);
+ const patchLines = diff.patch?.split("\n") ?? [];
+ const renderLine = (line: string, i: number, muted: boolean) => (
+ <span
+ key={`${i}-${line}`}
+ className={[
+ "block",
+ line.startsWith("+")
+ ? "text-emerald-700 dark:text-emerald-300"
+ : line.startsWith("-")
+ ? "text-rose-700 dark:text-rose-300"
+ : "text-muted-foreground",
+ muted ? "!text-muted-foreground" : "",
+ ]
+ .filter(Boolean)
+ .join(" ")}
+ >
+ {line}
+ </span>
+ );
return (
<div className="flex flex-col">
<FSubRow glyph="±" glyphClass="text-sky-700 dark:text-sky-300">
- <span
- className={uxV1 ? "text-foreground" : "font-mono text-foreground"}
- title={diff.label}
- >
- {uxV1 ? humanizeBlockLabel(diff.label) : diff.label}
+ <span className="text-foreground" title={diff.label}>
+ {humanizeBlockLabel(diff.label)}
</span>
<span className="pl-1.5 font-mono text-emerald-700 dark:text-emerald-300">
{`+${diff.added}`}
@@ -1031,43 +1071,53 @@ function FCodeWriteDiff({
<span className="pl-1 font-mono text-rose-700 dark:text-rose-300">
{`−${diff.removed}`}
</span>
- {/* A disabled control receives no pointer events, so the reason why it is
- dead has to hang on something that does. */}
- <span
- title={
- diff.patchDropped
- ? "The diff was too large to keep, so only its line counts were saved."
- : undefined
- }
- >
- <button
- type="button"
- className="pl-2 text-muted-foreground underline-offset-2 hover:underline disabled:no-underline disabled:opacity-50"
- disabled={diff.patch === undefined}
- aria-expanded={open}
- onClick={onToggle}
+ {peek ? null : (
+ /* A disabled control receives no pointer events, so the reason why it is
+ dead has to hang on something that does. */
+ <span
+ title={
+ diff.patchDropped
+ ? "The diff was too large to keep, so only its line counts were saved."
+ : undefined
+ }
>
- {open ? "hide diff" : "view diff"}
- </button>
- </span>
+ <button
+ ref={expandedToggleRef}
+ type="button"
+ className="pl-2 text-muted-foreground underline-offset-2 hover:underline disabled:no-underline disabled:opacity-50"
+ disabled={diff.patch === undefined}
+ aria-expanded={open}
+ onClick={onToggle}
+ >
+ {open ? "hide diff" : "view diff"}
+ </button>
+ </span>
+ )}
</FSubRow>
{open && diff.patch !== undefined ? (
<pre className="ml-5 overflow-x-auto whitespace-pre rounded border border-border/60 bg-muted/40 p-2 text-[11px] leading-[1.5]">
- {diff.patch.split("\n").map((line, i) => (
- <div
- key={`${i}-${line}`}
- className={
- line.startsWith("+")
- ? "text-emerald-700 dark:text-emerald-300"
- : line.startsWith("-")
- ? "text-rose-700 dark:text-rose-300"
- : "text-muted-foreground"
- }
- >
- {line}
- </div>
- ))}
+ {patchLines.map((line, i) => renderLine(line, i, false))}
</pre>
+ ) : peek && diff.patch !== undefined ? (
+ <button
+ type="button"
+ data-code-diff-peek="true"
+ aria-label={`Expand code changes for ${diff.label}`}
+ aria-expanded={false}
+ className="relative ml-5 max-h-[72px] cursor-pointer overflow-hidden rounded bg-muted/20 px-2 pb-6 pt-2 text-left text-[11px] leading-[1.5] transition-colors hover:bg-muted/30 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring motion-reduce:transition-none"
+ onClick={() => {
+ restoreFocusAfterPeek.current = true;
+ onToggle();
+ }}
+ >
+ <code className="block whitespace-pre">
+ {patchLines.slice(0, 2).map((line, i) => renderLine(line, i, true))}
+ </code>
+ <span
+ aria-hidden="true"
+ className="pointer-events-none absolute inset-x-0 bottom-0 h-5 bg-gradient-to-b from-transparent to-muted/80"
+ />
+ </button>
) : null}
</div>
);
@@ -1078,20 +1128,20 @@ function FActivityLogRow({
open,
onToggle,
diffOpen,
+ diffPeek,
onDiffToggle,
turnEnded,
onBlockSelect,
- uxV1,
outcomeReasonFallback,
}: {
row: ActivityRowModel;
open: boolean;
onToggle: () => void;
diffOpen: (label: string) => boolean;
+ diffPeek: (label: string) => boolean;
onDiffToggle: (label: string) => void;
turnEnded: boolean;
onBlockSelect?: (label: string) => void;
- uxV1?: boolean;
outcomeReasonFallback?: string | null;
}) {
const last = row.entries[row.entries.length - 1];
@@ -1104,22 +1154,34 @@ function FActivityLogRow({
row.pending && only !== undefined && only.state !== "running"
? undefined
: only;
+ const exactFailure =
+ last?.kind === "tool_result" && last.success === false ? last : null;
const hasDetail =
row.blocks.length > 0 ||
row.entries.length > 1 ||
row.codeDiffs.length > 0 ||
- row.reason !== null;
+ row.reason !== null ||
+ exactFailure !== null;
// Body content is whatever the line does not already show: a solo block's
- // line is the card, so every entry is still unrendered; otherwise the line
- // is the last entry and the body carries the ones before it.
- const bodyEntries = soloBlock ? row.entries : row.entries.slice(0, -1);
+ // line is the card, so its tool entries stay represented by the block's own
+ // evidence; otherwise the line is the last entry and the body carries the
+ // ones before it.
+ const bodyEntries = soloBlock ? [] : row.entries.slice(0, -1);
+ const bodyFailures = bodyEntries.filter(
+ (entry) => entry.kind === "tool_result" && entry.success === false,
+ );
+ const bodySteps = bodyEntries.filter(
+ (entry) => entry.kind !== "tool_result" || entry.success !== false,
+ );
// The reason is a body child too: a row whose only detail is its reason
// would otherwise render an empty container and hide the prose entirely.
- const bodyChildren =
- bodyEntries.length +
- (soloBlock ? 0 : row.blocks.length) +
- row.codeDiffs.length +
- (row.reason === null ? 0 : 1);
+ const bodyChildren = soloBlock
+ ? 0
+ : bodyEntries.length +
+ row.blocks.length +
+ row.codeDiffs.length +
+ (row.reason === null ? 0 : 1) +
+ (exactFailure === null ? 0 : 1);
// The collapsed row carries the whole write's delta; per-block identity and
// the patch itself live in the detail. A row folding two writes sums them,
// since one line cannot name both blocks without becoming two.
@@ -1135,10 +1197,10 @@ function FActivityLogRow({
row.reason !== null && reasonShown < row.reason.length;
useFrameTick(open && reasonRevealing);
- // Only a browse row accumulates entries, and only a run row carries blocks,
- // so these two counts can never both apply to one row.
+ // A combined write/test row can carry both entries and blocks; prefer the
+ // step count when there are several tool transitions to summarize.
const foldedSummary =
- row.entries.length > 1
+ row.entries.length > 1 && (last?.attempts ?? 1) <= 1
? `\u00b7 ${row.entries.length} steps`
: row.blocks.length > 0
? `\u00b7 ${row.blocks.length} ${row.blocks.length === 1 ? "block" : "blocks"}`
@@ -1166,25 +1228,90 @@ function FActivityLogRow({
const mark =
soloBlock || !settled
? null
- : last.success === false
- ? "✕"
- : row.kind === "run"
- ? "✓"
- : null;
+ : last.success !== false && row.kind === "run"
+ ? "✓"
+ : null;
+
+ const reasonNode =
+ row.reason === null ? null : (
+ <FSubRow
+ glyph="✦"
+ glyphClass="text-sky-700 dark:text-sky-300"
+ italic
+ muted
+ >
+ <span
+ data-testid="copilot-reason"
+ className={[
+ "break-words [overflow-wrap:anywhere]",
+ // The tail keeps the full string in flow so the row never grows,
+ // while the cap prevents the reveal from moving later evidence.
+ reasonRevealing
+ ? "overflow-hidden [max-height:calc(4*1.55em)]"
+ : "line-clamp-4",
+ ].join(" ")}
+ >
+ {row.reason.slice(0, reasonShown)}
+ <span
+ aria-hidden="true"
+ className={reasonRevealing ? "animate-pulse" : "opacity-0"}
+ >
+ {"\u258c"}
+ </span>
+ <span className="text-transparent">
+ {row.reason.slice(reasonShown)}
+ </span>
+ </span>
+ </FSubRow>
+ );
+ const diffNodes = row.codeDiffs.map((diff) => (
+ <FCodeWriteDiff
+ key={diff.label}
+ diff={diff}
+ open={diffOpen(diff.label)}
+ peek={diffPeek(diff.label)}
+ onToggle={() => onDiffToggle(diff.label)}
+ />
+ ));
+ const rowFailures = row.entries.filter(
+ (entry) => entry.kind === "tool_result" && entry.success === false,
+ );
const lineNode = soloBlock ? (
<FBlockRun
block={soloBlock}
turnEnded={turnEnded}
onSelect={onBlockSelect}
- uxV1={uxV1}
outcomeReasonFallback={outcomeReasonFallback}
rowTitle={row.label}
flat
rowGlyph={kindGlyph}
rowKindWord={kindWord}
rowTrailing={rowElapsed}
+ rowDiffCounts={
+ row.codeDiffs.length === 0
+ ? undefined
+ : { added: rowAdded, removed: rowRemoved }
+ }
expansion={{ open, onToggle }}
+ quietFailure
+ detailBeforeBlock={
+ row.reason !== null || diffNodes.length > 0 ? (
+ <>
+ {reasonNode}
+ {diffNodes}
+ </>
+ ) : undefined
+ }
+ detailAfterBlock={
+ rowFailures.length > 0 ? (
+ <>
+ {rowFailures.map((entry) => (
+ <ActivityRow key={entry.id} entry={entry} />
+ ))}
+ </>
+ ) : undefined
+ }
/>
) : (
<FLogLine
@@ -1220,12 +1347,10 @@ function FActivityLogRow({
</span>
) : null}
{row.codeDiffs.length === 0 ? null : (
- <span className="font-mono tabular-nums">
- <span className="text-muted-foreground dark:text-slate-500">
- {" \u00b7 "}
- </span>
- <span className="text-emerald-700 dark:text-emerald-300">{`+${rowAdded}`}</span>
- <span className="pl-1 text-rose-700 dark:text-rose-300">{`\u2212${rowRemoved}`}</span>
+ <span className="font-mono tabular-nums text-muted-foreground dark:text-slate-500">
+ <span>{" \u00b7 "}</span>
+ <span>{`+${rowAdded}`}</span>
+ <span className="pl-1">{`\u2212${rowRemoved}`}</span>
</span>
)}
</FLogLine>
@@ -1236,49 +1361,9 @@ function FActivityLogRow({
{lineNode}
{open && bodyChildren > 0 ? (
<div className="ml-[28px] flex flex-col gap-1 border-l border-border/60 py-1 pl-3">
- {row.codeDiffs.map((diff) => (
- <FCodeWriteDiff
- key={diff.label}
- diff={diff}
- open={diffOpen(diff.label)}
- onToggle={() => onDiffToggle(diff.label)}
- uxV1={uxV1}
- />
- ))}
- {row.reason === null ? null : (
- <FSubRow
- glyph="✦"
- glyphClass="text-sky-700 dark:text-sky-300"
- italic
- muted
- >
- <span
- data-testid="copilot-reason"
- className={[
- "break-words [overflow-wrap:anywhere]",
- // The tail keeps the full string in flow so the row never
- // grows, but that also makes the clamp paint its ellipsis on
- // line four from the first frame — stranded in the
- // transparent region while the reveal is still on line one.
- reasonRevealing
- ? "overflow-hidden [max-height:calc(4*1.55em)]"
- : "line-clamp-4",
- ].join(" ")}
- >
- {row.reason.slice(0, reasonShown)}
- <span
- aria-hidden="true"
- className={reasonRevealing ? "animate-pulse" : "opacity-0"}
- >
- {"\u258c"}
- </span>
- <span className="text-transparent">
- {row.reason.slice(reasonShown)}
- </span>
- </span>
- </FSubRow>
- )}
- {bodyEntries.map((entry) => (
+ {reasonNode}
+ {diffNodes}
+ {bodySteps.map((entry) => (
<ActivityRow key={entry.id} entry={entry} />
))}
{(soloBlock ? [] : row.blocks).map((b) => (
@@ -1287,29 +1372,26 @@ function FActivityLogRow({
block={b}
turnEnded={turnEnded}
onSelect={onBlockSelect}
- uxV1={uxV1}
outcomeReasonFallback={outcomeReasonFallback}
flat
+ quietFailure
/>
))}
+ {bodyFailures.map((entry) => (
+ <ActivityRow key={entry.id} entry={entry} />
+ ))}
+ {exactFailure === null ? null : <ActivityRow entry={exactFailure} />}
</div>
) : null}
</div>
);
}
-interface FActivityLogProps {
- turn: TurnNarrativeState;
- turnEnded: boolean;
- onBlockSelect?: (label: string) => void;
- uxV1?: boolean;
-}
-
function FActivityLog({
turn,
turnEnded,
onBlockSelect,
- uxV1,
+ interactionRef,
}: FActivityLogProps) {
const outcomeReasonFallback = notConfirmedDisplayReason(turn);
const { rows, focusIndex } = useMemo(() => deriveActivityLog(turn), [turn]);
@@ -1318,37 +1400,88 @@ function FActivityLog({
const [override, setOverride] = useState<ReadonlyMap<string, boolean>>(
() => new Map(),
);
- const toggle = useCallback((id: string, open: boolean) => {
- setOverride((prev) => new Map(prev).set(id, !open));
- }, []);
- // Every write's patch stays open for the rest of the turn rather than closing when a
- // newer write lands: a patch that vanishes mid-read is worse than a longer log. At Done
- // they all collapse to their counts, with the body behind `view diff`.
- const writeDiffsOpen = !turnEnded;
+ const logRef = useRef<HTMLDivElement>(null);
+ const ownInteractionRef = useRef<string | null>(null);
+ const lastInteractedRow = interactionRef ?? ownInteractionRef;
+ useEffect(() => {
+ const rowId = lastInteractedRow.current;
+ setOverride(new Map());
+ if (!turnEnded || rowId === null) return;
+ const timer = window.setTimeout(() => {
+ const row = Array.from(
+ logRef.current?.querySelectorAll<HTMLElement>(
+ "[data-activity-row-id]",
+ ) ?? [],
+ ).find((candidate) => candidate.dataset.activityRowId === rowId);
+ row?.querySelector<HTMLButtonElement>("button")?.focus();
+ lastInteractedRow.current = null;
+ }, 0);
+ return () => window.clearTimeout(timer);
+ }, [lastInteractedRow, turn.turnId, turnEnded]);
+ const toggle = useCallback(
+ (id: string, open: boolean) => {
+ lastInteractedRow.current = id;
+ setOverride((prev) => new Map(prev).set(id, !open));
+ },
+ [lastInteractedRow],
+ );
+ const toggleDiff = useCallback(
+ (rowId: string, label: string, open: boolean) => {
+ lastInteractedRow.current = rowId;
+ setOverride((prev) => {
+ const next = new Map(prev);
+ next.set(`diff:${rowId}:${label}`, !open);
+ // Expanding evidence is also an explicit request to keep its parent
+ // visible when the automatic frontier advances.
+ if (!open) next.set(rowId, true);
+ return next;
+ });
+ },
+ [lastInteractedRow],
+ );
+
+ if (!turnEnded && rows.length === 0) {
+ return <InstantAckPlaceholder />;
+ }
return (
- <div className="flex flex-col gap-1.5">
+ <div ref={logRef} className="flex flex-col gap-1.5">
{rows.map((row, i) => {
- const showsWriteDiff = writeDiffsOpen && row.codeDiffs.length > 0;
- const open =
- override.get(row.id) ?? (i === focusIndex || showsWriteDiff);
+ const focused = i === focusIndex;
+ const rowOverride = override.get(row.id);
+ const autoFocused = rowOverride === undefined && focused;
+ const open = rowOverride ?? focused;
const diffOpen = (label: string) =>
- override.get(`diff:${row.id}:${label}`) ?? showsWriteDiff;
+ override.get(`diff:${row.id}:${label}`) ?? false;
+ const diffPeek = (label: string) =>
+ autoFocused &&
+ !diffOpen(label) &&
+ row.codeDiffs.some(
+ (candidate) =>
+ candidate.label === label && candidate.patch !== undefined,
+ );
return (
- <FActivityLogRow
+ <div
key={row.id}
- row={row}
- open={open}
- onToggle={() => toggle(row.id, open)}
- diffOpen={diffOpen}
- onDiffToggle={(label) =>
- toggle(`diff:${row.id}:${label}`, diffOpen(label))
- }
- turnEnded={turnEnded}
- onBlockSelect={onBlockSelect}
- uxV1={uxV1}
- outcomeReasonFallback={outcomeReasonFallback}
- />
+ data-activity-row-id={row.id}
+ onFocusCapture={() => {
+ lastInteractedRow.current = row.id;
+ }}
+ >
+ <FActivityLogRow
+ row={row}
+ open={open}
+ onToggle={() => toggle(row.id, open)}
+ diffOpen={diffOpen}
+ diffPeek={diffPeek}
+ onDiffToggle={(label) =>
+ toggleDiff(row.id, label, diffOpen(label))
+ }
+ turnEnded={turnEnded}
+ onBlockSelect={onBlockSelect}
+ outcomeReasonFallback={outcomeReasonFallback}
+ />
+ </div>
);
})}
</div>
@@ -1373,9 +1506,18 @@ interface TurnHeadProps {
expanded: boolean;
onClick?: () => void;
subtitle?: ReactNode;
+ buttonRef?: Ref<HTMLButtonElement>;
+ controlsId?: string;
}
-function TurnHead({ summary, expanded, onClick, subtitle }: TurnHeadProps) {
+function TurnHead({
+ summary,
+ expanded,
+ onClick,
+ subtitle,
+ buttonRef,
+ controlsId,
+}: TurnHeadProps) {
const expandable = Boolean(onClick);
const headClass = "flex w-full items-start gap-3 px-3.5 py-3 text-left";
const body = (
@@ -1420,9 +1562,11 @@ function TurnHead({ summary, expanded, onClick, subtitle }: TurnHeadProps) {
return (
<button
+ ref={buttonRef}
type="button"
onClick={onClick}
aria-expanded={expanded}
+ aria-controls={controlsId}
className={headClass}
>
{body}
@@ -1435,7 +1579,8 @@ interface RollupCardProps {
summary: TurnSummary;
onExpand: () => void;
onBlockSelect?: (label: string) => void;
- uxV1?: boolean;
+ activityInteractionRef?: { current: string | null };
+ headerRef?: Ref<HTMLButtonElement>;
}
function RollupCard({
@@ -1443,7 +1588,8 @@ function RollupCard({
summary,
onExpand,
onBlockSelect,
- uxV1,
+ activityInteractionRef,
+ headerRef,
}: RollupCardProps) {
// The backend appends the judge's verdict to the closing message, so it needs the
// same display-layer rewrite the outcome reason gets.
@@ -1472,7 +1618,7 @@ function RollupCard({
const completed = rollupBlocks.filter((b) => isBlockOk(b));
const failed = rollupBlocks.filter((b) => b.state === "failed");
const stopped = rollupBlocks.filter((b) => b.state === "stopped");
- const showChecklist = Boolean(uxV1) && showPhaseChecklist(turn);
+ const showChecklist = showPhaseChecklist(turn);
// The log holds every block, but a non-solo run row renders its cards in the
// body, which is collapsed once the turn ends — so the log names a block on
// screen only in the one-block case. These lists stay until a run row carries
@@ -1493,6 +1639,8 @@ function RollupCard({
summary={summary}
expanded={false}
onClick={hasExpandableDetail ? onExpand : undefined}
+ buttonRef={headerRef}
+ controlsId={undefined}
subtitle={
subtitle ? (
<div
@@ -1515,7 +1663,7 @@ function RollupCard({
turn={turn}
turnEnded
onBlockSelect={onBlockSelect}
- uxV1={uxV1}
+ interactionRef={activityInteractionRef}
/>
</div>
) : null}
@@ -1540,14 +1688,10 @@ function RollupCard({
{palette.glyph}
</span>
<span
- className={
- uxV1
- ? "text-[11px] text-muted-foreground"
- : "font-mono text-[11px] text-muted-foreground"
- }
- title={uxV1 ? b.label : undefined}
+ className="text-[11px] text-muted-foreground"
+ title={b.label}
>
- {uxV1 ? humanizeBlockLabel(b.label) : b.label}
+ {humanizeBlockLabel(b.label)}
</span>
<span className="text-slate-600">·</span>
<span className="text-[11.5px] text-foreground dark:text-slate-200">
@@ -1578,14 +1722,10 @@ function RollupCard({
✕
</span>
<span
- className={
- uxV1
- ? "text-[11px] text-rose-700 dark:text-rose-300/80"
- : "font-mono text-[11px] text-rose-700 dark:text-rose-300/80"
- }
- title={uxV1 ? b.label : undefined}
+ className="text-[11px] text-rose-700 dark:text-rose-300/80"
+ title={b.label}
>
- {uxV1 ? humanizeBlockLabel(b.label) : b.label}
+ {humanizeBlockLabel(b.label)}
</span>
</li>
))}
@@ -1611,14 +1751,10 @@ function RollupCard({
■
</span>
<span
- className={
- uxV1
- ? "text-[11px] text-muted-foreground"
- : "font-mono text-[11px] text-muted-foreground"
- }
- title={uxV1 ? b.label : undefined}
+ className="text-[11px] text-muted-foreground"
+ title={b.label}
>
- {uxV1 ? humanizeBlockLabel(b.label) : b.label}
+ {humanizeBlockLabel(b.label)}
</span>
</li>
))}
@@ -1633,16 +1769,20 @@ interface DetailViewProps {
turn: TurnNarrativeState;
onCollapse: (() => void) | null;
onBlockSelect?: (label: string) => void;
- uxV1?: boolean;
workingRowActive?: boolean;
+ activityInteractionRef?: { current: string | null };
+ collapseRef?: Ref<HTMLButtonElement>;
+ detailsId?: string;
}
function DetailView({
turn,
onCollapse,
onBlockSelect,
- uxV1,
workingRowActive,
+ activityInteractionRef,
+ collapseRef,
+ detailsId,
}: DetailViewProps) {
const collapsedOutcomeReason = notConfirmedDisplayReason(turn);
const hasBlocks = turn.blocks.length > 0;
@@ -1654,7 +1794,7 @@ function DetailView({
// long design phase isn't silently invisible.
const hasDraft = (turn.draft?.blockCount ?? 0) > 0;
const showDesign = designStarted && (hasDraft || hasBlocks || !turn.terminal);
- const showChecklist = Boolean(uxV1) && showPhaseChecklist(turn);
+ const showChecklist = showPhaseChecklist(turn);
const preBlockNarration = turn.designActivity.filter(
(e) => e.kind === "narration",
);
@@ -1663,9 +1803,12 @@ function DetailView({
<div className="flex flex-col gap-2.5">
{onCollapse ? (
<button
+ ref={collapseRef}
type="button"
onClick={onCollapse}
aria-label="Collapse turn"
+ aria-expanded={true}
+ aria-controls={detailsId}
className="flex w-full items-center justify-end gap-1.5 px-3.5 py-1.5 text-[11px] font-medium uppercase tracking-wide text-muted-foreground hover:text-tertiary-foreground dark:text-slate-500"
>
<span>Collapse</span>
@@ -1675,58 +1818,57 @@ function DetailView({
</button>
) : null}
- {showChecklist ? (
- <>
- {turn.terminal === null ? <FWorkingHeader /> : null}
+ <div id={detailsId} className="flex flex-col gap-2.5">
+ {showChecklist ? (
<FActivityLog
key={turn.turnId ?? ""}
turn={turn}
turnEnded={turn.terminal !== null}
onBlockSelect={onBlockSelect}
- uxV1={uxV1}
+ interactionRef={activityInteractionRef}
/>
- </>
- ) : showDesign ? (
- <FDesignRow
- done={!designOpen}
- blockLabels={turn.draft?.blockLabels ?? []}
- activity={turn.designActivity}
- uxV1={uxV1}
- />
- ) : preBlockNarration.length > 0 ? (
- preBlockNarration.map((e) => (
- <FProse key={e.id} text={e.text} muted italic />
- ))
- ) : null}
+ ) : showDesign ? (
+ <FDesignRow
+ done={!designOpen}
+ blockLabels={turn.draft?.blockLabels ?? []}
+ activity={turn.designActivity}
+ />
+ ) : preBlockNarration.length > 0 ? (
+ preBlockNarration.map((e) => (
+ <FProse key={e.id} text={e.text} muted italic />
+ ))
+ ) : null}
- {!showChecklist && hasBlocks ? (
- <div className="flex flex-col gap-1">
- {turn.blocks.map((b) => (
- <FBlockRun
- key={b.workflowRunBlockId || b.label}
- block={b}
- turnEnded={turn.terminal !== null}
- onSelect={onBlockSelect}
- uxV1={uxV1}
- outcomeReasonFallback={collapsedOutcomeReason}
- />
- ))}
- </div>
- ) : null}
+ {!showChecklist && hasBlocks ? (
+ <div className="flex flex-col gap-1">
+ {turn.blocks.map((b) => (
+ <FBlockRun
+ key={b.workflowRunBlockId || b.label}
+ block={b}
+ turnEnded={turn.terminal !== null}
+ onSelect={onBlockSelect}
+ outcomeReasonFallback={collapsedOutcomeReason}
+ />
+ ))}
+ </div>
+ ) : null}
- {!hasBlocks && !designStarted && !turn.terminal && !workingRowActive ? (
- <div className="pl-9 text-[12px] italic text-muted-foreground dark:text-slate-500">
- Working…
- </div>
- ) : null}
+ {!hasBlocks && !designStarted && !turn.terminal && !workingRowActive ? (
+ <div className="pl-9 text-[12px] italic text-muted-foreground dark:text-slate-500">
+ Working…
+ </div>
+ ) : null}
- {turn.terminal && (turn.narrativeSummary || turn.terminalMessage) ? (
- <div className="whitespace-pre-wrap pl-9 pr-8 text-[13px] leading-[1.55] text-foreground dark:text-slate-200">
- {humanizeJudgeText(
- turn.narrativeSummary?.trim() || turn.terminalMessage?.trim() || "",
- )}
- </div>
- ) : null}
+ {turn.terminal && (turn.narrativeSummary || turn.terminalMessage) ? (
+ <div className="whitespace-pre-wrap pl-9 pr-8 text-[13px] leading-[1.55] text-foreground dark:text-slate-200">
+ {humanizeJudgeText(
+ turn.narrativeSummary?.trim() ||
+ turn.terminalMessage?.trim() ||
+ "",
+ )}
+ </div>
+ ) : null}
+ </div>
</div>
);
}
@@ -1734,33 +1876,46 @@ function DetailView({
interface NarrativeViewProps {
turn: TurnNarrativeState;
onBlockSelect?: (blockLabel: string) => void;
- uxV1?: boolean;
workingRowActive?: boolean;
}
export function NarrativeView({
turn,
onBlockSelect,
- uxV1,
workingRowActive,
}: NarrativeViewProps) {
- const summary = useMemo(
- () => computeTurnSummary(turn, { uxV1 }),
- [turn, uxV1],
- );
+ const summary = useMemo(() => computeTurnSummary(turn), [turn]);
const isInFlight = turn.terminal === null;
const isComplete = !isInFlight;
const [userRolled, setUserRolled] = useState<boolean | null>(null);
+ const activityInteractionRef = useRef<string | null>(null);
const rolled = userRolled === null ? isComplete : userRolled;
+ const rollupButtonRef = useRef<HTMLButtonElement>(null);
+ const collapseButtonRef = useRef<HTMLButtonElement>(null);
+ const pendingTurnFocus = useRef<"rollup" | "detail" | null>(null);
+ const detailsId = `copilot-turn-${turn.turnId ?? turn.turnIndex}-details`;
+ useEffect(() => {
+ if (pendingTurnFocus.current === "rollup") {
+ rollupButtonRef.current?.focus();
+ } else if (pendingTurnFocus.current === "detail") {
+ collapseButtonRef.current?.focus();
+ }
+ pendingTurnFocus.current = null;
+ }, [rolled]);
if (rolled && isComplete) {
return (
<RollupCard
turn={turn}
summary={summary}
- onExpand={() => setUserRolled(false)}
+ onExpand={() => {
+ activityInteractionRef.current = null;
+ pendingTurnFocus.current = "detail";
+ setUserRolled(false);
+ }}
onBlockSelect={onBlockSelect}
- uxV1={uxV1}
+ activityInteractionRef={activityInteractionRef}
+ headerRef={rollupButtonRef}
/>
);
}
@@ -1768,10 +1923,20 @@ export function NarrativeView({
return (
<DetailView
turn={turn}
- onCollapse={isComplete ? () => setUserRolled(true) : null}
+ onCollapse={
+ isComplete
+ ? () => {
+ activityInteractionRef.current = null;
+ pendingTurnFocus.current = "rollup";
+ setUserRolled(true);
+ }
+ : null
+ }
onBlockSelect={onBlockSelect}
- uxV1={uxV1}
workingRowActive={workingRowActive}
+ activityInteractionRef={activityInteractionRef}
+ collapseRef={collapseButtonRef}
+ detailsId={detailsId}
/>
);
}
diff --git a/skyvern-frontend/src/routes/workflows/copilot/NarrativeView.workingLine.test.tsx b/skyvern-frontend/src/routes/workflows/copilot/NarrativeView.workingLine.test.tsx
index 2740716a4..030313a83 100644
--- a/skyvern-frontend/src/routes/workflows/copilot/NarrativeView.workingLine.test.tsx
+++ b/skyvern-frontend/src/routes/workflows/copilot/NarrativeView.workingLine.test.tsx
@@ -10,6 +10,7 @@ const exploringTurn = (): TurnNarrativeState => ({
...EMPTY_NARRATIVE,
turnId: "turn-1",
turnIndex: 0,
+ designStarted: true,
});
afterEach(() => {
@@ -17,13 +18,13 @@ afterEach(() => {
});
describe("NarrativeView — transcript working line", () => {
- it("keeps the line when the composer's verb row is not showing", () => {
- render(<NarrativeView turn={exploringTurn()} uxV1 />);
- expect(screen.getByText("Working…")).toBeTruthy();
- });
+ it("replaces the active-turn working header with the acknowledgement", () => {
+ render(<NarrativeView turn={exploringTurn()} />);
- it("drops the line once the composer's verb row carries the state", () => {
- render(<NarrativeView turn={exploringTurn()} uxV1 workingRowActive />);
expect(screen.queryByText("Working…")).toBeNull();
+ expect(screen.queryByText("· building your workflow")).toBeNull();
+ expect(screen.getByRole("status").textContent).toContain(
+ "Copilot is working on your request…",
+ );
});
});
diff --git a/skyvern-frontend/src/routes/workflows/copilot/WorkflowCopilotChat.blockActions.test.tsx b/skyvern-frontend/src/routes/workflows/copilot/WorkflowCopilotChat.blockActions.test.tsx
index c8ec4bc18..b248bcf78 100644
--- a/skyvern-frontend/src/routes/workflows/copilot/WorkflowCopilotChat.blockActions.test.tsx
+++ b/skyvern-frontend/src/routes/workflows/copilot/WorkflowCopilotChat.blockActions.test.tsx
@@ -21,14 +21,6 @@ type StreamCall = {
reject: (error: unknown) => void;
};
-const { mockCopilotUxV1Enabled } = vi.hoisted(() => ({
- mockCopilotUxV1Enabled: vi.fn(),
-}));
-
-vi.mock("posthog-js/react", () => ({
- useFeatureFlagEnabled: () => mockCopilotUxV1Enabled(),
-}));
-
const {
streamCalls,
postStreaming,
@@ -246,8 +238,6 @@ beforeEach(() => {
releaseStudioRun.mockClear();
HTMLElement.prototype.scrollIntoView = vi.fn();
HTMLElement.prototype.scrollTo = vi.fn();
- mockCopilotUxV1Enabled.mockReset();
- mockCopilotUxV1Enabled.mockReturnValue(true);
streamCalls.length = 0;
postStreaming.mockClear();
cancelPost.mockClear();
@@ -365,24 +355,6 @@ describe("WorkflowCopilotChat — recorded-action live poll wiring", () => {
expect(timelineGet).not.toHaveBeenCalled();
});
- it("never fetches the run timeline when copilot_ux_v1 is off", async () => {
- mockCopilotUxV1Enabled.mockReturnValue(false);
- await renderChat();
- await submit("build a workflow");
-
- // Cover every entry point: the early poll start, the evaluating fallback,
- // and the terminal convergence fetch must all stay inert flag-off.
- streamCalls[0]!.onMessage(blockProgressFrame({ workflow_run_id: "wr_1" }));
- streamCalls[0]!.onMessage(runOutcomeFrame({ verdict: "evaluating" }));
- streamCalls[0]!.onMessage(runOutcomeFrame({ verdict: "demonstrated" }));
-
- // The terminal fetch is async (awaits getClient), so flush pending
- // microtasks before asserting it never fired — a synchronous assert would
- // pass even if the guard were missing.
- await new Promise((resolve) => setTimeout(resolve, 0));
- expect(timelineGet).not.toHaveBeenCalled();
- });
-
it("renders the recorded actions once the timeline fetch resolves", async () => {
timelineGet.mockResolvedValue({
data: [
@@ -551,8 +523,8 @@ describe("WorkflowCopilotChat — recorded-action live poll wiring", () => {
fireEvent.click(
within(statusRegion).getByRole("button", { expanded: false }),
);
- // uxV1 is on by default in this file, so the row's primary text is the
- // humanized label ("block_1" -> "Block 1"), not the raw block label.
+ // The row's primary text is the humanized label ("block_1" -> "Block 1"),
+ // not the raw block label.
fireEvent.click(within(statusRegion).getByText("Block 1"));
await waitFor(() => expect(screen.getByText("Wobble Gizmo")).toBeTruthy());
diff --git a/skyvern-frontend/src/routes/workflows/copilot/WorkflowCopilotChat.composerControls.test.tsx b/skyvern-frontend/src/routes/workflows/copilot/WorkflowCopilotChat.composerControls.test.tsx
index fcf5ba3d0..a42c8638a 100644
--- a/skyvern-frontend/src/routes/workflows/copilot/WorkflowCopilotChat.composerControls.test.tsx
+++ b/skyvern-frontend/src/routes/workflows/copilot/WorkflowCopilotChat.composerControls.test.tsx
@@ -26,12 +26,10 @@ type StreamCall = {
reject: (error: unknown) => void;
};
-const { mockCopilotUxV1Enabled } = vi.hoisted(() => ({
- mockCopilotUxV1Enabled: vi.fn(() => true),
-}));
-
vi.mock("posthog-js/react", () => ({
- useFeatureFlagEnabled: () => mockCopilotUxV1Enabled(),
+ useFeatureFlagEnabled: () => {
+ throw new Error("WorkflowCopilotChat must not consult PostHog");
+ },
}));
const { streamCalls, postStreaming, cancelPost, historyResponse } = vi.hoisted(
@@ -185,8 +183,6 @@ async function submit(value: string) {
beforeEach(() => {
HTMLElement.prototype.scrollIntoView = vi.fn();
HTMLElement.prototype.scrollTo = vi.fn();
- mockCopilotUxV1Enabled.mockReset();
- mockCopilotUxV1Enabled.mockReturnValue(true);
streamCalls.length = 0;
postStreaming.mockClear();
cancelPost.mockClear();
@@ -202,7 +198,7 @@ afterEach(() => {
cleanup();
});
-describe("WorkflowCopilotChat — S4 composer, copilot_ux_v1 on", () => {
+describe("WorkflowCopilotChat — unflagged S4 composer", () => {
it("defaults straight to Build with code when code-first is accessible", async () => {
await renderChat({ copilotV2: true, codeBlockMode: true });
await submit("build me a workflow");
@@ -385,43 +381,3 @@ describe("WorkflowCopilotChat — S4 composer, copilot_ux_v1 on", () => {
).toBeTruthy();
});
});
-
-describe("WorkflowCopilotChat — S4 composer, copilot_ux_v1 off (parity)", () => {
- it("keeps the legacy plain status line for a live-browser queue, with no bubble footer or chip", async () => {
- mockCopilotUxV1Enabled.mockReturnValue(false);
- await renderChat({
- copilotV2: true,
- codeBlockMode: true,
- requiresLiveBrowser: true,
- isLiveBrowserReady: false,
- });
- await submit("build me a workflow");
-
- expect(postStreaming).not.toHaveBeenCalled();
- // Same wording, but via the legacy aria-live status line — the S4
- // chip and the new bubble footer are both flag-gated on uxV1.
- expect(
- screen.getByText("Prompt queued. Waiting for live browser..."),
- ).toBeTruthy();
- expect(screen.queryByText("Queued")).toBeNull();
- expect(
- screen.queryByRole("button", { name: "Edit queued message" }),
- ).toBeNull();
- });
-
- it("keeps the legacy flat row: bordered textarea, legacy placeholder, mic before the input", async () => {
- mockCopilotUxV1Enabled.mockReturnValue(false);
- await renderChat({ copilotV2: true, codeBlockMode: true });
- const ta = textarea();
- const mic = screen.getByRole("button", { name: "Dictate message" });
-
- expect(ta.getAttribute("placeholder")).toBe(
- "Message Skyvern Copilot, or paste recorded steps…",
- );
- expect(ta.className).toContain("border-input");
- // Legacy layout: the mic sits before the textarea, outside any embedded container.
- expect(
- ta.compareDocumentPosition(mic) & Node.DOCUMENT_POSITION_PRECEDING,
- ).toBeTruthy();
- });
-});
diff --git a/skyvern-frontend/src/routes/workflows/copilot/WorkflowCopilotChat.composerMode.test.tsx b/skyvern-frontend/src/routes/workflows/copilot/WorkflowCopilotChat.composerMode.test.tsx
index 649cef056..1d0af75fe 100644
--- a/skyvern-frontend/src/routes/workflows/copilot/WorkflowCopilotChat.composerMode.test.tsx
+++ b/skyvern-frontend/src/routes/workflows/copilot/WorkflowCopilotChat.composerMode.test.tsx
@@ -94,13 +94,6 @@ vi.mock("react-router-dom", async (importOriginal) => {
};
});
-// This suite exercises the legacy (copilot_ux_v1 off) default-mode logic; no
-// test here touches copilot_ux_v1-gated behavior, so pin it off rather than
-// the stray `true` this file previously carried over from SKY-11973's mock.
-vi.mock("posthog-js/react", () => ({
- useFeatureFlagEnabled: () => false,
-}));
-
const saveData = {
title: "Test WF",
workflow: {
@@ -167,9 +160,7 @@ async function renderChat(flags: FlagConfig) {
</FeatureFlagValueContext.Provider>
</FeatureFlagContext.Provider>,
);
- await waitFor(() =>
- expect(screen.getByPlaceholderText(/Message Skyvern Copilot/)).toBeTruthy(),
- );
+ await waitFor(() => expect(screen.getByRole("textbox")).toBeTruthy());
return view;
}
@@ -184,7 +175,7 @@ async function submit(value: string) {
});
}
-async function selectMode(label: "Ask" | "Build" | "Build workflow as code") {
+async function selectMode(label: "Ask" | "Build" | "Build with code") {
await act(async () => {
fireEvent.pointerDown(screen.getByRole("button", { name: "Switch mode" }), {
button: 0,
@@ -215,61 +206,32 @@ afterEach(() => {
cleanup();
});
-describe("WorkflowCopilotChat — composer default mode variant", () => {
- it("leaves code_block unset for backend fallback when the default variant is unset", async () => {
+describe("WorkflowCopilotChat — unflagged composer default", () => {
+ it("defaults to Build with code when code-first is accessible", async () => {
await renderChat({ copilotV2: true, codeBlockMode: true });
await submit("build me a workflow");
await waitFor(() => expect(postStreaming).toHaveBeenCalledTimes(1));
- expect(streamCalls[0]?.body.mode).toBe("build");
- expect(streamCalls[0]?.body.code_block).toBe(null);
- });
-
- it("sends code_block=true for the build_code override variant", async () => {
- await renderChat({
- copilotV2: true,
- codeBlockMode: true,
- defaultMode: "build_code",
- });
- await submit("build me a workflow");
- await waitFor(() => expect(postStreaming).toHaveBeenCalledTimes(1));
-
expect(streamCalls[0]?.body.mode).toBe("build");
expect(streamCalls[0]?.body.code_block).toBe(true);
});
- it("sends code_block=false for the build_no_code variant", async () => {
+ it("ignores the retired default-mode variant", async () => {
await renderChat({
copilotV2: true,
codeBlockMode: true,
- defaultMode: "build_no_code",
+ defaultMode: "ask",
});
await submit("build me a workflow");
await waitFor(() => expect(postStreaming).toHaveBeenCalledTimes(1));
expect(streamCalls[0]?.body.mode).toBe("build");
- expect(streamCalls[0]?.body.code_block).toBe(false);
- });
-
- it("defaults to Ask for the ask variant and sends code_block=null", async () => {
- await renderChat({
- copilotV2: true,
- codeBlockMode: true,
- defaultMode: "ask",
- });
- await submit("answer a question");
- await waitFor(() => expect(postStreaming).toHaveBeenCalledTimes(1));
-
- expect(streamCalls[0]?.body.mode).toBe("ask");
- expect(streamCalls[0]?.body.code_block).toBe(null);
+ expect(streamCalls[0]?.body.code_block).toBe(true);
});
- it("defaults to Ask for the ask_code variant and sends code_block=null while in Ask", async () => {
- await renderChat({
- copilotV2: true,
- codeBlockMode: true,
- defaultMode: "ask_code",
- });
+ it("sends code_block=null when Ask is selected", async () => {
+ await renderChat({ copilotV2: true, codeBlockMode: true });
+ await selectMode("Ask");
await submit("answer a question");
await waitFor(() => expect(postStreaming).toHaveBeenCalledTimes(1));
@@ -277,13 +239,10 @@ describe("WorkflowCopilotChat — composer default mode variant", () => {
expect(streamCalls[0]?.body.code_block).toBe(null);
});
- it("lands on code ON when selecting Build workflow as code", async () => {
- await renderChat({
- copilotV2: true,
- codeBlockMode: true,
- defaultMode: "ask_code",
- });
- await selectMode("Build workflow as code");
+ it("lands on code ON when selecting Build with code", async () => {
+ await renderChat({ copilotV2: true, codeBlockMode: true });
+ await selectMode("Ask");
+ await selectMode("Build with code");
await submit("build me a workflow");
await waitFor(() => expect(postStreaming).toHaveBeenCalledTimes(1));
@@ -291,12 +250,8 @@ describe("WorkflowCopilotChat — composer default mode variant", () => {
expect(streamCalls[0]?.body.code_block).toBe(true);
});
- it("turns code OFF when selecting plain Build from a code default", async () => {
- await renderChat({
- copilotV2: true,
- codeBlockMode: true,
- defaultMode: "build_code",
- });
+ it("turns code OFF when selecting plain Build", async () => {
+ await renderChat({ copilotV2: true, codeBlockMode: true });
await selectMode("Build");
await submit("build me a workflow");
await waitFor(() => expect(postStreaming).toHaveBeenCalledTimes(1));
@@ -305,7 +260,7 @@ describe("WorkflowCopilotChat — composer default mode variant", () => {
expect(streamCalls[0]?.body.code_block).toBe(false);
});
- it("sends code_block=null when the code-block flag is off, ignoring the variant", async () => {
+ it("sends code_block=null when code-first is inaccessible", async () => {
await renderChat({
copilotV2: true,
codeBlockMode: false,
diff --git a/skyvern-frontend/src/routes/workflows/copilot/WorkflowCopilotChat.confirmCard.test.tsx b/skyvern-frontend/src/routes/workflows/copilot/WorkflowCopilotChat.confirmCard.test.tsx
index 4f766e0fe..df29ba28b 100644
--- a/skyvern-frontend/src/routes/workflows/copilot/WorkflowCopilotChat.confirmCard.test.tsx
+++ b/skyvern-frontend/src/routes/workflows/copilot/WorkflowCopilotChat.confirmCard.test.tsx
@@ -25,14 +25,6 @@ type StreamCall = {
reject: (error: unknown) => void;
};
-const { mockCopilotUxV1Enabled } = vi.hoisted(() => ({
- mockCopilotUxV1Enabled: vi.fn(() => true),
-}));
-
-vi.mock("posthog-js/react", () => ({
- useFeatureFlagEnabled: () => mockCopilotUxV1Enabled(),
-}));
-
const { streamCalls, postStreaming, cancelPost, historyResponse } = vi.hoisted(
() => {
const calls: StreamCall[] = [];
@@ -200,8 +192,6 @@ function diagnoseNarrativePayload(message: string) {
beforeEach(() => {
HTMLElement.prototype.scrollIntoView = vi.fn();
HTMLElement.prototype.scrollTo = vi.fn();
- mockCopilotUxV1Enabled.mockReset();
- mockCopilotUxV1Enabled.mockReturnValue(true);
streamCalls.length = 0;
postStreaming.mockClear();
cancelPost.mockClear();
@@ -281,12 +271,4 @@ describe("WorkflowCopilotChat — Confirm chip (SKY-12137)", () => {
expect(screen.queryByRole("button", { name: "Confirm" })).toBeNull();
});
-
- it("does not render when the flag is off", async () => {
- mockCopilotUxV1Enabled.mockReturnValue(false);
- await renderChat();
- await sendConfirmNote();
-
- expect(screen.queryByRole("button", { name: "Confirm" })).toBeNull();
- });
});
diff --git a/skyvern-frontend/src/routes/workflows/copilot/WorkflowCopilotChat.credentialCard.test.tsx b/skyvern-frontend/src/routes/workflows/copilot/WorkflowCopilotChat.credentialCard.test.tsx
index 3f3a2a7dd..eebd59918 100644
--- a/skyvern-frontend/src/routes/workflows/copilot/WorkflowCopilotChat.credentialCard.test.tsx
+++ b/skyvern-frontend/src/routes/workflows/copilot/WorkflowCopilotChat.credentialCard.test.tsx
@@ -9,8 +9,6 @@ import {
} from "@testing-library/react";
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
-import { COPILOT_UX_V1_FLAG } from "@/util/featureFlags";
-
import type { WorkflowCopilotCredentialRequiredUpdate } from "./workflowCopilotTypes";
type StreamBody = {
@@ -37,7 +35,6 @@ const {
modalOverrideType,
modalDefaultTestUrl,
toastFn,
- flagMap,
} = vi.hoisted(() => {
const calls: StreamCall[] = [];
const streaming = vi.fn(
@@ -97,7 +94,6 @@ const {
modalOverrideType: { current: undefined as string | undefined },
modalDefaultTestUrl: { current: undefined as string | undefined },
toastFn: vi.fn(),
- flagMap: { current: {} as Record<string, boolean> },
};
});
@@ -236,10 +232,6 @@ vi.mock("react-router-dom", async (importOriginal) => {
};
});
-vi.mock("posthog-js/react", () => ({
- useFeatureFlagEnabled: (flag: string) => flagMap.current[flag] ?? false,
-}));
-
const saveData = {
title: "Test WF",
workflow: {
@@ -452,7 +444,6 @@ beforeEach(() => {
credsFail.current = false;
modalOverrideType.current = undefined;
modalDefaultTestUrl.current = undefined;
- flagMap.current = {};
historyResponse.data = {
workflow_copilot_chat_id: "chat-1",
chat_history: [],
@@ -488,16 +479,14 @@ const streamScoutTurn = async () => {
describe("WorkflowCopilotChat — activity log", () => {
it("renders the flat log, not the retired phase rail", async () => {
- flagMap.current = { [COPILOT_UX_V1_FLAG]: true };
await streamScoutTurn();
expect(screen.getByText("Opened the sign-in page")).toBeTruthy();
expect(screen.queryByText("Explore site")).toBeNull();
});
});
-describe("WorkflowCopilotChat — credential card wiring (flag on)", () => {
+describe("WorkflowCopilotChat — credential card wiring", () => {
it("sends supports_credential_pause on the request", async () => {
- flagMap.current = { [COPILOT_UX_V1_FLAG]: true };
await renderChat();
await submit("build me a workflow");
await waitFor(() => expect(postStreaming).toHaveBeenCalledTimes(1));
@@ -505,7 +494,6 @@ describe("WorkflowCopilotChat — credential card wiring (flag on)", () => {
});
it("renders the inline-pause card when a credential_required frame arrives", async () => {
- flagMap.current = { [COPILOT_UX_V1_FLAG]: true };
await renderChat();
await submit("build me a workflow");
await waitFor(() => expect(postStreaming).toHaveBeenCalledTimes(1));
@@ -522,7 +510,6 @@ describe("WorkflowCopilotChat — credential card wiring (flag on)", () => {
});
it("skip POSTs a credential-response with action skip", async () => {
- flagMap.current = { [COPILOT_UX_V1_FLAG]: true };
await renderChat();
await submit("build me a workflow");
await waitFor(() => expect(postStreaming).toHaveBeenCalledTimes(1));
@@ -543,7 +530,6 @@ describe("WorkflowCopilotChat — credential card wiring (flag on)", () => {
});
it("connect with an existing matched credential POSTs the credential_id", async () => {
- flagMap.current = { [COPILOT_UX_V1_FLAG]: true };
credentialsData.current = [
{
credential_id: "cred-hn",
@@ -598,7 +584,6 @@ describe("WorkflowCopilotChat — credential card wiring (flag on)", () => {
});
it("connect CTA opens the modal, then a created credential POSTs connected", async () => {
- flagMap.current = { [COPILOT_UX_V1_FLAG]: true };
await renderChat();
await submit("build me a workflow");
await waitFor(() => expect(postStreaming).toHaveBeenCalledTimes(1));
@@ -627,7 +612,6 @@ describe("WorkflowCopilotChat — credential card wiring (flag on)", () => {
});
it("shows the full org credential list on a pause ask (not just the frame's candidates) and answers via the typed POST", async () => {
- flagMap.current = { [COPILOT_UX_V1_FLAG]: true };
credentialsData.current = [
{ credential_id: "cred-abc", name: "abc", tested_url: null },
{ credential_id: "cred-spare", name: "spare-portal", tested_url: null },
@@ -665,7 +649,6 @@ describe("WorkflowCopilotChat — credential card wiring (flag on)", () => {
});
it("keeps the card actionable, toasts, and never logs the raw error (resume_token leak) when the resume POST fails", async () => {
- flagMap.current = { [COPILOT_UX_V1_FLAG]: true };
const errSpy = vi.spyOn(console, "error").mockImplementation(() => {});
// AxiosError-shaped: config.data carries the one-time resume_token.
sansApiPost.mockRejectedValueOnce(
@@ -698,7 +681,6 @@ describe("WorkflowCopilotChat — credential card wiring (flag on)", () => {
});
it("degrades a pause ask to the Connect-credential CTA when the credentials fetch fails", async () => {
- flagMap.current = { [COPILOT_UX_V1_FLAG]: true };
const errSpy = vi.spyOn(console, "error").mockImplementation(() => {});
credsFail.current = true;
await renderChat();
@@ -721,7 +703,6 @@ describe("WorkflowCopilotChat — credential card wiring (flag on)", () => {
});
it("renders no card when the pause resolved to declined (frame never shown)", async () => {
- flagMap.current = { [COPILOT_UX_V1_FLAG]: true };
await renderChat();
await submit("use my saved login");
await waitFor(() => expect(postStreaming).toHaveBeenCalledTimes(1));
@@ -737,7 +718,6 @@ describe("WorkflowCopilotChat — credential card wiring (flag on)", () => {
});
it("terminal-mode connect/skip never hits the network", async () => {
- flagMap.current = { [COPILOT_UX_V1_FLAG]: true };
await renderChat();
await submit("who am I signing in as?");
await waitFor(() => expect(postStreaming).toHaveBeenCalledTimes(1));
@@ -756,7 +736,6 @@ describe("WorkflowCopilotChat — credential card wiring (flag on)", () => {
});
it("clears the pause card on a terminal error — no dead actionable card", async () => {
- flagMap.current = { [COPILOT_UX_V1_FLAG]: true };
await renderChat();
await submit("build me a workflow");
await waitFor(() => expect(postStreaming).toHaveBeenCalledTimes(1));
@@ -778,7 +757,6 @@ describe("WorkflowCopilotChat — credential card wiring (flag on)", () => {
});
it("terminal connect via the modal auto-continues once and morphs the receipt", async () => {
- flagMap.current = { [COPILOT_UX_V1_FLAG]: true };
await renderChat();
await submit("who am I signing in as?");
await waitFor(() => expect(postStreaming).toHaveBeenCalledTimes(1));
@@ -808,7 +786,6 @@ describe("WorkflowCopilotChat — credential card wiring (flag on)", () => {
});
it("fetches the org credentials on a terminal ask and offers the picker", async () => {
- flagMap.current = { [COPILOT_UX_V1_FLAG]: true };
credentialsData.current = [
{ credential_id: "cred_hn", name: "HN login", tested_url: null },
];
@@ -831,7 +808,6 @@ describe("WorkflowCopilotChat — credential card wiring (flag on)", () => {
});
it("restores the terminal picker when the auto-continue send fails", async () => {
- flagMap.current = { [COPILOT_UX_V1_FLAG]: true };
credentialsData.current = [
{ credential_id: "cred_hn", name: "HN login", tested_url: null },
];
@@ -874,7 +850,6 @@ describe("WorkflowCopilotChat — credential card wiring (flag on)", () => {
});
it("restores the terminal picker when the auto-continue is cancelled", async () => {
- flagMap.current = { [COPILOT_UX_V1_FLAG]: true };
credentialsData.current = [
{ credential_id: "cred_hn", name: "HN login", tested_url: null },
];
@@ -906,7 +881,6 @@ describe("WorkflowCopilotChat — credential card wiring (flag on)", () => {
});
it("hides a stale terminal ask once it is no longer the last message", async () => {
- flagMap.current = { [COPILOT_UX_V1_FLAG]: true };
await renderChat();
await submit("who am I signing in as?");
await waitFor(() => expect(postStreaming).toHaveBeenCalledTimes(1));
@@ -929,7 +903,6 @@ describe("WorkflowCopilotChat — credential card wiring (flag on)", () => {
});
it("does not auto-continue while a turn is still in flight", async () => {
- flagMap.current = { [COPILOT_UX_V1_FLAG]: true };
await renderChat();
await submit("who am I signing in as?");
await waitFor(() => expect(postStreaming).toHaveBeenCalledTimes(1));
@@ -955,7 +928,6 @@ describe("WorkflowCopilotChat — credential card wiring (flag on)", () => {
});
it("passes the pause frame's login URL to the modal as defaultTestUrl", async () => {
- flagMap.current = { [COPILOT_UX_V1_FLAG]: true };
await renderChat();
await submit("build me a workflow");
await waitFor(() => expect(postStreaming).toHaveBeenCalledTimes(1));
@@ -975,7 +947,6 @@ describe("WorkflowCopilotChat — credential card wiring (flag on)", () => {
});
it("passes no defaultTestUrl for a terminal card (frame carries no URL)", async () => {
- flagMap.current = { [COPILOT_UX_V1_FLAG]: true };
await renderChat();
await submit("who am I signing in as?");
await waitFor(() => expect(postStreaming).toHaveBeenCalledTimes(1));
@@ -994,7 +965,6 @@ describe("WorkflowCopilotChat — credential card wiring (flag on)", () => {
});
it("renders the auto-bind receipt from the credentialAutoBound signal", async () => {
- flagMap.current = { [COPILOT_UX_V1_FLAG]: true };
await renderChat();
await submit("sign in and grab my dashboard");
await waitFor(() => expect(postStreaming).toHaveBeenCalledTimes(1));
@@ -1009,7 +979,6 @@ describe("WorkflowCopilotChat — credential card wiring (flag on)", () => {
});
it("Change re-picks through the existing terminal-continue path (no third path)", async () => {
- flagMap.current = { [COPILOT_UX_V1_FLAG]: true };
credentialsData.current = [
{ credential_id: "cred_work", name: "Work login", tested_url: null },
{
@@ -1050,7 +1019,6 @@ describe("WorkflowCopilotChat — credential card wiring (flag on)", () => {
});
it("defers the auto-bind receipt to a co-occurring credential ask", async () => {
- flagMap.current = { [COPILOT_UX_V1_FLAG]: true };
await renderChat();
await submit("sign in to both sites");
await waitFor(() => expect(postStreaming).toHaveBeenCalledTimes(1));
@@ -1075,34 +1043,6 @@ describe("WorkflowCopilotChat — credential card wiring (flag on)", () => {
});
});
-describe("WorkflowCopilotChat — credential card (flag off parity)", () => {
- it("omits supports_credential_pause and renders no card even if a frame arrives", async () => {
- await renderChat();
- await submit("build me a workflow");
- await waitFor(() => expect(postStreaming).toHaveBeenCalledTimes(1));
- expect(streamCalls[0]!.body.supports_credential_pause).toBeUndefined();
- await act(async () => {
- streamCalls[0]!.onMessage(turnStart());
- streamCalls[0]!.onMessage(credentialFrame());
- });
- expect(
- screen.queryByRole("button", { name: "Connect credential" }),
- ).toBeNull();
- });
-
- it("renders no auto-bind receipt with the flag off", async () => {
- await renderChat();
- await submit("sign in and grab my dashboard");
- await waitFor(() => expect(postStreaming).toHaveBeenCalledTimes(1));
- await act(async () => {
- streamCalls[0]!.onMessage(turnStart("turn-9"));
- streamCalls[0]!.onMessage(terminalAutoBoundResponse("turn-9"));
- streamCalls[0]!.resolve();
- });
- expect(screen.queryByText(/Using credential/)).toBeNull();
- });
-});
-
describe("WorkflowCopilotChat — auto-bound receipt chronology", () => {
const autoBoundResponse = (
turnId: string,
@@ -1160,7 +1100,6 @@ describe("WorkflowCopilotChat — auto-bound receipt chronology", () => {
}
it("keeps a repeated live receipt on the first turn", async () => {
- flagMap.current = { [COPILOT_UX_V1_FLAG]: true };
await renderChat();
await completeAutoBoundTurn(0, "turn-chronology-1", "First turn complete.");
await completeAutoBoundTurn(
@@ -1186,7 +1125,6 @@ describe("WorkflowCopilotChat — auto-bound receipt chronology", () => {
});
it("keeps the surviving scrollback receipt read-only", async () => {
- flagMap.current = { [COPILOT_UX_V1_FLAG]: true };
await renderChat();
await completeAutoBoundTurn(0, "turn-readonly-1", "First turn complete.");
expect(await screen.findByRole("button", { name: "Change" })).toBeTruthy();
@@ -1198,7 +1136,6 @@ describe("WorkflowCopilotChat — auto-bound receipt chronology", () => {
});
it("hydrates one receipt at the first persisted position", async () => {
- flagMap.current = { [COPILOT_UX_V1_FLAG]: true };
historyResponse.data.chat_history = [
historyMessage("turn-history-1", 0, "First persisted turn."),
historyMessage("turn-history-2", 1, "Second persisted turn."),
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 fb2a647ce..7b9678fd7 100644
--- a/skyvern-frontend/src/routes/workflows/copilot/WorkflowCopilotChat.historyRace.test.tsx
+++ b/skyvern-frontend/src/routes/workflows/copilot/WorkflowCopilotChat.historyRace.test.tsx
@@ -12,7 +12,6 @@ import {
FeatureFlagContext,
FeatureFlagValueContext,
} from "@/hooks/useFeatureFlag";
-import { COPILOT_UX_V1_FLAG } from "@/util/featureFlags";
type HistoryData = {
workflow_copilot_chat_id: string | null;
@@ -23,14 +22,14 @@ type HistoryData = {
// Only chat-history GETs are deferred (held here so a test controls
// isLoadingHistory); every other GET resolves immediately.
-const { postStreaming, cancelPost, historyQueue, flagMap, boolFlags } =
- vi.hoisted(() => ({
+const { postStreaming, cancelPost, historyQueue, boolFlags } = vi.hoisted(
+ () => ({
postStreaming: vi.fn(() => new Promise<void>(() => {})),
cancelPost: vi.fn().mockResolvedValue({}),
historyQueue: [] as Array<(resp: { data: HistoryData }) => void>,
- flagMap: { current: {} as Record<string, boolean> },
boolFlags: { current: {} as Record<string, boolean> },
- }));
+ }),
+);
vi.mock("@/api/sse", () => ({
getSseClient: vi.fn().mockResolvedValue({ postStreaming }),
@@ -76,10 +75,6 @@ vi.mock("react-router-dom", async (importOriginal) => {
};
});
-vi.mock("posthog-js/react", () => ({
- useFeatureFlagEnabled: (flag: string) => flagMap.current[flag] ?? false,
-}));
-
vi.mock("@/store/WorkflowHasChangesStore", () => ({
useWorkflowHasChangesStore: () => ({
getSaveData: () => ({
@@ -226,7 +221,6 @@ beforeEach(() => {
cancelPost.mockClear();
cancelPost.mockResolvedValue({});
historyQueue.length = 0;
- flagMap.current = {};
boolFlags.current = {};
});
@@ -238,8 +232,7 @@ afterEach(() => {
// Item 1 (SKY-12384): during a chat-history SWITCH, a prior chat's action card
// must not stay actionable — its action would post into the OUTGOING chat.
describe("WorkflowCopilotChat — history-race action-card gating (item 1)", () => {
- it("hides the review gate's Accept while a chat switch is loading (flag-on)", async () => {
- flagMap.current = { [COPILOT_UX_V1_FLAG]: true };
+ it("hides the review gate's Accept while a chat switch is loading", async () => {
await renderChat();
await flushHistory(
historyData({
@@ -267,8 +260,7 @@ describe("WorkflowCopilotChat — history-race action-card gating (item 1)", ()
await flushHistory(historyData({ workflow_copilot_chat_id: "chat_other" }));
});
- it("hides the Confirm chip while a chat switch is loading (flag-on)", async () => {
- flagMap.current = { [COPILOT_UX_V1_FLAG]: true };
+ it("hides the Confirm chip while a chat switch is loading", async () => {
await renderChat();
await flushHistory(
historyData({
@@ -302,7 +294,6 @@ describe("WorkflowCopilotChat — history-race action-card gating (item 1)", ()
// load must keep one owner — footer while the bubble exists, else the chip.
describe("WorkflowCopilotChat — queued prompt survives initial history load (item 2)", () => {
it("keeps the queued status + Cancel visible after the history load lands", async () => {
- flagMap.current = { [COPILOT_UX_V1_FLAG]: true };
boolFlags.current = { ENABLE_WORKFLOW_COPILOT_V2: true };
await renderChat({ requiresLiveBrowser: true, isLiveBrowserReady: false });
diff --git a/skyvern-frontend/src/routes/workflows/copilot/WorkflowCopilotChat.instantAck.test.tsx b/skyvern-frontend/src/routes/workflows/copilot/WorkflowCopilotChat.instantAck.test.tsx
index 223d9e175..1586af907 100644
--- a/skyvern-frontend/src/routes/workflows/copilot/WorkflowCopilotChat.instantAck.test.tsx
+++ b/skyvern-frontend/src/routes/workflows/copilot/WorkflowCopilotChat.instantAck.test.tsx
@@ -31,7 +31,6 @@ const {
historyResponse,
routeParams,
workflowRunQueryMock,
- mockFeatureFlagEnabled,
} = vi.hoisted(() => {
const calls: StreamCall[] = [];
const post = vi.fn().mockResolvedValue({});
@@ -66,14 +65,9 @@ const {
historyResponse: history,
routeParams: params,
workflowRunQueryMock: vi.fn(),
- mockFeatureFlagEnabled: vi.fn().mockReturnValue(true),
};
});
-vi.mock("posthog-js/react", () => ({
- useFeatureFlagEnabled: mockFeatureFlagEnabled,
-}));
-
vi.mock("@/api/sse", () => ({
getSseClient: vi.fn().mockResolvedValue({ postStreaming }),
}));
@@ -243,7 +237,6 @@ beforeEach(() => {
};
workflowRunQueryMock.mockReset();
workflowRunQueryMock.mockReturnValue({ data: undefined });
- mockFeatureFlagEnabled.mockReturnValue(true);
});
afterEach(() => {
@@ -278,14 +271,6 @@ describe("WorkflowCopilotChat — instant acknowledgement", () => {
expect(screen.getAllByRole("status")).toHaveLength(1);
});
- it("REGRESSION: never renders when copilot_ux_v1 is off", async () => {
- mockFeatureFlagEnabled.mockReturnValue(false);
- await renderChat();
- await submit("build a workflow");
-
- expectNoAckLines();
- });
-
it("REGRESSION: an Ask reply clears the placeholder when the turn completes", async () => {
await renderChat();
await submit("what does this workflow do?");
diff --git a/skyvern-frontend/src/routes/workflows/copilot/WorkflowCopilotChat.queue.test.tsx b/skyvern-frontend/src/routes/workflows/copilot/WorkflowCopilotChat.queue.test.tsx
index e52e076c4..23a646288 100644
--- a/skyvern-frontend/src/routes/workflows/copilot/WorkflowCopilotChat.queue.test.tsx
+++ b/skyvern-frontend/src/routes/workflows/copilot/WorkflowCopilotChat.queue.test.tsx
@@ -26,57 +26,50 @@ type StreamCall = {
resolve: () => void;
reject: (error: unknown) => void;
};
-const {
- streamCalls,
- postStreaming,
- cancelPost,
- historyResponse,
- speechState,
- copilotUxV1Enabled,
-} = vi.hoisted(() => {
- const calls: StreamCall[] = [];
- const post = vi.fn().mockResolvedValue({});
- const streaming = vi.fn(
- (
- _path: string,
- body: { message: string },
- onMessage: (payload: unknown) => boolean,
- ) =>
- new Promise<void>((resolve, reject) => {
- calls.push({ body, onMessage, resolve, reject });
- }),
- );
- const history = {
- data: {
- workflow_copilot_chat_id: null as string | null,
- chat_history: [] as {
- sender: "user" | "ai";
- content: string;
- created_at: string;
- narrative_payload?: Record<string, unknown> | null;
- }[],
- proposed_workflow: null as Record<string, unknown> | null,
- auto_accept: false,
- },
- };
- const speech = {
- isSupported: false,
- isListening: false,
- isHearingSpeech: false,
- start: vi.fn(),
- stop: vi.fn<() => Promise<Blob | null>>().mockResolvedValue(null),
- toggle: vi.fn(),
- takeAudioBlob: vi.fn<() => Blob | null>().mockReturnValue(null),
- };
- return {
- streamCalls: calls,
- postStreaming: streaming,
- cancelPost: post,
- historyResponse: history,
- speechState: speech,
- copilotUxV1Enabled: { value: false },
- };
-});
+const { streamCalls, postStreaming, cancelPost, historyResponse, speechState } =
+ vi.hoisted(() => {
+ const calls: StreamCall[] = [];
+ const post = vi.fn().mockResolvedValue({});
+ const streaming = vi.fn(
+ (
+ _path: string,
+ body: { message: string },
+ onMessage: (payload: unknown) => boolean,
+ ) =>
+ new Promise<void>((resolve, reject) => {
+ calls.push({ body, onMessage, resolve, reject });
+ }),
+ );
+ const history = {
+ data: {
+ workflow_copilot_chat_id: null as string | null,
+ chat_history: [] as {
+ sender: "user" | "ai";
+ content: string;
+ created_at: string;
+ narrative_payload?: Record<string, unknown> | null;
+ }[],
+ proposed_workflow: null as Record<string, unknown> | null,
+ auto_accept: false,
+ },
+ };
+ const speech = {
+ isSupported: false,
+ isListening: false,
+ isHearingSpeech: false,
+ start: vi.fn(),
+ stop: vi.fn<() => Promise<Blob | null>>().mockResolvedValue(null),
+ toggle: vi.fn(),
+ takeAudioBlob: vi.fn<() => Blob | null>().mockReturnValue(null),
+ };
+ return {
+ streamCalls: calls,
+ postStreaming: streaming,
+ cancelPost: post,
+ historyResponse: history,
+ speechState: speech,
+ };
+ });
vi.mock("@/api/sse", () => ({
getSseClient: vi.fn().mockResolvedValue({ postStreaming }),
@@ -119,15 +112,6 @@ vi.mock("react-router-dom", async (importOriginal) => {
};
});
-vi.mock("posthog-js/react", () => ({
- // "copilot_ux_v1" stays off by default — this file's fixtures pin today's
- // headline strings, not the disposition-first reorder behind that flag. The
- // mode pill it introduces is the only ask/build control a user can reach
- // mid-turn, so the test that needs one opts in.
- useFeatureFlagEnabled: (flag: string) =>
- flag !== "copilot_ux_v1" || copilotUxV1Enabled.value,
-}));
-
const saveData = {
title: "Test WF",
workflow: {
@@ -246,7 +230,6 @@ function renderChatWithCodeMode() {
// The mode pill is the one ask/build control that stays mounted through an
// in-flight turn. Code-block mode is off so switching mode moves only the mode.
function renderChatWithModePill() {
- copilotUxV1Enabled.value = true;
return renderChatWithFlags(
{
ENABLE_WORKFLOW_COPILOT_V2: true,
@@ -305,7 +288,6 @@ beforeEach(() => {
generatingBlockLabel: null,
cancelNonce: 0,
});
- copilotUxV1Enabled.value = false;
});
afterEach(() => {
@@ -960,7 +942,7 @@ describe("WorkflowCopilotChat — keep the chat live during a turn", () => {
call.resolve();
});
- expect(screen.getByText("Question")).toBeTruthy();
+ expect(screen.getByText("Needs your input")).toBeTruthy();
expect(screen.queryByText("Completed the run")).toBeNull();
});
@@ -997,7 +979,7 @@ describe("WorkflowCopilotChat — keep the chat live during a turn", () => {
call.resolve();
});
- expect(screen.getByText("Question")).toBeTruthy();
+ expect(screen.getByText("Needs your input")).toBeTruthy();
expect(screen.getByText(longInputRequest)).toBeTruthy();
expect(screen.queryByText("Answered")).toBeNull();
expect(screen.queryByText("Completed the run")).toBeNull();
@@ -1216,6 +1198,13 @@ describe("WorkflowCopilotChat — a repeat of the turn's own message is not re-r
it("drains an identical queued prompt when the composer left the code mode the turn opened in", async () => {
await renderChatWithCodeMode();
+ fireEvent.pointerDown(screen.getByRole("button", { name: "Switch mode" }), {
+ button: 0,
+ ctrlKey: false,
+ });
+ await act(async () => {
+ fireEvent.click(screen.getByLabelText("Build"));
+ });
await submit("build me a workflow");
await waitFor(() => expect(postStreaming).toHaveBeenCalledTimes(1));
expect(
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 65145c0e4..dfee08197 100644
--- a/skyvern-frontend/src/routes/workflows/copilot/WorkflowCopilotChat.reviewGate.test.tsx
+++ b/skyvern-frontend/src/routes/workflows/copilot/WorkflowCopilotChat.reviewGate.test.tsx
@@ -8,8 +8,6 @@ import {
} from "@testing-library/react";
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
-import { COPILOT_UX_V1_FLAG } from "@/util/featureFlags";
-
import type { WorkflowCopilotStreamResponseUpdate } from "./workflowCopilotTypes";
type StreamBody = {
@@ -23,44 +21,37 @@ type StreamCall = {
reject: (error: unknown) => void;
};
-const {
- streamCalls,
- postStreaming,
- cancelPost,
- historyGet,
- historyResponse,
- flagMap,
-} = vi.hoisted(() => {
- const calls: StreamCall[] = [];
- const post = vi.fn().mockResolvedValue({});
- const streaming = vi.fn(
- (
- _path: string,
- body: StreamBody,
- onMessage: (payload: unknown) => boolean,
- ) =>
- new Promise<void>((resolve, reject) => {
- calls.push({ body, onMessage, resolve, reject });
- }),
- );
- const history = {
- data: {
- workflow_copilot_chat_id: "chat-1" as string | null,
- chat_history: [] as unknown[],
- proposed_workflow: null as Record<string, unknown> | null,
- auto_accept: false,
- },
- };
- const get = vi.fn().mockImplementation(() => Promise.resolve(history));
- return {
- streamCalls: calls,
- postStreaming: streaming,
- cancelPost: post,
- historyGet: get,
- historyResponse: history,
- flagMap: { current: {} as Record<string, boolean> },
- };
-});
+const { streamCalls, postStreaming, cancelPost, historyGet, historyResponse } =
+ vi.hoisted(() => {
+ const calls: StreamCall[] = [];
+ const post = vi.fn().mockResolvedValue({});
+ const streaming = vi.fn(
+ (
+ _path: string,
+ body: StreamBody,
+ onMessage: (payload: unknown) => boolean,
+ ) =>
+ new Promise<void>((resolve, reject) => {
+ calls.push({ body, onMessage, resolve, reject });
+ }),
+ );
+ const history = {
+ data: {
+ workflow_copilot_chat_id: "chat-1" as string | null,
+ chat_history: [] as unknown[],
+ proposed_workflow: null as Record<string, unknown> | null,
+ auto_accept: false,
+ },
+ };
+ const get = vi.fn().mockImplementation(() => Promise.resolve(history));
+ return {
+ streamCalls: calls,
+ postStreaming: streaming,
+ cancelPost: post,
+ historyGet: get,
+ historyResponse: history,
+ };
+ });
vi.mock("@/api/sse", () => ({
getSseClient: vi.fn().mockResolvedValue({ postStreaming }),
@@ -99,10 +90,6 @@ vi.mock("react-router-dom", async (importOriginal) => {
};
});
-vi.mock("posthog-js/react", () => ({
- useFeatureFlagEnabled: (flag: string) => flagMap.current[flag] ?? false,
-}));
-
const saveData = {
title: "Test WF",
workflow: {
@@ -300,7 +287,6 @@ beforeEach(() => {
cancelPost.mockClear();
cancelPost.mockResolvedValue({});
historyGet.mockClear();
- flagMap.current = {};
historyResponse.data = {
workflow_copilot_chat_id: "chat-1",
chat_history: [],
@@ -313,9 +299,8 @@ afterEach(() => {
cleanup();
});
-describe("WorkflowCopilotChat — g2 review gate (flag-on, SKY-12136)", () => {
+describe("WorkflowCopilotChat — g2 review gate", () => {
it("does not send keep_pending_proposal on a chat's first message (nothing pending yet)", async () => {
- flagMap.current = { [COPILOT_UX_V1_FLAG]: true };
await renderChat();
await submit("build me a workflow");
@@ -325,7 +310,6 @@ describe("WorkflowCopilotChat — g2 review gate (flag-on, SKY-12136)", () => {
});
it("restores an actionable gate via the chip after a bypassed proposal (old code: buttons vanish forever)", async () => {
- flagMap.current = { [COPILOT_UX_V1_FLAG]: true };
await renderChat();
await submit("build me a workflow");
@@ -383,7 +367,6 @@ describe("WorkflowCopilotChat — g2 review gate (flag-on, SKY-12136)", () => {
});
it("shows the Untested pill on hydration of an old payload lacking proposalDisposition", async () => {
- flagMap.current = { [COPILOT_UX_V1_FLAG]: true };
historyResponse.data.proposed_workflow = proposedWorkflowPayload({
_copilot_unvalidated: true,
});
@@ -403,7 +386,6 @@ describe("WorkflowCopilotChat — g2 review gate (flag-on, SKY-12136)", () => {
});
it("renders a legacy (no-narrative) pending turn as pill + footer, no changes body", async () => {
- flagMap.current = { [COPILOT_UX_V1_FLAG]: true };
historyResponse.data.proposed_workflow = proposedWorkflowPayload({
_copilot_unvalidated: true,
});
@@ -430,7 +412,6 @@ describe("WorkflowCopilotChat — g2 review gate (flag-on, SKY-12136)", () => {
});
it("clears a stale pending gate when a later turn is auto-applied (stale Accept can't reapply over the newer canvas)", async () => {
- flagMap.current = { [COPILOT_UX_V1_FLAG]: true };
await renderChat();
await submit("build me a workflow");
@@ -471,7 +452,6 @@ describe("WorkflowCopilotChat — g2 review gate (flag-on, SKY-12136)", () => {
});
it("shows the gate live on a narrative-less turn, not only after a reload (SKY-14099)", async () => {
- flagMap.current = { [COPILOT_UX_V1_FLAG]: true };
await renderChat();
await submit("rename the blocks.");
@@ -490,7 +470,6 @@ describe("WorkflowCopilotChat — g2 review gate (flag-on, SKY-12136)", () => {
});
it("clears the proposal and shows a discarded receipt on a late Reject", async () => {
- flagMap.current = { [COPILOT_UX_V1_FLAG]: true };
await renderChat();
await submit("build me a workflow");
@@ -519,45 +498,3 @@ describe("WorkflowCopilotChat — g2 review gate (flag-on, SKY-12136)", () => {
expect(screen.queryByRole("button", { name: "Reject" })).toBeNull();
});
});
-
-describe("WorkflowCopilotChat — flag-off parity (SKY-12136)", () => {
- it("renders today's two green pills + Review + solid Reject with no chip, and never sends keep_pending_proposal", async () => {
- await renderChat({ docked: true });
-
- await submit("build me a workflow");
- await waitFor(() => expect(postStreaming).toHaveBeenCalledTimes(1));
- await act(async () => {
- streamCalls[0]!.onMessage(proposalResponse("Draft ready."));
- streamCalls[0]!.resolve();
- });
-
- expect(screen.getByRole("button", { name: "Accept" })).toBeTruthy();
- expect(screen.getByRole("button", { name: "Always accept" })).toBeTruthy();
- expect(screen.getByRole("button", { name: "Review" })).toBeTruthy();
- expect(screen.getByRole("button", { name: "Reject" })).toBeTruthy();
- expect(screen.queryByText(/proposal pending/)).toBeNull();
- expect(screen.queryByText("Untested")).toBeNull();
- expect(streamCalls[0]!.body.keep_pending_proposal).toBe(false);
-
- // docked -> today's DiffCard also renders alongside the raw button row.
- expect(screen.getByText("Proposed changes")).toBeTruthy();
- });
-
- it("nulls the proposal on the next send, matching today's orphaning behavior", async () => {
- await renderChat();
-
- await submit("build me a workflow");
- await waitFor(() => expect(postStreaming).toHaveBeenCalledTimes(1));
- await act(async () => {
- streamCalls[0]!.onMessage(proposalResponse("Draft ready."));
- streamCalls[0]!.resolve();
- });
- expect(screen.getByRole("button", { name: "Accept" })).toBeTruthy();
-
- await submit("also grab the story scores");
- await waitFor(() => expect(postStreaming).toHaveBeenCalledTimes(2));
-
- expect(streamCalls[1]!.body.keep_pending_proposal).toBe(false);
- expect(screen.queryByRole("button", { name: "Accept" })).toBeNull();
- });
-});
diff --git a/skyvern-frontend/src/routes/workflows/copilot/WorkflowCopilotChat.runLifecycle.test.tsx b/skyvern-frontend/src/routes/workflows/copilot/WorkflowCopilotChat.runLifecycle.test.tsx
index 030a1dc81..dc45f33f5 100644
--- a/skyvern-frontend/src/routes/workflows/copilot/WorkflowCopilotChat.runLifecycle.test.tsx
+++ b/skyvern-frontend/src/routes/workflows/copilot/WorkflowCopilotChat.runLifecycle.test.tsx
@@ -31,7 +31,6 @@ const {
historyResponse,
routeParams,
workflowRunQueryMock,
- mockFeatureFlagEnabled,
} = vi.hoisted(() => {
const calls: StreamCall[] = [];
const post = vi.fn().mockResolvedValue({});
@@ -66,14 +65,9 @@ const {
historyResponse: history,
routeParams: params,
workflowRunQueryMock: vi.fn(),
- mockFeatureFlagEnabled: vi.fn().mockReturnValue(true),
};
});
-vi.mock("posthog-js/react", () => ({
- useFeatureFlagEnabled: mockFeatureFlagEnabled,
-}));
-
vi.mock("@/api/sse", () => ({
getSseClient: vi.fn().mockResolvedValue({ postStreaming }),
}));
@@ -239,7 +233,6 @@ beforeEach(() => {
};
workflowRunQueryMock.mockReset();
workflowRunQueryMock.mockReturnValue({ data: undefined });
- mockFeatureFlagEnabled.mockReturnValue(true);
});
afterEach(() => {
@@ -333,36 +326,6 @@ describe("WorkflowCopilotChat — run lifecycle lines", () => {
}
});
- it("renders no lifecycle line when copilot_ux_v1 is off, even for a docked chat with a live run", async () => {
- mockFeatureFlagEnabled.mockReturnValue(false);
- workflowRunQueryMock.mockReturnValue({ data: makeRun() });
- const props = makeDockedProps({ workflowRunId: "wr_1" });
- const view = await renderChat(props);
-
- // Give any (incorrect) announcement a chance to land before asserting absence.
- await new Promise((resolve) => setTimeout(resolve, 0));
- expect(screen.queryByText(/watching it now/)).toBeNull();
-
- workflowRunQueryMock.mockReturnValue({
- data: makeRun({
- status: Status.Completed,
- started_at: "2026-01-01T00:00:00Z",
- finished_at: "2026-01-01T00:00:42Z",
- }),
- });
- view.rerender(chatUi(props));
-
- await new Promise((resolve) => setTimeout(resolve, 0));
- expect(screen.queryByText(/Run completed in/)).toBeNull();
-
- // Flag off must genuinely disable the run query, not just hide its output —
- // otherwise a docked-off/flag-off chat still polls the run in the background.
- expect(workflowRunQueryMock.mock.calls.length).toBeGreaterThan(0);
- for (const call of workflowRunQueryMock.mock.calls) {
- expect(call[0]).toEqual({ workflowRunId: undefined, enabled: false });
- }
- });
-
it("New chat wipes a rendered lifecycle line", async () => {
workflowRunQueryMock.mockReturnValue({ data: makeRun() });
await renderChat(makeDockedProps({ workflowRunId: "wr_1" }));
diff --git a/skyvern-frontend/src/routes/workflows/copilot/WorkflowCopilotChat.tsx b/skyvern-frontend/src/routes/workflows/copilot/WorkflowCopilotChat.tsx
index a18d7a88f..937ef3669 100644
--- a/skyvern-frontend/src/routes/workflows/copilot/WorkflowCopilotChat.tsx
+++ b/skyvern-frontend/src/routes/workflows/copilot/WorkflowCopilotChat.tsx
@@ -81,7 +81,7 @@ import { useRunLifecycleAnnouncements } from "./useRunLifecycleAnnouncements";
import { ConfirmCard, shouldShowConfirmCard } from "./cards/ConfirmCard";
import { ConnectedAccountChoiceCard } from "./cards/ConnectedAccountChoiceCard";
import { connectedAccountChoiceLabel } from "./cards/connectedAccountChoiceLabel";
-import { DiffCard, shouldShowDiffCard } from "./cards/DiffCard";
+import { shouldShowDiffCard } from "./cards/DiffCard";
import { ReviewGateCard, getReviewGateVerdict } from "./cards/ReviewGateCard";
import { GoogleReconnectCard } from "./cards/GoogleReconnectCard";
import {
@@ -105,8 +105,7 @@ import { computeFollowSignature, useStickToBottom } from "./useStickToBottom";
import { useTurnActivityChange } from "./useTurnActivityChange";
import { useSpeechToTextField } from "@/hooks/useSpeechToTextField";
import { SpeechInputButton } from "@/components/SpeechInputButton";
-import { useFeatureFlag, useFeatureFlagValue } from "@/hooks/useFeatureFlag";
-import { useFeatureFlagEnabled } from "posthog-js/react";
+import { useFeatureFlag } from "@/hooks/useFeatureFlag";
import {
DropdownMenu,
DropdownMenuTrigger,
@@ -114,7 +113,6 @@ import {
DropdownMenuItem,
} from "@/components/ui/dropdown-menu";
import { cn, formatElapsedSeconds } from "@/util/utils";
-import { COPILOT_UX_V1_FLAG } from "@/util/featureFlags";
import { ControlTooltip } from "@/routes/workflows/studio/ControlTooltip";
import {
useReleaseStudioRun,
@@ -188,44 +186,6 @@ function collectTimelineBlockActions(
return out;
}
-type ComposerDefaultVariant =
- | "build"
- | "build_code"
- | "build_no_code"
- | "ask"
- | "ask_code";
-
-function normalizeComposerDefaultVariant(
- variant: string | undefined,
-): ComposerDefaultVariant {
- if (
- variant === "ask" ||
- variant === "ask_code" ||
- variant === "build_code" ||
- variant === "build_no_code"
- ) {
- return variant;
- }
- return "build";
-}
-
-function defaultVariantUsesCode(variant: ComposerDefaultVariant): boolean {
- return variant === "build_code" || variant === "ask_code";
-}
-
-function defaultCodeBlockRequestOverride(
- variant: string | undefined,
-): boolean | null {
- if (variant === "build_code") {
- return true;
- }
- if (variant === "build" || variant === "build_no_code") {
- return false;
- }
- // Ask-only variants, including ask_code, do not send a build request override.
- return null;
-}
-
// Ask's mark is a text dingbat; Build's is a color emoji that ModeGlyph flattens
// to a tone-adaptive monochrome silhouette so both read flat on the dark UI.
const ASK_GLYPH = "\u275D\uFE0E";
@@ -723,42 +683,15 @@ export function WorkflowCopilotChat({
const copilotV2Flag = useFeatureFlag("ENABLE_WORKFLOW_COPILOT_V2");
const codeBlockModeFlag = useFeatureFlag("WORKFLOW_COPILOT_CODE_BLOCK_MODE");
const codeBlockAccessFlag = useFeatureFlag("CODE_BLOCK_ACCESS");
- // Client-side PostHog eval (not the backend-served flags above).
- const copilotUxV1Enabled = useFeatureFlagEnabled(COPILOT_UX_V1_FLAG) ?? false;
const copilotV2Enabled = copilotV2Flag === true;
const codeBlockModeEnabled =
codeBlockModeFlag === true && codeBlockAccessFlag === true;
- const defaultModeVariant = useFeatureFlagValue(
- "WORKFLOW_COPILOT_DEFAULT_MODE",
- );
- // S4: under the campaign flag, default straight to code-first (skipping the
- // WORKFLOW_COPILOT_DEFAULT_MODE A/B variant) whenever code-first is accessible.
const codeFirstAccessible = copilotV2Enabled && codeBlockModeEnabled;
- const s4DefaultVariant: ComposerDefaultVariant = codeFirstAccessible
- ? "build_code"
- : "build";
- // The variant configures the initial default only when both gating flags are on.
- const effectiveDefaultVariant: ComposerDefaultVariant = copilotUxV1Enabled
- ? s4DefaultVariant
- : copilotV2Enabled && codeBlockModeEnabled
- ? normalizeComposerDefaultVariant(defaultModeVariant)
- : "build";
- // codeBlockRequestOverride keys off the same source effectiveDefaultVariant
- // used, not the raw flag value, so the S4 default stays internally consistent.
- const codeOverrideVariantSource = copilotUxV1Enabled
- ? s4DefaultVariant
- : defaultModeVariant;
- const [composerMode, setComposerMode] = useState<"ask" | "build">(() =>
- effectiveDefaultVariant === "ask" || effectiveDefaultVariant === "ask_code"
- ? "ask"
- : "build",
- );
- const [codeWorkflow, setCodeWorkflow] = useState(() =>
- defaultVariantUsesCode(effectiveDefaultVariant),
- );
+ const [composerMode, setComposerMode] = useState<"ask" | "build">("build");
+ const [codeWorkflow, setCodeWorkflow] = useState(codeFirstAccessible);
const [codeBlockRequestOverride, setCodeBlockRequestOverride] = useState<
boolean | null
- >(() => defaultCodeBlockRequestOverride(codeOverrideVariantSource));
+ >(codeFirstAccessible);
// Flags arrive asynchronously from /customer; seed the default once they resolve, never again.
const composerSeededRef = useRef(false);
const flagsResolved =
@@ -770,30 +703,15 @@ export function WorkflowCopilotChat({
return;
}
composerSeededRef.current = true;
- setComposerMode(
- effectiveDefaultVariant === "ask" ||
- effectiveDefaultVariant === "ask_code"
- ? "ask"
- : "build",
- );
- setCodeWorkflow(defaultVariantUsesCode(effectiveDefaultVariant));
- setCodeBlockRequestOverride(
- defaultCodeBlockRequestOverride(codeOverrideVariantSource),
- );
- }, [
- flagsResolved,
- effectiveDefaultVariant,
- defaultModeVariant,
- copilotUxV1Enabled,
- codeOverrideVariantSource,
- ]);
+ setComposerMode("build");
+ setCodeWorkflow(codeFirstAccessible);
+ setCodeBlockRequestOverride(codeFirstAccessible);
+ }, [codeFirstAccessible, flagsResolved]);
// Build can never be active unless the V2 flag is on.
const isBuild = copilotV2Enabled && composerMode === "build";
- const codeToggleAllowed = effectiveDefaultVariant !== "build_no_code";
// "Build with code" is offered as a third mode in the dropdown rather than a
// separate toggle; the code state only renders on the button while in Build.
- const codeOptionAvailable =
- copilotV2Enabled && codeBlockModeEnabled && codeToggleAllowed;
+ const codeOptionAvailable = copilotV2Enabled && codeBlockModeEnabled;
const codeStateActive = isBuild && codeWorkflow && codeOptionAvailable;
const [messages, setMessages] = useState<ChatMessage[]>([]);
const [proposedWorkflow, setProposedWorkflow] =
@@ -1014,7 +932,7 @@ export function WorkflowCopilotChat({
);
}, []);
useRunLifecycleAnnouncements({
- workflowRunId: docked && copilotUxV1Enabled ? workflowRunId : undefined,
+ workflowRunId: docked ? workflowRunId : undefined,
// isLoading here, not inFlightRef: this hook needs a value React re-runs
// its effect on when the turn ends, which a ref can't do. The one-render
// lag that matters for the double-submit guard above doesn't matter here.
@@ -1030,7 +948,7 @@ export function WorkflowCopilotChat({
// growing set never duplicates rows and the terminal fetch just converges.
const fetchRecordedActions = useCallback(
async (runId: string) => {
- if (!copilotUxV1Enabled || !workflowPermanentId) return;
+ if (!workflowPermanentId) return;
try {
const client = await getClient(credentialGetter);
const response = await client.get<WorkflowRunTimelineItem[]>(
@@ -1068,12 +986,7 @@ export function WorkflowCopilotChat({
console.error("Failed to fetch recorded actions:", error);
}
},
- [
- applyStoredNarrativeEvent,
- copilotUxV1Enabled,
- credentialGetter,
- workflowPermanentId,
- ],
+ [applyStoredNarrativeEvent, credentialGetter, workflowPermanentId],
);
const finalizeRecordedActionsPoll = useCallback((runId: string) => {
const timer = actionPollRef.current.get(runId);
@@ -1091,7 +1004,7 @@ export function WorkflowCopilotChat({
}, []);
const startRecordedActionsPoll = useCallback(
(runId: string | null | undefined) => {
- if (!copilotUxV1Enabled || !runId || !workflowPermanentId) return;
+ if (!runId || !workflowPermanentId) return;
if (
actionPollRef.current.has(runId) ||
finalizedActionRunIds.current.has(runId)
@@ -1114,7 +1027,7 @@ export function WorkflowCopilotChat({
),
);
},
- [copilotUxV1Enabled, fetchRecordedActions, workflowPermanentId],
+ [fetchRecordedActions, workflowPermanentId],
);
const stopAllRecordedActionsPolls = useCallback(() => {
actionPollRef.current.forEach((timer) => clearInterval(timer));
@@ -1122,12 +1035,12 @@ export function WorkflowCopilotChat({
}, []);
const focusTurnRun = useCallback(
(runId: string | null | undefined) => {
- if (!docked || !copilotUxV1Enabled || !runId) return;
+ if (!docked || !runId) return;
if (focusedTurnRunId.current === runId) return;
focusedTurnRunId.current = runId;
switchStudioRun(runId);
},
- [copilotUxV1Enabled, docked, switchStudioRun],
+ [docked, switchStudioRun],
);
const releaseTurnRun = useCallback(
(runId?: string) => {
@@ -1376,7 +1289,6 @@ export function WorkflowCopilotChat({
// guard makes a stale or double-fired timer a no-op.
const DRAFTING_GAP_MS = 8000;
useEffect(() => {
- if (!copilotUxV1Enabled) return;
if (!shouldArmDraftingGapTimer(narrative)) return;
const wait = Math.max(
0,
@@ -1391,7 +1303,7 @@ export function WorkflowCopilotChat({
wait,
);
return () => clearTimeout(t);
- }, [narrative, applyStoredNarrativeEvent, copilotUxV1Enabled]);
+ }, [narrative, applyStoredNarrativeEvent]);
const textareaRef = useRef<HTMLTextAreaElement | null>(null);
const { getSaveData } = useWorkflowHasChangesStore();
const hasInitializedPosition = useRef(false);
@@ -1826,7 +1738,7 @@ export function WorkflowCopilotChat({
);
// A follow-up turn that ends without a new draft no longer nulls a bypassed
- // proposal client-side (flag-on); re-fetch the chat row instead, since the
+ // proposal client-side; re-fetch the chat row instead, since the
// backend (keep_pending_proposal) may have kept it alive server-side.
// useCallback-stable: handleSend depends on it and is itself a dependency
// of other effects, so a churning identity here would cascade into them.
@@ -2187,10 +2099,6 @@ export function WorkflowCopilotChat({
{ id: queuedId, sender: "user", content: candidate },
]);
}
- if (!copilotUxV1Enabled) {
- setProposedWorkflow(null);
- setPendingProposalTurnId(null);
- }
if (messageOverride === undefined) {
setInputValue("");
}
@@ -2228,10 +2136,6 @@ export function WorkflowCopilotChat({
if (!options.queuedMessageId) {
setMessages((prev) => [...prev, userMessage]);
}
- if (!copilotUxV1Enabled) {
- setProposedWorkflow(null);
- setPendingProposalTurnId(null);
- }
const messageContent = candidate;
if (messageOverride === undefined && !options.queuedMessageId) {
setInputValue("");
@@ -2251,14 +2155,12 @@ export function WorkflowCopilotChat({
isBuild && codeBlockModeEnabled ? codeBlockRequestOverride : null,
completedNormally: false,
};
- if (copilotUxV1Enabled) {
- // Clear the prior turn's lingering narrative so the instant-ack placeholder's
- // turnId===null gate holds on every send, and the first frame hands off cleanly.
- // Reset the ref too (it lags setNarrative by a passive effect) so a late
- // prior-turn recorded-actions fetch can't rebase onto the stale narrative.
- narrativeRef.current = EMPTY_NARRATIVE;
- setNarrative(EMPTY_NARRATIVE);
- }
+ // Clear the prior turn's lingering narrative so the instant-ack placeholder's
+ // turnId===null gate holds on every send, and the first frame hands off cleanly.
+ // Reset the ref too (it lags setNarrative by a passive effect) so a late
+ // prior-turn recorded-actions fetch can't rebase onto the stale narrative.
+ narrativeRef.current = EMPTY_NARRATIVE;
+ setNarrative(EMPTY_NARRATIVE);
const abortController = new AbortController();
streamingAbortController.current?.abort();
@@ -2497,7 +2399,7 @@ export function WorkflowCopilotChat({
applyWorkflowUpdate(responseEntry.snapshot);
setProposedWorkflow(null);
setPendingProposalTurnId(null);
- } else if (copilotUxV1Enabled && pendingProposalTurnId) {
+ } else if (pendingProposalTurnId) {
// No new draft this turn, but a bypassed proposal is still
// pending: re-fetch instead of nulling, since the backend (given
// keep_pending_proposal) may have kept it alive for a late Accept.
@@ -2578,11 +2480,8 @@ export function WorkflowCopilotChat({
target_block_label: targetBlockLabel,
product_action: endToEndAction ? "test_end_to_end" : null,
selected_block_label: readSelectedBlockLabel(),
- keep_pending_proposal:
- copilotUxV1Enabled && Boolean(pendingProposalTurnId),
- // Only opt in behind the flag; flag-off omits the field entirely so
- // the request stays byte-identical to legacy.
- ...(copilotUxV1Enabled && { supports_credential_pause: true }),
+ keep_pending_proposal: Boolean(pendingProposalTurnId),
+ supports_credential_pause: true,
} as WorkflowCopilotChatRequest,
(payload) => {
switch (payload.type) {
@@ -2770,7 +2669,6 @@ export function WorkflowCopilotChat({
codeBlockModeEnabled,
codeBlockRequestOverride,
composerMode,
- copilotUxV1Enabled,
copilotV2Enabled,
credentialGetter,
fetchRecordedActions,
@@ -3240,11 +3138,11 @@ export function WorkflowCopilotChat({
// (working reason) or the queued bubble's footer (live_browser reason);
// don't duplicate it as a second status line above the composer.
const browserStatusText = queuedPrompt
- ? copilotUxV1Enabled && copilotV2Enabled
+ ? copilotV2Enabled
? null
: queuedPromptWaitingStatus
: isLoading
- ? copilotUxV1Enabled && copilotV2Enabled
+ ? copilotV2Enabled
? null
: "Copilot is working. Your next send will wait for the next turn."
: isWaitingForLiveBrowser
@@ -3270,9 +3168,7 @@ export function WorkflowCopilotChat({
const hasComposerText = inputValue.trim().length > 0;
// The cycling verb row plus the stop button's orbiting ring carry the
// working state, so the prose status line and the queued chip stand down.
- const showWorkingRow = Boolean(
- copilotUxV1Enabled && copilotV2Enabled && isLoading,
- );
+ const showWorkingRow = Boolean(copilotV2Enabled && isLoading);
// A live_browser-reason queued prompt parks with no active turn to stop, so
// an empty composer's morph button would render as a guaranteed no-op "Send".
// With text typed it does act — it rewrites the parked prompt.
@@ -3347,9 +3243,7 @@ export function WorkflowCopilotChat({
</DropdownMenuItem>
{codeOptionAvailable ? (
<DropdownMenuItem
- aria-label={
- copilotUxV1Enabled ? "Build with code" : "Build workflow as code"
- }
+ aria-label="Build with code"
onSelect={() => {
setComposerMode("build");
setCodeWorkflow(true);
@@ -3362,11 +3256,7 @@ export function WorkflowCopilotChat({
>
<ModeGlyph mode="build" glow />
<span className="flex flex-1 flex-col">
- <span className="text-sm font-medium">
- {copilotUxV1Enabled
- ? "Build with code"
- : "Build workflow as code"}
- </span>
+ <span className="text-sm font-medium">Build with code</span>
<span className="text-xs leading-snug text-muted-foreground">
Build the workflow as code. Faster and more flexible, but may need
extra detail to handle every edge case.
@@ -3524,12 +3414,9 @@ export function WorkflowCopilotChat({
const hasUnconsumedAdjacentMessage =
adjacentMessage !== undefined &&
selectedConnectionId === null;
- const showProposalActions =
- isLastMessage && Boolean(proposedWorkflow);
const showReviewGate =
- copilotUxV1Enabled &&
- (shouldShowDiffCard(message.narrative) ||
- (turnId !== null && turnId === pendingProposalTurnId));
+ shouldShowDiffCard(message.narrative) ||
+ (turnId !== null && turnId === pendingProposalTurnId);
return (
<div
key={message.id}
@@ -3540,7 +3427,6 @@ export function WorkflowCopilotChat({
<NarrativeView
turn={message.narrative}
onBlockSelect={onBlockSelect}
- uxV1={copilotUxV1Enabled}
workingRowActive={showWorkingRow}
/>
{turnId !== null && choices.length > 0 ? (
@@ -3600,60 +3486,8 @@ export function WorkflowCopilotChat({
gateId={turnId ? `copilot-gate-${turnId}` : undefined}
flash={turnId !== null && turnId === gateFlashTurnId}
/>
- ) : !copilotUxV1Enabled ? (
- <>
- {showProposalActions && proposedWorkflow ? (
- <div className="flex flex-wrap gap-2 pl-1">
- <button
- type="button"
- onClick={() =>
- handleReviewWorkflow(proposedWorkflow)
- }
- className="rounded border border-cta/60 bg-cta/10 px-3 py-1 text-xs text-foreground hover:bg-cta/20"
- >
- Review
- </button>
- <button
- type="button"
- onClick={() =>
- handleAcceptWorkflow(proposedWorkflow)
- }
- className="rounded bg-success px-3 py-1 text-xs text-success-foreground hover:bg-success/90"
- >
- Accept
- </button>
- <button
- type="button"
- onClick={() =>
- handleAcceptWorkflow(proposedWorkflow, true)
- }
- className="rounded bg-success px-3 py-1 text-xs text-success-foreground hover:bg-success/80"
- >
- Always accept
- </button>
- <button
- type="button"
- onClick={handleRejectWorkflow}
- className="rounded bg-destructive px-3 py-1 text-xs text-destructive-foreground hover:bg-destructive/90"
- >
- Reject
- </button>
- </div>
- ) : null}
- {docked && shouldShowDiffCard(message.narrative) ? (
- <DiffCard
- pendingProposal={showProposalActions}
- rejected={
- message.narrative.turnId !== null &&
- rejectedTurnIds.has(message.narrative.turnId)
- }
- turn={message.narrative}
- />
- ) : null}
- </>
) : null}
- {copilotUxV1Enabled &&
- !isLoadingHistory &&
+ {!isLoadingHistory &&
isLastMessage &&
shouldShowConfirmCard(message.narrative) ? (
<ConfirmCard
@@ -3665,12 +3499,7 @@ export function WorkflowCopilotChat({
/>
) : null}
{(() => {
- if (
- isLoadingHistory ||
- !copilotUxV1Enabled ||
- turnId === null
- )
- return null;
+ if (isLoadingHistory || turnId === null) return null;
const credFrame = credentialCardFrameFor(
message.narrative,
);
@@ -3719,12 +3548,7 @@ export function WorkflowCopilotChat({
);
})()}
{(() => {
- if (
- isLoadingHistory ||
- !copilotUxV1Enabled ||
- turnId === null
- )
- return null;
+ if (isLoadingHistory || turnId === null) return null;
const autoBound = autoBoundReceiptFor(message);
if (!autoBound || !autoBoundReceiptIndexes.has(index))
return null;
@@ -3769,7 +3593,6 @@ export function WorkflowCopilotChat({
</div>
);
}
- const showProposedPanel = isLastMessage && proposedWorkflow;
const isGateOwnerOrLast =
index === gateIndex && Boolean(proposedWorkflow);
const selectionReceipt = connectedAccountSelectionReceipt(
@@ -3785,7 +3608,6 @@ export function WorkflowCopilotChat({
: message
}
queuedStatus={
- copilotUxV1Enabled &&
copilotV2Enabled &&
queuedPrompt?.reason === "live_browser" &&
queuedPrompt.id === message.id
@@ -3796,7 +3618,7 @@ export function WorkflowCopilotChat({
: null
}
footer={
- copilotUxV1Enabled && isGateOwnerOrLast ? (
+ isGateOwnerOrLast ? (
<ReviewGateCard
pending
verdict={getReviewGateVerdict(
@@ -3820,39 +3642,6 @@ export function WorkflowCopilotChat({
}
onTestEndToEnd={handleTestEndToEnd}
/>
- ) : !copilotUxV1Enabled && showProposedPanel ? (
- <>
- <button
- type="button"
- onClick={() => handleReviewWorkflow(proposedWorkflow)}
- className="rounded border border-cta/60 bg-cta/10 px-3 py-1 text-xs text-foreground hover:bg-cta/20"
- >
- Review
- </button>
- <button
- type="button"
- onClick={() => handleAcceptWorkflow(proposedWorkflow)}
- className="rounded bg-success px-3 py-1 text-xs text-success-foreground hover:bg-success/90"
- >
- Accept
- </button>
- <button
- type="button"
- onClick={() =>
- handleAcceptWorkflow(proposedWorkflow, true)
- }
- className="rounded bg-success px-3 py-1 text-xs text-success-foreground hover:bg-success/80"
- >
- Always accept
- </button>
- <button
- type="button"
- onClick={handleRejectWorkflow}
- className="rounded bg-destructive px-3 py-1 text-xs text-destructive-foreground hover:bg-destructive/90"
- >
- Reject
- </button>
- </>
) : null
}
/>
@@ -3865,10 +3654,7 @@ export function WorkflowCopilotChat({
render. The send-time reset (see handleSend) keeps turnId null on
every send, including queued-then-drained follow-ups.
*/}
- {copilotUxV1Enabled &&
- isLoading &&
- !isLoadingHistory &&
- narrative.turnId === null ? (
+ {isLoading && !isLoadingHistory && narrative.turnId === null ? (
<InstantAckPlaceholder />
) : null}
{/*
@@ -3885,11 +3671,9 @@ export function WorkflowCopilotChat({
<NarrativeView
turn={narrative}
onBlockSelect={onBlockSelect}
- uxV1={copilotUxV1Enabled}
workingRowActive={showWorkingRow}
/>
- {copilotUxV1Enabled &&
- !isLoadingHistory &&
+ {!isLoadingHistory &&
livePauseFrame &&
livePauseFrame.turn_id === narrative.turnId ? (
<CredentialCard
@@ -3937,7 +3721,7 @@ export function WorkflowCopilotChat({
{/* Input */}
<div className="border-t border-border p-3">
- {copilotUxV1Enabled && copilotV2Enabled ? (
+ {copilotV2Enabled ? (
<div className="mb-2">
<DropdownMenu>
<DropdownMenuTrigger asChild>
@@ -3973,8 +3757,7 @@ export function WorkflowCopilotChat({
</DropdownMenu>
</div>
) : null}
- {copilotUxV1Enabled &&
- proposedWorkflow &&
+ {proposedWorkflow &&
pendingProposalTurnId &&
(gateOwnerIndex !== lastTurnIndex || isLoading) ? (
<button
@@ -4006,7 +3789,6 @@ export function WorkflowCopilotChat({
/>
) : null}
{!showWorkingRow &&
- copilotUxV1Enabled &&
copilotV2Enabled &&
queuedPrompt &&
(queuedPrompt.reason === "working" || queuedBubbleOrphaned) ? (
@@ -4039,12 +3821,12 @@ export function WorkflowCopilotChat({
<SelectedBlockChip />
<div
className={
- copilotUxV1Enabled && copilotV2Enabled
+ copilotV2Enabled
? "flex items-end gap-1.5 rounded-lg border border-input bg-slate-elevation2 py-1.5 pl-3 pr-2.5 transition-colors focus-within:border-ring"
: "flex items-end gap-2"
}
>
- {copilotUxV1Enabled && copilotV2Enabled ? null : (
+ {copilotV2Enabled ? null : (
<SpeechInputButton
isSupported={isSpeechSupported}
isListening={isSpeechListening}
@@ -4062,7 +3844,7 @@ export function WorkflowCopilotChat({
? "Type to queue a message…"
: isWaitingForLiveBrowser
? "Type a prompt to send when ready..."
- : copilotUxV1Enabled && copilotV2Enabled
+ : copilotV2Enabled
? "Ask Copilot to build or change your workflow…"
: "Message Skyvern Copilot, or paste recorded steps…"
}
@@ -4071,7 +3853,7 @@ export function WorkflowCopilotChat({
onKeyDown={handleKeyPress}
rows={1}
className={
- copilotUxV1Enabled && copilotV2Enabled
+ copilotV2Enabled
? "min-h-10 flex-1 resize-none border-0 bg-transparent py-2 text-sm leading-6 text-foreground placeholder:truncate placeholder:text-muted-foreground focus:outline-none disabled:cursor-not-allowed disabled:opacity-50"
: "min-h-10 flex-1 resize-none rounded-lg border border-input bg-slate-elevation2 px-3 py-2 text-sm leading-6 text-foreground placeholder:truncate placeholder:text-muted-foreground focus:border-ring focus:outline-none disabled:cursor-not-allowed disabled:opacity-50"
}
@@ -4081,7 +3863,7 @@ export function WorkflowCopilotChat({
overflowY: "hidden",
}}
/>
- {copilotUxV1Enabled && copilotV2Enabled ? (
+ {copilotV2Enabled ? (
<SpeechInputButton
isSupported={isSpeechSupported}
isListening={isSpeechListening}
@@ -4091,7 +3873,7 @@ export function WorkflowCopilotChat({
iconClassName="h-3.5 w-3.5"
/>
) : null}
- {copilotUxV1Enabled && copilotV2Enabled ? (
+ {copilotV2Enabled ? (
<TooltipProvider>
<ControlTooltip
content={morphButtonLabel}
@@ -4299,7 +4081,7 @@ export function WorkflowCopilotChat({
)}
{/* Mounted only while open: CredentialsModal pulls react-query at mount,
so keeping it mounted-but-closed would tax every render for nothing. */}
- {copilotUxV1Enabled && credentialModalOpen ? (
+ {credentialModalOpen ? (
<CredentialsModal
isOpen
// A sign-in pause always needs a password credential; force the form
diff --git a/skyvern-frontend/src/routes/workflows/copilot/copilotActivityLog.test.ts b/skyvern-frontend/src/routes/workflows/copilot/copilotActivityLog.test.ts
index 4cdc72d2a..f9a0a0c26 100644
--- a/skyvern-frontend/src/routes/workflows/copilot/copilotActivityLog.test.ts
+++ b/skyvern-frontend/src/routes/workflows/copilot/copilotActivityLog.test.ts
@@ -364,6 +364,433 @@ describe("deriveActivityLog", () => {
expect(glyphsOf(log)).toEqual(["⟨⟩", "⟨⟩", "⟨⟩"]);
});
+ it("keeps a failed browse action separate from preceding successful work", () => {
+ const log = deriveActivityLog(
+ turnWith([
+ entry({
+ id: "tr-1",
+ kind: "tool_result",
+ toolName: "navigate_browser",
+ text: "Opened the certificant search",
+ success: true,
+ iteration: 0,
+ }),
+ entry({
+ id: "n-1",
+ kind: "narration",
+ text: "Opening the search form",
+ iteration: 0,
+ activeLabel: "Opening the certificant search",
+ outcomeLabel: "Opened the certificant search",
+ }),
+ entry({
+ id: "tr-2",
+ kind: "tool_result",
+ toolName: "get_page_evidence",
+ text: "The browser target crashed",
+ success: false,
+ iteration: 1,
+ }),
+ entry({
+ id: "n-2",
+ kind: "narration",
+ text: "Restoring the results page",
+ iteration: 1,
+ activeLabel: "Restoring access to the certification results",
+ outcomeLabel: "Restored the certification results",
+ }),
+ ]),
+ );
+
+ expect(log.rows).toHaveLength(2);
+ expect(log.rows.map((row) => row.label)).toEqual([
+ "Opened the certificant search",
+ "Restoring access to the certification results",
+ ]);
+ expect(log.rows[0]?.entries[0]?.success).toBe(true);
+ expect(log.rows[1]?.entries[0]?.success).toBe(false);
+ });
+
+ it("coalesces differently implemented retries of one narrated browse activity", () => {
+ const log = deriveActivityLog(
+ turnWith([
+ entry({
+ id: "tr-1",
+ kind: "tool_result",
+ toolName: "navigate_browser",
+ text: "The browser target was unavailable",
+ success: false,
+ iteration: 0,
+ }),
+ entry({
+ id: "n-1",
+ kind: "narration",
+ text: "Looking for the certification record",
+ iteration: 0,
+ activeLabel: "Searching for the certification record",
+ outcomeLabel: "Found the certification record",
+ }),
+ entry({
+ id: "tr-2",
+ kind: "tool_result",
+ toolName: "get_page_evidence",
+ text: "The results page did not load",
+ success: false,
+ iteration: 1,
+ }),
+ entry({
+ id: "n-2",
+ kind: "narration",
+ text: "Trying the search again",
+ iteration: 1,
+ activeLabel: "Searching for the certification record",
+ outcomeLabel: "Found the certification record",
+ }),
+ entry({
+ id: "tc-3",
+ kind: "tool_call",
+ toolName: "click_element",
+ text: "Opening the search form",
+ iteration: 2,
+ }),
+ entry({
+ id: "n-3",
+ kind: "narration",
+ text: "Trying a direct search",
+ iteration: 2,
+ activeLabel: "Searching for the certification record",
+ outcomeLabel: "Found the certification record",
+ }),
+ ]),
+ );
+
+ expect(log.rows).toHaveLength(1);
+ expect(log.rows[0]).toMatchObject({
+ id: "1",
+ label: "Searching for the certification record",
+ pending: true,
+ live: true,
+ startedAt: at(1),
+ endedAt: at(3),
+ });
+ expect(log.rows[0]?.entries).toHaveLength(3);
+ expect(log.rows[0]?.entries[2]?.attempts).toBe(3);
+ });
+
+ it("keeps overlapping browse siblings separate even with the same narrated intent", () => {
+ const log = deriveActivityLog(
+ turnWith([
+ entry({
+ id: "tr-a",
+ kind: "tool_result",
+ toolName: "navigate_browser",
+ text: "The first page failed",
+ success: false,
+ iteration: 0,
+ activityStartedAt: "2026-01-01T00:00:10Z",
+ timestamp: "2026-01-01T00:00:20Z",
+ }),
+ entry({
+ id: "n-a",
+ kind: "narration",
+ text: "Checking the page",
+ iteration: 0,
+ activeLabel: "Searching the page",
+ timestamp: "2026-01-01T00:00:20Z",
+ }),
+ entry({
+ id: "tr-b",
+ kind: "tool_result",
+ toolName: "get_page_evidence",
+ text: "The parallel page opened",
+ success: true,
+ iteration: 1,
+ activityStartedAt: "2026-01-01T00:00:11Z",
+ timestamp: "2026-01-01T00:00:21Z",
+ }),
+ entry({
+ id: "n-b",
+ kind: "narration",
+ text: "Checking the same page",
+ iteration: 1,
+ activeLabel: "Searching the page",
+ timestamp: "2026-01-01T00:00:21Z",
+ }),
+ ]),
+ );
+
+ expect(log.rows).toHaveLength(2);
+ expect(log.rows.map((row) => row.entries.length)).toEqual([1, 1]);
+ expect(log.rows.map((row) => row.id)).toEqual(["a", "b"]);
+ });
+
+ it("keeps browse tools from one iteration folded into one activity", () => {
+ const log = deriveActivityLog(
+ turnWith([
+ entry({
+ id: "tr-1",
+ kind: "tool_result",
+ toolName: "navigate_browser",
+ text: "Opened the search",
+ success: true,
+ iteration: 0,
+ }),
+ entry({
+ id: "tr-2",
+ kind: "tool_result",
+ toolName: "get_page_evidence",
+ text: "Read the search form",
+ success: true,
+ iteration: 0,
+ }),
+ ]),
+ );
+
+ expect(log.rows).toHaveLength(1);
+ expect(log.rows[0]?.entries).toHaveLength(2);
+ });
+
+ it("keeps a code write visible in the immediate test frontier", () => {
+ const log = deriveActivityLog(
+ turnWith([
+ entry({
+ id: "tr-write",
+ kind: "tool_result",
+ toolName: "add_block",
+ text: "Added the cart block",
+ success: true,
+ iteration: 2,
+ codeDiffs: [
+ {
+ label: "add_to_cart",
+ added: 15,
+ removed: 0,
+ patch: "+await page.click('button.add-to-cart')",
+ },
+ ],
+ }),
+ entry({
+ id: "tc-run",
+ kind: "tool_call",
+ toolName: "run_blocks_and_collect_debug",
+ text: "Testing the cart block",
+ iteration: 3,
+ }),
+ ]),
+ );
+
+ expect(log.rows).toHaveLength(1);
+ expect(log.rows[0]?.kind).toBe("run");
+ expect(log.rows[0]?.entries).toHaveLength(2);
+ expect(log.rows[0]?.codeDiffs).toMatchObject([
+ { label: "add_to_cart", added: 15, removed: 0 },
+ ]);
+ expect(log.focusIndex).toBe(0);
+ });
+
+ it("promotes an active block's repair diff into its frontier row", () => {
+ const log = deriveActivityLog(
+ turnWith(
+ [],
+ [
+ block({
+ label: "add_to_cart",
+ state: "running",
+ activity: [
+ entry({
+ id: "tc-repair",
+ kind: "tool_call",
+ toolName: "edit_block_and_run",
+ text: "Repairing and testing the cart block",
+ codeDiffs: [
+ {
+ label: "add_to_cart",
+ added: 2,
+ removed: 1,
+ patch: "-old\n+new",
+ },
+ ],
+ }),
+ ],
+ }),
+ ],
+ ),
+ );
+
+ expect(log.rows).toHaveLength(1);
+ expect(log.rows[0]?.codeDiffs).toMatchObject([
+ { label: "add_to_cart", added: 2, removed: 1, patch: "-old\n+new" },
+ ]);
+ expect(log.focusIndex).toBe(0);
+ });
+
+ it("does not merge an older parallel run into a later code write", () => {
+ const log = deriveActivityLog(
+ turnWith([
+ entry({
+ id: "tr-write",
+ kind: "tool_result",
+ toolName: "add_block",
+ text: "Added the cart block",
+ success: true,
+ timestamp: at(4),
+ codeDiffs: [
+ {
+ label: "add_to_cart",
+ added: 15,
+ removed: 0,
+ patch: "+await page.click('button.add-to-cart')",
+ },
+ ],
+ }),
+ entry({
+ id: "tr-run",
+ kind: "tool_result",
+ toolName: "run_blocks_and_collect_debug",
+ text: "An earlier parallel run finished",
+ success: true,
+ timestamp: at(5),
+ activityStartedAt: at(2),
+ }),
+ ]),
+ );
+
+ expect(log.rows).toHaveLength(2);
+ expect(log.rows.map((row) => row.kind)).toEqual(["author", "run"]);
+ });
+
+ it("anchors parallel block evidence by the run inside a combined write and test row", () => {
+ const log = deriveActivityLog(
+ turnWith(
+ [
+ entry({
+ id: "tr-prior-run",
+ kind: "tool_result",
+ toolName: "run_blocks_and_collect_debug",
+ text: "Finished the prior run",
+ success: true,
+ activityStartedAt: at(1),
+ timestamp: at(3),
+ }),
+ entry({
+ id: "tr-write",
+ kind: "tool_result",
+ toolName: "add_block",
+ text: "Added a repaired block",
+ success: true,
+ timestamp: at(4),
+ codeDiffs: [
+ {
+ label: "repaired_block",
+ added: 3,
+ removed: 0,
+ patch: "+await page.goto(URL)",
+ },
+ ],
+ }),
+ entry({
+ id: "tc-new-run",
+ kind: "tool_call",
+ toolName: "run_blocks_and_collect_debug",
+ text: "Testing the repaired block",
+ timestamp: at(6),
+ }),
+ ],
+ [
+ block({
+ workflowRunBlockId: "wrb-prior",
+ label: "prior_block",
+ startedAt: at(5),
+ }),
+ ],
+ ),
+ );
+
+ expect(log.rows).toHaveLength(2);
+ expect(labelsPerRow(log)).toEqual([["prior_block"], []]);
+ });
+
+ it("anchors a block to the latest qualifying run start regardless of completion order", () => {
+ const log = deriveActivityLog(
+ turnWith(
+ [
+ entry({
+ id: "tr-run-b",
+ kind: "tool_result",
+ toolName: "run_blocks_and_collect_debug",
+ text: "Run B completed first",
+ success: true,
+ activityStartedAt: at(20),
+ timestamp: at(30),
+ }),
+ entry({
+ id: "tr-run-a",
+ kind: "tool_result",
+ toolName: "run_blocks_and_collect_debug",
+ text: "Run A completed later",
+ success: true,
+ activityStartedAt: at(10),
+ timestamp: at(40),
+ }),
+ ],
+ [
+ block({
+ workflowRunBlockId: "wrb-b",
+ label: "run_b_block",
+ startedAt: at(25),
+ }),
+ ],
+ ),
+ );
+
+ expect(labelsPerRow(log)).toEqual([["run_b_block"], []]);
+ });
+
+ it("keeps exact failed retry evidence inside a recovered block", () => {
+ const log = deriveActivityLog(
+ turnWith(
+ [
+ entry({
+ id: "tr-run",
+ kind: "tool_result",
+ toolName: "run_blocks_and_collect_debug",
+ text: "The block recovered",
+ success: true,
+ }),
+ ],
+ [
+ block({
+ workflowRunBlockId: "wrb-recovered",
+ label: "recovered_block",
+ state: "completed",
+ activity: [
+ entry({
+ id: "tr-attempt-1",
+ kind: "tool_result",
+ toolName: "navigate_browser",
+ text: "The browser target crashed",
+ success: false,
+ timestamp: at(2),
+ }),
+ entry({
+ id: "tr-attempt-2",
+ kind: "tool_result",
+ toolName: "navigate_browser",
+ text: "Opened the page after retrying",
+ success: true,
+ timestamp: at(3),
+ }),
+ ],
+ }),
+ ],
+ ),
+ );
+
+ expect(log.rows[0]?.blocks[0]?.activity.map((entry) => entry.text)).toEqual(
+ ["The browser target crashed", "Opened the page after retrying"],
+ );
+ });
+
it("folds an adjacent same-tool retry into one row carrying the attempt count", () => {
const log = deriveActivityLog(
turnWith([
@@ -386,11 +813,13 @@ describe("deriveActivityLog", () => {
);
expect(log.rows).toHaveLength(1);
- expect(log.rows[0]?.entries[0]?.attempts).toBe(2);
- expect(log.rows[0]?.entries[0]?.text).toBe("Reached the confirmation page");
+ expect(log.rows[0]?.entries).toHaveLength(2);
+ expect(log.rows[0]?.entries[0]?.text).toBe("The login step timed out");
+ expect(log.rows[0]?.entries[1]?.attempts).toBe(2);
+ expect(log.rows[0]?.entries[1]?.text).toBe("Reached the confirmation page");
});
- it("re-keys a row when a retry folds into it, so a pin cannot survive the fold", () => {
+ it("keeps a row's identity stable when a retry folds into it", () => {
const attempt = entry({
id: "tr-1",
kind: "tool_result",
@@ -405,115 +834,398 @@ describe("deriveActivityLog", () => {
entry({
id: "tr-2",
kind: "tool_result",
- toolName: "update_and_run_blocks",
- text: "Reached the confirmation page",
+ toolName: "update_and_run_blocks",
+ text: "Reached the confirmation page",
+ success: true,
+ iteration: 1,
+ }),
+ ]),
+ );
+
+ expect(idsOf(before)).toEqual(["1"]);
+ expect(idsOf(after)).toEqual(["1"]);
+ });
+
+ it("derives the same rows from a hydrated narrative payload as from the live turn", () => {
+ const liveRows = deriveActivityLog(turnWith(repairLoopActivity())).rows;
+ const hydrated = hydrateNarrativeFromPayload({
+ turnId: "turn-1",
+ turnIndex: 0,
+ terminal: "response",
+ designActivity: repairLoopActivity(),
+ });
+
+ expect(hydrated).toBeDefined();
+ const hydratedLog = deriveActivityLog(hydrated!);
+
+ expect(hydratedLog.rows).toEqual(liveRows);
+ expect(glyphsOf(hydratedLog)).toEqual(["◎", "⟨⟩", "▷", "◎", "⟨⟩", "▷"]);
+ });
+
+ it("groups consecutive browse steps into one row and counts them", () => {
+ const log = deriveActivityLog(
+ turnWith(
+ ["navigate_browser", "get_page_evidence", "click_element"].map(
+ (toolName, i) =>
+ entry({
+ id: `tr-${i}`,
+ kind: "tool_result",
+ toolName,
+ text: `Browse step ${i}`,
+ success: true,
+ iteration: i,
+ }),
+ ),
+ ),
+ );
+
+ expect(log.rows).toHaveLength(1);
+ expect(log.rows[0]?.kind).toBe("browse");
+ expect(log.rows[0]?.entries).toHaveLength(3);
+ expect(log.rows[0]?.entries[2]?.text).toBe("Browse step 2");
+ });
+
+ it("attaches a narration to the row owning its iteration, emitting no row of its own", () => {
+ const log = deriveActivityLog(
+ turnWith([
+ entry({
+ id: "tr-1",
+ kind: "tool_result",
+ toolName: "navigate_browser",
+ text: "Opened the sign-in page",
+ success: true,
+ }),
+ entry({
+ id: "tc-2",
+ kind: "tool_call",
+ toolName: "update_workflow",
+ displayLabel: "Saving blocks",
+ iteration: 1,
+ }),
+ entry({
+ id: "n-1",
+ kind: "narration",
+ text: "Checking which fields the sign-in form needs",
+ iteration: 0,
+ }),
+ ]),
+ );
+
+ expect(log.rows.map((r) => r.kind)).toEqual(["browse", "author"]);
+ expect(
+ log.rows.every((r) => r.entries.every((e) => e.kind !== "narration")),
+ ).toBe(true);
+ expect(log.rows[0]?.reason).toBe(
+ "Checking which fields the sign-in form needs",
+ );
+ expect(log.rows[1]?.reason).toBeNull();
+ });
+
+ it("attaches an unmatched narration to the nearest preceding row", () => {
+ const log = deriveActivityLog(
+ turnWith([
+ entry({
+ id: "tr-1",
+ kind: "tool_result",
+ toolName: "navigate_browser",
+ text: "Opened the sign-in page",
+ success: true,
+ iteration: 0,
+ }),
+ entry({
+ id: "n-1",
+ kind: "narration",
+ text: "Looking for the pricing table",
+ iteration: 9,
+ }),
+ ]),
+ );
+
+ expect(log.rows.map((r) => r.kind)).toEqual(["browse"]);
+ expect(log.rows[0]?.reason).toBe("Looking for the pricing table");
+ });
+
+ it("attaches narration to the action in flight when its iteration trails the tool", () => {
+ const log = deriveActivityLog(
+ turnWith([
+ entry({
+ id: "tr-1",
+ kind: "tool_result",
+ toolName: "click",
+ text: "Opened the result",
+ success: true,
+ iteration: 2,
+ timestamp: "2026-01-01T00:00:24Z",
+ }),
+ entry({
+ id: "tc-inspect",
+ kind: "tool_call",
+ toolName: "inspect_page_for_composition",
+ text: "Inspecting page",
+ iteration: 3,
+ timestamp: "2026-01-01T00:00:31Z",
+ }),
+ entry({
+ id: "n-2",
+ kind: "narration",
+ text: "Reviewing the visible credential results",
+ iteration: 2,
+ activeLabel: "Reviewing the credential results",
+ outcomeLabel: "Reviewed the credential results",
+ timestamp: "2026-01-01T00:00:33Z",
+ }),
+ entry({
+ id: "tr-inspect",
+ kind: "tool_result",
+ toolName: "inspect_page_for_composition",
+ text: "The page could not be inspected",
+ success: false,
+ iteration: 3,
+ timestamp: "2026-01-01T00:00:51Z",
+ }),
+ ]),
+ );
+
+ expect(log.rows).toHaveLength(2);
+ expect(log.rows[0]?.reason).toBeNull();
+ expect(log.rows[1]).toMatchObject({
+ label: "Reviewing the credential results",
+ reason: "Reviewing the visible credential results",
+ });
+ });
+
+ it("does not let a stale pending call capture narration for a settled sibling", () => {
+ const log = deriveActivityLog(
+ turnWith([
+ entry({
+ id: "tc-stale",
+ kind: "tool_call",
+ toolName: "update_workflow",
+ text: "Opening the stale tab",
+ iteration: 0,
+ timestamp: "2026-01-01T00:00:10Z",
+ }),
+ entry({
+ id: "tc-settled",
+ kind: "tool_call",
+ toolName: "get_page_evidence",
+ text: "Inspecting the current page",
+ iteration: 1,
+ timestamp: "2026-01-01T00:00:20Z",
+ }),
+ entry({
+ id: "tr-settled",
+ kind: "tool_result",
+ toolName: "get_page_evidence",
+ text: "Read the current page",
success: true,
iteration: 1,
+ timestamp: "2026-01-01T00:00:25Z",
+ }),
+ entry({
+ id: "n-settled",
+ kind: "narration",
+ text: "Checking the current page for the result",
+ iteration: 1,
+ activeLabel: "Reviewing the current result",
+ timestamp: "2026-01-01T00:00:26Z",
}),
]),
);
- expect(idsOf(before)).toEqual(["1"]);
- expect(idsOf(after)).toEqual(["2"]);
- });
-
- it("derives the same rows from a hydrated narrative payload as from the live turn", () => {
- const liveRows = deriveActivityLog(turnWith(repairLoopActivity())).rows;
- const hydrated = hydrateNarrativeFromPayload({
- turnId: "turn-1",
- turnIndex: 0,
- terminal: "response",
- designActivity: repairLoopActivity(),
+ expect(log.rows[0]?.reason).toBeNull();
+ expect(log.rows[1]).toMatchObject({
+ label: "Reviewing the current result",
+ reason: "Checking the current page for the result",
});
+ });
- expect(hydrated).toBeDefined();
- const hydratedLog = deriveActivityLog(hydrated!);
+ it("uses iteration when parallel pending calls have overlapping time spans", () => {
+ const log = deriveActivityLog(
+ turnWith([
+ entry({
+ id: "tc-first",
+ kind: "tool_call",
+ toolName: "update_workflow",
+ text: "Opening the first page",
+ iteration: 0,
+ timestamp: "2026-01-01T00:00:10Z",
+ }),
+ entry({
+ id: "tc-second",
+ kind: "tool_call",
+ toolName: "get_page_evidence",
+ text: "Inspecting the second page",
+ iteration: 1,
+ timestamp: "2026-01-01T00:00:20Z",
+ }),
+ entry({
+ id: "n-first",
+ kind: "narration",
+ text: "Still opening the first page",
+ iteration: 0,
+ activeLabel: "Opening the first page",
+ timestamp: "2026-01-01T00:00:21Z",
+ }),
+ ]),
+ );
- expect(hydratedLog.rows).toEqual(liveRows);
- expect(glyphsOf(hydratedLog)).toEqual(["◎", "⟨⟩", "▷", "◎", "⟨⟩", "▷"]);
+ expect(log.rows[0]).toMatchObject({
+ label: "Opening the first page",
+ reason: "Still opening the first page",
+ });
+ expect(log.rows[1]?.reason).toBeNull();
});
- it("groups consecutive browse steps into one row and counts them", () => {
+ it("folds a technical recovery substep into the current narrated attempt", () => {
const log = deriveActivityLog(
- turnWith(
- ["navigate_browser", "get_page_evidence", "click_element"].map(
- (toolName, i) =>
- entry({
- id: `tr-${i}`,
- kind: "tool_result",
- toolName,
- text: `Browse step ${i}`,
- success: true,
- iteration: i,
- }),
- ),
- ),
+ turnWith([
+ entry({
+ id: "tr-inspect",
+ kind: "tool_result",
+ toolName: "inspect_page_for_composition",
+ text: "The page could not be inspected",
+ success: false,
+ iteration: 3,
+ }),
+ entry({
+ id: "n-3",
+ kind: "narration",
+ text: "The result page stopped responding",
+ iteration: 3,
+ activeLabel: "Reviewing the credential results",
+ }),
+ entry({
+ id: "tr-evaluate",
+ kind: "tool_result",
+ toolName: "evaluate",
+ text: "The page was unavailable",
+ success: false,
+ iteration: 4,
+ }),
+ ]),
);
expect(log.rows).toHaveLength(1);
- expect(log.rows[0]?.kind).toBe("browse");
- expect(log.rows[0]?.entries).toHaveLength(3);
- expect(log.rows[0]?.entries[2]?.text).toBe("Browse step 2");
+ expect(log.rows[0]).toMatchObject({
+ label: "Reviewing the credential results",
+ id: "inspect",
+ });
+ expect(log.rows[0]?.entries[1]?.attempts).toBe(2);
});
- it("attaches a narration to the row owning its iteration, emitting no row of its own", () => {
+ it("starts a new retry row after the prior narrated attempt recovered", () => {
const log = deriveActivityLog(
turnWith([
entry({
- id: "tr-1",
+ id: "tr-failed",
kind: "tool_result",
toolName: "navigate_browser",
- text: "Opened the sign-in page",
+ text: "The page did not open",
+ success: false,
+ iteration: 0,
+ }),
+ entry({
+ id: "n-failed",
+ kind: "narration",
+ text: "Trying the page",
+ iteration: 0,
+ activeLabel: "Opening the page",
+ }),
+ entry({
+ id: "tr-recovered",
+ kind: "tool_result",
+ toolName: "get_page_evidence",
+ text: "Read the page",
success: true,
+ iteration: 1,
}),
entry({
- id: "tc-2",
- kind: "tool_call",
- toolName: "update_workflow",
- displayLabel: "Saving blocks",
+ id: "n-recovered",
+ kind: "narration",
+ text: "The page is available",
iteration: 1,
+ activeLabel: "Opening the page",
}),
entry({
- id: "n-1",
+ id: "tr-later",
+ kind: "tool_result",
+ toolName: "click_element",
+ text: "The next click failed",
+ success: false,
+ iteration: 2,
+ }),
+ entry({
+ id: "n-later",
kind: "narration",
- text: "Checking which fields the sign-in form needs",
- iteration: 0,
+ text: "Trying the next control",
+ iteration: 2,
+ activeLabel: "Opening the page",
}),
]),
);
- expect(log.rows.map((r) => r.kind)).toEqual(["browse", "author"]);
- expect(
- log.rows.every((r) => r.entries.every((e) => e.kind !== "narration")),
- ).toBe(true);
- expect(log.rows[0]?.reason).toBe(
- "Checking which fields the sign-in form needs",
- );
- expect(log.rows[1]?.reason).toBeNull();
+ expect(log.rows).toHaveLength(2);
+ const recovered = log.rows[0]?.entries;
+ const later = log.rows[1]?.entries;
+ expect(recovered?.[recovered.length - 1]?.success).toBe(true);
+ expect(later?.[later.length - 1]?.success).toBe(false);
});
- it("attaches an unmatched narration to the nearest preceding row", () => {
+ it("recomputes pending and live after an out-of-order narrated retry merge", () => {
const log = deriveActivityLog(
turnWith([
entry({
- id: "tr-1",
+ id: "tr-first",
kind: "tool_result",
toolName: "navigate_browser",
- text: "Opened the sign-in page",
- success: true,
+ text: "The first attempt failed",
+ success: false,
iteration: 0,
}),
entry({
- id: "n-1",
+ id: "n-first",
kind: "narration",
- text: "Looking for the pricing table",
- iteration: 9,
+ text: "Trying the search",
+ iteration: 0,
+ activeLabel: "Searching the page",
+ }),
+ entry({
+ id: "tc-pending",
+ kind: "tool_call",
+ toolName: "get_page_evidence",
+ text: "Inspecting the page",
+ iteration: 1,
+ }),
+ entry({
+ id: "n-pending",
+ kind: "narration",
+ text: "Trying the search again",
+ iteration: 1,
+ activeLabel: "Searching the page",
+ }),
+ entry({
+ id: "tr-sibling",
+ kind: "tool_result",
+ toolName: "click_element",
+ text: "The sibling attempt failed",
+ success: false,
+ iteration: 2,
+ }),
+ entry({
+ id: "n-sibling",
+ kind: "narration",
+ text: "Still trying the search",
+ iteration: 2,
+ activeLabel: "Searching the page",
}),
]),
);
- expect(log.rows.map((r) => r.kind)).toEqual(["browse"]);
- expect(log.rows[0]?.reason).toBe("Looking for the pricing table");
+ expect(log.rows).toHaveLength(2);
+ expect(log.rows[0]).toMatchObject({ pending: true, live: true });
+ expect(log.rows[1]).toMatchObject({ pending: false, live: false });
+ expect(log.liveIndex).toBe(0);
});
it("drops a narration with no preceding row rather than rendering one", () => {
@@ -1114,6 +1826,142 @@ describe("deriveActivityLog", () => {
expect(live.rows[0]!.label).toBe("Looking for the invoice list");
});
+ it("keeps a failed row's active label instead of showing its predicted outcome", () => {
+ const log = deriveActivityLog({
+ ...turnWith([
+ entry({
+ id: "tr-1",
+ kind: "tool_result",
+ toolName: "update_and_run_blocks",
+ text: "The submit button stayed disabled",
+ success: false,
+ iteration: 0,
+ }),
+ entry({
+ id: "n-1",
+ kind: "narration",
+ text: "Confirming the form can be submitted",
+ iteration: 0,
+ activeLabel: "Testing form submission",
+ outcomeLabel: "Confirmed the form submits successfully",
+ }),
+ ]),
+ terminal: "response",
+ });
+
+ expect(log.rows[0]!.label).toBe("Testing form submission");
+ });
+
+ it("uses the outcome label after a retry recovers while preserving its failure", () => {
+ const log = deriveActivityLog({
+ ...turnWith([
+ entry({
+ id: "tr-1",
+ kind: "tool_result",
+ toolName: "navigate_browser",
+ text: "The page did not open",
+ success: false,
+ iteration: 0,
+ }),
+ entry({
+ id: "n-1",
+ kind: "narration",
+ text: "Trying the page",
+ iteration: 0,
+ activeLabel: "Opening the page",
+ outcomeLabel: "Opened the page",
+ }),
+ entry({
+ id: "tr-2",
+ kind: "tool_result",
+ toolName: "navigate_browser",
+ text: "The page opened",
+ success: true,
+ iteration: 1,
+ }),
+ entry({
+ id: "n-2",
+ kind: "narration",
+ text: "The retry reached the page",
+ iteration: 1,
+ activeLabel: "Opening the page",
+ outcomeLabel: "Opened the page after retrying",
+ }),
+ ]),
+ terminal: "response",
+ });
+
+ expect(log.rows).toHaveLength(1);
+ expect(log.rows[0]?.label).toBe("Opened the page after retrying");
+ expect(log.rows[0]?.entries[0]?.text).toBe("The page did not open");
+ expect(log.rows[0]?.entries[1]?.text).toBe("The page opened");
+ });
+
+ it.each([
+ ["stopped", undefined],
+ ["completed", "evaluating"],
+ ["completed", "not_demonstrated"],
+ ] as const)(
+ "keeps the active label for a non-success %s block with outcome %s",
+ (state, outcome) => {
+ const log = deriveActivityLog({
+ ...turnWith(
+ [
+ entry({
+ id: "tr-run",
+ kind: "tool_result",
+ toolName: "run_blocks_and_collect_debug",
+ text: "The run returned",
+ success: true,
+ iteration: 0,
+ }),
+ entry({
+ id: "n-run",
+ kind: "narration",
+ text: "Checking the run result",
+ iteration: 0,
+ activeLabel: "Checking the workflow",
+ outcomeLabel: "Confirmed the workflow works",
+ }),
+ ],
+ [block({ state, outcome })],
+ ),
+ terminal: "response",
+ });
+
+ expect(log.rows[0]?.label).toBe("Checking the workflow");
+ },
+ );
+
+ it("uses the outcome label only when a block has a successful verdict", () => {
+ const log = deriveActivityLog({
+ ...turnWith(
+ [
+ entry({
+ id: "tr-run",
+ kind: "tool_result",
+ toolName: "run_blocks_and_collect_debug",
+ text: "The run returned",
+ success: true,
+ iteration: 0,
+ }),
+ entry({
+ id: "n-run",
+ kind: "narration",
+ text: "Checking the run result",
+ iteration: 0,
+ activeLabel: "Checking the workflow",
+ outcomeLabel: "Confirmed the workflow works",
+ }),
+ ],
+ [block({ state: "completed", outcome: "demonstrated" })],
+ ),
+ terminal: "response",
+ });
+
+ expect(log.rows[0]?.label).toBe("Confirmed the workflow works");
+ });
+
it("leaves the row label null when the narrator never spoke for the step", () => {
const log = deriveActivityLog(
turnWith([
@@ -1277,6 +2125,33 @@ describe("deriveActivityLog", () => {
expect(log.focusIndex).toBe(log.rows.length - 1);
});
+ it("keeps a live row focused when an empty drafted block follows it", () => {
+ const log = deriveActivityLog(
+ turnWith(
+ [
+ entry({
+ id: "tc-1",
+ kind: "tool_call",
+ toolName: "navigate_browser",
+ displayLabel: "Searching the catalogue",
+ iteration: 0,
+ }),
+ ],
+ [
+ block({
+ workflowRunBlockId: "",
+ label: "add_first_result",
+ state: "drafted",
+ }),
+ ],
+ ),
+ );
+
+ expect(log.rows[log.liveIndex]?.pending).toBe(true);
+ expect(log.rows[log.rows.length - 1]?.blocks[0]?.state).toBe("drafted");
+ expect(log.focusIndex).toBe(log.liveIndex);
+ });
+
it("does not move focus back to an earlier row when a later one settles", () => {
const log = deriveActivityLog(
turnWith([
@@ -1415,6 +2290,33 @@ describe("deriveActivityLog", () => {
expect(log.rows[0]!.endedAt).toBe("2026-01-01T00:00:14+00:00");
});
+ it("spans a settled action from its call timestamp to its result timestamp", () => {
+ const log = deriveActivityLog(
+ turnWith([
+ entry({
+ id: "tc-1",
+ kind: "tool_call",
+ toolName: "navigate_browser",
+ text: "Opening page",
+ timestamp: "2026-01-01T00:00:04Z",
+ }),
+ entry({
+ id: "tr-1",
+ kind: "tool_result",
+ toolName: "navigate_browser",
+ text: "The page did not open",
+ success: false,
+ timestamp: "2026-01-01T00:00:24Z",
+ }),
+ ]),
+ );
+
+ expect(log.rows[0]).toMatchObject({
+ startedAt: "2026-01-01T00:00:04Z",
+ endedAt: "2026-01-01T00:00:24Z",
+ });
+ });
+
it("leaves the span null against a backend that does not stamp entries", () => {
const log = deriveActivityLog(
turnWith([
diff --git a/skyvern-frontend/src/routes/workflows/copilot/copilotActivityLog.ts b/skyvern-frontend/src/routes/workflows/copilot/copilotActivityLog.ts
index fc008c99e..f2400c226 100644
--- a/skyvern-frontend/src/routes/workflows/copilot/copilotActivityLog.ts
+++ b/skyvern-frontend/src/routes/workflows/copilot/copilotActivityLog.ts
@@ -7,6 +7,7 @@ import {
TurnNarrativeState,
condenseActivityEntries,
hasPendingToolCall,
+ isBlockOk,
parseUtcIsoMs,
toolCallIdOf,
} from "./narrativeState";
@@ -109,11 +110,17 @@ function runStartLookup(
}
}
return (row) => {
- const first = row.entries[0];
+ // A code write and its immediate test share one display row, but block
+ // evidence still belongs to the run invocation. Using the author entry's
+ // earlier timestamp here can make a parallel block look like part of the
+ // new test.
+ const firstRun = row.entries.find((entry) => kindOf(entry) === "run");
+ const first = firstRun ?? row.entries[0];
if (first === undefined) return null;
const callId = toolCallIdOf(first);
const startedAt =
(callId === undefined ? undefined : callStartedAt.get(callId)) ??
+ first.activityStartedAt ??
first.timestamp;
return parseUtcIsoMs(startedAt);
};
@@ -130,25 +137,153 @@ function anchorRunRow(
if (block.state === "drafted" || runRows.length === 0) {
return undefined;
}
- const lastRow = runRows[runRows.length - 1];
+ const timedRows = runRows.map((row) => ({ row, started: runStartedMs(row) }));
const blockStartedMs = parseUtcIsoMs(block.startedAt);
if (blockStartedMs === null) {
- return lastRow;
+ return (
+ timedRows.reduce<ActivityRow | undefined>((latest, candidate) => {
+ if (candidate.started === null) return latest;
+ if (latest === undefined) return candidate.row;
+ const latestStarted = runStartedMs(latest);
+ return latestStarted === null || candidate.started > latestStarted
+ ? candidate.row
+ : latest;
+ }, undefined) ?? runRows[runRows.length - 1]
+ );
}
let anchor: ActivityRow | undefined;
- for (const row of runRows) {
- const startedMs = runStartedMs(row);
- if (startedMs !== null && startedMs <= blockStartedMs) {
+ let anchorStarted = -Infinity;
+ for (const { row, started } of timedRows) {
+ if (
+ started !== null &&
+ started <= blockStartedMs &&
+ started > anchorStarted
+ ) {
anchor = row;
+ anchorStarted = started;
}
}
// Nothing started early enough means the block's own row aged out past the
// activity cap, so the nearest surviving row is the earliest one left.
- return anchor ?? runRows[0];
+ if (anchor !== undefined) return anchor;
+ return (
+ timedRows.reduce<ActivityRow | undefined>((earliest, candidate) => {
+ if (candidate.started === null) return earliest;
+ if (earliest === undefined) return candidate.row;
+ const earliestStarted = runStartedMs(earliest);
+ return earliestStarted === null || candidate.started < earliestStarted
+ ? candidate.row
+ : earliest;
+ }, undefined) ?? runRows[0]
+ );
+}
+
+function retryEntries(entry: ActivityEntry): ActivityEntry[] {
+ return [...(entry.priorFailures ?? []), entry];
}
function condensedBlock(block: BlockState): BlockState {
- return { ...block, activity: condenseActivityEntries(block.activity) };
+ return {
+ ...block,
+ activity: condenseActivityEntries(block.activity).flatMap(retryEntries),
+ };
+}
+
+function stableRowId(entry: ActivityEntry): string {
+ const root = entry.retryRootId;
+ if (root !== undefined) {
+ return root.startsWith("tc-") || root.startsWith("tr-")
+ ? root.slice(3)
+ : root;
+ }
+ return toolCallIdOf(entry) || entry.id;
+}
+
+function coalesceNarratedBrowseRetries(
+ rows: ActivityRow[],
+ intentByRow: ReadonlyMap<ActivityRow, string>,
+): void {
+ const coalesced: ActivityRow[] = [];
+ const coalescedIntents: (string | undefined)[] = [];
+ for (const row of rows) {
+ const previous = coalesced[coalesced.length - 1];
+ const intent = intentByRow.get(row);
+ const previousIntent = coalescedIntents[coalescedIntents.length - 1];
+ const previousTail = previous?.entries[previous.entries.length - 1];
+ const previousFailed =
+ previousTail?.kind === "tool_result" && previousTail.success === false;
+ const previousEndedMs = parseUtcIsoMs(previous?.endedAt);
+ const rowStartedMs = parseUtcIsoMs(row.startedAt);
+ // Parallel siblings can carry the same narrated intent. They are a retry
+ // only when the new attempt starts after the failed one ended; missing
+ // timestamps retain the legacy fallback for old hydrated payloads.
+ const followsFailure =
+ previousEndedMs === null ||
+ rowStartedMs === null ||
+ rowStartedMs >= previousEndedMs;
+ if (
+ previous?.kind !== "browse" ||
+ row.kind !== "browse" ||
+ !previousFailed ||
+ !followsFailure ||
+ intent === undefined ||
+ intent !== previousIntent
+ ) {
+ coalesced.push(row);
+ coalescedIntents.push(intent);
+ continue;
+ }
+
+ const latest = row.entries[row.entries.length - 1];
+ if (latest === undefined) {
+ coalesced.push(row);
+ coalescedIntents.push(intent);
+ continue;
+ }
+ const attempts =
+ (previous.entries[previous.entries.length - 1]?.attempts ?? 1) +
+ (latest.attempts ?? 1);
+ const earlierEntries = previous.entries.map((entry) => ({
+ ...entry,
+ attempts: undefined,
+ }));
+ const currentEntries = row.entries.slice();
+ currentEntries[currentEntries.length - 1] = {
+ ...latest,
+ attempts,
+ activityStartedAt:
+ previous.startedAt ?? latest.activityStartedAt ?? latest.timestamp,
+ };
+ coalesced[coalesced.length - 1] = {
+ ...row,
+ id: previous.id,
+ entries: [...earlierEntries, ...currentEntries],
+ startedAt: previous.startedAt ?? row.startedAt,
+ reason: row.reason ?? previous.reason,
+ reasonAt: row.reasonAt ?? previous.reasonAt,
+ };
+ }
+ rows.splice(0, rows.length, ...coalesced);
+}
+
+function rowContainsNarrationTime(
+ row: ActivityRow,
+ narrationTimestamp: string | undefined,
+): boolean {
+ const narrationMs = parseUtcIsoMs(narrationTimestamp);
+ if (narrationMs === null || row.entries.length === 0) return false;
+
+ const starts = row.entries
+ .flatMap((entry) => [entry.activityStartedAt, entry.timestamp])
+ .map(parseUtcIsoMs)
+ .filter((value): value is number => value !== null);
+ if (starts.length === 0) return false;
+
+ const startedMs = Math.min(...starts);
+ const endedMs = hasPendingToolCall(row.entries)
+ ? Infinity
+ : Math.max(...starts);
+ return narrationMs >= startedMs && narrationMs <= endedMs;
}
export function deriveActivityLog(turn: TurnNarrativeState): ActivityLog {
@@ -164,14 +299,47 @@ export function deriveActivityLog(turn: TurnNarrativeState): ActivityLog {
}
const kind = kindOf(entry);
const prev = rows[rows.length - 1];
- if (kind === "browse" && prev?.kind === "browse") {
- prev.entries.push(entry);
+ const previousEntry = prev?.entries[prev.entries.length - 1];
+ const previousEndedMs = parseUtcIsoMs(previousEntry?.timestamp);
+ const runStartedMs = parseUtcIsoMs(
+ entry.activityStartedAt ?? entry.timestamp,
+ );
+ const followsPreviousEntry =
+ previousEndedMs === null ||
+ runStartedMs === null ||
+ runStartedMs >= previousEndedMs;
+ // Successful and in-flight browse tools form one compact discovery row.
+ // A failed browse tool is its own recoverable attempt: folding it into the
+ // surrounding successes made an earlier successful action appear to fail,
+ // while folding multiple failures reused the wrong action title. Same-tool
+ // retries have already been condensed above and retain their attempt count.
+ if (
+ kind === "browse" &&
+ prev?.kind === "browse" &&
+ entry.success !== false &&
+ previousEntry?.success !== false
+ ) {
+ prev.entries.push(...retryEntries(entry));
+ continue;
+ }
+ // A block-scoped write and the run immediately following it are one user-
+ // facing build/test action. Keeping them on one frontier preserves the
+ // freshly written diff while the test is active instead of flashing the
+ // write row for a moment and collapsing it as soon as the run starts.
+ if (
+ kind === "run" &&
+ prev?.kind === "author" &&
+ followsPreviousEntry &&
+ prev.entries.some((candidate) => (candidate.codeDiffs?.length ?? 0) > 0)
+ ) {
+ prev.kind = "run";
+ prev.entries.push(...retryEntries(entry));
continue;
}
rows.push({
- id: toolCallIdOf(entry) || entry.id,
+ id: stableRowId(entry),
kind,
- entries: [entry],
+ entries: retryEntries(entry),
blocks: [],
codeDiffs: [],
pending: false,
@@ -183,35 +351,66 @@ export function deriveActivityLog(turn: TurnNarrativeState): ActivityLog {
});
}
- // Pair by iteration when the tag survived, else attach to the step the
- // narration followed: iteration is neither unique nor durable.
+ // Pair a narration to a result that chronology moved below it, then by the
+ // closest matching iteration, else to the step it followed. A pending row's
+ // open-ended time span is not an ownership claim: parallel calls commonly
+ // overlap, and an older unresolved call must not steal a sibling's prose.
for (const { entry, precedingRow } of narrations) {
// The owning row can sit either side of where the narration landed: a
// narration emitted mid-step precedes its own tool_result, while one
// emitted after a step follows it. Iteration also restarts each
// enforcement pass, so nearest-wins disambiguates a repeated number.
+ // Pairing a call/result whose narration arrived mid-flight moves its result
+ // after the narration. Only a later row can be that displaced owner. This
+ // narrow timestamp rule keeps "Reviewing…" with the inspection it describes
+ // without letting any older open-ended call capture unrelated narration.
let ownerIdx = -1;
- let bestDistance = Infinity;
- rows.forEach((row, i) => {
- if (!row.entries.some((e) => e.iteration === entry.iteration)) return;
- const distance = Math.abs(i - precedingRow);
- if (distance < bestDistance) {
- bestDistance = distance;
- ownerIdx = i;
+ const futureTimeOwners: number[] = [];
+ for (let i = precedingRow + 1; i < rows.length; i += 1) {
+ if (rowContainsNarrationTime(rows[i]!, entry.timestamp)) {
+ futureTimeOwners.push(i);
}
- });
+ }
+ if (futureTimeOwners.length === 1) {
+ ownerIdx = futureTimeOwners[0]!;
+ } else if (futureTimeOwners.length > 1) {
+ const matchingIteration = futureTimeOwners.filter((i) =>
+ rows[i]!.entries.some(
+ (candidate) => candidate.iteration === entry.iteration,
+ ),
+ );
+ if (matchingIteration.length === 1) {
+ ownerIdx = matchingIteration[0]!;
+ }
+ }
+ let bestDistance = Infinity;
+ if (ownerIdx === -1) {
+ rows.forEach((row, i) => {
+ if (!row.entries.some((e) => e.iteration === entry.iteration)) return;
+ const distance = Math.abs(i - precedingRow);
+ if (distance < bestDistance) {
+ bestDistance = distance;
+ ownerIdx = i;
+ }
+ });
+ }
const targetIdx = ownerIdx === -1 ? precedingRow : ownerIdx;
const target = rows[targetIdx];
if (target) {
target.reason = entry.text;
- // The reason tracks the latest narration, but the live title does not:
- // the first narration to reach a row names the work, and a later one
- // would rewrite a line the user is already reading. The outcome title
- // still comes from the latest narration, which is the one that knows how
- // the row ended.
+ // The reason tracks the latest narration, but the live title normally
+ // does not: the first narration to reach a row names the work, and a
+ // later one would rewrite a line the user is already reading. A combined
+ // write/test row is the exception because its current action genuinely
+ // advances from writing to testing while preserving one frontier.
const held = labelsByRow.get(targetIdx);
+ const combinedWriteAndRun =
+ target.kind === "run" &&
+ target.entries.some((candidate) => kindOf(candidate) === "author");
labelsByRow.set(targetIdx, {
- active: held?.active ?? entry.activeLabel,
+ active: combinedWriteAndRun
+ ? (entry.activeLabel ?? held?.active)
+ : (held?.active ?? entry.activeLabel),
outcome: entry.outcomeLabel ?? held?.outcome,
});
target.reasonAt = entry.receivedAtMs;
@@ -250,7 +449,7 @@ export function deriveActivityLog(turn: TurnNarrativeState): ActivityLog {
let liveIndex = -1;
rows.forEach((row) => {
const stamps = row.entries
- .map((e) => e.timestamp)
+ .flatMap((e) => [e.activityStartedAt, e.timestamp])
.filter((t): t is string => typeof t === "string")
.sort();
row.startedAt = stamps[0] ?? null;
@@ -262,6 +461,14 @@ export function deriveActivityLog(turn: TurnNarrativeState): ActivityLog {
for (const entry of row.entries) {
for (const diff of entry.codeDiffs ?? []) byLabel.set(diff.label, diff);
}
+ // A repair tool_call is bucketed under the block that is already running,
+ // not in designActivity. Its write-time diff still belongs to the block's
+ // frontier row and must be promoted before the later tool_result repeats it.
+ for (const block of row.blocks) {
+ for (const entry of block.activity) {
+ for (const diff of entry.codeDiffs ?? []) byLabel.set(diff.label, diff);
+ }
+ }
row.codeDiffs = [...byLabel.values()];
row.pending = hasPendingToolCall(row.entries);
row.live =
@@ -278,17 +485,84 @@ export function deriveActivityLog(turn: TurnNarrativeState): ActivityLog {
// liveIndex says: it is -1 on a terminated turn, and last-wins when two
// calls run in parallel. A step that never returned cannot show an outcome.
const working = row.pending || i === liveIndex;
+ // Outcome labels are predictions authored before the step resolves. When
+ // the attempt fails, keep the narrator's stable intent as the row title;
+ // the exact failure remains in the row detail instead of letting a stale
+ // success-shaped outcome replace what Copilot was trying to accomplish.
+ const terminalEntry = row.entries[row.entries.length - 1];
+ const cannotUsePredictedOutcome =
+ (terminalEntry?.kind === "tool_result" &&
+ terminalEntry.success === false) ||
+ row.blocks.some((block) => !isBlockOk(block));
row.label =
- (working ? tenses.active : (tenses.outcome ?? tenses.active)) ?? null;
+ (working || cannotUsePredictedOutcome
+ ? tenses.active
+ : (tenses.outcome ?? tenses.active)) ?? null;
+ });
+
+ // Narration names the user-facing activity; raw browser operations are its
+ // technical substeps. Until the narrator declares a new intent, keep those
+ // substeps under the current active label instead of flashing peer titles
+ // such as "Inspecting page" and "Opening page" between semantic labels.
+ let browseIntent: string | null = null;
+ const browseIntentByRow = new Map<ActivityRow, string>();
+ rows.forEach((row, i) => {
+ if (row.kind !== "browse") {
+ browseIntent = null;
+ return;
+ }
+ const active = labelsByRow.get(i)?.active;
+ if (active !== undefined) {
+ browseIntent = active;
+ } else if (browseIntent !== null) {
+ row.label = browseIntent;
+ }
+ if (browseIntent !== null) {
+ browseIntentByRow.set(row, browseIntent);
+ }
+ });
+
+ // Retries may switch browser tools while pursuing the same narrated intent.
+ // Tool-level condensation cannot recognize that as one activity, but the
+ // narrator's explicit active label can: adjacent failed attempts with the
+ // same label become one row. The first attempt keeps the stable row id so a
+ // user's expansion choice survives while later attempts update its status.
+ coalesceNarratedBrowseRetries(rows, browseIntentByRow);
+ liveIndex = -1;
+ rows.forEach((row, i) => {
+ row.pending = hasPendingToolCall(row.entries);
+ row.live =
+ !ended &&
+ (row.pending || row.blocks.some((block) => block.state === "running"));
+ if (row.live) liveIndex = i;
});
// While the model is generating, no row has an unmatched call and no block is
// running, so liveIndex is -1 and nothing would be open — the stretch that
- // reads as "one collapsed row and nothing going on". Rows only ever append,
- // so following the newest one keeps the freshest work open and moves forward
- // only, instead of hopping back to an earlier row when a parallel call
- // finishes and collapsing the row being read.
- const focusIndex = ended || rows.length === 0 ? -1 : rows.length - 1;
+ // reads as "one collapsed row and nothing going on". Follow the newest row in
+ // that gap. The one exception is a contentless draft placeholder appended
+ // after real live work: it describes what now exists, not what is happening,
+ // so it cannot hide the row carrying the active call or running block.
+ const newestIndex = rows.length - 1;
+ const newest = rows[newestIndex];
+ const newestIsEmptyDraft =
+ newest !== undefined &&
+ newest.entries.length === 0 &&
+ newest.codeDiffs.length === 0 &&
+ newest.reason === null &&
+ newest.blocks.length > 0 &&
+ newest.blocks.every(
+ (block) =>
+ block.state === "drafted" &&
+ block.activity.length === 0 &&
+ (block.recordedActions?.length ?? 0) === 0,
+ );
+ const focusIndex =
+ ended || rows.length === 0
+ ? -1
+ : liveIndex !== -1 && newestIsEmptyDraft
+ ? liveIndex
+ : newestIndex;
return { rows, liveIndex, focusIndex };
}
diff --git a/skyvern-frontend/src/routes/workflows/copilot/narrativeState.ts b/skyvern-frontend/src/routes/workflows/copilot/narrativeState.ts
index 049d31d26..20c29ba47 100644
--- a/skyvern-frontend/src/routes/workflows/copilot/narrativeState.ts
+++ b/skyvern-frontend/src/routes/workflows/copilot/narrativeState.ts
@@ -242,6 +242,16 @@ export interface ActivityEntry {
// Consecutive same-tool retries folded into this row by
// condenseActivityEntries. Unset outside that transform.
attempts?: number;
+ // First-attempt identity for the reader-visible retry row. The current
+ // entry keeps its real event id for correlation.
+ retryRootId?: string;
+ // Exact failed attempts hidden by retry condensation, retained for the
+ // expanded evidence view.
+ priorFailures?: ActivityEntry[];
+ // Server timestamp of the first call represented by this condensed entry.
+ // A settled tool_result otherwise retains only its completion timestamp,
+ // which makes real multi-second work render as 0:00.
+ activityStartedAt?: string;
// Server clock read for this event, persisted so a hydrated turn reports the
// same elapsed as the live one. Undefined against a backend that does not stamp.
timestamp?: string;
@@ -730,11 +740,19 @@ export function condenseActivityEntries(
const idx = id !== undefined ? callIndexById.get(id) : undefined;
if (idx !== undefined) {
callIndexById.delete(id!);
+ const call = paired[idx];
+ const settled =
+ call?.timestamp === undefined
+ ? entry
+ : {
+ ...entry,
+ activityStartedAt: call.activityStartedAt ?? call.timestamp,
+ };
if (idx === paired.length - 1) {
- paired[idx] = entry;
+ paired[idx] = settled;
} else {
paired[idx] = null;
- paired.push(entry);
+ paired.push(settled);
}
} else {
// Its tool_call was evicted past the activity cap — keep the
@@ -751,6 +769,14 @@ export function condenseActivityEntries(
let lastToolIdx = -1;
for (const entry of ordered) {
const prevTool = lastToolIdx >= 0 ? condensed[lastToolIdx] : undefined;
+ const previousEndedMs = parseUtcIsoMs(prevTool?.timestamp);
+ const currentStartedMs = parseUtcIsoMs(
+ entry.activityStartedAt ?? entry.timestamp,
+ );
+ const followsPreviousAttempt =
+ previousEndedMs === null ||
+ currentStartedMs === null ||
+ currentStartedMs >= previousEndedMs;
if (
prevTool &&
entry.toolName !== undefined &&
@@ -758,13 +784,24 @@ export function condenseActivityEntries(
(prevTool.displayLabel === undefined ||
entry.displayLabel === undefined ||
prevTool.displayLabel === entry.displayLabel) &&
- prevTool.success === false
+ prevTool.success === false &&
+ followsPreviousAttempt
) {
+ const { priorFailures: earlierFailures, ...previousAttempt } = prevTool;
condensed[lastToolIdx] = null;
lastToolIdx =
condensed.push({
...entry,
+ retryRootId: prevTool.retryRootId ?? prevTool.id,
+ priorFailures: [
+ ...(earlierFailures ?? []),
+ previousAttempt as ActivityEntry,
+ ],
attempts: (prevTool.attempts ?? 1) + 1,
+ activityStartedAt:
+ prevTool.activityStartedAt ??
+ prevTool.timestamp ??
+ entry.activityStartedAt,
}) - 1;
continue;
}
@@ -783,6 +820,12 @@ function appendCapped<T>(arr: T[], entry: T, cap: number): T[] {
return next.length > cap ? next.slice(next.length - cap) : next;
}
+function findActivityBlockIndex(blocks: BlockState[], entryId: string): number {
+ return blocks.findIndex((block) =>
+ block.activity.some((entry) => entry.id === entryId),
+ );
+}
+
function appendActivity(
blocks: BlockState[],
designActivity: ActivityEntry[],
@@ -820,9 +863,7 @@ function appendActivity(
),
};
}
- const callBlockIdx = blocks.findIndex((b) =>
- b.activity.some((e) => e.id === callId),
- );
+ const callBlockIdx = findActivityBlockIndex(blocks, callId);
if (callBlockIdx !== -1) {
const nextBlocks = blocks.slice();
const callBlock = nextBlocks[callBlockIdx]!;
@@ -853,6 +894,38 @@ function appendActivity(
return { blocks: nextBlocks, designActivity };
}
+function attachCodeDiffsToActivity(
+ blocks: BlockState[],
+ designActivity: ActivityEntry[],
+ targetId: string,
+ codeDiffs: CodeWriteDiff[],
+): { blocks: BlockState[]; designActivity: ActivityEntry[] } {
+ const designIndex = designActivity.findIndex(
+ (entry) => entry.id === targetId,
+ );
+ if (designIndex !== -1) {
+ const nextDesignActivity = designActivity.slice();
+ nextDesignActivity[designIndex] = {
+ ...nextDesignActivity[designIndex]!,
+ codeDiffs,
+ };
+ return { blocks, designActivity: nextDesignActivity };
+ }
+
+ const blockIndex = findActivityBlockIndex(blocks, targetId);
+ if (blockIndex === -1) return { blocks, designActivity };
+
+ const nextBlocks = blocks.slice();
+ const block = nextBlocks[blockIndex]!;
+ const activityIndex = block.activity.findIndex(
+ (entry) => entry.id === targetId,
+ );
+ const activity = block.activity.slice();
+ activity[activityIndex] = { ...activity[activityIndex]!, codeDiffs };
+ nextBlocks[blockIndex] = { ...block, activity };
+ return { blocks: nextBlocks, designActivity };
+}
+
export function mapBlockStatus(raw: string): BlockUIState {
switch (raw) {
case "running":
@@ -957,11 +1030,12 @@ export function applyNarrativeEvent(
event.tool_call_id == null ? null : `tc-${event.tool_call_id}`;
const withDiffs =
draftDiffs === undefined || diffTarget === null
- ? prev.designActivity
- : prev.designActivity.map((entry) =>
- entry.id === diffTarget
- ? { ...entry, codeDiffs: draftDiffs }
- : entry,
+ ? { blocks: nextBlocks, designActivity: prev.designActivity }
+ : attachCodeDiffsToActivity(
+ nextBlocks,
+ prev.designActivity,
+ diffTarget,
+ draftDiffs,
);
return {
@@ -971,8 +1045,8 @@ export function applyNarrativeEvent(
blockLabels: event.block_labels,
summary: event.summary,
},
- blocks: nextBlocks,
- designActivity: withDiffs,
+ blocks: withDiffs.blocks,
+ designActivity: withDiffs.designActivity,
};
}
@@ -1737,15 +1811,14 @@ function adjudicatedSummaryParts(
hasDrafts: boolean;
hasCleanCompletedBuild: boolean;
},
- uxV1 = false,
): AdjudicatedParts | null {
if (turn.responseKind === null) return null;
// Disposition-first (rule A): a pending draft review outranks why the turn
// ended, regardless of responseKind (including non-build/clarify turns).
- if (uxV1 && flags.needsUntestedProposalReview) {
+ if (flags.needsUntestedProposalReview) {
return { headline: "Draft needs review", accent: "qa", glyph: "!" };
}
- if (uxV1 && flags.needsTestedProposalReview) {
+ if (flags.needsTestedProposalReview) {
return { headline: "Workflow ready for review", accent: "qa", glyph: "!" };
}
if (turn.responseKind !== "build") {
@@ -1762,7 +1835,7 @@ function adjudicatedSummaryParts(
return { headline: "Outcome not confirmed", accent: "warn", glyph: "!" };
}
return {
- headline: uxV1 ? "Needs your input" : "Question",
+ headline: "Needs your input",
accent: "qa",
glyph: "✦",
};
@@ -1775,7 +1848,7 @@ function adjudicatedSummaryParts(
}
if (turn.responseType === "ASK_QUESTION") {
return {
- headline: uxV1 ? "Needs your input" : "Question",
+ headline: "Needs your input",
accent: "qa",
glyph: "✦",
};
@@ -1783,11 +1856,7 @@ function adjudicatedSummaryParts(
return null;
}
-export function computeTurnSummary(
- turn: TurnNarrativeState,
- opts: { uxV1?: boolean } = {},
-): TurnSummary {
- const uxV1 = opts.uxV1 ?? false;
+export function computeTurnSummary(turn: TurnNarrativeState): TurnSummary {
const rollupBlocks = latestBlocksByLabel(turn.blocks);
// A cancelled turn's terminal is "error" purely because the user stopped it,
// so that arm must not brand their own stop a failure.
@@ -1830,17 +1899,13 @@ export function computeTurnSummary(
const adjudicated =
isStoppedWithDraft || isFail || isStopped
? null
- : adjudicatedSummaryParts(
- turn,
- {
- needsUntestedProposalReview,
- needsTestedProposalReview,
- hasEdited,
- hasDrafts,
- hasCleanCompletedBuild,
- },
- uxV1,
- );
+ : adjudicatedSummaryParts(turn, {
+ needsUntestedProposalReview,
+ needsTestedProposalReview,
+ hasEdited,
+ hasDrafts,
+ hasCleanCompletedBuild,
+ });
const headline = adjudicated
? adjudicated.headline
@@ -1850,41 +1915,23 @@ export function computeTurnSummary(
? "Run halted"
: isStopped
? "Stopped"
- : uxV1
- ? needsUntestedProposalReview
- ? "Draft needs review"
- : needsTestedProposalReview
- ? "Workflow ready for review"
- : needsInput
- ? "Needs your input"
- : isQA
- ? mode === "refuse"
- ? "Declined"
- : mode === "clarify"
- ? "Needs your input"
- : "Answered"
- : hasEdited
- ? "Applied edits and re-tested"
- : hasDrafts
- ? "Built and tested the workflow"
- : "Completed the run"
- : needsInput
- ? "Question"
- : needsUntestedProposalReview
- ? "Draft needs review"
- : needsTestedProposalReview
- ? "Workflow ready for review"
- : isQA
- ? mode === "refuse"
- ? "Declined"
- : mode === "clarify"
- ? "Question"
- : "Answered"
- : hasEdited
- ? "Applied edits and re-tested"
- : hasDrafts
- ? "Built and tested the workflow"
- : "Completed the run";
+ : needsUntestedProposalReview
+ ? "Draft needs review"
+ : needsTestedProposalReview
+ ? "Workflow ready for review"
+ : needsInput
+ ? "Needs your input"
+ : isQA
+ ? mode === "refuse"
+ ? "Declined"
+ : mode === "clarify"
+ ? "Needs your input"
+ : "Answered"
+ : hasEdited
+ ? "Applied edits and re-tested"
+ : hasDrafts
+ ? "Built and tested the workflow"
+ : "Completed the run";
const stats: string[] = [];
const turnElapsed = formatElapsed(turn.startedAt, turn.endedAt);
diff --git a/skyvern-frontend/src/routes/workflows/editor/Workspace.tsx b/skyvern-frontend/src/routes/workflows/editor/Workspace.tsx
index 2279d7370..585f93849 100644
--- a/skyvern-frontend/src/routes/workflows/editor/Workspace.tsx
+++ b/skyvern-frontend/src/routes/workflows/editor/Workspace.tsx
@@ -33,7 +33,7 @@ import {
Edge,
} from "@xyflow/react";
import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
-import { useFeatureFlagEnabled, usePostHog } from "posthog-js/react";
+import { usePostHog } from "posthog-js/react";
import {
useWorkflowYamlEditorStore,
@@ -49,11 +49,6 @@ import { useActiveRunSessionQuery } from "../hooks/useActiveRunSessionQuery";
import { useDebugSessionQuery } from "../hooks/useDebugSessionQuery";
import { useIsGlobalWorkflow } from "../hooks/useIsGlobalWorkflow";
import { resolveWorkspaceBrowserSessionBindings } from "./browserSessionBindings";
-import {
- resolveBrowserPanelMode,
- resolveCdpRecordingExfiltrate,
- updateBrowserPanelLatch,
-} from "./browserPanelMode";
import { useBlockScriptsQuery } from "@/routes/workflows/hooks/useBlockScriptsQuery";
import { BrowserSessionStream } from "@/routes/browserSessions/BrowserSessionStream";
import { useStreamTransport } from "@/hooks/useRuntimeConfig";
@@ -132,8 +127,6 @@ import { isMacPlatform } from "@/util/platform";
import { parseHeaderJson } from "@/util/secretHeaders";
import { getJsonParseErrorDetail } from "@/util/jsonParseError";
import { cn } from "@/util/utils";
-import { RECORD_BROWSER_CDP_TRANSPORT_FLAG } from "@/util/featureFlags";
-
import { FlowRenderer, type FlowRendererProps } from "./FlowRenderer";
import { useCacheKeyValueUrlSync } from "./hooks/useCacheKeyValueUrlSync";
import {
@@ -820,37 +813,10 @@ function Workspace({
const { streamTransport } = useStreamTransport(
activeDebugSession?.browser_session_id,
);
- const cdpRecordingFlagEnabled =
- useFeatureFlagEnabled(RECORD_BROWSER_CDP_TRANSPORT_FLAG) ?? false;
- const browserPanelLatchRef = useRef({
- streamTransport,
- cdpRecordingEnabled: cdpRecordingFlagEnabled,
- });
- browserPanelLatchRef.current = updateBrowserPanelLatch(
- browserPanelLatchRef.current,
- {
- streamTransport,
- cdpRecordingEnabled: cdpRecordingFlagEnabled,
- },
- recordingStore.isRecording,
- );
- const { streamTransport: latchedStreamTransport, cdpRecordingEnabled } =
- browserPanelLatchRef.current;
- // Keep the panel mode stable if transport resolution or PostHog changes mid-recording.
- const { showCdp: isCdpStreamingMode, preferVnc: preferVncStream } =
- resolveBrowserPanelMode({
- streamTransport: latchedStreamTransport,
- isRecording: recordingStore.isRecording,
- cdpRecordingEnabled,
- });
- const recordingTransport =
- showBrowser && latchedStreamTransport === "cdp" && cdpRecordingEnabled
- ? "cdp"
- : "vnc";
- const setRecordingTransport = recordingStore.setRecordingTransport;
- useLayoutEffect(() => {
- setRecordingTransport(recordingTransport);
- }, [setRecordingTransport, recordingTransport]);
+ // Recording stays on the session's own transport: a cdp-transport session is one
+ // with no relayable RFB endpoint, so swapping to VNC to record kills the view.
+ const isCdpStreamingMode = streamTransport === "cdp";
+ const preferVncStream = streamTransport !== "cdp";
const workflowChangesStore = useWorkflowHasChangesStore();
@@ -870,11 +836,11 @@ function Workspace({
(!activeDebugSession || activeDebugSession.vnc_streaming_supported);
const showCdpBrowserPanel =
isCdpStreamingMode && shouldFetchDebugSession && !isRateLimited;
- // Recording is session-scoped: the stream opts out of reset-on-unmount (it
- // remounts across the CDP<->VNC recording swap mid-session), so the debug
- // session owns the reset here — embedded, StudioBrowserStream owns it. The id
- // guard keeps the null -> first-id transition from clearing a recording that
- // started before the session resolved.
+ // Recording is session-scoped: the stream opts out of reset-on-unmount (it can
+ // remount while the session persists), so the debug session owns the reset
+ // here — embedded, StudioBrowserStream owns it. The id guard keeps the
+ // null -> first-id transition from clearing a recording that started before
+ // the session resolved.
useEffect(() => {
if (embedded || !debugBrowserSessionId) {
return;
@@ -2730,12 +2696,6 @@ function Workspace({
) : isFlowCanvasReady || recordingStore.isRecording ? (
<BrowserSessionStream
browserSessionId={displayBrowserSessionId}
- exfiltrate={resolveCdpRecordingExfiltrate({
- cdpRecordingEnabled,
- isRecording: recordingStore.isRecording,
- finishRequested: recordingStore.finishRequested,
- })}
- workflowPermanentId={workflowPermanentId ?? null}
interactive={true}
showControlButtons={true}
// The CDP transport streams the page viewport only, so
@@ -2743,6 +2703,14 @@ function Workspace({
// to type into and a session resting on about:blank has
// no way out (SKY-13705).
enableUrlInput={true}
+ // undefined keeps the recording message channel closed on
+ // the non-recording live view; a defined value opens it.
+ exfiltrate={
+ recordingStore.isRecording
+ ? !recordingStore.finishRequested
+ : undefined
+ }
+ workflowPermanentId={workflowPermanentId ?? null}
onReadyChange={handleLiveBrowserReadyChange}
/>
) : (
diff --git a/skyvern-frontend/src/routes/workflows/editor/browserPanelMode.test.ts b/skyvern-frontend/src/routes/workflows/editor/browserPanelMode.test.ts
deleted file mode 100644
index 20cc65025..000000000
--- a/skyvern-frontend/src/routes/workflows/editor/browserPanelMode.test.ts
+++ /dev/null
@@ -1,90 +0,0 @@
-import { describe, expect, it } from "vitest";
-
-import {
- resolveBrowserPanelMode,
- resolveCdpRecordingExfiltrate,
- updateBrowserPanelLatch,
-} from "./browserPanelMode";
-
-describe("resolveBrowserPanelMode", () => {
- it("downgrades a flag-off CDP recording to VNC", () => {
- expect(
- resolveBrowserPanelMode({
- streamTransport: "cdp",
- isRecording: true,
- cdpRecordingEnabled: false,
- }),
- ).toEqual({ showCdp: false, preferVnc: true });
- });
-
- it("keeps a flag-on CDP recording on CDP", () => {
- expect(
- resolveBrowserPanelMode({
- streamTransport: "cdp",
- isRecording: true,
- cdpRecordingEnabled: true,
- }),
- ).toEqual({ showCdp: true, preferVnc: false });
- });
-
- it("prefers VNC while the transport is pending", () => {
- expect(
- resolveBrowserPanelMode({
- streamTransport: undefined,
- isRecording: false,
- cdpRecordingEnabled: true,
- }),
- ).toEqual({ showCdp: false, preferVnc: true });
- });
-});
-
-describe("updateBrowserPanelLatch", () => {
- it("keeps a pending transport from switching to CDP mid-recording", () => {
- const latch = {
- streamTransport: undefined,
- cdpRecordingEnabled: true,
- } as const;
-
- const duringRecording = updateBrowserPanelLatch(
- latch,
- {
- streamTransport: "cdp",
- cdpRecordingEnabled: true,
- },
- true,
- );
- expect(
- resolveBrowserPanelMode({
- ...duringRecording,
- isRecording: true,
- }),
- ).toEqual({ showCdp: false, preferVnc: true });
-
- const afterRecording = updateBrowserPanelLatch(
- duringRecording,
- {
- streamTransport: "cdp",
- cdpRecordingEnabled: true,
- },
- false,
- );
- expect(
- resolveBrowserPanelMode({
- ...afterRecording,
- isRecording: false,
- }),
- ).toEqual({ showCdp: true, preferVnc: false });
- });
-});
-
-describe("resolveCdpRecordingExfiltrate", () => {
- it("leaves CDP recording messages disabled while the flag is off", () => {
- expect(
- resolveCdpRecordingExfiltrate({
- cdpRecordingEnabled: false,
- isRecording: true,
- finishRequested: false,
- }),
- ).toBeUndefined();
- });
-});
diff --git a/skyvern-frontend/src/routes/workflows/editor/browserPanelMode.ts b/skyvern-frontend/src/routes/workflows/editor/browserPanelMode.ts
deleted file mode 100644
index 77110856b..000000000
--- a/skyvern-frontend/src/routes/workflows/editor/browserPanelMode.ts
+++ /dev/null
@@ -1,42 +0,0 @@
-import type { BrowserStreamingMode } from "@/hooks/useRuntimeConfig";
-
-export interface BrowserPanelLatch {
- streamTransport: BrowserStreamingMode | undefined;
- cdpRecordingEnabled: boolean;
-}
-
-export function updateBrowserPanelLatch(
- latched: BrowserPanelLatch,
- current: BrowserPanelLatch,
- isRecording: boolean,
-): BrowserPanelLatch {
- return isRecording ? latched : current;
-}
-
-export function resolveCdpRecordingExfiltrate({
- cdpRecordingEnabled,
- isRecording,
- finishRequested,
-}: {
- cdpRecordingEnabled: boolean;
- isRecording: boolean;
- finishRequested: boolean;
-}): boolean | undefined {
- return cdpRecordingEnabled ? isRecording && !finishRequested : undefined;
-}
-
-export function resolveBrowserPanelMode({
- streamTransport,
- isRecording,
- cdpRecordingEnabled,
-}: {
- streamTransport: BrowserStreamingMode | undefined;
- isRecording: boolean;
- cdpRecordingEnabled: boolean;
-}): { showCdp: boolean; preferVnc: boolean } {
- return {
- showCdp: streamTransport === "cdp" && (cdpRecordingEnabled || !isRecording),
- preferVnc:
- streamTransport !== "cdp" || (!cdpRecordingEnabled && isRecording),
- };
-}
diff --git a/skyvern-frontend/src/routes/workflows/hooks/useCreateWorkflowMutation.test.tsx b/skyvern-frontend/src/routes/workflows/hooks/useCreateWorkflowMutation.test.tsx
index 67a48be9a..70997caaa 100644
--- a/skyvern-frontend/src/routes/workflows/hooks/useCreateWorkflowMutation.test.tsx
+++ b/skyvern-frontend/src/routes/workflows/hooks/useCreateWorkflowMutation.test.tsx
@@ -57,7 +57,7 @@ describe("useCreateWorkflowMutation", () => {
});
await waitFor(() => expect(result.current.isSuccess).toBe(true));
- expect(OnboardingTelemetry.flowCompleted).toHaveBeenCalledWith("dashboard");
+ expect(OnboardingTelemetry.flowCompleted).toHaveBeenCalledWith("discover");
});
it("does not emit flow_completed for non-onboarding creations", async () => {
diff --git a/skyvern-frontend/src/routes/workflows/hooks/useCreateWorkflowMutation.ts b/skyvern-frontend/src/routes/workflows/hooks/useCreateWorkflowMutation.ts
index 58cf1a149..3695fa643 100644
--- a/skyvern-frontend/src/routes/workflows/hooks/useCreateWorkflowMutation.ts
+++ b/skyvern-frontend/src/routes/workflows/hooks/useCreateWorkflowMutation.ts
@@ -65,7 +65,7 @@ function useCreateWorkflowMutation() {
// this navigation unmounts the onboarding modal, and React Query skips
// mutate-level callbacks once their observer unmounts.
if (via === "onboarding_template") {
- OnboardingTelemetry.flowCompleted("dashboard");
+ OnboardingTelemetry.flowCompleted("discover");
}
const search = via ? `?via=${encodeURIComponent(via)}` : "";
navigate(
diff --git a/skyvern-frontend/src/routes/workflows/hooks/useRefreshOnboardingOnRunCompletion.test.tsx b/skyvern-frontend/src/routes/workflows/hooks/useRefreshOnboardingOnRunCompletion.test.tsx
index 7113eb375..25dc8341b 100644
--- a/skyvern-frontend/src/routes/workflows/hooks/useRefreshOnboardingOnRunCompletion.test.tsx
+++ b/skyvern-frontend/src/routes/workflows/hooks/useRefreshOnboardingOnRunCompletion.test.tsx
@@ -13,8 +13,12 @@ import type {
RecoveryGuidanceAssignment,
} from "@/store/onboarding/types";
import { useRefreshOnboardingOnRunCompletion } from "./useRefreshOnboardingOnRunCompletion";
+vi.mock("@clerk/clerk-react", () => ({
+ useAuth: () => ({ userId: "user-a" }),
+}));
-const ONBOARDING_KEY = { queryKey: ["userOnboarding"] };
+const ONBOARDING_KEY = { queryKey: ["userOnboarding", "user-a"] };
+const ONBOARDING_PREFIX = { queryKey: ["userOnboarding"] };
const RUN_ID = "wr_1";
function run(status: Status, workflowRunId = RUN_ID) {
@@ -84,7 +88,7 @@ function makeRaceWrapper(firstAssignment: RecoveryGuidanceAssignment | null) {
function onboardingInvalidations(spy: ReturnType<typeof vi.spyOn>): number {
return spy.mock.calls.filter(
(call: unknown[]) =>
- JSON.stringify(call[0]) === JSON.stringify(ONBOARDING_KEY),
+ JSON.stringify(call[0]) === JSON.stringify(ONBOARDING_PREFIX),
).length;
}
diff --git a/skyvern-frontend/src/routes/workflows/hooks/useRefreshOnboardingOnRunCompletion.ts b/skyvern-frontend/src/routes/workflows/hooks/useRefreshOnboardingOnRunCompletion.ts
index 00cecb129..a53d5de5f 100644
--- a/skyvern-frontend/src/routes/workflows/hooks/useRefreshOnboardingOnRunCompletion.ts
+++ b/skyvern-frontend/src/routes/workflows/hooks/useRefreshOnboardingOnRunCompletion.ts
@@ -1,4 +1,5 @@
import { useEffect, useRef } from "react";
+import { useAuth } from "@clerk/clerk-react";
import { useQueryClient } from "@tanstack/react-query";
import { Status } from "@/api/types";
import { statusIsFinalized } from "@/routes/tasks/types";
@@ -15,6 +16,7 @@ function useRefreshOnboardingOnRunCompletion(
workflowRun: RunLike | undefined,
): void {
const queryClient = useQueryClient();
+ const { userId } = useAuth();
const refreshedRunRef = useRef<string | null>(null);
const retryTimeoutRef = useRef<number | undefined>(undefined);
const retriedMissingAssignmentRef = useRef(false);
@@ -53,6 +55,7 @@ function useRefreshOnboardingOnRunCompletion(
}
const assignment = queryClient.getQueryData<OnboardingStateResponse>([
"userOnboarding",
+ userId,
])?.recovery_guidance_assignment;
if (assignment?.eligible_run_id === runId) {
return;
@@ -66,7 +69,7 @@ function useRefreshOnboardingOnRunCompletion(
void queryClient.invalidateQueries({ queryKey: ["userOnboarding"] });
}, 4_000);
});
- }, [workflowRun, queryClient]);
+ }, [workflowRun, queryClient, userId]);
}
export { useRefreshOnboardingOnRunCompletion };
diff --git a/skyvern-frontend/src/routes/workflows/studio/RunTab.tsx b/skyvern-frontend/src/routes/workflows/studio/RunTab.tsx
index fcf3e57b0..d5d854a0e 100644
--- a/skyvern-frontend/src/routes/workflows/studio/RunTab.tsx
+++ b/skyvern-frontend/src/routes/workflows/studio/RunTab.tsx
@@ -29,18 +29,20 @@ export function RunTab() {
// ?bl= marks a block-scoped run; "Retry" would rerun the whole workflow,
// so suppress that CTA for block runs (the block is rerun from the editor).
const isBlockRun = searchParams.has("bl");
+ const retryPath = `/agents/${workflowPermanentId}/run`;
+ const retryState =
+ workflowRun &&
+ workflowRun.workflow_run_id === runId &&
+ statusIsFinalized(workflowRun) &&
+ workflowRun.task_v2 === null
+ ? getRerunNavigationState(workflowRun)
+ : undefined;
const retryRun = () => {
- const path = `/agents/${workflowPermanentId}/run`;
- if (
- workflowRun &&
- workflowRun.workflow_run_id === runId &&
- statusIsFinalized(workflowRun) &&
- workflowRun.task_v2 === null
- ) {
- navigate(path, { state: getRerunNavigationState(workflowRun) });
+ if (retryState) {
+ navigate(retryPath, { state: retryState });
return;
}
- navigate(path);
+ navigate(retryPath);
};
return (
@@ -62,6 +64,11 @@ export function RunTab() {
}
}
onRetry={isBlockRun || workflowDeleted ? undefined : retryRun}
+ milestoneRerun={
+ isBlockRun || workflowDeleted
+ ? undefined
+ : { to: retryPath, state: retryState }
+ }
/>
);
}
diff --git a/skyvern-frontend/src/routes/workflows/studio/StreamPresenter.test.tsx b/skyvern-frontend/src/routes/workflows/studio/StreamPresenter.test.tsx
index bfe44ef6a..86a95d6cf 100644
--- a/skyvern-frontend/src/routes/workflows/studio/StreamPresenter.test.tsx
+++ b/skyvern-frontend/src/routes/workflows/studio/StreamPresenter.test.tsx
@@ -95,51 +95,58 @@ describe("StreamPresenter transport-swap recording", () => {
expect(screen.queryByTestId("vnc-stream")).toBeNull();
});
- it("keeps the recording message channel closed on the non-recording CDP live view", () => {
- // BrowserSessionStream opens its recording WebSocket whenever exfiltrate is
- // defined, so the idle live view must pass undefined, not false.
- render(<StreamPresenter browserSessionId="pbs_test" isRecording={false} />);
- expect(cdpStreamProps.last?.exfiltrate).toBeUndefined();
+ it("opts the VNC stream out of the unmount reset while recording", () => {
+ runtimeConfigMock.browserStreamingMode = "vnc";
+ render(<StreamPresenter browserSessionId="pbs_test" isRecording />);
+ expect(screen.queryByTestId("vnc-stream")).not.toBeNull();
+ expect(browserStreamProps.last?.resetRecordingOnUnmount).toBe(false);
});
+});
- it("keeps the CDP stream and drives exfiltration through it when recording starts on cdp transport", () => {
- // A CDP-transport session has no reachable VNC endpoint: swapping to VNC on
- // record killed the live view and hammered the API with reconnects.
+describe("StreamPresenter recording on a cdp-transport session", () => {
+ afterEach(() => {
+ cleanup();
+ browserStreamProps.last = null;
+ cdpStreamProps.last = null;
+ runtimeConfigMock.browserStreamingMode = "cdp";
+ runtimeConfigMock.transportPending = false;
+ useRecordingStore.getState().reset();
+ });
+
+ it("keeps the CDP stream and drives exfiltration through it when recording starts", () => {
+ // A cdp-transport session is one with no relayable RFB endpoint (a vendor
+ // browser). Swapping it to VNC on record tore down the only working stream
+ // and left the viewer dead while the API took a reconnect storm.
useRecordingStore
.getState()
.setIsRecording(true, { workflowPermanentId: "wpid_test" });
- const { rerender } = render(
- <StreamPresenter browserSessionId="pbs_test" isRecording={false} />,
- );
- expect(screen.queryByTestId("recording-pill")).toBeNull();
- rerender(<StreamPresenter browserSessionId="pbs_test" isRecording />);
+ render(<StreamPresenter browserSessionId="pbs_test" isRecording />);
+
expect(screen.queryByTestId("cdp-stream")).not.toBeNull();
expect(screen.queryByTestId("vnc-stream")).toBeNull();
expect(cdpStreamProps.last?.exfiltrate).toBe(true);
expect(cdpStreamProps.last?.workflowPermanentId).toBe("wpid_test");
- expect(screen.queryByTestId("recording-pill")).not.toBeNull();
});
- it("hides the CDP recording pill when the caller shows its own indicator", () => {
- useRecordingStore
- .getState()
- .setIsRecording(true, { workflowPermanentId: "wpid_test" });
- render(
- <StreamPresenter
- browserSessionId="pbs_test"
- isRecording
- hideRecordingIndicator
- />,
- );
- expect(screen.queryByTestId("recording-pill")).toBeNull();
+ it("keeps the recording message channel closed on the idle live view", () => {
+ // BrowserSessionStream opens its recording WebSocket whenever exfiltrate is
+ // defined, so the non-recording view must pass undefined, not false.
+ render(<StreamPresenter browserSessionId="pbs_test" isRecording={false} />);
+ expect(cdpStreamProps.last?.exfiltrate).toBeUndefined();
});
- it("records over the VNC stream, opted out of the unmount reset, on vnc transport", () => {
+ it("labels the recording with the transport it actually rode", () => {
+ // useProcessRecordingMutation reports store.recordingTransport to the backend;
+ // with nothing setting it, every CDP recording was mislabelled as vnc.
+ render(<StreamPresenter browserSessionId="pbs_test" />);
+ expect(useRecordingStore.getState().recordingTransport).toBe("cdp");
+ });
+
+ it("still records over VNC on a vnc-transport session", () => {
runtimeConfigMock.browserStreamingMode = "vnc";
render(<StreamPresenter browserSessionId="pbs_test" isRecording />);
expect(screen.queryByTestId("vnc-stream")).not.toBeNull();
expect(screen.queryByTestId("cdp-stream")).toBeNull();
- expect(browserStreamProps.last?.resetRecordingOnUnmount).toBe(false);
});
});
diff --git a/skyvern-frontend/src/routes/workflows/studio/StreamPresenter.tsx b/skyvern-frontend/src/routes/workflows/studio/StreamPresenter.tsx
index d2d31415b..d4add4347 100644
--- a/skyvern-frontend/src/routes/workflows/studio/StreamPresenter.tsx
+++ b/skyvern-frontend/src/routes/workflows/studio/StreamPresenter.tsx
@@ -23,9 +23,11 @@ type StreamPresenterProps = {
/**
* Transport-agnostic live browser stream: picks VNC vs CDP from runtime config.
- * Recording stays on the session's own transport — a CDP-transport session has
- * no reachable VNC endpoint, so swapping to VNC for recording kills the view;
- * exfiltration only needs the messages channel, which both transports carry.
+ * Recording stays on whichever transport the session already serves. Vendor
+ * sessions reach cdp precisely because they expose no relayable RFB endpoint, so
+ * swapping them to VNC to record killed the only stream they had; deployments
+ * that set BROWSER_STREAMING_MODE=cdp land here too and record over CDP the same
+ * way, whether or not their pods also run a VNC server.
*/
export function StreamPresenter({
browserSessionId,
@@ -92,7 +94,7 @@ export function StreamPresenter({
showControlButtons={showControlButtons}
exfiltrate={isRecording}
hideRecordingIndicator={hideRecordingIndicator}
- // StrictMode remounts this component; the recording must survive those.
+ // StrictMode remounts this component; the recording must survive that.
// StudioBrowserStream owns the session-level reset instead.
resetRecordingOnUnmount={false}
onActivity={onActivity}
diff --git a/skyvern-frontend/src/routes/workflows/studio/runview/RunView.test.tsx b/skyvern-frontend/src/routes/workflows/studio/runview/RunView.test.tsx
index 009eba2cf..56ff9fe46 100644
--- a/skyvern-frontend/src/routes/workflows/studio/runview/RunView.test.tsx
+++ b/skyvern-frontend/src/routes/workflows/studio/runview/RunView.test.tsx
@@ -2,6 +2,7 @@
import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
import {
+ act,
cleanup,
fireEvent,
render,
@@ -20,6 +21,7 @@ import { type ReactNode } from "react";
import { ActionTypes, Status, type ActionsApiResponse } from "@/api/types";
import { TooltipProvider } from "@/components/ui/tooltip";
+import { PageSlotsProvider, type PageSlots } from "@/store/PageSlots";
import { useRunPaneViewStore } from "@/store/useRunPaneViewStore";
import { useRunViewStore } from "@/store/RunViewStore";
import { useStudioBrowserStore } from "@/store/useStudioBrowserStore";
@@ -274,6 +276,7 @@ function renderRunView(
initialEntry = "/",
compact = false,
extra?: ReactNode,
+ pageSlots: PageSlots = {},
) {
const queryClient = new QueryClient({
defaultOptions: { queries: { retry: false } },
@@ -282,29 +285,31 @@ function renderRunView(
// component instances (and the MemoryRouter's URL state) are preserved.
const makeUi = () => (
<QueryClientProvider client={queryClient}>
- <MemoryRouter initialEntries={[initialEntry]}>
- {/* The toggles live in the pane header (StudioShell); render them
- alongside the body, under a TooltipProvider, the way the shell
- composes them. Only headerExtras (the toggles) sit under the
- compact context in production (StudioShell.tsx), not the body. */}
- <TooltipProvider delayDuration={0}>
- <StudioPaneCompactContext.Provider value={compact}>
- <RunPaneViewToggles />
- </StudioPaneCompactContext.Provider>
- {initialEntry.startsWith("/runs/") ? (
- <Routes>
- <Route
- path="/runs/:runId"
- element={<RunView workflowRunId="wr_1" {...props} />}
- />
- </Routes>
- ) : (
- <RunView workflowRunId="wr_1" {...props} />
- )}
- </TooltipProvider>
- <LocationSpy />
- {extra}
- </MemoryRouter>
+ <PageSlotsProvider value={pageSlots}>
+ <MemoryRouter initialEntries={[initialEntry]}>
+ {/* The toggles live in the pane header (StudioShell); render them
+ alongside the body, under a TooltipProvider, the way the shell
+ composes them. Only headerExtras (the toggles) sit under the
+ compact context in production (StudioShell.tsx), not the body. */}
+ <TooltipProvider delayDuration={0}>
+ <StudioPaneCompactContext.Provider value={compact}>
+ <RunPaneViewToggles />
+ </StudioPaneCompactContext.Provider>
+ {initialEntry.startsWith("/runs/") ? (
+ <Routes>
+ <Route
+ path="/runs/:runId"
+ element={<RunView workflowRunId="wr_1" {...props} />}
+ />
+ </Routes>
+ ) : (
+ <RunView workflowRunId="wr_1" {...props} />
+ )}
+ </TooltipProvider>
+ <LocationSpy />
+ {extra}
+ </MemoryRouter>
+ </PageSlotsProvider>
</QueryClientProvider>
);
const view = render(makeUi());
@@ -325,6 +330,37 @@ beforeEach(() => {
});
describe("RunView view toggles", () => {
+ test("mounts the milestone slot throughout Overview but not the editor", () => {
+ seedCompletedRun();
+ const MilestoneCard = vi.fn(() => <div data-testid="milestone-card" />);
+ const pageSlots = { workflowRunMilestoneCard: MilestoneCard };
+
+ const editor = renderRunView(
+ {},
+ "/?panes=editor",
+ false,
+ undefined,
+ pageSlots,
+ );
+ expect(MilestoneCard).not.toHaveBeenCalled();
+ expect(editor.queryByTestId("milestone-card")).toBeNull();
+ cleanup();
+
+ const overview = renderRunView(
+ {},
+ "/?panes=overview",
+ false,
+ undefined,
+ pageSlots,
+ );
+ expect(overview.queryByTestId("milestone-card")).not.toBeNull();
+ for (const view of ["inputs", "outputs", "code"] as const) {
+ act(() => useRunPaneViewStore.getState().setView(view));
+ overview.rerenderRunView();
+ expect(overview.queryByTestId("milestone-card")).not.toBeNull();
+ }
+ });
+
test("does not render run tags in Studio Overview", () => {
seedCompletedRun();
const { queryByTestId } = renderRunView();
diff --git a/skyvern-frontend/src/routes/workflows/studio/runview/RunView.tsx b/skyvern-frontend/src/routes/workflows/studio/runview/RunView.tsx
index 987831157..5b110fc2a 100644
--- a/skyvern-frontend/src/routes/workflows/studio/runview/RunView.tsx
+++ b/skyvern-frontend/src/routes/workflows/studio/runview/RunView.tsx
@@ -33,6 +33,10 @@ import { useRunPaneViewStore } from "@/store/useRunPaneViewStore";
import { useRunViewStore } from "@/store/RunViewStore";
import { useStudioBrowserStore } from "@/store/useStudioBrowserStore";
import { useWorkflowBlockSearchStore } from "@/store/WorkflowBlockSearchStore";
+import {
+ type WorkflowRunMilestoneCardProps,
+ usePageSlots,
+} from "@/store/PageSlots";
import { cn, isRecord } from "@/util/utils";
import { useWorkflowRunTimelineQuery } from "../../hooks/useWorkflowRunTimelineQuery";
@@ -89,6 +93,7 @@ type RunViewProps = {
runIdPending?: boolean;
onFix?: (seedMessage?: string, failingLabel?: string | null) => void;
onRetry?: () => void;
+ milestoneRerun?: WorkflowRunMilestoneCardProps["rerun"];
};
function isRunOutputError(value: unknown): value is RunOutputError {
@@ -199,7 +204,9 @@ export function RunView({
runIdPending = false,
onFix,
onRetry,
+ milestoneRerun,
}: RunViewProps) {
+ const { workflowRunMilestoneCard: WorkflowRunMilestoneCard } = usePageSlots();
const { runId: pathRunId } = useParams();
const queryOptions = workflowRunId ? { workflowRunId } : undefined;
// isLoading here, not isPending like RunTab: this query is enabled only once a run
@@ -718,6 +725,16 @@ export function RunView({
</div>
</Alert>
) : null}
+ {WorkflowRunMilestoneCard &&
+ runPaneOpen &&
+ !runIsPlaceholder &&
+ workflowRun.workflow_run_id === workflowRunId &&
+ workflowRun.status === Status.Completed ? (
+ <WorkflowRunMilestoneCard
+ workflowRunId={workflowRun.workflow_run_id}
+ rerun={milestoneRerun}
+ />
+ ) : null}
{view === "timeline" ? (
<div className="flex min-h-0 flex-1 flex-col gap-2">
diff --git a/skyvern-frontend/src/store/PageSlots.ts b/skyvern-frontend/src/store/PageSlots.ts
index e469a9433..cc4384824 100644
--- a/skyvern-frontend/src/store/PageSlots.ts
+++ b/skyvern-frontend/src/store/PageSlots.ts
@@ -3,10 +3,15 @@ import { createContext, useContext } from "react";
export type WorkflowAnalyticsPanelProps = {
workflowPermanentId: string;
};
+export type WorkflowRunMilestoneCardProps = Readonly<{
+ workflowRunId: string;
+ rerun?: Readonly<{ to: string; state?: unknown }>;
+}>;
export type PageSlots = {
workflowAnalyticsPanel?: React.ComponentType<WorkflowAnalyticsPanelProps>;
workflowRunsFilterControls?: React.ComponentType;
+ workflowRunMilestoneCard?: React.ComponentType<WorkflowRunMilestoneCardProps>;
};
const PageSlotsContext = createContext<PageSlots>({});
diff --git a/skyvern-frontend/src/store/onboarding/OnboardingProvider.test.tsx b/skyvern-frontend/src/store/onboarding/OnboardingProvider.test.tsx
index 63eab10d3..a8f0079e9 100644
--- a/skyvern-frontend/src/store/onboarding/OnboardingProvider.test.tsx
+++ b/skyvern-frontend/src/store/onboarding/OnboardingProvider.test.tsx
@@ -1,5 +1,7 @@
// @vitest-environment jsdom
+import { useState } from "react";
import {
+ act,
cleanup,
fireEvent,
render,
@@ -7,25 +9,30 @@ import {
waitFor,
} from "@testing-library/react";
import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
-import { afterEach, describe, expect, it, vi } from "vitest";
+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
+import type {
+ OnboardingState,
+ OnboardingStateResponse,
+ RecoveryGuidanceAssignment,
+ QuestionnairePatchV1,
+ QuestionnaireStateV1,
+} from "./types";
-const { mockGet, mockPost } = vi.hoisted(() => ({
+const { mockGet, mockPost, mockAuth } = vi.hoisted(() => ({
mockGet: vi.fn(),
mockPost: vi.fn(),
+ mockAuth: { userId: "user-a" },
}));
vi.mock("@clerk/clerk-react", () => ({
- useAuth: () => ({ isSignedIn: true }),
+ useAuth: () => ({ isSignedIn: true, userId: mockAuth.userId }),
}));
-
vi.mock("@/hooks/useCredentialGetter", () => ({
useCredentialGetter: () => () => Promise.resolve("test-token"),
}));
-
vi.mock("@/api/AxiosClient", () => ({
getClient: () => Promise.resolve({ get: mockGet, post: mockPost }),
}));
-
vi.mock("@/util/onboarding/OnboardingTelemetry", () => ({
OnboardingTelemetry: {
error: vi.fn(),
@@ -35,13 +42,89 @@ vi.mock("@/util/onboarding/OnboardingTelemetry", () => ({
},
}));
+type BroadcastListener = (event: MessageEvent<unknown>) => void;
+
+class FakeBroadcastChannel {
+ static channels: FakeBroadcastChannel[] = [];
+
+ readonly name: string;
+ private readonly listeners = new Set<BroadcastListener>();
+
+ constructor(name: string) {
+ this.name = name;
+ FakeBroadcastChannel.channels.push(this);
+ }
+
+ postMessage(data: unknown) {
+ for (const channel of FakeBroadcastChannel.channels) {
+ if (channel !== this && channel.name === this.name) {
+ for (const listener of channel.listeners) {
+ listener(new MessageEvent("message", { data }));
+ }
+ }
+ }
+ }
+
+ addEventListener(_type: "message", listener: BroadcastListener) {
+ this.listeners.add(listener);
+ }
+
+ removeEventListener(_type: "message", listener: BroadcastListener) {
+ this.listeners.delete(listener);
+ }
+
+ close() {
+ FakeBroadcastChannel.channels = FakeBroadcastChannel.channels.filter(
+ (channel) => channel !== this,
+ );
+ }
+}
+
import { OnboardingProvider } from "./OnboardingProvider";
-import type { OnboardingStateResponse } from "./types";
import { useOnboardingState } from "./useOnboardingState";
const DISMISSED_AT = "2026-01-01T00:00:00.000Z";
+const DISMISSED_LATER = "2026-01-02T00:00:00.000Z";
+const RECOVERY_GUIDANCE_ASSIGNMENT = {
+ experiment_version: "recovery-guidance-v1",
+ organization_id: "organization",
+ eligible_run_id: "run",
+ eligible_at: "2026-01-01T00:00:00Z",
+ arm: "treatment",
+} satisfies RecoveryGuidanceAssignment;
+const COMPLETE: QuestionnairePatchV1 = {
+ version: 1,
+ mutation_id: "mutation",
+ expected_revision: 0,
+ action: "complete",
+ role: "developer",
+ company_context: "startup",
+ scale_intent: "exploring",
+ referral_source: "search",
+};
-function freshResponse(): OnboardingStateResponse {
+function questionnaire(revision = 1): QuestionnaireStateV1 {
+ return {
+ version: 1,
+ response_id: "response",
+ revision,
+ last_mutation_id: "mutation",
+ status: "completed",
+ role: "developer",
+ company_context: "startup",
+ scale_intent: "exploring",
+ referral_source: "search",
+ completed_at: "2026-01-01T00:00:00Z",
+ skipped_at: null,
+ deferred_at: null,
+ updated_at: "2026-01-01T00:00:00Z",
+ defer_prompt_count: 0,
+ };
+}
+
+function response(
+ overrides: Partial<OnboardingState> = {},
+): OnboardingStateResponse {
return {
onboarding_state: {
tour_completed_at: null,
@@ -49,25 +132,91 @@ function freshResponse(): OnboardingStateResponse {
first_save_at: null,
first_run_at: null,
ab_variant: null,
- user_intent: null,
+ user_intent: "fill_forms",
seen_canvas: null,
seen_node_adder: null,
seen_sidebar: null,
seen_save_run: null,
+ ...overrides,
},
launch_date_at_signup: "2025-01-01T00:00:00Z",
recovery_guidance_assignment: null,
};
}
-function Consumer() {
- const { state, updateState } = useOnboardingState();
+function deferred<T>() {
+ let resolve!: (value: T) => void;
+ const promise = new Promise<T>((resolvePromise) => {
+ resolve = resolvePromise;
+ });
+ return { promise, resolve };
+}
+
+function Consumer({ prefix = "" }: Readonly<{ prefix?: string }>) {
+ const {
+ state,
+ updateState,
+ updateStateConfirmed,
+ recoveryGuidanceAssignment,
+ } = useOnboardingState();
+ const [confirmed, setConfirmed] = useState("idle");
return (
<div>
- <span data-testid="dismissed">{String(state?.modal_dismissed_at)}</span>
- <button onClick={() => updateState({ modal_dismissed_at: DISMISSED_AT })}>
+ <span data-testid={`${prefix}dismissed`}>
+ {String(state?.modal_dismissed_at)}
+ </span>
+ <span data-testid={`${prefix}revision`}>
+ {state?.questionnaire?.revision ?? 0}
+ </span>
+ <span data-testid={`${prefix}prompted`}>
+ {String(state?.questionnaire_prompted_at)}
+ </span>
+ <span data-testid={`${prefix}seen`}>{String(state?.seen_canvas)}</span>
+ <span data-testid={`${prefix}confirmed`}>{confirmed}</span>
+ <span data-testid={`${prefix}assignment`}>
+ {recoveryGuidanceAssignment?.eligible_run_id ?? "none"}
+ </span>
+ <button
+ type="button"
+ onClick={() => updateState({ modal_dismissed_at: DISMISSED_AT })}
+ >
dismiss
</button>
+ <button
+ type="button"
+ onClick={() => updateState({ modal_dismissed_at: DISMISSED_LATER })}
+ >
+ dismiss later
+ </button>
+ <button type="button" onClick={() => updateState({ seen_canvas: true })}>
+ see canvas
+ </button>
+ <button
+ type="button"
+ onClick={() => {
+ void updateStateConfirmed({ questionnaire: COMPLETE }).then(
+ (result) =>
+ setConfirmed(
+ "code" in result && typeof result.code === "string"
+ ? result.code
+ : "saved",
+ ),
+ () => setConfirmed("thrown"),
+ );
+ }}
+ >
+ {prefix}confirm
+ </button>
+ <button
+ type="button"
+ onClick={() => {
+ void updateStateConfirmed({
+ questionnaire_prompt: { version: 1, action: "reserve" },
+ });
+ }}
+ >
+ {prefix}reserve
+ </button>
</div>
);
}
@@ -75,71 +224,328 @@ function Consumer() {
function renderProvider() {
const queryClient = new QueryClient({
defaultOptions: {
- queries: { retry: false },
+ queries: { retry: false, staleTime: 5 * 60 * 1000 },
mutations: { retry: false },
},
});
- return render(
+ const renderTree = () => (
<QueryClientProvider client={queryClient}>
<OnboardingProvider>
<Consumer />
</OnboardingProvider>
- </QueryClientProvider>,
+ </QueryClientProvider>
+ );
+ const rendered = render(renderTree());
+ return {
+ ...rendered,
+ queryClient,
+ rerenderProvider: () => rendered.rerender(renderTree()),
+ };
+}
+
+function renderProviderPair() {
+ const firstClient = new QueryClient({
+ defaultOptions: {
+ queries: { retry: false, staleTime: 5 * 60 * 1000 },
+ mutations: { retry: false },
+ },
+ });
+ const secondClient = new QueryClient({
+ defaultOptions: {
+ queries: { retry: false, staleTime: 5 * 60 * 1000 },
+ mutations: { retry: false },
+ },
+ });
+ return render(
+ <>
+ <QueryClientProvider client={firstClient}>
+ <OnboardingProvider>
+ <Consumer prefix="a-" />
+ </OnboardingProvider>
+ </QueryClientProvider>
+ <QueryClientProvider client={secondClient}>
+ <OnboardingProvider>
+ <Consumer prefix="b-" />
+ </OnboardingProvider>
+ </QueryClientProvider>
+ </>,
);
}
+beforeEach(() => {
+ FakeBroadcastChannel.channels = [];
+ vi.stubGlobal("BroadcastChannel", FakeBroadcastChannel);
+});
+
afterEach(() => {
cleanup();
- vi.clearAllMocks();
+ vi.resetAllMocks();
+ vi.unstubAllGlobals();
+ FakeBroadcastChannel.channels = [];
+ mockAuth.userId = "user-a";
});
-describe("OnboardingProvider write resilience", () => {
- it("keeps the optimistic dismissal when the write fails", async () => {
- mockGet.mockResolvedValue({ data: freshResponse() });
- mockPost.mockRejectedValue(new Error("405 Method Not Allowed"));
-
+describe("OnboardingProvider writes", () => {
+ it("keeps confirmed POST success when the background refetch fails", async () => {
+ const confirmed = response({ questionnaire: questionnaire() });
+ mockGet
+ .mockResolvedValueOnce({ data: response() })
+ .mockRejectedValueOnce(new Error("refetch unavailable"));
+ mockPost.mockResolvedValueOnce({ data: confirmed });
renderProvider();
+ await waitFor(() => expect(mockGet).toHaveBeenCalledOnce());
+
+ fireEvent.click(screen.getByText("confirm"));
+
await waitFor(() =>
- expect(screen.getByTestId("dismissed").textContent).toBe("null"),
+ expect(screen.getByTestId("confirmed").textContent).toBe("saved"),
);
+ expect(screen.getByTestId("revision").textContent).toBe("1");
+ });
- fireEvent.click(screen.getByText("dismiss"));
+ it("broadcasts a reservation into another tab immediately", async () => {
+ const backgroundRefetch = deferred<{ data: OnboardingStateResponse }>();
+ mockGet
+ .mockResolvedValueOnce({ data: response() })
+ .mockResolvedValueOnce({ data: response() })
+ .mockReturnValue(backgroundRefetch.promise);
+ const reserved = response({
+ questionnaire_prompted_at: "2026-08-28T00:30:00Z",
+ });
+ reserved.questionnaire_prompt_result = {
+ status: "reserved",
+ prompted_at: "2026-08-28T00:30:00Z",
+ };
+ mockPost.mockResolvedValueOnce({ data: reserved });
+ renderProviderPair();
+ await waitFor(() => expect(mockGet).toHaveBeenCalledTimes(2));
- // Optimistic update applies immediately.
+ fireEvent.click(screen.getByText("b-reserve"));
+
+ await waitFor(() =>
+ expect(screen.getByTestId("a-prompted").textContent).toBe(
+ "2026-08-28T00:30:00Z",
+ ),
+ );
+ });
+ it("preserves one failed overlay through a synchronized POST/refetch interleaving", async () => {
+ const firstWrite = deferred<{ data: OnboardingStateResponse }>();
+ mockGet
+ .mockResolvedValueOnce({ data: response() })
+ .mockReturnValueOnce(firstWrite.promise)
+ .mockResolvedValue({ data: response({ seen_canvas: true }) });
+ mockPost
+ .mockReturnValueOnce(firstWrite.promise)
+ .mockRejectedValueOnce(new Error("offline"));
+ const { queryClient } = renderProvider();
+ await waitFor(() => expect(mockGet).toHaveBeenCalledOnce());
+
+ fireEvent.click(screen.getByText("see canvas"));
+ await waitFor(() => expect(mockPost).toHaveBeenCalledOnce());
+ fireEvent.click(screen.getByText("dismiss"));
await waitFor(() =>
expect(screen.getByTestId("dismissed").textContent).toBe(DISMISSED_AT),
);
- await waitFor(() => expect(mockPost).toHaveBeenCalledTimes(1));
+ void queryClient.invalidateQueries({ queryKey: ["userOnboarding"] });
+ await waitFor(() => expect(mockGet).toHaveBeenCalledTimes(2));
- // A failed write must NOT roll back the dismissal nor refetch the stale state.
- await new Promise((resolve) => setTimeout(resolve, 50));
+ firstWrite.resolve({ data: response({ seen_canvas: true }) });
+ await waitFor(() =>
+ expect([queryClient.isMutating(), queryClient.isFetching()]).toEqual([
+ 0, 0,
+ ]),
+ );
expect(screen.getByTestId("dismissed").textContent).toBe(DISMISSED_AT);
- expect(mockGet).toHaveBeenCalledTimes(1);
});
- it("refetches once after a successful write", async () => {
- const dismissedResponse: OnboardingStateResponse = {
- ...freshResponse(),
- onboarding_state: {
- ...freshResponse().onboarding_state,
- modal_dismissed_at: DISMISSED_AT,
- },
+ it("lets a later successful field value supersede an older failure", async () => {
+ mockGet
+ .mockResolvedValueOnce({ data: response() })
+ .mockResolvedValueOnce({
+ data: response({ modal_dismissed_at: DISMISSED_LATER }),
+ })
+ .mockResolvedValue({
+ data: response({
+ modal_dismissed_at: DISMISSED_LATER,
+ seen_canvas: true,
+ }),
+ });
+ mockPost
+ .mockRejectedValueOnce(new Error("offline"))
+ .mockResolvedValueOnce({
+ data: response({ modal_dismissed_at: DISMISSED_LATER }),
+ })
+ .mockResolvedValueOnce({
+ data: response({
+ modal_dismissed_at: DISMISSED_LATER,
+ seen_canvas: true,
+ }),
+ });
+ renderProvider();
+ await waitFor(() => expect(mockGet).toHaveBeenCalledOnce());
+
+ fireEvent.click(screen.getByText("dismiss"));
+ await waitFor(() => expect(mockPost).toHaveBeenCalledOnce());
+ fireEvent.click(screen.getByText("dismiss later"));
+ await waitFor(() =>
+ expect(screen.getByTestId("dismissed").textContent).toBe(DISMISSED_LATER),
+ );
+
+ fireEvent.click(screen.getByText("see canvas"));
+ await waitFor(() =>
+ expect(screen.getByTestId("seen").textContent).toBe("true"),
+ );
+ expect(screen.getByTestId("dismissed").textContent).toBe(DISMISSED_LATER);
+ });
+
+ it("keeps the GET-only recovery assignment after a confirmed write", async () => {
+ const assigned = (overrides: Partial<OnboardingState> = {}) => {
+ const value = response(overrides);
+ value.recovery_guidance_assignment = RECOVERY_GUIDANCE_ASSIGNMENT;
+ return value;
};
- // First GET is fresh; once the write succeeds the server persists, so the
- // refetch returns the dismissed state.
+ const confirmed = response({ questionnaire: questionnaire() });
+ Reflect.deleteProperty(confirmed, "recovery_guidance_assignment");
mockGet
- .mockResolvedValueOnce({ data: freshResponse() })
- .mockResolvedValue({ data: dismissedResponse });
- mockPost.mockResolvedValue({ data: dismissedResponse });
+ .mockResolvedValueOnce({ data: assigned() })
+ .mockResolvedValueOnce({ data: assigned({ seen_canvas: true }) })
+ .mockResolvedValueOnce({
+ data: assigned({ questionnaire: questionnaire(), seen_canvas: true }),
+ });
+ mockPost
+ .mockRejectedValueOnce(new Error("offline"))
+ .mockResolvedValueOnce({ data: confirmed });
+ const { queryClient } = renderProvider();
+ fireEvent.click(screen.getByText("dismiss"));
+ await waitFor(() => expect(queryClient.isMutating()).toBe(0));
+ await act(() =>
+ queryClient.invalidateQueries({ queryKey: ["userOnboarding"] }),
+ );
+ fireEvent.click(screen.getByText("confirm"));
+ await waitFor(() =>
+ expect(screen.getByTestId("revision").textContent).toBe("1"),
+ );
+ expect(screen.getByTestId("confirmed").textContent).toBe("saved");
+ expect(screen.getByTestId("assignment").textContent).toBe("run");
+ });
+ it("rejects a confirmed conflict when authoritative reconciliation fails", async () => {
+ const conflict = Object.assign(
+ new Error("Request failed with status code 409"),
+ {
+ isAxiosError: true,
+ response: {
+ status: 409,
+ data: { detail: "questionnaire_revision_conflict" },
+ },
+ },
+ );
+ mockGet
+ .mockResolvedValueOnce({ data: response() })
+ .mockRejectedValueOnce(new Error("reconciliation unavailable"));
+ mockPost.mockRejectedValueOnce(conflict);
renderProvider();
- await waitFor(() => expect(mockGet).toHaveBeenCalledTimes(1));
+ await waitFor(() => expect(mockGet).toHaveBeenCalledOnce());
- fireEvent.click(screen.getByText("dismiss"));
+ fireEvent.click(screen.getByText("confirm"));
- await waitFor(() => expect(mockPost).toHaveBeenCalledTimes(1));
- // onSuccess invalidates -> GET refetches exactly once more.
+ await waitFor(() =>
+ expect(screen.getByTestId("confirmed").textContent).toBe("thrown"),
+ );
+ });
+
+ it("isolates B's failed overlay while A settles after the switch", async () => {
+ const aWrite = deferred<{ data: OnboardingStateResponse }>();
+ const aRefetch = deferred<{ data: OnboardingStateResponse }>();
+ const bWrite = deferred<void>();
+ mockGet
+ .mockResolvedValueOnce({ data: response() })
+ .mockReturnValueOnce(aRefetch.promise)
+ .mockResolvedValue({ data: response() });
+ mockPost.mockReturnValueOnce(aWrite.promise).mockReturnValueOnce(
+ bWrite.promise.then(() => {
+ throw new Error("offline");
+ }),
+ );
+ const { queryClient, rerenderProvider } = renderProvider();
+ const invalidate = () =>
+ queryClient.invalidateQueries({ queryKey: ["userOnboarding"] });
+ await waitFor(() => expect(mockGet).toHaveBeenCalledOnce());
+ fireEvent.click(screen.getByText("see canvas"));
+ await waitFor(() => expect(mockPost).toHaveBeenCalledOnce());
+ const aRefresh = invalidate();
await waitFor(() => expect(mockGet).toHaveBeenCalledTimes(2));
+ mockAuth.userId = "user-b";
+ rerenderProvider();
+ await waitFor(() => expect(mockGet).toHaveBeenCalledTimes(3));
+ await waitFor(() =>
+ expect(screen.getByTestId("dismissed").textContent).toBe("null"),
+ );
+ fireEvent.click(screen.getByText("dismiss"));
+ await waitFor(() =>
+ expect(screen.getByTestId("dismissed").textContent).toBe(DISMISSED_AT),
+ );
+ aRefetch.resolve({ data: response() });
+ await aRefresh;
+ expect(
+ queryClient.getQueryData<OnboardingStateResponse>([
+ "userOnboarding",
+ "user-a",
+ ])?.onboarding_state.modal_dismissed_at,
+ ).toBeNull();
+ aWrite.resolve({ data: response({ seen_canvas: true }) });
+ await waitFor(() => expect(mockPost).toHaveBeenCalledTimes(2));
+ await act(invalidate);
+ expect(screen.getByTestId("dismissed").textContent).toBe(DISMISSED_AT);
+ bWrite.resolve();
+ await waitFor(() => expect(queryClient.isMutating()).toBe(0));
+ await act(invalidate);
expect(screen.getByTestId("dismissed").textContent).toBe(DISMISSED_AT);
});
+
+ it.each([
+ { status: 409, detail: "questionnaire_revision_conflict" },
+ { status: 409, detail: "questionnaire_requires_user_intent" },
+ { status: 409, detail: "questionnaire_update_requires_response" },
+ { status: 409, detail: "questionnaire_invalid_transition" },
+ { status: 403, detail: "onboarding_questionnaire_disabled" },
+ { status: 409, detail: undefined },
+ ])(
+ "returns $detail after reconciling HTTP $status",
+ async ({ status, detail }) => {
+ const code = detail ?? "unknown";
+ const authoritative = deferred<{ data: OnboardingStateResponse }>();
+ const error = Object.assign(new Error(code), {
+ isAxiosError: true,
+ response: {
+ status,
+ data: detail === undefined ? undefined : { detail },
+ },
+ });
+ mockGet
+ .mockResolvedValueOnce({ data: response() })
+ .mockReturnValue(authoritative.promise);
+ mockPost
+ .mockRejectedValueOnce(new Error("offline"))
+ .mockRejectedValueOnce(error);
+ renderProvider();
+ fireEvent.click(screen.getByText("dismiss"));
+ await waitFor(() => expect(mockPost).toHaveBeenCalledOnce());
+ fireEvent.click(screen.getByText("confirm"));
+
+ if (status === 409) {
+ authoritative.resolve({
+ data: response({ questionnaire: questionnaire(2) }),
+ });
+ await waitFor(() =>
+ expect(screen.getByTestId("revision").textContent).toBe("2"),
+ );
+ expect(screen.getByTestId("dismissed").textContent).toBe(DISMISSED_AT);
+ }
+
+ await waitFor(() =>
+ expect(screen.getByTestId("confirmed").textContent).toBe(code),
+ );
+ },
+ );
});
diff --git a/skyvern-frontend/src/store/onboarding/OnboardingProvider.tsx b/skyvern-frontend/src/store/onboarding/OnboardingProvider.tsx
index 9ddd16288..70c1f254b 100644
--- a/skyvern-frontend/src/store/onboarding/OnboardingProvider.tsx
+++ b/skyvern-frontend/src/store/onboarding/OnboardingProvider.tsx
@@ -1,15 +1,104 @@
-import { useCallback, useEffect, useRef } from "react";
-import { useQuery, useMutation, useQueryClient } from "@tanstack/react-query";
+import { useCallback, useEffect, useMemo, useRef } from "react";
+import { isAxiosError } from "axios";
+import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
import { useAuth } from "@clerk/clerk-react";
import { getClient } from "@/api/AxiosClient";
import { useCredentialGetter } from "@/hooks/useCredentialGetter";
import { OnboardingContext } from "./useOnboardingState";
import { OnboardingTelemetry } from "@/util/onboarding/OnboardingTelemetry";
-import type { OnboardingStatePatch, OnboardingStateResponse } from "./types";
-
-const QUERY_KEY = ["userOnboarding"] as const;
+import type {
+ ConfirmedPatch,
+ ConfirmedWriteResult,
+ LegacyOnboardingStatePatch,
+ OnboardingStateResponse,
+} from "./types";
const PRODUCT_LAUNCH_DATE = "2024-10-01T00:00:00Z";
+const MUTATION_SCOPE = { id: "userOnboarding" } as const;
+
+const ONBOARDING_BROADCAST_CHANNEL = "skyvern-user-onboarding";
+
+type QuestionnaireReservedMessage = {
+ type: "questionnaire-reserved";
+ userId: string;
+ promptedAt: string;
+};
+
+function parseQuestionnaireReservedMessage(
+ value: unknown,
+): QuestionnaireReservedMessage | null {
+ if (typeof value !== "object" || value === null) return null;
+ const type = Reflect.get(value, "type");
+ const userId = Reflect.get(value, "userId");
+ const promptedAt = Reflect.get(value, "promptedAt");
+ return type === "questionnaire-reserved" &&
+ typeof userId === "string" &&
+ typeof promptedAt === "string"
+ ? { type, userId, promptedAt }
+ : null;
+}
+
+function isAuthoritativeConfirmedResponse(
+ response: OnboardingStateResponse,
+): boolean {
+ const status = response.questionnaire_prompt_result?.status;
+ return status !== "flag_disabled" && status !== "ineligible";
+}
+
+function mergeConfirmedResponse(
+ current: OnboardingStateResponse | undefined,
+ response: OnboardingStateResponse,
+): OnboardingStateResponse {
+ return {
+ ...response,
+ recovery_guidance_assignment:
+ response.recovery_guidance_assignment ??
+ current?.recovery_guidance_assignment ??
+ null,
+ };
+}
+
+type LegacyWrite = {
+ version: number;
+ patch: LegacyOnboardingStatePatch;
+ status: "pending" | "failed" | "succeeded";
+};
+
+type LegacyMutationContext = {
+ legacyWriteVersion: number;
+ userId: string | null | undefined;
+ queryKey: readonly ["userOnboarding", string | null | undefined];
+};
+
+function legacyFieldsToReplay(
+ writes: LegacyWrite[],
+ version: number,
+): LegacyOnboardingStatePatch {
+ const fields: LegacyOnboardingStatePatch = {};
+ for (const write of writes) {
+ if (write.version >= version || write.status !== "succeeded") {
+ Object.assign(fields, write.patch);
+ } else {
+ for (const field of Object.keys(write.patch)) {
+ Reflect.deleteProperty(fields, field);
+ }
+ }
+ }
+ return fields;
+}
+
+function mergeNewerLegacyFields(
+ authoritativeState: OnboardingStateResponse,
+ legacyFields: LegacyOnboardingStatePatch,
+): OnboardingStateResponse {
+ return {
+ ...authoritativeState,
+ onboarding_state: {
+ ...authoritativeState.onboarding_state,
+ ...legacyFields,
+ },
+ };
+}
type Props = {
children: React.ReactNode;
@@ -17,27 +106,77 @@ type Props = {
function OnboardingProvider({ children }: Readonly<Props>) {
const credentialGetter = useCredentialGetter();
- const { isSignedIn } = useAuth();
+ const { isSignedIn, userId } = useAuth();
const queryClient = useQueryClient();
+ const queryKey = useMemo(
+ (): readonly ["userOnboarding", typeof userId] => [
+ "userOnboarding",
+ userId,
+ ],
+ [userId],
+ );
+ const legacyWriteVersionRef = useRef(0);
+ const legacyWritesRef = useRef<LegacyWrite[]>([]);
+ const previousUserIdRef = useRef<string | null | undefined>(undefined);
+ const conflictRefetchPendingRef = useRef(false);
+ const channelRef = useRef<BroadcastChannel | null>(null);
+ if (previousUserIdRef.current !== userId) {
+ legacyWritesRef.current = [];
+ legacyWriteVersionRef.current = 0;
+ previousUserIdRef.current = userId;
+ }
const { data, isLoading } = useQuery<OnboardingStateResponse>({
- queryKey: QUERY_KEY,
+ queryKey,
queryFn: async () => {
const client = await getClient(credentialGetter);
const response = await client.get<OnboardingStateResponse>(
"/users/me/onboarding",
);
- return response.data;
+ if (previousUserIdRef.current !== userId) {
+ return response.data;
+ }
+ const legacyFields = legacyFieldsToReplay(
+ legacyWritesRef.current,
+ legacyWriteVersionRef.current + 1,
+ );
+ return Object.keys(legacyFields).length === 0
+ ? response.data
+ : mergeNewerLegacyFields(response.data, legacyFields);
},
- enabled: !!credentialGetter && isSignedIn === true,
+ enabled: !!credentialGetter && isSignedIn === true && !!userId,
});
- const mutation = useMutation<
- OnboardingStateResponse,
- unknown,
- OnboardingStatePatch
- >({
- mutationFn: async (patch) => {
+ useEffect(() => {
+ if (typeof BroadcastChannel === "undefined") return;
+ const channel = new BroadcastChannel(ONBOARDING_BROADCAST_CHANNEL);
+ channelRef.current = channel;
+ const listener = (event: MessageEvent<unknown>) => {
+ const message = parseQuestionnaireReservedMessage(event.data);
+ if (!message || message.userId !== userId) return;
+ queryClient.setQueryData<OnboardingStateResponse>(queryKey, (current) =>
+ current
+ ? {
+ ...current,
+ onboarding_state: {
+ ...current.onboarding_state,
+ questionnaire_prompted_at: message.promptedAt,
+ },
+ }
+ : current,
+ );
+ void queryClient.invalidateQueries({ queryKey });
+ };
+ channel.addEventListener("message", listener);
+ return () => {
+ channel.removeEventListener("message", listener);
+ channel.close();
+ if (channelRef.current === channel) channelRef.current = null;
+ };
+ }, [queryClient, queryKey, userId]);
+
+ const writeState = useCallback(
+ async (patch: ConfirmedPatch) => {
const client = await getClient(credentialGetter);
const response = await client.post<OnboardingStateResponse>(
"/users/me/onboarding",
@@ -45,31 +184,120 @@ function OnboardingProvider({ children }: Readonly<Props>) {
);
return response.data;
},
+ [credentialGetter],
+ );
+
+ const legacyMutation = useMutation<
+ OnboardingStateResponse,
+ unknown,
+ LegacyOnboardingStatePatch,
+ LegacyMutationContext
+ >({
+ scope: MUTATION_SCOPE,
+ mutationFn: writeState,
onMutate: async (patch) => {
- await queryClient.cancelQueries({ queryKey: QUERY_KEY });
+ const legacyWriteVersion = legacyWriteVersionRef.current + 1;
+ legacyWriteVersionRef.current = legacyWriteVersion;
+ legacyWritesRef.current.push({
+ version: legacyWriteVersion,
+ patch,
+ status: "pending",
+ });
+ if (!conflictRefetchPendingRef.current) {
+ await queryClient.cancelQueries({ queryKey: queryKey });
+ }
const previous =
- queryClient.getQueryData<OnboardingStateResponse>(QUERY_KEY);
+ queryClient.getQueryData<OnboardingStateResponse>(queryKey);
if (previous) {
- queryClient.setQueryData<OnboardingStateResponse>(QUERY_KEY, {
+ queryClient.setQueryData<OnboardingStateResponse>(queryKey, {
...previous,
onboarding_state: { ...previous.onboarding_state, ...patch },
});
}
+ return { legacyWriteVersion, userId, queryKey };
},
- onError: () => {
- // Best-effort persistence: keep the optimistic state so a failed write
- // (offline / 5xx / 405) can never resurrect a dismissed modal or tour.
+ onError: (_error, _patch, context) => {
+ if (context && context.userId === previousUserIdRef.current) {
+ const write = legacyWritesRef.current.find(
+ ({ version }) => version === context.legacyWriteVersion,
+ );
+ if (write) write.status = "failed";
+ }
OnboardingTelemetry.error("dashboard");
},
- onSuccess: () => {
- queryClient.invalidateQueries({ queryKey: QUERY_KEY });
+ onSuccess: async (_nextState, _patch, context) => {
+ if (context.userId === previousUserIdRef.current) {
+ const write = legacyWritesRef.current.find(
+ ({ version }) => version === context.legacyWriteVersion,
+ );
+ if (write) write.status = "succeeded";
+ }
+ await queryClient.invalidateQueries({ queryKey: context.queryKey });
+ if (context.userId !== previousUserIdRef.current) return;
+ const newerFields = legacyFieldsToReplay(
+ legacyWritesRef.current,
+ context.legacyWriteVersion,
+ );
+ if (Object.keys(newerFields).length === 0) return;
+ queryClient.setQueryData<OnboardingStateResponse>(
+ context.queryKey,
+ (currentState) =>
+ currentState
+ ? mergeNewerLegacyFields(currentState, newerFields)
+ : currentState,
+ );
},
});
+ const confirmedMutation = useMutation<
+ OnboardingStateResponse,
+ unknown,
+ ConfirmedPatch
+ >({
+ scope: MUTATION_SCOPE,
+ mutationFn: async (patch) => {
+ try {
+ return await writeState(patch);
+ } catch (error) {
+ if (!isAxiosError(error) || error.response?.status !== 409) throw error;
+ conflictRefetchPendingRef.current = true;
+ await queryClient
+ .invalidateQueries({ queryKey: queryKey }, { throwOnError: true })
+ .finally(() => (conflictRefetchPendingRef.current = false));
+ throw error;
+ }
+ },
+ onMutate: async () => {
+ if (!conflictRefetchPendingRef.current) {
+ await queryClient.cancelQueries({ queryKey: queryKey });
+ }
+ },
+ onSuccess: (nextState) => {
+ if (isAuthoritativeConfirmedResponse(nextState)) {
+ queryClient.setQueryData<OnboardingStateResponse>(queryKey, (current) =>
+ mergeConfirmedResponse(current, nextState),
+ );
+ const promptedAt = nextState.onboarding_state.questionnaire_prompted_at;
+ if (typeof userId === "string" && promptedAt) {
+ try {
+ channelRef.current?.postMessage({
+ type: "questionnaire-reserved",
+ userId,
+ promptedAt,
+ } satisfies QuestionnaireReservedMessage);
+ } catch {
+ // Cross-tab synchronization is best effort; the background refetch remains authoritative.
+ }
+ }
+ }
+ void queryClient.invalidateQueries({ queryKey });
+ },
+ onError: () => OnboardingTelemetry.error("dashboard"),
+ });
+
const isNewUser =
data?.launch_date_at_signup != null &&
new Date(data.launch_date_at_signup) >= new Date(PRODUCT_LAUNCH_DATE);
-
const abVariant = data?.onboarding_state.ab_variant ?? null;
useEffect(() => {
@@ -81,24 +309,54 @@ function OnboardingProvider({ children }: Readonly<Props>) {
const prevSaveAt = useRef<string | null | undefined>(undefined);
const prevRunAt = useRef<string | null | undefined>(undefined);
useEffect(() => {
- const s = data?.onboarding_state;
- if (!s) return;
- // emit the activation-funnel milestones once, on the observed null -> set transition
- if (prevSaveAt.current === null && s.first_save_at !== null) {
+ const onboardingState = data?.onboarding_state;
+ if (!onboardingState) return;
+ if (prevSaveAt.current === null && onboardingState.first_save_at !== null) {
OnboardingTelemetry.firstWorkflowCreated("dashboard");
}
- if (prevRunAt.current === null && s.first_run_at !== null) {
+ if (prevRunAt.current === null && onboardingState.first_run_at !== null) {
OnboardingTelemetry.firstRunCompleted("dashboard");
}
- prevSaveAt.current = s.first_save_at;
- prevRunAt.current = s.first_run_at;
+ prevSaveAt.current = onboardingState.first_save_at;
+ prevRunAt.current = onboardingState.first_run_at;
}, [data?.onboarding_state]);
const updateState = useCallback(
- (patch: OnboardingStatePatch) => {
- mutation.mutate(patch);
+ (patch: LegacyOnboardingStatePatch) => {
+ legacyMutation.mutate(patch);
+ },
+ [legacyMutation],
+ );
+ const updateStateConfirmed = useCallback(
+ async (patch: ConfirmedPatch): Promise<ConfirmedWriteResult> => {
+ try {
+ return await confirmedMutation.mutateAsync(patch);
+ } catch (error) {
+ if (isAxiosError<{ detail?: string }>(error)) {
+ const status = error.response?.status;
+ const detail = error.response?.data?.detail;
+ if (status === 409) {
+ switch (detail) {
+ case "questionnaire_revision_conflict":
+ case "questionnaire_requires_user_intent":
+ case "questionnaire_update_requires_response":
+ case "questionnaire_invalid_transition":
+ return { code: detail };
+ default:
+ return { code: "unknown" };
+ }
+ }
+ if (
+ status === 403 &&
+ detail === "onboarding_questionnaire_disabled"
+ ) {
+ return { code: detail };
+ }
+ }
+ throw error;
+ }
},
- [mutation],
+ [confirmedMutation],
);
return (
@@ -107,6 +365,7 @@ function OnboardingProvider({ children }: Readonly<Props>) {
state: data?.onboarding_state ?? null,
isLoading,
updateState,
+ updateStateConfirmed,
isNewUser,
abVariant,
recoveryGuidanceAssignment: data?.recovery_guidance_assignment ?? null,
diff --git a/skyvern-frontend/src/store/onboarding/types.ts b/skyvern-frontend/src/store/onboarding/types.ts
index 3a51e9658..a4dc25f89 100644
--- a/skyvern-frontend/src/store/onboarding/types.ts
+++ b/skyvern-frontend/src/store/onboarding/types.ts
@@ -1,3 +1,106 @@
+export const QUESTIONNAIRE_USER_INTENTS_V1 = [
+ "fill_forms",
+ "extract_data",
+ "monitor_website",
+ "something_else",
+] as const;
+
+export type QuestionnaireUserIntentV1 =
+ (typeof QUESTIONNAIRE_USER_INTENTS_V1)[number];
+
+export function isQuestionnaireUserIntentV1(
+ value: string | null,
+): value is QuestionnaireUserIntentV1 {
+ return (
+ value !== null &&
+ QUESTIONNAIRE_USER_INTENTS_V1.some((intent) => intent === value)
+ );
+}
+
+export type QuestionnaireRoleV1 =
+ | "developer"
+ | "technical_operator"
+ | "business_operator"
+ | "product_manager"
+ | "founder_or_executive"
+ | "other"
+ | "prefer_not_to_say";
+
+export type QuestionnaireCompanyContextV1 =
+ | "personal_or_individual"
+ | "startup"
+ | "agency_or_services"
+ | "established_company"
+ | "education_or_research"
+ | "other"
+ | "prefer_not_to_say";
+
+export type QuestionnaireScaleIntentV1 =
+ | "exploring"
+ | "single_workflow"
+ | "recurring_individual"
+ | "team_or_multi_workflow"
+ | "production_high_volume"
+ | "unsure";
+
+export type QuestionnaireReferralSourceV1 =
+ | "search"
+ | "social"
+ | "ai_assistant"
+ | "friend_or_colleague"
+ | "video"
+ | "blog_or_article"
+ | "event_or_community"
+ | "podcast"
+ | "other"
+ | "prefer_not_to_say";
+
+export type QuestionnaireAnswersV1 = {
+ role: QuestionnaireRoleV1;
+ company_context: QuestionnaireCompanyContextV1;
+ scale_intent: QuestionnaireScaleIntentV1;
+ referral_source: QuestionnaireReferralSourceV1;
+};
+
+export type QuestionnairePatchV1 =
+ | ({
+ version: 1;
+ mutation_id: string;
+ expected_revision: number;
+ action: "complete" | "update";
+ } & QuestionnaireAnswersV1)
+ | {
+ version: 1;
+ mutation_id: string;
+ expected_revision: number;
+ action: "skip";
+ };
+
+export type QuestionnairePromptPatchV1 = { version: 1; action: "reserve" };
+
+export type QuestionnairePromptResultV1 =
+ | { status: "reserved"; prompted_at: string }
+ | { status: "flag_disabled" | "ineligible" | "already_prompted" };
+
+export type QuestionnaireStatusV1 = "completed" | "skipped" | "deferred";
+
+export type QuestionnaireStateV1 = {
+ version: 1;
+ response_id: string;
+ revision: number;
+ last_mutation_id: string;
+ status: QuestionnaireStatusV1;
+ role: QuestionnaireRoleV1 | null;
+ company_context: QuestionnaireCompanyContextV1 | null;
+ scale_intent: QuestionnaireScaleIntentV1 | null;
+ referral_source: QuestionnaireReferralSourceV1 | null;
+ completed_at: string | null;
+ skipped_at: string | null;
+ deferred_at: string | null;
+ updated_at: string;
+ defer_prompt_count: 0 | 1;
+};
+
export type OnboardingState = {
tour_completed_at: string | null;
modal_dismissed_at: string | null;
@@ -5,6 +108,8 @@ export type OnboardingState = {
first_run_at: string | null;
ab_variant: string | null;
user_intent: string | null;
+ questionnaire_prompted_at?: string | null;
+ questionnaire?: QuestionnaireStateV1 | null;
seen_canvas: boolean | null;
seen_node_adder: boolean | null;
seen_sidebar: boolean | null;
@@ -26,6 +131,51 @@ export type OnboardingStateResponse = {
onboarding_state: OnboardingState;
launch_date_at_signup: string | null;
recovery_guidance_assignment: RecoveryGuidanceAssignment | null;
+ questionnaire_prompt_result?: QuestionnairePromptResultV1 | null;
+};
+
+export type ConfirmedWriteCode =
+ | "questionnaire_revision_conflict"
+ | "questionnaire_requires_user_intent"
+ | "questionnaire_update_requires_response"
+ | "questionnaire_invalid_transition"
+ | "onboarding_questionnaire_disabled"
+ | "unknown";
+
+export type ConfirmedWriteResult =
+ | OnboardingStateResponse
+ | { code: ConfirmedWriteCode };
+
+type MutableOnboardingStatePatch = Partial<
+ Omit<
+ OnboardingState,
+ | "first_save_at"
+ | "first_run_at"
+ | "questionnaire"
+ | "questionnaire_prompted_at"
+ >
+>;
+
+export type LegacyOnboardingStatePatch = MutableOnboardingStatePatch & {
+ questionnaire?: never;
+ questionnaire_prompt?: never;
+};
+
+export type QuestionnaireOnlyOnboardingStatePatch = {
+ questionnaire: QuestionnairePatchV1;
+ questionnaire_prompt?: never;
+} & {
+ [Key in keyof MutableOnboardingStatePatch]?: never;
+};
+
+export type QuestionnairePromptOnlyOnboardingStatePatch = {
+ questionnaire?: never;
+ questionnaire_prompt: QuestionnairePromptPatchV1;
+} & {
+ [Key in keyof MutableOnboardingStatePatch]?: never;
};
-export type OnboardingStatePatch = Partial<OnboardingState>;
+export type ConfirmedPatch =
+ | QuestionnaireOnlyOnboardingStatePatch
+ | QuestionnairePromptOnlyOnboardingStatePatch
+ | LegacyOnboardingStatePatch;
diff --git a/skyvern-frontend/src/store/onboarding/useOnboardingState.ts b/skyvern-frontend/src/store/onboarding/useOnboardingState.ts
index b707f05ac..63521af63 100644
--- a/skyvern-frontend/src/store/onboarding/useOnboardingState.ts
+++ b/skyvern-frontend/src/store/onboarding/useOnboardingState.ts
@@ -1,14 +1,21 @@
import { createContext, useContext } from "react";
import type {
+ ConfirmedPatch,
+ ConfirmedWriteResult,
+ LegacyOnboardingStatePatch,
OnboardingState,
- OnboardingStatePatch,
RecoveryGuidanceAssignment,
} from "./types";
+type ConfirmedOnboardingStateWriter = (
+ patch: ConfirmedPatch,
+) => Promise<ConfirmedWriteResult>;
+
type OnboardingContextValue = {
state: OnboardingState | null;
isLoading: boolean;
- updateState: (patch: OnboardingStatePatch) => void;
+ updateState: (patch: LegacyOnboardingStatePatch) => void;
+ updateStateConfirmed: ConfirmedOnboardingStateWriter;
isNewUser: boolean;
abVariant: string | null;
recoveryGuidanceAssignment: RecoveryGuidanceAssignment | null;
@@ -31,4 +38,4 @@ function useOnboardingStateOptional(): OnboardingContextValue | null {
}
export { OnboardingContext, useOnboardingState, useOnboardingStateOptional };
-export type { OnboardingContextValue };
+export type { ConfirmedOnboardingStateWriter, OnboardingContextValue };
diff --git a/skyvern-frontend/src/store/useRecordingStore.ts b/skyvern-frontend/src/store/useRecordingStore.ts
index fc931b96f..23e504e97 100644
--- a/skyvern-frontend/src/store/useRecordingStore.ts
+++ b/skyvern-frontend/src/store/useRecordingStore.ts
@@ -258,11 +258,6 @@ interface RecordingStore {
* tell a reconnect (reuse session) from a new recording (fresh session).
*/
recordingAttemptId: string | null;
- /**
- * The open message socket, published by useRecordingMessageChannel. The v2
- * commit rides this socket because the ledger is local to the pod behind it.
- */
- messageSocket: WebSocket | null;
/**
* Latest live-interpretation snapshot from the backend. Snapshots are
* full replacements keyed by monotonically increasing session revision.
@@ -354,7 +349,6 @@ interface RecordingStore {
},
) => void;
setRecordingTransport: (transport: RecordingTransport) => void;
- setMessageSocket: (socket: WebSocket | null) => void;
/**
* Flush any pending events into a compressed chunk.
* Call this before consuming the data.
@@ -535,7 +529,6 @@ export const useRecordingStore = create<RecordingStore>((set, get) => ({
recordingTransport: "vnc",
workflowPermanentId: null,
recordingAttemptId: null,
- messageSocket: null,
draftSteps: [],
interpretationSessionId: null,
sessionRevision: 0,
@@ -781,10 +774,6 @@ export const useRecordingStore = create<RecordingStore>((set, get) => ({
}
},
- setMessageSocket: (messageSocket) => {
- set({ messageSocket });
- },
-
setIsRecording: (isRecording, meta) => {
if (isRecording) {
const state = get();
diff --git a/skyvern-frontend/src/util/featureFlags.ts b/skyvern-frontend/src/util/featureFlags.ts
index 0089bf8db..9ce7e4fac 100644
--- a/skyvern-frontend/src/util/featureFlags.ts
+++ b/skyvern-frontend/src/util/featureFlags.ts
@@ -29,9 +29,8 @@ export const WORKFLOWS_DIRECTORY_TREE_FLAG = "WORKFLOWS_DIRECTORY_TREE";
// Not enrolled reads as disabled, so the default stays the legacy editor.
export const WORKFLOW_STUDIO_FLAG = "workflow_studio_v2";
-// Gates progressive recorded-action reveal in copilot verify cards.
-// Not enrolled reads as disabled, so the default stays the pre-reveal card.
-export const COPILOT_UX_V1_FLAG = "copilot_ux_v1";
+// Gates the optional, server-confirmed onboarding details step.
+export const ONBOARDING_QUESTIONNAIRE_FLAG = "onboarding_questionnaire_v1";
// Gates the login-block fallback-credential editor. Off ⇒ the fallback config is hidden, because
// automatic retries only run for orgs in the CREDENTIAL_FALLBACK_RETRY rollout (backend gate), so
@@ -42,8 +41,4 @@ export const CREDENTIAL_FALLBACK_RETRY_FLAG = "CREDENTIAL_FALLBACK_RETRY";
// Opt-in preview (0% base): recordings synthesize code blocks instead of agent blocks.
export const RECORD_BROWSER_CODE_FIRST_FLAG = "record_browser_code_first";
-// Opt-in (0% base): recording keeps the CDP stream instead of swapping to VNC.
-export const RECORD_BROWSER_CDP_TRANSPORT_FLAG = "record_browser_cdp_transport";
-
-// Opt-in (0% base): Record Browser v2 — capture from the input path, no scripts injected into the page.
-export const RECORD_BROWSER_V2_FLAG = "record_browser_v2";
+export const ONBOARDING_PROGRESS_FLAG = "onboarding_progress_v1";
diff --git a/skyvern-frontend/src/util/onboarding/OnboardingTelemetry.test.ts b/skyvern-frontend/src/util/onboarding/OnboardingTelemetry.test.ts
index b2371f67d..45fcb705c 100644
--- a/skyvern-frontend/src/util/onboarding/OnboardingTelemetry.test.ts
+++ b/skyvern-frontend/src/util/onboarding/OnboardingTelemetry.test.ts
@@ -1,31 +1,181 @@
-import { describe, it, expect, vi, beforeEach } from "vitest";
import posthog from "posthog-js";
+import { beforeEach, describe, expect, it, vi } from "vitest";
import { OnboardingTelemetry } from "./OnboardingTelemetry";
vi.mock("posthog-js", () => ({
- default: { capture: vi.fn(), register: vi.fn() },
+ default: {
+ capture: vi.fn(),
+ register: vi.fn(),
+ getGroups: vi.fn(() => ({ organization: "org_123" })),
+ },
}));
-describe("OnboardingTelemetry hint events", () => {
- beforeEach(() => {
- vi.clearAllMocks();
- });
+const customDedupeProperty = ["$", "insert", "_id"].join("");
+const captureResult = {
+ uuid: "capture-id",
+ event: "captured",
+ properties: {},
+};
+
+beforeEach(() => {
+ vi.clearAllMocks();
+ vi.mocked(posthog.capture).mockReturnValue(captureResult);
+});
- it("hintShown captures a layer-2 event with the hint id", () => {
+describe("OnboardingTelemetry", () => {
+ it("captures layer-2 hint events", () => {
OnboardingTelemetry.hintShown("editor", "add-another-block");
- expect(posthog.capture).toHaveBeenCalledWith("onboarding.hint_shown", {
- surface: "editor",
- hint_id: "add-another-block",
- layer: 2,
+ OnboardingTelemetry.hintDismissed("runs", "run-recording");
+ expect(posthog.capture).toHaveBeenNthCalledWith(
+ 1,
+ "onboarding.hint_shown",
+ {
+ surface: "editor",
+ hint_id: "add-another-block",
+ layer: 2,
+ organization_id: "org_123",
+ step_id: "onboarding.hint_shown:v1",
+ },
+ );
+ expect(posthog.capture).toHaveBeenNthCalledWith(
+ 2,
+ "onboarding.hint_dismissed",
+ {
+ surface: "runs",
+ hint_id: "run-recording",
+ layer: 2,
+ organization_id: "org_123",
+ step_id: "onboarding.hint_dismissed:v1",
+ },
+ );
+ });
+
+ it("adds organization and versioned step identity without custom dedupe", () => {
+ OnboardingTelemetry.stepCompleted("discover", "first_agent_created");
+
+ expect(posthog.capture).toHaveBeenCalledWith("onboarding.step_completed", {
+ surface: "discover",
+ step: "first_agent_created",
+ organization_id: "org_123",
+ step_id: "first_agent_created:v1",
});
+ expect(posthog.capture).not.toHaveBeenCalledWith(
+ expect.any(String),
+ expect.objectContaining({
+ [customDedupeProperty]: expect.anything(),
+ }),
+ );
});
- it("hintDismissed captures a layer-2 event with the hint id", () => {
- OnboardingTelemetry.hintDismissed("runs", "run-recording");
- expect(posthog.capture).toHaveBeenCalledWith("onboarding.hint_dismissed", {
- surface: "runs",
- hint_id: "run-recording",
- layer: 2,
+ it("reports whether PostHog accepted a questionnaire capture", () => {
+ const input = {
+ primaryIntent: "fill_forms",
+ promptReason: "initial",
+ } as const;
+ expect(OnboardingTelemetry.questionnaireShown(input)).toBe(true);
+
+ vi.mocked(posthog.capture).mockReturnValueOnce(undefined);
+ expect(OnboardingTelemetry.questionnaireShown(input)).toBe(false);
+
+ vi.mocked(posthog.capture).mockImplementationOnce(() => {
+ throw new Error("capture unavailable");
+ });
+ expect(OnboardingTelemetry.questionnaireShown(input)).toBe(false);
+ });
+
+ it("captures the exact bounded questionnaire dictionaries", () => {
+ const answers = {
+ role: "developer",
+ company_context: "startup",
+ scale_intent: "exploring",
+ referral_source: "search",
+ } as const;
+ OnboardingTelemetry.questionnaireShown({
+ primaryIntent: null,
+ promptReason: "initial",
});
+ OnboardingTelemetry.questionnaireCompleted({
+ responseId: "response",
+ revision: 1,
+ primaryIntent: "fill_forms",
+ answers,
+ });
+ OnboardingTelemetry.questionnaireSkipped({
+ responseId: "response",
+ revision: 2,
+ disposition: "skip",
+ statusAfter: "skipped",
+ });
+ OnboardingTelemetry.questionnaireUpdated({
+ responseId: "response",
+ revision: 3,
+ primaryIntent: "fill_forms",
+ previousStatus: "deferred",
+ answers,
+ });
+
+ expect(posthog.capture).toHaveBeenCalledTimes(4);
+ expect(posthog.capture).toHaveBeenNthCalledWith(
+ 1,
+ "onboarding_questionnaire_shown",
+ {
+ questionnaire_version: 1,
+ "$feature/onboarding_questionnaire_v1": true,
+ surface: "get_started_modal",
+ primary_intent: null,
+ prompt_reason: "initial",
+ organization_id: "org_123",
+ step_id: "onboarding_questionnaire_shown:v1",
+ },
+ );
+ expect(posthog.capture).toHaveBeenNthCalledWith(
+ 2,
+ "onboarding_questionnaire_completed",
+ {
+ questionnaire_version: 1,
+ "$feature/onboarding_questionnaire_v1": true,
+ surface: "get_started_modal",
+ response_id: "response",
+ revision: 1,
+ primary_intent: "fill_forms",
+ ...answers,
+ organization_id: "org_123",
+ step_id: "onboarding_questionnaire_completed:v1",
+ },
+ );
+ expect(posthog.capture).toHaveBeenNthCalledWith(
+ 3,
+ "onboarding_questionnaire_skipped",
+ {
+ questionnaire_version: 1,
+ "$feature/onboarding_questionnaire_v1": true,
+ surface: "get_started_modal",
+ response_id: "response",
+ revision: 2,
+ disposition: "skip",
+ status_after: "skipped",
+ organization_id: "org_123",
+ step_id: "onboarding_questionnaire_skipped:v1",
+ },
+ );
+ expect(posthog.capture).toHaveBeenNthCalledWith(
+ 4,
+ "onboarding_questionnaire_updated",
+ {
+ questionnaire_version: 1,
+ "$feature/onboarding_questionnaire_v1": true,
+ surface: "get_started_modal",
+ response_id: "response",
+ revision: 3,
+ primary_intent: "fill_forms",
+ previous_status: "deferred",
+ ...answers,
+ organization_id: "org_123",
+ step_id: "onboarding_questionnaire_updated:v1",
+ },
+ );
+ expect(JSON.stringify(vi.mocked(posthog.capture).mock.calls)).not.toContain(
+ customDedupeProperty,
+ );
});
});
diff --git a/skyvern-frontend/src/util/onboarding/OnboardingTelemetry.ts b/skyvern-frontend/src/util/onboarding/OnboardingTelemetry.ts
index 93f91df54..6af136cc3 100644
--- a/skyvern-frontend/src/util/onboarding/OnboardingTelemetry.ts
+++ b/skyvern-frontend/src/util/onboarding/OnboardingTelemetry.ts
@@ -1,14 +1,69 @@
-import posthog from "posthog-js";
-
-type Surface = "dashboard" | "editor" | "runs" | "settings" | "api_docs";
+import posthog, { type Properties } from "posthog-js";
+import type {
+ QuestionnaireAnswersV1,
+ QuestionnaireStatusV1,
+ QuestionnaireUserIntentV1,
+} from "@/store/onboarding/types";
+
+type Surface =
+ | "dashboard"
+ | "discover"
+ | "editor"
+ | "runs"
+ | "settings"
+ | "api_docs";
type TourLayer = 1 | 2;
-function capture(event: string, properties: Record<string, unknown>): void {
+type QuestionnaireShownInput = {
+ primaryIntent: QuestionnaireUserIntentV1 | null;
+ promptReason: "initial";
+};
+
+type QuestionnaireResponseInput = {
+ responseId: string;
+ revision: number;
+};
+
+type QuestionnaireAnswerInput = QuestionnaireResponseInput & {
+ primaryIntent: QuestionnaireUserIntentV1;
+ answers: QuestionnaireAnswersV1;
+};
+
+type QuestionnaireSkippedInput = QuestionnaireResponseInput & {
+ disposition: "skip";
+ statusAfter: "skipped";
+};
+
+type QuestionnaireUpdatedInput = QuestionnaireAnswerInput & {
+ previousStatus: QuestionnaireStatusV1;
+};
+
+const ONBOARDING_STEP_VERSION = "v1";
+
+function capture(event: string, properties: Properties): boolean {
+ let organizationId: string | undefined;
try {
- posthog.capture(event, properties);
+ const groupId = posthog.getGroups().organization;
+ if (typeof groupId === "string" && groupId.length > 0) {
+ organizationId = groupId;
+ }
+ } catch {
+ organizationId = undefined;
+ }
+
+ try {
+ const stepName =
+ typeof properties.step === "string" ? properties.step : event;
+ const captureResult = posthog.capture(event, {
+ ...properties,
+ organization_id: organizationId,
+ step_id: `${stepName}:${ONBOARDING_STEP_VERSION}`,
+ });
+ return captureResult !== undefined;
} catch {
// PostHog may be unavailable in tests or before init.
+ return false;
}
}
@@ -97,6 +152,60 @@ function modalSkipped(surface: Surface): void {
capture("onboarding.modal_skipped", { surface });
}
+function questionnaireResponseProperties(input: QuestionnaireResponseInput) {
+ return {
+ questionnaire_version: 1,
+ "$feature/onboarding_questionnaire_v1": true,
+ surface: "get_started_modal",
+ response_id: input.responseId,
+ revision: input.revision,
+ };
+}
+
+function questionnaireAnswerProperties(answers: QuestionnaireAnswersV1) {
+ return {
+ role: answers.role,
+ company_context: answers.company_context,
+ scale_intent: answers.scale_intent,
+ referral_source: answers.referral_source,
+ };
+}
+
+function questionnaireShown(input: QuestionnaireShownInput): boolean {
+ return capture("onboarding_questionnaire_shown", {
+ questionnaire_version: 1,
+ "$feature/onboarding_questionnaire_v1": true,
+ surface: "get_started_modal",
+ primary_intent: input.primaryIntent,
+ prompt_reason: input.promptReason,
+ });
+}
+
+function questionnaireCompleted(input: QuestionnaireAnswerInput): void {
+ capture("onboarding_questionnaire_completed", {
+ ...questionnaireResponseProperties(input),
+ primary_intent: input.primaryIntent,
+ ...questionnaireAnswerProperties(input.answers),
+ });
+}
+
+function questionnaireSkipped(input: QuestionnaireSkippedInput): void {
+ capture("onboarding_questionnaire_skipped", {
+ ...questionnaireResponseProperties(input),
+ disposition: input.disposition,
+ status_after: input.statusAfter,
+ });
+}
+
+function questionnaireUpdated(input: QuestionnaireUpdatedInput): void {
+ capture("onboarding_questionnaire_updated", {
+ ...questionnaireResponseProperties(input),
+ primary_intent: input.primaryIntent,
+ previous_status: input.previousStatus,
+ ...questionnaireAnswerProperties(input.answers),
+ });
+}
+
// -- Activation milestones --
function firstWorkflowCreated(surface: Surface): void {
@@ -178,6 +287,10 @@ export const OnboardingTelemetry = {
modalTemplateSelected,
modalCopilotClicked,
modalSkipped,
+ questionnaireShown,
+ questionnaireCompleted,
+ questionnaireSkipped,
+ questionnaireUpdated,
emptyStateViewed,
emptyStateCTAClicked,
firstWorkflowCreated,
diff --git a/skyvern/browser_extension/broker_client.py b/skyvern/browser_extension/broker_client.py
index 8ac19c68f..3dcda8e8a 100644
--- a/skyvern/browser_extension/broker_client.py
+++ b/skyvern/browser_extension/broker_client.py
@@ -198,6 +198,17 @@ class BrokerClient:
self.scoped_tabs.append(snapshot)
return dict(snapshot)
+ async def list_scoped_tabs(self) -> list[dict[str, Any]]:
+ """Return fresh snapshots for tabs leased to this client."""
+ await self.start()
+ result = await self._control_request("lease.list", {}, 5.0)
+ raw_tabs = result.get("tabs")
+ if not isinstance(raw_tabs, list):
+ raise BrowserExtensionBrokerError("INVALID_FRAME", "Broker tab list is invalid")
+ tabs = _tab_snapshots(raw_tabs)
+ self.scoped_tabs = tabs
+ return [dict(tab) for tab in tabs]
+
async def release_tab(self, tab_id: int) -> None:
"""Release one leased tab according to the broker's authoritative origin."""
await self.start()
@@ -931,11 +942,14 @@ def _tab_snapshots(tabs: list[object]) -> list[dict[str, Any]]:
def _tab_snapshot(value: object) -> dict[str, Any] | None:
if not isinstance(value, dict) or type(value.get("tabId")) is not int:
return None
- return {
+ snapshot: dict[str, Any] = {
"tabId": value["tabId"],
"url": value.get("url") if isinstance(value.get("url"), str) else "",
"title": value.get("title") if isinstance(value.get("title"), str) else "",
}
+ if type(value.get("active")) is bool:
+ snapshot["active"] = value["active"]
+ return snapshot
def _startup_error_message(code: str) -> str:
diff --git a/skyvern/browser_extension/broker_server.py b/skyvern/browser_extension/broker_server.py
index ebbef1dec..50948a411 100644
--- a/skyvern/browser_extension/broker_server.py
+++ b/skyvern/browser_extension/broker_server.py
@@ -92,7 +92,9 @@ CONTROL_INBOUND_TIMEOUT_SECONDS = 45.0
EXTENSION_RESET_TIMEOUT_SECONDS = 5.0
MAX_PENDING_TAB_EVENT_TABS = 64
MAX_PENDING_TAB_EVENTS_PER_TAB = 16
-_LEASED_OPS = frozenset({"debugger.attach", "debugger.send", "debugger.detach", "tabs.activate", "tabs.remove"})
+_LEASED_OPS = frozenset(
+ {"debugger.attach", "debugger.send", "debugger.detach", "dom.evaluate", "tabs.activate", "tabs.remove"}
+)
_WORKSTATION_GRANT_OPS = frozenset({"workstation.grant", "workstation.revoke"})
_APPROVAL_SOURCE_INTERACTIVE = "interactive"
_APPROVAL_SOURCE_GRANT = "grant"
@@ -892,7 +894,7 @@ class BrowserExtensionBrokerServer:
"Approve this agent's browser session in the Skyvern Agent confirmation tab",
)
if (
- op in {"extension.request", "lease.acquire_default"}
+ op in {"extension.request", "lease.acquire_default", "lease.list"}
and relay.connected
and relay.extension_protocol_version != PROTOCOL_VERSION
):
@@ -900,6 +902,31 @@ class BrowserExtensionBrokerServer:
"EXTENSION_UPGRADE_REQUIRED",
"Reload the current Skyvern Agent extension before using this agent",
)
+ if op == "lease.list":
+ if args:
+ raise BrowserExtensionBrokerError("INVALID_REQUEST", "Lease list does not accept arguments")
+ if self._extension_reset_quarantined:
+ raise BrowserExtensionBrokerError(
+ self._extension_reset_error or "EXTENSION_RESET_IN_PROGRESS",
+ "Extension state reset has not completed",
+ retry_after=0.1 if self._extension_reset_error in {None, "EXTENSION_RESET_IN_PROGRESS"} else None,
+ )
+ listed = await relay.request("tabs.list", {}, timeout=5.0)
+ tabs = listed.get("tabs")
+ if not isinstance(tabs, list):
+ raise BrowserExtensionBrokerError("INVALID_FRAME", "Extension tab list is invalid")
+ owned_tab_ids = {
+ tab_id
+ for tab_id, lease in self._leases.items()
+ if not lease.draining and lease.client_id == connection.client_id
+ }
+ return {
+ "tabs": [
+ dict(tab)
+ for tab in tabs
+ if isinstance(tab, dict) and type(tab.get("tabId")) is int and tab["tabId"] in owned_tab_ids
+ ]
+ }
if op == "lease.release":
if set(args) != {"tabId"}:
raise BrowserExtensionBrokerError("INVALID_REQUEST", "Lease release requires only a tabId")
diff --git a/skyvern/browser_extension/extension/README.md b/skyvern/browser_extension/extension/README.md
index 9a971a3ad..fd371e843 100644
--- a/skyvern/browser_extension/extension/README.md
+++ b/skyvern/browser_extension/extension/README.md
@@ -18,25 +18,26 @@ To set it up manually:
2. Open `chrome://extensions`, enable **Developer mode**, and click **Load unpacked**.
3. Select the directory printed by the command.
-4. Start the local MCP server in extension mode:
+4. Open the extension's **Details** page and enable **Allow User Scripts**.
+5. Start the local MCP server in extension mode:
```bash
skyvern run mcp --browser-extension
```
-5. Start explicit pairing:
+6. Start explicit pairing:
```bash
skyvern browser extension-pair
```
-6. The pairing page hands off automatically; click **Approve pairing** in the **Skyvern Agent** confirmation tab
+7. The pairing page hands off automatically; click **Approve pairing** in the **Skyvern Agent** confirmation tab
(the single approval step).
The local pairing page checks that the extension is available before it claims the single-use offer. If pairing starts
before the extension is loaded, keep the page open. It retains the offer and continues automatically after the
extension becomes available.
-7. Add controllable tabs to the **Skyvern Controlled** group.
+8. Add controllable tabs to the **Skyvern Controlled** group.
On POSIX, extension mode uses the persistent broker by default. The first broker start automatically validates or
initializes its journal and copies an existing legacy credential into the owner-only broker run directory, or creates
@@ -73,8 +74,9 @@ The extension connects outbound to `ws://127.0.0.1:19777/extension/v1` by defaul
In broker mode, `extension.secret` is daemon-owned and `skyvern browser extension-token` intentionally refuses to copy
it. Use the explicit pairing command instead. The popup token-paste flow remains available only with the legacy opt-out.
-Chrome's debugger infobar remains visible while Skyvern controls a tab. Clicking **Cancel**, removing the tab with the
-popup, or dragging the tab out of **Skyvern Controlled** revokes access.
+Debugger-backed tools display Chrome's debugger infobar; direct `skyvern_evaluate` calls do not. Clicking **Cancel** in
+the infobar revokes debugger access. Removing a tab with the popup or dragging it out of **Skyvern Controlled** revokes
+all extension access to that tab.
For the complete setup, security model, and limitations, see
[Control Your Chrome with Skyvern Agent](../../../docs/developers/optimization/chrome-extension.mdx).
diff --git a/skyvern/browser_extension/extension/dom_router.js b/skyvern/browser_extension/extension/dom_router.js
new file mode 100644
index 000000000..78045360f
--- /dev/null
+++ b/skyvern/browser_extension/extension/dom_router.js
@@ -0,0 +1,74 @@
+import {
+ ERROR_CODES,
+ ProtocolError,
+ requireArgs,
+ requireTabId,
+} from "./protocol.js";
+
+const MAX_EXPRESSION_LENGTH = 1_000_000;
+
+function assertWebTab(tab) {
+ const url = typeof tab?.url === "string" ? tab.url.trim().toLowerCase() : "";
+ if (!url.startsWith("http://") && !url.startsWith("https://")) {
+ throw new ProtocolError(
+ ERROR_CODES.RESTRICTED_URL,
+ "DOM evaluation is available only on HTTP or HTTPS tabs.",
+ );
+ }
+}
+
+function pageEvaluationError(injectionResult) {
+ if (
+ typeof injectionResult?.error !== "string" ||
+ injectionResult.error.length === 0
+ ) {
+ return null;
+ }
+ return new ProtocolError(
+ ERROR_CODES.CDP_ERROR,
+ `The page expression failed: ${injectionResult.error.slice(0, 500)}`,
+ );
+}
+
+export async function evaluateDom(tabScope, args) {
+ const values = requireArgs(args);
+ if (
+ Object.keys(values).some((key) => !["tabId", "expression"].includes(key)) ||
+ typeof values.expression !== "string" ||
+ values.expression.length === 0 ||
+ values.expression.length > MAX_EXPRESSION_LENGTH
+ ) {
+ throw new ProtocolError(
+ ERROR_CODES.OP_NOT_ALLOWED,
+ "A DOM evaluation requires a valid expression.",
+ );
+ }
+ const tabId = requireTabId(values.tabId);
+ return tabScope.runTabOperation(tabId, async (lease) => {
+ assertWebTab(await tabScope.assertControllableLocked(tabId, lease));
+ let injectionResults;
+ try {
+ injectionResults = await chrome.userScripts.execute({
+ target: { tabId },
+ world: "MAIN",
+ injectImmediately: true,
+ js: [{ code: values.expression }],
+ });
+ } catch {
+ lease.assertCurrent();
+ assertWebTab(await tabScope.assertControllableLocked(tabId, lease));
+ throw new ProtocolError(
+ ERROR_CODES.CDP_ERROR,
+ "Chrome could not run this page expression. Enable Allow User Scripts for Skyvern Agent and retry.",
+ );
+ }
+ lease.assertCurrent();
+ assertWebTab(await tabScope.assertControllableLocked(tabId, lease));
+ const injectionResult = injectionResults?.[0];
+ const evaluationError = pageEvaluationError(injectionResult);
+ if (evaluationError !== null) {
+ throw evaluationError;
+ }
+ return { result: injectionResult?.result ?? null };
+ });
+}
diff --git a/skyvern/browser_extension/extension/manifest.json b/skyvern/browser_extension/extension/manifest.json
index 71625693c..c13eeba1c 100644
--- a/skyvern/browser_extension/extension/manifest.json
+++ b/skyvern/browser_extension/extension/manifest.json
@@ -1,17 +1,19 @@
{
"manifest_version": 3,
"name": "Skyvern Agent",
- "version": "0.2.0",
+ "version": "0.2.8",
"description": "Connects explicitly shared Chrome tabs to a local Skyvern browser session.",
- "minimum_chrome_version": "125",
+ "minimum_chrome_version": "138",
"key": "MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAwePOj+WEmgtKAfyF3PkP6UHuWMvHhJgt0K+53fM9I/WNgu2N4YwCqYjD0h5fr4wCZfwiElUfgwxjDBHwX/Re/Y4G7WlSEG4lDTFNSRGQczHYQnerh8NHR3Gtpq59WKtRxzbbl/e1sVxab6ZyvKjiPZlbmjL44455SldRDPBNJ/5XiSflRkgV1hJ/OOdsVT4ghzjRTJsFhFTK8X0LeMupnYbjgcLb6he0ox+dX/eeDlRt3Sq5uu9+QfJg93/yOo55c0NAa7AW+1+r37GfAtezbqk3fNSraNFfhH+GQhnA6d/KPKTC7Ut2SH1Y8NYHh1yDkyYVr2bq4T6Twr/H0YgL/wIDAQAB",
"permissions": [
"debugger",
+ "userScripts",
"tabs",
"tabGroups",
"storage",
"alarms"
],
+ "host_permissions": ["http://*/*", "https://*/*"],
"background": {
"service_worker": "service_worker.js",
"type": "module"
diff --git a/skyvern/browser_extension/extension/protocol.js b/skyvern/browser_extension/extension/protocol.js
index 8884fbf88..8f0f3951f 100644
--- a/skyvern/browser_extension/extension/protocol.js
+++ b/skyvern/browser_extension/extension/protocol.js
@@ -20,6 +20,7 @@ export const OPS = Object.freeze({
DEBUGGER_ATTACH: "debugger.attach",
DEBUGGER_DETACH: "debugger.detach",
DEBUGGER_SEND: "debugger.send",
+ DOM_EVALUATE: "dom.evaluate",
SHARE_TAB: "shareTab",
UNSHARE_TAB: "unshareTab",
TABS_CREATE: "tabs.create",
diff --git a/skyvern/browser_extension/extension/service_worker.js b/skyvern/browser_extension/extension/service_worker.js
index 57250ae64..7c9e632e3 100644
--- a/skyvern/browser_extension/extension/service_worker.js
+++ b/skyvern/browser_extension/extension/service_worker.js
@@ -1,5 +1,6 @@
import { BridgeConnection } from "./bridge_connection.js";
import { DebuggerRouter } from "./debugger_router.js";
+import { evaluateDom } from "./dom_router.js";
import {
ERROR_CODES,
EVENTS,
@@ -49,6 +50,7 @@ const handlers = new Map([
[OPS.DEBUGGER_ATTACH, (args) => debuggerRouter.attach(args)],
[OPS.DEBUGGER_DETACH, (args) => debuggerRouter.detach(args)],
[OPS.DEBUGGER_SEND, (args) => debuggerRouter.send(args)],
+ [OPS.DOM_EVALUATE, (args) => evaluateDom(tabScope, args)],
[OPS.TABS_CREATE, (args) => tabScope.create(args)],
[OPS.TABS_REMOVE, (args) => tabScope.remove(args)],
[OPS.TABS_ACTIVATE, (args) => tabScope.activate(args)],
diff --git a/skyvern/browser_extension/extension/tab_scope.js b/skyvern/browser_extension/extension/tab_scope.js
index 5fd54e452..abef542cf 100644
--- a/skyvern/browser_extension/extension/tab_scope.js
+++ b/skyvern/browser_extension/extension/tab_scope.js
@@ -15,6 +15,11 @@ const SKYVERN_GROUP_COLOR = "purple";
const TAB_GROUP_ID_NONE = -1;
const ANY_GROUP_ID = Symbol("anyGroupId");
const TAB_OPERATION_TIMEOUT_MS = 28_000;
+const SCOPE_REVOCATION_CODES = new Set([
+ ERROR_CODES.TAB_NOT_FOUND,
+ ERROR_CODES.TAB_NOT_SCOPED,
+ ERROR_CODES.RESTRICTED_URL,
+]);
function tabUrl(tab) {
return tab.pendingUrl || tab.url || "";
@@ -26,6 +31,12 @@ function isTabRestricted(tab) {
);
}
+function isScopeRevocation(error) {
+ return (
+ error instanceof ProtocolError && SCOPE_REVOCATION_CODES.has(error.code)
+ );
+}
+
export class TabScope {
constructor({ sendEvent, operationTimeoutMs = TAB_OPERATION_TIMEOUT_MS }) {
this.sendEvent = sendEvent;
@@ -36,6 +47,7 @@ export class TabScope {
this.expectedGroupTransitions = new Map();
this.tabOperations = new Map();
this.debuggerRouter = null;
+ this.tabOperationLeases = new Map();
this.activeOperationCount = 0;
this.operationGeneration = 0;
this.operationLeases = new Set();
@@ -53,6 +65,13 @@ export class TabScope {
void this.handleTabCreated(tab);
});
chrome.tabs.onRemoved.addListener((tabId) => {
+ this.cancelTabOperations(
+ tabId,
+ new ProtocolError(
+ ERROR_CODES.TAB_NOT_FOUND,
+ "The controlled tab was closed.",
+ ),
+ );
void this.handleTabRemoved(tabId);
});
chrome.tabs.onUpdated.addListener((tabId, changeInfo) => {
@@ -63,6 +82,7 @@ export class TabScope {
const expectedGroupTransition = Object.hasOwn(changeInfo, "groupId")
? this.getExpectedGroupTransition(tabId, changeInfo.groupId)
: null;
+ this.cancelForTabUpdate(tabId, changeInfo, expectedGroupTransition);
void this.handleTabUpdated(tabId, changeInfo, expectedGroupTransition);
}
});
@@ -102,7 +122,11 @@ export class TabScope {
) {
for (const [tabId, groupId] of Object.entries(storedGroups)) {
const numericTabId = Number(tabId);
- if (this.scopedTabIds.has(numericTabId) && Number.isInteger(groupId)) {
+ if (
+ this.scopedTabIds.has(numericTabId) &&
+ Number.isInteger(groupId) &&
+ groupId >= 0
+ ) {
this.scopedGroupIds.set(numericTabId, groupId);
}
}
@@ -182,6 +206,57 @@ export class TabScope {
return this.quarantinedTabIds.has(tabId);
}
+ cancelTabOperations(tabId, error) {
+ for (const lease of this.tabOperationLeases.get(tabId) ?? []) {
+ lease.cancel(error);
+ }
+ }
+ trackTabOperationLease(tabId, lease) {
+ const tabLeases = this.tabOperationLeases.get(tabId) ?? new Set();
+ tabLeases.add(lease);
+ this.tabOperationLeases.set(tabId, tabLeases);
+ }
+
+ untrackTabOperationLease(lease) {
+ for (const [tabId, tabLeases] of this.tabOperationLeases) {
+ tabLeases.delete(lease);
+ if (tabLeases.size === 0) {
+ this.tabOperationLeases.delete(tabId);
+ }
+ }
+ }
+
+ cancelForTabUpdate(tabId, changeInfo, expectedGroupTransition) {
+ if (!this.scopedTabIds.has(tabId)) {
+ return;
+ }
+ if (Object.hasOwn(changeInfo, "url")) {
+ const restricted = isRestrictedUrl(changeInfo.url);
+ this.cancelTabOperations(
+ tabId,
+ new ProtocolError(
+ restricted ? ERROR_CODES.RESTRICTED_URL : ERROR_CODES.COMMAND_TIMEOUT,
+ restricted
+ ? "Chrome does not allow controlling this URL."
+ : "The page changed while the extension operation was running.",
+ ),
+ );
+ return;
+ }
+ if (
+ Object.hasOwn(changeInfo, "groupId") &&
+ expectedGroupTransition === null &&
+ changeInfo.groupId !== this.scopedGroupIds.get(tabId)
+ ) {
+ this.cancelTabOperations(
+ tabId,
+ new ProtocolError(
+ ERROR_CODES.TAB_NOT_SCOPED,
+ "The tab left Skyvern Controlled.",
+ ),
+ );
+ }
+ }
async assertScoped(tabId) {
await this.ready;
if (!this.scopedTabIds.has(tabId)) {
@@ -206,6 +281,23 @@ export class TabScope {
}
lease?.assertCurrent();
await this.assertScoped(tabId);
+ const expectedGroupId = this.scopedGroupIds.get(tabId);
+ let controlledGroup = null;
+ if (expectedGroupId !== undefined && tab.groupId === expectedGroupId) {
+ controlledGroup = await this.getControlledGroup(tab.groupId);
+ lease?.assertCurrent();
+ }
+ if (
+ expectedGroupId === undefined ||
+ tab.groupId !== expectedGroupId ||
+ controlledGroup === null
+ ) {
+ await this.removeFromScopeLocked(tabId, "unshared", true, lease);
+ throw new ProtocolError(
+ ERROR_CODES.TAB_NOT_SCOPED,
+ "The requested tab is no longer in Skyvern Controlled.",
+ );
+ }
if (isTabRestricted(tab)) {
await this.removeFromScopeLocked(tabId, "unshared", true, lease);
throw new ProtocolError(
@@ -292,6 +384,8 @@ export class TabScope {
"Chrome did not return a tab identifier.",
);
}
+ this.trackTabOperationLease(tab.id, lease);
+ lease.assertCurrent();
this.createdTabIds.add(tab.id);
await this.persistScope(lease);
try {
@@ -405,6 +499,19 @@ export class TabScope {
async list() {
await this.ready;
const tabs = await this.collectScopedTabs(true);
+ let focusedTabId = null;
+ try {
+ const [focusedTab] = await chrome.tabs.query({
+ active: true,
+ lastFocusedWindow: true,
+ });
+ if (Number.isInteger(focusedTab?.id)) {
+ focusedTabId = focusedTab.id;
+ }
+ } catch {}
+ for (const tab of tabs) {
+ tab.active = tab.tabId === focusedTabId;
+ }
return { tabs };
}
@@ -426,131 +533,161 @@ export class TabScope {
if (!Number.isInteger(tab.id) || !Number.isInteger(tab.openerTabId)) {
return;
}
- await this.runTabOperation(tab.id, async (lease) => {
- if (!this.scopedTabIds.has(tab.openerTabId) || isTabRestricted(tab)) {
- return;
- }
- lease.assertCurrent();
- this.createdTabIds.add(tab.id);
- await this.persistScope(lease);
+ await this.runTabOperation(tab.openerTabId, async (openerLease) => {
try {
- const scopedTab = await this.addToScopeLocked(tab, lease);
- lease.assertCurrent();
- this.sendEvent(EVENTS.TABS_CREATED, {
- tabId: scopedTab.id,
- openerTabId: tab.openerTabId,
- url: tabUrl(scopedTab),
- });
+ await this.assertControllableLocked(tab.openerTabId, openerLease);
} catch (error) {
- try {
- await this.closeCreatedTab(tab.id);
- } catch {
- // Preserve the original setup error. The tab-removal event retries persistence.
+ if (isScopeRevocation(error)) {
+ return;
}
throw error;
}
+ if (isTabRestricted(tab)) {
+ return;
+ }
+ await this.runTabOperation(tab.id, async (lease) => {
+ openerLease.assertCurrent();
+ await this.assertControllableLocked(tab.openerTabId, openerLease);
+ this.createdTabIds.add(tab.id);
+ await this.persistScope(lease);
+ try {
+ const scopedTab = await this.addToScopeLocked(tab, lease);
+ openerLease.assertCurrent();
+ await this.assertControllableLocked(tab.openerTabId, openerLease);
+ lease.assertCurrent();
+ this.sendEvent(EVENTS.TABS_CREATED, {
+ tabId: scopedTab.id,
+ openerTabId: tab.openerTabId,
+ url: tabUrl(scopedTab),
+ });
+ } catch (error) {
+ if (this.scopedTabIds.has(tab.id)) {
+ try {
+ await this.removeFromScopeLocked(tab.id, "unshared", true, lease);
+ } catch {
+ // Continue closing the child tab.
+ }
+ }
+ try {
+ await this.closeCreatedTab(tab.id);
+ } catch {
+ // Preserve the original setup error. The tab-removal event retries persistence.
+ }
+ throw error;
+ }
+ });
});
}
async handleTabRemoved(tabId) {
await this.ready;
- await this.runTabOperation(tabId, async (lease) => {
- lease.assertCurrent();
- this.expectedGroupTransitions.delete(tabId);
- const ownershipChanged = this.createdTabIds.delete(tabId);
- if (this.scopedTabIds.has(tabId)) {
- await this.removeFromScopeLocked(tabId, "closed", false, lease);
- } else if (ownershipChanged) {
- await this.persistScope(lease);
- }
- });
+ await this.runTabOperation(
+ tabId,
+ async (lease) => {
+ lease.assertCurrent();
+ this.expectedGroupTransitions.delete(tabId);
+ const ownershipChanged = this.createdTabIds.delete(tabId);
+ if (this.scopedTabIds.has(tabId)) {
+ await this.removeFromScopeLocked(tabId, "closed", false, lease);
+ } else if (ownershipChanged) {
+ await this.persistScope(lease);
+ }
+ },
+ this.operationGeneration,
+ false,
+ );
}
async handleTabUpdated(tabId, changeInfo, expectedGroupTransition = null) {
await this.ready;
- await this.runTabOperation(tabId, async (lease) => {
- try {
- lease.assertCurrent();
- if (
- this.scopedTabIds.has(tabId) &&
- Object.hasOwn(changeInfo, "url") &&
- isRestrictedUrl(changeInfo.url)
- ) {
- await this.removeFromScopeLocked(tabId, "unshared", true, lease);
- return;
- }
- if (
- !Object.hasOwn(changeInfo, "groupId") ||
- expectedGroupTransition !== null
- ) {
- return;
- }
-
- let tab;
+ await this.runTabOperation(
+ tabId,
+ async (lease) => {
try {
- tab = await chrome.tabs.get(tabId);
- } catch {
- return;
- }
- lease.assertCurrent();
- if (tab.groupId !== changeInfo.groupId) {
- return;
- }
-
- const controlledGroup = await this.getControlledGroup(tab.groupId);
- lease.assertCurrent();
- if (this.scopedTabIds.has(tabId)) {
- const expectedGroupId = this.scopedGroupIds.get(tabId);
- if (tab.groupId === expectedGroupId) {
+ lease.assertCurrent();
+ if (
+ this.scopedTabIds.has(tabId) &&
+ Object.hasOwn(changeInfo, "url") &&
+ isRestrictedUrl(changeInfo.url)
+ ) {
+ await this.removeFromScopeLocked(tabId, "unshared", true, lease);
return;
}
- if (controlledGroup !== null) {
- this.scopedGroupIds.set(tabId, tab.groupId);
- await this.persistScope(lease);
- lease.assertCurrent();
- await this.updateControlledGroup(tab.groupId);
+ if (
+ !Object.hasOwn(changeInfo, "groupId") ||
+ expectedGroupTransition !== null
+ ) {
return;
}
- if (expectedGroupId !== undefined) {
- await this.removeFromScopeLocked(tabId, "unshared", true, lease);
+
+ let tab;
+ try {
+ tab = await chrome.tabs.get(tabId);
+ } catch {
+ return;
+ }
+ lease.assertCurrent();
+ if (tab.groupId !== changeInfo.groupId) {
+ return;
}
- return;
- }
- if (controlledGroup === null) {
- return;
- }
- if (isTabRestricted(tab)) {
+ const controlledGroup = await this.getControlledGroup(tab.groupId);
lease.assertCurrent();
- await this.ungroupTabLocked(tabId, tab.groupId);
- return;
- }
+ if (this.scopedTabIds.has(tabId)) {
+ const expectedGroupId = this.scopedGroupIds.get(tabId);
+ if (tab.groupId === expectedGroupId) {
+ return;
+ }
+ if (controlledGroup !== null) {
+ this.scopedGroupIds.set(tabId, tab.groupId);
+ await this.persistScope(lease);
+ lease.assertCurrent();
+ await this.updateControlledGroup(tab.groupId);
+ return;
+ }
+ if (expectedGroupId !== undefined) {
+ await this.removeFromScopeLocked(tabId, "unshared", true, lease);
+ }
+ return;
+ }
- if (this.quarantinedTabIds.has(tabId)) {
- throw new ProtocolError(
- ERROR_CODES.COMMAND_TIMEOUT,
- "The requested tab is still being reconciled after reset.",
+ if (controlledGroup === null) {
+ return;
+ }
+ if (isTabRestricted(tab)) {
+ lease.assertCurrent();
+ await this.ungroupTabLocked(tabId, tab.groupId);
+ return;
+ }
+
+ if (this.quarantinedTabIds.has(tabId)) {
+ throw new ProtocolError(
+ ERROR_CODES.COMMAND_TIMEOUT,
+ "The requested tab is still being reconciled after reset.",
+ );
+ }
+ lease.assertCurrent();
+ await this.updateControlledGroup(tab.groupId);
+ lease.assertCurrent();
+ const scopedTab = await this.addGroupedTabToScopeLocked(
+ tab,
+ tab.groupId,
+ lease,
);
+ lease.assertCurrent();
+ this.sendEvent(EVENTS.SCOPE_TAB_ADDED, {
+ ...this.publicTab(scopedTab, false),
+ origin: "shared",
+ });
+ } finally {
+ if (expectedGroupTransition !== null) {
+ this.clearExpectedGroupTransition(tabId, expectedGroupTransition);
+ }
}
- lease.assertCurrent();
- await this.updateControlledGroup(tab.groupId);
- lease.assertCurrent();
- const scopedTab = await this.addGroupedTabToScopeLocked(
- tab,
- tab.groupId,
- lease,
- );
- lease.assertCurrent();
- this.sendEvent(EVENTS.SCOPE_TAB_ADDED, {
- ...this.publicTab(scopedTab, false),
- origin: "shared",
- });
- } finally {
- if (expectedGroupTransition !== null) {
- this.clearExpectedGroupTransition(tabId, expectedGroupTransition);
- }
- }
- });
+ },
+ this.operationGeneration,
+ false,
+ );
}
async closeCreatedTab(tabId) {
@@ -587,11 +724,18 @@ export class TabScope {
);
}
this.scopedTabIds.add(tab.id);
- await this.persistScope(lease);
- lease?.assertCurrent();
- await this.groupTabLocked(tab, lease);
- lease?.assertCurrent();
- return this.assertControllableLocked(tab.id, lease);
+ try {
+ await this.persistScope(lease);
+ lease?.assertCurrent();
+ await this.groupTabLocked(tab, lease);
+ lease?.assertCurrent();
+ return await this.assertControllableLocked(tab.id, lease);
+ } catch (error) {
+ this.scopedTabIds.delete(tab.id);
+ this.scopedGroupIds.delete(tab.id);
+ await this.persistScope(lease);
+ throw error;
+ }
}
async addGroupedTabToScopeLocked(tab, groupId, lease = null) {
@@ -644,7 +788,10 @@ export class TabScope {
async groupTabLocked(tab, lease = null) {
const tabId = tab.id;
if (!Number.isInteger(tabId) || !Number.isInteger(tab.windowId)) {
- return;
+ throw new ProtocolError(
+ ERROR_CODES.TAB_NOT_FOUND,
+ "Chrome returned an invalid tab for Skyvern Controlled.",
+ );
}
let groupId;
try {
@@ -677,12 +824,23 @@ export class TabScope {
if (error instanceof ProtocolError) {
throw error;
}
- return;
+ throw new ProtocolError(
+ ERROR_CODES.INTERNAL,
+ "Chrome could not add the tab to Skyvern Controlled.",
+ );
}
lease?.assertCurrent();
this.scopedGroupIds.set(tabId, groupId);
await this.persistScope(lease);
- await this.updateControlledGroup(groupId);
+ if (!(await this.updateControlledGroup(groupId))) {
+ await this.ungroupTabLocked(tabId, groupId);
+ this.scopedGroupIds.delete(tabId);
+ await this.persistScope(lease);
+ throw new ProtocolError(
+ ERROR_CODES.INTERNAL,
+ "Chrome could not label the Skyvern Controlled group.",
+ );
+ }
}
async ungroupTabLocked(tabId, scopedGroupId) {
@@ -730,8 +888,9 @@ export class TabScope {
title: SKYVERN_GROUP_TITLE,
color: SKYVERN_GROUP_COLOR,
});
+ return true;
} catch {
- return;
+ return false;
}
}
@@ -769,20 +928,15 @@ export class TabScope {
if (!this.scopedTabIds.has(tabId)) {
return null;
}
- let scopedTab;
try {
- scopedTab = await chrome.tabs.get(tabId);
- } catch {
- lease.assertCurrent();
- await this.removeFromScopeLocked(tabId, "closed", false, lease);
- return null;
- }
- lease.assertCurrent();
- if (isTabRestricted(scopedTab)) {
- await this.removeFromScopeLocked(tabId, "unshared", true, lease);
- return null;
+ const scopedTab = await this.assertControllableLocked(tabId, lease);
+ return this.publicTab(scopedTab, includeActive);
+ } catch (error) {
+ if (isScopeRevocation(error)) {
+ return null;
+ }
+ throw error;
}
- return this.publicTab(scopedTab, includeActive);
},
generation,
);
@@ -849,22 +1003,13 @@ export class TabScope {
}
const expectedGroupId = this.scopedGroupIds.get(tabId);
if (
- expectedGroupId !== undefined &&
+ expectedGroupId === undefined ||
tab.groupId !== expectedGroupId
) {
- const controlledGroup = await this.getControlledGroup(tab.groupId);
- lease.assertCurrent();
- if (controlledGroup === null) {
- await this.removeFromScopeLocked(tabId, "unshared", true, lease);
- } else {
- this.scopedGroupIds.set(tabId, tab.groupId);
- await this.persistScope(lease);
- lease.assertCurrent();
- await this.updateControlledGroup(tab.groupId);
- }
- } else if (expectedGroupId === undefined) {
- await this.groupTabLocked(tab, lease);
+ await this.removeFromScopeLocked(tabId, "unshared", true, lease);
+ return;
}
+ await this.assertControllableLocked(tabId, lease);
},
generation,
);
@@ -875,6 +1020,7 @@ export class TabScope {
tabId,
operation,
expectedGeneration = this.operationGeneration,
+ cancelOnTabEvent = true,
) {
while (this.resetting) {
await this.resetFinished;
@@ -905,6 +1051,9 @@ export class TabScope {
}
this.activeOperationCount += 1;
this.operationLeases.add(lease);
+ if (cancelOnTabEvent) {
+ this.trackTabOperationLease(tabId, lease);
+ }
const previous = this.tabOperations.get(tabId) ?? Promise.resolve();
const current = previous
.catch(() => undefined)
@@ -917,6 +1066,7 @@ export class TabScope {
this.tabOperations.delete(tabId);
}
this.operationLeases.delete(lease);
+ this.untrackTabOperationLease(lease);
clearTimeout(timeoutId);
this.activeOperationCount -= 1;
if (this.activeOperationCount === 0) {
diff --git a/skyvern/browser_extension/protocol.py b/skyvern/browser_extension/protocol.py
index 37b583e45..3b04142d7 100644
--- a/skyvern/browser_extension/protocol.py
+++ b/skyvern/browser_extension/protocol.py
@@ -17,6 +17,7 @@ ALLOWED_OPS = frozenset(
"debugger.attach",
"debugger.detach",
"debugger.send",
+ "dom.evaluate",
"tabs.create",
"tabs.remove",
"tabs.activate",
diff --git a/skyvern/browser_extension/relay.py b/skyvern/browser_extension/relay.py
index 1dd24bd0d..1fdbaae29 100644
--- a/skyvern/browser_extension/relay.py
+++ b/skyvern/browser_extension/relay.py
@@ -613,6 +613,15 @@ class ExtensionRelayServer:
return None
return dict(self.scoped_tabs[0])
+ async def list_scoped_tabs(self) -> list[dict]:
+ """Return current tab snapshots from the embedded single-owner extension."""
+ result = await self.request("tabs.list", {})
+ tabs = result.get("tabs")
+ if not isinstance(tabs, list):
+ raise ExtensionRequestError("INTERNAL", "The extension returned an invalid tab list")
+ self.scoped_tabs = [snapshot for tab in tabs if (snapshot := _tab_snapshot(tab)) is not None]
+ return [dict(tab) for tab in self.scoped_tabs]
+
async def release_tab(self, tab_id: int) -> None:
"""Embedded single-owner relay keeps user tabs open when its CDP client closes."""
await self.request("debugger.detach", {"tabId": tab_id}, timeout=2.0)
@@ -1223,8 +1232,11 @@ def _tab_snapshot(value: object) -> dict | None:
return None
url = value.get("url")
title = value.get("title")
- return {
+ snapshot = {
"tabId": tab_id,
"url": url if isinstance(url, str) else "",
"title": title if isinstance(title, str) else "",
}
+ if type(value.get("active")) is bool:
+ snapshot["active"] = value["active"]
+ return snapshot
diff --git a/skyvern/browser_extension/runtime.py b/skyvern/browser_extension/runtime.py
index 5fd33ca85..a5547274c 100644
--- a/skyvern/browser_extension/runtime.py
+++ b/skyvern/browser_extension/runtime.py
@@ -55,6 +55,7 @@ class _Relay(Protocol):
async def request(self, op: str, args: dict, timeout: float = 30.0) -> dict: ...
async def ensure_root_lease(self) -> dict | None: ...
+ async def list_scoped_tabs(self) -> list[dict]: ...
async def release_tab(self, tab_id: int) -> None: ...
@@ -176,6 +177,23 @@ class BrowserExtensionRuntime:
async def wait_for_extension(self, timeout: float = 10.0) -> bool:
return await self._relay.wait_connected(timeout)
+ async def evaluate(self, expression: str) -> Any:
+ await self._relay.ensure_root_lease()
+ tabs = await self._relay.list_scoped_tabs()
+ candidates = [tab for tab in tabs if type(tab.get("tabId")) is int]
+ active = [tab for tab in candidates if tab.get("active") is True]
+ if len(active) == 1:
+ tab = active[0]
+ elif len(candidates) == 1:
+ tab = candidates[0]
+ else:
+ raise BrowserExtensionError("Select one Skyvern Controlled tab before evaluating JavaScript")
+ result = await self._relay.request(
+ "dom.evaluate",
+ {"tabId": tab["tabId"], "expression": expression},
+ )
+ return result.get("result")
+
@staticmethod
def open_extension_url(url: str) -> bool:
if sys.platform == "darwin":
diff --git a/skyvern/cli/commands/browser.py b/skyvern/cli/commands/browser.py
index 8cd26be2b..ef9dc20b4 100644
--- a/skyvern/cli/commands/browser.py
+++ b/skyvern/cli/commands/browser.py
@@ -645,11 +645,12 @@ def extension_install() -> None:
console.print("1. Enable Developer mode.")
console.print("2. Click Load unpacked.")
console.print(f"3. Select {extension_dir}.", markup=False, soft_wrap=True)
+ console.print("4. Open Skyvern Agent details and enable Allow User Scripts.")
console.print(
- "4. Start your extension-mode MCP server; its first broker start enables broker state automatically."
+ "5. Start your extension-mode MCP server; its first broker start enables broker state automatically."
)
- console.print("5. Run skyvern browser extension-pair to start explicit pairing.")
- console.print('6. Add tabs to the "Skyvern Controlled" group.')
+ console.print("6. Run skyvern browser extension-pair to start explicit pairing.")
+ console.print('7. Add tabs to the "Skyvern Controlled" group.')
return
try:
@@ -674,17 +675,18 @@ def extension_install() -> None:
console.print("1. Enable Developer mode.")
console.print("2. Click Load unpacked.")
console.print(f"3. Select {extension_dir}.", markup=False, soft_wrap=True)
+ console.print("4. Open Skyvern Agent details and enable Allow User Scripts.")
if bridge_listening and port is not None:
- console.print("4. Approve pairing in the Skyvern Agent confirmation tab (one click).")
- console.print('5. Add tabs to the "Skyvern Controlled" group.')
+ console.print("5. Approve pairing in the Skyvern Agent confirmation tab (one click).")
+ console.print('6. Add tabs to the "Skyvern Controlled" group.')
try:
_launch_extension_pairing(port)
except BrowserExtensionError:
console.print("Automatic pairing could not start. Run skyvern browser extension-pair after setup.")
else:
- console.print("4. Open the Skyvern Agent popup.")
- console.print("5. Paste the pairing token and click Connect.")
- console.print('6. Add tabs to the "Skyvern Controlled" group.')
+ console.print("5. Open the Skyvern Agent popup.")
+ console.print("6. Paste the pairing token and click Connect.")
+ console.print('7. Add tabs to the "Skyvern Controlled" group.')
console.print("When your MCP server is running, pair with: skyvern browser extension-pair")
diff --git a/skyvern/cli/mcp_tools/browser.py b/skyvern/cli/mcp_tools/browser.py
index bfd101f4f..a9003eeec 100644
--- a/skyvern/cli/mcp_tools/browser.py
+++ b/skyvern/cli/mcp_tools/browser.py
@@ -2450,6 +2450,43 @@ async def skyvern_evaluate(
js = _wrap_async_iife(expression)
+ current = get_current_session()
+ current_context = getattr(current, "context", None)
+ from skyvern.browser_extension.runtime import BrowserExtensionRuntime
+
+ extension_runtime = BrowserExtensionRuntime.instance()
+ direct_extension_evaluation = (
+ extension_runtime is not None
+ and current_context is not None
+ and current_context.mode == "extension"
+ and cdp_url is None
+ and (session_id is None or session_id == current_context.session_id)
+ )
+ if direct_extension_evaluation and extension_runtime is not None and current_context is not None:
+ browser_context = current_context
+ with Timer() as timer:
+ try:
+ result = await extension_runtime.evaluate(js)
+ timer.mark("extension")
+ except Exception as exc:
+ return make_result(
+ "skyvern_evaluate",
+ ok=False,
+ browser_context=browser_context,
+ timing_ms=timer.timing_ms,
+ error=make_error(
+ ErrorCode.ACTION_FAILED,
+ str(exc),
+ "Select one HTTP(S) tab in Skyvern Controlled and enable Allow User Scripts",
+ ),
+ )
+ return make_result(
+ "skyvern_evaluate",
+ browser_context=browser_context,
+ data={"result": result, "sdk_equivalent": f"await page.evaluate({expression[:80]!r})"},
+ timing_ms=timer.timing_ms,
+ )
+
try:
page, ctx = await get_page(session_id=session_id, cdp_url=cdp_url)
except BrowserNotAvailableError as exc:
diff --git a/skyvern/config.py b/skyvern/config.py
index 6322d1294..9ddd81c4d 100644
--- a/skyvern/config.py
+++ b/skyvern/config.py
@@ -266,6 +266,12 @@ class Settings(BaseSettings):
# Kill switch for the live codegen-progress SSE frame (drafted block labels while an authoring
# tool call streams). Off restores exact pre-change behavior; old frontends drop the frame either way.
WORKFLOW_COPILOT_CODEGEN_PROGRESS_ENABLED: bool = True
+ # Admits the Odysseys benchmark's typed entry-point input on the copilot chat route, and only
+ # together with the X-Copilot-Eval header. Never enabled outside the dedicated eval lane.
+ WORKFLOW_COPILOT_ODYSSEYS_EVAL_INPUTS_ENABLED: bool = False
+ # The caller-supplied header is not an authorization: on a shared deployment only API
+ # credentials belonging to these explicitly configured eval organizations may seed an entry point.
+ WORKFLOW_COPILOT_ODYSSEYS_EVAL_ORGANIZATION_IDS: list[str] = []
# Local-development escape hatch: run a copilot block test run in the API process when sandbox
# dispatch is unavailable, instead of failing closed. Grants nothing on its own -- see
# AgentFunction.allow_copilot_inline_code_execution for the conditions it is ANDed with.
diff --git a/skyvern/cors.py b/skyvern/cors.py
index 5d117941e..aeeba7e2e 100644
--- a/skyvern/cors.py
+++ b/skyvern/cors.py
@@ -1,9 +1,55 @@
from collections.abc import Sequence
+from typing import Any
import structlog
LOG = structlog.get_logger(__name__)
+WILDCARD_ORIGIN = "*"
+
+
+def cors_allows_any_origin(allowed_origins: Sequence[str]) -> bool:
+ return any(origin.strip() == WILDCARD_ORIGIN for origin in allowed_origins)
+
+
+def cors_middleware_kwargs(
+ allowed_origins: Sequence[str],
+ allowed_origin_regex: str | None,
+ expose_headers: list[str] | None = None,
+) -> dict[str, Any]:
+ """Build the CORSMiddleware kwargs for the app-level CORS policy.
+
+ An exact "*" (the self-hosted default) allows every origin, but never with credentials:
+ wildcard + allow_credentials lets any site send cookie-authenticated requests.
+ Header-based API-key auth does not need CORS credentials.
+ """
+ kwargs: dict[str, Any]
+ if cors_allows_any_origin(allowed_origins):
+ discarded_origins = [
+ stripped for origin in allowed_origins if (stripped := origin.strip()) and stripped != WILDCARD_ORIGIN
+ ]
+ LOG.warning(
+ "Wildcard CORS origin configured; allowing every origin without credentials",
+ discarded_origin_count=len(discarded_origins),
+ origin_regex_configured=credentialed_cors_allow_origin_regex(allowed_origin_regex) is not None,
+ )
+ kwargs = {
+ "allow_origins": [WILDCARD_ORIGIN],
+ "allow_methods": ["*"],
+ "allow_headers": ["*"],
+ }
+ else:
+ kwargs = {
+ "allow_origins": credentialed_cors_allow_origins(allowed_origins),
+ "allow_credentials": True,
+ "allow_methods": ["*"],
+ "allow_headers": ["*"],
+ "allow_origin_regex": credentialed_cors_allow_origin_regex(allowed_origin_regex),
+ }
+ if expose_headers is not None:
+ kwargs["expose_headers"] = expose_headers
+ return kwargs
+
def credentialed_cors_allow_origins(allowed_origins: Sequence[str]) -> list[str]:
wildcard_origin_count = 0
diff --git a/skyvern/forge/agent.py b/skyvern/forge/agent.py
index bfe19a63e..4bed3186b 100644
--- a/skyvern/forge/agent.py
+++ b/skyvern/forge/agent.py
@@ -80,6 +80,7 @@ from skyvern.forge.failure_classifier import classify_from_failure_reason
from skyvern.forge.prompts import prompt_engine
from skyvern.forge.sdk.api.aws import get_aws_client
from skyvern.forge.sdk.api.files import (
+ calculate_sha256_for_file,
get_path_for_workflow_download_directory,
list_downloading_files_in_directory,
list_files_in_directory,
@@ -917,6 +918,23 @@ class ForgeAgent:
]
if not files_to_rename:
return []
+ # A persistent-session download lands in the session dir and, for blob: URLs, is also written to
+ # the run dir by the eager carve-out; dedupe the session copy by content so FileUploadBlock uploads
+ # one file, not two (SKY-14276). Seed the snapshot only from local paths newly discovered for this
+ # task (the eager carve-out copies) — never from baseline files already present before the task, or
+ # a new session download that happens to share bytes with a baseline would be wrongly dropped. With
+ # no s3://, gs:// candidate nothing consults the snapshot, so no local file is hashed either.
+ run_dir_checksums: set[str] = set()
+ if any(file.startswith(("s3://", "gs://")) for file in files_to_rename):
+ for local_file in files_to_rename:
+ if local_file.startswith(("s3://", "gs://")):
+ continue
+ try:
+ run_dir_checksums.add(calculate_sha256_for_file(local_file))
+ except OSError:
+ # A listed file that can't be read (vanished mid-finalization, permissions) just
+ # doesn't participate in dedupe — fail open toward materializing, never toward dropping.
+ continue
for file in files_to_rename:
local_file_name = file
if file.startswith(("s3://", "gs://")):
@@ -926,6 +944,10 @@ class ForgeAgent:
file_data = await get_gcs_client().download_file(file, log_exception=False)
if not file_data:
continue
+ candidate_checksum = hashlib.sha256(file_data).hexdigest()
+ if candidate_checksum in run_dir_checksums:
+ continue
+ run_dir_checksums.add(candidate_checksum)
local_file_name = file.split("/")[-1]
with open(os.path.join(workflow_download_directory, local_file_name), "wb") as f:
f.write(file_data)
@@ -1843,6 +1865,11 @@ class ForgeAgent:
staged_downloads=staged_downloads,
deadline_seconds=loop_deadline_seconds,
verification_blocker=verification_state.block_completion,
+ # Only for a bare task, where setup navigated this browser_state to task.url and the
+ # status unambiguously belongs to the starting posting. A workflow block reuses the
+ # browser_state across blocks, so its last status may be a prior block's — skip it there
+ # and let the in-loop `navigate` classifier cover block-driven dead-ends.
+ initial_navigation_status=(browser_state.last_navigation_status if task_block is None else None),
)
finally:
if context and credential_parameter_key is not None:
@@ -4911,6 +4938,10 @@ class ForgeAgent:
) -> tuple[Step, BrowserState, DetailedAgentStepOutput]:
if pre_resolved_browser_state is not None:
browser_state = pre_resolved_browser_state
+ # An inherited browser_state was NOT navigated to this task's url here, so its
+ # last_navigation_status belongs to an earlier navigation, not this task's starting URL.
+ # Clear it so the Task V3 loop never reads a stale status as this run's starting-URL dead-end.
+ browser_state.last_navigation_status = None
elif workflow_run:
browser_state = await app.BROWSER_MANAGER.get_or_create_for_workflow_run(
workflow_run=workflow_run,
diff --git a/skyvern/forge/agent_functions.py b/skyvern/forge/agent_functions.py
index 562f3f2ba..7cbf54efc 100644
--- a/skyvern/forge/agent_functions.py
+++ b/skyvern/forge/agent_functions.py
@@ -39,7 +39,11 @@ from skyvern.forge.sdk.api.llm.api_handler_factory import get_org_aware_secondar
from skyvern.forge.sdk.api.llm.exceptions import LLMProviderError
from skyvern.forge.sdk.cache.base import CACHE_EXPIRE_TIME
from skyvern.forge.sdk.copilot.code_block_preflight import CodeBlockScanFinding
-from skyvern.forge.sdk.copilot.config import CopilotConfig, block_authoring_policy_from_code_only_mode
+from skyvern.forge.sdk.copilot.config import (
+ CopilotConfig,
+ block_authoring_policy_for_request,
+ block_authoring_policy_from_code_only_mode,
+)
from skyvern.forge.sdk.core import skyvern_context
from skyvern.forge.sdk.db.agent_db import AgentDB
from skyvern.forge.sdk.models import Step, StepStatus
@@ -85,6 +89,7 @@ if TYPE_CHECKING:
from skyvern.forge.sdk.schemas.totp_codes import OTPType
from skyvern.forge.sdk.services.credential.credential_vault_service import CredentialVaultService
from skyvern.forge.sdk.workflow.context_manager import WorkflowRunContext
+ from skyvern.forge.sdk.workflow.models.block import DownloadEvidenceProbe
from skyvern.forge.sdk.workflow.models.code_block_recorder import RecordingPage
from skyvern.forge.sdk.workflow.models.tags import CallerType
from skyvern.forge.sdk.workflow.models.workflow import Workflow, WorkflowRun, WorkflowRunStatus
@@ -93,9 +98,6 @@ if TYPE_CHECKING:
LOG = structlog.get_logger()
-# Playwright's always-on ffmpeg VP8 encoder scales CPU with pixel count; 720p is the
-# legibility / CPU tradeoff point that the BROWSER_RECORDING_720P flag opts a run into.
-RECORDING_VIDEO_SIZE_720P: dict[str, int] = {"width": 1280, "height": 720}
EMAIL_OTP_CREDENTIAL_REFRESH_INTERVAL_SECONDS = 30
EMAIL_OTP_MAX_RESULTS = 5
EMAIL_OTP_SEARCH_INTERVAL_SECONDS = 30
@@ -965,10 +967,6 @@ class AgentFunction:
"""
return True
- async def is_record_browser_v2_enabled(self, organization_id: str | None) -> bool:
- """Record Browser v2 (no page scripts). Self-hosted deployments run v1."""
- return False
-
async def resolve_stream_transport(
self, *, browser_session_id: str | None, organization_id: str | None, ip_address: str | None = None
) -> str:
@@ -1050,6 +1048,7 @@ class AgentFunction:
distinct_id: str | None,
organization_id: str | None,
workflow_permanent_id: str | None = None,
+ viewport: dict[str, int] | None = None,
) -> dict[str, int] | None:
"""Resolve the browser recording resolution for this run.
@@ -1105,11 +1104,22 @@ class AgentFunction:
Gating lives here, at the block-execution call site, rather than inside
execute_code_block_override so the override only runs the runner. OSS has no
- runner and returns False; cloud overrides to consult SECURE_CODEBLOCK_ENABLED and
- only routes runs that have a browser session for the runner to broker against.
+ runner and returns False; cloud overrides to consult SECURE_CODEBLOCK_ENABLED.
+ The runner brokers against the run's persistent session when one exists, else
+ the worker's local browser.
"""
return False
+ def on_origin_scoped_headers_route_installed(
+ self, browser_context: BrowserContext, target_origin: tuple[str, str, int] | None
+ ) -> None:
+ """A context route now rewrites headers for requests to ``target_origin``.
+
+ Cloud registers an exemption so its CodeBlock egress filter yields matching requests
+ back to that route instead of fulfilling them itself; OSS has no such filter.
+ """
+ return None
+
def serialize_codeblock_parameters(self, parameters: dict[str, Any]) -> dict[str, Any]:
"""Cloud overrides this with the runner's canonical parameter serialization."""
return parameters
@@ -1142,7 +1152,7 @@ class AgentFunction:
) -> ScriptExecutionPolicyDecision:
return ScriptExecutionPolicyDecision(allowed=True, selection_reason="oss_default")
- async def should_auto_create_browser_session_for_code_block(
+ async def should_route_to_secure_codeblock_runner(
self,
*,
workflow_run_id: str,
@@ -1151,15 +1161,13 @@ class AgentFunction:
workflow_id: str | None = None,
pin_verdict: bool = False,
) -> bool:
- """Whether a run containing a CodeBlock should get an auto-provisioned browser session.
+ """Whether a run containing a CodeBlock must route to a worker pool that has the runner.
``pin_verdict`` asks the resolver to freeze an authoritative verdict onto the run, and is
for the caller whose routing decision depends on it. OSS has nothing to pin.
- The secure CodeBlock runner brokers page operations against a live persistent browser
- session, so a run that has a CodeBlock but no caller-supplied session needs one created
- for it before block execution. OSS has no runner and returns False; cloud overrides to
- consult the same env/flag gate as should_use_codeblock_runner.
+ OSS has no runner and returns False; cloud overrides to consult the same env/flag gate as
+ should_use_codeblock_runner.
"""
return False
@@ -1186,6 +1194,7 @@ class AgentFunction:
recording_page: RecordingPage | None = None,
download_run_id: str | None = None,
download_binding: DownloadBinding | None = None,
+ download_evidence: DownloadEvidenceProbe | None = None,
) -> CodeBlockEngineResult | None:
"""Run a CodeBlock through the secure runner, or return None for legacy.
@@ -1732,6 +1741,23 @@ class AgentFunction:
"""Solve and apply a reCAPTCHA token. OSS has no solver client."""
return False
+ async def resolve_google_credential_id(self, organization_id: str, credential_id: str) -> str:
+ """Accept a Google connection name or account email wherever a credential id is expected.
+
+ The id is not surfaced outside the block editor's dropdown, so blocks written by hand or by
+ an agent carry the connection's name instead. An unresolvable reference passes through so
+ the caller's own not-found handling still runs.
+ """
+ try:
+ return await google_oauth_service.resolve_credential_reference(organization_id, credential_id)
+ except Exception:
+ LOG.warning(
+ "Failed to resolve Google connection reference",
+ organization_id=organization_id,
+ exc_info=True,
+ )
+ return credential_id
+
async def get_google_sheets_credentials(
self,
organization_id: str,
@@ -1743,6 +1769,7 @@ class AgentFunction:
instead of crashing. Cloud overrides this with an access-token cache
on top of the same backend.
"""
+ credential_id = await self.resolve_google_credential_id(organization_id, credential_id)
try:
secrets = await google_oauth_service.load_credential_secrets(
organization_id=organization_id,
@@ -2427,11 +2454,23 @@ class AgentFunction:
)
async def get_copilot_config_for_request(
- self, organization_id: str | None = None, code_block_mode: bool | None = None
+ self,
+ organization_id: str | None = None,
+ code_block_mode: bool | None = None,
+ composer_mode: Literal["ask", "build"] | None = None,
) -> CopilotConfig | None:
"""Return a request-scoped workflow copilot config override."""
del organization_id
- return self.get_copilot_config(code_block_mode)
+ fallback_code_block_mode = settings.WORKFLOW_COPILOT_CODE_BLOCK_MODE
+ config = self.get_copilot_config(code_block_mode)
+ if config is None:
+ return None
+ config.block_authoring_policy = block_authoring_policy_for_request(
+ code_block_mode,
+ composer_mode,
+ fallback_code_block_mode=fallback_code_block_mode,
+ )
+ return config
async def should_render_copilot_terminal_from_envelope(self, organization_id: str | None = None) -> bool:
del organization_id
diff --git a/skyvern/forge/api_app.py b/skyvern/forge/api_app.py
index 765166819..41b156d0e 100644
--- a/skyvern/forge/api_app.py
+++ b/skyvern/forge/api_app.py
@@ -31,7 +31,7 @@ from starlette_context.middleware import RawContextMiddleware
from starlette_context.plugins.base import Plugin
from skyvern.config import _ensure_sqlite_dir, settings
-from skyvern.cors import credentialed_cors_allow_origin_regex, credentialed_cors_allow_origins
+from skyvern.cors import cors_middleware_kwargs
from skyvern.exceptions import SkyvernHTTPException
from skyvern.forge import app as forge_app
from skyvern.forge.forge_app_initializer import start_forge_app
@@ -99,11 +99,7 @@ class SecurityHeadersMiddleware:
def add_credentialed_cors_middleware(fastapi_app: FastAPI) -> None:
fastapi_app.add_middleware(
CORSMiddleware,
- allow_origins=credentialed_cors_allow_origins(settings.ALLOWED_ORIGINS),
- allow_credentials=True,
- allow_methods=["*"],
- allow_headers=["*"],
- allow_origin_regex=credentialed_cors_allow_origin_regex(settings.ALLOWED_ORIGIN_REGEX),
+ **cors_middleware_kwargs(settings.ALLOWED_ORIGINS, settings.ALLOWED_ORIGIN_REGEX),
)
diff --git a/skyvern/forge/prompts/skyvern/workflow-copilot-agent.j2 b/skyvern/forge/prompts/skyvern/workflow-copilot-agent.j2
index 4d7350b8d..f358a2966 100644
--- a/skyvern/forge/prompts/skyvern/workflow-copilot-agent.j2
+++ b/skyvern/forge/prompts/skyvern/workflow-copilot-agent.j2
@@ -18,8 +18,8 @@ CREDENTIAL HANDLING - CRITICAL:
DO NOT PROVIDE RAW LOGIN/PASSWORD values to tools. If a message contains a raw secret written inline (a password, API key, token, or one-time code), do not echo it, do not type or submit it into a page, do not pass it as a run parameter, and do not use the browser or run anything with it. You may persist only a redacted draft that uses a saved credential parameter; then ask the user to store the secret as a saved credential and reply with its name — that is the whole turn.
Ask only when the turn is genuinely blocked on something only the user can supply: a credential identity you cannot resolve, a human-only value, or a choice between materially different builds where guessing wrong throws the work away. Your tools resolve most of the rest — exhaust them first; a question whose answer a tool would have returned is a wasted turn. Everything else you decide: choose the sensible default, act on it, and name the choice so the user can redirect you. When the request leaves an ordinary detail open, choose the least expansive interpretation that still satisfies everything the user explicitly asked for, grounded in the current page; state the choice and continue. Do not expand into pagination, older history, or other sections unless the request asks for that scope or current-page evidence shows it is needed to satisfy the explicit request. If your question states what you would do, you are not blocked — you are asking permission; do the thing and report it. Never re-ask what the conversation, the account state, the current workflow, or run evidence already answers.
-One carve-out. Before a test run performs an action that spends money, sends a message or email to someone else, or destroys something the user cannot restore — placing an order, submitting a payment, sending, deleting, cancelling — build and run everything up to that step, then stop and ask. Naming what you are about to do is a real question there, not permission-seeking. Every reversible action you take without asking.
-When the user explicitly requested a non-financial form submission, current evidence matches that request, and submitting will not send a message or email to someone else or destroy, delete, or cancel something the user cannot restore, carry it through; do not stop at review to ask for the same permission again.
+One carve-out. Before a test run performs an action that spends money or destroys something the user cannot restore — placing an order, submitting a payment, deleting, cancelling — build and run everything up to that step, then stop and ask. Naming what you are about to do is a real question there, not permission-seeking. Every reversible action you take without asking.
+When the user explicitly requested a non-financial form submission, current evidence matches that request, and submitting will not destroy, delete, or cancel something the user cannot restore, carry it through; do not stop at review to ask for the same permission again.
Serve every part of the request, not the first milestone, and test what you change before you present it — an untested draft is acceptable only when the user asked for one, and then you say so.
diff --git a/skyvern/forge/sdk/api/files.py b/skyvern/forge/sdk/api/files.py
index c022c1c71..aa37a0a29 100644
--- a/skyvern/forge/sdk/api/files.py
+++ b/skyvern/forge/sdk/api/files.py
@@ -1,6 +1,7 @@
import asyncio
import hashlib
import html
+import json
import mimetypes
import os
import re
@@ -10,7 +11,7 @@ import zipfile
from dataclasses import dataclass
from http import HTTPStatus
from pathlib import Path
-from typing import TYPE_CHECKING, TypeAlias
+from typing import TYPE_CHECKING, Any, NamedTuple, TypeAlias
from urllib.parse import parse_qsl, unquote, urlencode, urlparse
import aiohttp
@@ -40,6 +41,7 @@ from skyvern.forge.sdk.core.aiohttp_helper import (
validate_and_pin_fetch_url,
validate_and_pin_redirect_url,
)
+from skyvern.forge.sdk.core.hashing import diagnostic_fingerprint
from skyvern.forge.sdk.core.http_request_authorization import (
RedirectHopAuthorization,
RedirectHopAuthorizer,
@@ -724,12 +726,161 @@ def get_path_for_workflow_download_directory(run_id: str | None) -> Path:
return Path(get_download_dir(run_id=run_id))
+def download_dir_path_for_run(run_id: str | None) -> Path:
+ return Path(settings.DOWNLOAD_PATH) / str(run_id)
+
+
def get_download_dir(run_id: str | None) -> str:
- download_dir = os.path.join(settings.DOWNLOAD_PATH, str(run_id))
+ download_dir = str(download_dir_path_for_run(run_id))
os.makedirs(download_dir, exist_ok=True)
return download_dir
+MAX_OBSERVED_DOWNLOAD_ENTRY_FINGERPRINTS = 10
+DOWNLOAD_VISIBILITY_DUMP_ENV = "SKYVERN_DOWNLOAD_VISIBILITY_DUMP"
+
+DownloadVisibilityFields: TypeAlias = dict[str, int | bool | str | list[str] | None]
+
+
+class DownloadDirObservation(NamedTuple):
+ entry_count: int
+ total_bytes: int
+ in_flight_count: int
+ newest_mtime_ns: int
+ entry_fps: tuple[str, ...]
+ entry_fps_truncated: bool
+ dir_missing: bool
+ read_failed: bool
+
+
+def observe_download_dir(path: Path) -> DownloadDirObservation:
+ """Privacy-safe snapshot of a download directory for diagnostics.
+
+ Never raises and never carries an entry name or an OS error message: a failed read is reported
+ as a flag so a logged zero is not mistaken for an empty directory.
+ """
+ entry_count = 0
+ total_bytes = 0
+ in_flight_count = 0
+ newest_mtime_ns = 0
+ entry_fps: list[str] = []
+ read_failed = False
+ try:
+ with os.scandir(path) as entries:
+ for entry in entries:
+ entry_count += 1
+ if entry.name.endswith(BROWSER_DOWNLOADING_SUFFIX):
+ in_flight_count += 1
+ if len(entry_fps) < MAX_OBSERVED_DOWNLOAD_ENTRY_FINGERPRINTS:
+ entry_fps.append(diagnostic_fingerprint(entry.name))
+ try:
+ entry_stat = entry.stat()
+ except OSError:
+ read_failed = True
+ else:
+ total_bytes += entry_stat.st_size
+ newest_mtime_ns = max(newest_mtime_ns, entry_stat.st_mtime_ns)
+ except FileNotFoundError:
+ return DownloadDirObservation(0, 0, 0, 0, (), False, True, False)
+ except (OSError, ValueError):
+ # scandir raises ValueError, not OSError, on a path holding an embedded null byte.
+ return DownloadDirObservation(0, 0, 0, 0, (), False, False, True)
+ return DownloadDirObservation(
+ entry_count=entry_count,
+ total_bytes=total_bytes,
+ in_flight_count=in_flight_count,
+ newest_mtime_ns=newest_mtime_ns,
+ entry_fps=tuple(entry_fps),
+ entry_fps_truncated=entry_count > len(entry_fps),
+ dir_missing=False,
+ read_failed=read_failed,
+ )
+
+
+def _observation_fields(prefix: str, observation: DownloadDirObservation | None) -> DownloadVisibilityFields:
+ names = DownloadDirObservation._fields
+ if observation is None:
+ return {f"{prefix}_{name}": None for name in names}
+ fields: DownloadVisibilityFields = {}
+ for name in names:
+ value = getattr(observation, name)
+ fields[f"{prefix}_{name}"] = list(value) if isinstance(value, tuple) else value
+ return fields
+
+
+def _observation_advanced(before: DownloadDirObservation, after: DownloadDirObservation) -> bool | None:
+ """None when either side could not be read: its counters are partial, so a comparison would invent movement."""
+ if before.read_failed or after.read_failed:
+ return None
+ return (
+ after.entry_count > before.entry_count
+ or after.total_bytes > before.total_bytes
+ or after.newest_mtime_ns > before.newest_mtime_ns
+ )
+
+
+def classify_download_visibility(
+ *,
+ pre: DownloadDirObservation,
+ settled: DownloadDirObservation | None,
+ post: DownloadDirObservation,
+ alt_pre: DownloadDirObservation | None,
+ alt_post: DownloadDirObservation | None,
+ listed_run_id: str,
+ workflow_run_id: str,
+ download_binding_kind: str | None,
+) -> DownloadVisibilityFields:
+ """Emitted fields for one registration boundary: when bytes landed, and whether they landed elsewhere.
+
+ Movement is read from newest_mtime_ns as well as counts and bytes so a same-name same-size
+ overwrite still registers, and the alternate directory is read as a pre-to-post delta so files
+ a sibling block left behind cannot look like a location mismatch.
+ """
+ alt_entry_delta: int | None = None
+ alt_bytes_delta: int | None = None
+ alt_moved: bool | None = None
+ if alt_pre is not None and alt_post is not None and not (alt_pre.read_failed or alt_post.read_failed):
+ alt_entry_delta = alt_post.entry_count - alt_pre.entry_count
+ alt_bytes_delta = alt_post.total_bytes - alt_pre.total_bytes
+ alt_moved = _observation_advanced(alt_pre, alt_post)
+ fields: DownloadVisibilityFields = {
+ "listed_run_id": listed_run_id,
+ "download_run_id_differs": listed_run_id != workflow_run_id,
+ "download_binding_kind": download_binding_kind,
+ "landed_between_snapshots": _observation_advanced(pre, post),
+ "landed_during_settle": _observation_advanced(pre, settled) if settled is not None else None,
+ "landed_after_settle": _observation_advanced(settled, post) if settled is not None else None,
+ "alt_entry_delta": alt_entry_delta,
+ "alt_bytes_delta": alt_bytes_delta,
+ "alt_moved": alt_moved,
+ }
+ for prefix, observation in (
+ ("pre", pre),
+ ("settled", settled),
+ ("post", post),
+ ("alt_pre", alt_pre),
+ ("alt_post", alt_post),
+ ):
+ fields.update(_observation_fields(prefix, observation))
+ return fields
+
+
+def dump_download_visibility_inputs(name: str, payload: dict[str, Any]) -> None:
+ """Append classifier inputs as JSONL under DOWNLOAD_VISIBILITY_DUMP_ENV, for offline replay.
+
+ Inert unless that env var names a directory.
+ """
+ dump_dir = os.environ.get(DOWNLOAD_VISIBILITY_DUMP_ENV)
+ if not dump_dir:
+ return
+ try:
+ os.makedirs(dump_dir, exist_ok=True)
+ with open(os.path.join(dump_dir, f"{name}.jsonl"), "a", encoding="utf-8") as handle:
+ handle.write(json.dumps(payload) + "\n")
+ except (OSError, TypeError, ValueError):
+ LOG.warning("Failed to append download visibility dump", dump_name=name)
+
+
RUN_TEMP_NAMESPACE = "runs"
diff --git a/skyvern/forge/sdk/artifact/storage/s3.py b/skyvern/forge/sdk/artifact/storage/s3.py
index 192352632..f5e8e442a 100644
--- a/skyvern/forge/sdk/artifact/storage/s3.py
+++ b/skyvern/forge/sdk/artifact/storage/s3.py
@@ -19,6 +19,7 @@ from skyvern.forge.sdk.api.aws import AsyncAWSClient, S3StorageClass, S3Uri
from skyvern.forge.sdk.api.files import (
calculate_sha256_for_file,
create_named_temporary_file,
+ dump_download_visibility_inputs,
get_download_dir,
get_skyvern_temp_dir,
unzip_bytes_to_temp_directory,
@@ -63,6 +64,35 @@ def _safe_get_file_size(path: str) -> int | None:
return None
+def empty_read_decision(
+ *,
+ download_row_count: int | None,
+ rows_lookup_failed: bool,
+ skip_fired: bool,
+ rows_present_but_unresolvable: bool,
+ listed: bool,
+) -> dict[str, int | bool | str | None]:
+ """Why a downloads read came back empty, from counts alone — never a listing."""
+ if rows_lookup_failed:
+ cause = "row_lookup_failed"
+ elif rows_present_but_unresolvable:
+ cause = "rows_present_but_unresolvable"
+ elif skip_fired:
+ cause = "listing_skipped_zero_rows"
+ elif download_row_count is None:
+ cause = "listed_rows_unqueried"
+ else:
+ cause = "listed_and_empty"
+ return {
+ "download_row_count": download_row_count,
+ "rows_lookup_failed": rows_lookup_failed,
+ "skip_fired": skip_fired,
+ "rows_present_but_unresolvable": rows_present_but_unresolvable,
+ "listed": listed,
+ "empty_read_cause": cause,
+ }
+
+
class S3Storage(BaseStorage):
_PATH_VERSION = "v1"
# Cap concurrent head_object fan-out in the legacy listing fallback.
@@ -738,7 +768,7 @@ class S3Storage(BaseStorage):
return
already_saved = (
download_checksums_by_uri(
- await self._list_download_artifacts_safe(organization_id=organization_id, run_id=run_id)
+ (await self._list_download_artifacts_safe(organization_id=organization_id, run_id=run_id))[0]
)
if run_id is not None
else {}
@@ -833,16 +863,84 @@ class S3Storage(BaseStorage):
# If HMAC signing isn't configured (self-hosted OSS default), the signed
# endpoint requires an API key webhook consumers don't have, so we stay
# on the legacy S3-list+presign path even when rows exist.
+
+ # ``download_row_count`` stays None when the rows were never queried (no keyring, no run id,
+ # or the lookup failed), so an unqueried read is never reported as a read that found nothing.
+ download_row_count: int | None = None
+ rows_lookup_failed = False
if run_id is not None and settings.ARTIFACT_CONTENT_HMAC_KEYRING:
- artifacts = await self._list_download_artifacts_safe(organization_id=organization_id, run_id=run_id)
+ artifacts, rows_lookup_failed = await self._list_download_artifacts_safe(
+ organization_id=organization_id, run_id=run_id
+ )
+ if not rows_lookup_failed:
+ download_row_count = len(artifacts)
if artifacts:
- return await _file_infos_from_download_artifacts(artifacts)
- if await self._skip_empty_downloads_listing(organization_id=organization_id, run_id=run_id):
+ file_infos = await _file_infos_from_download_artifacts(artifacts)
+ if not file_infos:
+ self._log_empty_downloads_read(
+ organization_id=organization_id,
+ run_id=run_id,
+ download_row_count=download_row_count,
+ rows_lookup_failed=rows_lookup_failed,
+ skip_fired=False,
+ rows_present_but_unresolvable=True,
+ listed=False,
+ )
+ return file_infos
+ if not rows_lookup_failed and await self._skip_empty_downloads_listing(
+ organization_id=organization_id, run_id=run_id
+ ):
+ self._log_empty_downloads_read(
+ organization_id=organization_id,
+ run_id=run_id,
+ download_row_count=download_row_count,
+ rows_lookup_failed=rows_lookup_failed,
+ skip_fired=True,
+ rows_present_but_unresolvable=False,
+ listed=False,
+ )
return []
# Legacy fallback — runs predating SKY-8861 (no artifact rows) and
# OSS-default deployments without HMAC signing both arrive here.
- return await self._get_downloaded_files_via_s3_listing(organization_id=organization_id, run_id=run_id)
+ file_infos = await self._get_downloaded_files_via_s3_listing(organization_id=organization_id, run_id=run_id)
+ if not file_infos:
+ self._log_empty_downloads_read(
+ organization_id=organization_id,
+ run_id=run_id,
+ download_row_count=download_row_count,
+ rows_lookup_failed=rows_lookup_failed,
+ skip_fired=False,
+ rows_present_but_unresolvable=False,
+ listed=True,
+ )
+ return file_infos
+
+ def _log_empty_downloads_read(
+ self,
+ *,
+ organization_id: str,
+ run_id: str | None,
+ download_row_count: int | None,
+ rows_lookup_failed: bool,
+ skip_fired: bool,
+ rows_present_but_unresolvable: bool,
+ listed: bool,
+ ) -> None:
+ decision = empty_read_decision(
+ download_row_count=download_row_count,
+ rows_lookup_failed=rows_lookup_failed,
+ skip_fired=skip_fired,
+ rows_present_but_unresolvable=rows_present_but_unresolvable,
+ listed=listed,
+ )
+ dump_download_visibility_inputs("empty_read", {"run_id": run_id, **decision})
+ LOG.info(
+ "downloads.empty_read",
+ organization_id=organization_id,
+ run_id=run_id,
+ **decision,
+ )
async def _skip_empty_downloads_listing(self, *, organization_id: str, run_id: str) -> bool:
"""True when a run with zero DOWNLOAD rows may skip the legacy S3 LIST.
@@ -874,9 +972,13 @@ class S3Storage(BaseStorage):
cutover = cutover.replace(tzinfo=timezone.utc)
return created_at >= cutover
- async def _list_download_artifacts_safe(self, *, organization_id: str, run_id: str) -> list[Artifact]:
+ async def _list_download_artifacts_safe(self, *, organization_id: str, run_id: str) -> tuple[list[Artifact], bool]:
+ """The run's DOWNLOAD rows, plus whether the lookup itself failed.
+
+ The failure flag is what separates "this run has no download rows" from "we could not tell".
+ """
try:
- return await app.DATABASE.artifacts.list_artifacts_for_run_by_type(
+ artifacts = await app.DATABASE.artifacts.list_artifacts_for_run_by_type(
run_id=run_id,
organization_id=organization_id,
artifact_type=ArtifactType.DOWNLOAD,
@@ -888,7 +990,8 @@ class S3Storage(BaseStorage):
run_id=run_id,
exc_info=True,
)
- return []
+ return [], True
+ return artifacts, False
async def _get_downloaded_files_via_s3_listing(self, *, organization_id: str, run_id: str | None) -> list[FileInfo]:
bucket = settings.AWS_S3_BUCKET_UPLOADS
diff --git a/skyvern/forge/sdk/copilot/agent.py b/skyvern/forge/sdk/copilot/agent.py
index 55fe59374..7a4d35486 100644
--- a/skyvern/forge/sdk/copilot/agent.py
+++ b/skyvern/forge/sdk/copilot/agent.py
@@ -103,6 +103,7 @@ from skyvern.forge.sdk.copilot.enforcement import (
from skyvern.forge.sdk.copilot.entrypoint import (
anchor_recovers_entrypoint,
extract_in_turn_entry_url,
+ resolve_turn_entrypoint_url,
)
from skyvern.forge.sdk.copilot.failure_tracking import (
PER_TOOL_BUDGET_FAILURE_CATEGORY,
@@ -4082,6 +4083,7 @@ async def run_copilot_agent(
prior_executed_block_fingerprints: dict[str, set[str]] | None = None,
eval_capture_case_id: str | None = None,
eval_mode: CopilotEvalMode | None = None,
+ eval_entrypoint_url: str | None = None,
) -> AgentResult:
# One id per turn — passed to every downstream AgentResult and
# CopilotContext so the envelope and terminal frames correlate. The
@@ -4127,6 +4129,7 @@ async def run_copilot_agent(
prior_executed_block_fingerprints=prior_executed_block_fingerprints,
eval_capture_case_id=eval_capture_case_id,
eval_mode=eval_mode,
+ eval_entrypoint_url=eval_entrypoint_url,
)
return result
except Exception as exc:
@@ -4227,6 +4230,7 @@ async def _run_copilot_turn_impl(
prior_executed_block_fingerprints: dict[str, set[str]] | None = None,
eval_capture_case_id: str | None = None,
eval_mode: CopilotEvalMode | None = None,
+ eval_entrypoint_url: str | None = None,
) -> AgentResult:
copilot_config = config or CopilotConfig(security_rules=security_rules)
copilot_config = config_for_eval_mode(copilot_config, eval_mode)
@@ -4438,10 +4442,33 @@ async def _run_copilot_turn_impl(
chat_request.workflow_yaml or "",
transcript_anchor,
)
- if in_turn_entrypoint is not None:
- ctx.resolved_discovery_entrypoint_url = in_turn_entrypoint
- elif ctx.resolved_discovery_entrypoint_url is None:
- ctx.resolved_discovery_entrypoint_url = anchor_entrypoint or persisted_entrypoint_url
+ ctx.resolved_discovery_entrypoint_url = resolve_turn_entrypoint_url(
+ eval_entrypoint_url=eval_entrypoint_url,
+ in_turn_entrypoint=in_turn_entrypoint,
+ anchor_entrypoint=anchor_entrypoint,
+ persisted_entrypoint_url=persisted_entrypoint_url,
+ current_entrypoint_url=ctx.resolved_discovery_entrypoint_url,
+ )
+ if eval_entrypoint_url:
+ # finalize_observation_context stamps entrypoint_url only on the way out, so the seed
+ # would otherwise first reach the model on turn N+1 and a benchmark case is one turn.
+ raw_context = (safe_global_llm_context or "").strip()
+ seeded_context = StructuredContext.from_json_str(safe_global_llm_context)
+ context_parse_failed = raw_context.startswith("{") and seeded_context.user_goal == raw_context
+ if context_parse_failed:
+ # A seed the model never sees must not still win the ladder, or the turn resolves
+ # seeded while reasoning unseeded. Re-resolve as if no seed had been supplied.
+ LOG.warning("copilot_eval_entrypoint_seed_skipped", reason="unparsed_structured_context")
+ ctx.resolved_discovery_entrypoint_url = resolve_turn_entrypoint_url(
+ eval_entrypoint_url=None,
+ in_turn_entrypoint=in_turn_entrypoint,
+ anchor_entrypoint=anchor_entrypoint,
+ persisted_entrypoint_url=persisted_entrypoint_url,
+ current_entrypoint_url=None,
+ )
+ else:
+ seeded_context.entrypoint_url = eval_entrypoint_url
+ safe_global_llm_context = seeded_context.to_json_str()
from skyvern.forge.sdk.copilot.enforcement import (
CopilotNonRetriableNavError,
CopilotTotalTimeoutError,
diff --git a/skyvern/forge/sdk/copilot/config.py b/skyvern/forge/sdk/copilot/config.py
index 6f64a452e..5fdbfad17 100644
--- a/skyvern/forge/sdk/copilot/config.py
+++ b/skyvern/forge/sdk/copilot/config.py
@@ -4,6 +4,7 @@ from __future__ import annotations
from dataclasses import dataclass, field
from enum import StrEnum
+from typing import Literal
from skyvern.config import settings
from skyvern.forge.sdk.copilot.output_extraction_plan import ShapeExpectation
@@ -12,6 +13,7 @@ from skyvern.forge.sdk.copilot.output_extraction_plan import ShapeExpectation
class BlockAuthoringPolicy(StrEnum):
STANDARD = "standard"
CODE_ONLY_BROWSER = "code_only_browser"
+ TASK_V3_PURE = "task_v3_pure"
def normalize_block_authoring_policy(value: object) -> BlockAuthoringPolicy:
@@ -29,6 +31,21 @@ def block_authoring_policy_from_code_only_mode(enabled: bool) -> BlockAuthoringP
return BlockAuthoringPolicy.CODE_ONLY_BROWSER if enabled else BlockAuthoringPolicy.STANDARD
+def block_authoring_policy_for_request(
+ code_block_mode: bool | None,
+ composer_mode: Literal["ask", "build"] | None,
+ *,
+ fallback_code_block_mode: bool,
+) -> BlockAuthoringPolicy:
+ if code_block_mode is True:
+ return BlockAuthoringPolicy.CODE_ONLY_BROWSER
+ if composer_mode == "build":
+ return BlockAuthoringPolicy.TASK_V3_PURE
+ if code_block_mode is False:
+ return BlockAuthoringPolicy.STANDARD
+ return block_authoring_policy_from_code_only_mode(fallback_code_block_mode)
+
+
def download_scout_act_required_for_policy(block_authoring_policy: BlockAuthoringPolicy | str | None) -> bool:
return normalize_block_authoring_policy(block_authoring_policy) == BlockAuthoringPolicy.CODE_ONLY_BROWSER
diff --git a/skyvern/forge/sdk/copilot/enforcement.py b/skyvern/forge/sdk/copilot/enforcement.py
index dc54b11ef..7cb2db62f 100644
--- a/skyvern/forge/sdk/copilot/enforcement.py
+++ b/skyvern/forge/sdk/copilot/enforcement.py
@@ -601,6 +601,84 @@ def _truncated_output_fallback(output: str) -> str:
return output[:_TOOL_OUTPUT_SUMMARIZE_THRESHOLD] + _TOOL_OUTPUT_TRUNCATION_SUFFIX
+# Compacting page evidence to {"ok":true} tells the model it has evidence while leaving it none, so
+# raw excerpts and derived relations go first and the bounded facts describing what is on the page,
+# and which browser saw it, stay. An allowlist rather than a drop-list: an evidence field nobody has
+# classified yet is likelier to be raw page text than a fact worth keeping.
+_PAGE_EVIDENCE_IDENTITY = (
+ "source_tool",
+ "current_url",
+ "inspected_url",
+ "page_title",
+ "observation_step",
+ "source_browser_session_id",
+ "workflow_run_id",
+ "observed_after_workflow_run",
+)
+_PAGE_EVIDENCE_FACT_LISTS = (
+ "forms",
+ "navigation_targets",
+ "result_containers",
+ "clickable_controls",
+ "challenge_controls",
+ "modal_overlays",
+ "page_obstructions",
+)
+_PAGE_EVIDENCE_MAX_ENTRIES = 12
+_PAGE_EVIDENCE_ENTRY_CHARS = 400
+# Per-list bounds alone would let a page with many forms and links produce a compacted output as
+# large as an uncompacted one, defeating the pass whose job is keeping the turn inside the window.
+_PAGE_EVIDENCE_SUMMARY_CHARS = 4000
+
+
+def _is_page_evidence(data: dict[str, Any]) -> bool:
+ if data.get("source_tool") == "inspect_page_for_composition":
+ return True
+ return any(key in data for key in _PAGE_EVIDENCE_FACT_LISTS) and "inspected_url" in data
+
+
+def _compact_length(value: Any) -> int:
+ return len(json.dumps(value, separators=(",", ":")))
+
+
+def _bounded_evidence_entries(value: list[Any], budget: int) -> list[Any]:
+ entries: list[Any] = []
+ for entry in value[:_PAGE_EVIDENCE_MAX_ENTRIES]:
+ blob = json.dumps(entry, separators=(",", ":"))
+ bounded = entry if len(blob) <= _PAGE_EVIDENCE_ENTRY_CHARS else blob[:_PAGE_EVIDENCE_ENTRY_CHARS]
+ budget -= _compact_length(bounded)
+ if budget < 0:
+ break
+ entries.append(bounded)
+ return entries
+
+
+def _summarize_page_evidence(parsed: dict[str, Any], data: dict[str, Any]) -> dict[str, Any]:
+ kept: dict[str, Any] = {}
+ for key in _PAGE_EVIDENCE_IDENTITY:
+ value = data.get(key, parsed.get(key))
+ if value not in (None, ""):
+ kept[key] = value
+ budget = _PAGE_EVIDENCE_SUMMARY_CHARS - _compact_length(kept)
+ for key in _PAGE_EVIDENCE_FACT_LISTS:
+ value = data.get(key)
+ if budget <= 0 or not isinstance(value, list) or not value:
+ continue
+ entries = _bounded_evidence_entries(value, budget)
+ if entries:
+ kept[key] = entries
+ budget -= _compact_length(entries)
+ challenge_state = data.get("challenge_state")
+ if isinstance(challenge_state, dict) and challenge_state.get("detected"):
+ kept["challenge_state"] = {
+ key: challenge_state.get(key) for key in ("detected", "kind", "source") if challenge_state.get(key)
+ }
+ indicators = data.get("anti_bot_indicators")
+ if isinstance(indicators, list) and indicators:
+ kept["anti_bot_indicators"] = indicators[:8]
+ return kept
+
+
def _summarize_tool_output(output: str) -> str:
"""Compress an old function_call_output to a compact JSON synopsis that
preserves only signal fields (ok/error/status/failure_reason/block labels).
@@ -627,6 +705,14 @@ def _summarize_tool_output(output: str) -> str:
synopsis["error"] = str(parsed["error"])[:200]
data = parsed.get("data")
+ if isinstance(data, dict) and _is_page_evidence(data):
+ synopsis["page_evidence"] = _summarize_page_evidence(parsed, data)
+ synopsis["_summarized"] = "older page evidence — bounded facts retained, raw excerpts dropped"
+ try:
+ return json.dumps(synopsis, separators=(",", ":"))
+ except (TypeError, ValueError):
+ return _truncated_output_fallback(output)
+
if isinstance(data, dict):
code = data.get("code")
if isinstance(code, str) and code:
diff --git a/skyvern/forge/sdk/copilot/entrypoint.py b/skyvern/forge/sdk/copilot/entrypoint.py
index 05139fb22..328dbf5c3 100644
--- a/skyvern/forge/sdk/copilot/entrypoint.py
+++ b/skyvern/forge/sdk/copilot/entrypoint.py
@@ -91,3 +91,22 @@ def anchor_recovers_entrypoint(
):
return None
return extract_anchor_entry_url(transcript_earliest_user_turn)
+
+
+def resolve_turn_entrypoint_url(
+ *,
+ eval_entrypoint_url: str | None,
+ in_turn_entrypoint: str | None,
+ anchor_entrypoint: str | None,
+ persisted_entrypoint_url: str | None,
+ current_entrypoint_url: str | None,
+) -> str | None:
+ """The benchmark seed outranks in-turn extraction because an instruction that happens to name a
+ domain would otherwise silently beat the dataset URL the run is supposed to start from."""
+ if eval_entrypoint_url:
+ return eval_entrypoint_url
+ if in_turn_entrypoint is not None:
+ return in_turn_entrypoint
+ if current_entrypoint_url is None:
+ return anchor_entrypoint or persisted_entrypoint_url
+ return current_entrypoint_url
diff --git a/skyvern/forge/sdk/copilot/mcp_adapter.py b/skyvern/forge/sdk/copilot/mcp_adapter.py
index 5700c53b8..1f61865ae 100644
--- a/skyvern/forge/sdk/copilot/mcp_adapter.py
+++ b/skyvern/forge/sdk/copilot/mcp_adapter.py
@@ -1005,10 +1005,11 @@ def _transform_args(
def _copilot_to_call_tool_result(
copilot_result: dict[str, Any],
+ tool_name: str = "",
) -> CallToolResult:
if not copilot_result:
return CallToolResult(content=[], isError=True)
- sanitized = sanitize_tool_result_for_llm("", copilot_result)
+ sanitized = sanitize_tool_result_for_llm(tool_name, copilot_result)
marked = mark_mcp_result_untrusted_for_llm(sanitized)
content: list[TextContent] = [TextContent(type="text", text=json.dumps(marked))]
is_error = copilot_result.get("ok", True) is not True
@@ -1307,7 +1308,7 @@ class SkyvernOverlayMCPServer(MCPServer):
result = _scrub_tool_result(copilot_ctx, result)
LOG.info("Raw-secret safety blocked MCP browser tool", tool_name=tool_name)
record_tool_step_result_for_ctx(copilot_ctx, tool_name, arguments, result)
- return _copilot_to_call_tool_result(result)
+ return _copilot_to_call_tool_result(result, tool_name)
if overlay.pre_hook:
try:
@@ -1338,7 +1339,7 @@ class SkyvernOverlayMCPServer(MCPServer):
else:
hook_result = _scrub_tool_result(copilot_ctx, hook_result)
record_tool_step_result_for_ctx(copilot_ctx, tool_name, arguments, hook_result)
- return _copilot_to_call_tool_result(hook_result)
+ return _copilot_to_call_tool_result(hook_result, tool_name)
mcp_args = _transform_args(arguments, overlay)
@@ -1391,7 +1392,7 @@ class SkyvernOverlayMCPServer(MCPServer):
else:
err = _scrub_tool_result(copilot_ctx, err)
record_tool_step_result_for_ctx(copilot_ctx, tool_name, arguments, err)
- return _copilot_to_call_tool_result(err)
+ return _copilot_to_call_tool_result(err, tool_name)
if continuity_result is not None:
_log_mcp_timing(copilot_ctx, tool_name, mcp_name, phases, {}, "model", "session_error")
if uses_shared_browser_outcome:
@@ -1409,7 +1410,7 @@ class SkyvernOverlayMCPServer(MCPServer):
else:
continuity_result = _scrub_tool_result(copilot_ctx, continuity_result)
record_tool_step_result_for_ctx(copilot_ctx, tool_name, arguments, continuity_result)
- return _copilot_to_call_tool_result(continuity_result)
+ return _copilot_to_call_tool_result(continuity_result, tool_name)
mcp_args["session_id"] = copilot_ctx.browser_session_id
call_browser_session_id = copilot_ctx.browser_session_id if overlay.requires_browser else None
call_browser_session_generation = copilot_ctx.browser_session_continuity_generation
@@ -1473,7 +1474,7 @@ class SkyvernOverlayMCPServer(MCPServer):
else:
err = _scrub_tool_result(copilot_ctx, err)
record_tool_step_result_for_ctx(copilot_ctx, tool_name, arguments, err)
- return _copilot_to_call_tool_result(err)
+ return _copilot_to_call_tool_result(err, tool_name)
except CopilotBrowserSessionUnavailable as exc:
_log_mcp_timing(copilot_ctx, tool_name, mcp_name, phases, {}, "model", "session_error")
try:
@@ -1523,7 +1524,7 @@ class SkyvernOverlayMCPServer(MCPServer):
_browser_session_loss_result({}, disposition=disposition),
)
record_tool_step_result_for_ctx(copilot_ctx, tool_name, arguments, err)
- return _copilot_to_call_tool_result(err)
+ return _copilot_to_call_tool_result(err, tool_name)
except asyncio.CancelledError:
_log_mcp_timing(copilot_ctx, tool_name, mcp_name, phases, {}, "model", "cancelled")
if uses_shared_browser_outcome:
@@ -1560,7 +1561,7 @@ class SkyvernOverlayMCPServer(MCPServer):
else:
err = _scrub_tool_exception(copilot_ctx, tool_name, exc)
record_tool_step_result_for_ctx(copilot_ctx, tool_name, arguments, err)
- return _copilot_to_call_tool_result(err)
+ return _copilot_to_call_tool_result(err, tool_name)
browser_outcome: _BrowserCallOutcome | None = None
if uses_shared_browser_outcome:
@@ -1676,7 +1677,7 @@ class SkyvernOverlayMCPServer(MCPServer):
action_relation=ScreenshotActionRelation.TOOL_RESULT,
),
)
- return _copilot_to_call_tool_result(copilot_result)
+ return _copilot_to_call_tool_result(copilot_result, tool_name)
async def call_internal_tool(
self,
diff --git a/skyvern/forge/sdk/copilot/model_input_capture.py b/skyvern/forge/sdk/copilot/model_input_capture.py
new file mode 100644
index 000000000..d374e958c
--- /dev/null
+++ b/skyvern/forge/sdk/copilot/model_input_capture.py
@@ -0,0 +1,104 @@
+"""Canonical tool-surface evidence for local Copilot model-input captures."""
+
+from __future__ import annotations
+
+import contextvars
+import hashlib
+import json
+from dataclasses import dataclass
+from pathlib import Path
+from typing import Any
+
+import structlog
+
+TOOL_SURFACE_VERSION = "copilot-model-tool-surface-v1"
+LOG = structlog.get_logger()
+
+
+@dataclass(frozen=True, slots=True)
+class SerializedToolSurface:
+ payload: dict[str, Any]
+ sha256: str
+
+
+@dataclass(frozen=True, slots=True)
+class _PendingModelInputCapture:
+ path: Path
+ payload: dict[str, Any]
+ redaction_parameters: dict[str, Any]
+
+
+_PENDING_MODEL_INPUT_CAPTURE: contextvars.ContextVar[_PendingModelInputCapture | None] = contextvars.ContextVar(
+ "_PENDING_MODEL_INPUT_CAPTURE",
+ default=None,
+)
+
+
+def serialize_tool_surface(tools: list[Any]) -> SerializedToolSurface:
+ """Serialize the ordered FunctionTool contract passed to the model."""
+
+ payload = {
+ "version": TOOL_SURFACE_VERSION,
+ "tools": [
+ {
+ "name": tool.name,
+ "description": tool.description or "",
+ "params_json_schema": tool.params_json_schema,
+ "strict_json_schema": tool.strict_json_schema,
+ }
+ for tool in tools
+ ],
+ }
+ encoded = json.dumps(payload, sort_keys=True, separators=(",", ":"), default=str).encode()
+ return SerializedToolSurface(payload=payload, sha256=hashlib.sha256(encoded).hexdigest())
+
+
+def register_pending_model_input_capture(
+ *,
+ path: Path,
+ payload: dict[str, Any],
+ redaction_parameters: dict[str, Any],
+) -> None:
+ """Bind an input dump to the next model request in this async context."""
+
+ _PENDING_MODEL_INPUT_CAPTURE.set(
+ _PendingModelInputCapture(
+ path=path,
+ payload=payload,
+ redaction_parameters=redaction_parameters,
+ )
+ )
+
+
+def clear_pending_model_input_capture() -> None:
+ _PENDING_MODEL_INPUT_CAPTURE.set(None)
+
+
+def attach_tool_surface_to_pending_capture(tools: list[Any]) -> None:
+ """Finish a pending dump with the exact surface about to reach the model."""
+
+ pending = _PENDING_MODEL_INPUT_CAPTURE.get()
+ _PENDING_MODEL_INPUT_CAPTURE.set(None)
+ if pending is None:
+ return
+
+ try:
+ from skyvern.forge import app
+
+ surface = serialize_tool_surface(tools)
+ payload = {
+ **pending.payload,
+ "tool_surface": surface.payload,
+ "tool_surface_sha256": surface.sha256,
+ }
+ parameters = pending.redaction_parameters
+ if parameters:
+ payload = app.AGENT_FUNCTION.redact_codeblock_parameter_values(payload, parameters)
+ if not isinstance(payload, dict):
+ payload = {}
+ serialized = json.dumps(payload, indent=2, default=str)
+ if parameters:
+ serialized = app.AGENT_FUNCTION.redact_codeblock_parameter_values(serialized, parameters)
+ pending.path.write_text(serialized if isinstance(serialized, str) else "")
+ except Exception: # noqa: BLE001 - optional capture evidence must never block the model call
+ LOG.warning("Failed to attach tool surface to Copilot model-input capture")
diff --git a/skyvern/forge/sdk/copilot/model_telemetry.py b/skyvern/forge/sdk/copilot/model_telemetry.py
index b711406ae..17d0c0c24 100644
--- a/skyvern/forge/sdk/copilot/model_telemetry.py
+++ b/skyvern/forge/sdk/copilot/model_telemetry.py
@@ -44,6 +44,7 @@ from skyvern.forge.sdk.copilot.cache_envelope import (
ExplicitCacheEnvelope,
build_explicit_cache_envelope,
)
+from skyvern.forge.sdk.copilot.model_input_capture import attach_tool_surface_to_pending_capture
from skyvern.forge.sdk.copilot.pending_operation import pending_operation
LOG = structlog.get_logger()
@@ -276,6 +277,7 @@ class CopilotLitellmModel(LitellmModel):
conversation_id: str | None = None,
prompt: Any | None = None,
) -> ModelResponse:
+ attach_tool_surface_to_pending_capture(tools)
with model_call_telemetry_scope(
self.next_model_call_index(),
model=self.model,
@@ -307,6 +309,7 @@ class CopilotLitellmModel(LitellmModel):
conversation_id: str | None = None,
prompt: Any | None = None,
) -> AsyncIterator[TResponseStreamEvent]:
+ attach_tool_surface_to_pending_capture(tools)
with model_call_telemetry_scope(
self.next_model_call_index(),
model=self.model,
diff --git a/skyvern/forge/sdk/copilot/output_utils.py b/skyvern/forge/sdk/copilot/output_utils.py
index 0abeb26dd..c57ad890c 100644
--- a/skyvern/forge/sdk/copilot/output_utils.py
+++ b/skyvern/forge/sdk/copilot/output_utils.py
@@ -856,7 +856,10 @@ def sanitize_tool_result_for_llm(tool_name: str, result: dict[str, Any]) -> dict
# 2000 chars ~= 500 LLM tokens — enough for the model to see the
# overall shape without consuming a meaningful slice of the prompt
# budget. Over this, point the model at get_block_schema instead.
- if len(schema_str) > 2000:
+ # get_block_schema is exempt: the schema is what it was called for, and the steering
+ # message names the call that produced it, so truncating here leaves the model no route
+ # to the fields it asked for.
+ if len(schema_str) > 2000 and tool_name != "get_block_schema":
data["schema"] = {
"_truncated": True,
"message": (
diff --git a/skyvern/forge/sdk/copilot/session_factory.py b/skyvern/forge/sdk/copilot/session_factory.py
index 3636c089e..9cbf8cfb2 100644
--- a/skyvern/forge/sdk/copilot/session_factory.py
+++ b/skyvern/forge/sdk/copilot/session_factory.py
@@ -40,6 +40,10 @@ from skyvern.forge.sdk.copilot.enforcement import (
log_recent_tool_output_truncation,
pending_screenshot_message,
)
+from skyvern.forge.sdk.copilot.model_input_capture import (
+ clear_pending_model_input_capture,
+ register_pending_model_input_capture,
+)
from skyvern.forge.sdk.copilot.screenshot_utils import (
PendingFrameLease,
ScreenshotActionRelation,
@@ -241,6 +245,7 @@ def _maybe_dump_model_input(data: CallModelData[Any], model_data: ModelInputData
includes page text and tool results, so writing takes both an explicit path and a local
environment rather than the path alone.
"""
+ clear_pending_model_input_capture()
dump_dir = os.getenv("COPILOT_DUMP_MODEL_INPUTS")
if not dump_dir or settings.ENV != "local":
return
@@ -262,7 +267,6 @@ def _maybe_dump_model_input(data: CallModelData[Any], model_data: ModelInputData
"prompt_sha256": (
prompt_sha256(model_data.instructions) if isinstance(model_data.instructions, str) else None
),
- "tool_surface_sha256": getattr(ctx, "eval_tool_surface_sha256", None),
"instructions": model_data.instructions,
"input": [_jsonable(item) for item in model_data.input],
"requested_output_paths": requested_output_paths,
@@ -277,6 +281,11 @@ def _maybe_dump_model_input(data: CallModelData[Any], model_data: ModelInputData
if parameters:
serialized = app.AGENT_FUNCTION.redact_codeblock_parameter_values(serialized, parameters)
path.write_text(serialized if isinstance(serialized, str) else "")
+ register_pending_model_input_capture(
+ path=path,
+ payload=payload,
+ redaction_parameters=parameters,
+ )
except Exception:
LOG.warning("Failed to dump copilot model input")
diff --git a/skyvern/forge/sdk/copilot/tools/banned_blocks.py b/skyvern/forge/sdk/copilot/tools/banned_blocks.py
index 65bda2cbd..bd8553987 100644
--- a/skyvern/forge/sdk/copilot/tools/banned_blocks.py
+++ b/skyvern/forge/sdk/copilot/tools/banned_blocks.py
@@ -1,5 +1,6 @@
from __future__ import annotations
+from collections.abc import Mapping
from dataclasses import dataclass
from enum import StrEnum
from typing import Any
@@ -21,6 +22,7 @@ class CopilotBlockPolicyStatus(StrEnum):
class CopilotBlockPolicyScope(StrEnum):
ALL = "all"
CODE_ONLY_BROWSER = "code_only_browser"
+ TASK_V3_PURE = "task_v3_pure"
@dataclass(frozen=True)
@@ -34,6 +36,7 @@ class CopilotBlockPolicy:
_P = CopilotBlockPolicy
_ALL = CopilotBlockPolicyScope.ALL
_CODE_ONLY = CopilotBlockPolicyScope.CODE_ONLY_BROWSER
+_TASK_V3_PURE = CopilotBlockPolicyScope.TASK_V3_PURE
_BANNED = CopilotBlockPolicyStatus.BANNED
_PENDING = CopilotBlockPolicyStatus.CODE_NATIVE_PENDING
_AI_LEAF = CopilotBlockPolicyStatus.DECLARED_AI_LEAF
@@ -67,6 +70,12 @@ _COPILOT_BLOCK_TYPE_POLICIES: dict[str, CopilotBlockPolicy] = {
"workflow blocks or focused code blocks instead."
),
),
+ "code": _P(
+ _BANNED,
+ _TASK_V3_PURE,
+ "Task V3-only execution",
+ "Use engine-less deterministic blocks or a supported task block pinned to `skyvern-3.0`.",
+ ),
**{
block_type: _P(
_BANNED,
@@ -110,7 +119,45 @@ _COPILOT_BANNED_BLOCK_TYPES: frozenset[str] = frozenset(
for block_type, policy in _COPILOT_BLOCK_TYPE_POLICIES.items()
if policy.scope == CopilotBlockPolicyScope.ALL
)
-_COPILOT_CODE_ONLY_BROWSER_BANNED_BLOCK_TYPES: frozenset[str] = frozenset(_COPILOT_BLOCK_TYPE_POLICIES.keys())
+_COPILOT_CODE_ONLY_BROWSER_BANNED_BLOCK_TYPES: frozenset[str] = frozenset(
+ block_type
+ for block_type, policy in _COPILOT_BLOCK_TYPE_POLICIES.items()
+ if policy.scope in {CopilotBlockPolicyScope.ALL, CopilotBlockPolicyScope.CODE_ONLY_BROWSER}
+)
+_TASK_V3_PURE_TASK_BLOCK_TYPES: frozenset[str] = frozenset(
+ {"task", "navigation", "login", "action", "validation", "extraction", "file_download"}
+)
+_TASK_V3_PURE_BANNED_BLOCK_TYPES: frozenset[str] = frozenset(
+ block_type
+ for block_type, policy in _COPILOT_BLOCK_TYPE_POLICIES.items()
+ if policy.scope == CopilotBlockPolicyScope.TASK_V3_PURE
+ or (policy.status == CopilotBlockPolicyStatus.DECLARED_AI_LEAF and block_type not in _TASK_V3_PURE_TASK_BLOCK_TYPES)
+)
+_TASK_V3_ENGINE = "skyvern-3.0"
+
+
+class TaskV3PureViolationCode(StrEnum):
+ BLOCK_TYPE_UNAVAILABLE = "block_type_unavailable"
+ ENGINE_NOT_SKYVERN_V3 = "engine_not_skyvern_v3"
+ UNSUPPORTED_V3_COMBINATION = "unsupported_v3_combination"
+ SYNTHETIC_TASK_CONTROL_FLOW = "synthetic_task_control_flow"
+
+
+@dataclass(frozen=True)
+class TaskV3PurePolicyViolation:
+ label: str
+ block_type: str
+ code: TaskV3PureViolationCode
+ guidance: str
+
+ def as_dict(self) -> dict[str, str]:
+ return {
+ "label": self.label,
+ "block_type": self.block_type,
+ "code": self.code.value,
+ "guidance": self.guidance,
+ }
+
# Shared suffix across every LLM-facing rejection message for banned
# block emission — the pre-hook (schema-lookup reject) and the post-
@@ -147,15 +194,21 @@ def _copilot_block_authoring_policy(ctx: AgentContext | None) -> BlockAuthoringP
def _copilot_banned_block_types(ctx: AgentContext | None) -> frozenset[str]:
- if _copilot_block_authoring_policy(ctx) == BlockAuthoringPolicy.CODE_ONLY_BROWSER:
+ policy = _copilot_block_authoring_policy(ctx)
+ if policy == BlockAuthoringPolicy.CODE_ONLY_BROWSER:
return _COPILOT_CODE_ONLY_BROWSER_BANNED_BLOCK_TYPES
+ if policy == BlockAuthoringPolicy.TASK_V3_PURE:
+ return _TASK_V3_PURE_BANNED_BLOCK_TYPES
return _COPILOT_BANNED_BLOCK_TYPES
def _active_policy_scopes(ctx: AgentContext | None) -> frozenset[CopilotBlockPolicyScope]:
scopes = {CopilotBlockPolicyScope.ALL}
- if _copilot_block_authoring_policy(ctx) == BlockAuthoringPolicy.CODE_ONLY_BROWSER:
+ policy = _copilot_block_authoring_policy(ctx)
+ if policy == BlockAuthoringPolicy.CODE_ONLY_BROWSER:
scopes.add(CopilotBlockPolicyScope.CODE_ONLY_BROWSER)
+ elif policy == BlockAuthoringPolicy.TASK_V3_PURE:
+ scopes.add(CopilotBlockPolicyScope.TASK_V3_PURE)
return frozenset(scopes)
@@ -164,6 +217,8 @@ def _copilot_block_policy(
ctx: AgentContext | None,
) -> tuple[str, CopilotBlockPolicy] | None:
normalized = normalize_copilot_block_type_alias(block_type.strip().lower())
+ if normalized == "task" and _copilot_block_authoring_policy(ctx) == BlockAuthoringPolicy.TASK_V3_PURE:
+ return None
policy = _COPILOT_BLOCK_TYPE_POLICIES.get(normalized)
if policy is not None and policy.scope in _active_policy_scopes(ctx):
return normalized, policy
@@ -267,11 +322,133 @@ Runtime facts:
def _copilot_banned_block_alternatives(ctx: AgentContext | None) -> str:
- if _copilot_block_authoring_policy(ctx) == BlockAuthoringPolicy.CODE_ONLY_BROWSER:
+ policy = _copilot_block_authoring_policy(ctx)
+ if policy == BlockAuthoringPolicy.CODE_ONLY_BROWSER:
return _code_only_browser_unavailable_summary()
+ if policy == BlockAuthoringPolicy.TASK_V3_PURE:
+ return (
+ "Use engine-less workflow blocks for deterministic orchestration and integrations, or one of "
+ "`task`, `navigation`, `login`, `action`, `validation`, `extraction`, and `file_download` with "
+ "`engine: skyvern-3.0`."
+ )
return _COPILOT_BANNED_BLOCK_ALTERNATIVES
+def _task_v3_pure_policy_violations(workflow_yaml: str) -> list[TaskV3PurePolicyViolation]:
+ """Validate the complete proposed definition, including pre-existing leaves.
+
+ Task-V3-pure mode deliberately does not grandfather legacy blocks: accepting
+ any edit means the resulting workflow is pure, rather than only the edited
+ labels being pure.
+ """
+ blocks = _parse_workflow_blocks(workflow_yaml)
+ if blocks is None:
+ return []
+ violations: list[TaskV3PurePolicyViolation] = []
+ for block in blocks:
+ if isinstance(block, Mapping):
+ violations.extend(_task_v3_pure_block_violations(block))
+ return violations
+
+
+def _task_v3_pure_block_violations(block: Mapping[str, object]) -> list[TaskV3PurePolicyViolation]:
+ raw_type = block.get("block_type")
+ if not isinstance(raw_type, str):
+ return []
+ block_type = normalize_copilot_block_type_alias(raw_type.strip().lower())
+ raw_label = block.get("label")
+ label = raw_label if isinstance(raw_label, str) else "(unlabeled)"
+ violations: list[TaskV3PurePolicyViolation] = []
+
+ if block_type in _TASK_V3_PURE_BANNED_BLOCK_TYPES:
+ violations.append(
+ TaskV3PurePolicyViolation(
+ label=label,
+ block_type=block_type,
+ code=TaskV3PureViolationCode.BLOCK_TYPE_UNAVAILABLE,
+ guidance="Task-V3-pure mode does not allow code or task_v2 blocks.",
+ )
+ )
+ elif block_type in _TASK_V3_PURE_TASK_BLOCK_TYPES:
+ if block.get("engine") != _TASK_V3_ENGINE:
+ violations.append(
+ TaskV3PurePolicyViolation(
+ label=label,
+ block_type=block_type,
+ code=TaskV3PureViolationCode.ENGINE_NOT_SKYVERN_V3,
+ guidance="Set the submitted block engine exactly to `skyvern-3.0`.",
+ )
+ )
+ if block_type == "validation" and block.get("complete_on_download") is True:
+ violations.append(
+ TaskV3PurePolicyViolation(
+ label=label,
+ block_type=block_type,
+ code=TaskV3PureViolationCode.UNSUPPORTED_V3_COMBINATION,
+ guidance="Use a separate file_download block; Task V3 does not support download-gated validation.",
+ )
+ )
+
+ if block_type == "for_loop":
+ loop_variable_reference = block.get("loop_variable_reference")
+ loop_over_parameter_key = block.get("loop_over_parameter_key")
+ has_free_form_loop_reference = (
+ not isinstance(loop_variable_reference, str)
+ or loop_variable_reference.strip(" {}") != loop_over_parameter_key
+ )
+ if loop_variable_reference not in (None, "") and has_free_form_loop_reference:
+ violations.append(
+ TaskV3PurePolicyViolation(
+ label=label,
+ block_type=block_type,
+ code=TaskV3PureViolationCode.SYNTHETIC_TASK_CONTROL_FLOW,
+ guidance="Use `loop_over_parameter_key`; free-form loop input creates a synthetic task.",
+ )
+ )
+ elif block_type == "while_loop":
+ condition = block.get("condition")
+ if isinstance(condition, Mapping) and condition.get("criteria_type", "jinja2_template") != "jinja2_template":
+ violations.append(
+ TaskV3PurePolicyViolation(
+ label=label,
+ block_type=block_type,
+ code=TaskV3PureViolationCode.SYNTHETIC_TASK_CONTROL_FLOW,
+ guidance="Use a `jinja2_template` condition; prompt criteria create a synthetic task.",
+ )
+ )
+ elif block_type == "conditional":
+ branch_conditions = block.get("branch_conditions")
+ if isinstance(branch_conditions, list) and any(
+ isinstance(branch, Mapping)
+ and isinstance(branch.get("criteria"), Mapping)
+ and branch["criteria"].get("criteria_type", "jinja2_template") != "jinja2_template"
+ for branch in branch_conditions
+ ):
+ violations.append(
+ TaskV3PurePolicyViolation(
+ label=label,
+ block_type=block_type,
+ code=TaskV3PureViolationCode.SYNTHETIC_TASK_CONTROL_FLOW,
+ guidance="Use `jinja2_template` branch criteria; prompt criteria create a synthetic task.",
+ )
+ )
+
+ loop_blocks = block.get("loop_blocks")
+ if isinstance(loop_blocks, list):
+ for nested in loop_blocks:
+ if isinstance(nested, Mapping):
+ violations.extend(_task_v3_pure_block_violations(nested))
+ return violations
+
+
+def _task_v3_pure_reject_message(violations: list[TaskV3PurePolicyViolation]) -> str:
+ details = " ".join(
+ f"{violation.label} ({violation.block_type}, {violation.code.value}): {violation.guidance}"
+ for violation in violations
+ )
+ return f"The submitted workflow violates the active Task-V3-pure block policy. {details}"
+
+
def _banned_block_reject_message(items: list[tuple[str, str]], ctx: AgentContext | None = None) -> str:
"""Uniform error text for the post-emission reject, sharing the
alternatives suffix with the schema pre-hook."""
diff --git a/skyvern/forge/sdk/copilot/tools/mcp_hooks.py b/skyvern/forge/sdk/copilot/tools/mcp_hooks.py
index b36449086..70481ced7 100644
--- a/skyvern/forge/sdk/copilot/tools/mcp_hooks.py
+++ b/skyvern/forge/sdk/copilot/tools/mcp_hooks.py
@@ -1,6 +1,7 @@
from __future__ import annotations
import asyncio
+import copy
import json
import re
import uuid
@@ -9,6 +10,7 @@ from enum import StrEnum
from typing import Any
import structlog
+from pydantic import JsonValue
from skyvern.forge import app
from skyvern.forge.sdk.copilot.block_type_aliases import normalize_copilot_block_type_alias
@@ -40,6 +42,7 @@ from skyvern.forge.sdk.copilot.runtime import AgentContext, ScoutedInteraction,
from skyvern.forge.sdk.copilot.secret_redaction import redact_raw_secrets_for_prompt
from skyvern.forge.sdk.copilot.secret_scrub import registered_scrub_values
from skyvern.forge.sdk.schemas.credentials import Credential
+from skyvern.schemas.workflows import TaskBlockYAML
from ._shared import (
_DISCOVERY_PER_CALL_TIMEOUT_SECONDS,
@@ -50,6 +53,9 @@ from .banned_blocks import (
_CODE_ONLY_TARGET_EVIDENCE_KEYS,
_COPILOT_BANNED_BLOCK_TYPES,
_COPILOT_CODE_ONLY_BROWSER_BANNED_BLOCK_TYPES,
+ _TASK_V3_ENGINE,
+ _TASK_V3_PURE_BANNED_BLOCK_TYPES,
+ _TASK_V3_PURE_TASK_BLOCK_TYPES,
_code_only_browser_schema_guidance,
_code_only_browser_unavailable_summary,
_copilot_banned_block_alternatives,
@@ -58,6 +64,8 @@ from .banned_blocks import (
_copilot_block_policy,
_record_code_native_pending_capability,
_render_block_policy_detail,
+ _task_v3_pure_block_violations,
+ _task_v3_pure_reject_message,
)
from .page_observation import (
_record_composition_page_observation,
@@ -162,6 +170,16 @@ async def _get_block_schema_pre_hook(
normalized = normalize_copilot_block_type_alias(block_type)
if normalized != block_type.strip().lower():
params["block_type"] = normalized
+ if _copilot_block_authoring_policy(ctx) == BlockAuthoringPolicy.TASK_V3_PURE and normalized == "task":
+ return {
+ "ok": True,
+ "data": {
+ "block_type": "task",
+ "summary": "Run a general browser task with the Task V3 engine.",
+ "schema": _task_v3_pure_schema(TaskBlockYAML.model_json_schema()),
+ "task_v3_pure_guidance": _task_v3_pure_schema_guidance(),
+ },
+ }
policy_entry = _copilot_block_policy(normalized, ctx)
if policy_entry is None:
return None
@@ -208,7 +226,8 @@ async def _validate_block_pre_hook(
ctx: AgentContext,
) -> dict[str, Any] | None:
_normalize_block_json_alias(params)
- if _copilot_block_authoring_policy(ctx) != BlockAuthoringPolicy.CODE_ONLY_BROWSER:
+ authoring_policy = _copilot_block_authoring_policy(ctx)
+ if authoring_policy not in {BlockAuthoringPolicy.CODE_ONLY_BROWSER, BlockAuthoringPolicy.TASK_V3_PURE}:
return None
block_json = params.get("block_json")
if not isinstance(block_json, str):
@@ -219,6 +238,15 @@ async def _validate_block_pre_hook(
return None
if not isinstance(raw, dict):
return None
+ if authoring_policy == BlockAuthoringPolicy.TASK_V3_PURE:
+ violations = _task_v3_pure_block_violations(raw)
+ if violations:
+ return {
+ "ok": False,
+ "error": _task_v3_pure_reject_message(violations),
+ "data": {"violations": [violation.as_dict() for violation in violations]},
+ }
+ return None
block_type = raw.get("block_type")
if not isinstance(block_type, str):
return None
@@ -250,10 +278,39 @@ async def _get_block_schema_post_hook(
if isinstance(block_types, dict):
for banned in _copilot_banned_block_types(ctx):
block_types.pop(banned, None)
+ if _copilot_block_authoring_policy(ctx) == BlockAuthoringPolicy.TASK_V3_PURE:
+ for task_block_type in sorted(_TASK_V3_PURE_TASK_BLOCK_TYPES):
+ block_types.setdefault(
+ task_block_type,
+ f"Task V3 {task_block_type.replace('_', ' ')} block",
+ )
data["count"] = len(block_types)
block_type = data.get("block_type")
+ if (
+ _copilot_block_authoring_policy(ctx) == BlockAuthoringPolicy.TASK_V3_PURE
+ and isinstance(block_type, str)
+ and block_type in _TASK_V3_PURE_TASK_BLOCK_TYPES
+ and isinstance(data.get("schema"), dict)
+ ):
+ data["schema"] = _task_v3_pure_schema(data["schema"])
+ data["task_v3_pure_guidance"] = _task_v3_pure_schema_guidance()
if _copilot_block_authoring_policy(ctx) == BlockAuthoringPolicy.CODE_ONLY_BROWSER and block_type == "code":
ctx.code_only_code_schema_seen = True
+ schema = data.get("schema")
+ if isinstance(schema, dict):
+ properties = schema.get("properties")
+ if isinstance(properties, dict) and isinstance(properties.get("prompt"), dict):
+ properties["prompt"] = {
+ "type": "string",
+ "description": (
+ "Every new or wholly rewritten code block must include this non-null string: "
+ "the model-authored plain-language Goal shown in the editor."
+ ),
+ }
+ required = schema.get("required")
+ required_fields = required if isinstance(required, list) else []
+ if "prompt" not in required_fields:
+ schema["required"] = [*required_fields, "prompt"]
data["code_only_note"] = _code_only_browser_unavailable_summary()
data["code_only_guidance"] = _code_only_browser_schema_guidance()
data["download_claim_helper_contract"] = download_claim_helper_contract()
@@ -266,6 +323,32 @@ async def _get_block_schema_post_hook(
return result
+def _task_v3_pure_schema(schema: dict[str, JsonValue]) -> dict[str, JsonValue]:
+ policy_schema = copy.deepcopy(schema)
+ properties = policy_schema.get("properties")
+ if isinstance(properties, dict):
+ properties["engine"] = {
+ "type": "string",
+ "const": _TASK_V3_ENGINE,
+ "description": "Required by the active Task-V3-pure authoring policy.",
+ }
+ required = policy_schema.get("required")
+ if isinstance(required, list) and "engine" not in required:
+ required.append("engine")
+ elif not isinstance(required, list):
+ policy_schema["required"] = ["engine"]
+ return policy_schema
+
+
+def _task_v3_pure_schema_guidance() -> list[str]:
+ return [
+ "Set every task-shaped block engine exactly to `skyvern-3.0`.",
+ "Use engine-less blocks for orchestration, integrations, direct navigation, waits, files, and human interaction.",
+ "Use `loop_over_parameter_key` for for_loop input and explicit `jinja2_template` criteria for conditional or while_loop control flow.",
+ "Code, task_v2, free-form for_loop inputs, prompt control-flow criteria, and download-gated validation are unavailable.",
+ ]
+
+
async def _get_workflow_knowledge_post_hook(
result: dict[str, Any],
raw: dict[str, Any],
@@ -1519,7 +1602,11 @@ def _block_schema_banned_types_note(
banned = (
_COPILOT_CODE_ONLY_BROWSER_BANNED_BLOCK_TYPES
if normalize_block_authoring_policy(block_authoring_policy) == BlockAuthoringPolicy.CODE_ONLY_BROWSER
- else _COPILOT_BANNED_BLOCK_TYPES
+ else (
+ _TASK_V3_PURE_BANNED_BLOCK_TYPES
+ if normalize_block_authoring_policy(block_authoring_policy) == BlockAuthoringPolicy.TASK_V3_PURE
+ else _COPILOT_BANNED_BLOCK_TYPES
+ )
)
return f"Unavailable under the active policy and rejected on request: {', '.join(sorted(banned))}."
diff --git a/skyvern/forge/sdk/copilot/tools/run_execution.py b/skyvern/forge/sdk/copilot/tools/run_execution.py
index 652f5f495..a5f32d216 100644
--- a/skyvern/forge/sdk/copilot/tools/run_execution.py
+++ b/skyvern/forge/sdk/copilot/tools/run_execution.py
@@ -138,6 +138,7 @@ from skyvern.forge.sdk.schemas.workflow_runs import WorkflowRunBlock
from skyvern.forge.sdk.settings_manager import SettingsManager
from skyvern.forge.sdk.utils.pdf_parser import extract_pdf_file
from skyvern.forge.sdk.workflow.models.block import CodeBlock
+from skyvern.forge.sdk.workflow.models.code_block_recorder import RECORDED_FAILURE_RESPONSE_MAX_CHARS
from skyvern.forge.sdk.workflow.models.parameter import OutputParameter, WorkflowParameter, WorkflowParameterType
from skyvern.forge.sdk.workflow.models.workflow import Workflow, WorkflowRun, WorkflowRunStatus
from skyvern.forge.sdk.workflow.runtime_completion import contract_from_request_criteria
@@ -452,7 +453,9 @@ async def _attach_action_traces(
if action.response:
# Persistence masks registered secrets and parameters; a token the block
# obtained at runtime is in neither registry, so screen it here too.
- entry["response"] = redact_raw_secrets_for_prompt(action.response)[:300]
+ entry["response"] = redact_raw_secrets_for_prompt(action.response)[
+ :RECORDED_FAILURE_RESPONSE_MAX_CHARS
+ ]
action_trace.append(entry)
block_result["action_trace"] = action_trace
@@ -2302,7 +2305,11 @@ async def _run_blocks_and_collect_debug(
browser_session_id=run_session_id,
block_labels=labels_to_execute,
block_outputs=block_outputs_to_seed or None,
- workflow_override=runtime_workflow,
+ # The run was created against the dispatch version, so execute that same
+ # definition: its blocks carry the persisted output-parameter rows. Executing
+ # the in-memory runtime copy instead registers block outputs against ids that
+ # were never persisted, and every consumer keyed on the definition drops them.
+ workflow_override=dispatch_workflow or runtime_workflow,
requested_completion_contract=requested_completion_contract,
)
)
diff --git a/skyvern/forge/sdk/copilot/tools/workflow_update.py b/skyvern/forge/sdk/copilot/tools/workflow_update.py
index 5044fcf2f..55d579ea7 100644
--- a/skyvern/forge/sdk/copilot/tools/workflow_update.py
+++ b/skyvern/forge/sdk/copilot/tools/workflow_update.py
@@ -131,6 +131,8 @@ from .banned_blocks import (
_copilot_block_authoring_policy,
_detect_new_banned_blocks,
_record_banned_block_reject_span,
+ _task_v3_pure_policy_violations,
+ _task_v3_pure_reject_message,
)
from .credentials import _credential_id_misbinding_findings, _credential_reference_validation_error
from .frontier import (
@@ -3978,6 +3980,19 @@ async def _update_workflow(
last_yaml = ctx.last_workflow_yaml
prior_yaml = last_yaml if isinstance(last_yaml, str) and last_yaml else ctx.workflow_yaml
+ if _copilot_block_authoring_policy(ctx) == BlockAuthoringPolicy.TASK_V3_PURE:
+ task_v3_pure_violations = _task_v3_pure_policy_violations(workflow_yaml)
+ if task_v3_pure_violations:
+ violation_items = [(violation.label, violation.block_type) for violation in task_v3_pure_violations]
+ _record_banned_block_reject_span("_update_workflow", violation_items)
+ return _blocked(
+ AuthorTimeBlock(
+ block_id=BANNED_BLOCKS_BLOCK_ID,
+ error=_task_v3_pure_reject_message(task_v3_pure_violations),
+ data={"violations": [violation.as_dict() for violation in task_v3_pure_violations]},
+ )
+ )
+
# Post-emission reject of copilot-v2 writes that introduce a banned
# block type. The schema pre_hook only fires when the LLM consults the
# schema; this safety net fires regardless of emission path. Label-based
diff --git a/skyvern/forge/sdk/core/skyvern_context.py b/skyvern/forge/sdk/core/skyvern_context.py
index b23e5eddc..83d966709 100644
--- a/skyvern/forge/sdk/core/skyvern_context.py
+++ b/skyvern/forge/sdk/core/skyvern_context.py
@@ -2,14 +2,18 @@ from __future__ import annotations
import asyncio
import builtins
+import html
+import re
+from bisect import bisect_left, bisect_right
from contextlib import contextmanager
from contextvars import ContextVar, Token
from dataclasses import dataclass, field
from enum import StrEnum
-from typing import TYPE_CHECKING, Any, Callable, Iterator, TypedDict
+from typing import TYPE_CHECKING, Any, Callable, Iterable, Iterator, TypedDict
from zoneinfo import ZoneInfo
import structlog
+from pydantic import AnyHttpUrl, TypeAdapter, ValidationError
from skyvern.config import settings
from skyvern.schemas.run_enums import RunEngine
@@ -39,6 +43,124 @@ MAX_DIALOG_MESSAGE_CHARS = 500
MODEL_HIDDEN_PLACEHOLDER = "[withheld: sign-in link]"
+# An apostrophe is legal inside a URL, so it is part of the span; a prose quote is trimmed with the
+# other trailing punctuation below.
+URL_IN_TEXT = re.compile(r"https?://[^\s<>\"`]+", re.IGNORECASE)
+_URL_START = re.compile(r"https?://", re.IGNORECASE)
+_URL_TRAILING_PUNCTUATION = ".,;:!?)]}>'\""
+_PERCENT_ESCAPE_RE = re.compile(r"%[0-9a-f]{2}", re.IGNORECASE)
+# Upper bound on prose punctuation or quotes tried around one URL span, so a page-controlled run of
+# punctuation cannot make the pass quadratic.
+_MAX_SPAN_CUTS = 8
+# The same WHATWG parser validate_fetch_url runs before page.goto, so an echoed URL is compared in the
+# exact shape the browser was handed (host case/IDN/IP literal, default port, dot segments, path chars).
+_BROWSER_URL = TypeAdapter(AnyHttpUrl)
+# Chromium additionally percent-encodes these two path characters that the spec parser keeps raw.
+_CHROMIUM_PATH_ESCAPES = str.maketrans({"^": "%5E", "|": "%7C"})
+_URL_PATH_RE = re.compile(r"^(?P<prefix>[a-z][a-z0-9+.-]*://[^/?#]*)(?P<path>[^?#]*)", re.IGNORECASE)
+
+
+def canonical_url(url: str) -> str:
+ """The identity of a URL as the browser reports it back: WHATWG-normalized, Chromium path escapes
+ applied, percent-escape case folded. Comparison-only; a string the parser rejects is compared as
+ written."""
+ try:
+ normalized = str(_BROWSER_URL.validate_python(url))
+ except ValidationError:
+ normalized = url
+ normalized = _URL_PATH_RE.sub(
+ lambda m: m.group("prefix") + m.group("path").translate(_CHROMIUM_PATH_ESCAPES), normalized, count=1
+ )
+ return _PERCENT_ESCAPE_RE.sub(lambda m: m.group(0).upper(), normalized)
+
+
+def opaque_url_echo_forms(url: str) -> tuple[str, ...]:
+ """Every shape a surface can hand back a payload URL in, and so every shape the masker matches: as
+ minted, as the browser canonicalises it, and either one entity-escaped for HTML."""
+ canonical = canonical_url(url)
+ return tuple(dict.fromkeys((url, html.escape(url, quote=False), canonical, html.escape(canonical, quote=False))))
+
+
+def opaque_url_echo_window(urls: Iterable[str]) -> int:
+ """The longest text the masker recognises as one payload URL, in UTF-16 code units so a JS slice()
+ measures it the same way; the slack covers the punctuation a span search trims around it."""
+ return (
+ max((len(form.encode("utf-16-le")) // 2 for url in urls for form in opaque_url_echo_forms(url)), default=0) + 16
+ )
+
+
+def _mask_url_span(raw: str, canonical: dict[str, str], window: int) -> str:
+ """Rewrite every payload ref inside one URL-shaped span. Iterative and window-bounded, so a page
+ that glues thousands of refs with quotes costs linear time and no stack."""
+ quotes = [i for i, ch in enumerate(raw) if ch == "'"]
+ out: list[str] = []
+ pos = 0
+ # Scheme-only search: matching the greedy span regex from each offset would rescan the tail.
+ while (match := _URL_START.search(raw, pos)) is not None:
+ start = match.start()
+ out.append(raw[pos:start])
+ # Candidate ends, longest first: the window edge and each quote in it (a ref that extends past a
+ # quote wins over a ref that is its prefix; a ref whose own path holds many quotes is found from
+ # the last few), each with a bounded amount of trailing punctuation trimmed.
+ limit = min(len(raw), start + window)
+ first, last = bisect_left(quotes, start), bisect_right(quotes, limit)
+ stops = {*quotes[first : first + _MAX_SPAN_CUTS], *quotes[max(first, last - _MAX_SPAN_CUTS) : last], limit}
+ ends: builtins.set[int] = builtins.set()
+ for stop in stops:
+ floor = stop
+ while floor > start and raw[floor - 1] in _URL_TRAILING_PUNCTUATION:
+ floor -= 1
+ ends.update((stop, *range(floor, min(stop, floor + _MAX_SPAN_CUTS))))
+ token = None
+ for stop in sorted(ends, reverse=True):
+ if stop <= start:
+ continue
+ span = raw[start:stop]
+ # A span lifted out of HTML carries entity-escaped separators (&amp;); a ref never does, so
+ # only the text side is decoded, and only after the raw span failed to match.
+ for candidate in dict.fromkeys((span, html.unescape(span) if "&" in span else span)):
+ token = canonical.get(canonical_url(candidate))
+ if token is not None:
+ break
+ if token is not None:
+ out.append(token)
+ pos = stop
+ break
+ else:
+ out.append(raw[start])
+ pos = start + 1
+ out.append(raw[pos:])
+ return "".join(out)
+
+
+def mask_opaque_urls_in_text(text: str, refs: dict[str, str]) -> str:
+ """Replace every occurrence of a known payload signed-URL in ``text`` with its opaque token — the
+ inverse of resolving that token. Masking is by PROVENANCE (membership in ``refs``), never URL
+ shape, so a live-page URL the model must reason about is untouched even when it is itself
+ signing-shaped (a ``?gclid=``/``?token=`` landing page). ``refs`` maps token -> real URL (the
+ OpaqueUrlRefs.refs shape). Same object when nothing matches."""
+ if not refs:
+ return text
+ masked = text
+ # Longest URL first so a payload URL that is a prefix of another is not partially rewritten.
+ for token, url in sorted(refs.items(), key=lambda item: len(item[1]), reverse=True):
+ # A URL rendered inside HTML (get_html) has its query separators entity-encoded (& -> &amp;),
+ # so a multi-parameter presigned URL never matches its raw form there; match the escaped form
+ # too. Plain-text surfaces carry only the raw form, where html.escape is a no-op.
+ for variant in dict.fromkeys((url, html.escape(url, quote=False))):
+ if variant in masked:
+ masked = masked.replace(variant, token)
+ # The browser reports a payload URL back in canonical form (page.url adds the "/" path, drops a
+ # default port, punycodes a host), which no exact substring pass can anticipate; compare each
+ # URL-shaped span of the text by canonical identity, still membership-only.
+ if not URL_IN_TEXT.search(masked):
+ return masked
+ canonical = {canonical_url(url): token for token, url in refs.items()}
+ window = opaque_url_echo_window(refs.values())
+ rewritten = URL_IN_TEXT.sub(lambda m: _mask_url_span(m.group(0), canonical, window), masked)
+ return masked if rewritten == masked else rewritten
+
+
def _unwired_authority() -> RuntimeOriginAuthority:
# Same deferred-import reason as the TYPE_CHECKING block above: the policy core pulls the action
# models, which this module must not import at module load.
@@ -125,6 +247,11 @@ class SkyvernContext:
# run's context is rebuilt on the worker and never carries it, so runner selection can tell the
# two apart instead of inferring it from a process-wide capability.
copilot_inline_execution: bool = False
+ # The CodeBlock arm the rollout assigned this run to ("secure_runner" / "legacy_in_process"),
+ # stamped only on an authoritative flag/pin verdict so log lines can be grouped by arm for an
+ # unbiased secure-vs-legacy comparison. Left None when no genuine assignment was made (no browser
+ # session, provider unreachable) so a degraded provider never biases the legacy arm.
+ codeblock_execution_path: str | None = None
navigation_goal: str | None = None
navigation_payload: dict[str, Any] | list | str | None = None
complete_criterion_is_untrusted: bool = False
@@ -144,6 +271,12 @@ class SkyvernContext:
# output (e.g. a magic sign-in link), as opposed to values the model needs to read (e.g. a TOTP
# code) that are only scrubbed from artifacts/logs.
model_hidden_values: set[str] = field(default_factory=builtins.set)
+ # Signed payload URLs the v3 loop minted opaque tokens for (token -> real URL, mirroring
+ # OpaqueUrlRefs.refs). Applied to every model-facing tool result by hide_from_model so a resolved
+ # ref never re-enters the transcript verbatim. Keyed by membership, never URL shape. Replaced whole
+ # per task on the assumption blocks run sequentially; a parallel block type must single-flight
+ # this like workflow_block_engine_lock or one task's refs stomp another's mid-flight.
+ opaque_url_refs: dict[str, str] = field(default_factory=dict)
refresh_working_page: bool = False
frame_index_map: dict[Frame, int] = field(default_factory=dict)
dropped_css_svg_element_map: dict[str, bool] = field(default_factory=dict)
@@ -405,16 +538,14 @@ class SkyvernContext:
self.model_hidden_values.add(value)
def hide_from_model(self, text: str) -> str:
- """Exact-match replace every model_hidden_values entry with MODEL_HIDDEN_PLACEHOLDER, longest
- value first so a substring value can't fragment a longer one. Same object when nothing matches."""
- if not self.model_hidden_values:
- return text
+ """Return ``text`` with everything that must not reach the model's view of tool output replaced
+ by a model-safe surrogate: first each model_hidden_values entry by MODEL_HIDDEN_PLACEHOLDER
+ (longest value first so a substring value can't fragment a longer one), then each known payload
+ signed-URL by its opaque token (by PROVENANCE, not shape). Same object when nothing matches."""
for value in sorted(self.model_hidden_values, key=len, reverse=True):
- if not value:
- continue
- if value in text:
+ if value and value in text:
text = text.replace(value, MODEL_HIDDEN_PLACEHOLDER)
- return text
+ return mask_opaque_urls_in_text(text, self.opaque_url_refs)
def record_dialog_message(self, dialog_type: str, dialog_message: str) -> None:
"""Buffer a dialog with FIFO cap; identical entries bump a count instead of duplicating."""
diff --git a/skyvern/forge/sdk/encrypt/aes.py b/skyvern/forge/sdk/encrypt/aes.py
index 8a008d3b2..740f93544 100644
--- a/skyvern/forge/sdk/encrypt/aes.py
+++ b/skyvern/forge/sdk/encrypt/aes.py
@@ -1,5 +1,6 @@
import base64
import hashlib
+from collections.abc import Iterable
from cryptography.hazmat.primitives import hashes
from cryptography.hazmat.primitives.ciphers import Cipher, algorithms, modes
@@ -7,18 +8,18 @@ from cryptography.hazmat.primitives.kdf.pbkdf2 import PBKDF2HMAC
from skyvern.forge.sdk.encrypt.base import BaseEncryptor, EncryptMethod
-# The public defaults and fallback parameters retain the legacy MD5 normalization so
-# existing ciphertext remains decryptable. New ciphertext configured with an explicit
-# salt and IV uses SHA-256 normalization instead.
+# key/salt path: md5 output is fed into PBKDF2HMAC-SHA256 (100k iterations) inside
+# _derive_key(); md5 is only a string->16-byte normalizer, so usedforsecurity=False is
+# honest. Changing the hash would invalidate every stored ciphertext, so the
+# normalizer itself is locked-in until a re-key migration.
#
-# The SHA-derived IV remains deterministic, matching the persisted ciphertext format.
-# A future authenticated-encryption migration can introduce random nonces stored with
-# each ciphertext; that requires a versioned payload and is separate from removing MD5
-# from the primary encryption path here.
-#
-# Fallback candidates are decrypt-only. They let deployments read values written before
-# this normalization change and naturally age out as those values are rewritten through
-# the primary path.
+# iv path (default_iv / self.iv below): md5 output becomes the AES-CBC IV directly,
+# so md5 *is* being used in a security-sensitive position there. But the real issue
+# is architectural — the IV is deterministic (same input string -> same IV every
+# time), which breaks AES-CBC semantic security. Swapping md5 for SHA-256 wouldn't
+# fix that. Fix requires random per-encryption IVs stored alongside ciphertext,
+# which is a breaking migration tracked separately. Those two md5() calls are left
+# without usedforsecurity=False on purpose so the alert keeps surfacing as debt.
default_iv = hashlib.md5(b"deterministic_iv_0123456789").digest()
default_salt = hashlib.md5(b"deterministic_salt_0123456789", usedforsecurity=False).digest()
@@ -30,29 +31,25 @@ class AES(BaseEncryptor):
secret_key: str,
salt: str | None = None,
iv: str | None = None,
- fallback_decrypt_keys: list[tuple[str | None, str | None]] | None = None,
+ fallback_decrypt_keys: Iterable[tuple[str | None, str | None]] | None = None,
) -> None:
self.secret_key = hashlib.md5(secret_key.encode("utf-8"), usedforsecurity=False).digest()
- self.salt = hashlib.sha256(salt.encode("utf-8")).digest() if salt else default_salt
- self.iv = hashlib.sha256(iv.encode("utf-8")).digest()[:16] if iv else default_iv
- self._fallback_decrypt_params: list[tuple[bytes, bytes]] = [
- (
- hashlib.sha256(fb_salt.encode("utf-8")).digest() if fb_salt else default_salt,
- hashlib.sha256(fb_iv.encode("utf-8")).digest()[:16] if fb_iv else default_iv,
- )
- for fb_salt, fb_iv in (fallback_decrypt_keys or [])
+ self.salt, self.iv = self._encryption_params(salt, iv)
+ self._fallback_decrypt_params = [
+ self._encryption_params(fallback_salt, fallback_iv)
+ for fallback_salt, fallback_iv in (fallback_decrypt_keys or [])
]
- self._fallback_decrypt_params.extend(
- (
- hashlib.md5(fb_salt.encode("utf-8"), usedforsecurity=False).digest() if fb_salt else default_salt,
- hashlib.md5(fb_iv.encode("utf-8")).digest() if fb_iv else default_iv,
- )
- for fb_salt, fb_iv in (fallback_decrypt_keys or [])
- )
def method(self) -> EncryptMethod:
return EncryptMethod.AES
+ @staticmethod
+ def _encryption_params(salt: str | None, iv: str | None) -> tuple[bytes, bytes]:
+ return (
+ hashlib.md5(salt.encode("utf-8"), usedforsecurity=False).digest() if salt else default_salt,
+ hashlib.md5(iv.encode("utf-8")).digest() if iv else default_iv,
+ )
+
def _derive_key(self, salt: bytes | None = None) -> bytes:
kdf = PBKDF2HMAC(
algorithm=hashes.SHA256(),
diff --git a/skyvern/forge/sdk/encrypt/bootstrap.py b/skyvern/forge/sdk/encrypt/bootstrap.py
index 6450c675d..26e606c6f 100644
--- a/skyvern/forge/sdk/encrypt/bootstrap.py
+++ b/skyvern/forge/sdk/encrypt/bootstrap.py
@@ -46,9 +46,9 @@ def create_aes_encryptor(
"secret; empty values and the default placeholder 'fillmein' both fail closed."
)
fallback_parameters = list(fallback_decrypt_keys or ())
- # Legacy ciphertext has no version marker. Always retry the pre-SHA-normalization
- # parameters on decrypt, including explicit deployment salt/IV settings.
- fallback_parameters.insert(0, (salt, iv))
+ if not (salt and iv):
+ # Legacy ciphertext has no version marker, so retry the pre-derivation parameters on decrypt.
+ fallback_parameters.insert(0, (salt, iv))
return AES(
secret_key=secret_key,
salt=salt or _derive_from_secret_key(secret_key, _SALT_DERIVATION_LABEL),
diff --git a/skyvern/forge/sdk/forge_log.py b/skyvern/forge/sdk/forge_log.py
index 6f1c1a7cb..39e1a4732 100644
--- a/skyvern/forge/sdk/forge_log.py
+++ b/skyvern/forge/sdk/forge_log.py
@@ -428,6 +428,8 @@ def add_log_context(logger: logging.Logger, method_name: str, event_dict: EventD
event_dict["browser_session_id"] = context.browser_session_id
if getattr(context, "copilot_session_id", None):
event_dict["copilot_session_id"] = context.copilot_session_id
+ if getattr(context, "codeblock_execution_path", None):
+ event_dict["codeblock_execution_path"] = context.codeblock_execution_path
if getattr(context, "browser_container_ip", None):
event_dict["browser_container_ip"] = context.browser_container_ip
if getattr(context, "browser_container_task_arn", None):
diff --git a/skyvern/forge/sdk/routes/streaming/cdp_input.py b/skyvern/forge/sdk/routes/streaming/cdp_input.py
index 85b18a178..9de5b834a 100644
--- a/skyvern/forge/sdk/routes/streaming/cdp_input.py
+++ b/skyvern/forge/sdk/routes/streaming/cdp_input.py
@@ -3,7 +3,6 @@ CDP input channel for interactive browser control via Chrome DevTools Protocol.
"""
import asyncio
-import contextlib
import dataclasses
import json
import time
@@ -11,13 +10,13 @@ import typing as t
import structlog
from fastapi import WebSocket, WebSocketDisconnect
+from opentelemetry import metrics
from playwright.async_api import CDPSession
from websockets.exceptions import ConnectionClosedError, ConnectionClosedOK
from skyvern.exceptions import BlockedNavigationDestination, InvalidUrl
from skyvern.forge import app
from skyvern.forge.sdk.routes.routers import base_router, legacy_base_router
-from skyvern.forge.sdk.routes.streaming import latency_probe
from skyvern.forge.sdk.routes.streaming.auth import auth, require_client_id
from skyvern.forge.sdk.routes.streaming.screencast import (
_resolve_working_page,
@@ -32,9 +31,6 @@ from skyvern.forge.sdk.streaming.registries import (
try_stream_ref_inc,
)
from skyvern.forge.sdk.workflow.models.workflow import WorkflowRunStatus
-from skyvern.services.browser_recording.v2.resolver import get_resolver
-from skyvern.services.browser_recording.v2.session import get_session_v2
-from skyvern.services.browser_recording.v2.tap import tap_navigation, tap_pipelined
from skyvern.utils.url_validators import prepend_scheme_and_validate_url
from skyvern.webeye.browser_errors import is_target_closed_message
from skyvern.webeye.browser_state import BrowserState
@@ -45,17 +41,19 @@ LOG = structlog.get_logger()
_INPUT_KIND_LABELS = frozenset(
{"mouseEvent", "keyEvent", "wheelEvent", "navigateEvent", "goBackEvent", "goForwardEvent", "reloadEvent"}
)
-_input_wait_seconds = latency_probe._meter.create_histogram(
+_LATENCY_BUCKETS_SECONDS = [0.001, 0.002, 0.005, 0.01, 0.02, 0.03, 0.045, 0.06, 0.1, 0.25, 0.5, 1.0, 2.5, 5.0]
+_meter = metrics.get_meter("skyvern.live_view")
+_input_wait_seconds = _meter.create_histogram(
"skyvern.live_view.input_wait_seconds",
unit="s",
description="Input event: receive_text returned -> dispatch started, including active-page resolution",
- explicit_bucket_boundaries_advisory=latency_probe._LATENCY_BUCKETS_SECONDS,
+ explicit_bucket_boundaries_advisory=_LATENCY_BUCKETS_SECONDS,
)
-_input_dispatch_seconds = latency_probe._meter.create_histogram(
+_input_dispatch_seconds = _meter.create_histogram(
"skyvern.live_view.input_dispatch_seconds",
unit="s",
description="Input event: dispatch handling after an active CDP session is acquired",
- explicit_bucket_boundaries_advisory=latency_probe._LATENCY_BUCKETS_SECONDS,
+ explicit_bucket_boundaries_advisory=_LATENCY_BUCKETS_SECONDS,
)
_VALID_MOUSE_TYPES = {"mousePressed", "mouseReleased", "mouseMoved"}
@@ -73,7 +71,6 @@ ACTIVE_PAGE_INPUT_REFRESH_INTERVAL = 0.5
_NAVIGATION_RESET_TIMEOUT_MS = 5_000
_TARGET_CLOSED_ERROR_TYPES = frozenset({"TargetClosedError", "CdpTargetClosedError"})
_PIPELINED_INPUT_KINDS = frozenset({"mouseEvent", "wheelEvent", "keyEvent"})
-_LATENCY_PROBED_MOUSE_TYPES = frozenset({"mousePressed", "mouseReleased"})
_MAX_IN_FLIGHT_INPUT_DISPATCHES = 32
@@ -81,10 +78,6 @@ def _input_kind_label(kind: object) -> str:
return kind if isinstance(kind, str) and kind in _INPUT_KIND_LABELS else "other"
-def _is_discrete_input(kind: str, msg: dict) -> bool:
- return kind in {"keyEvent", "wheelEvent"} or msg.get("eventType") in _LATENCY_PROBED_MOUSE_TYPES
-
-
@dataclasses.dataclass
class CdpInputChannel:
client_id: str
@@ -122,21 +115,6 @@ class ActivePageCdpInputSession:
self.next_refresh_at = 0.0
self.page_resolution_failed = False
- async def _attach_observer(self, page: object, session: CDPSession) -> None:
- if self.entity_type != "browser_session":
- return
- recording_session = get_session_v2(self.entity_id)
- if recording_session is None:
- return
- try:
- await recording_session.attach_page(str(id(page)), session)
- except Exception:
- LOG.warning(
- "v2 observer attach failed",
- **{self.log_id_key: self.log_id_value},
- exc_info=True,
- )
-
async def get_session(self, *, force_refresh: bool = False) -> CDPSession | None:
now = time.monotonic()
if not force_refresh and now < self.next_refresh_at:
@@ -162,14 +140,12 @@ class ActivePageCdpInputSession:
self.page_resolution_failed = False
self.next_refresh_at = now + self.refresh_interval
if self.cdp_session is not None and page is self.page:
- await self._attach_observer(page, self.cdp_session)
return self.cdp_session
await self.close()
session = await page.context.new_cdp_session(page) # type: ignore[attr-defined]
self.cdp_session = session
self.page = page
- await self._attach_observer(page, session)
LOG.info(
"CDP input rebound to active page",
**{self.log_id_key: self.log_id_value},
@@ -323,11 +299,6 @@ async def _close_ws_safely(websocket: WebSocket, code: int, reason: str = "") ->
pass
-async def _send_pong(websocket: WebSocket, t: object) -> None:
- with contextlib.suppress(Exception):
- await websocket.send_json({"kind": "pong", "t": t})
-
-
_EVENT_DISPATCH_MAP: dict[str, tuple[t.Callable[[dict], dict | None], str]] = {
"mouseEvent": (_validate_mouse_event, "Input.dispatchMouseEvent"),
"keyEvent": (_validate_key_event, "Input.dispatchKeyEvent"),
@@ -509,14 +480,12 @@ async def _run_input_loop(
input_session: ActivePageCdpInputSession,
log_id_key: str,
log_id_value: str,
- browser_session_id: str | None,
) -> None:
dropped_log_count = 0
no_active_page_log_count = 0
dispatch_semaphore = asyncio.Semaphore(_MAX_IN_FLIGHT_INPUT_DISPATCHES)
dispatch_tasks: set[asyncio.Task[None]] = set()
dispatch_failure_close_started = False
- bound_cdp_session: CDPSession | None = None
async def dispatch_pipelined_event(
cdp_session: CDPSession,
@@ -571,12 +540,6 @@ async def _run_input_loop(
kind = msg.get("kind") or msg.get("type")
- if kind == "ping":
- task = asyncio.create_task(_send_pong(websocket, msg.get("t")))
- dispatch_tasks.add(task)
- task.add_done_callback(dispatch_tasks.discard)
- continue
-
if kind == "take-control":
channel.interactor = "user"
LOG.info("CDP input: take-control received", **{log_id_key: log_id_value}, client_id=channel.client_id)
@@ -615,20 +578,11 @@ async def _run_input_loop(
no_active_page_log_count += 1
continue
- if cdp_session is not bound_cdp_session:
- resolver = get_resolver(browser_session_id) if browser_session_id else None
- if resolver is not None and bound_cdp_session is not None:
- resolver.forget_session(bound_cdp_session)
- bound_cdp_session = cdp_session
-
if kind in _PIPELINED_INPUT_KINDS:
dispatch = _validate_cdp_dispatch(kind, msg, log_id_key, log_id_value)
if dispatch is None:
continue
cdp_method, validated = dispatch
- tap_pipelined(browser_session_id, kind, validated, received_at, input_session.page, cdp_session)
- if browser_session_id and _is_discrete_input(kind, msg):
- latency_probe.note_input(browser_session_id, received_at)
await dispatch_semaphore.acquire()
if dispatch_failure_close_started:
dispatch_semaphore.release()
@@ -648,7 +602,6 @@ async def _run_input_loop(
dispatch_started = time.monotonic()
_input_wait_seconds.record(dispatch_started - received_at, attributes)
try:
- tap_navigation(browser_session_id, kind, msg, received_at, input_session.page)
await _dispatch_event(cdp_session, input_session.page, kind, msg, log_id_key, log_id_value, websocket)
except Exception:
LOG.warning(
@@ -743,7 +696,7 @@ async def cdp_input_stream(
LOG.info("CDP input channel ready", workflow_run_id=workflow_run_id, client_id=client_id)
await websocket.send_json({"kind": "ready"})
- await _run_input_loop(websocket, channel, input_session, "workflow_run_id", workflow_run_id, None)
+ await _run_input_loop(websocket, channel, input_session, "workflow_run_id", workflow_run_id)
except ConnectionClosedOK:
LOG.info("CDP input: WS closed cleanly", workflow_run_id=workflow_run_id)
@@ -825,9 +778,7 @@ async def cdp_input_browser_session_stream(
LOG.info("CDP input channel ready", browser_session_id=browser_session_id, client_id=client_id)
await websocket.send_json({"kind": "ready"})
- await _run_input_loop(
- websocket, channel, input_session, "browser_session_id", browser_session_id, browser_session_id
- )
+ await _run_input_loop(websocket, channel, input_session, "browser_session_id", browser_session_id)
except ConnectionClosedOK:
LOG.info("CDP input: WS closed cleanly", browser_session_id=browser_session_id)
@@ -838,7 +789,6 @@ async def cdp_input_browser_session_stream(
except Exception:
LOG.warning("CDP input: unexpected error", browser_session_id=browser_session_id, exc_info=True)
finally:
- latency_probe.forget(browser_session_id)
await _close_input_session_and_release_browser_state(
input_session, browser_state, "browser_session", browser_session_id
)
diff --git a/skyvern/forge/sdk/routes/streaming/channels/README.md b/skyvern/forge/sdk/routes/streaming/channels/README.md
index da6e28c45..a526c0800 100644
--- a/skyvern/forge/sdk/routes/streaming/channels/README.md
+++ b/skyvern/forge/sdk/routes/streaming/channels/README.md
@@ -4,7 +4,7 @@ A "channel", as used within the streaming mechanism of our remote browsers,
is a WebSocket fit to some particular purpose.
There is/are:
- - a "VNC" channel that transmits NoVNC's RFB protocol data (legacy viewers)
+ - a "VNC" channel that transmits NoVNC's RFB protocol data
- a "Message" channel that transmits JSON between the frontend app and
the api server
- "CDP" channels that send messages to a remote browser using CDP protocol
@@ -15,10 +15,10 @@ There is/are:
In all cases, these are just WebSockets. They have been bucketed into "named channels"
to aid understanding.
-Record Browser captures actions over CDP: the frontend renders screencast frames
-from the browser-session stream, user events arrive via the Exfiltration channel,
-and the Message channel carries recording commands and interpretation updates.
-The VNC channel and its Message pairing below apply to legacy VNC viewers.
+First-party browser sessions render over VNC. Record Browser captures user events
+over the Exfiltration channel, and the Message channel carries recording commands
+and interpretation updates. Vendor-held sessions without a relayable RFB endpoint
+render from CDP screencast instead.
These channels are described at the top of their respective files.
diff --git a/skyvern/forge/sdk/routes/streaming/channels/message.py b/skyvern/forge/sdk/routes/streaming/channels/message.py
index c04728364..9e67a4721 100644
--- a/skyvern/forge/sdk/routes/streaming/channels/message.py
+++ b/skyvern/forge/sdk/routes/streaming/channels/message.py
@@ -16,7 +16,6 @@ import asyncio
import dataclasses
import enum
import math
-import time
import typing as t
import structlog
@@ -25,8 +24,6 @@ from pydantic import BaseModel
from starlette.websockets import WebSocketState
from websockets.exceptions import ConnectionClosedError
-from skyvern.forge import app
-from skyvern.forge.sdk.routes.streaming import latency_probe
from skyvern.forge.sdk.routes.streaming.auth import get_x_api_key
from skyvern.forge.sdk.routes.streaming.channels.cdp import ChannelContext
from skyvern.forge.sdk.routes.streaming.channels.execution import execution_for_message_channel
@@ -46,25 +43,7 @@ from skyvern.forge.sdk.streaming.registries import (
)
from skyvern.forge.sdk.workflow.models.workflow import WorkflowRun
from skyvern.services.browser_recording.session_registry import interpretation_registry
-from skyvern.services.browser_recording.types import (
- RecordingDraftStep,
- RecordingInterpretationUpdate,
-)
-from skyvern.services.browser_recording.v2.render import (
- RenderMode,
- overlay_from_draft_steps,
- render_blocks,
- render_code,
-)
-from skyvern.services.browser_recording.v2.session import (
- RecordingSessionV2,
- RecordingUpdateV2,
- discard_session_v2,
- get_session_v2,
- start_session_v2,
-)
-from skyvern.services.browser_recording.v2.tap import tap_paste
-from skyvern.services.browser_recording.v2.wire import draft_steps_from_v2
+from skyvern.services.browser_recording.types import RecordingDraftStep, RecordingInterpretationUpdate
LOG = structlog.get_logger()
_MAX_IN_FLIGHT_CLIPBOARD_TASKS = 2
@@ -95,8 +74,6 @@ class MessageKind(enum.StrEnum):
RECORDING_CAPTURE_RESUME = "recording-capture-resume"
RECORDING_REARM_CAPTURE = "recording-rearm-capture"
RECORDING_INTERPRETATION_UPDATE = "recording-interpretation-update"
- RECORDING_COMMIT = "recording-commit"
- RECORDING_COMMITTED = "recording-committed"
SCREENSHOT = "screenshot"
TAKE_CONTROL = "take-control"
TAKE_SCREENSHOT = "take-screenshot"
@@ -143,8 +120,6 @@ MessageKinds = t.Literal[
MessageKind.RECORDING_CAPTURE_RESUME,
MessageKind.RECORDING_REARM_CAPTURE,
MessageKind.RECORDING_INTERPRETATION_UPDATE,
- MessageKind.RECORDING_COMMIT,
- MessageKind.RECORDING_COMMITTED,
MessageKind.SCREENSHOT,
MessageKind.TAKE_CONTROL,
MessageKind.TAKE_SCREENSHOT,
@@ -189,14 +164,6 @@ class MessageInRecordingRearmCapture(Message):
kind: t.Literal[MessageKind.RECORDING_REARM_CAPTURE] = MessageKind.RECORDING_REARM_CAPTURE
-class MessageInRecordingCommit(Message):
- kind: t.Literal[MessageKind.RECORDING_COMMIT] = MessageKind.RECORDING_COMMIT
- mode: t.Literal["blocks", "auto"] = "auto"
- # The panel's edits (deletions, renames); None means commit every interpreted step.
- draft_steps: list[dict] | None = None
-
-
@dataclasses.dataclass
class MessageInTakeControl(Message):
kind: t.Literal[MessageKind.TAKE_CONTROL] = MessageKind.TAKE_CONTROL
@@ -316,15 +283,6 @@ class MessageOutRecordingInterpretationUpdate(Message):
finalized: bool = False
-class MessageOutRecordingCommitted(Message):
- kind: t.Literal[MessageKind.RECORDING_COMMITTED] = MessageKind.RECORDING_COMMITTED
- blocks: list[dict] = dataclasses.field(default_factory=list)
- parameters: list[dict] = dataclasses.field(default_factory=list)
- mode: RenderMode = "blocks"
- diagnostics: dict = dataclasses.field(default_factory=dict)
-
-
@dataclasses.dataclass
class MessageOutTabInfo(Message):
kind: t.Literal[MessageKind.BROWSER_TABS] = MessageKind.BROWSER_TABS
@@ -347,7 +305,6 @@ MessageIn = (
| MessageInNavigate
| MessageInRecordingCapturePause
| MessageInRecordingCaptureResume
- | MessageInRecordingCommit
| MessageInRecordingRearmCapture
| MessageInReload
| MessageInTakeControl
@@ -359,7 +316,6 @@ MessageOut = (
MessageOutBrowserUrl
| MessageOutError
| MessageOutExfiltratedEvent
- | MessageOutRecordingCommitted
| MessageOutRecordingInterpretationUpdate
| MessageOutScreenshot
| MessageOutTabInfo
@@ -403,15 +359,6 @@ def reify_channel_message(data: dict) -> MessageIn:
return MessageInRecordingCaptureResume()
case MessageKind.RECORDING_REARM_CAPTURE:
return MessageInRecordingRearmCapture()
- case MessageKind.RECORDING_COMMIT:
- mode = data.get("mode")
- draft_steps = data.get("draft_steps")
- return MessageInRecordingCommit(
- mode="blocks" if mode == "blocks" else "auto",
- draft_steps=[step for step in draft_steps if isinstance(step, dict)]
- if isinstance(draft_steps, list)
- else None,
- )
case MessageKind.GET_BROWSER_URL:
return MessageInGetBrowserUrl()
case MessageKind.GO_BACK:
@@ -579,13 +526,6 @@ async def loop_stream_messages(message_channel: MessageChannel) -> None:
class_name = message_channel.class_name
exfiltration_channel: ExfiltrationChannel | None = None
live_interpretation_browser_session_id: str | None = None
- # Latched at the first begin-exfiltration: one socket drives one recorder, so a stale
- # v2 registry entry cannot hijack a v1 recording and a mid-socket flag flip cannot start both.
- recording_v2: bool | None = None
- # Captured once, like live_interpretation_browser_session_id, so cleanup can find the
- # session even after message_channel.browser_session goes None (e.g. the browser session
- # times out mid-recording while the live-view socket stays open).
- recording_v2_browser_session_id: str | None = None
clipboard_tasks: set[asyncio.Task[None]] = set()
clipboard_task_count = 0
@@ -606,11 +546,6 @@ async def loop_stream_messages(message_channel: MessageChannel) -> None:
task.add_done_callback(clipboard_tasks.discard)
return True
- def recording_session_v2() -> RecordingSessionV2 | None:
- if not recording_v2 or recording_v2_browser_session_id is None:
- return None
- return get_session_v2(recording_v2_browser_session_id)
-
async def send(message: MessageOut) -> None:
# Single-writer: enqueue only; backend_to_frontend is the sole task that
# writes to the websocket, so responses and out-of-band messages (event
@@ -621,8 +556,6 @@ async def loop_stream_messages(message_channel: MessageChannel) -> None:
nonlocal class_name
nonlocal exfiltration_channel
nonlocal live_interpretation_browser_session_id
- nonlocal recording_v2
- nonlocal recording_v2_browser_session_id
message: MessageIn
# receive_json returns whatever the client's JSON parses to — a top-level
@@ -697,39 +630,6 @@ async def loop_stream_messages(message_channel: MessageChannel) -> None:
if message_channel.browser_session
else None
)
- if browser_session_id:
- latency_probe.set_recording(browser_session_id, True)
-
- if recording_v2 is None:
- recording_v2 = bool(browser_session_id) and await app.AGENT_FUNCTION.is_record_browser_v2_enabled(
- message_channel.organization_id
- )
-
- if recording_v2 and browser_session_id:
- recording_v2_browser_session_id = browser_session_id
-
- def on_v2_update(update: RecordingUpdateV2) -> None:
- message_channel.send_nowait(
- messages=[
- MessageOutRecordingInterpretationUpdate(
- interpretation_session_id=browser_session_id or "",
- session_revision=update.session_revision,
- steps=draft_steps_from_v2(update.steps, update.epoch_offset_ms),
- changed_steps=draft_steps_from_v2(update.changed_steps, update.epoch_offset_ms),
- is_snapshot=update.is_snapshot,
- pending=update.pending,
- finalized=update.finalized,
- )
- ]
- )
-
- start_session_v2(
- browser_session_id=browser_session_id,
- organization_id=message_channel.organization_id,
- workflow_permanent_id=message.workflow_permanent_id,
- on_update=on_v2_update,
- )
- return
def on_interpretation_update(update: RecordingInterpretationUpdate) -> None:
message_channel.send_nowait(
@@ -916,13 +816,6 @@ async def loop_stream_messages(message_channel: MessageChannel) -> None:
try:
async with execution_for_message_channel(message_channel) as execute:
- tap_paste(
- message_channel.browser_session.persistent_browser_session_id
- if message_channel.browser_session
- else None,
- text,
- time.monotonic(),
- )
await execute.paste_text(text)
except Exception:
LOG.exception(
@@ -935,14 +828,6 @@ async def loop_stream_messages(message_channel: MessageChannel) -> None:
await send_error(message.kind, "Clipboard is busy; try again.")
case MessageKind.END_EXFILTRATION:
- if message_channel.browser_session:
- latency_probe.set_recording(message_channel.browser_session.persistent_browser_session_id, False)
- if recording_v2:
- if (v2_session := recording_session_v2()) is not None:
- # Seal only: the ledger is the commit's sole input and lives on this pod,
- # so the session stays in the registry until recording-commit or teardown.
- await v2_session.seal()
- return
# Channel teardown is best-effort: a browser whose target already
# closed raises here, and that must never skip the interpretation
# flush below — losing every draft the user just recorded.
@@ -963,28 +848,18 @@ async def loop_stream_messages(message_channel: MessageChannel) -> None:
live_interpretation_browser_session_id = None
case MessageKind.RECORDING_CAPTURE_PAUSE:
- if recording_v2:
- if (v2_session := recording_session_v2()) is not None:
- v2_session.pause()
- return
if exfiltration_channel is not None:
exfiltration_channel.pause_capture()
if live_interpretation_browser_session_id:
interpretation_registry.pause_capture(live_interpretation_browser_session_id)
case MessageKind.RECORDING_CAPTURE_RESUME:
- if recording_v2:
- if (v2_session := recording_session_v2()) is not None:
- v2_session.resume()
- return
if exfiltration_channel is not None:
exfiltration_channel.resume_capture()
if live_interpretation_browser_session_id:
interpretation_registry.resume_capture(live_interpretation_browser_session_id)
case MessageKind.RECORDING_REARM_CAPTURE:
- if recording_v2:
- return
if exfiltration_channel is not None:
try:
await exfiltration_channel.rearm_all_pages()
@@ -995,37 +870,6 @@ async def loop_stream_messages(message_channel: MessageChannel) -> None:
)
await send_error(message.kind, "Failed to re-arm recording capture.")
- case MessageKind.RECORDING_COMMIT:
- commit_session = recording_session_v2()
- if commit_session is None:
- await send_error(message.kind, "No recording to commit.")
- return
- try:
- if not commit_session.sealed:
- await commit_session.seal()
- overlay = overlay_from_draft_steps(message.draft_steps)
- result = render_code(commit_session, overlay) if message.mode != "blocks" else None
- if result is None:
- result = render_blocks(commit_session, overlay)
- except Exception:
- # The session stays in the registry so the client can retry the commit.
- LOG.exception(
- f"{class_name} failed to render the recording.",
- **message_channel.identity,
- )
- await send_error(message.kind, "Failed to render the recording.")
- return
-
- await send(
- MessageOutRecordingCommitted(
- blocks=result.blocks,
- parameters=result.parameters,
- mode=result.mode,
- diagnostics=result.diagnostics,
- )
- )
- discard_session_v2(commit_session.browser_session_id)
-
case MessageKind.GET_BROWSER_URL:
try:
async with execution_for_message_channel(message_channel) as execute:
@@ -1218,12 +1062,6 @@ async def loop_stream_messages(message_channel: MessageChannel) -> None:
if pending_clipboard_tasks:
await asyncio.gather(*pending_clipboard_tasks, return_exceptions=True)
LOG.debug(f"{class_name} Closing the message channel stream.", **message_channel.identity)
- # A live v2 recording survives a socket reconnect (begin-exfiltration restarts the
- # ticker); only a sealed one is dropped here.
- if (v2_session := recording_session_v2()) is not None:
- await v2_session.stop_ticker()
- if v2_session.sealed:
- discard_session_v2(v2_session.browser_session_id)
if exfiltration_channel is not None:
try:
await exfiltration_channel.stop()
diff --git a/skyvern/forge/sdk/routes/streaming/latency_probe.py b/skyvern/forge/sdk/routes/streaming/latency_probe.py
deleted file mode 100644
index 993217e62..000000000
--- a/skyvern/forge/sdk/routes/streaming/latency_probe.py
+++ /dev/null
@@ -1,47 +0,0 @@
-from opentelemetry import metrics
-
-_LATENCY_BUCKETS_SECONDS = [0.001, 0.002, 0.005, 0.01, 0.02, 0.03, 0.045, 0.06, 0.1, 0.25, 0.5, 1.0, 2.5, 5.0]
-MAX_SESSIONS = 1024
-_pending_inputs: dict[str, float] = {}
-# dict, not set: the cap must evict the oldest session, not an arbitrary one.
-_recording: dict[str, None] = {}
-
-_meter = metrics.get_meter("skyvern.live_view")
-input_to_frame_seconds = _meter.create_histogram(
- "skyvern.live_view.input_to_frame_seconds",
- unit="s",
- description="Input message received by the API -> next screencast frame received by the API",
- explicit_bucket_boundaries_advisory=_LATENCY_BUCKETS_SECONDS,
-)
-
-
-def note_input(browser_session_id: str, received_at: float) -> None:
- if browser_session_id not in _pending_inputs and len(_pending_inputs) >= MAX_SESSIONS:
- _pending_inputs.pop(next(iter(_pending_inputs)))
- _pending_inputs[browser_session_id] = received_at
-
-
-def note_frame(browser_session_id: str, received_at: float) -> None:
- input_received_at = _pending_inputs.pop(browser_session_id, None)
- if input_received_at is None:
- return
- input_to_frame_seconds.record(
- received_at - input_received_at,
- {"recording": "on" if browser_session_id in _recording else "off"},
- )
-
-
-def set_recording(browser_session_id: str, active: bool) -> None:
- if active:
- if browser_session_id not in _recording and len(_recording) >= MAX_SESSIONS:
- _recording.pop(next(iter(_recording)))
- _recording[browser_session_id] = None
- else:
- _recording.pop(browser_session_id, None)
-
-
-def forget(browser_session_id: str) -> None:
- """Every teardown path reaches here, so it also clears the recording gauge an abrupt
- disconnect would otherwise leave latched on."""
- _pending_inputs.pop(browser_session_id, None)
- _recording.pop(browser_session_id, None)
diff --git a/skyvern/forge/sdk/routes/streaming/screencast.py b/skyvern/forge/sdk/routes/streaming/screencast.py
index 1934a3c13..958a2b91e 100644
--- a/skyvern/forge/sdk/routes/streaming/screencast.py
+++ b/skyvern/forge/sdk/routes/streaming/screencast.py
@@ -15,7 +15,6 @@ from opentelemetry import metrics
from playwright.async_api import CDPSession
from skyvern.forge import app
-from skyvern.forge.sdk.routes.streaming import latency_probe
from skyvern.forge.sdk.routes.streaming.client_disconnect import watch_for_client_disconnect
from skyvern.webeye.browser_state import BrowserState
@@ -256,8 +255,6 @@ async def start_screencast_loop(
asyncio.create_task(_ack_frame(session, params.get("sessionId", 0)))
if session is not cdp_session:
return
- if entity_type == "browser_session":
- latency_probe.note_frame(entity_id, received_at)
metadata = params.get("metadata", {})
if metadata:
_update_viewport_from_metadata(metadata)
diff --git a/skyvern/forge/sdk/routes/workflow_copilot.py b/skyvern/forge/sdk/routes/workflow_copilot.py
index 9f4a1c0cb..02c7e7dc0 100644
--- a/skyvern/forge/sdk/routes/workflow_copilot.py
+++ b/skyvern/forge/sdk/routes/workflow_copilot.py
@@ -10,6 +10,7 @@ from dataclasses import dataclass
from datetime import datetime, timedelta, timezone
from pathlib import Path
from typing import Any, Iterator
+from urllib.parse import urlparse
import structlog
import yaml
@@ -115,6 +116,7 @@ from skyvern.schemas.workflows import (
from skyvern.utils.prompt_truncation import truncate_page_html_for_summary
from skyvern.utils.secret_headers import merge_masked_headers
from skyvern.utils.strings import escape_code_fences
+from skyvern.utils.url_validators import is_blocked_host
from skyvern.utils.yaml_loader import safe_load_no_dates
WORKFLOW_KNOWLEDGE_BASE_PATH = Path("skyvern/forge/prompts/skyvern/workflow_knowledge_base.txt")
@@ -1886,6 +1888,7 @@ async def _new_copilot_chat_post(
organization: Organization,
*,
eval_mode: CopilotEvalMode | None = None,
+ eval_entrypoint_url: str | None = None,
) -> EventSourceResponse:
"""ENABLE_WORKFLOW_COPILOT_V2 dispatch target.
@@ -2212,7 +2215,9 @@ async def _new_copilot_chat_post(
copilot_config = (
await app.AGENT_FUNCTION.get_copilot_config_for_request(
- organization.organization_id, code_block_mode=chat_request.code_block
+ organization.organization_id,
+ code_block_mode=chat_request.code_block,
+ composer_mode=chat_request.mode,
)
) or CopilotConfig()
@@ -2320,6 +2325,7 @@ async def _new_copilot_chat_post(
request.headers.get("x-copilot-eval-case") if settings.ENV == "local" else None
),
eval_mode=eval_mode,
+ eval_entrypoint_url=eval_entrypoint_url,
)
agent_result.turn_outcome = _with_current_copilot_code_mode_metadata(
@@ -2635,12 +2641,53 @@ async def workflow_copilot_chat_audio(
)
+def _validated_eval_entrypoint_url(
+ request: Request, chat_request: WorkflowCopilotChatRequest, organization: Organization
+) -> str | None:
+ """A silently dropped seed produces a benchmark run that looks seeded and never was, so every
+ rejected condition raises instead of falling back to the default resolution path."""
+ if chat_request.eval_entrypoint_url is None:
+ return None
+ eval_entrypoint_url = chat_request.eval_entrypoint_url
+ if (
+ not settings.WORKFLOW_COPILOT_ODYSSEYS_EVAL_INPUTS_ENABLED
+ or organization.organization_id not in settings.WORKFLOW_COPILOT_ODYSSEYS_EVAL_ORGANIZATION_IDS
+ or request.headers.get("x-copilot-eval") != "odysseys"
+ ):
+ raise HTTPException(
+ status_code=status.HTTP_400_BAD_REQUEST,
+ detail="eval_entrypoint_url is not accepted on this deployment",
+ )
+ try:
+ parsed = urlparse(eval_entrypoint_url)
+ accepted = (
+ parsed.scheme in {"http", "https"}
+ and bool(parsed.hostname)
+ and parsed.username is None
+ and not any(char.isspace() for char in eval_entrypoint_url)
+ and (parsed.port is None or 0 < parsed.port < 65536)
+ # Same host policy every other URL-accepting entry point applies, so a metadata or
+ # RFC1918 host is refused here rather than only at the navigation guard. A local
+ # fixture lane passes by listing its own host in ALLOWED_HOSTS, as it already must.
+ and not is_blocked_host(parsed.hostname or "")
+ )
+ except ValueError:
+ accepted = False
+ if not accepted:
+ raise HTTPException(
+ status_code=status.HTTP_400_BAD_REQUEST,
+ detail="eval_entrypoint_url must be an http(s) URL",
+ )
+ return eval_entrypoint_url
+
+
@base_router.post("/workflow/copilot/chat-post", include_in_schema=False)
async def workflow_copilot_chat_post(
request: Request,
chat_request: WorkflowCopilotChatRequest,
organization: Organization = Depends(org_auth_service.get_current_org),
) -> EventSourceResponse:
+ eval_entrypoint_url = _validated_eval_entrypoint_url(request, chat_request, organization)
raw_eval_mode = request.headers.get("x-copilot-eval-mode")
if raw_eval_mode is not None:
try:
@@ -2655,10 +2702,26 @@ async def workflow_copilot_chat_post(
or organization.organization_id not in settings.WORKFLOW_COPILOT_BROWSER_ABLATION_ORGANIZATION_IDS
):
raise HTTPException(status_code=status.HTTP_403_FORBIDDEN, detail="Copilot eval mode is disabled")
- return await _new_copilot_chat_post(request, chat_request, organization, eval_mode=eval_mode)
+ return await _new_copilot_chat_post(
+ request,
+ chat_request,
+ organization,
+ eval_mode=eval_mode,
+ eval_entrypoint_url=eval_entrypoint_url,
+ )
if await _should_use_copilot_v2(organization, chat_request.workflow_permanent_id, mode=chat_request.mode):
- return await _new_copilot_chat_post(request, chat_request, organization)
+ return await _new_copilot_chat_post(
+ request,
+ chat_request,
+ organization,
+ eval_entrypoint_url=eval_entrypoint_url,
+ )
+ if eval_entrypoint_url is not None:
+ raise HTTPException(
+ status_code=status.HTTP_400_BAD_REQUEST,
+ detail="eval_entrypoint_url requires the copilot v2 agent path",
+ )
async def stream_handler(stream: EventSourceStream) -> None:
turn_id = uuid.uuid4().hex
diff --git a/skyvern/forge/sdk/schemas/workflow_copilot.py b/skyvern/forge/sdk/schemas/workflow_copilot.py
index 332e88770..4484ff0aa 100644
--- a/skyvern/forge/sdk/schemas/workflow_copilot.py
+++ b/skyvern/forge/sdk/schemas/workflow_copilot.py
@@ -181,6 +181,13 @@ class WorkflowCopilotChatRequest(BaseModel):
"for that run."
),
)
+ eval_entrypoint_url: str | None = Field(
+ None,
+ description=(
+ "Benchmark-only starting URL. Rejected unless the eval setting and the X-Copilot-Eval header "
+ "are both present; never sent by the product."
+ ),
+ )
class WorkflowCopilotCancelRequest(BaseModel):
diff --git a/skyvern/forge/sdk/services/google_oauth_service.py b/skyvern/forge/sdk/services/google_oauth_service.py
index 12e760744..15d07d48a 100644
--- a/skyvern/forge/sdk/services/google_oauth_service.py
+++ b/skyvern/forge/sdk/services/google_oauth_service.py
@@ -27,7 +27,7 @@ from skyvern.config import settings
from skyvern.forge import app
from skyvern.forge.sdk.cache.base import AsyncLock, NoopLock
from skyvern.forge.sdk.db.enums import OrganizationAuthTokenType
-from skyvern.forge.sdk.db.id import generate_google_oauth_credential_id
+from skyvern.forge.sdk.db.id import GOOGLE_OAUTH_CREDENTIAL_PREFIX, generate_google_oauth_credential_id
# Lifecycle constants and InvalidConsentNonceError live on the repository (the DB owns
# them); re-export from this module so the cloud shim and existing call sites keep
@@ -897,6 +897,71 @@ async def get_visible_credentials_for_org(organization_id: str) -> list[GoogleOA
return await app.DATABASE.google_oauth.list_visible_for_org(organization_id=organization_id)
+def _matches_reference(credential: GoogleOAuthCredentialBase, normalized_reference: str) -> bool:
+ if not normalized_reference:
+ return False
+ return (
+ credential.credential_name.strip().casefold() == normalized_reference
+ or (credential.email_address or "").strip().casefold() == normalized_reference
+ )
+
+
+async def resolve_credential_reference(organization_id: str, reference: str) -> str:
+ """Map a caller-supplied Google connection reference onto a stored credential id.
+
+ The stored id appears nowhere outside the block editor's account dropdown, so a hand-written
+ or agent-written block reaches here carrying the connection name or the account email instead.
+ Accept all three. Unresolvable references come back unchanged; the caller reports not-found.
+ """
+ reference = reference.strip()
+ if not reference or reference.startswith(f"{GOOGLE_OAUTH_CREDENTIAL_PREFIX}_"):
+ return reference
+
+ credentials = await get_visible_credentials_for_org(organization_id)
+ normalized = reference.casefold()
+ matches = [credential for credential in credentials if _matches_reference(credential, normalized)]
+ active = [credential for credential in matches if credential.state == STATE_ACTIVE]
+ candidates = active or matches
+ if len({credential.id for credential in candidates}) != 1:
+ return reference
+ return candidates[0].id
+
+
+async def describe_credential_failure(organization_id: str, reference: str) -> str:
+ """Explain why ``reference`` produced no access token, in terms the workflow author can act on."""
+ reconnect = "Reconnect the Google account: no valid access token"
+ try:
+ credentials = await get_visible_credentials_for_org(organization_id)
+ except Exception:
+ LOG.warning("Failed to list Google connections while describing a credential failure", exc_info=True)
+ return reconnect
+
+ reference = reference.strip()
+ if any(credential.id == reference for credential in credentials):
+ return reconnect
+
+ normalized = reference.casefold()
+ matches = [credential for credential in credentials if _matches_reference(credential, normalized)]
+ if len(matches) == 1:
+ return reconnect
+ if len(matches) > 1:
+ return (
+ f"credential_id '{reference}' matches {len(matches)} connected Google accounts. "
+ "Rename them on the Integrations page, or pick the account in the block editor."
+ )
+ if not credentials:
+ return (
+ f"credential_id '{reference}' cannot be resolved: no Google account is connected to this "
+ "organization. Connect one on the Integrations page."
+ )
+ names = ", ".join(f"'{credential.credential_name}'" for credential in credentials)
+ return (
+ f"credential_id '{reference}' does not match any connected Google account. "
+ f"Connected accounts: {names}. Use one of those names, the account email, or pick the "
+ "account in the block editor."
+ )
+
+
async def update_email_address(
*,
organization_id: str,
diff --git a/skyvern/forge/sdk/workflow/models/block.py b/skyvern/forge/sdk/workflow/models/block.py
index bf14f2603..da8b7811c 100644
--- a/skyvern/forge/sdk/workflow/models/block.py
+++ b/skyvern/forge/sdk/workflow/models/block.py
@@ -99,10 +99,13 @@ from skyvern.forge.sdk.api import email
from skyvern.forge.sdk.api.aws import AsyncAWSClient
from skyvern.forge.sdk.api.files import (
calculate_sha256_for_file,
+ classify_download_visibility,
+ download_dir_path_for_run,
download_file,
get_download_dir,
get_path_for_workflow_download_directory,
is_remote_url,
+ observe_download_dir,
parse_uri_to_path,
resolve_local_or_download_file,
resolve_run_download_id,
@@ -194,6 +197,7 @@ from skyvern.forge.sdk.workflow.models._jinja import (
)
from skyvern.forge.sdk.workflow.models.code_block_recorder import (
CODE_BLOCK_FILENAME,
+ RECORDED_FAILURE_RESPONSE_MAX_CHARS,
RecordingPage,
json_safe_recorder_output,
user_code_line_from_exception,
@@ -243,6 +247,7 @@ from skyvern.schemas.workflows import (
from skyvern.services import otp_email, otp_service, planner_levers
from skyvern.services.error_detection_service import detect_user_defined_errors_for_task
from skyvern.services.self_heal_cap import check_and_increment_self_heal_cap
+from skyvern.utils.contained_effects import contained_effect
from skyvern.utils.prompt_engine import PROMPT_HARD_CEILING_TOKENS
from skyvern.utils.strings import generate_random_string
from skyvern.utils.templating import get_missing_variables
@@ -4027,7 +4032,7 @@ def _code_block_failure_action(*, failing_line: int | None, action_order: int, r
status=ActionStatus.failed,
action_order=action_order,
description=f"code error at line {failing_line}" if failing_line else "code error",
- response=response[:500],
+ response=response[:RECORDED_FAILURE_RESPONSE_MAX_CHARS],
output={"code_line": failing_line},
)
@@ -4425,8 +4430,12 @@ def _code_block_build_class(func: Any, name: str, /, *bases: Any, metaclass: Any
_DOWNLOAD_CLAIM_TIMEOUT_SECONDS = 60
_DOWNLOAD_CLAIM_SESSION_OBSERVE_SECONDS = 10
_DOWNLOAD_CLAIM_CLICK_TIMEOUT_SECONDS = 15
+_DOWNLOAD_CLAIM_EVIDENCE_TIMEOUT_SECONDS = 10
_DOWNLOAD_CLAIM_FALLBACK_STEM = "downloaded_file"
+DownloadEvidenceProbe = Callable[[], Awaitable[tuple[list[FileInfo] | None, set[str]]]]
+_DownloadIdentity = tuple[str | None, str | None]
+
def _download_monitor_owns_binding(page: Page | RecordingPage) -> bool:
"""True when the CDP download monitor, not the browser, is delivering this context's downloads.
@@ -4439,6 +4448,46 @@ def _download_monitor_owns_binding(page: Page | RecordingPage) -> bool:
return interceptor.is_monitoring_browser_downloads()
+async def _registered_download_identities(
+ download_evidence: DownloadEvidenceProbe | None,
+) -> dict[_DownloadIdentity, str] | None:
+ """Registered downloads keyed by an identity two reads agree on, or ``None`` when registration
+ could not be read — never proof that nothing arrived. The probe re-runs registration, so it is
+ bounded here rather than left to spend its own minutes-long budget on a failing claim."""
+ if download_evidence is None:
+ return None
+ try:
+ async with asyncio.timeout(_DOWNLOAD_CLAIM_EVIDENCE_TIMEOUT_SECONDS):
+ registered, _ = await download_evidence()
+ except Exception:
+ LOG.warning("Code block download claim could not read registration evidence", exc_info=True)
+ return None
+ if registered is None:
+ return None
+ return {(file_info.filename, file_info.checksum): file_info.filename or "" for file_info in registered}
+
+
+async def _newly_registered_download_name(
+ download_evidence: DownloadEvidenceProbe | None,
+ registered_before_click: dict[_DownloadIdentity, str] | None,
+) -> str | None:
+ """The name of a file this click registered, or ``None`` when no new registration can be proven.
+
+ A block that downloaded earlier already has registered files, so only a delta is evidence that
+ the click delivered anything."""
+ if registered_before_click is None:
+ return None
+ registered_after_click = await _registered_download_identities(download_evidence)
+ if registered_after_click is None:
+ return None
+ new_names = sorted(
+ name for identity, name in registered_after_click.items() if identity not in registered_before_click and name
+ )
+ if not new_names:
+ return None
+ return normalize_download_filename(new_names[0]) or _DOWNLOAD_CLAIM_FALLBACK_STEM
+
+
async def _code_block_click_and_claim_download_builtin(
page: Page | RecordingPage,
selector: str,
@@ -4446,6 +4495,7 @@ async def _code_block_click_and_claim_download_builtin(
organization_id: str | None = None,
workflow_run_id: str | None = None,
download_binding: DownloadBinding | None = None,
+ download_evidence: DownloadEvidenceProbe | None = None,
) -> str:
"""Click ``selector`` once and confirm the browser download it fires, returning the sanitized
suggested filename as a summary.
@@ -4463,6 +4513,13 @@ async def _code_block_click_and_claim_download_builtin(
if not resolved_selector:
raise CodeBlockDownloadClaimError("click_and_claim_download requires the selector of the affordance to click.")
click_error: BaseException | None = None
+ # Only a binding whose delivery this page cannot observe can reach the grace branch below, so
+ # the extra registration read is taken for those claims alone.
+ registered_before_click = (
+ await _registered_download_identities(download_evidence)
+ if download_binding is DownloadBinding.SESSION_DIR or _download_monitor_owns_binding(page)
+ else None
+ )
# A provider-owned session delivers the bytes on its own connection, so this page may never see
# the event at all (SKY-11371). Wait briefly for one rather than spending the full window on an
# event that is not this binding's proof of delivery.
@@ -4490,21 +4547,30 @@ async def _code_block_click_and_claim_download_builtin(
engaged=False,
binding=download_binding.value,
monitor_owns_binding=claim_monitor_owns_binding,
- clicked=click_error is None,
+ click_completed_without_error=click_error is None,
workflow_run_id=workflow_run_id,
organization_id=organization_id,
)
+ delivered_name = (
+ await _newly_registered_download_name(download_evidence, registered_before_click)
+ if download_binding is DownloadBinding.SESSION_DIR or claim_monitor_owns_binding
+ else None
+ )
if click_error is not None:
- # A selector that no longer matches is a page failure, not a download that failed to
- # fire. Re-raise Playwright's own error so the healing path still recognises its type.
- raise click_error
+ if delivered_name is None:
+ # A selector that no longer matches is a page failure, not a download that failed to
+ # fire. Re-raise Playwright's own error so the healing path still recognises its type.
+ raise click_error
+ # The click did not return, but this binding's writer registered a file it started, so
+ # failing here would fail a download that arrived.
+ return delivered_name
if download_binding is DownloadBinding.SESSION_DIR or claim_monitor_owns_binding:
# The click landed, and this binding's delivery belongs to the session watcher or to the
# monitor -- which denies browser-native downloads and fetches the bytes itself, so no
# Download event need ever reach this page. Failing here would fail a download that
# succeeded; the execution layer still reports an unregistered intent when nothing
# arrives.
- return _DOWNLOAD_CLAIM_FALLBACK_STEM
+ return delivered_name or _DOWNLOAD_CLAIM_FALLBACK_STEM
raise CodeBlockDownloadClaimError("Clicking the affordance did not fire a browser download.") from exc
monitor_owns_binding = _download_monitor_owns_binding(page)
@@ -4544,6 +4610,7 @@ def _bind_code_block_download_claim(
organization_id: str | None,
workflow_run_id: str | None,
download_binding: DownloadBinding | None,
+ download_evidence: DownloadEvidenceProbe | None = None,
) -> Callable[[Page | RecordingPage, str], Awaitable[str]]:
"""Two-argument closure rather than a `partial`: keyword
defaults on a `partial` would let block code override the run identity it is bound to."""
@@ -4555,6 +4622,7 @@ def _bind_code_block_download_claim(
organization_id=organization_id,
workflow_run_id=workflow_run_id,
download_binding=download_binding,
+ download_evidence=download_evidence,
)
return click_and_claim_download
@@ -4703,6 +4771,7 @@ class CodeBlock(Block):
workflow_run_block_id: str | None = None,
download_run_id: str | None = None,
download_binding: DownloadBinding | None = None,
+ download_evidence: DownloadEvidenceProbe | None = None,
) -> Callable[[], Awaitable[dict[str, Any]]]:
# SECURITY: validate before exec(). The AST check must run on the raw
# user code so it can block dunder identifiers like __capture_locals.
@@ -4746,6 +4815,7 @@ class CodeBlock(Block):
organization_id=organization_id,
workflow_run_id=workflow_run_id,
download_binding=download_binding,
+ download_evidence=download_evidence,
)
parameter_defaults: dict[str, Any] = {}
if parameters:
@@ -4998,7 +5068,87 @@ async def wrapper({default_args}):
exc_info=True,
)
+ def _bind_download_evidence_probe(
+ self,
+ *,
+ engine: str,
+ organization_id: str | None,
+ workflow_run_id: str,
+ workflow_run_block_id: str,
+ session_bound: bool,
+ resolved_download_id: str | None,
+ ) -> DownloadEvidenceProbe:
+ """The claim's read of what this run has registered, on the same authority the binding
+ verdict consults — the claim never scans a directory of its own."""
+
+ async def probe() -> tuple[list[FileInfo] | None, set[str]]:
+ return await self._register_downloaded_files(
+ engine=engine,
+ organization_id=organization_id,
+ workflow_run_id=workflow_run_id,
+ workflow_run_block_id=workflow_run_block_id,
+ session_bound=session_bound,
+ download_run_id=resolved_download_id,
+ )
+
+ return probe
+
async def _register_downloaded_files(
+ self,
+ *,
+ engine: str,
+ organization_id: str | None,
+ workflow_run_id: str,
+ workflow_run_block_id: str,
+ session_bound: bool = False,
+ download_run_id: str | None = None,
+ download_binding_kind: str | None = None,
+ ) -> tuple[list[FileInfo] | None, set[str]]:
+ """Register downloads, recording what the registered directory held on either side.
+
+ Bracketed here rather than in one engine's dispatch so the record is not engine-biased,
+ for the same reason the unregistered-intent signal is emitted from every engine.
+ """
+ listed_run_id = download_run_id or workflow_run_id
+ listed_dir = download_dir_path_for_run(listed_run_id)
+ alt_dir = download_dir_path_for_run(workflow_run_id) if listed_run_id != workflow_run_id else None
+ pre = observe_download_dir(listed_dir)
+ alt_pre = observe_download_dir(alt_dir) if alt_dir is not None else None
+ try:
+ return await self._register_downloaded_files_inner(
+ organization_id=organization_id,
+ workflow_run_id=workflow_run_id,
+ workflow_run_block_id=workflow_run_block_id,
+ session_bound=session_bound,
+ download_run_id=download_run_id,
+ )
+ finally:
+ with contained_effect(
+ "download registration visibility",
+ workflow_run_id=workflow_run_id,
+ workflow_run_block_id=workflow_run_block_id,
+ ):
+ LOG.info(
+ "codeblock.download_registration_visibility",
+ workflow_run_id=workflow_run_id,
+ workflow_run_block_id=workflow_run_block_id,
+ organization_id=organization_id,
+ engine=engine,
+ boundary="register",
+ session_bound=session_bound,
+ **classify_download_visibility(
+ pre=pre,
+ settled=None,
+ post=observe_download_dir(listed_dir),
+ alt_pre=alt_pre,
+ alt_post=observe_download_dir(alt_dir) if alt_dir is not None else None,
+ listed_run_id=listed_run_id,
+ workflow_run_id=workflow_run_id,
+ download_binding_kind=download_binding_kind,
+ ),
+ )
+
+ async def _register_downloaded_files_inner(
self,
*,
organization_id: str | None,
@@ -6061,6 +6211,7 @@ async def wrapper({default_args}):
resolved_download_id: str | None,
download_dir_before: set[tuple[str, int, int]] | None,
session_bound: bool,
+ download_binding_kind: str | None = None,
result: dict[str, Any] | list | str | None = None,
) -> dict[str, Any] | None:
"""Registration evidence for a block that failed after a download already landed.
@@ -6097,6 +6248,8 @@ async def wrapper({default_args}):
needs_registration = bool(new_names & before_names) or not new_names.issubset(registered_names)
if needs_registration:
downloaded_files, skipped_file_names = await self._register_downloaded_files(
+ engine=engine,
+ download_binding_kind=download_binding_kind,
organization_id=organization_id or workflow_run_context.organization_id,
workflow_run_id=workflow_run_id,
workflow_run_block_id=workflow_run_block_id,
@@ -6162,6 +6315,7 @@ async def wrapper({default_args}):
resolved_download_id=resolved_download_id,
download_dir_before=download_dir_before,
session_bound=session_download_lane_active(browser_state),
+ download_binding_kind=download_binding_of(browser_state).value,
result=output_parameter_value,
)
or output_parameter_value
@@ -6244,6 +6398,8 @@ async def wrapper({default_args}):
# directory (SKY-13694's completed-with-null arm).
try:
downloaded_files, skipped_file_names = await self._register_downloaded_files(
+ engine="inline",
+ download_binding_kind=download_binding_of(browser_state).value,
organization_id=organization_id or workflow_run_context.organization_id,
workflow_run_id=workflow_run_id,
workflow_run_block_id=workflow_run_block_id,
@@ -6304,6 +6460,7 @@ async def wrapper({default_args}):
resolved_download_id=resolved_download_id,
download_dir_before=download_dir_before,
session_bound=session_download_lane_active(browser_state),
+ download_binding_kind=download_binding_of(browser_state).value,
result=result.output_parameter_value,
)
if failure_output is not None:
@@ -6880,6 +7037,14 @@ async def wrapper({default_args}):
try:
await recorder.link_block()
+ download_evidence = self._bind_download_evidence_probe(
+ engine="secure_runner" if use_codeblock_runner else "inline",
+ organization_id=organization_id,
+ workflow_run_id=workflow_run_id,
+ workflow_run_block_id=workflow_run_block_id,
+ session_bound=session_download_lane_active(browser_state),
+ resolved_download_id=resolved_download_id,
+ )
if use_codeblock_runner:
secure_code_block_result = await app.AGENT_FUNCTION.execute_code_block_override(
block=self,
@@ -6893,6 +7058,7 @@ async def wrapper({default_args}):
recording_page=recording_page,
download_run_id=resolved_download_id,
download_binding=download_binding_of(browser_state),
+ download_evidence=download_evidence,
)
LOG.info(
"Secure CodeBlock override returned",
@@ -7046,6 +7212,8 @@ async def wrapper({default_args}):
or not secure_new_names.issubset(secure_registered_names)
):
host_files, secure_skipped_file_names = await self._register_downloaded_files(
+ engine="secure_runner",
+ download_binding_kind=download_binding_of(browser_state).value,
organization_id=organization_id or workflow_run_context.organization_id,
workflow_run_id=workflow_run_id,
workflow_run_block_id=workflow_run_block_id,
@@ -7105,6 +7273,16 @@ async def wrapper({default_args}):
workflow_run_block_id=workflow_run_block_id,
block_label=self.label,
)
+ # The downgraded block now runs inline, so a probe still labelled secure_runner
+ # would file this run's registrations under the engine that declined it.
+ download_evidence = self._bind_download_evidence_probe(
+ engine="inline",
+ organization_id=organization_id,
+ workflow_run_id=workflow_run_id,
+ workflow_run_block_id=workflow_run_block_id,
+ session_bound=session_download_lane_active(browser_state),
+ resolved_download_id=resolved_download_id,
+ )
user_function = self.generate_async_user_function(
self.code,
recording_page,
@@ -7114,6 +7292,7 @@ async def wrapper({default_args}):
workflow_run_block_id=workflow_run_block_id,
download_run_id=resolved_download_id,
download_binding=download_binding_of(browser_state),
+ download_evidence=download_evidence,
)
try:
result = await self.execute_user_function_with_timeout(
@@ -7219,6 +7398,7 @@ async def wrapper({default_args}):
resolved_download_id=resolved_download_id,
download_dir_before=download_dir_before,
session_bound=session_download_lane_active(browser_state),
+ download_binding_kind=download_binding_of(browser_state).value,
result=failure_output,
)
if download_aware_failure_output is None:
@@ -7292,7 +7472,7 @@ async def wrapper({default_args}):
recorded.append(
_code_block_failure_action(
action_order=len(recorded),
- response=(failure_reason or "")[:500],
+ response=failure_reason or "",
failing_line=failing_line,
)
)
@@ -7333,6 +7513,7 @@ async def wrapper({default_args}):
resolved_download_id=resolved_download_id,
download_dir_before=download_dir_before,
session_bound=session_download_lane_active(browser_state),
+ download_binding_kind=download_binding_of(browser_state).value,
),
status=BlockStatus.failed,
workflow_run_block_id=workflow_run_block_id,
@@ -7373,6 +7554,8 @@ async def wrapper({default_args}):
try:
downloaded_files, skipped_file_names = await self._register_downloaded_files(
+ engine="inline",
+ download_binding_kind=download_binding_of(browser_state).value,
organization_id=organization_id or workflow_run_context.organization_id,
workflow_run_id=workflow_run_id,
workflow_run_block_id=workflow_run_block_id,
diff --git a/skyvern/forge/sdk/workflow/models/code_block_recorder.py b/skyvern/forge/sdk/workflow/models/code_block_recorder.py
index 1b1f9b7b7..e0da28046 100644
--- a/skyvern/forge/sdk/workflow/models/code_block_recorder.py
+++ b/skyvern/forge/sdk/workflow/models/code_block_recorder.py
@@ -25,6 +25,9 @@ CODE_BLOCK_FILENAME = "<code_block>"
CODE_LINE_OFFSET = 2
MAX_RECORDED_ACTION_VALIDATION_ERROR_FIELDS = 20
PENDING_CALL_DELAY_SECONDS = 20.0
+# Every writer and the copilot projection share this, so a failure is bounded once. Wide enough
+# for the head of a Playwright call log that states whether the locator resolved and whether the
+# element was visible and stable — the lines that separate a tool failure from a bad locator.
RECORDED_FAILURE_RESPONSE_MAX_CHARS = 500
RECORDED_FAILURE_CAPTURE_MAX_CHARS = 8000
diff --git a/skyvern/forge/sdk/workflow/models/google_sheets_blocks.py b/skyvern/forge/sdk/workflow/models/google_sheets_blocks.py
index 420cc3683..be6ccc7d7 100644
--- a/skyvern/forge/sdk/workflow/models/google_sheets_blocks.py
+++ b/skyvern/forge/sdk/workflow/models/google_sheets_blocks.py
@@ -11,6 +11,7 @@ from jinja2 import UndefinedError
from skyvern.config import settings
from skyvern.forge import app
+from skyvern.forge.sdk.services import google_oauth_service
from skyvern.forge.sdk.workflow.context_manager import WorkflowRunContext
from skyvern.forge.sdk.workflow.exceptions import FailedToFormatJinjaStyleParameter
from skyvern.forge.sdk.workflow.models._jinja import (
@@ -120,6 +121,31 @@ def _disambiguate_header(header: list[str]) -> list[str]:
return disambiguated
+@dataclass(frozen=True)
+class GoogleSheetsAccess:
+ access_token: str | None
+ failure_reason: str | None
+
+
+async def _google_sheets_access(organization_id: str, credential_id: str) -> GoogleSheetsAccess:
+ """Mint an access token for a block's ``credential_id``, diagnosing failure before reporting it.
+
+ A reference naming no connection and a connection whose token cannot be minted are different
+ problems: reporting both as "reconnect" sends someone round the reconnect loop instead of at
+ the wrong identifier.
+ """
+ access_token = await app.AGENT_FUNCTION.get_google_sheets_credentials(
+ organization_id=organization_id,
+ credential_id=credential_id,
+ )
+ if access_token:
+ return GoogleSheetsAccess(access_token=access_token, failure_reason=None)
+ return GoogleSheetsAccess(
+ access_token=None,
+ failure_reason=await google_oauth_service.describe_credential_failure(organization_id, credential_id),
+ )
+
+
class GoogleSheetsReadBlock(Block):
block_type: Literal[BlockType.GOOGLE_SHEETS_READ] = BlockType.GOOGLE_SHEETS_READ # type: ignore
@@ -216,19 +242,17 @@ class GoogleSheetsReadBlock(Block):
workflow_run_block_id=workflow_run_block_id,
organization_id=organization_id,
)
- access_token = await app.AGENT_FUNCTION.get_google_sheets_credentials(
- organization_id=effective_org_id,
- credential_id=self.credential_id,
- )
- if not access_token:
+ access = await _google_sheets_access(effective_org_id, self.credential_id)
+ if not access.access_token:
return await self.build_block_result(
success=False,
- failure_reason="Reconnect the Google account: no valid access token",
+ failure_reason=access.failure_reason,
output_parameter_value=None,
status=BlockStatus.failed,
workflow_run_block_id=workflow_run_block_id,
organization_id=organization_id,
)
+ access_token = access.access_token
fields = (
"spreadsheetId,sheets("
@@ -724,19 +748,17 @@ class GoogleSheetsWriteBlock(Block):
workflow_run_block_id=workflow_run_block_id,
organization_id=organization_id,
)
- access_token = await app.AGENT_FUNCTION.get_google_sheets_credentials(
- organization_id=effective_org_id,
- credential_id=self.credential_id,
- )
- if not access_token:
+ access = await _google_sheets_access(effective_org_id, self.credential_id)
+ if not access.access_token:
return await self.build_block_result(
success=False,
- failure_reason="Reconnect the Google account: no valid access token",
+ failure_reason=access.failure_reason,
output_parameter_value=None,
status=BlockStatus.failed,
workflow_run_block_id=workflow_run_block_id,
organization_id=organization_id,
)
+ access_token = access.access_token
created_sheet_id: int | None = None
target_sheet_title = self.sheet_name or extract_a1_sheet_prefix(a1)
diff --git a/skyvern/forge/sdk/workflow/service.py b/skyvern/forge/sdk/workflow/service.py
index df97a6175..ae9ea7c73 100644
--- a/skyvern/forge/sdk/workflow/service.py
+++ b/skyvern/forge/sdk/workflow/service.py
@@ -54,7 +54,6 @@ from skyvern.exceptions import (
BrowserSessionClosed,
BrowserSessionNotFound,
BrowserSessionNotRenewable,
- BrowserSessionStartupTimeout,
DisabledBlockExecutionError,
DownloadSaveIncompleteError,
InProcessScriptExecutionDenied,
@@ -480,17 +479,6 @@ _WORKFLOW_RUN_ESCAPED_EXCEPTION_FAILURE_CATEGORY = [
}
]
-# Short lifespan for auto-provisioned CodeBlock sessions; the renewal loop extends it while the
-# run is active, so this only bounds how long a leaked session lingers if cleanup never runs.
-CODE_BLOCK_SESSION_TIMEOUT_MINUTES = 20
-# Wall clock, not an attempt count: a waiting run holds a whole worker pod
-# (max_concurrent_activities=1), so what has to stay bounded is the time pinned, whatever the
-# per-attempt startup deadline happens to be.
-CODE_BLOCK_SESSION_STARTUP_BUDGET_SECONDS = 90.0
-# Bounds the run-end close of an auto-provisioned CodeBlock session so a slow close cannot pin
-# the worker pod; on timeout the session timeout above still reaps the session.
-CODE_BLOCK_SESSION_CLOSE_TIMEOUT_SECONDS = 30.0
-
# Structured warning emitted when a debug-session run's visible PBS profile is
# incompatible with the LoginBlock credential's saved profile. Observability
# dashboards key on these strings — do not rename without updating monitors.
@@ -3803,123 +3791,6 @@ class WorkflowService:
)
return bool(profile and profile.is_managed)
- async def auto_create_browser_session_for_code_block_if_needed(
- self,
- organization_id: str,
- workflow: Workflow,
- *,
- workflow_run_id: str,
- browser_session_id: str | None = None,
- browser_profile_id: str | None = None,
- proxy_location: ProxyLocationInput = None,
- ) -> PersistentBrowserSession | None:
- """Auto-provision a persistent browser session for runs that contain a CodeBlock.
-
- The secure CodeBlock runner brokers page operations against a live persistent browser
- session, so a CodeBlock with no caller-supplied session would otherwise fall back to
- the legacy in-process executor. When the org is enabled for the secure runner, provision
- a session here so the CodeBlock routes to the runner. A run's browser_profile_id is loaded
- into the session so profile-backed CodeBlock workflows still reach the runner. Returns None
- (run continues on the legacy path) when no CodeBlock is present, the org is not enabled, or a
- session was already supplied. Session-creation failure propagates: an enrolled run must fail
- closed rather than silently downgrade its code to in-process execution.
- """
- if browser_session_id: # the caller supplied a session; respect it unchanged
- return None
-
- all_blocks = get_all_blocks(workflow.workflow_definition.blocks)
- if not any(block.block_type == BlockType.CODE for block in all_blocks):
- return None
-
- should_create = await app.AGENT_FUNCTION.should_auto_create_browser_session_for_code_block(
- workflow_run_id=workflow_run_id,
- organization_id=organization_id,
- workflow_permanent_id=workflow.workflow_permanent_id,
- workflow_id=workflow.workflow_id,
- )
- if not should_create:
- return None
-
- try:
- browser_session = await self._create_code_block_browser_session(
- organization_id=organization_id,
- browser_profile_id=browser_profile_id,
- proxy_location=proxy_location,
- workflow_run_id=workflow_run_id,
- )
- except Exception:
- LOG.error(
- "Failed to auto-create browser session for CodeBlock run; failing the run closed",
- workflow_run_id=workflow_run_id,
- organization_id=organization_id,
- workflow_permanent_id=workflow.workflow_permanent_id,
- exc_info=True,
- )
- raise
-
- LOG.info(
- "Auto-created browser session for CodeBlock run",
- workflow_run_id=workflow_run_id,
- organization_id=organization_id,
- workflow_permanent_id=workflow.workflow_permanent_id,
- browser_session_id=browser_session.persistent_browser_session_id,
- )
- return browser_session
-
- async def _create_code_block_browser_session(
- self,
- *,
- organization_id: str,
- browser_profile_id: str | None,
- proxy_location: ProxyLocationInput,
- workflow_run_id: str,
- ) -> PersistentBrowserSession:
- """Create the CodeBlock session, retrying only a startup timeout.
-
- A startup timeout means the session fleet had no free capacity inside the deadline,
- not that the request was invalid — the fleet scales on demand, so a fresh attempt
- often lands on pods that came up just after the previous deadline expired. Every
- other failure is deterministic, so retrying it only delays the run.
-
- Retrying is bounded by wall clock rather than by attempts because the waiting run
- occupies a whole worker pod, and it does so during exactly the capacity crunch that
- causes the timeout — so the cost to bound is time held, not requests made.
- """
- deadline = time.monotonic() + CODE_BLOCK_SESSION_STARTUP_BUDGET_SECONDS
- attempt = 0
- while True:
- attempt += 1
- try:
- return await app.PERSISTENT_SESSIONS_MANAGER.create_session(
- organization_id=organization_id,
- timeout_minutes=CODE_BLOCK_SESSION_TIMEOUT_MINUTES,
- browser_profile_id=browser_profile_id,
- proxy_location=proxy_location,
- inherit_profile_proxy=True,
- workflow_run_id=workflow_run_id,
- )
- except BrowserSessionStartupTimeout:
- if time.monotonic() >= deadline:
- raise
- # A cancel can land while we wait. Provisioning another billed session for a
- # run that already finished helps nobody and deepens the shortage.
- workflow_run = await self.get_workflow_run(workflow_run_id=workflow_run_id)
- if workflow_run.status.is_final():
- LOG.info(
- "Workflow run reached a final state while its CodeBlock session was starting; not retrying",
- workflow_run_id=workflow_run_id,
- organization_id=organization_id,
- workflow_status=workflow_run.status,
- )
- raise
- LOG.warning(
- "Browser session for CodeBlock run timed out starting; retrying",
- workflow_run_id=workflow_run_id,
- organization_id=organization_id,
- attempt=attempt,
- budget_seconds=CODE_BLOCK_SESSION_STARTUP_BUDGET_SECONDS,
- )
-
@staticmethod
async def _close_reused_session_best_effort(*, organization_id: str, session_id: str) -> None:
try:
@@ -5022,7 +4893,6 @@ class WorkflowService:
return workflow_run
browser_session = None
- code_block_browser_session_id: str | None = None
using_managed_browser_profile = await self._browser_profile_is_managed(
organization_id=organization.organization_id,
browser_profile_id=browser_profile_id,
@@ -5036,49 +4906,6 @@ class WorkflowService:
proxy_location=workflow_run.proxy_location,
)
- # The CodeBlock auto-PBS path is intentionally NOT gated on browser_profile_id: a
- # profile-backed CodeBlock workflow still needs a session for the secure runner, so the
- # profile is loaded into the auto-created session instead of skipping it.
- if browser_session is None and browser_session_id is None:
- # The helper raises only for a secure-runner-enrolled run whose session could not be
- # created; letting that run continue would silently execute its code in-process instead
- # of the sandbox, so fail closed like the sidecar-absent posture.
- try:
- browser_session = await self.auto_create_browser_session_for_code_block_if_needed(
- organization.organization_id,
- workflow,
- workflow_run_id=workflow_run_id,
- browser_session_id=browser_session_id,
- browser_profile_id=browser_profile_id,
- proxy_location=workflow_run.proxy_location,
- )
- except Exception as e:
- failure_reason = (
- "Failed to create the browser session required for secure code execution: "
- f"{get_user_facing_exception_message(e)}"
- )
- # Conditional: a cancel can land while the session is still starting, and an
- # unconditional write would overwrite that terminal status with ``failed``.
- workflow_run = (
- await self.mark_workflow_run_as_failed_if_not_final(
- workflow_run_id=workflow_run_id, failure_reason=failure_reason
- )
- or workflow_run
- )
- await self.clean_up_workflow(
- workflow=workflow,
- workflow_run=workflow_run,
- api_key=api_key,
- browser_session_id=browser_session_id,
- close_browser_on_completion=close_browser_on_completion,
- need_call_webhook=need_call_webhook,
- )
- return workflow_run
- # A session set here came from the CodeBlock helper — the one session this run owns
- # and must close at cleanup.
- if browser_session is not None:
- code_block_browser_session_id = browser_session.persistent_browser_session_id
-
if browser_session:
browser_session_id = browser_session.persistent_browser_session_id
close_browser_on_completion = True
@@ -5103,11 +4930,20 @@ class WorkflowService:
browser_session_id=browser_session_id,
)
except Exception as e:
- LOG.exception(
- "Failed to begin browser session for workflow run",
- browser_session_id=browser_session_id,
- workflow_run_id=workflow_run_id,
- )
+ # An expired session is the caller's to resolve, and the run record already carries
+ # the same message as failure_reason. Every other lease failure keeps its traceback.
+ if isinstance(e, BrowserSessionClosed):
+ LOG.warning(
+ "Browser session expired before the workflow run could lease it",
+ browser_session_id=browser_session_id,
+ workflow_run_id=workflow_run_id,
+ )
+ else:
+ LOG.exception(
+ "Failed to begin browser session for workflow run",
+ browser_session_id=browser_session_id,
+ workflow_run_id=workflow_run_id,
+ )
failure_reason = (
f"Failed to begin browser session for workflow run: {get_user_facing_exception_message(e)}"
)
@@ -5122,7 +4958,6 @@ class WorkflowService:
browser_session_id=browser_session_id,
close_browser_on_completion=close_browser_on_completion,
need_call_webhook=need_call_webhook,
- code_block_browser_session_id=code_block_browser_session_id,
)
return workflow_run
# Start background task to periodically renew the browser session
@@ -5620,7 +5455,6 @@ class WorkflowService:
browser_persistence_status=browser_persistence_status,
skip_browser_session_write_back=browser_write_back_exhausted,
schedule_credential_fallback_retry=not finally_block_set_terminal_outcome,
- code_block_browser_session_id=code_block_browser_session_id,
)
return workflow_run
@@ -11213,7 +11047,6 @@ class WorkflowService:
browser_persistence_status: WorkflowRunStatus | None = None,
skip_browser_session_write_back: bool = False,
schedule_credential_fallback_retry: bool = True,
- code_block_browser_session_id: str | None = None,
) -> None:
# Direct cleanup callers can enter with a terminal row. When browser cleanup is still
# pending, install the tombstone before the first awaited terminal hook. A pre-finalization
@@ -11336,42 +11169,6 @@ class WorkflowService:
if schedule_credential_fallback_retry:
self._schedule_credential_fallback_retry(workflow_run)
- # A session this run auto-created for its CodeBlock has no owner once the run ends;
- # caller-supplied sessions are deliberately left open. Positional args: the cloud
- # manager and the OSS protocol disagree on the second parameter's name.
- if code_block_browser_session_id:
- try:
- has_active_child_run = False
- if child_workflow_run_ids:
- child_runs = await app.DATABASE.workflow_runs.get_workflow_runs_by_parent_workflow_run_id(
- parent_workflow_run_id=workflow_run.workflow_run_id,
- organization_id=workflow_run.organization_id,
- )
- has_active_child_run = any(not child.status.is_final() for child in child_runs)
- if has_active_child_run:
- # A fire-and-forget child (use_parent_browser_session) may have inherited this
- # session; leave it to the session timeout instead of closing it mid-child-run.
- LOG.info(
- "Skipping CodeBlock browser session close while child workflow runs are active",
- workflow_run_id=workflow_run.workflow_run_id,
- browser_session_id=code_block_browser_session_id,
- )
- else:
- await asyncio.wait_for(
- app.PERSISTENT_SESSIONS_MANAGER.close_session(
- workflow_run.organization_id,
- code_block_browser_session_id,
- ),
- timeout=CODE_BLOCK_SESSION_CLOSE_TIMEOUT_SECONDS,
- )
- except Exception:
- LOG.warning(
- "Failed to close the auto-created CodeBlock browser session",
- workflow_run_id=workflow_run.workflow_run_id,
- browser_session_id=code_block_browser_session_id,
- exc_info=True,
- )
-
async def prepare_workflow_webhook(
self,
workflow_run: WorkflowRun,
diff --git a/skyvern/forge/taskv3/engine.py b/skyvern/forge/taskv3/engine.py
index bcaae2497..4090071fb 100644
--- a/skyvern/forge/taskv3/engine.py
+++ b/skyvern/forge/taskv3/engine.py
@@ -23,12 +23,15 @@ from __future__ import annotations
import json
import time
+from datetime import UTC, datetime
from typing import Any, Awaitable, Callable
import structlog
from skyvern.config import settings
+from skyvern.forge.sdk.api.llm.api_handler_factory import VISION_FALLBACK_PROMPT_NAMES
from skyvern.forge.sdk.api.llm.exceptions import LLMProviderErrorRetryableTask
+from skyvern.forge.sdk.core import skyvern_context
from skyvern.forge.taskv3.loop import (
DEFAULT_MAX_SETTLE_DEFERRALS,
ActivityRecency,
@@ -78,6 +81,7 @@ How to work:
- Batch aggressively: in ONE turn you can `type` into many fields AND `click` many radio/checkbox options AND `select_option` on several dropdowns. Answer a whole form section in a single turn — never spend a separate turn on each click.
- Autocomplete / typeahead / combobox fields (location, school, employer lookups) render suggestions only AFTER you type, and the raw text you type is NOT accepted until you pick a suggestion. Use the `select_combobox` tool (selector + value) for these — it types, waits for the suggestions to render, selects the best-matching one, and verifies the field committed. Do NOT `type` into them or press keys yourself. If `select_combobox` returns an error, the field is genuinely unfilled — try a fuller value or report it; never treat it as done.
- `observe` already gives you everything you need to fill a field (selector, label, type, current value, options, and the surrounding question text) — act on it directly. `get_html` is a rare last resort for ONE specific element `observe` failed to describe: NEVER call it on a whole page/form/section, NEVER call it twice for the same element, and NEVER inspect more than once before acting.
+- `look` is a separate last resort for when the TEXT tools are not enough: you can't tell what the page looks like, a control you expect isn't in `observe` (custom or shadow-DOM widgets), or an action isn't taking and you can't tell why. It returns ONE screenshot with every visible control boxed and numbered; then act on a number with `click(mark=N)` or `type(mark=N, text=...)`. Do NOT call `look` to double-check what `observe` already told you, and do not call it every turn — it is for when you are genuinely stuck on something visual.
- Inspecting the page does NOT progress the task — only `type`/`select_option`/`click` do. If your recent turns were mostly `observe`/`get_html` with little typing or clicking, you are stuck inspecting: stop, and fill every field you can from the latest `observe` snapshot using its selectors before doing anything else.
- Before calling finish with status=completed, re-check with `observe` that the goal's effect is present in the page's SETTLED, loaded content (no loading indicators or empty panels standing in for it), that every required field holds its intended value, and that the only remaining step is the final submit; fix anything missing first. Call `finish(status, reason, extracted_output)` when the goal is achieved (completed) or impossible/blocked (failed/terminated).
@@ -194,6 +198,7 @@ async def run_task_v3_agent_loop(
completion_blocker: CompletionBlocker | None = None,
staged_downloads: set[str] | None = None,
verification_blocker: VerificationBlocker | None = None,
+ initial_navigation_status: int | None = None,
) -> LoopOutcome:
"""Run one Task V3 task to completion against `page`, returning the loop outcome.
@@ -209,9 +214,34 @@ async def run_task_v3_agent_loop(
# (the same boundary credential placeholders already use) avoids that. Page-free runs have no
# tools to resolve a token with, so the payload stays verbatim for the model to judge directly.
refs = mask_opaque_urls(parameters) if not page_free else OpaqueUrlRefs(masked=parameters, refs={})
+ # The single model-facing masking boundary reads these off the task context (the chokepoint
+ # hide_from_model already runs on every tool result), so a resolved ref echoed by any tool —
+ # success or error — is rewritten to its token by membership, without each tool opting in. Set
+ # unconditionally (empty when this task minted none): the context is shared across every task block
+ # in a workflow run and blocks run sequentially, so this is the boundary's sole writer and a prior
+ # block's refs must not linger and mask this block's output to a token only that block's resolver —
+ # not this one's — can reverse. A production run always has a context (execute_step establishes it
+ # before _execute_task_v3); the None-guard only spares context-free test calls, which carry no real
+ # payload to leak. The same dict object, not a copy: a ref derived mid-task (a navigate redirect)
+ # must reach the boundary.
+ ctx = skyvern_context.current()
+ if ctx is not None:
+ ctx.opaque_url_refs = refs.refs
if refs.refs:
resolve_typed_text = refs.chain(resolve_typed_text)
+ # Offer `look` only when this run's model AND this run's screenshot policy will actually deliver
+ # the image — `_llm_screenshots_for_call` drops it both for a non-vision model and, for the
+ # non-vision-fallback `taskv3-agent-loop` prompt, whenever the run is in the enriched_tree_no_images
+ # cohort (an org is pinned there at 100% today). Otherwise `look` would advertise an image the model
+ # never sees.
+ _ctx = skyvern_context.current()
+ vision_enabled = llm_caller.llm_config.supports_vision and (
+ _ctx is None
+ or _ctx.llm_screenshots_enabled_for_prompt(
+ is_vision_fallback_prompt=prompt_name in VISION_FALLBACK_PROMPT_NAMES
+ )
+ )
# Page-free mode is structural, not advisory: no browser tools exist to call and the system
# prompt never mentions perception, so a data-only validation cannot read the live DOM.
browser_tools = (
@@ -223,6 +253,7 @@ async def run_task_v3_agent_loop(
organization_id=organization_id,
resolve_typed_text=resolve_typed_text,
opaque_refs=refs,
+ vision_enabled=vision_enabled,
)
)
@@ -260,6 +291,9 @@ async def run_task_v3_agent_loop(
elif completion_blocker is not None and completion_probe is None:
extra_system_guidance = extra_system_guidance + DOWNLOAD_REQUIRED_GUIDANCE
system_prompt = base_system_prompt + extra_system_guidance
+ system_prompt += datetime.now(ctx.tz_info if ctx and ctx.tz_info else UTC).strftime(
+ "\n\nToday's date is %Y-%m-%d (%A), %Z."
+ )
if refs.refs:
system_prompt += OPAQUE_URL_GUIDANCE
outcome = await run_agent_tool_loop(
@@ -284,6 +318,7 @@ async def run_task_v3_agent_loop(
submit_watch=None if page_free else submit_watch,
completion_probe=completion_probe,
staged_downloads=staged_downloads,
+ initial_navigation_status=initial_navigation_status,
)
if refs.refs:
outcome.reason = refs.resolve(outcome.reason)
diff --git a/skyvern/forge/taskv3/loop.py b/skyvern/forge/taskv3/loop.py
index 907d35031..f5803303b 100644
--- a/skyvern/forge/taskv3/loop.py
+++ b/skyvern/forge/taskv3/loop.py
@@ -40,10 +40,14 @@ class ToolResult:
status: ToolStatus
content: str
data: dict[str, Any] | None = None
+ # Transient images the loop must show the model on the NEXT call only (the on-demand `look`
+ # tool's annotated screenshot). Threaded into one .call()'s ephemeral screenshots= arg and never
+ # appended to the transcript, so it costs one image on one turn and is gone the turn after.
+ screenshots: list[bytes] | None = None
@classmethod
- def ok(cls, content: str, data: dict[str, Any] | None = None) -> ToolResult:
- return cls("ok", content, data)
+ def ok(cls, content: str, data: dict[str, Any] | None = None, screenshots: list[bytes] | None = None) -> ToolResult:
+ return cls("ok", content, data, screenshots)
@classmethod
def error(cls, content: str, data: dict[str, Any] | None = None) -> ToolResult:
@@ -188,6 +192,19 @@ ACTION_LOOP_TERMINATE_AFTER = 6
# Facetable sibling of PERCEPTION_STALL_REASON_PREFIX; same dashboard contract.
ACTION_LOOP_REASON_PREFIX = "action_loop:"
+# Hard "the resource does not exist / is gone" HTTP statuses. A navigation landing on one of these is
+# a genuine non-capability dead-end (a dead or removed posting), which v1 routes to `terminated`. Both
+# the in-loop `navigate` tool and the pre-loop initial-URL navigation classify against this set. NARROW
+# on purpose: auth (401/403), rate-limit (429) and transient server errors (5xx) are recoverable or
+# capability failures, not dead-ends, and are left to the model / stay `failed`.
+NAVIGATION_DEAD_END_STATUSES = frozenset({404, 410})
+
+# A navigation landed on a hard dead-end (HTTP 404/410): the target posting does not exist or was
+# removed, so the goal cannot be completed there. Ends the run as `terminated`, matching v1's terminate
+# verdict for the same condition. Covers both the in-loop `navigate` tool and the pre-loop initial-URL
+# navigation. Facetable sibling of the prefixes above.
+NAV_DEAD_END_REASON_PREFIX = "navigation_dead_end:"
+
# Emitted, never acted on, when the oscillation rule WOULD have terminated. The step engine's
# tripwires (skyvern/forge/sdk/fail_fast/shadow.py) earn the right to act by publishing this event
# first and deriving a decision precision from it; a rule that ADDS terminations gets the same
@@ -558,6 +575,8 @@ def _unblocker_options(available_tools: set[str]) -> list[str]:
options.append("if the page may be waiting on a verification widget, call solve_captcha")
if "get_html" in available_tools:
options.append("take ONE targeted get_html look at the region that should be changing")
+ if "look" in available_tools:
+ options.append("if you can't tell what's on the page or why an action isn't taking, call look to see it")
options.append("if the goal is already met, call finish(status=completed)")
options.append("if genuinely blocked, call finish(status=terminated) naming the blocker as the reason")
return options
@@ -932,6 +951,7 @@ async def run_agent_tool_loop(
telemetry_salt: str | None = None,
completion_probe: CompletionProbe | None = None,
staged_downloads: set[str] | None = None,
+ initial_navigation_status: int | None = None,
) -> LoopOutcome:
tool_by_name = {tool.name: tool for tool in tools}
# Per run, never logged: the hashes it keys are stable within this run (the only scope any guard
@@ -991,8 +1011,30 @@ async def run_agent_tool_loop(
total_tokens = 0
billable_actions: list[str] = []
action_steps = 0
+ # Images produced by an on-demand `look` this turn, to show the model on the NEXT call only. Passed
+ # as the transient screenshots= arg once, then cleared, so a look costs one image on one turn and
+ # never enters `messages` (the transcript re-seeds message_history each turn, so it's structurally
+ # gone the turn after).
+ pending_screenshots: list[bytes] = []
started_at = time.monotonic()
+ # The task's starting URL is navigated during browser setup, before this loop runs, so a dead/removed
+ # starting posting never routes through the in-loop `navigate` tool — the model just observes the dead
+ # page and finishes (defaulting to failed). Classify that pre-loop navigation here so the dominant
+ # dead-posting case ends `terminated`, matching v1, without waiting on the model's finish discretion.
+ # Cancellation is checked first, exactly as the first loop turn would: a run canceled during setup must
+ # persist as `canceled` (and stay unbilled), not be pre-empted into `terminated` by this fast path.
+ if outcome is None and initial_navigation_status in NAVIGATION_DEAD_END_STATUSES:
+ if should_cancel is not None and await should_cancel():
+ outcome = LoopOutcome("canceled", "run canceled")
+ else:
+ LOG.info("taskv3 loop initial navigation dead end", http_status=initial_navigation_status)
+ outcome = LoopOutcome(
+ "terminated",
+ f"{NAV_DEAD_END_REASON_PREFIX} the task's starting URL returned HTTP {initial_navigation_status} "
+ "— the target no longer exists or has been removed, so the goal cannot be completed there",
+ )
+
while outcome is None:
if should_cancel is not None and await should_cancel():
outcome = LoopOutcome("canceled", "run canceled")
@@ -1019,6 +1061,10 @@ async def run_agent_tool_loop(
# run can't balloon the context to the token backstop (the pre-compaction runaway mode).
_compact_transcript(messages, snapshot_indices)
llm_caller.message_history = list(messages)
+ # Consume any pending look image into THIS call only, then clear: the image rides one request
+ # and is never appended to `messages`, so the turn after carries zero image blocks.
+ screenshots_for_call = pending_screenshots or None
+ pending_screenshots = []
# Retry only the LLM call on transient provider errors. No browser tool has run this
# turn, so re-issuing the same call is side-effect-free — unlike a whole-task retry,
# which would re-execute prior clicks/types. This restores the step engine's transient
@@ -1034,6 +1080,7 @@ async def run_agent_tool_loop(
tools=openai_tools,
use_message_history=True,
raw_response=True,
+ screenshots=screenshots_for_call,
**active_call_kwargs,
)
break
@@ -1095,6 +1142,10 @@ async def run_agent_tool_loop(
stall_nudges_due: list[tuple[str, int]] = []
action_nudges_due: list[tuple[str, dict[str, Any], int]] = []
round_actions: list[tuple[str, dict[str, Any], bool]] = []
+ # A hard 404/410 from an in-loop navigate, applied only AFTER the batch so a same-turn fallback
+ # navigate can clear it — the model is told to batch aggressively, and terminating on the first
+ # of a batched [navigate(dead), navigate(live)] would discard the recovery it planned.
+ pending_nav_dead_end: int | None = None
for idx, (tool_call_id, tool_name, args) in enumerate(tool_calls):
# Enforce the cap per tool call so one batched turn cannot overrun it, and honor a
# cancellation that arrives mid-batch before the next click/type/submit runs. Neither
@@ -1192,6 +1243,12 @@ async def run_agent_tool_loop(
messages.append(
{"role": "tool", "tool_call_id": tool_call_id, "name": tool_name, "content": model_facing_content}
)
+ # A look's annotated screenshot is shown to the model on the next call only, never stored in
+ # the transcript. Consumed and cleared at the top of the next turn. Only the LATEST snapshot
+ # survives: a second look in the same turn supersedes the first (its marks replace the prior
+ # ones), so re-sending the stale image would just hand the model a dead numbering.
+ if result.screenshots:
+ pending_screenshots = list(result.screenshots)
result_data = result.data or {}
if progress is not None and observe_summary:
invalid_fields = observe_summary.get("invalid_fields")
@@ -1361,6 +1418,16 @@ async def run_agent_tool_loop(
_append_skipped_tool_results(messages, tool_calls[idx + 1 :], "completion probe fired")
break
+ dead_end_status = result_data.get("navigation_dead_end")
+ if dead_end_status is not None:
+ # A hard 404/410 landing is a non-capability dead-end (a dead/removed posting). Remember
+ # it but do NOT break the batch: a later navigate in the same turn can land the run on a
+ # live page and clear it below. Applied once the batch settles (after this for-loop).
+ pending_nav_dead_end = dead_end_status
+ elif result_data.get("page_state_changed"):
+ # A successful navigate moved the run off any dead page seen earlier this batch.
+ pending_nav_dead_end = None
+
if spec is not None and spec.terminal and result.status == "ok":
data = result.data or {}
outcome = LoopOutcome(
@@ -1377,6 +1444,17 @@ async def run_agent_tool_loop(
_append_skipped_tool_results(messages, tool_calls[idx + 1 :], "earlier tool call in this batch failed")
break
+ # The batch settled on a dead page (an in-loop navigate hit a hard 404/410 and no later navigate
+ # recovered): end the run as terminated deterministically, matching v1, rather than leaving the
+ # failed/terminated choice to the model's finish tool (which does not converge on this class).
+ if outcome is None and pending_nav_dead_end is not None:
+ LOG.info("taskv3 loop navigation dead end", http_status=pending_nav_dead_end, turn=turns)
+ outcome = LoopOutcome(
+ "terminated",
+ f"{NAV_DEAD_END_REASON_PREFIX} navigate landed on a dead page (HTTP {pending_nav_dead_end}) — "
+ "the target no longer exists or has been removed, so the goal cannot be completed there",
+ )
+
# Warn only after the batch completes: a user message may not sit between an assistant
# turn's tool results, and the model reads it with the snapshot that tripped it.
if outcome is None and stall_nudges_due:
diff --git a/skyvern/forge/taskv3/opaque_refs.py b/skyvern/forge/taskv3/opaque_refs.py
index 12bdeef68..7426bb8c9 100644
--- a/skyvern/forge/taskv3/opaque_refs.py
+++ b/skyvern/forge/taskv3/opaque_refs.py
@@ -6,7 +6,6 @@ Never import this from tools.py, loop.py, or auth_tools.py: it imports auth_tool
from __future__ import annotations
import hashlib
-import html
import re
from dataclasses import dataclass
from typing import Any, Callable
@@ -14,6 +13,7 @@ from urllib.parse import unquote, unquote_plus, urlsplit
import structlog
+from skyvern.forge.sdk.core.skyvern_context import mask_opaque_urls_in_text
from skyvern.forge.taskv3.auth_tools import _MIN_REDACTED_QUERY_VALUE_CHARS, _OPAQUE_QUERY_VALUE_RE
LOG = structlog.get_logger()
@@ -205,23 +205,24 @@ class OpaqueUrlRefs:
resolved = resolved.replace(token, url)
return resolved
+ def derive(self, url: str) -> str:
+ """Give ``url`` the provenance of a payload ref — a redirect target reached through one — so the
+ boundary masks it and a later tool call can resolve it. Returns its token."""
+ token = _token_for(url)
+ self.refs[token] = url
+ return token
+
def mask(self, text: str) -> str:
"""Replace every occurrence of a known payload signed-URL in ``text`` with its opaque token —
the inverse of resolve(). Masking is by PROVENANCE, not URL shape: only a URL we minted from
the payload is rewritten, so a live-page URL the model must reason about is never touched, even
when it is itself signing-shaped (a ``?gclid=``/``?token=`` landing page). Output-only surfaces
- never resolve the token back; the token is the same one the payload masker minted for that URL."""
- masked = text
- # Longest URL first so a payload URL that is a prefix of another is not partially rewritten.
- for token, url in sorted(self.refs.items(), key=lambda item: len(item[1]), reverse=True):
- # A URL rendered inside HTML (get_html) has its query separators entity-encoded (& -> &amp;),
- # so a multi-parameter presigned URL — the dominant signed-payload shape — never matches its
- # raw form there; match the escaped form too. Plain-text surfaces only carry the raw form,
- # where html.escape is a no-op, so the extra variant is harmless (dedup collapses it).
- for variant in dict.fromkeys((url, html.escape(url, quote=False))):
- if variant in masked:
- masked = masked.replace(variant, token)
- return masked
+ never resolve the token back; the token is the same one the payload masker minted for that URL.
+
+ Shares one implementation with the model-facing boundary (SkyvernContext.hide_from_model), so
+ the pre-truncation surfaces (observe/get_html) and the universal tool-result boundary can never
+ diverge."""
+ return mask_opaque_urls_in_text(text, self.refs)
def resolve_deep(self, value: Any) -> Any:
if isinstance(value, str):
diff --git a/skyvern/forge/taskv3/tools.py b/skyvern/forge/taskv3/tools.py
index 681cfa376..3beed2a6d 100644
--- a/skyvern/forge/taskv3/tools.py
+++ b/skyvern/forge/taskv3/tools.py
@@ -13,16 +13,21 @@ alongside `make_finish_tool()`.
from __future__ import annotations
import asyncio
+import io
import json
import os
import random
import re
+from enum import Enum
from typing import TYPE_CHECKING, Any, Awaitable, Callable
import structlog
+from PIL import Image, ImageDraw
from skyvern.constants import BROWSER_DOWNLOADING_SUFFIX
-from skyvern.forge.taskv3.loop import ToolResult, ToolSpec
+from skyvern.core.script_generations.fuzzy_matcher import match_option_exact_or_stem
+from skyvern.forge.sdk.core.skyvern_context import URL_IN_TEXT, canonical_url, opaque_url_echo_window
+from skyvern.forge.taskv3.loop import NAVIGATION_DEAD_END_STATUSES, ToolHandler, ToolResult, ToolSpec
from skyvern.forge.taskv3.preflight import PREFLIGHT_TOOL_NAMES, preflight_tool_action
if TYPE_CHECKING:
@@ -43,9 +48,24 @@ PAGE_UNAVAILABLE_ERROR = "browser page unavailable"
OBSERVE_URL_MAX_CHARS = 300
# The exact selector shapes our own enrichment mints: data-tv3 by observe(), data-tv3-menu by the
-# click menu probe. Either exists only where we set it, so one that matches nothing now cannot
-# reappear without a fresh observe / menu-opening click.
-_TV3_MARKER_SELECTOR_RE = re.compile(r'^\[data-tv3(?:-menu)?="[^"\\]+"\]$')
+# click menu probe, data-tv3-act by act-by-mark (written transiently on the look-resolved element
+# just before the action and cleared after). Each exists only where we set it, so one that matches
+# nothing now cannot reappear without a fresh observe / menu-opening click / look.
+_TV3_MARKER_SELECTOR_RE = re.compile(r'^\[data-tv3(?:-menu|-act)?="[^"\\]+"\]$')
+# An opaque identifier (a uuid, or a run of 12+ hex digits) does not survive a model's copy: one
+# transposed pair sends every later call to a selector that matches nothing. observe hands such a
+# selector out under a short alias instead, resolved back before any handler sees it.
+_OPAQUE_ID_RUN_RE = re.compile(
+ r"[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}|(?=[0-9a-f]*[a-f])[0-9a-f]{12,}", re.I
+)
+# Lenient on purpose: the model may tag-qualify or unquote the handle; the number is what names it.
+_ALIAS_SELECTOR_RE = re.compile(r'^\s*[a-z]*\[data-tv3-ref=["\']?(\d+)["\']?\]\s*$', re.I)
+# Every identity attribute an emitted selector names (id, name, data-testid — the attributes
+# observe's naturalSelector minds), wherever it sits in the compound: each one is masked out of
+# results and markup, so the value that triggered the alias never reaches the transcript.
+_SELECTOR_ID_COMPONENTS_RE = re.compile(
+ r'\[(id|name|data-testid)="((?:[^"\\]|\\.)*)"\]|(#)([^\s#.>+~\[\]()=,:*|^$\'"\\]+)'
+)
# Whitespace outside a quoted attribute value is a combinator: only hostAnchored composes selectors
# that way, while a natural `[name="first name"]` keeps its single round trip.
_TV3_QUOTED_VALUE_RE = re.compile(r'"(?:[^"\\]|\\.)*"')
@@ -58,6 +78,162 @@ def _is_host_anchored_selector(selector: str) -> bool:
return bool(_TV3_ANCHORED_SELECTOR_RE.match(_TV3_QUOTED_VALUE_RE.sub('""', selector.strip())))
+# A plain bare `#<id>`: no combinator/pseudo/attribute part, and no char that would need escaping
+# inside `[id="<id>"]` (quotes, backslash, and whitespace are excluded, so the rewrite is always safe).
+_BARE_ID_SELECTOR_RE = re.compile(r"""^#([^\s#.>+~\[\]()=,:*|^$'"\\]+)$""")
+
+
+def _bare_id_is_invalid_css(ident: str) -> bool:
+ # Invalid as a bare `#id` when the first char can't start a CSS identifier: a digit, a hyphen
+ # followed by a digit, or a lone hyphen. `--`-leading is valid and is deliberately not flagged.
+ if not ident:
+ return True
+ if ident[0].isdigit():
+ return True
+ return ident[0] == "-" and (len(ident) == 1 or ident[1].isdigit())
+
+
+def _normalize_selector(selector: str) -> str:
+ """Rewrite a bare `#<id>` that is invalid as written (digit/UUID/hyphen-digit leading, common on ATS
+ forms) into the equivalent `[id="<id>"]`. `#id` ≡ `[id="id"]` for every id, and a bare id that already
+ parses is returned untouched, so a valid selector's target is never altered."""
+ match = _BARE_ID_SELECTOR_RE.match(selector.strip())
+ if match is None or not _bare_id_is_invalid_css(match.group(1)):
+ return selector
+ return f'[id="{match.group(1)}"]'
+
+
+# patchright/playwright report an invalid CSS selector with one of these message markers; matching the
+# message (not the exception type) survives the patchright/playwright fork boundary. Version-coupled
+# strings: a unit test RED-proofs the exact wording so a library upgrade that reworded them fails loudly.
+_INVALID_SELECTOR_MARKERS = ("is not a valid selector", "while parsing selector", "while parsing css selector")
+
+
+def _invalid_selector_result(selector: Any, exc: Exception) -> ToolResult | None:
+ """An actionable error when `exc` is an invalid-CSS-selector parse failure; otherwise None so the
+ caller re-raises (timeouts, teardown, and unrelated failures must not be swallowed)."""
+ if not any(marker in str(exc) for marker in _INVALID_SELECTOR_MARKERS):
+ return None
+ return ToolResult.error(
+ f"{selector!r} is not a valid CSS selector. Use a selector from the latest observe(), or an "
+ '[id="..."] / [name="..."] attribute form (ids that start with a digit are not valid as a bare #id).'
+ )
+
+
+# Every tool that acts on a model-supplied CSS selector. file_upload's naked query_selector was the one
+# that crashed on an invalid selector; the guard is shared so all of these inherit the same behavior.
+_SELECTOR_GUARD_TOOL_NAMES = frozenset(
+ {
+ "get_html",
+ "click",
+ "hover",
+ "type",
+ "select_option",
+ "select_combobox",
+ "press_key",
+ "scroll",
+ "wait",
+ "file_upload",
+ }
+)
+
+
+def _with_selector_guard(handler: ToolHandler) -> ToolHandler:
+ """Shared seam for selector tools: normalize a bare invalid `#id` before the handler resolves it, and
+ convert a residual invalid-selector crash into an actionable error instead of a batch-aborting raise."""
+
+ async def wrapped(args: dict[str, Any]) -> ToolResult:
+ selector = args.get("selector")
+ if isinstance(selector, str):
+ args = {**args, "selector": _normalize_selector(selector)}
+ try:
+ return await handler(args)
+ except Exception as exc:
+ guarded = _invalid_selector_result(args.get("selector"), exc)
+ if guarded is not None:
+ return guarded
+ raise
+
+ return wrapped
+
+
+# The observable-state vocabulary a readback compares — the same fields observe reports per element.
+# None means "not read"; the classifier treats absence as no-committable-state, never as a value.
+_COMMIT_STATE_KEYS = ("value", "checked", "selected", "pressed")
+
+
+class CommitStatus(str, Enum):
+ OK = "ok" # state moved in the committing direction, read off exactly one element
+ DID_NOT_COMMIT = "did_not_commit" # target readable, and it did NOT commit
+ UNVERIFIED = "unverified" # no readable committable state, or committed but re-resolved to n != 1
+
+
+def _has_committable_state(state: dict[str, Any] | None) -> bool:
+ return isinstance(state, dict) and any(state.get(k) is not None for k in _COMMIT_STATE_KEYS)
+
+
+def _classify_commit(
+ pre: dict[str, Any] | None, post_matches: int, post: dict[str, Any] | None, *, committed_value: bool | None = None
+) -> CommitStatus:
+ """Classify a value-must-change action from a before/after observable-state readback.
+
+ Ranked fail-closed: a readable did-not-commit is reported whatever the target re-resolved to, because
+ only an error halts a batched turn (INV-1 guards the confident ok, not the refusal). A commit read off
+ a target that re-resolved to n != 1 is `unverified` (INV-1); no readable committable state is
+ `unverified` (INV-2). `committed_value` hands in a caller's own value-dimension truth in place of the
+ generic any-field-changed rule.
+ """
+ if post is None or not _has_committable_state(post):
+ return CommitStatus.UNVERIFIED
+ if committed_value is None:
+ if pre is None or not _has_committable_state(pre):
+ return CommitStatus.UNVERIFIED
+ committed_value = any(pre.get(k) != post.get(k) for k in _COMMIT_STATE_KEYS)
+ if not committed_value:
+ return CommitStatus.DID_NOT_COMMIT
+ return CommitStatus.OK if post_matches == 1 else CommitStatus.UNVERIFIED
+
+
+def _match_menu_option(value: str, options: list[dict[str, Any]]) -> int | None:
+ """Pick the enumerated menu row (its data-tv3-menu index) whose label matches the wanted value.
+
+ Deterministic and site-agnostic, precision-first. Exact/singular-plural-stem matching (apostrophe
+ folding, unique-or-None) is delegated to the shared `match_option_exact_or_stem` so this is not a
+ third copy of that logic. Failing that, a UNIQUE FORWARD token-prefix — the observed value is a whole-
+ token prefix of a fuller option label ("Decline" → "Decline to self-identify") — is accepted. The
+ REVERSE direction is deliberately NOT matched: committing a shorter, more-general option for a longer
+ value ("New York" → "New") is a silent wrong success, and on a virtualised window the fuller row may
+ simply be unrendered. A value that is only an incidental SUBSTRING of an option is never matched ("No"
+ inside "Prefer not to answer"). Ambiguity or no match returns None so the caller hands the options
+ back to the model. Uniqueness is only meaningful over the COMPLETE list — the caller must not pass a
+ truncated slice.
+ """
+ rows = [(o.get("n"), str(o.get("text") or "")) for o in options if isinstance(o.get("n"), int)]
+ if not value or not rows:
+ return None
+
+ # Collapse runs of whitespace before the exact/stem tier — the shared normalizer folds case and
+ # apostrophes but not internal spacing.
+ def _collapse(s: str) -> str:
+ return " ".join(s.split())
+
+ hit = match_option_exact_or_stem(_collapse(value), [_collapse(label) for _, label in rows])
+ if hit is not None:
+ return rows[hit][0]
+
+ def toks(s: str) -> list[str]:
+ # Fold commas and apostrophes so a short value token-prefix-matches a punctuated label ("Yes" →
+ # "Yes, I consent"). A slash is left intact so a combined "Yes/No" option is not prefix-matched by
+ # "Yes".
+ return re.sub(r"[,'’]", " ", s).lower().split()
+
+ want = toks(value)
+ if not want:
+ return None
+ prefixed = [n for n, label in rows if (t := toks(label)) and len(want) < len(t) and t[: len(want)] == want]
+ return prefixed[0] if len(prefixed) == 1 else None
+
+
# ARIA combobox signals — used by observe() only to add a hint that a field is a typeahead. This is a
# nudge for the model, not load-bearing: type() handles typeaheads behaviorally (see _FIND_SUGGESTION_JS),
# so a field with no ARIA (a plain <input> backed by a custom dropdown) is still handled correctly.
@@ -94,6 +270,27 @@ _MENU_ROW_ROLES_JS = (
"new Set(" + _WIDGET_ROLES_JS + ".filter((r) => ['combobox','listbox','spinbutton','tab'].indexOf(r) === -1))"
)
+# Counts the VISIBLE menu-row descendants of a node, using the SAME row definition _FIND_MENU_JS
+# reports on (its MENU_ROW_ROLES plus native <button>/<a>), so the growth signal and the finder cannot
+# disagree about what a row is. Assumes an enclosing `vis(el)` helper. Shared by the two click probes.
+_VIS_ROWS_JS = (
+ r"""
+ const MENU_ROW_ROLES = """
+ + _MENU_ROW_ROLES_JS
+ + r""";
+ const _visRows = (el) => {
+ let n = 0;
+ try {
+ for (const d of el.querySelectorAll('[role], button, a')) {
+ const t = d.tagName;
+ if ((MENU_ROW_ROLES.has(d.getAttribute('role')) || t === 'BUTTON' || t === 'A') && vis(d)) n++;
+ }
+ } catch (e) {}
+ return n;
+ };
+"""
+)
+
# Every open shadow root on the page, document first, then each root in depth-first order. Web-component libraries put the
# real input/button inside a shadow root, and `document.querySelector*` does not cross that boundary
@@ -190,6 +387,23 @@ _PIERCED_QUERY_JS = (
const preReset = () => {
pQSA('[data-tv3-pre]').forEach((e) => e.removeAttribute('data-tv3-pre'));
window.__tv3_pre = new WeakSet();
+ focusReset();
+ };
+ // A third class beside pre-existing and typing-revealed: rows a list rendered in reaction to the
+ // FOCUS click. They are options the widget offered, not a filter it applied to the typed value, so
+ // a match among them is picked under the open->observe->pick contract, not the typeahead's.
+ const focusMark = (el, inShadow) => {
+ if (inShadow) { if (window.__tv3_focus instanceof WeakSet) window.__tv3_focus.add(el); }
+ else el.setAttribute('data-tv3-focus', '1');
+ };
+ const focusHas = (el) => {
+ try { if (el.hasAttribute('data-tv3-focus')) return true; } catch (e) { /* clobbered getter */ }
+ return window.__tv3_focus instanceof WeakSet && window.__tv3_focus.has(el);
+ };
+ const focusReset = () => {
+ pQSA('[data-tv3-focus]').forEach((e) => e.removeAttribute('data-tv3-focus'));
+ window.__tv3_focus = new WeakSet();
+ window.__tv3_focus_offered = null;
};
// 'body *' has no meaning inside a shadow root, whose own descendants are the equivalent scope.
const pScopeEach = (fn) => {
@@ -232,17 +446,83 @@ _PRESNAPSHOT_JS = (
# INNERMOST row — a candidate that contains another match is a container (its text is the union of all
# rows, so it ties/outranks any single row; clicking it would land on the wrong row), so it's dropped.
# Tags the winner with data-tv3-sugg and returns {text, score}, or null if nothing reacted.
+# The ONE definition of "may this row be auto-clicked". Every finder that decides that embeds this
+# snippet: two hand-copied predicates drifted once (menuitem listed as both option and nav, so
+# `<a role=menuitem href>` read as an option and was clicked off the form). Semantics resolve from the
+# closest declaring ANCESTOR, not the reduced leaf (`<a href><span>` reduces to the span).
+_ROW_SEMANTICS_JS = r"""
+ const OPT_SEL = '[role="option"],[role="menuitemradio"],[role="menuitemcheckbox"],[role="treeitem"],[role="radio"]';
+ const NAV_SEL = 'a[href],button,[role="button"],[role="link"],[role="menuitem"],[role="tab"]';
+ const isNavRow = (el) => { try { return !el.closest(OPT_SEL) && !!el.closest(NAV_SEL); } catch (e) { return true; } };
+ // The nearest ancestor (across shadow boundaries, bounded) matching `sel`, or null. closest() stops
+ // at a shadow root, so a row whose text lives inside a component would otherwise have no row.
+ const LIST_SEL = '[role="listbox"],[role="menu"],[role="tree"],[role="grid"],[role="radiogroup"],datalist';
+ const ancestorMatching = (el, sel) => {
+ for (let n = el, hops = 0; n && hops < 32; hops++, n = n.parentNode || n.host || null) {
+ if (n.nodeType !== 1) continue;
+ let hit = false;
+ try { hit = n.matches(sel); } catch (e) { hit = false; }
+ if (hit) return n;
+ }
+ return null;
+ };
+ // Which of several lists is THIS field's menu: the one it declares (aria-controls/aria-owns,
+ // resolved in the field's root and its ancestor roots), else one within the dropdown window under
+ // or above the field, else the largest. Size alone would name a sibling list's options as its own.
+ const fieldOwnList = (field, lists) => {
+ if (!lists.length) return null;
+ if (field) {
+ const ids = [];
+ for (const a of ['aria-controls', 'aria-owns']) {
+ const v = field.getAttribute && field.getAttribute(a);
+ if (v) for (const id of v.split(/\s+/)) if (id) ids.push(id);
+ }
+ if (ids.length) {
+ for (let root = field.getRootNode(), hops = 0; root && hops < 8; hops++, root = root.host ? root.host.getRootNode() : null) {
+ for (const id of ids) {
+ let target = null;
+ try { target = root.getElementById ? root.getElementById(id) : null; } catch (e) { target = null; }
+ if (!target) continue;
+ const hit = lists.find((l) => l === target || (target.contains && target.contains(l)) || pContains(target, l));
+ if (hit) return hit;
+ }
+ if (!root.host) break;
+ }
+ }
+ let fr = null;
+ try { fr = field.getBoundingClientRect(); } catch (e) { fr = null; }
+ if (fr) {
+ const near = lists.filter((l) => {
+ let r = null;
+ try { r = l.getBoundingClientRect(); } catch (e) { return false; }
+ if (!r || (r.width === 0 && r.height === 0)) return false;
+ return r.top >= fr.top - 400 && r.top <= fr.bottom + 500 && r.right >= fr.left && r.left <= fr.right;
+ });
+ // A known field with no declared and no nearby list has no menu among these candidates;
+ // saying so lets the caller fall back to what was recorded when the field opened.
+ if (!near.length) return null;
+ lists = near;
+ }
+ }
+ return lists[0];
+ };
+"""
+
_FIND_SUGGESTION_JS = (
r"""(args) => {"""
+ _PIERCED_QUERY_JS
+ + _ROW_SEMANTICS_JS
+ r"""
const STOP = """
+ _STOPWORDS_JS
+ r""";
const toks = (s) => new Set(String(s).toLowerCase().replace(/[\/,]/g, ' ').split(/\s+/).filter((w) => w.length >= 3 && !STOP.has(w)));
const want = toks(args.value || '');
+ const wantNorm = String(args.value || '').replace(/\s+/g, ' ').trim().toLowerCase();
+ // A value with no >=3-char word ("No", "UK") has nothing to overlap; it matches a row only by exact text.
+ const exact = want.size ? null : String(args.value || '').replace(/\s+/g, ' ').trim().toLowerCase();
pQSA('[data-tv3-sugg]').forEach((e) => e.removeAttribute('data-tv3-sugg'));
- if (!want.size || !preReady()) return null;
+ if ((!want.size && !exact) || !preReady()) return null;
const field = pQS(args.field) || (args.el && args.el.isConnected ? args.el : null);
// No field means no geometry gate, and without it the scan below is page-wide and will happily
// tag -- and then click -- a row far from the control the caller typed into. Refuse instead:
@@ -254,10 +534,8 @@ _FIND_SUGGESTION_JS = (
if (preHas(el)) continue; // existed/was visible before typing → not a reaction
const tag = el.tagName;
if (tag === 'INPUT' || tag === 'TEXTAREA' || tag === 'SELECT' || tag === 'SCRIPT' || tag === 'STYLE' || tag === 'LABEL' || tag === 'FORM') continue;
- const role = el.getAttribute('role');
// never click something navigational (would leave the form) unless it's explicitly an option
- const nav = (tag === 'A' && el.hasAttribute('href')) || tag === 'BUTTON' || role === 'button' || role === 'link' || role === 'menuitem' || role === 'tab';
- if (nav && role !== 'option') continue;
+ if (isNavRow(el)) continue;
if (el.children.length > 8) continue; // a suggestion row, not a big container
const r = el.getBoundingClientRect();
if (r.width === 0 || r.height === 0 || r.height > 120) continue; // visible, row-sized (allows a 2-line row)
@@ -267,10 +545,20 @@ _FIND_SUGGESTION_JS = (
}
const txt = (el.innerText || '').trim();
if (!txt || txt.length > 80) continue;
- const have = toks(txt);
let score = 0;
- for (const w of want) if (have.has(w)) score++;
- if (score > 0) cands.push({ el, score, h: r.height });
+ const norm = txt.replace(/\s+/g, ' ').trim().toLowerCase();
+ // A row whose whole text IS the value outranks every partial match ("New York" over "New York
+ // City"; "No" over "No, I have not ..."), in both scoring modes.
+ const isExact = norm === (exact !== null ? exact : wantNorm);
+ if (exact !== null) {
+ if (isExact) score = 2;
+ else if (norm.split(/\s*[,;:(]\s*|\s+[-\u2013\u2014]\s+/)[0] === exact) score = 1;
+ } else {
+ const have = toks(txt);
+ for (const w of want) if (have.has(w)) score++;
+ if (isExact && score > 0) score += 100;
+ }
+ if (score > 0) cands.push({ el, score, h: r.height, exactRow: isExact });
}
if (!cands.length) return null;
// Drop any candidate that CONTAINS another candidate (a dropdown container over its own rows), then
@@ -279,6 +567,9 @@ _FIND_SUGGESTION_JS = (
const pool = leaves.length ? leaves : cands;
pool.sort((a, b) => b.score - a.score || a.h - b.h);
const best = pool[0];
+ // Two leading-clause matches for a short value ("No, ..." and "No - ...") with no exact row are
+ // ambiguous: geometry must not decide an answer, so refuse and let the caller report the options.
+ if (exact !== null && !best.exactRow && pool.length > 1 && pool[1].score === best.score) return null;
// Refuse to tag a multi-row CONTAINER even when it is the only match (its score came from different
// rows' text combined, and clicking it would land on an arbitrary middle row). A real suggestion is a
// single row: its visible child elements, if any, sit on one line (inline sub-parts), not stacked rows.
@@ -289,7 +580,189 @@ _FIND_SUGGESTION_JS = (
}
if (childRows.size >= 2) return null;
best.el.setAttribute('data-tv3-sugg', '1');
- return { text: (best.el.innerText || '').trim(), score: best.score };
+ // The values a row declares for itself (value/data-* attributes on the row or its option ancestor):
+ // a widget that commits a code ("CA" for "California") commits one of these, and nothing else short.
+ // Only attributes that NAME a value count; a positional or boolean attribute (data-index="1",
+ // data-selected="true") is not a value the widget would commit.
+ const declared = [];
+ try {
+ const VALUE_ATTR = /^(value|data-value|data-val|data-v|data-code|data-key|data-option-value|name|title)$/;
+ // An explicit option value may legitimately be "1" or "true"; any other attribute must not
+ // contribute one (a positional data-index="1" is not a value the widget commits).
+ const EXPLICIT = /^(value|data-value)$/;
+ // The option row may sit above a shadow boundary (a component's host); closest() stops there.
+ let opt = null;
+ for (let n = best.el, hops = 0; n && hops < 32; hops++, n = n.parentNode || n.host || null) {
+ if (n.nodeType !== 1) continue;
+ let hit = false;
+ try { hit = n.matches(OPT_SEL); } catch (e) { hit = false; }
+ if (hit) { opt = n; break; }
+ }
+ for (const node of new Set([best.el, opt || best.el])) {
+ for (const a of node.attributes) {
+ if (!VALUE_ATTR.test(a.name)) continue;
+ const v = String(a.value).trim();
+ if (!v || v.length > 40) continue;
+ if (!EXPLICIT.test(a.name) && (/^\d+$/.test(v) || /^(true|false|null|undefined)$/i.test(v))) continue;
+ declared.push(v);
+ }
+ }
+ } catch (e) { /* attributes unreadable: no declared values */ }
+ return { text: (best.el.innerText || '').trim(), score: best.score, fromFocus: focusHas(best.el), declared: declared.slice(0, 12) };
+}"""
+)
+
+# Second pass after the focus click: everything now visible that is not a list row is marked as
+# pre-existing, so focus-revealed help/validation text cannot read as a suggestion while a menu the
+# focus opened keeps its rows eligible.
+_FOCUS_SNAPSHOT_JS = (
+ r"""(arg) => {"""
+ + _PIERCED_QUERY_JS
+ + _ROW_SEMANTICS_JS
+ + r"""
+ if (!preReady()) return;
+ focusReset();
+ let field = null;
+ try { field = pQS(arg.sel); } catch (e) { field = null; }
+ if (!field && arg.el && arg.el.isConnected) field = arg.el;
+ // Menu/option semantics, not any list: a plain <ul> that focus revealed is page text, an ARIA
+ // list or an option row is the widget's own menu. A list that CONTAINS the field is layout.
+ const LIST = LIST_SEL;
+ const inOptionList = (el) => {
+ for (let n = el; n; n = n.parentNode || n.host || null) {
+ if (n.nodeType !== 1) continue;
+ let isList = false;
+ try { isList = n.matches(LIST) || n.matches(OPT_SEL); } catch (e) { isList = false; }
+ if (isList) return !(field && pContains(n, field));
+ }
+ return false;
+ };
+ pScopeEach((el, inShadow) => {
+ if (preHas(el)) return;
+ const r = el.getBoundingClientRect();
+ if (r.width <= 0 || r.height <= 0) return;
+ if (inOptionList(el)) focusMark(el, inShadow); else preMark(el, inShadow);
+ });
+ // Record what the list offered NOW: a widget that filters by re-rendering unmounts the rows the
+ // typed value does not match, so a later read would find nothing to name on an honest no-match.
+ const byList = new Map();
+ const seen = new Set();
+ pScopeEach((el) => {
+ if (!focusHas(el)) return;
+ const row = ancestorMatching(el, OPT_SEL);
+ if (!row || seen.has(row)) return;
+ seen.add(row);
+ const txt = (row.textContent || '').replace(/\s+/g, ' ').trim();
+ if (!txt || txt.length > 80) return;
+ const key = ancestorMatching(row, LIST_SEL) || row.parentNode;
+ if (!byList.has(key)) byList.set(key, []);
+ byList.get(key).push(txt);
+ });
+ const lists = Array.from(byList.keys()).sort((a, b) => byList.get(b).length - byList.get(a).length);
+ const own = fieldOwnList(field, lists);
+ const best = own ? byList.get(own) : [];
+ // Stamped with the field it was recorded for: a record left by an earlier field is never read
+ // for this one, even when this call's own focus pass did not run.
+ window.__tv3_focus_offered = { sel: arg.sel, total: best.length, labels: best.slice(0, 15) };
+}"""
+)
+
+# The labels the widget OFFERED when the field opened — its focus-revealed rows (see _FOCUS_SNAPSHOT_JS),
+# read even after the typed filter hid them, so an honest no-match can name the real choices instead of
+# leaving the model to guess a label again. Reads only; tags nothing.
+_FOCUS_OFFERED_LABELS_JS = (
+ r"""(arg) => {"""
+ + _PIERCED_QUERY_JS
+ + _ROW_SEMANTICS_JS
+ + r"""
+ let field = null;
+ try { field = pQS(arg.sel); } catch (e) { field = null; }
+ if (!field && arg.el && arg.el.isConnected) field = arg.el;
+ // Rows grouped by their list; only the list that offered the most rows is this field's own
+ // menu -- a page-wide sweep would attribute another widget's options to this field.
+ const byList = new Map();
+ const seen = new Set();
+ for (const el of pScopeAll()) {
+ if (!focusHas(el)) continue;
+ if (field && pContains(el, field)) continue;
+ const row = ancestorMatching(el, OPT_SEL);
+ if (!row || seen.has(row)) continue;
+ seen.add(row);
+ const txt = (row.textContent || '').replace(/\s+/g, ' ').trim();
+ if (!txt || txt.length > 80) continue;
+ const list = ancestorMatching(row, LIST_SEL) || row.parentNode;
+ if (!byList.has(list)) byList.set(list, []);
+ byList.get(list).push(txt);
+ }
+ const lists = Array.from(byList.keys()).sort((a, b) => byList.get(b).length - byList.get(a).length);
+ const own = fieldOwnList(field, lists);
+ const best = own ? byList.get(own) : [];
+ if (!best.length) {
+ const rec = window.__tv3_focus_offered;
+ if (rec && rec.sel === arg.sel && Array.isArray(rec.labels) && rec.labels.length) return { total: rec.total || rec.labels.length, labels: rec.labels.slice(0, 15) };
+ }
+ return { total: best.length, labels: best.slice(0, 15) };
+}"""
+)
+
+# Classifies the currently-open list's rows as EXPANDABLE CATEGORIES rather than leaves — for the
+# no-match error path only, when _FIND_SUGGESTION_JS found nothing (a drilldown menu's leaves are
+# often hidden a level down until their category is clicked, so text-matching never sees them). Unlike
+# the reaction-gated finders above, category rows commonly PRE-EXIST the typing, so this does not gate
+# on preHas/preReady — only on geometry (the same field-rect window) and a positive expand signal:
+# aria-haspopup, aria-expanded, or (for a clickable option/menuitem/treeitem row) >=2 nested option
+# rows. Tags qualifying rows data-tv3-menu="1..N" so the model can click one via the menu-click channel;
+# leaves data-tv3-menu untouched when it tags nothing, so it never clobbers a prior menu's tags.
+_FIND_CATEGORIES_JS = (
+ r"""(args) => {"""
+ + _PIERCED_QUERY_JS
+ + r"""
+ const field = pQS(args.field);
+ if (!field) return null;
+ const fr = field.getBoundingClientRect();
+ const ROW_ROLES = new Set(['option', 'menuitem', 'treeitem', 'row', 'group']);
+ const CHILD_ROLES = new Set(['option', 'menuitem', 'treeitem']);
+ const cats = [];
+ for (const el of pScopeAll()) {
+ if (el === field || cats.length >= 8) continue;
+ const tag = el.tagName;
+ if (tag === 'INPUT' || tag === 'TEXTAREA' || tag === 'SELECT' || tag === 'SCRIPT' || tag === 'STYLE' || tag === 'LABEL' || tag === 'FORM') continue;
+ const role = el.getAttribute('role');
+ if (!ROW_ROLES.has(role)) continue;
+ // Never offer a navigational row: clicking an <a href>/<button> leaves the form (mirrors the same
+ // exclusion in _FIND_SUGGESTION_JS). An already-open row (aria-expanded="true") would collapse on
+ // click, not reveal, so it is not a category worth clicking either.
+ if ((tag === 'A' && el.hasAttribute('href')) || tag === 'BUTTON') continue;
+ if (el.getAttribute('aria-expanded') === 'true') continue;
+ if (el.getAttribute('aria-disabled') === 'true' || el.hasAttribute('disabled')) continue;
+ const r = el.getBoundingClientRect();
+ if (r.width === 0 || r.height === 0 || r.height > 120) continue;
+ if (r.top < fr.top - 400 || r.top > fr.bottom + 500) continue;
+ if (r.right < fr.left || r.left > fr.right) continue;
+ const hp = el.getAttribute('aria-haspopup');
+ const hasPopup = hp !== null && hp !== 'false';
+ // Only a COLLAPSED row is worth clicking to reveal options; aria-expanded="true" is already open,
+ // so clicking it would toggle it closed.
+ const hasExpanded = el.getAttribute('aria-expanded') === 'false';
+ // A container role (group/row) is a static section wrapper unless it carries an explicit expand
+ // affordance; only an option/menuitem/treeitem row may qualify on nested-option count alone, else
+ // a grouped listbox (role=group over already-visible option leaves) is misread as a drilldown.
+ let childCount = 0;
+ if (CHILD_ROLES.has(role)) {
+ for (const kid of el.querySelectorAll('[role]')) {
+ if (CHILD_ROLES.has(kid.getAttribute('role'))) childCount++;
+ }
+ }
+ if (!hasPopup && !hasExpanded && childCount < 2) continue;
+ const label = el.getAttribute('aria-label') || (el.innerText || '').trim().split('\n')[0];
+ const text = label.trim().slice(0, 80);
+ if (!text) continue;
+ cats.push({ el, text });
+ }
+ if (!cats.length) return null;
+ pQSA('[data-tv3-menu]').forEach((e) => e.removeAttribute('data-tv3-menu'));
+ cats.forEach((c, i) => c.el.setAttribute('data-tv3-menu', String(i + 1)));
+ return { count: cats.length, categories: cats.map((c, i) => ({ n: i + 1, text: c.text })) };
}"""
)
@@ -305,6 +778,10 @@ _VERIFY_COMMIT_JS = (
+ r"""
const toks = (s) => new Set(String(s).toLowerCase().replace(/[\/,]/g, ' ').split(/\s+/).filter((w) => w.length >= 3));
const overlaps = (a, b) => { const B = toks(b); for (const w of toks(a)) if (B.has(w)) return true; return false; };
+ // Token overlap drops words shorter than 3 chars, so a short committed label ("No", "MA") has no token
+ // to overlap. Case/space-normalized EXACT equality rescues it — a hidden value that IS the chosen label
+ // is a real commit, and an exact match cannot be an incidental partial overlap.
+ const eqi = (a, b) => !!a && !!b && a.replace(/\s+/g, ' ').trim().toLowerCase() === b.replace(/\s+/g, ' ').trim().toLowerCase();
const el = pQS(args.field) || (args.el && args.el.isConnected ? args.el : null);
// null (not '') when there is nothing to read: the caller must tell "read it, no commit" from
// "could not read it", and a later second probe would answer about a different instant.
@@ -313,22 +790,91 @@ _VERIFY_COMMIT_JS = (
const chosen = String(args.chosen || '').trim() || typed;
const cur = (el.value || '').trim();
const tagged = pQS('[data-tv3-sugg]');
- const listClosed = !tagged || tagged.getBoundingClientRect().height === 0;
+ // The open->observe->pick path tags no suggestion, so `listClosed` would be unconditionally true and
+ // defeat the change check — the caller sets noSuggestionList so the el.value branch rests on an actual
+ // change from the pre-click value (passed as `typed`), never leftover text the tool itself put there.
+ const listClosed = args.noSuggestionList ? false : (!tagged || tagged.getBoundingClientRect().height === 0);
// A short normalized value ("New York" -> "NY", "United States" -> "US") has no >=3-char token to
// overlap, so accept it on causality alone (it changed / the list closed). Longer values must still
// relate to the chosen suggestion so an unrelated change can't read as a successful commit.
- if (cur && (cur !== typed || listClosed) && (toks(cur).size === 0 || overlaps(cur, chosen) || overlaps(cur, typed))) return cur;
+ if (args.noSuggestionList) {
+ // On the open->observe->pick path the CHOSEN label is known, so require the new value to BE it
+ // (short: exact; long: token overlap), not merely "some short value changed" — a dead row that
+ // resets the input to "N/A" changes cur but does not commit the chosen option.
+ const declared = Array.isArray(args.chosenValues) ? args.chosenValues : [];
+ if (cur && cur !== typed && (eqi(cur, chosen) || overlaps(cur, chosen) || declared.some((d) => eqi(d, cur)))) return cur;
+ } else if (cur && (cur !== typed || listClosed) && (toks(cur).size === 0 || overlaps(cur, chosen) || overlaps(cur, typed))) {
+ return cur;
+ }
const cont = el.closest('div,li,fieldset');
if (cont) {
+ // On the pick path the caller snapshots the hidden values BEFORE the click: a value that merely
+ // shares a token with the chosen label ("People Operations" left over while "Sales Operations" was
+ // clicked dead) is the stale state, not a commit — only an exact chosen label or a CHANGED value counts.
+ const preHidden = new Set(Array.isArray(args.preHidden) ? args.preHidden : []);
for (const h of cont.querySelectorAll('input[type=hidden]')) {
const v = (h.value || '').trim();
- if (v && (overlaps(v, chosen) || overlaps(v, typed))) return v;
+ if (!v) continue;
+ if (eqi(v, chosen)) return v;
+ if (args.noSuggestionList) {
+ const declaredHidden = Array.isArray(args.chosenValues) ? args.chosenValues : [];
+ if ((overlaps(v, chosen) || declaredHidden.some((d) => eqi(d, v))) && !preHidden.has(v)) return v;
+ continue;
+ }
+ if (overlaps(v, chosen) || eqi(v, typed) || overlaps(v, typed)) return v;
+ }
+ }
+ // React-Select / styled combobox: on commit the value moves OUT of the filter input into a
+ // single-value node or token beside it and the input is cleared, so the reads above miss it. Read
+ // that committed surface — but only once the widget reports closed (aria-expanded=false), so a
+ // still-open list reflecting the typed filter can't read as a commitment, and scoped to the nearest
+ // ancestor holding exactly this one combobox trigger, so a sibling field showing the same label
+ // can't pre-confirm this one. Mirrors v1's _CUSTOM_SELECT_COMMITTED_STATE_JS.
+ const expandedEl = el.getAttribute('aria-expanded') != null ? el : el.closest('[aria-expanded]');
+ const expanded = expandedEl ? expandedEl.getAttribute('aria-expanded') : null;
+ if (expanded === 'false') {
+ const TRIGGER = "[role=combobox],[aria-haspopup=listbox],[aria-haspopup=menu],button[aria-expanded],input[role=combobox],select";
+ const SURFACE = "[class*='single-value'],[class*='singleValue'],[class*='multi-value__label'],[role=option][aria-selected=true],.chip,.pill,[class*='token']";
+ let scope = null;
+ for (let anc = el.parentElement, hops = 1; anc && hops <= 4; hops++, anc = anc.parentElement) {
+ const trig = anc.querySelectorAll(TRIGGER);
+ if (anc.querySelector(SURFACE) && trig.length === 1 && (trig[0] === el || el.contains(trig[0]))) {
+ scope = anc;
+ break;
+ }
+ }
+ if (scope) {
+ // EXACT normalized match, not token overlap (mirrors v1's matchesExpected): a stale single-value
+ // or a leftover multi-select token that merely SHARES a word with the chosen label would read as a
+ // false commit when the real selection silently failed. A committed surface normally holds exactly
+ // the chosen label (or, for a multi-value chip, it among comma-separated parts).
+ const norm = (s) => String(s == null ? '' : s).replace(/\s+/g, ' ').trim().toLowerCase();
+ const want = norm(chosen) || norm(typed);
+ const surfaceMatches = (raw) => {
+ const n = norm(raw);
+ if (!n || !want) return false;
+ return n === want || n.split(',').map((p) => p.trim()).includes(want);
+ };
+ for (const s of scope.querySelectorAll(SURFACE)) {
+ // textContent OR the accessible name (aria-label): a chip/single-value can carry the committed
+ // label only in aria-label with no text node — v1 reads both, so this must too.
+ const t = (s.textContent || '').trim();
+ if (surfaceMatches(t)) return t;
+ const al = (s.getAttribute('aria-label') || '').trim();
+ if (surfaceMatches(al)) return al;
+ }
}
}
return '';
}"""
)
+# The hidden-input values _VERIFY_COMMIT_JS would read for this field, in the same div/li/fieldset scope.
+_HIDDEN_VALUES_JS = (
+ "el => { const c = el.closest('div,li,fieldset'); if (!c) return []; "
+ "return Array.from(c.querySelectorAll('input[type=hidden]')).map((h) => (h.value || '').trim()).filter(Boolean); }"
+)
+
# Why a reaction probe's answer about this selector may not carry a claim. `unprobeable` -- in-page
# CSS cannot even parse it (Playwright syntax like `css=`, `>> nth=`, `:visible`, `text=`).
# `component` -- it lives inside a component. The probes DO pierce open shadow roots, so this no
@@ -467,6 +1013,120 @@ async def pending_marker(page: Any, selector: str) -> str | None:
return marker
+# Cap on marks a single look draws: more than this yields an unreadable set-of-marks image and a legend
+# the model cannot map back. In DOM order (document first), so a truncated look still numbers the
+# top-of-page controls the model most likely wants.
+_LOOK_MAX_MARKS = 60
+
+# Hard per-run ceiling on look() calls. look bills one image per call and is not an action step, so
+# without a cap the only bound is max_turns (~1 image/turn) — a metered vision cost the operator's
+# constraint forbids. A last-resort tool rarely needs more than a handful; past this it returns an
+# error pointing back at the text tools rather than adding another image.
+_LOOK_MAX_PER_RUN = 20
+
+# Enumerate the same interactive controls observe() does, across open shadow roots, keeping only the
+# ones with pixels on screen (a visible box intersecting the viewport). Tag each with a transient
+# data-tv3-look index and return its CSS-px rect so the marks can be drawn on the screenshot. The
+# index is cleared right after handles are grabbed — it exists only to pair a handle to a rect.
+_LOOK_ENUM_JS = (
+ r"""(() => {
+ const _roots = """
+ + _SHADOW_ROOTS_JS
+ + r""";
+ const q = 'input,textarea,select,button,a[href],[role=button],[role=checkbox],[role=radio],[role=combobox],[role=option],[role=menuitem],[role=menuitemcheckbox],[role=menuitemradio],[role=listbox],[role=switch],[role=spinbutton],[role=tab],[contenteditable=true]';
+ const vw = window.innerWidth, vh = window.innerHeight;
+ const seen = new Set();
+ const out = [];
+ let n = 0;
+ let truncated = false;
+ for (const root of _roots(document)) {
+ let els;
+ try { els = root.querySelectorAll(q); } catch (e) { continue; }
+ for (const el of els) {
+ if (seen.has(el)) continue;
+ seen.add(el);
+ let r;
+ try { r = el.getBoundingClientRect(); } catch (e) { continue; }
+ if (r.width < 4 || r.height < 4) continue;
+ if (r.bottom <= 0 || r.right <= 0 || r.top >= vh || r.left >= vw) continue;
+ let shown = true;
+ try {
+ shown = el.checkVisibility
+ ? el.checkVisibility({opacityProperty: true, visibilityProperty: true, contentVisibilityAuto: true})
+ : true;
+ } catch (e) {}
+ if (!shown) continue;
+ if (n >= """
+ + str(_LOOK_MAX_MARKS)
+ + r""") { truncated = true; break; }
+ n += 1;
+ try { el.setAttribute('data-tv3-look', String(n)); } catch (e) { n -= 1; continue; }
+ let label = '';
+ let placeholder = '';
+ try {
+ const t = (el.getAttribute('type') || '').toLowerCase();
+ // .value is a useful label for a text/submit field but is 'on'/junk for a checkbox or radio —
+ // and is the SECRET for a password field, which (like observe) must never enter the legend.
+ const valuable = el.tagName === 'INPUT' && !['checkbox', 'radio', 'password'].includes(t) ? (el.value || '') : '';
+ // Cap generously (not the 80-char display width): the value is masked for payload-minted
+ // signed URLs Python-side, which needs the WHOLE URL to match by provenance before the label
+ // is truncated for display. A tighter cap here would truncate the URL past recognition.
+ // As in observe: the associated <label> outranks the placeholder, which is a template hint,
+ // not a name -- and travels separately when it differs, since a format hint makes the value typeable.
+ let named = '';
+ if (el.labels) { for (const l of el.labels) { named = (l.innerText || '').trim(); if (named) break; } }
+ placeholder = (el.getAttribute('placeholder') || '').trim().replace(/\s+/g, ' ').slice(0, 2000);
+ label = (el.getAttribute('aria-label') || named || placeholder || valuable
+ || el.innerText || el.getAttribute('title') || el.getAttribute('name') || '')
+ .trim().replace(/\s+/g, ' ').slice(0, 2000);
+ } catch (e) {}
+ const rec = { n, x: r.left, y: r.top, w: r.width, h: r.height, tag: (el.tagName || '').toLowerCase(), label };
+ if (placeholder && placeholder !== label) rec.placeholder = placeholder;
+ out.push(rec);
+ }
+ if (truncated) break;
+ }
+ return { vw, vh, truncated, elements: out };
+})()"""
+)
+
+# Write the transient act-by-mark attribute on an element handle the caller already resolved
+# (Playwright's engine, which pierces open shadow). Returns whether the node is still connected; a
+# detached handle errors rather than re-resolving by a stale coordinate.
+_LOOK_TAG_HANDLE_JS = "(el, n) => { try { el.setAttribute('data-tv3-act', String(n)); } catch (e) { return false; } return el.isConnected; }"
+
+
+def _annotate_screenshot(png_bytes: bytes, elements: list[dict[str, Any]], vw: int, *, max_width: int = 1024) -> bytes:
+ """Draw a numbered set-of-marks box over each element on the viewport screenshot, server-side.
+
+ Boxes are drawn in the SAME numbering the legend and act-by-mark use. The screenshot is in device
+ pixels and the rects in CSS pixels; downscaling to `max_width` first and mapping CSS px through the
+ single factor `final_width / vw` folds devicePixelRatio and the downscale into one transform, so
+ the boxes land regardless of the display's pixel ratio."""
+ img = Image.open(io.BytesIO(png_bytes)).convert("RGB")
+ if img.width > max_width:
+ scale = max_width / img.width
+ img = img.resize((max_width, max(1, round(img.height * scale))))
+ factor = (img.width / vw) if vw else 1.0
+ draw = ImageDraw.Draw(img)
+ for e in elements:
+ x0 = e["x"] * factor
+ y0 = e["y"] * factor
+ x1 = (e["x"] + e["w"]) * factor
+ y1 = (e["y"] + e["h"]) * factor
+ draw.rectangle([x0, y0, x1, y1], outline=(255, 0, 0), width=2)
+ label = str(e["n"])
+ tw = 6 * len(label) + 4
+ # Sit the label tag just above the box, but drop it just inside the top edge when the box is
+ # flush against the top of the viewport so a top-row mark's number stays legible.
+ ly = y0 - 12 if y0 >= 12 else y0
+ draw.rectangle([x0, ly, x0 + tw, ly + 12], fill=(255, 0, 0))
+ draw.text((x0 + 2, ly + 1), label, fill=(255, 255, 255))
+ buf = io.BytesIO()
+ img.save(buf, format="PNG")
+ return buf.getvalue()
+
+
_VISIBLE_PROXY_JS = r"""(el) => {
let named = el.labels && el.labels[0];
if (!named) {
@@ -514,6 +1174,56 @@ _ROOT_QUERY_JS = (
)
+_IN_COMPONENT_JS = (
+ r"""(arg) => {
+ const _q = """
+ + _ROOT_QUERY_JS
+ + r""";
+ const el = _q.find(arg.sel) || (arg.el && arg.el.isConnected ? arg.el : null);
+ if (!el) return false;
+ try { return Node.prototype.getRootNode.call(el) !== document; } catch (e) { return false; }
+}"""
+)
+
+# A component that mirrors its own id onto the native control inside its shadow root makes a bare
+# `#id` match the HOST first (document is the first root, and Playwright picks the first match too).
+# observe names such a control by tag (`input[id="…"]`), but the model routinely drops the tag. When the
+# selector's first match is a non-control host whose shadow tree holds exactly one form control that
+# the same selector also matches, name that control the way observe would have -- the host is what a
+# person sees, the control is what accepts the value.
+_MIRRORED_HOST_CONTROL_JS = (
+ r"""(sel) => {
+ const _q = """
+ + _ROOT_QUERY_JS
+ + r""";
+ const CONTROL = 'INPUT,TEXTAREA,SELECT,BUTTON';
+ const WIDGET_ROLE = /^(textbox|searchbox|combobox|listbox|button|checkbox|radio|switch|spinbutton|slider)$/i;
+ const isControl = (e) => e.matches(CONTROL) || e.isContentEditable || WIDGET_ROLE.test(e.getAttribute('role') || '');
+ let first = null;
+ try { first = _q.find(sel); } catch (e) { return null; }
+ if (!first) return null;
+ let root = null;
+ try { root = first.shadowRoot; } catch (e) { return null; }
+ // A host that only DECLARES a widget role still delegates to the control inside it.
+ if (!root || root.nodeType !== 11 || first.matches(CONTROL) || first.isContentEditable) return null;
+ const inside = (e) => { for (let n = e; n; n = n.parentNode || n.host || null) if (n === first) return true; return false; };
+ const controls = _q.all(sel).filter((e) => e !== first && inside(e) && isControl(e));
+ if (controls.length !== 1) return null;
+ const c = controls[0];
+ if (!c.id || String(c.id) !== String(first.id)) return null;
+ // The same screen observe applies to an id it hands out: this string becomes the selector every
+ // later message names, so a forgeable character or an unbounded length must not pass through.
+ const FORGEABLE = /[\x00-\x1f\x7f\u0085\u2028\u2029\u200b-\u200f\u202a-\u202e\u2066-\u2069]/;
+ const id = String(c.id);
+ if (id.length > 200 || FORGEABLE.test(id)) return null;
+ const tag = c.tagName.toLowerCase();
+ if (!/^[a-z][a-z0-9-]*$/.test(tag)) return null;
+ const named = tag + '[id="' + id.replace(/\\/g, '\\\\').replace(/"/g, '\\"') + '"]';
+ return _q.all(named).length === 1 && _q.find(named) === c ? named : null;
+}"""
+)
+
+
# Every other probe here asks whether a control is VISIBLE. This one asks whether it is REACHABLE,
# which is a different question and the only one that separates these two cases: Playwright reports a
# covered input as "visible, enabled, stable" and then fails the separate hit-target check, retrying
@@ -544,15 +1254,42 @@ _TYPE_TARGET_PROBE_JS = (
}
let top = null;
try { top = document.elementFromPoint(r.left + r.width / 2, r.top + r.height / 2); } catch (e) { return out; }
- // elementFromPoint sees the top-level document only, so a control inside a component resolves to
- // its host. Treat that as reachable: the host IS what a real click lands on, and the browser
- // retargets the event inward. The walk must hop ShadowRoot -> host, because Node.contains stays in
- // the light tree and would read every component control as covered by its own host.
+ // document.elementFromPoint stops at the outermost host, so a control inside a component reads as
+ // covered by that host -- and a form-sized outer component is too big to pass as a skin. Descend
+ // through each hit host's own root to the composed hit target, the element a real click lands on.
+ // `hit` stays the light-DOM element for NAMING below: the model needs a handle it can act on, and
+ // a host is that handle when the layer lives inside a component.
+ const hit = top;
+ for (let hops = 0; top && hops < 32; hops++) {
+ // A page can make shadowRoot a throwing getter; a throw here would escape the probe and read as
+ // "not occluded", so it ends the descent instead.
+ let root = null;
+ try { root = top.shadowRoot; } catch (e) { break; }
+ if (!root || root.nodeType !== 11) break;
+ let inner = null;
+ try { inner = root.elementFromPoint(r.left + r.width / 2, r.top + r.height / 2); } catch (e) { break; }
+ if (!inner || inner === top) break;
+ top = inner;
+ }
+ // The walk must hop ShadowRoot -> host, because Node.contains stays in the light tree and would
+ // read every component control as covered by its own host.
+ // Composed-tree containment: a slotted node renders inside the component's shadow (its
+ // assignedSlot), so a hit on a control's slotted label is a hit on the control, not a cover.
const related = (a, b) => {
- for (let n = b; n; n = n.parentNode || n.host || null) if (n === a) return true;
+ for (let n = b, hops = 0; n && hops < 256; hops++, n = n.assignedSlot || n.parentNode || n.host || null) if (n === a) return true;
+ return false;
+ };
+ const domRelated = (a, b) => {
+ for (let n = b, hops = 0; n && hops < 256; hops++, n = n.parentNode || n.host || null) if (n === a) return true;
return false;
};
- if (!top || top === el || related(el, top)) return out;
+ if (!top || top === el) return out;
+ if (related(el, top)) {
+ // Reachable only through slot assignment: the driver's DOM-containment hit-target check will
+ // call this label an interceptor, so the caller dispatches without that check.
+ if (!domRelated(el, top)) out.slotted = true;
+ return out;
+ }
out.occluded = true;
// Whether to force is a question about the OCCLUDER, not about the field. Structure alone is not
// enough: when the field sits directly under <body>, or shares a container with a portal target,
@@ -684,7 +1421,8 @@ _TYPE_TARGET_PROBE_JS = (
// Named regardless of skinned: the typing path ignores the name when it forces past a skin, but the
// CLICK path has no force fallback -- a click covered by the field's own open listbox times out, and
// the model needs the occluder named (its options listed) rather than a bare 15s Page.click Timeout.
- if (out.occluded && top !== document.body && top !== document.documentElement) {
+ if (out.occluded && hit && hit !== document.body && hit !== document.documentElement) {
+ top = hit;
// A throw anywhere below would otherwise escape page.evaluate() entirely and be read upstream
// as "the probe failed" -- which _reachable_for_typing treats as reachable=True, skipping
// occlusion detection altogether. Naming the occluder is best-effort; out.occluded/out.skinned
@@ -1098,6 +1836,7 @@ _SELECT_VISIBILITY_JS = (
// whatever the run submits next.
return {
exists: true,
+ nodeName: (el.nodeName || '').toLowerCase(),
visible: r.width > 0 && r.height > 0 && cs.visibility !== 'hidden',
disabled: !!el.disabled,
proxied: !!_visibleProxy(el),
@@ -1106,6 +1845,31 @@ _SELECT_VISIBILITY_JS = (
}"""
)
+# Whether a selector's own element is a typeable field (an input/textarea/contenteditable that can
+# accept keystrokes) rather than a click-to-open anchor (a button/div that only opens a list). The
+# shared custom-combobox commit path types into typeable anchors and refuses non-typeable ones, so a
+# page.fill throw ("Element is not an <input>") never replaces the <select> throw this fix removes.
+_ANCHOR_TYPEABLE_JS = (
+ r"""(arg) => {
+ const _q = """
+ + _ROOT_QUERY_JS
+ + r""";
+ const _executorEl = arg.el && arg.el.isConnected ? arg.el : null;
+ try {
+ const el = _q.find(arg.sel) || _executorEl;
+ if (!el) return false;
+ const tag = el.tagName;
+ if (tag === 'TEXTAREA') return !el.disabled && !el.readOnly;
+ if (tag === 'INPUT') {
+ const t = (el.getAttribute('type') || 'text').toLowerCase();
+ const NONTEXT = new Set(['checkbox','radio','button','submit','reset','file','image','range','color','hidden']);
+ return !NONTEXT.has(t) && !el.disabled && !el.readOnly;
+ }
+ return !!el.isContentEditable;
+ } catch (e) { return false; }
+}"""
+)
+
# Read back after a forced select_option so a styled proxy that silently didn't sync from its
# native control is caught rather than reported as a successful selection.
_SELECT_READBACK_JS = (
@@ -1243,6 +2007,10 @@ _CLICK_PRECHECK_JS = (
let optSel = '';
let optKids = -1;
let optH = -1;
+ let optVis = -1;
+"""
+ + _VIS_ROWS_JS
+ + r"""
if (target && openRows.length) {
for (const el of openRows) {
// The target being the row or inside it is an option pick. The target merely CONTAINING rows
@@ -1255,6 +2023,7 @@ _CLICK_PRECHECK_JS = (
optSel = selState(el);
optKids = el.children.length;
optH = Math.round(el.getBoundingClientRect().height);
+ optVis = _visRows(el);
break;
}
if (pContains(target, el)) containsMenu = true;
@@ -1262,10 +2031,14 @@ _CLICK_PRECHECK_JS = (
}
preReset();
pScopeEach((el, inShadow) => { if (vis(el)) preMark(el, inShadow); });
- return { menuOpen: openRows.length > 0, isOption, containsMenu, optText, optState, optSel, optKids, optH };
+ return { menuOpen: openRows.length > 0, isOption, containsMenu, optText, optState, optSel, optKids, optH, optVis };
}"""
)
+# Same-document token for the click retry: a navigation destroys window, a pushState does not.
+_CLICK_SAME_DOC_PLANT_JS = "() => { window.__tv3_click_same = 1; }"
+_CLICK_SAME_DOC_CHECK_JS = "() => window.__tv3_click_same === 1"
+
# Planted on window before an option click; a navigation clears window, so its absence afterwards is
# the page saying "different document" even when the post-click probe's own JS is what failed.
_CLICK_DOC_PLANT_JS = "() => { window.__tv3_click_doc = 1; }"
@@ -1306,6 +2079,9 @@ _MENU_AFTER_JS = (
el.getAttribute('aria-checked'), el.getAttribute('aria-selected'), el.getAttribute('aria-pressed'),
].join('|');
};
+"""
+ + _VIS_ROWS_JS
+ + r"""
let stillOpen = 0;
const rows = [];
for (const el of pQSA('[data-tv3-menu]')) if (vis(el)) { stillOpen++; rows.push(el); }
@@ -1315,6 +2091,7 @@ _MENU_AFTER_JS = (
let optSel = '';
let optKids = -1;
let optH = -1;
+ let optVis = -1;
if (target) {
for (const el of rows) {
if (el === target || pContains(el, target)) {
@@ -1322,11 +2099,12 @@ _MENU_AFTER_JS = (
optSel = selState(el);
optKids = el.children.length;
optH = Math.round(el.getBoundingClientRect().height);
+ optVis = _visRows(el);
break;
}
}
}
- return { stillOpen, optState, optSel, optKids, optH };
+ return { stillOpen, optState, optSel, optKids, optH, optVis };
}"""
)
@@ -1343,6 +2121,7 @@ _FIND_MENU_JS = (
r"""(arg) => {
const clicked = arg.sel;"""
+ _PIERCED_QUERY_JS
+ + _ROW_SEMANTICS_JS
+ r"""
const MENU_ROW_ROLES = """
+ _MENU_ROW_ROLES_JS
@@ -1359,7 +2138,7 @@ _FIND_MENU_JS = (
const tr = trigger.getBoundingClientRect();
const rows = [];
for (const el of pScopeAll()) {
- if (preHas(el)) continue;
+ if (preHas(el) || focusHas(el)) continue;
const tag = el.tagName;
if (tag === 'INPUT' || tag === 'TEXTAREA' || tag === 'SELECT' || tag === 'SCRIPT' || tag === 'STYLE' || tag === 'LABEL' || tag === 'FORM') continue;
if (el.children.length > 8) continue;
@@ -1416,9 +2195,24 @@ _FIND_MENU_JS = (
for (const [p, set] of groups) {
const g = Array.from(set);
if (g.length < 2) continue;
- if (!boundaryStandIns.has(p) && preHas(p)) continue;
- // A dialog is a page mode, not a menu — mislabeling it invites a wrong "pick an option" move.
- try { if (p.closest('dialog,[role~="dialog"],[aria-modal="true"]')) continue; } catch (e) {}
+ // A pre-existing container normally is not a just-opened menu. The exception: the row you CLICKED
+ // (or a container inside it) that expanded to reveal leaves which pre-existed hidden — there the
+ // container is old but the leaves are the new reaction. Scoped to within the clicked row so an
+ // unrelated pre-existing list that merely gained rows elsewhere is still rejected.
+ const withinClicked = p === trigger || pContains(trigger, p);
+ if (!boundaryStandIns.has(p) && preHas(p) && !withinClicked) continue;
+ // A dialog is a page mode, not a menu — mislabeling its action buttons invites a wrong "pick an
+ // option" move. But a real option list legitimately renders inside a modal (an application form's
+ // select in a dialog), so exclude a dialog group ONLY when its rows are not explicit menu options:
+ // a confirm dialog's Cancel/Confirm pair (plain buttons) stays excluded, a role=option listbox does not.
+ try {
+ if (p.closest('dialog,[role~="dialog"],[aria-modal="true"]')) {
+ // Test the closest option-role ANCESTOR, not the reduced leaf: a role=option row with a styled
+ // <span> child reduces to the span (null role), so a leaf-only check would wrongly reject it.
+ // menuitem rows are enumerable here (a menu in a dialog is still a menu) but stay nav for clicking.
+ if (!g.every((c) => c.el.closest(OPT_SEL + ',[role="menuitem"]'))) continue;
+ }
+ } catch (e) {}
const pr = p.getBoundingClientRect();
if (!vis(pr) || pr.height > 500) continue;
if (pr.top < tr.top - 200 || pr.top > tr.bottom + 400) continue;
@@ -1437,18 +2231,105 @@ _FIND_MENU_JS = (
c.el.setAttribute('data-tv3-menu', String(n));
if (options.length < 15) options.push({ n, text: c.txt.slice(0, 60) });
}
- return { count: n, options };
+ // Undeclared virtualisation: a list that renders only a window declares nothing (no aria-setsize),
+ // but its scroll container carries the FULL extent (react-window sizes a spacer to the whole list).
+ // Rendered-in-full lists fill their scroll extent; a window leaves more than a row of it uncovered.
+ let partial = false;
+ try {
+ const first = best.g[0].r, last = best.g[best.g.length - 1].r;
+ const span = last.bottom - first.top;
+ const rowH = Math.max(1, span / best.g.length);
+ for (let sc = best.p, hops = 0; sc && hops < 6; hops++, sc = sc.parentElement) {
+ const ovy = getComputedStyle(sc).overflowY;
+ if ((ovy === 'auto' || ovy === 'scroll' || ovy === 'overlay') && sc.scrollHeight > sc.clientHeight + 1) {
+ partial = sc.scrollHeight - span >= 1.5 * rowH;
+ break;
+ }
+ }
+ } catch (e) { partial = false; }
+ return { count: n, options, partial };
+}"""
+)
+
+# Read the FULL (untruncated) label of every row _FIND_MENU_JS tagged data-tv3-menu, across the same
+# pierced reach it tags in. _FIND_MENU_JS caps its returned `options` at 15 and truncates each to 60
+# chars for payload size; the deterministic match must see the whole list at full length so a value at
+# row 20, or a label longer than 60 chars, is neither missed nor matched on a cut-off token. `nav` marks
+# a row this tool must not auto-click — _FIND_MENU_JS enumerates <a href>/<button>/menuitem rows because
+# it only REPORTS, but clicking a navigational row would leave the form (mirrors _FIND_SUGGESTION_JS,
+# which refuses exactly these unless role=option).
+_MENU_OPTION_TEXTS_JS = (
+ r"""() => {"""
+ + _PIERCED_QUERY_JS
+ + _ROW_SEMANTICS_JS
+ + r"""
+ return Array.from(pQSA('[data-tv3-menu]')).map((el) => {
+ // `_FIND_MENU_JS` tags the innermost leaf; an option whose ancestor declares aria-setsize is a child
+ // that declares none, so read the closest declaring ancestor or the incomplete-list guard is bypassed.
+ const nav = isNavRow(el);
+ const setEl = el.closest('[aria-setsize]');
+ const setsize = setEl ? parseInt(setEl.getAttribute('aria-setsize'), 10) : NaN;
+ return {
+ n: parseInt(el.getAttribute('data-tv3-menu'), 10),
+ text: (el.innerText || el.textContent || '').trim(),
+ nav: nav,
+ setsize: Number.isFinite(setsize) && setsize > 0 ? setsize : 0,
+ };
+ });
+}"""
+)
+
+# Whether the anchor (or its nearest aria-expanded ancestor) currently reports an OPEN list. Used to
+# gate the "close a stray open list" Escape: sending Escape with no menu open would bubble to and close
+# a surrounding dialog, so we only send it once a menu is confirmed open.
+_MENU_OPEN_JS = (
+ r"""(arg) => {"""
+ + _PIERCED_QUERY_JS
+ + r"""
+ const el = pQS(arg.sel) || (arg.el && arg.el.isConnected ? arg.el : null);
+ if (!el) return false;
+ const exp = el.getAttribute('aria-expanded') != null ? el : el.closest('[aria-expanded]');
+ return !!(exp && exp.getAttribute('aria-expanded') === 'true');
+}"""
+)
+
+# True when the anchor (or its combobox ancestor) declares aria-autocomplete list/both/inline -- the ARIA
+# contract for a combobox that searches as you type. It is the reaction signal for a searchable widget that
+# filtered to ZERO rows on an absent value (nothing new for _FIND_MENU_JS to count), which must still read
+# as a genuine no-match rather than fall through to a click-to-open enumeration.
+_DECLARES_SEARCH_AUTOCOMPLETE_JS = (
+ r"""(arg) => {"""
+ + _PIERCED_QUERY_JS
+ + r"""
+ const SEARCH = new Set(['list', 'both', 'inline']);
+ const read = (n) => (n.getAttribute('aria-autocomplete') || '').toLowerCase();
+ let el = pQS(arg.sel) || (arg.el && arg.el.isConnected ? arg.el : null);
+ if (!el) return false;
+ if (SEARCH.has(read(el))) return true;
+ const cb = el.closest('[aria-autocomplete]');
+ return !!(cb && SEARCH.has(read(cb)));
}"""
)
-# Page total for `group` text across one observe; per entry stays at 200 characters.
+# Page total for `group` text across one observe, counted at the 200-character display width of each
+# entry; the record retains up to the masking width, which Python masks and then caps to 200.
OBSERVE_GROUP_TEXT_TOTAL_CAP = 4000
+# Display width of each masked-then-capped field of the observe digest. Every render site reads its
+# width here, so the retain margin below is always sized for the widest window.
+OBSERVE_DISPLAY_WIDTHS = {"label": 140, "placeholder": 60, "value": 100, "invalid": 140, "group": 200, "text": 300}
+# Floor for the width the enumeration retains per field before Python masks and caps it. Widened per
+# call so the longest payload-minted URL fits whole after the widest display window.
+OBSERVE_RETAIN_WIDTH_MIN = 2000
+OBSERVE_FIELD_DISPLAY_MAX = max(OBSERVE_DISPLAY_WIDTHS.values())
# Raw DOM perception: collect visible interactive elements with a stable selector each.
# Elements without a natural selector get a data-tv3 marker so later actions can target them.
-_OBSERVE_JS = (
+_OBSERVE_JS_TEMPLATE = (
r"""
async () => {
+ // Field text is retained at this width and masked, then capped for display, in Python. Substituted
+ // per call from the payload refs: any minted URL that starts inside a display window fits whole.
+ const _RETAIN_WIDTH = __OBSERVE_RETAIN_WIDTH__;
const _GROUP_TEXT_TOTAL_CAP = """
+ str(OBSERVE_GROUP_TEXT_TOTAL_CAP)
+ r""";
@@ -2087,7 +2968,7 @@ async () => {
let textOnly = true;
try { for (const n of host.childNodes) { if (n.nodeType !== 3) { textOnly = false; break; } } } catch (e) { return ''; }
if (!textOnly) return '';
- return String(host.innerText || '').replace(/\s+/g, ' ').trim().slice(0, 140);
+ return String(host.innerText || '').replace(/\s+/g, ' ').trim().slice(0, _RETAIN_WIDTH);
};
// Controls inside a component that we could not name, split by CAUSE: these need different
// fixes, and one merged tally would send the follow-up after the wrong one.
@@ -2111,8 +2992,11 @@ async () => {
const fingerprint = (el) => {
try {
return [
- el.checked === true, el.type === 'password' ? '' : String(el.value || '').slice(0, 140), el.disabled === true,
+ // Sliced at the width the record retains: a change in any byte the rendered line depends on
+ // (its masking reads the whole retained value) must invalidate the record.
+ el.checked === true, el.type === 'password' ? '' : String(el.value || '').slice(0, _RETAIN_WIDTH), el.disabled === true,
el.getAttribute('aria-checked'), el.getAttribute('aria-selected'), el.getAttribute('aria-pressed'), el.getAttribute('aria-expanded'),
+ el.getAttribute('aria-valuenow'),
el.getAttribute('aria-label'), el.getAttribute('aria-labelledby'), el.getAttribute('title'), el.getAttribute('placeholder'),
el.getAttribute('aria-disabled'), el.readOnly === true, el.required === true, el.hidden === true, el.getAttribute('aria-hidden'),
].join('\u0001');
@@ -2294,7 +3178,8 @@ async () => {
}
if (!strongLabel) strongLabel = byId('aria-labelledby');
if (!strongLabel) strongLabel = (el.innerText || '').trim();
- if (!strongLabel && host) strongLabel = slottedText(el, host);
+ let slottedName = false;
+ if (!strongLabel && host) { strongLabel = slottedText(el, host); slottedName = !!strongLabel; }
// A text control the page itself hides from assistive tech, takes out of the tab order and
// leaves unnamed is one no person can reach; a non-zero box does not make it a field.
const isTextLike = el.tagName === 'TEXTAREA' || (el.tagName === 'INPUT' && _PHANTOM_TEXT_TYPES.test(String(el.type || '').toLowerCase()));
@@ -2341,7 +3226,10 @@ async () => {
mintedOn.push(minted);
}
}
- let label = (el.getAttribute('aria-label') || el.getAttribute('placeholder') || '').trim() || strongLabel;
+ // The placeholder ranks below every real name (strongLabel already starts with aria-label) and
+ // travels separately as a hint: a format placeholder ('dd/mm/yyyy') is what makes the value typeable.
+ const placeholder = (el.getAttribute('placeholder') || '').trim();
+ let label = strongLabel || placeholder;
if (!label) label = (el.type === 'password' ? '' : el.value || '').trim();
if (!label) label = (el.getAttribute('title') || '').trim();
const role = el.getAttribute('role');
@@ -2350,7 +3238,12 @@ async () => {
// back the raw attribute, so `type` there is a page-controlled string that reached the rendered
// line -- and a MIME type is noise to the model anyway.
const _typed = el.tagName === 'INPUT' || el.tagName === 'BUTTON' || el.tagName === 'SELECT';
- const rec = { i, tag: el.tagName.toLowerCase(), type: (_typed && el.type) || null, selector, label: label.slice(0, 140) };
+ // Label, placeholder and value are capped generously here, not at their display widths: each is
+ // masked for payload-minted signed URLs Python-side, which needs the WHOLE URL to match by
+ // provenance before the display cap lands. A tighter cap here would truncate the URL past
+ // recognition and leak its signing tail.
+ const rec = { i, tag: el.tagName.toLowerCase(), type: (_typed && el.type) || null, selector, label: label.slice(0, _RETAIN_WIDTH) };
+ if (placeholder && placeholder !== label) rec.placeholder = placeholder.slice(0, _RETAIN_WIDTH);
if (hidden) rec.hidden = true;
// A widget role is what the element IS -- a <div role="switch"> renders as a bare div otherwise,
// and the model cannot tell it from decoration. The role travels with its state below, or it is
@@ -2361,7 +3254,7 @@ async () => {
// element line for a selector that does not exist.
if (role && _WIDGET_ROLES.indexOf(String(role)) !== -1) rec.role = String(role);
if (el.tagName === 'SELECT') rec.options = Array.from(el.options).map((o) => o.value + '|' + o.text).slice(0, 60);
- if (el.type === 'password') { if (el.value) rec.value = '(hidden)'; } else if (el.value) rec.value = String(el.value).slice(0, 100);
+ if (el.type === 'password') { if (el.value) rec.value = '(hidden)'; } else if (el.value) rec.value = String(el.value).slice(0, _RETAIN_WIDTH);
// ARIA defines switch as a checkbox variant carrying the same aria-checked, so it belongs here.
if (el.type === 'checkbox' || el.type === 'radio') rec.checked = !!el.checked;
else if (role === 'checkbox' || role === 'radio' || role === 'switch') {
@@ -2375,7 +3268,7 @@ async () => {
if ((role === 'tab' || role === 'option') && (selected === 'true' || selected === 'false')) rec.selected = selected === 'true';
if (role === 'spinbutton') {
const now = el.getAttribute('aria-valuenow');
- if (now !== null && !rec.value) rec.value = String(now).slice(0, 100);
+ if (now !== null && !rec.value) rec.value = String(now).slice(0, _RETAIN_WIDTH);
}
if (el.getAttribute('aria-required') === 'true' || el.required) rec.required = true;
const isChoice = el.type === 'checkbox' || el.type === 'radio' || role === 'checkbox' || role === 'radio';
@@ -2386,7 +3279,7 @@ async () => {
// willValidate excludes readonly/disabled fields the agent cannot fix; password is excluded so
// validationMessage (which can echo the typed value) never leaks it.
else if (!isChoice && el.type !== 'password' && el.value && el.willValidate && !(el.form && el.form.noValidate) && el.validity && !el.validity.valid) {
- rec.invalid = (el.validationMessage || '').slice(0, 140) || true;
+ rec.invalid = (el.validationMessage || '').slice(0, _RETAIN_WIDTH) || true;
}
// Flag typeahead/autocomplete inputs so the model treats them as combobox fills instead of typing
// raw text that never registers as a valid selection (type() also auto-commits them). See _IS_AUTOCOMPLETE_JS.
@@ -2398,9 +3291,14 @@ async () => {
if (isChoice || strongLabel.length < 3) {
// The description is the last rung: it is routinely a per-field hint ("This field is
// required") shared by every field, which would name nothing and dedupe to nothing.
- const gt = (_groupText(el, isChoice) || byId('aria-describedby')).slice(0, 200);
- if (gt && gt.length > strongLabel.length && gt !== lastGroup && groupTotal + gt.length <= _GROUP_TEXT_TOTAL_CAP) {
- rec.group = gt;
+ // The record carries the text at the masking width; the budget, the dedupe and the
+ // name-vs-description comparison all stay at the 200-char display width.
+ const gtFull = (_groupText(el, isChoice) || byId('aria-describedby')).slice(0, _RETAIN_WIDTH);
+ const gt = gtFull.slice(0, 200);
+ // A slotted caption is compared at the 140 width it used to be stored at.
+ const nameLength = slottedName ? Math.min(strongLabel.length, 140) : strongLabel.length;
+ if (gt && gt.length > nameLength && gt !== lastGroup && groupTotal + gt.length <= _GROUP_TEXT_TOTAL_CAP) {
+ rec.group = gtFull;
lastGroup = gt;
groupTotal += gt.length;
}
@@ -2413,7 +3311,7 @@ async () => {
// A submit or button input is named by its caption, and a caption is what a refusal beside it
// repeats; a field's own control is the only thing a wrapper holds.
const captioned = rec.tag === 'input' && /^(?:submit|button|reset|image)$/.test(rec.type || '');
- if ((rec.tag === 'input' && !captioned) || rec.tag === 'select' || rec.tag === 'textarea') labelOfControl.set(el, rec.label.replace(/\s+/g, ' ').trim());
+ if ((rec.tag === 'input' && !captioned) || rec.tag === 'select' || rec.tag === 'textarea') labelOfControl.set(el, rec.label.slice(0, 140).replace(/\s+/g, ' ').trim());
out.push(rec);
elOfRec.set(rec, el);
stampOfRec.set(rec, { fp: fingerprint(el), anchor: lastAnchor && lastAnchor.sel === selector ? lastAnchor : null });
@@ -2529,13 +3427,18 @@ async () => {
// dump, so the digest stays bounded and can't regrow the context that transcript compaction
// bounds. All three carry page-controlled text at the same trust level as element labels.
const texts = [];
+ // The digest is deduped and budgeted at its 300-char display width, and `text` carries exactly that.
+ // An entry cut by that width also travels whole (at the masking width) in `textFull`, so Python can
+ // mask a minted URL in it before capping the line.
+ const fullText = new Map();
let textTotal = 0;
let textFull = false;
let textDropped = 0;
// `limit` is a cumulative reservation: a channel stops at its limit so the channels after it keep
// a floor of the 900 total instead of being starved by whichever channel ran first.
const pushText = (t, limit = 900) => {
- t = (t || '').replace(/\s+/g, ' ').trim().slice(0, 300);
+ const full = (t || '').replace(/\s+/g, ' ').trim().slice(0, _RETAIN_WIDTH);
+ t = full.slice(0, 300);
if (!t) return;
// Containment dedupe, richer message wins: an alert's text re-surfaces inside its heading's
// parent text, and a terse early entry ("Saved") must not suppress a later superset
@@ -2545,6 +3448,7 @@ async () => {
const keptTotal = kept.reduce((total, s) => total + s.length, 0);
if (keptTotal + t.length > limit) { textFull = textFull || limit >= 900; textDropped++; return; }
texts.length = 0; texts.push(...kept, t); textTotal = keptTotal + t.length;
+ fullText.set(t, full);
};
const visible = (el) => { const r = el.getBoundingClientRect(); return r.width > 0 && r.height > 0; };
// Isolated: a hostile page's throwing accessor (fingerprinting scripts poison innerText and
@@ -2622,7 +3526,8 @@ async () => {
// already built, so recognising them asks the page nothing.
const listedLabels = new Set();
for (const r of out) {
- const lb = (r.label || '').replace(/\s+/g, ' ').trim();
+ // Sliced to the label's display width: the messages below are compared at that width.
+ const lb = (r.label || '').slice(0, 140).replace(/\s+/g, ' ').trim();
if (lb) listedLabels.add(lb);
}
// Stricter than visible(): this channel's selector is broad and site chrome is routinely present
@@ -2768,19 +3673,31 @@ async () => {
}
} catch (e) { iframeInfo.total = 0; iframeInfo.inComponents = 0; iframeInfo.entries.length = 0; iframeInfo.unread = 0; iframeInfo.failed = true; }
- return JSON.stringify({ url: location.href, title: document.title, text: texts, textTruncated: textFull, textDropped: textDropped, iframes: iframeInfo, dropped: dropped, truncated: truncated, truncatedInComponents: truncatedInComponents, unnamedAnonymous: unnamedAnonymous, unnamedBudget: unnamedBudget, unnamedDuplicated: unnamedDuplicated, unnamedUnverifiable: unnamedUnverifiable, unnamedUnsafe: unnamedUnsafe, unreadableRoot: sawUnreadableRoot, undiscoveredRoots: undiscoveredRoots, rootCount: allRoots.length - 1, hiddenListed: hiddenListed, phantomDropped: phantomDropped, markersMinted: markersWritten, markersReused: markersReused, pageMutated: mutated, elements: out });
+ return JSON.stringify({ url: location.href, title: document.title, text: texts, textFull: texts.map((t) => { const f = fullText.get(t); return f && f !== t ? f : null; }), textTruncated: textFull, textDropped: textDropped, iframes: iframeInfo, dropped: dropped, truncated: truncated, truncatedInComponents: truncatedInComponents, unnamedAnonymous: unnamedAnonymous, unnamedBudget: unnamedBudget, unnamedDuplicated: unnamedDuplicated, unnamedUnverifiable: unnamedUnverifiable, unnamedUnsafe: unnamedUnsafe, unreadableRoot: sawUnreadableRoot, undiscoveredRoots: undiscoveredRoots, rootCount: allRoots.length - 1, hiddenListed: hiddenListed, phantomDropped: phantomDropped, markersMinted: markersWritten, markersReused: markersReused, pageMutated: mutated, elements: out });
}
"""
)
-def _menu_open_note(found: dict[str, Any], selector: str, *, clicked_row: bool = False) -> str:
- count = int(found.get("count") or 0)
+def observe_js(retain_width: int = OBSERVE_RETAIN_WIDTH_MIN) -> str:
+ return _OBSERVE_JS_TEMPLATE.replace("__OBSERVE_RETAIN_WIDTH__", str(int(retain_width)), 1)
+
+
+_OBSERVE_JS = observe_js()
+
+
+def _menu_mark_parts(options: list[dict[str, Any]], cap: int) -> list[str]:
parts = []
- for o in (found.get("options") or [])[:15]:
+ for o in (options or [])[:cap]:
# option texts are page-controlled and land in the LLM transcript — same sanitation as filenames
text = _DOWNLOAD_NOTICE_SANITIZE_RE.sub("", str(o.get("text", "")))
parts.append(f'[data-tv3-menu="{o.get("n")}"] {text!r}')
+ return parts
+
+
+def _menu_open_note(found: dict[str, Any], selector: str, *, clicked_row: bool = False) -> str:
+ count = int(found.get("count") or 0)
+ parts = _menu_mark_parts(found.get("options") or [], 15)
overflow = f" (+{count - len(parts)} more — re-observe for the full list)" if count > len(parts) else ""
# Naming the raw selector would contradict the next sentence when the caller IS a menu row:
# this note has just renumbered every data-tv3-menu, so the selector clicked to get here is one
@@ -2794,6 +3711,25 @@ def _menu_open_note(found: dict[str, Any], selector: str, *, clicked_row: bool =
)
+async def _categories_note(page: Any, selector: str) -> str | None:
+ # Enrichment for the typeahead no-match path only: never lets the classifier's own failure become
+ # the tool's failure, since a crash here would replace a real (if unhelpful) error with a worse one.
+ try:
+ found = await page.evaluate(_FIND_CATEGORIES_JS, {"field": selector})
+ except Exception:
+ return None
+ if not found or not found.get("count"):
+ return None
+ items = "; ".join(_menu_mark_parts(found.get("categories") or [], 8))
+ return (
+ f"Some rows near this field carry an expand affordance and may be categories whose options are "
+ f"nested rather than shown in the flat list: {items}. If one could contain your value, click its "
+ '[data-tv3-menu="N"] selector to reveal its options, then re-observe to confirm what the click '
+ "did before relying on it. These numbers are freshly assigned and change whenever the list "
+ "re-renders: act on the newest data-tv3-menu list, not an earlier one."
+ )
+
+
def _spec(
name: str, description: str, params: dict[str, Any], handler: Callable[[dict[str, Any]], Awaitable[ToolResult]]
) -> ToolSpec:
@@ -2836,32 +3772,186 @@ async def _upload_submit_delay() -> None:
await asyncio.sleep(random.uniform(_UPLOAD_SUBMIT_DELAY_BASE_S, _UPLOAD_SUBMIT_DELAY_BASE_S * 2))
-def build_browser_tools(
- page_provider: PageProvider,
- *,
- downloads_dir: str | None = None,
- organization_id: str | None = None,
- resolve_typed_text: Callable[[str], Any] | None = None,
- opaque_refs: OpaqueUrlRefs | None = None,
-) -> list[ToolSpec]:
- """Raw-browser tools that resolve their page from `page_provider` on every call."""
+# A genuine file upload dispatches at least one of these: the API call that mints the upload handle
+# and/or the write to storage. resource_type is limited to xhr/fetch so page analytics pings, image
+# beacons, navigations, and static asset loads never register as upload activity.
+_UPLOAD_ACTIVITY_METHODS = frozenset({"POST", "PUT", "PATCH"})
+_UPLOAD_ACTIVITY_RESOURCE_TYPES = frozenset({"xhr", "fetch"})
- def _mask_refs(text: str) -> str:
- # A signed payload URL masked to a token in the payload must not reappear verbatim through a
- # free-text emit surface (observe's url= line, get_html, a download error) and get retyped by
- # the model. Masking is by provenance: only URLs the payload masker minted are rewritten, so a
- # live-page URL the model reasons about is never touched. No refs (page-free) → identity.
- return opaque_refs.mask(text) if opaque_refs is not None else text
- def _resolve_text(text: str) -> str:
- # Workflow credential values reach the model only as secret placeholders; resolve them to the
- # real value at fill time (the same boundary the step engine uses). Fail open to the literal.
- if resolve_typed_text is None:
- return text
+class _UploadActivityProbe:
+ """Counts upload-like network dispatches during a file_upload: set_input_files populating the input
+ at the Playwright layer does not prove the site registered the file (post-navigation the change
+ handler may be unwired, so the site dispatches nothing). Counting request dispatch — not completion —
+ is the earliest signal that the site reacted at all; a dispatched-but-failed upload still counts."""
+
+ def __init__(self, page: Any) -> None:
+ self._page = page
+ self._count = 0
+
+ def _on_request(self, request: Any) -> None:
try:
- resolved = resolve_typed_text(text)
+ if (
+ request.method in _UPLOAD_ACTIVITY_METHODS
+ and str(request.resource_type).lower() in _UPLOAD_ACTIVITY_RESOURCE_TYPES
+ ):
+ self._count += 1
except Exception:
- LOG.warning("taskv3 typed-text resolution failed; typing the literal text", exc_info=True)
+ pass
+
+ def start(self) -> None:
+ try:
+ self._page.on("request", self._on_request)
+ except Exception:
+ LOG.info("taskv3 upload-activity probe could not attach", exc_info=True)
+
+ def stop(self) -> None:
+ try:
+ self._page.remove_listener("request", self._on_request)
+ except Exception:
+ pass
+
+ def saw_upload(self) -> bool:
+ return self._count > 0
+
+
+# Rendered text across the document and every open shadow root. Used as a before/after pair around
+# set_input_files: a filename that was absent and is now present could only have been written by the
+# site's own file-handling code, which is the one thing a silent no-op (or ambient network noise) can
+# never produce.
+_PAGE_TEXT_JS = (
+ r"""() => {
+ const _shadowRoots = """
+ + _SHADOW_ROOTS_JS
+ + r""";
+ let out = '';
+ for (const root of _shadowRoots(document)) {
+ try {
+ // Rendered text only: textContent would count hidden nodes, <script> and <style>. A shadow
+ // root has no innerText itself, so read each element child — but only rendered ones, since
+ // innerText on an element that is not rendered (a <style>, a hidden chip) is its textContent.
+ const tops = root === document ? [document.body] : Array.from(root.children);
+ for (const el of tops) {
+ if (!el || typeof el.innerText !== 'string') continue;
+ if (!(el.getClientRects && el.getClientRects().length > 0)) continue;
+ out += ' ' + el.innerText;
+ }
+ } catch (e) {}
+ }
+ return out;
+}"""
+)
+
+
+# Words a site uses when it names a file it refused. A veto only: a spurious match turns a confirmation
+# into a recoverable error, never the reverse; a rejection phrased outside this list is the known miss.
+_UPLOAD_REJECTION_WORDS = re.compile(
+ r"\b(error|invalid|reject\w*|unsupported|fail\w*|unsuccessful|exceed\w*|denied|blocked|declined|removed|"
+ r"discarded|corrupt\w*|wrong|issue\w*|too\s+(large|big)|must be|unable|"
+ r"(not|never|won['’]t|will not|do not)(\s+\w+){0,2}\s+(allow|support|accept|upload|permit|attach|save)\w*|"
+ r"(can|could|would|is|was|do|did|does|has|have)\s?(n['’]?|['’])t|cannot|try(\s+\w+){0,2}\s+again)\b",
+ re.IGNORECASE,
+)
+_FILENAME_MENTION_CHARS = 240
+
+
+async def _page_rendered_text(page: Any) -> str | None:
+ """The page's rendered text across the document and open shadow roots; None when it cannot be read."""
+ try:
+ text = await page.evaluate(_PAGE_TEXT_JS)
+ except Exception:
+ LOG.info("taskv3 file_upload page-text readback failed", exc_info=True)
+ return None
+ return text if isinstance(text, str) else None
+
+
+def _mentions_filename(text: str, filename: str) -> bool:
+ """Whole-token mention of the staged file's full name (the browser reports exactly this basename as
+ File.name, so it is what a site renders). A name joined to more name characters ("old-cv.pdf",
+ "cv.pdf.bak") is a different file, not this one."""
+ name = os.path.basename(filename).strip()
+ if not name:
+ return False
+ return re.search(r"(?<![\w.\-])" + re.escape(name) + r"(?![\w.\-])", text, re.IGNORECASE) is not None
+
+
+def _newly_rendered_lines(before: str, after: str) -> list[str]:
+ seen = {line.strip() for line in before.splitlines()}
+ return [line.strip() for line in after.splitlines() if line.strip() and line.strip() not in seen]
+
+
+async def _input_holds_file(el: Any) -> bool:
+ """Playwright-layer readback that set_input_files populated the control — proves the file attached to
+ the input element, not that the site registered it. Fail-open: an unreadable control must never turn a
+ real upload into a false negative."""
+ try:
+ count = await el.evaluate("e => (e && e.files) ? e.files.length : 0")
+ return bool(count) and int(count) > 0
+ except Exception:
+ LOG.info("taskv3 file-input populate readback failed, assuming populated", exc_info=True)
+ return True
+
+
+# Counts fields holding in-progress state a reload would discard, piercing shadow roots. Unlike the
+# pre-submit form serializer it COUNTS file inputs (files.length > 0) — an attached file is exactly the
+# progress the same-URL reload guard exists to protect — and it skips hidden fields (site-managed, always
+# present) so their presence alone never trips the guard.
+_FILLED_STATE_JS = (
+ "(() => { const _q = " + _ROOT_QUERY_JS + "; let n = 0; for (const el of _q.all('input,textarea,select')) { "
+ "const t = (el.type || '').toLowerCase(); "
+ "if (t === 'hidden') continue; "
+ "if (t === 'file') { if (el.files && el.files.length > 0) n++; continue; } "
+ "if (t === 'checkbox' || t === 'radio') { if (el.checked) n++; continue; } "
+ "if (el.value) n++; } return n; })()"
+)
+
+
+async def _count_filled_fields(page: Any) -> int:
+ """How many fields hold state a reload would wipe (incl. an attached file). Fail-open to 0: a probe
+ failure must never let this guard block a navigation."""
+ try:
+ return int(await page.evaluate(_FILLED_STATE_JS))
+ except Exception:
+ LOG.info("taskv3 filled-state probe failed, treating page as empty", exc_info=True)
+ return 0
+
+
+def build_browser_tools(
+ page_provider: PageProvider,
+ *,
+ downloads_dir: str | None = None,
+ organization_id: str | None = None,
+ resolve_typed_text: Callable[[str], Any] | None = None,
+ opaque_refs: OpaqueUrlRefs | None = None,
+ vision_enabled: bool = True,
+) -> list[ToolSpec]:
+ """Raw-browser tools that resolve their page from `page_provider` on every call.
+
+ `vision_enabled` gates the on-demand `look` tool: it is offered only when the run's model can
+ actually receive the screenshot it produces (a non-vision model drops it before the request), so
+ the tool is never advertised to a model that cannot see its output."""
+
+ def _mask_refs(text: str) -> str:
+ # A signed payload URL masked to a token in the payload must not reappear verbatim through a
+ # free-text emit surface (observe's url= line, get_html, a download error) and get retyped by
+ # the model. Masking is by provenance: only URLs the payload masker minted are rewritten, so a
+ # live-page URL the model reasons about is never touched. No refs (page-free) → identity.
+ return opaque_refs.mask(text) if opaque_refs is not None else text
+
+ def _observe_js() -> str:
+ # Retain exactly what the masker can recognise past the widest display window.
+ window = opaque_url_echo_window(opaque_refs.refs.values()) if opaque_refs is not None else 0
+ return observe_js(max(OBSERVE_RETAIN_WIDTH_MIN, OBSERVE_FIELD_DISPLAY_MAX + window))
+
+ def _resolve_text(text: str) -> str:
+ # Workflow credential values reach the model only as secret placeholders; resolve them to the
+ # real value at fill time (the same boundary the step engine uses). Fail open to the literal.
+ if resolve_typed_text is None:
+ return text
+ try:
+ resolved = resolve_typed_text(text)
+ except Exception:
+ LOG.warning("taskv3 typed-text resolution failed; typing the literal text", exc_info=True)
return text
return resolved if isinstance(resolved, str) else text
@@ -2871,6 +3961,66 @@ def build_browser_tools(
# dispatcher or a twice-resolving handler must replace this handoff, not reuse it.
_prefetched_page: list[Any] = []
+ # Per-run set-of-marks from the most recent look(): mark index -> {handle, tag, label}. A
+ # fresh look replaces it (marks renumber), and act-by-mark resolves mark=N against it at act time.
+ _look_manifest: dict[int, dict[str, Any]] = {}
+ # Opaque-id aliases, run-scoped and stable: the same emitted selector maps to the same alias for
+ # the whole run, like opaque_url_ tokens, so the model never handles the raw identifier.
+ _alias_for_selector: dict[str, str] = {}
+ _selector_for_alias: dict[str, str] = {}
+
+ def _alias_for(selector: str) -> str:
+ if not _OPAQUE_ID_RUN_RE.search(selector):
+ return selector
+ alias = _alias_for_selector.get(selector)
+ if alias is None:
+ alias = f'[data-tv3-ref="{len(_alias_for_selector) + 1}"]'
+ _alias_for_selector[selector] = alias
+ _selector_for_alias[alias] = selector
+ return alias
+
+ def _mask_aliases(text: str) -> str:
+ # Real selector -> alias, and a WHOLE `id="<raw>"` attribute in markup -> the alias attribute.
+ # Anchored on purpose: the raw id also appears as a substring of other attributes, hrefs and
+ # page values, and rewriting those would corrupt what the model reads. Longest selector first
+ # so a host-anchored selector is not half-masked by its host's own alias.
+ for real, alias in sorted(_alias_for_selector.items(), key=lambda kv: -len(kv[0])):
+ if real in text:
+ text = text.replace(real, alias)
+ for m in _SELECTOR_ID_COMPONENTS_RE.finditer(real):
+ attr = "id" if m.group(3) else m.group(1)
+ raw = m.group(4) if m.group(3) else m.group(2)
+ if raw and _OPAQUE_ID_RUN_RE.search(raw) and raw in text:
+ text = re.sub(r"(?<=\s)" + attr + '="' + re.escape(raw) + '"', alias[1:-1], text)
+ return text
+
+ def _with_alias_resolution(handler: ToolHandler) -> ToolHandler:
+ async def wrapped(args: dict[str, Any]) -> ToolResult:
+ selector = args.get("selector")
+ alias_match = _ALIAS_SELECTOR_RE.match(selector) if isinstance(selector, str) else None
+ if alias_match:
+ real = _selector_for_alias.get(f'[data-tv3-ref="{alias_match.group(1)}"]')
+ if real is None:
+ return ToolResult.error(
+ f"{alias_match.group(0).strip()} is not a selector from the latest observe — re-observe and "
+ "use a selector from the new observation"
+ )
+ args = {**args, "selector": real}
+ result = await handler(args)
+ if _alias_for_selector and isinstance(result.content, str):
+ masked = _mask_aliases(result.content)
+ if masked != result.content:
+ result = ToolResult(result.status, masked, result.data, result.screenshots)
+ return result
+
+ return wrapped
+
+ _look_count = [0] # per-run look() invocations, capped at _LOOK_MAX_PER_RUN
+ # The (canonical URL, filled-field count) of the last same-URL reload the destructive-nav guard
+ # refused. A repeat to that URL confirms intent and is allowed — but only if the at-risk state has
+ # not GROWN since (else a file attached after the refusal would be wiped by a stale confirmation).
+ _reload_confirm_pending: list[tuple[str, int] | None] = [None]
+
async def _resolve_page() -> tuple[Any, ToolResult | None]:
# Single-use handoff from the preflight wrapper so a preflighted call resolves the page
# once, not twice (each resolution is a must_get_working_page with its recovery path).
@@ -2896,7 +4046,7 @@ def build_browser_tools(
if error is not None:
return error
# Bound the one perception call so a wedged page can't hang the turn indefinitely.
- raw = await asyncio.wait_for(page.evaluate(_OBSERVE_JS), timeout=30)
+ raw = await asyncio.wait_for(page.evaluate(_observe_js()), timeout=30)
data = json.loads(raw) if isinstance(raw, str) else raw
elements = data.get("elements", [])
omitted_anonymous = data.get("unnamedAnonymous") or 0
@@ -2945,8 +4095,18 @@ def build_browser_tools(
lines.append(
f"note: {phantom_dropped} unreachable input(s) omitted (aria-hidden, out of the tab order, unlabeled)"
)
- for t in data.get("text") or []:
- lines.append(f"text: {t!r}")
+
+ # Mask before capping: the masker matches a payload-minted URL by provenance over its WHOLE
+ # text, so a display cap applied first (as the JS once did) leaves a fragment it cannot
+ # recognise, signing tail included.
+ def _field(raw: object, width: int) -> str:
+ return _mask_refs(str(raw))[:width]
+
+ texts = data.get("text") or []
+ texts_full = data.get("textFull") or []
+ for i, t in enumerate(texts):
+ full = texts_full[i] if i < len(texts_full) else None
+ lines.append(f"text: {_field(full or t, OBSERVE_DISPLAY_WIDTHS['text'])!r}")
text_dropped = data.get("textDropped") or 0
if text_dropped:
# A capped digest must say it was capped: silently showing the first N reads as "that is all".
@@ -3051,10 +4211,13 @@ def build_browser_tools(
f"note: {omitted_in_components} control(s) inside components are not listed because we "
f"have no selector that identifies them: {'; '.join(why)}"
)
+
for e in elements:
extra = ""
if e.get("value"):
- extra += f" value={e['value']!r}"
+ extra += f" value={_field(e['value'], OBSERVE_DISPLAY_WIDTHS['value'])!r}"
+ if e.get("placeholder"):
+ extra += f" placeholder={_field(e['placeholder'], OBSERVE_DISPLAY_WIDTHS['placeholder'])!r}"
if e.get("options"):
extra += f" options={e['options']}"
if e.get("checked") is not None:
@@ -3066,7 +4229,11 @@ def build_browser_tools(
if e.get("required"):
extra += " *required"
if e.get("invalid"):
- extra += " *invalid" if e["invalid"] is True else f" *invalid={e['invalid']!r}"
+ extra += (
+ " *invalid"
+ if e["invalid"] is True
+ else f" *invalid={_field(e['invalid'], OBSERVE_DISPLAY_WIDTHS['invalid'])!r}"
+ )
if e.get("autocomplete"):
extra += " [autocomplete→use select_combobox]"
if e.get("hidden"):
@@ -3077,7 +4244,7 @@ def build_browser_tools(
else:
extra += " [hidden-native: styled proxy; click acts on it directly]"
if e.get("group"):
- extra += f" group={e['group']!r}"
+ extra += f" group={_field(e['group'], OBSERVE_DISPLAY_WIDTHS['group'])!r}"
# INVARIANT for this line and every line above it: no page-controlled byte reaches the
# digest un-escaped, and the header's count and the number of element lines come from the
# same list. Everything else here is either repr'd or a literal. `type` is the trap --
@@ -3090,7 +4257,10 @@ def build_browser_tools(
kind += "/" + _digest_token(e["type"], 40)
elif e.get("role"):
kind += "/" + _digest_token(e["role"], 40)
- lines.append(f"[{e['selector']}] {kind} {e.get('label', '')!r}{extra}")
+ lines.append(
+ f"[{_alias_for(e['selector'])}] {kind} "
+ f"{_field(e.get('label', ''), OBSERVE_DISPLAY_WIDTHS['label'])!r}{extra}"
+ )
# Counts only, for the per-call log record: every perception change that alters only what
# this function renders is otherwise invisible to production telemetry.
summary = {
@@ -3228,6 +4398,37 @@ def build_browser_tools(
element = None
return {"sel": selector, "el": element}
+ async def _resolve_mirrored_host_control(page: Any, selector: str) -> str:
+ # Only a single compound selector can name a host by mistake; a composed (host-anchored) one
+ # already points inside a root and a marker selector names exactly what observe marked.
+ # Only a selector that names no tag can land on a host by mistake; a tag-qualified one already
+ # says which element it means, so the page-wide walk is skipped for it.
+ stripped = selector.strip()
+ if (
+ not stripped.startswith(("#", "["))
+ or " " in _TV3_QUOTED_VALUE_RE.sub('""', stripped)
+ or _TV3_MARKER_SELECTOR_RE.match(stripped)
+ ):
+ return selector
+ try:
+ named = await page.evaluate(_MIRRORED_HOST_CONTROL_JS, selector)
+ except Exception:
+ return selector
+ if isinstance(named, str) and named:
+ LOG.debug(
+ "taskv3 selector resolved to a shadow host; acting on its mirrored control",
+ selector=selector,
+ control=named,
+ )
+ return named
+ return selector
+
+ async def _post_match_count(page: Any, selector: str) -> int:
+ try:
+ return await page.locator(selector).count()
+ except Exception:
+ return 1 # count unavailable → do not block, mirroring _marker_matches' fail-open
+
async def _ambiguous_selector_error(page: Any, selector: str) -> ToolResult | None:
# A host-anchored selector straddles a shadow boundary, which the per-root marker count
# cannot see through; the executor's own engine can, so it supplies the count. Playwright's
@@ -3283,6 +4484,7 @@ def build_browser_tools(
sel_baseline = pre.get("optSel") or ""
kids_baseline = pre.get("optKids")
height_baseline = pre.get("optH")
+ vis_baseline = pre.get("optVis")
def _committed_state(after: dict[str, Any]) -> bool:
return bool(after.get("optState")) and after.get("optState") != baseline
@@ -3294,15 +4496,21 @@ def build_browser_tools(
def _grew(after: dict[str, Any]) -> bool:
# The row got bigger of its own accord, which is the one shape where "it committed"
- # has a competitor. Height as well as child count, because a row whose single wrapper
- # is REPLACED by an expanded one keeps its count and still grows taller.
+ # has a competitor. Child count, height, or visible descendant rows: a category whose
+ # leaves pre-exist hidden and are revealed on click keeps its child COUNT and may keep
+ # its height, but its visible descendant row count rises — measured within the clicked
+ # row, so a sibling reveal (a real commit that also shows peers) does not trip it.
def _up(now: Any, before: Any, by: int) -> bool:
ok = (int, float)
if isinstance(now, bool) or isinstance(before, bool):
return False
return isinstance(now, ok) and isinstance(before, ok) and before >= 0 and now - before > by
- return _up(after.get("optKids"), kids_baseline, 0) or _up(after.get("optH"), height_baseline, 2)
+ return (
+ _up(after.get("optKids"), kids_baseline, 0)
+ or _up(after.get("optH"), height_baseline, 2)
+ or _up(after.get("optVis"), vis_baseline, 0)
+ )
async def _state_holds(state: str) -> tuple[dict[str, Any] | None, str | None]:
# A real commit settles; self-updating content (a countdown, a live price) keeps
@@ -3456,7 +4664,9 @@ def build_browser_tools(
page, error = await _resolve_page()
if error is not None:
return error
- selector = args["selector"]
+ selector = args.get("selector")
+ if not selector:
+ return ToolResult.error("click needs a selector, or mark=N from the last look().")
if _TV3_MARKER_SELECTOR_RE.match(selector.strip()):
matches = await _marker_matches(page, selector)
if matches == 0:
@@ -3505,7 +4715,7 @@ def build_browser_tools(
# behind describes the row before the hover, so the hover's own doing -- an
# aria-selected mark, a row-hover toolbar that grows the row -- reads as the
# click's.
- for key in ("optSel", "optKids", "optH"):
+ for key in ("optSel", "optKids", "optH", "optVis"):
if key in hovered:
pre[key] = hovered[key]
except Exception:
@@ -3521,6 +4731,17 @@ def build_browser_tools(
# One resolution for the whole pre-click phase: these run back to back with no mutation
# between them, so re-asking the executor per probe would only buy round trips.
pre_click_arg = await _probe_arg(page, selector)
+ # Only a control inside a component can have a slotted label; a light-DOM click keeps its
+ # single round trip.
+ reach_pre = None
+ try:
+ if await page.evaluate(_IN_COMPONENT_JS, pre_click_arg):
+ reach_pre = await page.evaluate(_TYPE_TARGET_PROBE_JS, pre_click_arg)
+ except Exception:
+ reach_pre = None
+ if isinstance(reach_pre, dict) and reach_pre.get("exists") and reach_pre.get("disabled"):
+ return ToolResult.error(f"{selector} is disabled — it cannot be clicked until the page enables it")
+ slotted_label = isinstance(reach_pre, dict) and bool(reach_pre.get("slotted")) and not reach_pre.get("occluded")
try:
skin_probe = await page.evaluate(_SKINNED_CHECKBOX_PROBE_JS, pre_click_arg)
except Exception:
@@ -3592,7 +4813,16 @@ def build_browser_tools(
base = f"clicked {selector} (hidden native control, toggled directly) — now at {await _url(page)}"
else:
try:
- await page.click(selector, timeout=15000)
+ await page.evaluate(_CLICK_SAME_DOC_PLANT_JS)
+ except Exception:
+ pass
+ try:
+ if slotted_label:
+ # The composed-tree probe already answered: the only thing "over" this control is its
+ # own slotted label, which the driver's containment check would wait 15s to reject.
+ await page.click(selector, timeout=15000, force=True)
+ else:
+ await page.click(selector, timeout=15000)
except Exception as e:
gone = False
try:
@@ -3617,7 +4847,33 @@ def build_browser_tools(
# own open listbox. Name the occluder rather than re-raise a bare Page.click Timeout.
if reach_probe and reach_probe.get("occluded"):
return _covered_error(selector, reach_probe.get("occluder"), verb="clicked")
- raise
+ # A URL is the wrong question (pushState moves it without leaving the page); the token
+ # planted before the click answers "is this still the same document" exactly.
+ try:
+ same_document = bool(await page.evaluate(_CLICK_SAME_DOC_CHECK_JS))
+ except Exception:
+ same_document = False
+ # Only the driver's own hit-target refusal is retried: any other failure (a download or
+ # navigation the click started, a detached node) keeps its original error.
+ intercepted = "intercepts pointer events" in str(e)
+ if (
+ intercepted
+ and same_document
+ and reach_probe
+ and reach_probe.get("exists")
+ and not reach_probe.get("disabled")
+ ):
+ # The driver's hit-target check reads DOM containment, so a control whose visible
+ # label is slotted into its shadow tree reads as intercepted by its own label. The
+ # composed-tree probe just said nothing covers it, so the click a person makes lands
+ # on it; dispatch that click at the same point without the containment check.
+ try:
+ await page.locator(selector).first.wait_for(state="visible", timeout=3000)
+ await page.click(selector, timeout=5000, force=True)
+ except Exception:
+ raise e from None
+ else:
+ raise
base = f"clicked {selector} — now at {await _url(page)}"
# url_after vs url_before is the real page-transition signal the shadow net-progress ledger
@@ -3634,13 +4890,26 @@ def build_browser_tools(
checked_after = await page.evaluate(_CHECKBOX_CHECKED_JS, await _probe_arg(page, selector))
except Exception:
checked_after = None
- if checked_after is None:
- return ToolResult.ok(
- f"{base} — the control left the page after the click, so its state could not be "
- "verified; re-observe before relying on it",
- data=transition_data,
- )
- if checked_after == checked_before:
+ matches = await _post_match_count(page, selector)
+ post_state = {"checked": checked_after} if checked_after is not None else None
+ verdict = _classify_commit({"checked": checked_before}, matches, post_state)
+ if verdict is CommitStatus.UNVERIFIED:
+ if post_state is None:
+ return ToolResult.ok(
+ f"{base} — the control left the page after the click, so its state could not be "
+ "verified; re-observe before relying on it",
+ data=transition_data,
+ )
+ if matches != 1:
+ return ToolResult.ok(
+ f"{base} — it re-resolved to {matches} elements after the click, so its state could "
+ "not be verified; re-observe before relying on it",
+ data=transition_data,
+ )
+ # Readable, singular post-click state but no pre-click baseline to diff against (the
+ # pre-read raced): as before the unified verdict, fall through to the ordinary post path
+ # rather than claim the control left the page.
+ if verdict is CommitStatus.DID_NOT_COMMIT:
return ToolResult.error(
f"click on {selector} did NOT commit: the control still reads checked={checked_after!r} — "
"the styled proxy may not sync from its hidden control; re-observe and act on the visible "
@@ -3754,6 +5023,8 @@ def build_browser_tools(
# surfaced (an ordinary field, or nothing matched); committed is None when a suggestion was
# clicked but no value landed.
best_txt: str | None = None
+ from_focus = False
+ declared: list[str] = []
for _ in range(rounds):
await asyncio.sleep(0.4)
try:
@@ -3766,12 +5037,30 @@ def build_browser_tools(
found = None
if isinstance(found, dict) and found.get("text"):
best_txt = str(found["text"])
+ from_focus = bool(found.get("fromFocus"))
+ declared = [str(v) for v in (found.get("declared") or []) if isinstance(v, str)]
break
if not best_txt:
return None, None, False
# Click the tagged best row. If the list re-rendered and dropped the tag, re-find (re-tag the
# current best) and click once more — never blind-press ArrowDown/Enter, which would commit
# whichever row the widget happens to highlight rather than the one we actually scored.
+ # A pick from a focus-opened list is verified under the pick contract, which needs the hidden
+ # values as they were BEFORE the click so a stale leftover cannot read as the commit.
+ # Captured before ANY click: a re-find after a failed first click may land on a focus-revealed
+ # row, and the pick contract it is verified under needs the state as it was before the click.
+ pre_hidden: list[str] = []
+ pre_value = value
+ try:
+ raw_hidden = await page.locator(selector).first.evaluate(_HIDDEN_VALUES_JS, timeout=2000)
+ if isinstance(raw_hidden, list):
+ pre_hidden = [str(v) for v in raw_hidden if isinstance(v, str)]
+ except Exception:
+ pre_hidden = []
+ try:
+ pre_value = str(await page.locator(selector).first.input_value(timeout=2000))
+ except Exception:
+ pre_value = value
clicked = False
try:
await page.click('[data-tv3-sugg="1"]', timeout=3000)
@@ -3784,6 +5073,8 @@ def build_browser_tools(
)
if isinstance(refound, dict) and refound.get("text"):
best_txt = str(refound["text"])
+ from_focus = bool(refound.get("fromFocus"))
+ declared = [str(v) for v in (refound.get("declared") or []) if isinstance(v, str)]
await page.click('[data-tv3-sugg="1"]', timeout=3000)
clicked = True
except Exception:
@@ -3795,12 +5086,17 @@ def build_browser_tools(
await asyncio.sleep(0.3)
readable = False
try:
+ # A row the FOCUS click revealed was offered, not filtered: verify it under the pick
+ # contract (the value must BE the chosen label), not the typeahead's change-based one.
read = await page.evaluate(
_VERIFY_COMMIT_JS,
{
"field": selector,
- "typed": value,
+ "typed": pre_value if from_focus else value,
"chosen": best_txt,
+ "noSuggestionList": from_focus,
+ "preHidden": pre_hidden,
+ "chosenValues": declared,
"el": (await _probe_arg(page, selector))["el"],
},
)
@@ -3816,18 +5112,28 @@ def build_browser_tools(
page: Any, selector: str, value: str, rounds: int
) -> tuple[str | None, str | None, bool]:
# Keystroke-type (so a widget's async suggestion fetch fires on real key events). Snapshot the
- # visible DOM just before typing so the finder treats only NEW/reacting nodes as suggestions —
- # static page text that merely shares a word with the value can't be mistaken for one.
- focused, occluder = await _focus_for_typing(page, selector)
- if not focused:
- raise _FieldCovered(selector, occluder)
- await page.fill(selector, "", timeout=15000)
+ # visible DOM BEFORE the focus click, not just before typing: a widget that opens its full list on
+ # focus and then filters it in place keeps the same row nodes, so a snapshot taken after the click
+ # marks every option as pre-existing and the reaction gate rejects the rows the keystrokes kept.
+ # Static page text that merely shares a word with the value is still excluded — it was visible
+ # before the click too.
presnapshot_ok = True
try:
await page.evaluate(_PRESNAPSHOT_JS)
except Exception:
presnapshot_ok = False
LOG.info("taskv3 typeahead pre-snapshot failed; skipping suggestion probe", selector=selector)
+ focused, occluder = await _focus_for_typing(page, selector)
+ if not focused:
+ raise _FieldCovered(selector, occluder)
+ if presnapshot_ok:
+ # Focus may reveal help text or a validation note as well as a menu; only rows of a list
+ # are a reaction the finder may pick from, so everything else focus revealed is marked too.
+ try:
+ await page.evaluate(_FOCUS_SNAPSHOT_JS, await _probe_arg(page, selector))
+ except Exception:
+ pass
+ await page.fill(selector, "", timeout=15000)
await page.type(selector, value, delay=15, timeout=15000)
if not presnapshot_ok:
# Without the pre-snapshot the reaction-gate can't tell a new suggestion from static page
@@ -3836,6 +5142,20 @@ def build_browser_tools(
return None, None, False
return await _commit_typeahead(page, selector, value, rounds)
+ async def _typeahead_commit_verdict(
+ page: Any, selector: str, committed: str | None, readable: bool
+ ) -> tuple[CommitStatus, int]:
+ # Route the typeahead's own commit truth through the unified classifier so the site gains INV-1
+ # (a commit read off n≠1 → unverified) and INV-2 (unreadable → unverified) for free. `committed` (the
+ # token-overlap result of _VERIFY_COMMIT_JS) is the value dimension the classifier cannot compute
+ # itself, so it is handed in as committed_value; behavior on a single stable element is unchanged.
+ matches = await _post_match_count(page, selector)
+ # post carries the READABILITY dimension (INV-2), committed_value the value dimension. A field
+ # read back empty is readable ("" has state) and did-not-commit; only an unreadable field (read
+ # returned null → readable False) is INV-2 unverified. `committed or ""` keeps that split clean.
+ post = {"value": committed or ""} if readable else None
+ return _classify_commit(None, matches, post, committed_value=bool(committed)), matches
+
# Input kinds that are never typeaheads — skip the suggestion probe (and its latency) for these.
# `textarea` is included: free-text boxes never render a typeahead and would just pay the probe tax.
_NON_TYPEAHEAD_TYPES = frozenset(
@@ -3887,10 +5207,13 @@ def build_browser_tools(
page, error = await _resolve_page()
if error is not None:
return error
- selector = args["selector"]
+ selector = args.get("selector")
+ if not selector:
+ return ToolResult.error("type needs a selector, or mark=N from the last look().")
ambiguous = await _ambiguous_selector_error(page, selector)
if ambiguous is not None:
return ambiguous
+ selector = await _resolve_mirrored_host_control(page, selector)
text = _resolve_text(args.get("text", ""))
press_enter = args.get("press_enter")
clear = args.get("clear", True)
@@ -3908,24 +5231,40 @@ def build_browser_tools(
return _covered_error(exc.selector, exc.occluder)
except _FieldNotEditable as exc:
return _not_editable_error(exc)
- if opt_txt and committed:
- return ToolResult.ok(
- f"typed into {selector}; it is a typeahead — selected {opt_txt!r} (committed value: {committed!r})"
- )
- if opt_txt and not committed:
- # The verifier pierces open roots and also reads the element the executor resolved,
- # so inside a component the failure is established rather than guessed. A list portaled
- # elsewhere, or a field in a closed root, is still beyond both -- and that is exactly
- # what the read reports by returning nothing, so the softening follows the read.
- why = None if readable else await _unverifiable_because(page, selector)
- if why:
+ if opt_txt:
+ verdict, matches = await _typeahead_commit_verdict(page, selector, committed, readable)
+ if verdict is CommitStatus.OK:
+ return ToolResult.ok(
+ f"typed into {selector}; it is a typeahead — selected {opt_txt!r} "
+ f"(committed value: {committed!r})"
+ )
+ if verdict is CommitStatus.UNVERIFIED and matches != 1:
+ # INV-1: the field re-resolved to n≠1 after the click (remounted or now ambiguous), so
+ # there is no stable element to read the commit off — soft, not a false did-not-commit.
return ToolResult.ok(
- f"clicked suggestion {opt_txt!r} for {selector}; {why}, so the commit could not "
- "be verified — re-observe to confirm the value before relying on it"
+ f"clicked suggestion {opt_txt!r} for {selector}, but it re-resolved to {matches} "
+ "elements so the commit could not be verified — re-observe to confirm the value "
+ "before relying on it"
+ )
+ if verdict is CommitStatus.UNVERIFIED:
+ # INV-2 (unreadable). The verifier pierces open roots and also reads the element the
+ # executor resolved, so inside a component the failure is established rather than
+ # guessed. A list portaled elsewhere, or a field in a closed root, is still beyond both
+ # -- and that is exactly what the read reports by returning nothing, so the softening
+ # follows the read.
+ why = await _unverifiable_because(page, selector)
+ if why:
+ return ToolResult.ok(
+ f"clicked suggestion {opt_txt!r} for {selector}; {why}, so the commit could not "
+ "be verified — re-observe to confirm the value before relying on it"
+ )
+ return ToolResult.error(
+ f"clicked suggestion {opt_txt!r} for {selector} but it did not commit — the field is "
+ "NOT filled; re-observe and retry, do not proceed"
)
- # A suggestion surfaced but the field did not accept it — the field is NOT filled. Return
- # an error so a batched turn halts here (the loop stops the rest of the batch on error)
- # instead of proceeding — e.g. to a queued submit — on an uncommitted field.
+ # DID_NOT_COMMIT: a suggestion surfaced but the field did not accept it — the field is NOT
+ # filled. Return an error so a batched turn halts here (the loop stops the rest of the batch
+ # on error) instead of proceeding — e.g. to a queued submit — on an uncommitted field.
return ToolResult.error(
f"clicked suggestion {opt_txt!r} for {selector} but it did not commit — the field is NOT "
"filled; re-observe and retry, do not proceed"
@@ -3959,6 +5298,319 @@ def build_browser_tools(
await page.press(selector, "Enter")
return ToolResult.ok(f"typed into {selector}")
+ async def _anchor_typeable(page: Any, selector: str) -> bool:
+ # Fail-open on a probe error: a transient evaluate failure must not flip a valid typeahead into
+ # a refusal (the far more common caller is select_combobox, whose contract is to type).
+ try:
+ return bool(await page.evaluate(_ANCHOR_TYPEABLE_JS, await _probe_arg(page, selector)))
+ except Exception:
+ return True
+
+ async def _open_observe_pick(page: Any, selector: str, value: str, *, close_open_menu: bool = False) -> ToolResult:
+ # Commit a click-to-open single-select in ONE call: open the list, enumerate the option rows the
+ # click rendered (v3's own _FIND_MENU_JS tags them data-tv3-menu="N"), deterministically pick the
+ # match, click it, and VERIFY — reusing the same commit-verify contract as the typeahead path.
+ # This is the branch v3 lacked: a non-searchable react-select (a real <input> that never filters)
+ # and a non-typeable button/div anchor both land here. When no deterministic match is found the
+ # tool returns a truthful did-not-commit AND the observed options, so the model resolves a
+ # genuinely unexpected widget by sight (look()/act-by-mark) — never a blind text-LLM guess.
+ if close_open_menu:
+ # A prior keystroke attempt may have opened this widget's list; close it so the pre-snapshot
+ # captures the CLOSED page and _FIND_MENU_JS counts only rows THIS open-click renders. Escape
+ # is sent ONLY once a menu is confirmed open (aria-expanded=true) — a stray Escape with nothing
+ # open would bubble to and close a surrounding dialog, discarding the form. If the widget does
+ # not expose aria-expanded, we skip Escape and let the reopen self-heal below handle a toggle.
+ try:
+ menu_open = bool(await page.evaluate(_MENU_OPEN_JS, await _probe_arg(page, selector)))
+ except Exception:
+ menu_open = False
+ if menu_open:
+ try:
+ await page.keyboard.press("Escape")
+ await asyncio.sleep(0.1)
+ except Exception:
+ pass
+
+ async def _open_and_enumerate() -> tuple[dict[str, Any] | None, ToolResult | None]:
+ try:
+ await page.evaluate(_PRESNAPSHOT_JS)
+ except Exception:
+ return None, ToolResult.error(
+ f"could not snapshot the page to open {selector}'s option list — the field is NOT "
+ "filled; re-observe, then click the control and pick the option you want"
+ )
+ try:
+ # 5s, not the 15s a routine click waits: the control is already present (we just typed
+ # into it, or it is a visible button), so it opens at once — a long wait here only delays
+ # the error on a field that unmounted itself, which must fail loudly, not slowly.
+ await page.click(selector, timeout=5000)
+ except Exception:
+ return None, ToolResult.error(
+ f"could not click {selector} to open its option list — the field is NOT filled; "
+ "re-observe and retry"
+ )
+ for _ in range(6):
+ await asyncio.sleep(0.4)
+ try:
+ menu = await page.evaluate(_FIND_MENU_JS, await _probe_arg(page, selector))
+ except Exception as e:
+ LOG.debug("taskv3 open-observe-pick menu-find failed", selector=selector, error=str(e))
+ menu = None
+ if isinstance(menu, dict) and menu.get("count"):
+ return menu, None
+ return None, None
+
+ found, err = await _open_and_enumerate()
+ if err is not None:
+ return err
+ if found is None:
+ # The list may have been open on entry (a prior call, or an Escape the widget ignored), so the
+ # open-click above TOGGLED it shut. Try once more: the second open-click reopens it and the
+ # re-snapshot inside _open_and_enumerate makes the reopened rows read as new.
+ found, err = await _open_and_enumerate()
+ if err is not None:
+ return err
+ if not isinstance(found, dict) or not found.get("count"):
+ # The open-click rendered no enumerable option list (portalled/closed-root, or not a menu).
+ # Truthful did-not-commit; the model's vision handles it from here.
+ return ToolResult.error(
+ f"opened {selector} but no option list rendered to pick {value!r} from — the field is NOT "
+ "filled; look() at the control and click the option you want"
+ )
+ # Read the whole tagged list at full length so the match is neither missed on a >60-char label
+ # nor computed over a truncated ≤15 slice (which would let "unique in the first 15" stand in for
+ # "unique in the menu").
+ count = int(found.get("count") or 0)
+ read: list[dict[str, Any]] = []
+ try:
+ full_rows = await page.evaluate(_MENU_OPTION_TEXTS_JS)
+ if isinstance(full_rows, list):
+ read = [o for o in full_rows if isinstance(o, dict) and isinstance(o.get("n"), int)]
+ except Exception as e:
+ LOG.debug("taskv3 open-observe-pick full-text read failed", selector=selector, error=str(e))
+
+ def _n_order(o: dict[str, Any]) -> int:
+ n = o.get("n")
+ return n if isinstance(n, int) else 1 << 30
+
+ # `overflowed` = the enumerated set is not the whole list, so uniqueness cannot be established and
+ # ALL auto-commit is refused. That is true when the full read failed, when `_FIND_MENU_JS` tagged
+ # more rows than the read returned, OR when a row's `aria-setsize` declares more options than were
+ # rendered (a virtualised list whose window is all that is in the DOM — count == len(read) there).
+ declared = max((int(o.get("setsize") or 0) for o in read), default=0)
+ overflowed = not read or count > len(read) or declared > len(read) or bool(found.get("partial"))
+ rows = read or (found.get("options") or [])
+ rows.sort(key=_n_order)
+ # Never auto-click a navigational row (`<a href>`/`<button>`/menuitem): `_FIND_MENU_JS` enumerates
+ # them because it only reports, but clicking one would leave the form.
+ options = [o for o in rows if not o.get("nav")]
+ if rows and not options:
+ # Refusing to auto-click is not the same as having nothing to show: hand the model the marks
+ # so a button-built select is one deliberate click away instead of an empty listing.
+ shown_nav = "; ".join(
+ f'[data-tv3-menu="{o.get("n")}"] {str(o.get("text") or "")[:60]!r}' for o in rows[:15]
+ )
+ return ToolResult.error(
+ f"opened {selector} but every row is a link/button this tool will not auto-click ({shown_nav}"
+ f"{'; +' + str(len(rows) - 15) + ' more' if len(rows) > 15 else ''}) — the field is NOT filled; "
+ 'if one of them is the option you want, click it by its [data-tv3-menu="N"] selector'
+ )
+ idx = None if overflowed else _match_menu_option(value, options)
+ if idx is None:
+ # Match over the FULL list above, but bound the error PAYLOAD: enumerate at most 15 rows,
+ # each ≤60 chars, so a miss on a 250-option country list does not ship a 15KB tool message.
+ shown = options[:15]
+ listing = "; ".join(f'[data-tv3-menu="{o.get("n")}"] {str(o.get("text") or "")[:60]!r}' for o in shown)
+ if overflowed:
+ return ToolResult.error(
+ f"{value!r} matched no option in the part of {selector}'s list we could read "
+ f"({listing}) — the list is longer than we could enumerate; scroll or look() to see "
+ 'the rest, then click the option by its [data-tv3-menu="N"] selector'
+ )
+ not_shown = len(options) - len(shown)
+ if not_shown > 0:
+ # More selectable rows exist than we listed — do not claim the value is absent.
+ return ToolResult.error(
+ f"{value!r} matched no option among the first {len(shown)} of {len(options)} in "
+ f"{selector} ({listing}; +{not_shown} more) — scroll or look() to see the rest, then "
+ 'click the option by its [data-tv3-menu="N"] selector'
+ )
+ return ToolResult.error(
+ f"opened {selector} but no option matched {value!r}; the list shows {listing} — "
+ 'pick the right one by its [data-tv3-menu="N"] selector, or look() to see the full menu'
+ )
+ matched = next((str(o.get("text") or "") for o in options if o.get("n") == idx), value)
+ # Read the field's committable value BEFORE the click. The verifier then rests on a CHANGE from
+ # this (passed as `typed`, with noSuggestionList so the always-true listClosed cannot stand in for
+ # one) — so leftover text a type attempt left in the field, whether or not a clear would succeed,
+ # can never read back as the commit.
+ try:
+ pre_value = str(await page.eval_on_selector(selector, "el => (el.value || '')") or "")
+ except Exception:
+ pre_value = ""
+ pre_hidden: list[str] = []
+ try:
+ raw_hidden = await page.eval_on_selector(selector, _HIDDEN_VALUES_JS)
+ if isinstance(raw_hidden, list):
+ pre_hidden = [str(v) for v in raw_hidden if isinstance(v, str)]
+ except Exception:
+ pre_hidden = []
+ try:
+ await page.click(f'[data-tv3-menu="{idx}"]', timeout=5000)
+ except Exception:
+ return ToolResult.error(
+ f"opened {selector} and matched {matched!r} but could not click it — re-observe and click "
+ f'[data-tv3-menu="{idx}"]'
+ )
+ await asyncio.sleep(0.3)
+ readable = False
+ committed = ""
+ try:
+ read = await page.evaluate(
+ _VERIFY_COMMIT_JS,
+ {
+ "field": selector,
+ "typed": pre_value,
+ "chosen": matched,
+ "noSuggestionList": True,
+ "preHidden": pre_hidden,
+ "el": (await _probe_arg(page, selector))["el"],
+ },
+ )
+ readable = read is not None
+ committed = str(read or "").strip()
+ except Exception as e:
+ LOG.debug("taskv3 open-observe-pick commit-verify failed", selector=selector, error=str(e))
+ committed = ""
+ verdict, matches = await _typeahead_commit_verdict(page, selector, committed or None, readable)
+ if verdict is CommitStatus.OK:
+ return ToolResult.ok(f"selected {matched!r} for {selector} (committed value: {committed!r})")
+ if verdict is CommitStatus.UNVERIFIED and matches != 1:
+ return ToolResult.ok(
+ f"selected {matched!r} for {selector}, but it re-resolved to {matches} elements so the "
+ "commit could not be verified — re-observe to confirm the value before relying on it"
+ )
+ if verdict is CommitStatus.UNVERIFIED:
+ why = await _unverifiable_because(page, selector)
+ if why:
+ return ToolResult.ok(
+ f"selected {matched!r} for {selector}; {why}, so the commit could not be verified — "
+ "re-observe to confirm the value before relying on it"
+ )
+ return ToolResult.error(f"clicked {matched!r} but {selector} did not commit a value")
+ return ToolResult.error(f"clicked {matched!r} but {selector} did not commit a value")
+
+ async def _commit_custom_combobox(page: Any, selector: str, value: str) -> ToolResult:
+ # Shared custom-combobox commit — the ONE path select_combobox and select_option's non-native
+ # branch both route through. Two mechanisms, one tool call: a TYPEAHEAD (searchable react-select /
+ # spl-autocomplete) commits by keystroke-type -> WAIT for the reacting suggestion -> click ->
+ # verify; a CLICK-TO-OPEN single-select (non-searchable react-select, button/div listbox) commits
+ # by open -> observe the rendered options -> pick the match -> verify. A non-typeable anchor goes
+ # straight to the open path; a typeable anchor tries typeahead first and falls through to the open
+ # path only when NOTHING reacts to keystrokes (the widget doesn't filter). Fails loudly rather than
+ # leaving raw typed text a widget won't accept (a false "filled" — the failure mode this prevents).
+ if await _anchor_typeable(page, selector):
+ try:
+ committed, opt_txt, readable = await _type_and_commit(page, selector, value, rounds=8)
+ except _FieldCovered as exc:
+ return _covered_error(exc.selector, exc.occluder)
+ except _FieldNotEditable as exc:
+ return _not_editable_error(exc)
+ if opt_txt is None:
+ # No MATCHING suggestion reacted -- but that alone does not say a list never rendered: a
+ # searchable typeahead that filtered to zero and a non-searchable widget that never filters
+ # both land here. The finder pierces open shadow roots, so inside a component it saw the
+ # list -- but a portalled/closed-root list stays invisible, so keep the honest "re-observe"
+ # note for that reach case first.
+ why = await _unverifiable_because(page, selector)
+ if why:
+ return ToolResult.ok(
+ f"typed {value!r} into {selector}; {why}, so the suggestion list could not be seen "
+ "and no selection was verified — re-observe to confirm the value committed before "
+ "relying on it"
+ )
+ # A drill-down widget hides its options under expandable category rows, so open→observe→pick's
+ # flat enumeration cannot reach them — surface the categories and fail loudly instead.
+ cats = await _categories_note(page, selector)
+ if cats:
+ return ToolResult.error(
+ f"no autocomplete suggestion matched {value!r} for {selector}; the field is NOT filled. {cats}"
+ )
+ # A searchable typeahead whose value is genuinely absent must report the honest no-match
+ # rather than reopen a list the value is not in. Two independent signals establish
+ # "searchable": (a) _FIND_MENU_JS finds rows NEW since the pre-type snapshot — a list that
+ # reacted to the keystrokes (a menu opened on focus/click sits in that snapshot and does not
+ # count, so a non-searchable widget still falls through); (b) the anchor declares
+ # aria-autocomplete list/both/inline — the ARIA contract that catches a combobox which
+ # filtered to ZERO rows, leaving nothing new to count.
+ searchable = False
+ try:
+ reacted_menu = await page.evaluate(_FIND_MENU_JS, await _probe_arg(page, selector))
+ searchable = isinstance(reacted_menu, dict) and bool(reacted_menu.get("count"))
+ except Exception:
+ searchable = False
+ if not searchable:
+ try:
+ searchable = bool(
+ await page.evaluate(_DECLARES_SEARCH_AUTOCOMPLETE_JS, await _probe_arg(page, selector))
+ )
+ except Exception:
+ searchable = False
+ if searchable:
+ # Name the choices the widget offered when it opened, so the next call can use the
+ # exact label instead of guessing one; the contract stays an honest did-not-commit.
+ offered: list[str] = []
+ offered_total = 0
+ try:
+ raw_offered = await page.evaluate(_FOCUS_OFFERED_LABELS_JS, await _probe_arg(page, selector))
+ if isinstance(raw_offered, dict):
+ offered = [str(t) for t in (raw_offered.get("labels") or []) if isinstance(t, str)]
+ offered_total = int(raw_offered.get("total") or 0)
+ except Exception:
+ offered = []
+ if offered and offered_total > len(offered):
+ offered_note = (
+ f". The list offers {offered_total} rows; the first {len(offered)}: "
+ + "; ".join(repr(t[:60]) for t in offered)
+ + " — if the label you want is not among them, click the control and look() at the list"
+ )
+ elif offered:
+ offered_note = (
+ ". The list offers: "
+ + "; ".join(repr(t[:60]) for t in offered)
+ + " — call select_combobox again with one of these exact labels"
+ )
+ else:
+ offered_note = ""
+ return ToolResult.error(
+ f"no autocomplete suggestion matched {value!r} for {selector}; the field is NOT filled "
+ f"— do not assume success or move on as if it were{offered_note}"
+ )
+ # The focus-click of the type attempt may have opened this widget's list, so close it first.
+ return await _open_observe_pick(page, selector, value, close_open_menu=True)
+ verdict, matches = await _typeahead_commit_verdict(page, selector, committed, readable)
+ if verdict is CommitStatus.OK:
+ return ToolResult.ok(f"selected {opt_txt!r} for {selector} (committed value: {committed!r})")
+ if verdict is CommitStatus.UNVERIFIED and matches != 1:
+ # INV-1: re-resolved to n≠1 after the click — no stable element to read the commit off.
+ return ToolResult.ok(
+ f"selected {opt_txt!r} for {selector}, but it re-resolved to {matches} elements so the "
+ "commit could not be verified — re-observe to confirm the value before relying on it"
+ )
+ if verdict is CommitStatus.UNVERIFIED:
+ # INV-2 (unreadable): keep the reach-based softening — a portalled/closed-root field is
+ # beyond the verifier, so the read returning nothing is not evidence the value did not commit.
+ why = await _unverifiable_because(page, selector)
+ if why:
+ return ToolResult.ok(
+ f"selected {opt_txt!r} for {selector}; {why}, so the commit could not be verified — "
+ "re-observe to confirm the value before relying on it"
+ )
+ return ToolResult.error(f"selected suggestion {opt_txt!r} but {selector} did not commit a value")
+ return ToolResult.error(f"selected suggestion {opt_txt!r} but {selector} did not commit a value")
+ # A non-typeable anchor (a button/div that only opens a list on click): open, observe, pick.
+ return await _open_observe_pick(page, selector, value)
+
async def select_option(args: dict[str, Any]) -> ToolResult:
page, error = await _resolve_page()
if error is not None:
@@ -3969,14 +5621,30 @@ def build_browser_tools(
ambiguous = await _ambiguous_selector_error(page, selector)
if ambiguous is not None:
return ambiguous
+ selector = await _resolve_mirrored_host_control(page, selector)
try:
probe = await page.evaluate(_SELECT_VISIBILITY_JS, await _probe_arg(page, selector))
except Exception:
probe = None
- # force bypasses actionability for a select a design system hides behind a styled proxy;
- # Playwright still sets the value and dispatches native input/change on the real element.
+ # A disabled control cannot be set whichever kind it is; check before diverting so a disabled
+ # custom combobox gets the accurate "is disabled" message rather than the typeable-gate refusal.
if isinstance(probe, dict) and probe.get("exists") and probe.get("disabled"):
return ToolResult.error(f"{selector} is disabled — it cannot be set until the page enables it")
+ # Native-vs-custom gates on the authoritative nodeName (a structural signal, not a heuristic).
+ # Divert to the shared custom-combobox path ONLY when the probe positively confirms a
+ # non-<select> element (React-Select, spl-autocomplete, div-list) that page.select_option would
+ # throw "Element is not a <select> element" on — so it commits in ONE action instead of degrading
+ # the model into click-open + click-option flail. When the probe is unavailable or the element
+ # could not be read, default to the native path below (unchanged), so a real <select> whose probe
+ # momentarily fails is never misrouted into typing.
+ probe_node = str(probe.get("nodeName") or "") if isinstance(probe, dict) and probe.get("exists") else None
+ if probe_node is not None and probe_node != "select":
+ chosen = label if label is not None else value
+ if not isinstance(chosen, str) or not chosen:
+ return ToolResult.error("select_option needs a label or value to choose")
+ return await _commit_custom_combobox(page, selector, _resolve_text(chosen))
+ # force bypasses actionability for a select a design system hides behind a styled proxy;
+ # Playwright still sets the value and dispatches native input/change on the real element.
force = bool(isinstance(probe, dict) and probe.get("exists") and not probe.get("visible"))
if force and not probe.get("proxied"):
return _unreachable_error(selector)
@@ -3990,21 +5658,30 @@ def build_browser_tools(
readback = await page.evaluate(_SELECT_READBACK_JS, await _probe_arg(page, selector))
except Exception:
readback = None
- committed = False
value_read: Any = None
+ post: dict[str, Any] | None = None
+ committed_value: bool | None = None
if isinstance(readback, dict):
value_read = readback.get("value")
- committed = readback.get("selectedLabel") == label if label is not None else value_read == value
- if readback is None:
- return ToolResult.ok(
- f"selected on {selector} — the control left the page afterwards, so the selection could not "
- "be verified; re-observe before relying on it"
- )
- if not committed:
+ post = {"value": value_read}
+ committed_value = readback.get("selectedLabel") == label if label is not None else value_read == value
+ matches = await _post_match_count(page, selector)
+ verdict = _classify_commit(None, matches, post, committed_value=committed_value)
+ if verdict is CommitStatus.DID_NOT_COMMIT:
return ToolResult.error(
f"select on {selector} did NOT commit: native select still reads {value_read!r} — the styled "
"widget may not sync from its hidden control; re-observe and act on the visible proxy instead"
)
+ if verdict is CommitStatus.UNVERIFIED:
+ reason = (
+ "the control left the page afterwards"
+ if post is None
+ else f"it re-resolved to {matches} elements afterwards"
+ )
+ return ToolResult.ok(
+ f"selected on {selector} — {reason}, so the selection could not be verified; re-observe "
+ "before relying on it"
+ )
return ToolResult.ok(f"selected on {selector} (hidden native select, set directly)")
async def press_key(args: dict[str, Any]) -> ToolResult:
@@ -4061,14 +5738,65 @@ def build_browser_tools(
page, error = await _resolve_page()
if error is not None:
return error
- url = await asyncio.to_thread(validate_fetch_url, _resolve_text(args["url"]))
- response = await page.goto(url, timeout=60000, wait_until="load")
+ requested = args["url"]
+ resolved = _resolve_text(requested)
+ # Payload provenance means an opaque token was resolved, not any substitution (a credential
+ # placeholder resolves too, but a page reached through one is the model's own to see).
+ from_ref = opaque_refs is not None and opaque_refs.resolve(requested) != requested
+ url = await asyncio.to_thread(validate_fetch_url, resolved)
+ # Destructive same-URL reload guard: a full reload of the page we are already on discards any
+ # in-progress form state (filled fields, an attached file) — an unforced state-wipe the loop
+ # otherwise scores as progress. Refuse it once with an actionable message; a repeat to the same
+ # URL confirms the model means to reset and is allowed through.
+ target_canonical = canonical_url(url)
+ same_page = canonical_url(await _url(page)) == target_canonical
+ filled = await _count_filled_fields(page) if same_page else 0
+ if filled > 0:
+ pending = _reload_confirm_pending[0]
+ # Confirm only a repeat whose at-risk state did not grow since the refusal: a file attached
+ # after the first warning must be re-refused, not silently wiped by a stale confirmation.
+ # Keyed by URL + count, not page identity or field content: a second page on the same
+ # canonical URL, or a same-count content swap, falls open to a single unguarded reload (the
+ # pre-guard behavior), never a new failure.
+ if pending is not None and pending[0] == target_canonical and filled <= pending[1]:
+ _reload_confirm_pending[0] = None
+ LOG.info("taskv3 navigate destructive-reload guard confirmed on repeat")
+ else:
+ _reload_confirm_pending[0] = (target_canonical, filled)
+ LOG.info("taskv3 navigate destructive-reload guard refused", filled_fields=filled)
+ return ToolResult.error(
+ "already on this page and it has filled fields (including any attached file); reloading "
+ "it would discard them. Act on the current page instead — or, if you intend to reset the "
+ "form, navigate here again to confirm."
+ )
+ else:
+ _reload_confirm_pending[0] = None
+ try:
+ response = await page.goto(url, timeout=60000, wait_until="load")
+ except Exception as exc:
+ if not from_ref:
+ raise
+ # Playwright names the URL that failed, which after a redirect is not the ref: every URL
+ # in the cause was reached by following the ref, so the model sees it as the token.
+ return ToolResult.error(f"navigation failed: {URL_IN_TEXT.sub(lambda _m: requested, str(exc))}")
+ landed = await _url(page)
+ # A payload ref that redirects hands its provenance to wherever it lands, so a credential the
+ # landing URL carries is masked at the boundary exactly like the ref itself. An error page
+ # (chrome-error://) is not a landing.
+ if from_ref and landed.startswith(("http://", "https://")) and canonical_url(landed) != canonical_url(url):
+ assert opaque_refs is not None
+ opaque_refs.derive(landed)
# Surface the HTTP status: an error page otherwise reads as a successful navigation, hiding
# dead URLs and blank shells from the model.
status = f" (HTTP {response.status})" if response is not None else ""
# page_state_changed tells the loop's action-loop guard the world moved: a re-attempt after
# a navigation is a fresh attempt, not a repeat against unchanged state.
- return ToolResult.ok(f"navigated to {await _url(page)}{status}", data={"page_state_changed": True})
+ data: dict[str, Any] = {"page_state_changed": True}
+ # A hard 404/410 landing is a dead/removed target: flag it so the loop ends the run as
+ # terminated (v1's behavior) rather than defaulting the outcome to failed.
+ if response is not None and response.status in NAVIGATION_DEAD_END_STATUSES:
+ data["navigation_dead_end"] = response.status
+ return ToolResult.ok(f"navigated to {landed}{status}", data=data)
async def file_upload(args: dict[str, Any]) -> ToolResult:
# Lazy import: keeps this module importable for unit tests without the full forge/storage graph.
@@ -4081,36 +5809,96 @@ def build_browser_tools(
ambiguous = await _ambiguous_selector_error(page, selector)
if ambiguous is not None:
return ambiguous
+ # Validate the selector before fetching: an invalid or missing selector fails here, before anything
+ # is staged into downloads_dir, so the selector guard's residual error can never leave a phantom
+ # upload for the download-signal wrapper to misread as a browser download.
+ if await page.query_selector(selector) is None:
+ return ToolResult.error(f"no file input for selector {selector!r}")
source = _resolve_text(args["file"])
- try:
- local_path = await download_file(source, output_dir=downloads_dir, organization_id=organization_id)
- except Exception as exc:
- # Catching here (rather than letting the loop's handler catch) is only to mask the URL:
- # a failed download echoes the source back in its message, and a signed payload URL would
- # otherwise leak its signing artifact to the model (the SKY-14492 retype case). Re-emit the
- # traceback log the loop's handler would have produced so the local catch doesn't swallow it.
- LOG.warning("taskv3 tool handler raised", tool="file_upload", exc_info=True)
- return ToolResult.error(_mask_refs(f"tool_error: {type(exc).__name__}: {exc}"))
+ # A failed download echoes the source back in the loop's generic tool_error; the model-facing
+ # masking boundary (hide_from_model) rewrites any signed payload ref to its token there, so this
+ # handler no longer catches locally just to mask the URL (the SKY-14492 retype case).
+ local_path = await download_file(source, output_dir=downloads_dir, organization_id=organization_id)
# For http(s) sources download_file stages into downloads_dir; naming the file lets the
# download-signal wrapper suppress it without swallowing unrelated downloads that complete
# during this call (for other schemes the key is inert — nothing in the dir matches).
staged = {"staged_download": os.path.basename(local_path)}
- paths = [local_path]
+ # Re-resolve after the download: a rerender during a slow fetch can detach the earlier handle, so
+ # bind the element fresh immediately before uploading (missing now means it vanished mid-download).
el = await page.query_selector(selector)
if el is None:
return ToolResult("error", f"no file input for selector {selector!r}", staged)
- await el.set_input_files(paths)
- # Settle + a small randomized delay so the upload and a following submit are not dispatched
- # in the same instant, matching v1's upload cadence (the engine that clears this step reliably).
- await _settle_after_upload(page)
- await _upload_submit_delay()
+ # Verify the upload took EFFECT, not just that set_input_files did not raise. Watch upload-like
+ # network dispatches across the set_input_files + settle window (the window we already dwell in,
+ # so this adds no latency); a genuine upload dispatches at least one, a silent no-op none.
+ probe = _UploadActivityProbe(page)
+ # Read before the attach on every call: the consume-and-clear check needs the pre-attach text,
+ # and whether it will be needed is only known afterwards. One local evaluate, no wait.
+ text_before = await _page_rendered_text(page)
+ probe.start()
+ try:
+ await el.set_input_files([local_path])
+ populated = await _input_holds_file(el)
+ # Settle + a small randomized delay so the upload and a following submit are not dispatched
+ # in the same instant, matching v1's upload cadence (the engine that clears this step reliably).
+ await _settle_after_upload(page)
+ await _upload_submit_delay()
+ finally:
+ probe.stop()
+ if not populated:
+ # A consume-and-clear dropzone reads the file on change, uploads it and resets the input, so
+ # an empty control after a genuine upload is normal there. Confirming it needs every signal
+ # a silent no-op cannot fake at once: the file's own name newly rendered on the page AND an
+ # upload dispatched (a client-side rejection names the file but sends nothing; ambient
+ # traffic sends but never names it), and no rejection wording anywhere the site newly rendered.
+ text_after = await _page_rendered_text(page)
+ shown_newly = (
+ text_before is not None
+ and text_after is not None
+ and not _mentions_filename(text_before, local_path)
+ and _mentions_filename(text_after, local_path)
+ )
+ if shown_newly:
+ assert text_before is not None and text_after is not None
+ new_lines = _newly_rendered_lines(text_before, text_after)
+ new_text = "\n".join(new_lines)
+ said = " | ".join(line for line in new_lines if _mentions_filename(line, local_path))
+ said = said[:_FILENAME_MENTION_CHARS]
+ if probe.saw_upload() and not _UPLOAD_REJECTION_WORDS.search(new_text):
+ LOG.info("taskv3 file_upload input cleared after attach but the page shows the uploaded file")
+ return ToolResult.ok(
+ f"uploaded 1 file to {selector} (the site consumed the file and now shows it: {said!r})",
+ staged,
+ )
+ LOG.info(
+ "taskv3 file_upload input cleared after attach; page names the file without confirming it",
+ upload_activity=probe.saw_upload(),
+ )
+ return ToolResult(
+ "error",
+ f"the file input {selector} is empty after the attach and the page now says {said!r} — "
+ f"re-observe to confirm the file was accepted before submitting",
+ staged,
+ )
+ return ToolResult("error", f"file did not attach to {selector} — re-observe the field", staged)
+ if not probe.saw_upload():
+ # The file is on the input but the site never reacted: report a recoverable error (not a
+ # confident OK) so the loop re-verifies before submitting. A submit-time-upload form lands
+ # here too and costs one re-plan turn, never a lost file.
+ return ToolResult(
+ "error",
+ f"attached the file to {selector} but observed no upload activity — re-observe the field "
+ f"to confirm the file is shown before submitting; if the form uploads on submit this may "
+ f"be expected",
+ staged,
+ )
return ToolResult.ok(f"uploaded 1 file to {selector}", staged)
async def select_combobox(args: dict[str, Any]) -> ToolResult:
- # Explicit typeahead fill (type() also drives this automatically): type the value, WAIT for the
- # async suggestion list, pick the best-matching suggestion, and VERIFY the field committed. Fails
- # loudly if nothing matches rather than leaving raw typed text the widget won't accept as a valid
- # selection (a false "filled" — the failure mode this exists to prevent).
+ # Explicit typeahead fill (type() also drives this automatically). Routes through the shared
+ # custom-combobox commit path: type the value, WAIT for the async suggestion list, pick the
+ # best-matching suggestion, and VERIFY the field committed. Fails loudly if nothing matches
+ # rather than leaving raw typed text the widget won't accept as a valid selection.
page, error = await _resolve_page()
if error is not None:
return error
@@ -4118,45 +5906,166 @@ def build_browser_tools(
ambiguous = await _ambiguous_selector_error(page, selector)
if ambiguous is not None:
return ambiguous
+ selector = await _resolve_mirrored_host_control(page, selector)
value = _resolve_text(args["value"])
+ return await _commit_custom_combobox(page, selector, value)
+
+ async def _clear_look_tags(page: Any) -> None:
try:
- committed, opt_txt, readable = await _type_and_commit(page, selector, value, rounds=8)
- except _FieldCovered as exc:
- return _covered_error(exc.selector, exc.occluder)
- except _FieldNotEditable as exc:
- return _not_editable_error(exc)
- if opt_txt is None:
- # The suggestion finder pierces open shadow roots, so inside a component it now sees a
- # list rendered in that root -- but a portalled or closed-root list stays invisible, so a
- # missing list there is still not evidence there was none, and "the field is NOT filled"
- # would be measurably false (the value is typed in). Erroring would also strand the
- # country/phone comboboxes on the very forms this targets. observe pierces too, so
- # re-observing is a check the model can run.
- why = await _unverifiable_because(page, selector)
- if why:
- return ToolResult.ok(
- f"typed {value!r} into {selector}; {why}, so the suggestion list could not be seen "
- "and no selection was verified — re-observe to confirm the value committed before "
- "relying on it"
- )
+ await page.evaluate(
+ "() => { const _q = " + _ROOT_QUERY_JS + "; "
+ "_q.all('[data-tv3-look]').forEach((e) => e.removeAttribute('data-tv3-look')); }"
+ )
+ except Exception:
+ pass
+
+ async def _clear_act_tags(page: Any) -> None:
+ try:
+ await page.evaluate(
+ "() => { const _q = " + _ROOT_QUERY_JS + "; "
+ "_q.all('[data-tv3-act]').forEach((e) => e.removeAttribute('data-tv3-act')); }"
+ )
+ except Exception:
+ pass
+
+ async def look(_args: dict[str, Any]) -> ToolResult:
+ if _look_count[0] >= _LOOK_MAX_PER_RUN:
return ToolResult.error(
- f"no autocomplete suggestion matched {value!r} for {selector}; the field is NOT filled "
- "— do not assume success or move on as if it were"
+ f"look budget reached ({_LOOK_MAX_PER_RUN} per run) — rely on observe/get_html and act on "
+ "what you already saw instead of looking again."
+ )
+ page, error = await _resolve_page()
+ if error is not None:
+ return error
+ _look_count[0] += 1
+ # Passive read + server-side render. The screenshot is a viewport frame (device px); the marks
+ # are enumerated separately so the boxes are drawn in PIL, never injected into the DOM.
+ try:
+ png = await page.screenshot()
+ except Exception as exc:
+ LOG.warning("taskv3 look screenshot failed", exc_info=True)
+ return ToolResult.error(f"look failed to capture the page: {type(exc).__name__}: {exc}")
+ try:
+ data = await asyncio.wait_for(page.evaluate(_LOOK_ENUM_JS), timeout=30)
+ except Exception as exc:
+ await _clear_look_tags(page)
+ LOG.warning("taskv3 look enumeration failed", exc_info=True)
+ return ToolResult.error(f"look failed to enumerate controls: {type(exc).__name__}: {exc}")
+ elements = data.get("elements", []) if isinstance(data, dict) else []
+ vw = int(data.get("vw") or 0) if isinstance(data, dict) else 0
+ # Release the prior look's retained handles before minting a new set (they leak in the driver
+ # otherwise), then grab one live handle per mark while the transient index is still on the DOM.
+ for old in _look_manifest.values():
+ try:
+ await old["handle"].dispose()
+ except Exception:
+ pass
+ _look_manifest.clear()
+ for e in elements:
+ n = int(e["n"])
+ try:
+ handle = await page.query_selector(f'[data-tv3-look="{n}"]')
+ except Exception:
+ handle = None
+ if handle is None:
+ continue
+ _look_manifest[n] = {
+ "handle": handle,
+ "tag": e.get("tag", ""),
+ "label": e.get("label", ""),
+ }
+ await _clear_look_tags(page)
+ # Draw ONLY the marks we retained a handle for, so every number on the image is one the model
+ # can actually act on (a control that detached between enumeration and handle-grab is dropped
+ # from both the image and the legend, never shown as an unusable box).
+ kept = [e for e in elements if int(e["n"]) in _look_manifest]
+ try:
+ annotated = await asyncio.get_running_loop().run_in_executor(None, _annotate_screenshot, png, kept, vw)
+ except Exception as exc:
+ LOG.warning("taskv3 look annotation failed", exc_info=True)
+ return ToolResult.error(f"look failed to render marks: {type(exc).__name__}: {exc}")
+ if not kept:
+ return ToolResult.ok(
+ "look: no interactive controls are visible in the viewport. Scroll or re-observe.",
+ screenshots=[annotated],
)
- if not committed:
- why = None if readable else await _unverifiable_because(page, selector)
- if why:
- return ToolResult.ok(
- f"selected {opt_txt!r} for {selector}; {why}, so the commit could not be verified — "
- "re-observe to confirm the value before relying on it"
- )
- return ToolResult.error(f"selected suggestion {opt_txt!r} but {selector} did not commit a value")
- return ToolResult.ok(f"selected {opt_txt!r} for {selector} (committed value: {committed!r})")
+
+ # Mask payload-minted signed URLs, then truncate for display — in that ORDER. A label taken
+ # from an input's value can carry a resolved presigned URL; masking (as observe and get_html do)
+ # rewrites it to its opaque token so the model can't retype it, and truncating first would sever
+ # the URL past the provenance match and leak a partial signed URL into the transcript.
+ def _label(raw: object, width: int = 80) -> str:
+ return _digest_token(_mask_refs(str(raw)), width)
+
+ lines = [
+ f"[{int(e['n'])}] {_digest_token(e.get('tag', ''), 20)} {_label(e.get('label', ''))!r}"
+ + (f" placeholder={_label(e['placeholder'], 60)!r}" if e.get("placeholder") else "")
+ for e in kept
+ ]
+ header = (
+ f"look: {len(kept)} visible control(s), numbered on the screenshot. Act on one with "
+ "click(mark=N) or type(mark=N, text=...)."
+ )
+ if isinstance(data, dict) and data.get("truncated"):
+ header += f" (only the first {_LOOK_MAX_MARKS} are marked; scroll for more.)"
+ legend = header + "\n" + "\n".join(lines)
+ return ToolResult.ok(legend, screenshots=[annotated])
+
+ async def _resolve_mark(page: Any, mark: int) -> tuple[str | None, ToolResult | None]:
+ # Turn mark=N into a selector the existing click/type handlers act through. Resolution is the
+ # SAME live element handle look retained (Playwright's engine, which pierces open shadow), tagged
+ # data-tv3-act=N at act time so the marker branch uniqueness-checks and commit-verifies it like
+ # any other marker. A detached handle errors rather than re-guessing by coordinates: a stale
+ # look-time point could hit whatever now occupies those pixels after a scroll, which is exactly
+ # the wrong-element class this must not introduce.
+ entry = _look_manifest.get(mark)
+ if entry is None:
+ return None, ToolResult.error(
+ f"mark {mark} is not in the current set of marks. Call look() first, then act on a number it drew."
+ )
+ await _clear_act_tags(page)
+ handle = entry.get("handle")
+ connected = False
+ if handle is not None:
+ try:
+ connected = bool(await handle.evaluate(_LOOK_TAG_HANDLE_JS, mark))
+ except Exception:
+ connected = False
+ if not connected:
+ return None, ToolResult.error(
+ f"mark {mark} no longer points to an element on the page — it moved or the page "
+ "re-rendered since look(). Call look() again and act on a fresh number."
+ )
+ return f'[data-tv3-act="{mark}"]', None
+
+ def _with_act_by_mark(handler: ToolHandler) -> ToolHandler:
+ async def wrapped(args: dict[str, Any]) -> ToolResult:
+ mark = args.get("mark")
+ if mark is None:
+ return await handler(args)
+ if args.get("selector"):
+ return ToolResult.error("Pass either mark or selector to act on a control, not both.")
+ try:
+ mark_int = int(mark)
+ except (TypeError, ValueError):
+ return ToolResult.error(f"mark must be an integer from the last look(), got {mark!r}.")
+ page, error = await _resolve_page()
+ if error is not None:
+ return error
+ selector, mark_error = await _resolve_mark(page, mark_int)
+ if mark_error is not None:
+ return mark_error
+ try:
+ return await handler({**args, "selector": selector})
+ finally:
+ await _clear_act_tags(page)
+
+ return wrapped
tools = [
_spec(
"observe",
- "Snapshot the page's visible interactive elements (raw DOM) with a CSS selector, label, type, value, and options for each. Also reports cross-origin iframes present (host + captcha signature); their contents cannot be observed or reached by selector. Call once per page, then act by selector.",
+ 'Snapshot the page\'s visible interactive elements (raw DOM) with a CSS selector, label, type, value, and options for each. A selector printed as [data-tv3-ref="N"] is a short handle for a control whose real id is long and opaque; copy it exactly as printed. Also reports cross-origin iframes present (host + captcha signature); their contents cannot be observed or reached by selector. Call once per page, then act by selector.',
_obj({}),
observe,
),
@@ -4166,14 +6075,32 @@ def build_browser_tools(
_obj({"selector": {"type": "string", "description": "CSS selector; omit for whole page"}}),
get_html,
),
+ _spec(
+ "look",
+ "Rare last resort: take ONE annotated screenshot of the viewport when the text tools are "
+ "insufficient — the layout is confusing, a control you expect isn't in observe (custom/"
+ "shadow-DOM widgets), or an action isn't taking and you can't tell why. Returns the page "
+ "image with every visible control boxed and numbered, plus a legend. Then act on a number "
+ "with click(mark=N) or type(mark=N, text=...). NEVER call it just to double-check observe.",
+ _obj({}),
+ look,
+ ),
_spec(
"click",
- "Click an element by CSS selector. If the click opens a menu of options, the result lists "
- 'them with [data-tv3-menu="N"] selectors — click one of those to select (verified: you get '
- "a loud error, not a silent no-op, if the selection does not commit; do not blindly repeat "
- "a failed click). If the click triggers a file download, the tool result reports it when "
- "detected.",
- _obj({"selector": {"type": "string"}}, ["selector"]),
+ "Click an element by CSS selector (or by mark=N from the last look()). If the click opens a "
+ 'menu of options, the result lists them with [data-tv3-menu="N"] selectors — click one of '
+ "those to select (verified: you get a loud error, not a silent no-op, if the selection does "
+ "not commit; do not blindly repeat a failed click). If the click triggers a file download, "
+ "the tool result reports it when detected.",
+ _obj(
+ {
+ "selector": {"type": "string"},
+ "mark": {
+ "type": "integer",
+ "description": "A number from the last look(); use instead of selector",
+ },
+ },
+ ),
click,
),
_spec(
@@ -4184,15 +6111,20 @@ def build_browser_tools(
),
_spec(
"type",
- "Type text into an input/textarea by CSS selector (clears first by default).",
+ "Type text into an input/textarea by CSS selector (or by mark=N from the last look()); "
+ "clears first by default.",
_obj(
{
"selector": {"type": "string"},
+ "mark": {
+ "type": "integer",
+ "description": "A number from the last look(); use instead of selector",
+ },
"text": {"type": "string"},
"clear": {"type": "boolean"},
"press_enter": {"type": "boolean"},
},
- ["selector", "text"],
+ ["text"],
),
type_text,
),
@@ -4252,6 +6184,11 @@ def build_browser_tools(
file_upload,
),
]
+ if not vision_enabled:
+ # A non-vision model drops the screenshot before the request, so `look` would advertise an
+ # image the model never sees. Drop the tool entirely; a `mark=N` with no look then just errors
+ # "not in the current set of marks" (a clean no-op), so click/type need no further change.
+ tools = [t for t in tools if t.name != "look"]
for _tool_spec in tools:
if _tool_spec.name in (
"click",
@@ -4263,12 +6200,22 @@ def build_browser_tools(
"file_upload",
):
_tool_spec.billable = True
- if _tool_spec.name in ("observe", "get_html"):
+ if _tool_spec.name in ("observe", "get_html", "look"):
# Large perception dumps: only the latest snapshot is relevant, so let the loop elide older
- # ones from the re-sent transcript (bounds context on perception-heavy pages).
+ # ones from the re-sent transcript (bounds context on perception-heavy pages). look's legend
+ # (not its ephemeral image, which never enters the transcript) rides the same rule.
_tool_spec.compactable = True
if _tool_spec.name in PREFLIGHT_TOOL_NAMES:
_tool_spec.handler = _with_preflight(_tool_spec.name, _tool_spec.handler, page_provider, _prefetched_page)
+ if _tool_spec.name in _SELECTOR_GUARD_TOOL_NAMES:
+ # Outside preflight (it builds its action from the normalized selector), inside act_by_mark
+ # (mark=N resolves to a selector first), so every selector tool inherits the guard.
+ _tool_spec.handler = _with_alias_resolution(_with_selector_guard(_tool_spec.handler))
+ if _tool_spec.name in ("click", "type"):
+ # OUTERMOST wrapper: resolve mark=N to a selector before preflight builds its action from
+ # args["selector"], so the whole verified click/type path (uniqueness gate, commit-verify)
+ # runs on the act-by-mark selector unchanged.
+ _tool_spec.handler = _with_act_by_mark(_tool_spec.handler)
_apply_download_signal(tools, downloads_dir)
return tools
@@ -4402,11 +6349,13 @@ def _apply_download_signal(tools: list[ToolSpec], downloads_dir: str | None) ->
capped = capped + [f"+{overflow} more files downloaded"]
pending[:] = deliver if _compactable else []
# The flag lets the loop's action-loop guard treat the download as progress without
- # sniffing the notice lines back out of the content string.
+ # sniffing the notice lines back out of the content string. Preserve screenshots so a
+ # result that also carried a look image (or any future image) is not silently dropped.
return ToolResult(
result.status,
result.content + "\n" + "\n".join(capped),
{**(result.data or {}), "download_notice": True},
+ result.screenshots,
)
except Exception:
LOG.warning("taskv3 download signal computation failed", tool=_tool_name, exc_info=True)
diff --git a/skyvern/services/browser_recording/v2/__init__.py b/skyvern/services/browser_recording/v2/__init__.py
deleted file mode 100644
index e69de29bb..000000000
diff --git a/skyvern/services/browser_recording/v2/keyfold.py b/skyvern/services/browser_recording/v2/keyfold.py
deleted file mode 100644
index 9a70f53b8..000000000
--- a/skyvern/services/browser_recording/v2/keyfold.py
+++ /dev/null
@@ -1,191 +0,0 @@
-from collections import deque
-from collections.abc import Sequence
-from dataclasses import dataclass, field
-from typing import Any, Literal
-
-from skyvern.services.browser_recording.v2.ledger import Gesture
-
-FactKind = Literal["click", "type_text", "press_key"]
-_NAVIGATION_KINDS = frozenset({"navigate", "go_back", "go_forward", "reload"})
-_KEY_DOWN_TYPES = frozenset({"keyDown", "rawKeyDown"})
-# CDP Input.dispatchKeyEvent modifiers: Alt=1, Ctrl=2, Meta=4, Shift=8. Shift still produces typed text.
-_CHORD_MODIFIERS = 1 | 2 | 4
-
-
-@dataclass(slots=True, repr=False)
-class Fact:
- kind: FactKind
- t_start: float
- t_end: float
- page_key: str
- url: str
- x: int | None = None
- y: int | None = None
- button: str | None = None
- click_count: int | None = None
- key: str | None = None
- typed_value: str | None = None
- typed_length: int = 0
- gesture_seqs: list[int] = field(default_factory=list)
- target_id: str | None = None
- frame_id: str | None = None
- backend_node_id: int | None = None
- selector: str | None = None
- role: str | None = None
- accessible_name: str | None = None
- tag: str | None = None
- input_type: str | None = None
- shadow_path: list[str] | None = None
-
- def redact(self) -> None:
- self.typed_value = None
-
- def __repr__(self) -> str:
- return f"Fact(kind={self.kind!r}, typed_length={self.typed_length}, gesture_count={len(self.gesture_seqs)})"
-
-
-def _fact(gesture: Gesture, kind: FactKind, **fields: Any) -> Fact:
- locator_source = fields.pop("locator_source", gesture)
- return Fact(
- kind,
- gesture.t_received,
- fields.pop("t_end", gesture.t_received),
- gesture.page_key,
- gesture.url,
- gesture_seqs=fields.pop("gesture_seqs", [gesture.seq]),
- target_id=gesture.target_id,
- frame_id=gesture.frame_id,
- backend_node_id=gesture.backend_node_id,
- selector=locator_source.selector,
- role=locator_source.role,
- accessible_name=locator_source.accessible_name,
- tag=locator_source.tag,
- input_type=locator_source.input_type,
- shadow_path=locator_source.shadow_path,
- **fields,
- )
-
-
-def fold(gestures: Sequence[Gesture]) -> list[Fact]:
- facts: list[Fact] = []
- typed_chars: list[str] = []
- typed_gestures: list[Gesture] = []
- standalone_keys: list[Gesture] = []
- pending_clicks: dict[str | None, deque[Fact]] = {}
- focus_gesture: Gesture | None = None
- # Focus is secret-until-established: a run typed before the first click (autofocused field) is redacted.
- focus_unknown = True
- run_focus: Gesture | None = None
- run_focus_unknown = False
-
- def flush_standalone_keys() -> None:
- facts.extend(_fact(gesture, "press_key", key=gesture.key) for gesture in standalone_keys)
- standalone_keys.clear()
-
- def start_run() -> None:
- nonlocal run_focus, run_focus_unknown
- run_focus = focus_gesture
- run_focus_unknown = focus_unknown
-
- def seal_run() -> None:
- nonlocal run_focus, run_focus_unknown
- if typed_chars:
- first, last = typed_gestures[0], typed_gestures[-1]
- fact = _fact(
- first,
- "type_text",
- t_end=last.t_received,
- typed_value="".join(typed_chars),
- typed_length=len(typed_chars),
- gesture_seqs=[gesture.seq for gesture in typed_gestures],
- locator_source=run_focus or first,
- )
- if run_focus_unknown or (run_focus is not None and run_focus.is_secret):
- fact.redact()
- facts.append(fact)
- flush_standalone_keys()
- typed_chars.clear()
- typed_gestures.clear()
- run_focus = None
- run_focus_unknown = False
-
- for gesture in gestures:
- if gesture.kind == "mouse_pressed":
- seal_run()
- focus_gesture = gesture
- focus_unknown = False
- fact = _fact(
- gesture, "click", x=gesture.x, y=gesture.y, button=gesture.button, click_count=gesture.click_count
- )
- facts.append(fact)
- pending_clicks.setdefault(gesture.button, deque()).append(fact)
- continue
-
- if gesture.kind == "mouse_released":
- pending = pending_clicks.get(gesture.button)
- if pending:
- fact = pending.popleft()
- fact.t_end = gesture.t_received
- fact.gesture_seqs.append(gesture.seq)
- continue
-
- if gesture.kind in _NAVIGATION_KINDS:
- seal_run()
- # A press whose release never arrived (mousedown-triggered nav, interrupted drag)
- # would otherwise take the t_end of the next release on that button, on the new page.
- pending_clicks.clear()
- focus_gesture = None
- focus_unknown = True
- continue
-
- if gesture.kind == "paste":
- if gesture.text:
- if standalone_keys:
- seal_run()
- if not typed_gestures:
- start_run()
- typed_chars.extend(gesture.text)
- typed_gestures.append(gesture)
- continue
-
- if gesture.kind != "key" or gesture.key_event_type not in _KEY_DOWN_TYPES:
- continue
-
- if gesture.key in {"Enter", "Tab"}:
- seal_run()
- facts.append(_fact(gesture, "press_key", key=gesture.key))
- if gesture.key == "Tab":
- focus_gesture = None
- focus_unknown = True
- continue
-
- if gesture.key == "Backspace":
- # A key like ArrowLeft moved the caret, so the run it interrupted is over: popping
- # across it would delete a character the user never deleted.
- if standalone_keys:
- seal_run()
- if typed_chars:
- typed_chars.pop()
- typed_gestures.append(gesture)
- else:
- standalone_keys.append(gesture)
- continue
-
- if (
- gesture.key_event_type == "keyDown"
- and gesture.text
- and gesture.text.isprintable()
- and not gesture.modifiers & _CHORD_MODIFIERS
- ):
- if standalone_keys:
- seal_run()
- if not typed_gestures:
- start_run()
- typed_chars.extend(gesture.text)
- typed_gestures.append(gesture)
- continue
-
- standalone_keys.append(gesture)
-
- seal_run()
- return facts
diff --git a/skyvern/services/browser_recording/v2/ledger.py b/skyvern/services/browser_recording/v2/ledger.py
deleted file mode 100644
index 9c4d844d3..000000000
--- a/skyvern/services/browser_recording/v2/ledger.py
+++ /dev/null
@@ -1,154 +0,0 @@
-from collections import deque
-from collections.abc import Callable, Iterator
-from dataclasses import dataclass, field, replace
-from typing import Literal
-
-from skyvern.services.browser_recording.v2.resolver import stop_resolver
-
-GestureKind = Literal[
- "mouse_pressed",
- "mouse_released",
- "mouse_moved",
- "wheel",
- "key",
- "paste",
- "navigate",
- "go_back",
- "go_forward",
- "reload",
-]
-EffectKind = Literal["navigation", "network_settle", "download", "file_chooser", "dialog", "target"]
-
-
-@dataclass(slots=True, repr=False)
-class Gesture:
- seq: int
- t_received: float
- kind: GestureKind
- page_key: str
- url: str
- x: int | None = None
- y: int | None = None
- button: str | None = None
- click_count: int | None = None
- modifiers: int = 0
- key: str | None = None
- code: str | None = None
- text: str | None = None
- windows_virtual_key_code: int | None = None
- key_event_type: str | None = None
- delta_x: int | None = None
- delta_y: int | None = None
- target_url: str | None = None
- target_id: str | None = None
- frame_id: str | None = None
- backend_node_id: int | None = None
- selector: str | None = None
- role: str | None = None
- accessible_name: str | None = None
- tag: str | None = None
- input_type: str | None = None
- shadow_path: list[str] | None = None
- is_secret: bool = False
-
- def __repr__(self) -> str:
- return f"Gesture(kind={self.kind!r}, text_length={len(self.text or '')})"
-
-
-@dataclass(slots=True)
-class Effect:
- seq: int
- t_received: float
- kind: EffectKind
- page_key: str
- url: str | None = None
- frame_id: str | None = None
- target_id: str | None = None
- caused_by_seq: int | None = None
- busy_ms: int | None = None
- is_main_frame: bool = False
- detail: dict[str, str | int | bool] = field(default_factory=dict)
-
-
-class GestureLedger:
- def __init__(self, browser_session_id: str, *, capacity: int = 50_000) -> None:
- self.browser_session_id = browser_session_id
- self.capacity = capacity
- self.paused = False
- self._rows: deque[Gesture] = deque(maxlen=capacity)
- self._effects: deque[Effect] = deque(maxlen=capacity)
- self._stop_hooks: list[Callable[[], None]] = []
- self._next_seq = 1
-
- @property
- def version(self) -> int:
- return self._next_seq
-
- def append(self, gesture_without_seq: Gesture) -> Gesture | None:
- if self.paused:
- return None
- gesture = replace(gesture_without_seq, seq=self._next_seq)
- self._next_seq += 1
- # Native-rate moves would otherwise flood the count-capped ring and evict the clicks and keys the fold
- # needs; only the last move before a discrete gesture carries hover information.
- if (
- gesture.kind == "mouse_moved"
- and self._rows
- and self._rows[-1].kind == "mouse_moved"
- and self._rows[-1].page_key == gesture.page_key
- ):
- self._rows.pop()
- self._rows.append(gesture)
- return gesture
-
- def append_effect(self, effect_without_seq: Effect) -> Effect | None:
- if self.paused:
- return None
- effect = replace(effect_without_seq, seq=self._next_seq)
- self._next_seq += 1
- self._effects.append(effect)
- return effect
-
- def rows(self) -> list[Gesture]:
- return list(self._rows)
-
- def iter_recent(self) -> Iterator[Gesture]:
- return reversed(self._rows)
-
- def effects(self) -> list[Effect]:
- return list(self._effects)
-
- def on_stop(self, callback: Callable[[], None]) -> None:
- self._stop_hooks.append(callback)
-
- def _run_stop_hooks(self) -> None:
- hooks, self._stop_hooks = self._stop_hooks, []
- for callback in hooks:
- callback()
-
- def __len__(self) -> int:
- return len(self._rows)
-
- def __repr__(self) -> str:
- return f"GestureLedger(count={len(self)}, capacity={self.capacity})"
-
-
-_ledgers: dict[str, GestureLedger] = {}
-
-
-def start_ledger(browser_session_id: str) -> GestureLedger:
- return _ledgers.get(browser_session_id) or _ledgers.setdefault(
- browser_session_id, GestureLedger(browser_session_id)
- )
-
-
-def get_ledger(browser_session_id: str) -> GestureLedger | None:
- return _ledgers.get(browser_session_id)
-
-
-def stop_ledger(browser_session_id: str) -> GestureLedger | None:
- stop_resolver(browser_session_id)
- ledger = _ledgers.pop(browser_session_id, None)
- if ledger is not None:
- ledger._run_stop_hooks()
- return ledger
diff --git a/skyvern/services/browser_recording/v2/observation.py b/skyvern/services/browser_recording/v2/observation.py
deleted file mode 100644
index 42216ad6e..000000000
--- a/skyvern/services/browser_recording/v2/observation.py
+++ /dev/null
@@ -1,365 +0,0 @@
-from __future__ import annotations
-
-import asyncio
-import contextlib
-from collections.abc import Callable
-from functools import partial
-from time import monotonic
-from typing import Any
-
-from skyvern.services.browser_recording.v2.ledger import Effect, Gesture, GestureLedger
-
-CLICK_NAVIGATION_WINDOW_MS = 3000
-SETTLE_QUIET_MS = 500
-SETTLE_MAX_MS = 15000
-BOOKKEEPING_CAPACITY = 4096
-
-
-def _str(payload: dict[str, Any], key: str) -> str | None:
- value = payload.get(key)
- return value if isinstance(value, str) else None
-
-
-class Observer:
- def __init__(self, ledger: GestureLedger) -> None:
- self.ledger = ledger
- self._attached_page_sessions: set[int] = set()
- self._attached_browser_sessions: set[int] = set()
- self._listeners: list[tuple[Any, str, Callable[[dict[str, Any]], None]]] = []
- self._frame_pages: dict[str, str] = {}
- self._pending_navigations: dict[str, Effect] = {}
- self._last_activity: dict[str, float] = {}
- self._settle_timers: dict[str, asyncio.TimerHandle] = {}
- self._settled_gestures: dict[tuple[str, int], None] = {}
- self._target_urls: dict[str, str | None] = {}
- self._main_frames: dict[str, str] = {}
-
- async def attach_page_session(self, page_key: str, cdp_session: Any) -> None:
- session_key = id(cdp_session)
- if session_key in self._attached_page_sessions:
- return
-
- self._remove_listeners(self._attached_page_sessions)
- self._attached_page_sessions.clear()
-
- def frame_started(payload: dict[str, Any]) -> None:
- frame_id = _str(payload, "frameId")
- self._on_navigation(page_key, frame_id, _str(payload, "url"), True, self._is_main_frame(page_key, frame_id))
-
- def frame_navigated(payload: dict[str, Any]) -> None:
- frame = payload.get("frame")
- if not isinstance(frame, dict):
- return
- frame_id = _str(frame, "id")
- is_main_frame = _str(frame, "parentId") is None
- if is_main_frame and frame_id is not None:
- self._main_frames[page_key] = frame_id
- self._on_navigation(page_key, frame_id, _str(frame, "url"), False, is_main_frame)
-
- def within_document(payload: dict[str, Any]) -> None:
- frame_id = _str(payload, "frameId")
- if frame_id is not None:
- self._remember_frame_page(frame_id, page_key)
- self._append_navigation(
- page_key, frame_id, _str(payload, "url"), monotonic(), self._is_main_frame(page_key, frame_id)
- )
-
- listeners: dict[str, Callable[[dict[str, Any]], None]] = {
- "Page.frameStartedNavigating": frame_started,
- "Page.frameNavigated": frame_navigated,
- "Page.navigatedWithinDocument": within_document,
- "Network.requestWillBeSent": partial(self._on_network_activity, page_key),
- "Network.loadingFinished": partial(self._on_network_activity, page_key),
- "Network.loadingFailed": partial(self._on_network_activity, page_key),
- # Chrome emits fileChooserOpened only while Page.setInterceptFileChooserDialog is enabled; v2
- # deliberately does not enable interception until PR-9, so this row is silent until then.
- "Page.fileChooserOpened": partial(self._on_file_chooser, page_key),
- "Page.javascriptDialogOpening": partial(self._on_dialog, page_key),
- }
- self._register_listeners(cdp_session, listeners)
- try:
- await asyncio.gather(
- cdp_session.send("Page.enable", {}),
- cdp_session.send("Network.enable", {}),
- )
- except Exception:
- self._remove_listeners({session_key})
- raise
- await self._remember_main_frame(page_key, cdp_session)
- self._attached_page_sessions.add(session_key)
-
- async def attach_browser_session(self, cdp_session: Any) -> None:
- session_key = id(cdp_session)
- if session_key in self._attached_browser_sessions:
- return
-
- self._register_listeners(
- cdp_session,
- {
- "Target.targetCreated": partial(self._on_target, True),
- "Target.targetInfoChanged": partial(self._on_target, False),
- },
- )
- try:
- await cdp_session.send("Target.setDiscoverTargets", {"discover": True})
- except Exception:
- self._remove_listeners({session_key})
- raise
- self._attached_browser_sessions.add(session_key)
-
- def detach(self) -> None:
- for timer in self._settle_timers.values():
- timer.cancel()
- self._settle_timers.clear()
- for session, event, callback in self._listeners:
- with contextlib.suppress(Exception):
- session.remove_listener(event, callback)
- self._listeners.clear()
- self._attached_page_sessions.clear()
- self._attached_browser_sessions.clear()
- self._frame_pages.clear()
- self._pending_navigations.clear()
- self._last_activity.clear()
- self._settled_gestures.clear()
- self._target_urls.clear()
- self._main_frames.clear()
-
- def _register_listeners(
- self,
- cdp_session: Any,
- listeners: dict[str, Callable[[dict[str, Any]], None]],
- ) -> None:
- for event, callback in listeners.items():
- cdp_session.on(event, callback)
- self._listeners.append((cdp_session, event, callback))
-
- def _remove_listeners(self, session_keys: set[int]) -> None:
- retained = []
- for session, event, callback in self._listeners:
- if id(session) not in session_keys:
- retained.append((session, event, callback))
- continue
- with contextlib.suppress(Exception):
- session.remove_listener(event, callback)
- self._listeners = retained
-
- async def _remember_main_frame(self, page_key: str, cdp_session: Any) -> None:
- # Only main-frame navigations become steps, and frameStartedNavigating/navigatedWithinDocument
- # do not say which frame is the main one.
- frame_id: Any = None
- with contextlib.suppress(Exception):
- frame_tree = await cdp_session.send("Page.getFrameTree", {})
- frame_id = frame_tree["frameTree"]["frame"]["id"]
- if isinstance(frame_id, str):
- self._main_frames[page_key] = frame_id
-
- def _is_main_frame(self, page_key: str, frame_id: str | None) -> bool:
- return frame_id is not None and self._main_frames.get(page_key) == frame_id
-
- def _remember_frame_page(self, frame_id: str, page_key: str) -> None:
- self._frame_pages.pop(frame_id, None)
- self._frame_pages[frame_id] = page_key
- if len(self._frame_pages) > BOOKKEEPING_CAPACITY:
- self._frame_pages.pop(next(iter(self._frame_pages)))
-
- def _on_navigation(
- self, page_key: str, frame_id: str | None, url: str | None, is_start: bool, is_main_frame: bool
- ) -> None:
- if frame_id is not None:
- self._remember_frame_page(frame_id, page_key)
- received_at = monotonic()
- if not is_start and frame_id is not None:
- pending = self._pending_navigations.pop(frame_id, None)
- if (
- pending is not None
- and not self.ledger.paused
- and 0 <= received_at - pending.t_received <= CLICK_NAVIGATION_WINDOW_MS / 1000
- ):
- pending.url = url
- pending.is_main_frame = pending.is_main_frame or is_main_frame
- return
- effect = self._append_navigation(page_key, frame_id, url, received_at, is_main_frame)
- if is_start and frame_id is not None and effect is not None:
- self._pending_navigations[frame_id] = effect
-
- def _append_navigation(
- self,
- page_key: str,
- frame_id: str | None,
- url: str | None,
- received_at: float,
- is_main_frame: bool,
- ) -> Effect | None:
- gesture = self._recent_navigation_gesture(page_key, received_at)
- return self.ledger.append_effect(
- Effect(
- seq=0,
- t_received=received_at,
- kind="navigation",
- page_key=page_key,
- url=url,
- frame_id=frame_id,
- caused_by_seq=gesture.seq if gesture is not None else None,
- is_main_frame=is_main_frame,
- )
- )
-
- def _recent_navigation_gesture(self, page_key: str, received_at: float) -> Gesture | None:
- for gesture in self.ledger.iter_recent():
- if gesture.page_key != page_key:
- continue
- if gesture.kind != "mouse_pressed" and not (gesture.kind == "key" and gesture.key == "Enter"):
- continue
- elapsed = received_at - gesture.t_received
- if 0 <= elapsed <= CLICK_NAVIGATION_WINDOW_MS / 1000:
- return gesture
- return None
- return None
-
- def _on_network_activity(self, page_key: str, payload: dict[str, Any]) -> None:
- frame_id = _str(payload, "frameId")
- if frame_id is not None:
- self._remember_frame_page(frame_id, page_key)
- received_at = monotonic()
- self._last_activity[page_key] = received_at
- timer = self._settle_timers.pop(page_key, None)
- if timer is not None:
- timer.cancel()
- gesture = self._recent_gesture(page_key, received_at)
- if gesture is None or (page_key, gesture.seq) in self._settled_gestures:
- return
- elapsed = received_at - gesture.t_received
- if elapsed >= SETTLE_MAX_MS / 1000:
- self._append_network_settle(page_key, gesture.seq, gesture.t_received)
- return
- loop = asyncio.get_running_loop()
- self._settle_timers[page_key] = loop.call_later(
- min(SETTLE_QUIET_MS / 1000, SETTLE_MAX_MS / 1000 - elapsed),
- self._append_network_settle,
- page_key,
- gesture.seq,
- gesture.t_received,
- )
-
- def _recent_gesture(self, page_key: str, received_at: float) -> Gesture | None:
- for gesture in self.ledger.iter_recent():
- if gesture.kind in {"mouse_moved", "wheel", "mouse_released"}:
- continue
- if gesture.page_key == page_key and gesture.t_received <= received_at:
- return gesture
- return None
-
- def _append_network_settle(self, page_key: str, gesture_seq: int, gesture_received_at: float) -> None:
- self._settle_timers.pop(page_key, None)
- if (page_key, gesture_seq) in self._settled_gestures:
- return
- last_activity = self._last_activity[page_key]
- capped = monotonic() - gesture_received_at >= SETTLE_MAX_MS / 1000
- self._settled_gestures[(page_key, gesture_seq)] = None
- if len(self._settled_gestures) > BOOKKEEPING_CAPACITY:
- self._settled_gestures.pop(next(iter(self._settled_gestures)))
- self.ledger.append_effect(
- Effect(
- seq=0,
- t_received=monotonic(),
- kind="network_settle",
- page_key=page_key,
- caused_by_seq=gesture_seq,
- busy_ms=SETTLE_MAX_MS if capped else max(0, round((last_activity - gesture_received_at) * 1000)),
- detail={"capped": True} if capped else {},
- )
- )
-
- def _on_file_chooser(self, page_key: str, payload: dict[str, Any]) -> None:
- frame_id = _str(payload, "frameId")
- if frame_id is not None:
- self._remember_frame_page(frame_id, page_key)
- detail: dict[str, str | int | bool] = {}
- mode = _str(payload, "mode")
- if mode is not None:
- detail["mode"] = mode
- if isinstance(payload.get("backendNodeId"), int):
- detail["backendNodeId"] = payload["backendNodeId"]
- self.ledger.append_effect(
- Effect(
- seq=0,
- t_received=monotonic(),
- kind="file_chooser",
- page_key=page_key,
- frame_id=frame_id,
- detail=detail,
- )
- )
-
- def _on_dialog(self, page_key: str, payload: dict[str, Any]) -> None:
- detail: dict[str, str | int | bool] = {}
- dialog_type = _str(payload, "type")
- if dialog_type is not None:
- detail["type"] = dialog_type
- self.ledger.append_effect(
- Effect(
- seq=0,
- t_received=monotonic(),
- kind="dialog",
- page_key=page_key,
- detail=detail,
- )
- )
-
- def _on_target(self, is_created: bool, payload: dict[str, Any]) -> None:
- target_info = payload.get("targetInfo")
- if not isinstance(target_info, dict):
- return
- target_id = _str(target_info, "targetId")
- target_type = _str(target_info, "type")
- url = _str(target_info, "url")
- if target_id is None or target_type != "page":
- return
- if is_created and target_id in self._target_urls:
- return
- if not is_created and target_id in self._target_urls and self._target_urls[target_id] == url:
- return
- self._target_urls.pop(target_id, None)
- self._target_urls[target_id] = url
- if len(self._target_urls) > BOOKKEEPING_CAPACITY:
- self._target_urls.pop(next(iter(self._target_urls)))
- self.ledger.append_effect(
- Effect(
- seq=0,
- t_received=monotonic(),
- kind="target",
- page_key=target_id,
- url=url,
- target_id=target_id,
- detail={"type": target_type},
- )
- )
-
-
-observers: dict[str, Observer] = {}
-
-
-def _unregister_observer(browser_session_id: str, observer: Observer) -> None:
- if observers.get(browser_session_id) is observer:
- observers.pop(browser_session_id)
-
-
-def start_observer(browser_session_id: str, ledger: GestureLedger) -> Observer:
- observer = observers.get(browser_session_id)
- if observer is None:
- observer = Observer(ledger)
- observers[browser_session_id] = observer
- ledger.on_stop(observer.detach)
- ledger.on_stop(partial(_unregister_observer, browser_session_id, observer))
- return observer
-
-
-def get_observer(browser_session_id: str) -> Observer | None:
- return observers.get(browser_session_id)
-
-
-def stop_observer(browser_session_id: str) -> Observer | None:
- observer = observers.pop(browser_session_id, None)
- if observer is not None:
- observer.detach()
- return observer
diff --git a/skyvern/services/browser_recording/v2/render.py b/skyvern/services/browser_recording/v2/render.py
deleted file mode 100644
index 5e825e534..000000000
--- a/skyvern/services/browser_recording/v2/render.py
+++ /dev/null
@@ -1,344 +0,0 @@
-from __future__ import annotations
-
-import keyword
-import re
-import textwrap
-from collections.abc import Mapping, Sequence
-from dataclasses import dataclass, field, replace
-from typing import Any, Literal
-from urllib.parse import urlparse
-
-import structlog
-
-from skyvern.client.types.workflow_definition_yaml_blocks_item import (
- WorkflowDefinitionYamlBlocksItem_Action,
- WorkflowDefinitionYamlBlocksItem_Code,
- WorkflowDefinitionYamlBlocksItem_GotoUrl,
-)
-from skyvern.client.types.workflow_definition_yaml_parameters_item import WorkflowDefinitionYamlParametersItem_Workflow
-from skyvern.forge.sdk.copilot.code_block_steps import derive_code_block_steps
-from skyvern.forge.sdk.copilot.code_block_synthesis import synthesize_code_block, synthesize_goto_code_block
-from skyvern.forge.sdk.workflow.exceptions import InsecureCodeDetected
-from skyvern.forge.sdk.workflow.models.block import CodeBlock
-from skyvern.services.browser_recording.v2.keyfold import Fact, fold
-from skyvern.services.browser_recording.v2.session import RecordingSessionV2, StepV2
-
-LOG = structlog.get_logger()
-
-RenderMode = Literal["blocks", "code"]
-
-_INTERACTIVE_KINDS = frozenset({"click", "type_text", "press_key"})
-_LOCATOR_REQUIRED_KINDS = frozenset({"click", "type_text"})
-# Below this the synthesizer's own wait_for_load_state after each click already covers the settle.
-_WAIT_THRESHOLD_MS = 2000
-
-
-@dataclass(slots=True)
-class RenderResult:
- blocks: list[dict]
- parameters: list[dict]
- mode: RenderMode
- diagnostics: dict
- notes: list[str] = field(default_factory=list)
-
-
-@dataclass(slots=True)
-class StepOverlay:
- kept_step_ids: frozenset[str]
- titles: dict[str, str]
- urls: dict[str, str]
-
-
-def overlay_from_draft_steps(draft_steps: Sequence[Mapping[str, Any]] | None) -> StepOverlay | None:
- if draft_steps is None:
- return None
-
- kept: set[str] = set()
- titles: dict[str, str] = {}
- urls: dict[str, str] = {}
- for draft in draft_steps:
- step_id = str(draft.get("step_id") or "")
- if not step_id:
- continue
- kept.add(step_id)
- title = str(draft.get("title") or "").strip()
- if title:
- titles[step_id] = title
- url = str(draft.get("url") or "").strip()
- if url:
- urls[step_id] = url
-
- if draft_steps and not kept:
- # Drafts without step ids cannot be joined back to steps; keeping the raw
- # steps beats treating the whole recording as deleted.
- return None
- return StepOverlay(frozenset(kept), titles, urls)
-
-
-def _overlaid_steps(session: RecordingSessionV2, overlay: StepOverlay | None) -> list[StepV2]:
- steps = session.steps
- if overlay is None:
- return steps
-
- kept: list[StepV2] = []
- for step in steps:
- if step.step_id not in overlay.kept_step_ids:
- continue
- title = overlay.titles.get(step.step_id)
- url = overlay.urls.get(step.step_id)
- if title or url:
- step = replace(step, title=title or step.title, url=url or step.url)
- kept.append(step)
- return kept
-
-
-def _facts_by_step_id(session: RecordingSessionV2) -> dict[str, Fact]:
- facts: dict[str, Fact] = {}
- for fact in fold(session.ledger.rows()):
- first_seq = fact.gesture_seqs[0] if fact.gesture_seqs else 0
- facts[f"{session.browser_session_id}:{first_seq}"] = fact
- return facts
-
-
-def _slug(text: str) -> str:
- slug = re.sub(r"\W+", "_", text.strip().lower()).strip("_")[:60]
- if not slug or slug[0].isdigit():
- slug = f"field_{slug}".rstrip("_")
- if keyword.iskeyword(slug):
- slug = f"{slug}_field"
- return slug
-
-
-def _host(url: str | None) -> str:
- return urlparse(url).netloc if url else ""
-
-
-def _unique(base: str, used: set[str]) -> str:
- candidate = base
- suffix = 2
- while candidate in used:
- candidate = f"{base}_{suffix}"
- suffix += 1
- used.add(candidate)
- return candidate
-
-
-def _has_locator(fact: Fact | None) -> bool:
- return bool(fact and (fact.selector or (fact.role and fact.accessible_name)))
-
-
-def _diagnostics(session: RecordingSessionV2, facts: Mapping[str, Fact], dropped: int, unlocatable: int) -> dict:
- return {
- "rows": len(session.ledger.rows()),
- "facts": len(facts),
- "dropped": dropped,
- "unlocatable": unlocatable,
- }
-
-
-def _blank_default(parameter: Mapping[str, Any]) -> dict:
- return WorkflowDefinitionYamlParametersItem_Workflow(
- key=str(parameter["key"]),
- workflow_parameter_type="string",
- # Recorded values never persist as defaults: a secret typed into any field
- # must not land in a DB-stored, API-exposed default_value.
- default_value="",
- description="",
- ).dict()
-
-
-def render_blocks(session: RecordingSessionV2, overlay: StepOverlay | None = None) -> RenderResult:
- facts = _facts_by_step_id(session)
- steps = _overlaid_steps(session, overlay)
-
- blocks: list[dict] = []
- parameters: list[dict] = []
- keys_by_identity: dict[tuple[str, str, str], str] = {}
- used_keys: set[str] = set()
- used_labels: set[str] = set()
- dropped = 0
- unlocatable = 0
-
- for step in steps:
- fact = facts.get(step.step_id)
- if step.kind == "goto_url":
- if not step.url:
- dropped += 1
- continue
- label = _unique(_slug(f"goto_{_host(step.url)}") or "goto_url", used_labels)
- blocks.append(WorkflowDefinitionYamlBlocksItem_GotoUrl(label=label, url=step.url).dict())
- continue
-
- if step.kind not in _INTERACTIVE_KINDS:
- dropped += 1
- continue
-
- if step.kind in _LOCATOR_REQUIRED_KINDS and not _has_locator(fact):
- unlocatable += 1
-
- parameter_key: str | None = None
- if step.kind == "type_text":
- identity = (
- (fact.selector or "") if fact else "",
- (fact.role or "") if fact else "",
- step.accessible_name or "",
- )
- parameter_key = keys_by_identity.get(identity)
- if parameter_key is None:
- base = step.accessible_name or (fact.tag if fact and fact.tag else "") or "field"
- parameter_key = _unique(_slug(base), used_keys)
- keys_by_identity[identity] = parameter_key
- parameters.append(_blank_default({"key": parameter_key}))
-
- navigation_goal = (
- f"{step.title} with the value of the {parameter_key} parameter" if parameter_key else step.title
- )
- blocks.append(
- WorkflowDefinitionYamlBlocksItem_Action(
- label=_unique(_slug(step.title) or "act", used_labels),
- title=step.title,
- navigation_goal=navigation_goal,
- error_code_mapping=None,
- # The editor's convertToNode reads block.parameters.map(p => p.key).
- parameters=[{"key": parameter_key}] if parameter_key else [],
- parameter_keys=[parameter_key] if parameter_key else [],
- ).dict()
- )
-
- return RenderResult(
- blocks=blocks,
- parameters=parameters,
- mode="blocks",
- diagnostics=_diagnostics(session, facts, dropped, unlocatable),
- )
-
-
-def _interaction(step: StepV2, fact: Fact) -> dict[str, Any]:
- base: dict[str, Any] = {}
- if fact.selector:
- base["selector"] = fact.selector
- if fact.role:
- base["role"] = fact.role
- if fact.accessible_name:
- base["accessible_name"] = fact.accessible_name
-
- if step.kind == "click":
- return {"tool_name": "click", **base}
- if step.kind == "press_key":
- return {"tool_name": "press_key", "key": fact.key}
- return {"tool_name": "type_text", **base, "typed_value": fact.typed_value, "typed_length": fact.typed_length}
-
-
-def render_code(session: RecordingSessionV2, overlay: StepOverlay | None = None) -> RenderResult | None:
- facts = _facts_by_step_id(session)
- steps = _overlaid_steps(session, overlay)
-
- segments: list[tuple[str | None, list[dict[str, Any]]]] = [(None, [])]
- notes: list[str] = []
- dropped = 0
- shadow_hosts = 0
-
- for step in steps:
- if step.kind == "goto_url":
- if not step.url:
- dropped += 1
- continue
- # Every navigation gets its own segment so code renders one page.goto per
- # navigation, exactly as render_blocks emits one goto_url block per navigation.
- if segments[-1] == (None, []):
- segments[-1] = (step.url, [])
- else:
- segments.append((step.url, []))
- continue
-
- if step.kind not in _INTERACTIVE_KINDS:
- dropped += 1
- continue
-
- fact = facts.get(step.step_id)
- if fact is None or (step.kind in _LOCATOR_REQUIRED_KINDS and not _has_locator(fact)):
- LOG.info(
- "Record Browser v2 code render found an unlocatable interaction",
- browser_session_id=session.browser_session_id,
- step_kind=step.kind,
- )
- return None
-
- if fact.shadow_path:
- shadow_hosts += 1
-
- segments[-1][1].append(_interaction(step, fact))
- if step.settle_ms is not None and step.settle_ms > _WAIT_THRESHOLD_MS:
- segments[-1][1].append({"tool_name": "wait", "duration_ms": step.settle_ms})
-
- if shadow_hosts:
- notes.append(f"{shadow_hosts} interaction(s) inside a closed shadow root use their host element's selector")
-
- if segments[0][0] is None and segments[0][1]:
- first_url = next((step.url for step in steps if step.url), None)
- segments[0] = (first_url, segments[0][1])
-
- blocks: list[dict] = []
- parameter_keys_seen: set[str] = set()
- parameters: list[dict] = []
- used_labels: set[str] = set()
-
- for source_url, trajectory in segments:
- if trajectory and source_url:
- trajectory[0] = {**trajectory[0], "source_url": source_url}
- if trajectory:
- synthesized = synthesize_code_block(trajectory, strict_selectors=False)
- elif source_url:
- synthesized = synthesize_goto_code_block(source_url)
- else:
- continue
- if synthesized is None:
- continue
-
- code = textwrap.dedent(synthesized.code)
- try:
- CodeBlock.is_safe_code(code)
- # ast.parse raises ValueError on e.g. null bytes; any failure inside the safety
- # gate must fall back to blocks, never surface as an error to the operator.
- except (SyntaxError, ValueError, InsecureCodeDetected):
- LOG.warning(
- "Record Browser v2 code render rejected by the code safety gate",
- browser_session_id=session.browser_session_id,
- exc_info=True,
- )
- return None
-
- notes.extend(synthesized.notes)
- block_parameter_keys: list[str] = []
- for parameter in synthesized.parameters:
- key = str(parameter.get("key") or "").strip()
- if not key or parameter.get("credential_id"):
- continue
- block_parameter_keys.append(key)
- if key not in parameter_keys_seen:
- parameter_keys_seen.add(key)
- parameters.append(_blank_default({"key": key}))
-
- blocks.append(
- WorkflowDefinitionYamlBlocksItem_Code(
- label=_unique(_slug(f"recorded_{_host(source_url)}") or "recorded_steps", used_labels),
- code=code,
- parameter_keys=block_parameter_keys or None,
- parameters=[{"key": key} for key in block_parameter_keys],
- # A non-null prompt is what makes the editor render the code-first node; ""
- # leaves the Goal for the user, because a fabricated one would arm self-heal.
- prompt="",
- steps=derive_code_block_steps(code) or None,
- ).dict()
- )
-
- if not blocks:
- return None
-
- return RenderResult(
- blocks=blocks,
- parameters=parameters,
- mode="code",
- diagnostics=_diagnostics(session, facts, dropped, 0),
- notes=notes,
- )
diff --git a/skyvern/services/browser_recording/v2/resolver.py b/skyvern/services/browser_recording/v2/resolver.py
deleted file mode 100644
index 3485f73c6..000000000
--- a/skyvern/services/browser_recording/v2/resolver.py
+++ /dev/null
@@ -1,393 +0,0 @@
-from __future__ import annotations
-
-import asyncio
-import re
-import time
-import weakref
-from typing import TYPE_CHECKING, Any
-
-import structlog
-
-if TYPE_CHECKING:
- from skyvern.services.browser_recording.v2.ledger import Gesture, GestureLedger
-
-LOG = structlog.get_logger()
-
-_SIMPLE_CSS_ID = re.compile(r"^[A-Za-z_][A-Za-z0-9_-]*$")
-_FRAME_TAGS = frozenset({"IFRAME", "FRAME"})
-_ROOT_NODE_TYPES = frozenset({9, 11})
-_MAX_ANCESTORS = 8
-_MAX_SHADOW_DEPTH = 4
-_MAX_STRUCTURAL_SEGMENTS = 4
-
-
-class Resolver:
- def __init__(self, ledger: GestureLedger) -> None:
- self.ledger = ledger
- self._tasks: set[asyncio.Task[None]] = set()
- self._dom_enabled: weakref.WeakKeyDictionary[Any, None] = weakref.WeakKeyDictionary()
- self._target_ids: weakref.WeakKeyDictionary[Any, str | None] = weakref.WeakKeyDictionary()
- self._child_sessions: weakref.WeakKeyDictionary[Any, Any] = weakref.WeakKeyDictionary()
- self._cache_lock = asyncio.Lock()
-
- def on_gesture(self, gesture: Gesture, cdp_session: Any, page: Any) -> None:
- gesture.is_secret = True
- coroutine = self._resolve(gesture, cdp_session, page)
- try:
- task = asyncio.create_task(coroutine)
- except (RuntimeError, TypeError) as error:
- coroutine.close()
- LOG.debug("Target resolution was not scheduled", error_type=type(error).__name__)
- return
- self._tasks.add(task)
- task.add_done_callback(self._tasks.discard)
-
- def forget_session(self, cdp_session: Any) -> None:
- self._dom_enabled.pop(cdp_session, None)
- self._target_ids.pop(cdp_session, None)
-
- async def _resolve(self, gesture: Gesture, cdp_session: Any, page: Any) -> None:
- started = time.monotonic()
- tag: str | None = None
- role: str | None = None
- try:
- await asyncio.sleep(0)
- x, y = gesture.x, gesture.y
- if x is None or y is None:
- return
-
- target_id = await self._target_id(cdp_session)
- session = cdp_session
- hit, node = await self._resolve_node(session, x, y)
- tag = _tag(node)
- if tag in _FRAME_TAGS and not node.get("contentDocument"):
- child_session = await self._session_for_frame(session, page, _frame_id(hit, node))
- if child_session is None:
- return
- x, y = await self._translate_coordinates(session, node, x, y)
- session = child_session
- hit, node = await self._resolve_node(session, x, y)
- tag = _tag(node)
-
- backend_node_id = _integer(hit.get("backendNodeId")) or _integer(node.get("backendNodeId"))
- if backend_node_id is None:
- return
- attributes = _attributes(node)
- frame_id = _frame_id(hit, node)
- role, accessible_name, ax_properties = await self._ax_metadata(session, backend_node_id)
- selector, shadow_path = await self._locator(session, node, role, accessible_name, frame_id)
- input_type = attributes.get("type")
-
- gesture.target_id = target_id
- gesture.frame_id = frame_id
- gesture.backend_node_id = backend_node_id
- gesture.selector = selector
- gesture.role = role
- gesture.accessible_name = accessible_name
- gesture.tag = tag
- gesture.input_type = input_type
- gesture.shadow_path = shadow_path
- gesture.is_secret = _is_secret(tag, input_type, role, ax_properties)
- LOG.debug(
- "Target resolved",
- tag=tag,
- role=role,
- duration_ms=(time.monotonic() - started) * 1000,
- )
- except asyncio.CancelledError:
- raise
- except Exception as error: # noqa: BLE001
- LOG.debug(
- "Target resolution failed",
- tag=tag,
- role=role,
- duration_ms=(time.monotonic() - started) * 1000,
- error_type=type(error).__name__,
- )
-
- async def _resolve_node(self, session: Any, x: float, y: float) -> tuple[dict, dict]:
- await self._enable_dom(session)
- hit = await session.send(
- "DOM.getNodeForLocation",
- {
- "x": x,
- "y": y,
- "includeUserAgentShadowDOM": False,
- "ignorePointerEventsNone": False,
- },
- )
- backend_node_id = hit.get("backendNodeId")
- described = await session.send("DOM.describeNode", {"backendNodeId": backend_node_id, "depth": 0})
- return hit, described.get("node") or {}
-
- async def _enable_dom(self, session: Any) -> None:
- async with self._cache_lock:
- if session not in self._dom_enabled:
- await session.send("DOM.enable", {})
- self._dom_enabled[session] = None
-
- async def _document_root(self, session: Any) -> int | None:
- """Never cached: a same-session navigation invalidates every nodeId, and this one is
- handed straight to DOM.querySelectorAll for the uniqueness check."""
- await self._enable_dom(session)
- response = await session.send("DOM.getDocument", {"depth": 0})
- return _integer((response.get("root") or {}).get("nodeId"))
-
- async def _target_id(self, session: Any) -> str | None:
- async with self._cache_lock:
- if session not in self._target_ids:
- response = await session.send("Target.getTargetInfo", {})
- target_id = (response.get("targetInfo") or {}).get("targetId")
- self._target_ids[session] = target_id if isinstance(target_id, str) else None
- return self._target_ids[session]
-
- async def _session_for_frame(self, session: Any, page: Any, frame_id: str | None) -> Any | None:
- if frame_id is None:
- return None
- tree = await session.send("Page.getFrameTree", {})
- descriptor = _find_frame(tree.get("frameTree") or {}, frame_id)
- if descriptor is None:
- return None
- url, name = descriptor.get("url"), descriptor.get("name")
- candidates = [frame for frame in page.frames if frame.url == url and (not name or frame.name == name)]
- if not candidates:
- return None
- if len(candidates) == 1:
- return await self._child_session(page, candidates[0])
- # Same url and no distinguishing name: ask each out-of-process frame's own session which
- # frame it is, rather than picking the first match and silently resolving in the wrong one.
- for frame in candidates:
- child_session = await self._child_session(page, frame)
- tree = await child_session.send("Page.getFrameTree", {})
- if ((tree.get("frameTree") or {}).get("frame") or {}).get("id") == frame_id:
- return child_session
- return None
-
- async def _child_session(self, page: Any, frame: Any) -> Any:
- async with self._cache_lock:
- if frame not in self._child_sessions:
- self._child_sessions[frame] = await page.context.new_cdp_session(frame)
- return self._child_sessions[frame]
-
- async def _translate_coordinates(self, session: Any, node: dict, x: int, y: int) -> tuple[int, int]:
- backend_node_id = node.get("backendNodeId")
- response = await session.send("DOM.getBoxModel", {"backendNodeId": backend_node_id})
- quad = (response.get("model") or {}).get("content") or []
- if len(quad) < 8:
- return x, y
- return int(x - min(quad[0::2])), int(y - min(quad[1::2]))
-
- async def _ax_metadata(self, session: Any, backend_node_id: int) -> tuple[str | None, str | None, dict]:
- response = await session.send(
- "Accessibility.getPartialAXTree",
- {"backendNodeId": backend_node_id, "fetchRelatives": False},
- )
- nodes = response.get("nodes") or []
- node = nodes[0] if nodes else {}
- role = _ax_value(node.get("role"))
- name = _ax_value(node.get("name"))
- properties = {
- prop.get("name"): _ax_value(prop.get("value"))
- for prop in node.get("properties") or []
- if isinstance(prop, dict) and isinstance(prop.get("name"), str)
- }
- return role, name, properties
-
- async def _locator(
- self,
- session: Any,
- node: dict,
- role: str | None,
- accessible_name: str | None,
- frame_id: str | None,
- ) -> tuple[str, list[str] | None]:
- shadow_path: list[str] = []
- current = node
- selector = ""
- for _ in range(_MAX_SHADOW_DEPTH):
- root, structural = await self._within_root(session, current)
- selector = await self._unique_selector(session, current, structural, root, role, accessible_name, frame_id)
- if _integer(root.get("nodeType")) != 11:
- return selector, shadow_path or None
- host_id = _integer(root.get("parentId"))
- if host_id is None:
- break
- shadow_path.insert(0, selector)
- role, accessible_name = None, None
- response = await session.send("DOM.describeNode", {"nodeId": host_id, "depth": 0})
- current = response.get("node") or {}
- return selector, shadow_path or None
-
- async def _within_root(self, session: Any, node: dict) -> tuple[dict, list[str]]:
- segments: list[str] = []
- current = node
- for _ in range(_MAX_ANCESTORS):
- parent_id = _integer(current.get("parentId"))
- if parent_id is None:
- break
- response = await session.send("DOM.describeNode", {"nodeId": parent_id, "depth": 1})
- parent = response.get("node") or {}
- segments.insert(0, _structural_segment(current, parent))
- if _integer(parent.get("nodeType")) in _ROOT_NODE_TYPES:
- return parent, segments
- current = parent
- return {}, segments
-
- async def _unique_selector(
- self,
- session: Any,
- node: dict,
- structural: list[str],
- root: dict,
- role: str | None,
- accessible_name: str | None,
- frame_id: str | None,
- ) -> str:
- root_node_id = _integer(root.get("nodeId"))
- if root_node_id is None:
- root_node_id = await self._document_root(session)
- for candidate in _attribute_candidates(_tag(node), _attributes(node)):
- if await self._match_count(session, root_node_id, candidate) == 1:
- return candidate
- if role and accessible_name and await self._ax_match_count(session, frame_id, role, accessible_name) == 1:
- return f'role={role}[name="{_quoted(accessible_name)}"]'
- return " > ".join(structural[-_MAX_STRUCTURAL_SEGMENTS:]) or (_tag(node) or "*").lower()
-
- async def _match_count(self, session: Any, root_node_id: int | None, selector: str) -> int:
- if root_node_id is None:
- return 0
- try:
- response = await session.send("DOM.querySelectorAll", {"nodeId": root_node_id, "selector": selector})
- except Exception: # noqa: BLE001
- return 0
- return len(response.get("nodeIds") or [])
-
- async def _ax_match_count(self, session: Any, frame_id: str | None, role: str, name: str) -> int:
- try:
- response = await session.send("Accessibility.getFullAXTree", {"frameId": frame_id} if frame_id else {})
- except Exception: # noqa: BLE001
- return 0
- return sum(
- 1
- for ax_node in response.get("nodes") or []
- if not ax_node.get("ignored")
- and _ax_value(ax_node.get("role")) == role
- and _ax_value(ax_node.get("name")) == name
- and ax_node.get("backendDOMNodeId") is not None
- )
-
- def close(self) -> None:
- for task in tuple(self._tasks):
- task.cancel()
- self._tasks.clear()
-
-
-def _integer(value: Any) -> int | None:
- return value if isinstance(value, int) else None
-
-
-def _tag(node: dict) -> str | None:
- value = node.get("localName") or node.get("nodeName")
- return value.upper() if isinstance(value, str) else None
-
-
-def _attributes(node: dict) -> dict[str, str]:
- values = node.get("attributes") or []
- return {
- values[index]: values[index + 1]
- for index in range(0, len(values) - 1, 2)
- if isinstance(values[index], str) and isinstance(values[index + 1], str)
- }
-
-
-def _ax_value(value: Any) -> Any:
- return value.get("value") if isinstance(value, dict) else None
-
-
-def _frame_id(hit: dict, node: dict) -> str | None:
- value = node.get("frameId") or hit.get("frameId")
- return value if isinstance(value, str) else None
-
-
-def _find_frame(tree: dict, frame_id: str) -> dict | None:
- frame = tree.get("frame") or {}
- if frame.get("id") == frame_id:
- return frame
- for child in tree.get("childFrames") or []:
- found = _find_frame(child, frame_id)
- if found is not None:
- return found
- return None
-
-
-def _quoted(value: str) -> str:
- return value.replace("\\", "\\\\").replace('"', '\\"')
-
-
-def _attribute_candidates(tag: str | None, attributes: dict[str, str]) -> list[str]:
- html_tag = (tag or "*").lower()
- candidates: list[str] = []
- element_id = attributes.get("id")
- if element_id and not _is_synthetic_id(element_id):
- candidates.append(f"#{element_id}" if _SIMPLE_CSS_ID.match(element_id) else f'[id="{_quoted(element_id)}"]')
- if name := attributes.get("name"):
- candidates.append(f'{html_tag}[name="{_quoted(name)}"]')
- if aria_label := attributes.get("aria-label"):
- candidates.append(f'{html_tag}[aria-label="{_quoted(aria_label)}"]')
- if test_id := attributes.get("data-testid"):
- candidates.append(f'[data-testid="{_quoted(test_id)}"]')
- return candidates
-
-
-def _is_synthetic_id(value: str) -> bool:
- if ":" in value or re.search(r"\d{3,}", value):
- return True
- if re.match(r"^[a-zA-Z]{1,2}[-_]?\d+$", value):
- return True
- return any(
- len(token) >= 6 and re.search(r"\d", token) and re.search(r"[a-zA-Z]", token)
- for token in re.split(r"[-_:.]", value)
- )
-
-
-def _structural_segment(node: dict, parent: dict) -> str:
- node_name = node.get("nodeName")
- siblings = [
- child
- for child in parent.get("children") or []
- if _integer(child.get("nodeType")) == 1 and child.get("nodeName") == node_name
- ]
- position = next(
- (index for index, child in enumerate(siblings, 1) if child.get("backendNodeId") == node.get("backendNodeId")),
- 1,
- )
- return f"{(_tag(node) or '*').lower()}:nth-of-type({position})"
-
-
-def _is_secret(
- tag: str | None,
- input_type: str | None,
- role: str | None,
- ax_properties: dict,
-) -> bool:
- if tag == "INPUT" and (input_type or "").lower() == "password":
- return True
- return role == "textbox" and any(bool(ax_properties.get(name)) for name in ("secure", "password"))
-
-
-_resolvers: dict[str, Resolver] = {}
-
-
-def start_resolver(browser_session_id: str, ledger: GestureLedger) -> Resolver:
- return _resolvers.get(browser_session_id) or _resolvers.setdefault(browser_session_id, Resolver(ledger))
-
-
-def get_resolver(browser_session_id: str) -> Resolver | None:
- return _resolvers.get(browser_session_id)
-
-
-def stop_resolver(browser_session_id: str) -> Resolver | None:
- resolver = _resolvers.pop(browser_session_id, None)
- if resolver is not None:
- resolver.close()
- return resolver
diff --git a/skyvern/services/browser_recording/v2/session.py b/skyvern/services/browser_recording/v2/session.py
deleted file mode 100644
index cb3f3df73..000000000
--- a/skyvern/services/browser_recording/v2/session.py
+++ /dev/null
@@ -1,325 +0,0 @@
-from __future__ import annotations
-
-import asyncio
-import time
-from collections.abc import Callable, Sequence
-from dataclasses import dataclass, field
-from typing import Any, Literal
-from urllib.parse import urlparse
-
-import structlog
-
-from skyvern.services.browser_recording.v2.keyfold import Fact, fold
-from skyvern.services.browser_recording.v2.ledger import Effect, Gesture, start_ledger, stop_ledger
-from skyvern.services.browser_recording.v2.observation import start_observer
-from skyvern.services.browser_recording.v2.resolver import start_resolver
-
-LOG = structlog.get_logger()
-
-INTERPRET_INTERVAL_SECONDS = 0.15
-MAX_TICK_FAILURES = 5
-
-StepKind = Literal["click", "type_text", "press_key", "goto_url", "download", "upload", "dialog"]
-
-_EFFECT_STEPS: dict[str, tuple[StepKind, str]] = {
- "download": ("download", "Download file"),
- "file_chooser": ("upload", "Upload file"),
- "dialog": ("dialog", "Handle dialog"),
-}
-
-
-@dataclass(slots=True)
-class StepV2:
- step_id: str
- kind: StepKind
- title: str
- t_start: float
- t_end: float
- url: str | None
- selector: str | None
- role: str | None
- accessible_name: str | None
- frame_id: str | None
- typed_length: int = 0
- settle_ms: int | None = None
- gesture_seqs: list[int] = field(default_factory=list)
-
-
-@dataclass(slots=True)
-class RecordingUpdateV2:
- session_revision: int
- steps: list[StepV2]
- changed_steps: list[StepV2]
- is_snapshot: bool
- pending: bool
- finalized: bool
- # StepV2 timestamps are monotonic; the wire wants epoch ms.
- epoch_offset_ms: float = 0.0
-
-
-def _target_name(fact: Fact) -> str:
- name = fact.accessible_name or (fact.tag.lower() if fact.tag else "")
- return name.strip() or "element"
-
-
-def _short_url(url: str | None) -> str:
- if not url:
- return "page"
- parsed = urlparse(url)
- if not parsed.netloc:
- return url
- path = "" if parsed.path in ("", "/") else parsed.path
- return f"{parsed.netloc}{path}"
-
-
-def _fact_title(fact: Fact) -> str:
- if fact.kind == "click":
- return f"Click {_target_name(fact)}"
- if fact.kind == "type_text":
- return f"Type into {_target_name(fact)}"
- return f"Press {fact.key or 'key'}"
-
-
-def interpret_steps(browser_session_id: str, gestures: Sequence[Gesture], effects: Sequence[Effect]) -> list[StepV2]:
- steps: dict[int, StepV2] = {}
- by_gesture: dict[int, StepV2] = {}
-
- for fact in fold(gestures):
- first_seq = fact.gesture_seqs[0]
- step = StepV2(
- step_id=f"{browser_session_id}:{first_seq}",
- kind=fact.kind,
- title=_fact_title(fact),
- t_start=fact.t_start,
- t_end=fact.t_end,
- url=fact.url or None,
- selector=fact.selector,
- role=fact.role,
- accessible_name=fact.accessible_name,
- frame_id=fact.frame_id,
- typed_length=fact.typed_length,
- gesture_seqs=list(fact.gesture_seqs),
- )
- steps[first_seq] = step
- for gesture_seq in fact.gesture_seqs:
- by_gesture[gesture_seq] = step
-
- for effect in effects:
- caused = by_gesture.get(effect.caused_by_seq) if effect.caused_by_seq is not None else None
- if effect.kind == "navigation":
- if caused is None and effect.is_main_frame:
- steps[effect.seq] = StepV2(
- step_id=f"{browser_session_id}:{effect.seq}",
- kind="goto_url",
- title=f"Go to {_short_url(effect.url)}",
- t_start=effect.t_received,
- t_end=effect.t_received,
- url=effect.url,
- selector=None,
- role=None,
- accessible_name=None,
- frame_id=effect.frame_id,
- )
- elif effect.kind == "network_settle":
- if caused is not None and effect.busy_ms is not None:
- caused.settle_ms = effect.busy_ms
- elif (effect_step := _EFFECT_STEPS.get(effect.kind)) is not None:
- effect_kind, effect_title = effect_step
- steps[effect.seq] = StepV2(
- step_id=f"{browser_session_id}:{effect.seq}",
- kind=effect_kind,
- title=effect_title,
- t_start=effect.t_received,
- t_end=effect.t_received,
- url=effect.url,
- selector=None,
- role=None,
- accessible_name=None,
- frame_id=effect.frame_id,
- )
-
- return [steps[key] for key in sorted(steps)]
-
-
-class RecordingSessionV2:
- def __init__(
- self,
- *,
- browser_session_id: str,
- organization_id: str,
- workflow_permanent_id: str | None,
- on_update: Callable[[RecordingUpdateV2], None],
- ) -> None:
- self.browser_session_id = browser_session_id
- self.organization_id = organization_id
- self.workflow_permanent_id = workflow_permanent_id
- self.on_update = on_update
- self.ledger = start_ledger(browser_session_id)
- self.resolver = start_resolver(browser_session_id, self.ledger)
- self.observer = start_observer(browser_session_id, self.ledger)
- self.sealed = False
- self.epoch_offset_ms = time.time() * 1000 - time.monotonic() * 1000
- self._steps: list[StepV2] = []
- self._emitted: dict[str, StepV2] = {}
- self._revision = 0
- self._interpreted_version = 0
- self._ticker: asyncio.Task[None] | None = None
-
- @property
- def steps(self) -> list[StepV2]:
- return list(self._steps)
-
- async def attach_page(self, page_key: str, cdp_session: Any) -> None:
- await self.observer.attach_page_session(page_key, cdp_session)
-
- async def attach_browser(self, cdp_session: Any) -> None:
- await self.observer.attach_browser_session(cdp_session)
-
- def pause(self) -> None:
- self.ledger.paused = True
-
- def resume(self) -> None:
- self.ledger.paused = False
-
- def interpret(self) -> None:
- self._emit(is_snapshot=False)
-
- async def seal(self) -> list[StepV2]:
- self.sealed = True
- self.ledger.paused = True
- await self.stop_ticker()
- self._emit(is_snapshot=True)
- return self.steps
-
- def discard(self) -> None:
- self.sealed = True
- self.ledger.paused = True
- if self._ticker is not None:
- self._ticker.cancel()
- self._ticker = None
- stop_ledger(self.browser_session_id)
-
- def resume_streaming(self, on_update: Callable[[RecordingUpdateV2], None]) -> None:
- self.on_update = on_update
- self._start_ticker()
- self._emit(is_snapshot=True)
-
- def _emit(self, *, is_snapshot: bool) -> None:
- self._interpreted_version = self.ledger.version
- steps = interpret_steps(self.browser_session_id, self.ledger.rows(), self.ledger.effects())
- changed = [step for step in steps if self._emitted.get(step.step_id) != step]
- removed = self._emitted.keys() - {step.step_id for step in steps}
- snapshot = is_snapshot or self._revision == 0 or bool(removed)
- if not changed and not snapshot:
- return
-
- self._steps = steps
- self._emitted = {step.step_id: step for step in steps}
- self._revision += 1
- self.on_update(
- RecordingUpdateV2(
- session_revision=self._revision,
- steps=steps,
- changed_steps=[] if snapshot else changed,
- is_snapshot=snapshot,
- pending=not self.sealed,
- finalized=self.sealed,
- epoch_offset_ms=self.epoch_offset_ms,
- )
- )
-
- def _start_ticker(self) -> None:
- if self.sealed or (self._ticker is not None and not self._ticker.done()):
- return
- self._ticker = asyncio.create_task(self._tick())
-
- async def stop_ticker(self) -> None:
- ticker, self._ticker = self._ticker, None
- if ticker is None:
- return
- ticker.cancel()
- try:
- await ticker
- except asyncio.CancelledError:
- pass
-
- async def _tick(self) -> None:
- failures = 0
- while not self.sealed:
- await asyncio.sleep(INTERPRET_INTERVAL_SECONDS)
- if self._interpreted_version == self.ledger.version:
- continue
- try:
- self.interpret()
- except Exception:
- failures += 1
- if failures >= MAX_TICK_FAILURES:
- LOG.warning(
- "Record Browser v2 interpretation failed repeatedly; stopping live updates",
- browser_session_id=self.browser_session_id,
- exc_info=True,
- )
- return
- else:
- failures = 0
-
-
-sessions_v2: dict[str, RecordingSessionV2] = {}
-# A socket that drops without sealing keeps its session alive on purpose so a reconnect can
-# resume it; a client that never comes back would otherwise pin its ledger for the life of the
-# pod. The cap is the only thing that reaches stop_ledger for those.
-MAX_LIVE_SESSIONS = 64
-
-
-def _evict_oldest_session() -> None:
- while len(sessions_v2) >= MAX_LIVE_SESSIONS:
- oldest = next(iter(sessions_v2))
- LOG.warning("Dropping the oldest v2 recording session to stay under the cap", browser_session_id=oldest)
- discard_session_v2(oldest)
-
-
-def start_session_v2(
- *,
- browser_session_id: str,
- organization_id: str,
- workflow_permanent_id: str | None,
- on_update: Callable[[RecordingUpdateV2], None],
-) -> RecordingSessionV2:
- session = sessions_v2.get(browser_session_id)
- if session is not None:
- session.resume_streaming(on_update)
- return session
-
- _evict_oldest_session()
- # A ledger can outlive the session that owned it (a teardown that never sealed).
- stop_ledger(browser_session_id)
- session = RecordingSessionV2(
- browser_session_id=browser_session_id,
- organization_id=organization_id,
- workflow_permanent_id=workflow_permanent_id,
- on_update=on_update,
- )
- sessions_v2[browser_session_id] = session
- session.resume_streaming(on_update)
- return session
-
-
-def get_session_v2(browser_session_id: str) -> RecordingSessionV2 | None:
- return sessions_v2.get(browser_session_id)
-
-
-async def stop_session_v2(browser_session_id: str) -> list[StepV2]:
- session = sessions_v2.pop(browser_session_id, None)
- if session is None:
- return []
- steps = await session.seal()
- # The sealed session keeps its ledger for the commit path, but nothing may keep
- # observing: stop_ledger detaches the observer and closes the resolver.
- stop_ledger(browser_session_id)
- return steps
-
-
-def discard_session_v2(browser_session_id: str) -> None:
- session = sessions_v2.pop(browser_session_id, None)
- if session is not None:
- session.discard()
diff --git a/skyvern/services/browser_recording/v2/tap.py b/skyvern/services/browser_recording/v2/tap.py
deleted file mode 100644
index bc0fc0a8d..000000000
--- a/skyvern/services/browser_recording/v2/tap.py
+++ /dev/null
@@ -1,137 +0,0 @@
-import functools
-from collections.abc import Callable
-from typing import Any, ParamSpec
-
-import structlog
-
-from skyvern.services.browser_recording.v2.ledger import Gesture, GestureKind, GestureLedger, get_ledger
-from skyvern.services.browser_recording.v2.resolver import get_resolver
-
-LOG = structlog.get_logger(__name__)
-P = ParamSpec("P")
-
-
-def _never_raises(tap: Callable[P, None]) -> Callable[P, None]:
- # The taps sit on the live input path; a recording bug must never close the user's input channel.
- @functools.wraps(tap)
- def guarded(*args: P.args, **kwargs: P.kwargs) -> None:
- try:
- tap(*args, **kwargs)
- except Exception:
- LOG.warning("Record Browser v2 tap failed; gesture dropped", tap=tap.__name__, exc_info=True)
-
- return guarded
-
-
-_MOUSE_KINDS: dict[str, GestureKind] = {
- "mousePressed": "mouse_pressed",
- "mouseReleased": "mouse_released",
- "mouseMoved": "mouse_moved",
-}
-_NAVIGATION_KINDS: dict[str, GestureKind] = {
- "navigateEvent": "navigate",
- "goBackEvent": "go_back",
- "goForwardEvent": "go_forward",
- "reloadEvent": "reload",
-}
-
-
-def _ledger_for(browser_session_id: str | None) -> GestureLedger | None:
- if browser_session_id is None:
- return None
- return get_ledger(browser_session_id)
-
-
-@_never_raises
-def tap_pipelined(
- browser_session_id: str | None,
- kind: str,
- validated: dict,
- received_at: float,
- page: Any,
- cdp_session: Any,
-) -> None:
- if (ledger := _ledger_for(browser_session_id)) is None:
- return
-
- gesture_kind: GestureKind | None
- if kind == "mouseEvent":
- gesture_kind = _MOUSE_KINDS.get(validated.get("type") or "")
- elif kind == "wheelEvent":
- gesture_kind = "wheel"
- elif kind == "keyEvent":
- gesture_kind = "key"
- else:
- gesture_kind = None
- if gesture_kind is None:
- return
-
- gesture = ledger.append(
- Gesture(
- seq=0,
- t_received=received_at,
- kind=gesture_kind,
- page_key=str(id(page)),
- url=getattr(page, "url", ""),
- x=validated.get("x"),
- y=validated.get("y"),
- button=validated.get("button"),
- click_count=validated.get("clickCount"),
- modifiers=validated.get("modifiers", 0),
- key=validated.get("key"),
- code=validated.get("code"),
- text=validated.get("text"),
- windows_virtual_key_code=validated.get("windowsVirtualKeyCode"),
- key_event_type=validated.get("type") if kind == "keyEvent" else None,
- delta_x=validated.get("deltaX"),
- delta_y=validated.get("deltaY"),
- )
- )
- if (
- gesture is not None
- and gesture_kind == "mouse_pressed"
- and (resolver := get_resolver(ledger.browser_session_id)) is not None
- ):
- resolver.on_gesture(gesture, cdp_session, page)
-
-
-@_never_raises
-def tap_navigation(
- browser_session_id: str | None,
- kind: str,
- msg: dict,
- received_at: float,
- page: Any,
-) -> None:
- if (ledger := _ledger_for(browser_session_id)) is None or (gesture_kind := _NAVIGATION_KINDS.get(kind)) is None:
- return
-
- ledger.append(
- Gesture(
- seq=0,
- t_received=received_at,
- kind=gesture_kind,
- page_key=str(id(page)),
- url=getattr(page, "url", ""),
- target_url=msg.get("url") if kind == "navigateEvent" else None,
- )
- )
-
-
-@_never_raises
-def tap_paste(browser_session_id: str | None, text: str, received_at: float) -> None:
- if (ledger := _ledger_for(browser_session_id)) is None:
- return
- rows = ledger.rows()
- previous = rows[-1] if rows else None
-
- ledger.append(
- Gesture(
- seq=0,
- t_received=received_at,
- kind="paste",
- page_key=previous.page_key if previous else "",
- url=previous.url if previous else "",
- text=text,
- )
- )
diff --git a/skyvern/services/browser_recording/v2/wire.py b/skyvern/services/browser_recording/v2/wire.py
deleted file mode 100644
index f5ed2db93..000000000
--- a/skyvern/services/browser_recording/v2/wire.py
+++ /dev/null
@@ -1,40 +0,0 @@
-from skyvern.services.browser_recording.types import (
- ActionKind,
- RecordingDraftStep,
- RecordingDraftStepEditableField,
-)
-from skyvern.services.browser_recording.v2.session import StepV2
-
-# The panel renders v1 draft steps, so v2 rides the same wire shape. Kinds the panel
-# cannot render (download, upload, dialog) stay in the ledger until PR-9 gives them UI.
-_V2_ACTION_KINDS: dict[str, ActionKind] = {
- "click": ActionKind.CLICK,
- "type_text": ActionKind.INPUT_TEXT,
- "press_key": ActionKind.CLICK,
- "goto_url": ActionKind.URL_CHANGE,
-}
-
-
-def draft_steps_from_v2(steps: list[StepV2], epoch_offset_ms: float) -> list[RecordingDraftStep]:
- draft_steps = []
- for step in steps:
- action_kind = _V2_ACTION_KINDS.get(step.kind)
- if action_kind is None:
- continue
- is_goto = step.kind == "goto_url"
- draft_steps.append(
- RecordingDraftStep(
- step_id=step.step_id,
- action_kind=action_kind,
- block_type="goto_url" if is_goto else "action",
- label=step.title,
- title=step.title,
- navigation_goal=None if is_goto else step.title,
- url=step.url,
- editable_fields=[RecordingDraftStepEditableField.TITLE]
- + ([RecordingDraftStepEditableField.URL] if is_goto else []),
- timestamp_start=step.t_start * 1000 + epoch_offset_ms,
- timestamp_end=step.t_end * 1000 + epoch_offset_ms,
- )
- )
- return draft_steps
diff --git a/skyvern/webeye/actions/handler.py b/skyvern/webeye/actions/handler.py
index 96bd482a5..d5fc86c76 100644
--- a/skyvern/webeye/actions/handler.py
+++ b/skyvern/webeye/actions/handler.py
@@ -11,6 +11,7 @@ import time
import urllib.parse
import uuid
from collections import deque
+from contextvars import ContextVar
from datetime import datetime, timedelta, timezone
from enum import StrEnum
from pathlib import Path
@@ -172,6 +173,7 @@ from skyvern.webeye.browser_engine import UNSET_SELECTION, BrowserEngineSelectio
from skyvern.webeye.browser_factory import initialize_download_dir, read_download_failure, resolve_artifact_path
from skyvern.webeye.browser_state import BLANK_PAGE_URLS, BrowserState
from skyvern.webeye.cdp_download_interceptor import (
+ BROWSER_DOWNLOAD_EVENT_ADMISSION_GRACE_SECONDS,
DOWNLOAD_MIME_TYPES,
MAX_FILE_SIZE_BYTES,
begin_requested_download_for_context,
@@ -1201,6 +1203,12 @@ async def _save_adopted_session_download(
return None
+# Set for the duration of a file-download block's non-download click that is authorized as a
+# false-click candidate. Read by handle_click_action to enable the same-action download bypass of
+# the expensive dropdown/custom-select rescrape; never gates persistence or task finalization.
+_false_click_download_eligible: ContextVar[bool] = ContextVar("false_click_download_eligible", default=False)
+
+
def _remove_download_listener(page: Page, callback: Callable[[Download], None]) -> None:
off = getattr(page, "off", None)
if callable(off):
@@ -1215,6 +1223,36 @@ def _remove_download_listener(page: Page, callback: Callable[[Download], None])
LOG.warning("Page does not support removing download listeners")
+def _register_false_click_download_probe(page: Page, observed: asyncio.Event) -> Callable[[], None]:
+ """Flag ``observed`` when a download is minted on the clicked page or a popup it spawns
+ during the click window. Returns a cleanup that removes every listener it installed."""
+ download_handles: list[tuple[Page, Callable[[Download], None]]] = []
+
+ def _flag_download(_download: Download) -> None:
+ observed.set()
+
+ def _on_popup(popup_page: Page) -> None:
+ popup_page.on("download", _flag_download)
+ download_handles.append((popup_page, _flag_download))
+
+ page.on("download", _flag_download)
+ download_handles.append((page, _flag_download))
+ page.on("popup", _on_popup)
+
+ def _cleanup() -> None:
+ try:
+ _remove_popup_listener(page, _on_popup)
+ except Exception:
+ LOG.warning("Failed to remove false-click download popup listener", exc_info=True)
+ for observed_page, callback in download_handles:
+ try:
+ _remove_download_listener(observed_page, callback)
+ except Exception:
+ LOG.warning("Failed to remove false-click download listener", exc_info=True)
+
+ return _cleanup
+
+
def _remove_popup_listener(page: Page, callback: Callable[[Page], None]) -> None:
off = getattr(page, "off", None)
if callable(off):
@@ -2613,6 +2651,112 @@ def _exact_value_input_type(input_type: str | None) -> str:
return (input_type or "").strip().lower()
+_DATE_VALUE_SEPARATORS = re.compile(r"[^0-9]+")
+_DATE_MASK_SEPARATORS = re.compile(r"[^a-z]+")
+
+
+def _strict_date_mask_order(placeholder: str | None) -> tuple[str, ...] | None:
+ # The day/month/year order a strict placeholder mask declares ("mm/dd/yyyy" -> ("m","d","y")), or None
+ # when it is not a fully-specified mask: each separator-delimited token must be a pure run of one date
+ # letter (d/dd, m/mm, yyyy), so prose, first-letter lookalikes, and partial years never define an order.
+ if not placeholder:
+ return None
+ tokens = [token for token in _DATE_MASK_SEPARATORS.split(placeholder.strip().lower()) if token]
+ if len(tokens) != 3:
+ return None
+ order: list[str] = []
+ for token in tokens:
+ if re.fullmatch(r"d{1,2}", token):
+ order.append("d")
+ elif re.fullmatch(r"m{1,2}", token):
+ order.append("m")
+ elif re.fullmatch(r"y{4}", token):
+ order.append("y")
+ else:
+ return None
+ if sorted(order) != ["d", "m", "y"]:
+ return None
+ return tuple(order)
+
+
+def _canonical_iso_date(text: str, placeholder: str | None) -> str | None:
+ # ``text`` as the YYYY-MM-DD an <input type=date> accepts, or None when it is not a date or the order
+ # cannot be trusted. Order comes from the field's own strict mask; without a mask only an unambiguous
+ # reading (four-digit year first, or a component above 12 pinning the day) is taken, and datetime()
+ # rejects impossible calendar dates -- so an ambiguous value is refused, never written as a wrong date.
+ parts = [part for part in _DATE_VALUE_SEPARATORS.split(text.strip()) if part]
+ if len(parts) != 3 or not all(part.isdigit() for part in parts):
+ return None
+ order = _strict_date_mask_order(placeholder)
+ if order is None:
+ if len(parts[0]) == 4:
+ order = ("y", "m", "d")
+ elif len(parts[2]) == 4 and int(parts[0]) > 12:
+ order = ("d", "m", "y")
+ elif len(parts[2]) == 4 and int(parts[1]) > 12:
+ order = ("m", "d", "y")
+ else:
+ return None
+ fields = dict(zip(order, parts))
+ if len(fields) != 3 or len(fields["y"]) != 4:
+ return None
+ try:
+ return datetime(int(fields["y"]), int(fields["m"]), int(fields["d"])).strftime("%Y-%m-%d")
+ except ValueError:
+ return None
+
+
+def _is_malformed_value_error(exc: BaseException) -> bool:
+ # locator.fill() raises "Malformed value" when the live node is a structured input (a date input takes
+ # only YYYY-MM-DD) and the value is not canonical; it validates before committing, so the field is left
+ # untouched and the write can be retried in canonical form.
+ return "malformed value" in str(exc).lower()
+
+
+async def _live_date_input_canonical_value(
+ skyvern_element: SkyvernElement,
+ text: str,
+ fill_error: BaseException,
+ engine_selection: BrowserEngineSelection | None,
+) -> str | None:
+ # The canonical YYYY-MM-DD to re-fill after locator.fill() rejected ``text`` as malformed, or None when
+ # the failure is not a live date input rejecting a recoverable value. The LIVE type and placeholder --
+ # not the stale scraped type -- decide recovery, so a non-date field or an unrelated error yields None
+ # and the caller re-raises unchanged.
+ if not (_is_selected_engine_error(fill_error, engine_selection) and _is_malformed_value_error(fill_error)):
+ return None
+ try:
+ if _exact_value_input_type(await skyvern_element.get_attr("type", mode="dynamic")) != "date":
+ return None
+ placeholder = await skyvern_element.get_attr("placeholder", mode="dynamic")
+ except Exception:
+ # A live read can itself fail when a navigation/DOM race destroys the node; without recovery
+ # evidence return None so the caller re-raises the original malformed-value failure rather than
+ # letting this secondary read error mask it (and be tolerated elsewhere as a false success).
+ return None
+ return _canonical_iso_date(text, placeholder)
+
+
+async def _recover_atomic_fill_as_live_date(
+ skyvern_element: SkyvernElement,
+ text: str,
+ fill_error: BaseException,
+ engine_selection: BrowserEngineSelection | None,
+) -> str | None:
+ # Single owner of the malformed-value recovery shared by every path that atomically fills a native
+ # exact-value input: the ordinary branch and the secret read-back branch. After an atomic fill raised,
+ # a field scraped as text but live type=date rejects a displayed locale value as malformed, so re-fill
+ # in canonical YYYY-MM-DD read from the live DOM. Returns the committed canonical value -- the field then
+ # holds the ISO value, not ``text``, so the caller reads that value back, not ``text``. Returns None for an
+ # ambiguous, non-date, or unrelated failure so the caller re-raises it unchanged and keeps its existing
+ # semantics. No value is logged.
+ canonical = await _live_date_input_canonical_value(skyvern_element, text, fill_error, engine_selection)
+ if canonical is None:
+ return None
+ await skyvern_element.input_fill(text=canonical)
+ return canonical
+
+
def _secret_readback_is_unreadable_mask(actual_value: str | None, *, is_password: bool) -> bool:
# Unreadable only when the read-back is ENTIRELY mask glyphs (optionally separator-grouped, e.g.
# "•••• ••••" / "****-****"): a custom reveal/mask widget is rendering only bullets, not the real
@@ -2699,13 +2843,31 @@ async def _fill_secret_with_readback(
# Parity with the ordinary atomic-fill branch: re-resolve a locator that went stale between scrape and
# write so a re-mounted controlled input is filled instead of timing out on a zero-match cached target.
+ # The value the field is expected to hold after the first write and the transport the retry uses. Both stay
+ # the intended secret unless a stale-scraped date recovered to canonical ISO below, in which case the field
+ # holds YYYY-MM-DD and the retry must re-fill that ISO atomically (never the locale text, never the
+ # per-character seam, which corrupts a structured date value).
+ readback_expected = text
+ date_recovered = False
await skyvern_element.refresh_locator_if_stale()
if sequential_first:
await skyvern_element.input_sequentially(text=text)
else:
- await skyvern_element.input_fill(text=text)
+ try:
+ await skyvern_element.input_fill(text=text)
+ except Exception as fill_error:
+ # A stale-scraped text field that is live type=date rejects the displayed locale value as
+ # malformed; recover in canonical ISO form. It then holds YYYY-MM-DD, not ``text`` -- but a
+ # controlled date node can still accept that fill and asynchronously clear/rewrite it, so the
+ # read-back below verifies the canonical value rather than trusting the accepted write. A
+ # non-date/ambiguous failure re-raises unchanged.
+ canonical = await _recover_atomic_fill_as_live_date(skyvern_element, text, fill_error, engine_selection)
+ if canonical is None:
+ raise
+ readback_expected = canonical
+ date_recovered = True
- if _secret_input_cannot_round_trip(text, maxlength=maxlength):
+ if _secret_input_cannot_round_trip(readback_expected, maxlength=maxlength):
LOG.info(
"Leaving credential as filled: field cannot round-trip the value by its declared contract",
element_id=skyvern_element.get_id(),
@@ -2731,7 +2893,7 @@ async def _fill_secret_with_readback(
return None
# Exact equality first: a value that round-trips exactly is confirmed, even one made only of mask-like
# characters -- so an all-"*" secret is a match, never misclassified as an unreadable mask.
- if not _secret_readback_is_mismatch(text, actual_value):
+ if not _secret_readback_is_mismatch(readback_expected, actual_value):
return None
if _secret_readback_is_unreadable_mask(actual_value, is_password=is_password):
@@ -2745,10 +2907,15 @@ async def _fill_secret_with_readback(
# attr, so it stayed atomic-fill eligible): repeating the same atomic fill can never emit the key events
# that advance through the sibling boxes. Re-resolve a possibly re-mounted locator, then retry with the
# sequential transport instead of another identical fill. The read-back below still verifies the target and
- # fails closed -- a sequential write that merely did not raise is not success (SKY-13821).
+ # fails closed -- a sequential write that merely did not raise is not success (SKY-13821). A recovered date
+ # instead re-fills the canonical ISO atomically: the per-character seam hard-throws on a structured date
+ # input and the locale text is not what the field accepts.
await skyvern_element.refresh_locator_if_stale()
await skyvern_element.input_clear()
- await skyvern_element.input_sequentially(text=text)
+ if date_recovered:
+ await skyvern_element.input_fill(text=readback_expected)
+ else:
+ await skyvern_element.input_sequentially(text=text)
actual_value, navigated = await _read_back()
if navigated:
LOG.info(
@@ -2756,7 +2923,7 @@ async def _fill_secret_with_readback(
element_id=skyvern_element.get_id(),
)
return None
- if _secret_readback_matches(text, actual_value):
+ if _secret_readback_matches(readback_expected, actual_value):
return None
LOG.warning(
@@ -3661,24 +3828,37 @@ class ActionHandler:
_action_span.set_attribute("triggers_download", trigger_download_action)
_tracer = otel_trace.get_tracer("skyvern")
if not trigger_download_action:
+ # Authorizes the same-action download bypass in handle_click_action. This is decoupled
+ # from popup grace: the bypass only skips the dead dropdown rescrape and never persists,
+ # so a FileDownloadBlock false-click candidate arms it regardless of the grace setting.
+ false_click_bypass_eligible = (
+ file_download_false_click_eligible and isinstance(action, ClickAction) and action.download is False
+ )
+ # The popup-grace persistence wrapper stays separately gated: it captures/persists a
+ # download the click mints on a popup, which is only worth its cost when grace > 0.
observe_false_click = (
- file_download_false_click_eligible
- and isinstance(action, ClickAction)
- and action.download is False
+ false_click_bypass_eligible
and browser_state is not None
and settings.FILE_DOWNLOAD_FALSE_CLICK_POPUP_GRACE_SECONDS > 0
)
if not observe_false_click:
- with traced_span(_tracer, "skyvern.agent.action.handle_inner") as _hi_span:
- apply_context_attrs(_hi_span)
- results = await ActionHandler._handle_action(
- scraped_page=scraped_page,
- task=task,
- step=step,
- page=page,
- action=action,
- allow_stale_refresh=allow_stale_refresh,
- )
+ false_click_eligible_token = (
+ _false_click_download_eligible.set(True) if false_click_bypass_eligible else None
+ )
+ try:
+ with traced_span(_tracer, "skyvern.agent.action.handle_inner") as _hi_span:
+ apply_context_attrs(_hi_span)
+ results = await ActionHandler._handle_action(
+ scraped_page=scraped_page,
+ task=task,
+ step=step,
+ page=page,
+ action=action,
+ allow_stale_refresh=allow_stale_refresh,
+ )
+ finally:
+ if false_click_eligible_token is not None:
+ _false_click_download_eligible.reset(false_click_eligible_token)
else:
assert browser_state is not None
page_url_before_download = page.url
@@ -3773,6 +3953,7 @@ class ActionHandler:
download_popup, browser_state, page, page_url_before_download
)
+ false_click_eligible_token = _false_click_download_eligible.set(True)
try:
with traced_span(_tracer, "skyvern.agent.action.handle_inner") as _hi_span:
apply_context_attrs(_hi_span)
@@ -3800,6 +3981,7 @@ class ActionHandler:
raise
await process_captured_download(results)
finally:
+ _false_click_download_eligible.reset(false_click_eligible_token)
try:
_remove_popup_listener(page, on_popup)
except Exception:
@@ -5709,6 +5891,13 @@ async def handle_click_action(
return await handle_upload_file_action(upload_file_action, page, scraped_page, task, step)
else:
incremental_scraped: IncrementalScrapePage | None = None
+ # Inside a file-download block, a non-download click authorized as a false-click candidate can
+ # still mint the file. If it does, the post-click dropdown/custom-select rescrape below is dead
+ # work that costs ~90-120s; observing the download lets us skip straight to the click result.
+ false_click_download_observed: asyncio.Event | None = (
+ asyncio.Event() if _false_click_download_eligible.get() else None
+ )
+ remove_download_probe: Callable[[], None] | None = None
try:
engine_selection = resolve_engine_selection_for_task(task, app.BROWSER_MANAGER)
skyvern_frame = await SkyvernFrame.create_instance(
@@ -5719,6 +5908,8 @@ async def handle_click_action(
engine_selection=engine_selection,
)
await incremental_scraped.start_listen_dom_increment(await skyvern_element.get_element_handler())
+ if false_click_download_observed is not None:
+ remove_download_probe = _register_false_click_download_probe(page, false_click_download_observed)
has_onclick_attr = await skyvern_element.has_attr("onclick", mode="static")
results = await chain_click(
@@ -5738,12 +5929,37 @@ async def handle_click_action(
return results
try:
+ if false_click_download_observed is not None and false_click_download_observed.is_set():
+ LOG.info(
+ "Same-action download observed for a file-download click; bypassing dropdown rescrape",
+ element_id=skyvern_element.get_id(),
+ )
+ return results
+
if has_onclick_attr:
LOG.info(
"The element has onclick attribute, waiting for 1 second to load new elements", action=action
)
await skyvern_frame.safe_wait_for_animation_end(before_wait_sec=1, caller="click.onclick")
+ if false_click_download_observed is not None:
+ # Browser.downloadWillBegin can arrive on a later loop turn, just after the
+ # click await resolves; give the real probe event a narrow admission window
+ # before paying for the sequential rescrape.
+ try:
+ await asyncio.wait_for(
+ false_click_download_observed.wait(),
+ timeout=BROWSER_DOWNLOAD_EVENT_ADMISSION_GRACE_SECONDS,
+ )
+ except asyncio.TimeoutError:
+ pass
+ if false_click_download_observed.is_set():
+ LOG.info(
+ "Late same-action download observed for a file-download click; bypassing dropdown rescrape",
+ element_id=skyvern_element.get_id(),
+ )
+ return results
+
if sequential_click_result := await handle_sequential_click_with_submit_bypass(
action=action,
action_history=results,
@@ -5773,6 +5989,8 @@ async def handle_click_action(
return results
finally:
+ if remove_download_probe is not None:
+ remove_download_probe()
if incremental_scraped:
try:
await incremental_scraped.stop_listen_dom_increment()
@@ -7271,7 +7489,18 @@ async def _handle_input_text_action(
)
if fill_atomically:
await skyvern_element.refresh_locator_if_stale()
- await skyvern_element.input_fill(text)
+ try:
+ await skyvern_element.input_fill(text)
+ except Exception as fill_error:
+ # A field scraped as text but live type=date rejects a locale value here; recover in
+ # canonical form from the live DOM, else re-raise so an ambiguous or non-date failure
+ # keeps its existing semantics.
+ if (
+ await _recover_atomic_fill_as_live_date(skyvern_element, text, fill_error, engine_selection)
+ is None
+ ):
+ raise
+ return [ActionSuccess()]
else:
await skyvern_element.input_sequentially(text=text)
# The residual per-character seam can still lose a leading prefix on a caret-resetting
@@ -10743,7 +10972,7 @@ _SELECTED_LABEL_PREFIXES = ("selected ", "selected:")
_CUSTOM_SELECT_MATCHED_STATE_JS = r"""
(el) => {
- const normalize = (value) => (value ?? "").replace(/\s+/g, " ").trim().toLowerCase();
+ const normalize = (value) => String(value ?? "").replace(/\s+/g, " ").trim().toLowerCase();
const label = [
el.textContent,
el.getAttribute("aria-label"),
@@ -10781,7 +11010,7 @@ _CUSTOM_SELECT_COMMITTED_STATE_JS = r"""
const anchorIsComboboxInput = args.anchorIsComboboxInput;
const allowAriaSelectedOptionTokens = args.allowAriaSelectedOptionTokens !== false;
const allowSingleValueScope = args.allowSingleValueScope === true;
- const normalize = (value) => (value ?? "").replace(/\s+/g, " ").trim().toLowerCase();
+ const normalize = (value) => String(value ?? "").replace(/\s+/g, " ").trim().toLowerCase();
const splitValues = (value) => {
const normalized = normalize(value);
if (!normalized) return [];
@@ -10971,6 +11200,20 @@ def _custom_select_matched_state_confirms_pre_click(state: dict | None, expected
return bool(state.get("ariaSelected"))
+async def _custom_select_committed_readback_confirms(
+ selected_element: SkyvernElement, requested_value: str | None
+) -> bool:
+ # A strict scope read can miss a commit the chosen option itself reflects, so re-read the option's
+ # own matched state before ownership recovery. Exact normalized label plus a committed signal only:
+ # a bare single-select highlight, a mismatch, or an unreadable state is never success (SKY-14909).
+ expected_label = _normalize_select_shadow_text(requested_value)
+ if not expected_label:
+ return False
+ return _custom_select_matched_state_confirms_pre_click(
+ await _read_custom_select_matched_state(selected_element), expected_label
+ )
+
+
async def _custom_select_scope_confirms_committed(
*,
readback_scope_element: SkyvernElement | None,
@@ -11623,6 +11866,42 @@ def _matching_custom_select_anchor_ids(
]
+def _collect_subtree_element_ids(subtrees: list[dict]) -> list[str]:
+ ids: list[str] = []
+ stack = list(subtrees)
+ while stack:
+ node = stack.pop()
+ node_id = node.get("id")
+ if node_id:
+ ids.append(str(node_id))
+ stack.extend(node.get("children", []) or [])
+ return ids
+
+
+def _resolve_already_open_owned_listbox(
+ *,
+ current_element_id: str,
+ scraped_page_after_open: ScrapedPage,
+) -> tuple[str, list[dict]] | None:
+ """Resolve the anchor's single aria-owned listbox when the strict new-element diff is empty
+ because the combobox was already open.
+
+ Returns ``(anchor_id, owned_subtrees)`` only when the anchor is a ``role=combobox`` that is
+ currently ``aria-expanded=true`` and uniquely owns exactly one listbox subtree; otherwise
+ ``None`` so the caller stays fail-closed and raises no-incremental.
+ """
+ original_anchor = scraped_page_after_open.id_to_element_dict.get(current_element_id)
+ if original_anchor is None:
+ return None
+ attributes = original_anchor.get("attributes") or {}
+ if str(attributes.get("aria-expanded") or "").lower() != "true":
+ return None
+ return _resolve_owned_custom_select_recovery(
+ original_anchor=original_anchor,
+ refreshed_page=scraped_page_after_open,
+ )
+
+
@traced(name="skyvern.agent.dropdown.select_emerging")
async def select_from_emerging_elements(
current_element_id: str,
@@ -11656,7 +11935,26 @@ async def select_from_emerging_elements(
]
if len(new_interactable_element_ids) == 0:
- raise NoIncrementalElementFoundForCustomSelection(element_id=current_element_id)
+ already_open = _resolve_already_open_owned_listbox(
+ current_element_id=current_element_id,
+ scraped_page_after_open=scraped_page_after_open,
+ )
+ if already_open is None:
+ raise NoIncrementalElementFoundForCustomSelection(element_id=current_element_id)
+ _anchor_id, owned_subtrees = already_open
+ new_element_ids = set(_collect_subtree_element_ids(owned_subtrees))
+ new_interactable_element_ids = [
+ element_id
+ for element_id in new_element_ids
+ if (await dom_after_open.get_skyvern_element_by_id(element_id)).is_interactable()
+ ]
+ if len(new_interactable_element_ids) == 0:
+ raise NoIncrementalElementFoundForCustomSelection(element_id=current_element_id)
+ LOG.info(
+ "Custom-select combobox already open; selecting from its aria-owned listbox",
+ current_element_id=current_element_id,
+ owned_option_count=len(new_interactable_element_ids),
+ )
# Extract minimal subtrees rooted at new elements — avoids sending the full page DOM
# which gets truncated on large pages, losing portal-rendered dropdown items.
@@ -11840,7 +12138,11 @@ async def select_from_emerging_elements(
original_anchor = scraped_page_after_open.id_to_element_dict.get(current_element_id)
await selected_element.scroll_into_view()
- await selected_element.click(page=page, engine_selection=engine_selection)
+ await selected_element.click(
+ page=page,
+ engine_selection=engine_selection,
+ intercept_js_fallback_label=requested_value,
+ )
readback_scope_element = await _resolve_custom_select_readback_scope_element(
get_readback_scope_element=get_readback_scope_element,
target_value=options.target_value or "",
@@ -11901,6 +12203,21 @@ async def select_from_emerging_elements(
try:
refreshed_page = await scraped_page_after_open.generate_scraped_page_without_screenshots()
refreshed_dom = DomUtil(scraped_page=refreshed_page, page=page, engine_selection=engine_selection)
+ # A strict scope verify can read not-committed while the chosen option itself reflects the commit;
+ # honor that BEFORE any ownership-dependent branch (missing, ambiguous, or no owned listbox) so a
+ # set field is not failed just because recovery ownership cannot be resolved.
+ if await _custom_select_committed_readback_confirms(selected_element, requested_value):
+ _log_custom_select_verification_outcome(
+ "Custom-select committed readback outcome",
+ phase="committed_readback",
+ settles=recovery_settles,
+ committed=True,
+ verification_branch="matched_state",
+ verification_reason="committed_readback",
+ recovery_attempted=False,
+ recovery_succeeded=False,
+ )
+ return ActionSuccess()
ownership = _custom_select_anchor_ownership(original_anchor)
if ownership is None:
raise ValueError("Custom-select recovery ownership is missing")
diff --git a/skyvern/webeye/browser_factory.py b/skyvern/webeye/browser_factory.py
index d4b358d5f..6f5a6deb9 100644
--- a/skyvern/webeye/browser_factory.py
+++ b/skyvern/webeye/browser_factory.py
@@ -48,6 +48,7 @@ from skyvern.exceptions import (
from skyvern.forge import app
from skyvern.forge.sdk.api.files import get_download_dir, make_temp_directory, resolve_run_download_id
from skyvern.forge.sdk.browser_network_egress_monitor import BrowserNetworkEgressMonitor
+from skyvern.forge.sdk.core.hashing import diagnostic_fingerprint
from skyvern.forge.sdk.core.http_request_authorization import (
RunScopedRedirectHopAuthorizer,
deny_unenrolled_redirect_hop,
@@ -244,6 +245,7 @@ async def _apply_origin_scoped_headers(
else:
await route.fallback()
+ app.AGENT_FUNCTION.on_origin_scoped_headers_route_installed(browser_context, target_origin)
await browser_context.route("**/*", apply_headers)
@@ -422,7 +424,7 @@ def set_download_file_listener(
"Download artifact absent on this connection; skipping worker-side rename",
workflow_run_id=workflow_run_id,
task_id=task_id,
- suggested_filename=download.suggested_filename,
+ suggested_filename_fp=diagnostic_fingerprint(download.suggested_filename),
)
return
if file_path.suffix:
@@ -432,7 +434,7 @@ def set_download_file_listener(
"No file extensions, going to add file extension automatically",
workflow_run_id=workflow_run_id,
task_id=task_id,
- suggested_filename=download.suggested_filename,
+ suggested_filename_fp=diagnostic_fingerprint(download.suggested_filename),
url=_redact_url_query(download.url),
)
suffix = Path(download.suggested_filename).suffix
@@ -456,7 +458,7 @@ def set_download_file_listener(
"Add extension according to the parsed query params of download url",
workflow_run_id=workflow_run_id,
task_id=task_id,
- filename=value,
+ filename_fp=diagnostic_fingerprint(value),
)
file_path.rename(str(file_path) + suffix)
return
diff --git a/skyvern/webeye/browser_state.py b/skyvern/webeye/browser_state.py
index 81037ab0c..f7c1b1ed0 100644
--- a/skyvern/webeye/browser_state.py
+++ b/skyvern/webeye/browser_state.py
@@ -28,6 +28,9 @@ class BrowserState(Protocol):
# The per-run pinned engine (or None for states built outside the per-run engine seam), so
# recovery code can classify driver-native errors against THIS run's selected engine.
engine_selection: BrowserEngineSelection | None
+ # HTTP status of the most recent navigate_to_url (None until one runs, or when it produced no
+ # response). The Task V3 loop reads it to classify a dead/removed starting URL.
+ last_navigation_status: int | None
def add_on_close(self, callback: Callable[[], Awaitable[None]]) -> None: ...
diff --git a/skyvern/webeye/dialog_handler.py b/skyvern/webeye/dialog_handler.py
index 87e883315..f01a13f46 100644
--- a/skyvern/webeye/dialog_handler.py
+++ b/skyvern/webeye/dialog_handler.py
@@ -14,9 +14,25 @@ from skyvern.forge.prompts import prompt_engine
from skyvern.forge.sdk.api.llm.api_handler_factory import get_org_aware_secondary_llm_api_handler
from skyvern.forge.sdk.browser_action_preflight import preflight_dialog_response
from skyvern.forge.sdk.core import skyvern_context
+from skyvern.webeye.browser_errors import is_target_closed_message
LOG = structlog.get_logger()
+_DIALOG_GONE_MESSAGE_MARKER = "no dialog is showing"
+
+
+def _is_dialog_gone_error(exc: BaseException) -> bool:
+ """Whether the dialog was already gone by the time we answered it — the page navigated, closed,
+ or something else dismissed it first.
+
+ Matched on message text rather than exception class: the deployed driver is patchright, whose
+ error type is not the ``playwright.async_api`` one this module imports, so a class-based
+ ``except`` would silently miss every one of these.
+ """
+ message = str(exc)
+ return _DIALOG_GONE_MESSAGE_MARKER in message.lower() or is_target_closed_message(message)
+
+
# Track contexts that already have a dialog handler to avoid duplicate registration
# when the same BrowserContext is returned by CDP reconnect paths.
_registered_contexts: weakref.WeakSet[BrowserContext] = weakref.WeakSet()
@@ -32,7 +48,8 @@ async def _handle_dialog(dialog: Dialog, page: Page | None = None) -> None:
For alert and beforeunload dialogs, always accepts without calling the LLM.
For confirm/prompt dialogs with no task context, auto-accepts (no LLM round-trip needed).
For confirm/prompt dialogs with task context, calls the secondary LLM handler to decide.
- Falls back to accept on any error (safer than dismiss for form submissions).
+ Falls back to accept on any decision error (safer than dismiss for form submissions), except
+ when the dialog itself is already gone — nothing is answerable then.
``page`` is the page this handler was registered on — the dialog's originating page. Every
response this handler gives except an alert's (which has no alternative) routes through
@@ -85,69 +102,82 @@ async def _handle_dialog(dialog: Dialog, page: Page | None = None) -> None:
else:
await dialog.accept(prompt_text)
- # Alert (no choice to preflight) auto-accepts directly; beforeunload accept commits a pending
- # navigation, so its acceptance goes through the choke point.
- if dialog_type == "alert":
- log.info("Dialog auto-accepted", dialog_type=dialog_type)
- await dialog.accept()
- return
- if dialog_type == "beforeunload":
- log.info("Dialog auto-accepted", dialog_type=dialog_type)
- await _respond("accept")
- return
-
- if not navigation_goal and not navigation_payload:
- log.info("Dialog auto-accepted (no task context)", dialog_type=dialog_type)
- await _respond("accept", default_value or "")
- return
-
- # For confirm/prompt with task context, call LLM to decide
+ # Answering races the page, and every response path below can lose it. This runs as a pyee
+ # listener, so an escaping error lands in asyncio's default exception handler at error level
+ # with none of the context bound above; the race is an expected outcome, everything else is not.
try:
- prompt = prompt_engine.load_prompt(
- "handle-dialog",
- dialog_type=dialog_type,
- dialog_message=dialog_message,
- default_value=default_value,
- navigation_goal=navigation_goal,
- navigation_payload=json.dumps(navigation_payload) if navigation_payload else None,
- )
-
- # JS dialogs block the page's JS thread while open. We need a hard timeout
- # to ensure the page doesn't stay frozen indefinitely if the LLM call is slow.
- response = await asyncio.wait_for(
- get_org_aware_secondary_llm_api_handler(default=app.SECONDARY_LLM_API_HANDLER)(
- prompt=prompt,
- prompt_name="handle-dialog",
- organization_id=organization_id,
- ),
- timeout=DIALOG_LLM_TIMEOUT,
- )
-
- action = str(response.get("action", "accept")).lower()
- prompt_text = response.get("prompt_text")
-
- if action not in ("accept", "dismiss"):
- log.warning("Dialog LLM returned unexpected action, defaulting to accept", llm_action=action)
- action = "accept"
-
- log.info(
- "Dialog handled via LLM",
- action=action,
- has_prompt_text=prompt_text is not None,
- )
-
- if action == "dismiss":
- await _respond("dismiss")
- else:
- await _respond("accept", prompt_text if prompt_text is not None else (default_value or ""))
+ # Alert (no choice to preflight) auto-accepts directly; beforeunload accept commits a
+ # pending navigation, so its acceptance goes through the choke point.
+ if dialog_type == "alert":
+ log.info("Dialog auto-accepted", dialog_type=dialog_type)
+ await dialog.accept()
+ return
+ if dialog_type == "beforeunload":
+ log.info("Dialog auto-accepted", dialog_type=dialog_type)
+ await _respond("accept")
+ return
- except asyncio.TimeoutError:
- log.warning("Dialog LLM call timed out, falling back to accept")
- await _respond("accept", default_value or "")
+ if not navigation_goal and not navigation_payload:
+ log.info("Dialog auto-accepted (no task context)", dialog_type=dialog_type)
+ await _respond("accept", default_value or "")
+ return
- except Exception:
- log.exception("Dialog handler error, falling back to accept")
- await _respond("accept", default_value or "")
+ # For confirm/prompt with task context, call LLM to decide
+ try:
+ prompt = prompt_engine.load_prompt(
+ "handle-dialog",
+ dialog_type=dialog_type,
+ dialog_message=dialog_message,
+ default_value=default_value,
+ navigation_goal=navigation_goal,
+ navigation_payload=json.dumps(navigation_payload) if navigation_payload else None,
+ )
+
+ # JS dialogs block the page's JS thread while open. We need a hard timeout
+ # to ensure the page doesn't stay frozen indefinitely if the LLM call is slow.
+ response = await asyncio.wait_for(
+ get_org_aware_secondary_llm_api_handler(default=app.SECONDARY_LLM_API_HANDLER)(
+ prompt=prompt,
+ prompt_name="handle-dialog",
+ organization_id=organization_id,
+ ),
+ timeout=DIALOG_LLM_TIMEOUT,
+ )
+
+ action = str(response.get("action", "accept")).lower()
+ prompt_text = response.get("prompt_text")
+
+ if action not in ("accept", "dismiss"):
+ log.warning("Dialog LLM returned unexpected action, defaulting to accept", llm_action=action)
+ action = "accept"
+
+ log.info(
+ "Dialog handled via LLM",
+ action=action,
+ has_prompt_text=prompt_text is not None,
+ )
+
+ if action == "dismiss":
+ await _respond("dismiss")
+ else:
+ await _respond("accept", prompt_text if prompt_text is not None else (default_value or ""))
+
+ except asyncio.TimeoutError:
+ log.warning("Dialog LLM call timed out, falling back to accept")
+ await _respond("accept", default_value or "")
+
+ except Exception as exc:
+ # A dialog that is already gone cannot be answered, so the fallback accept would both
+ # overrule a deliberate dismissal and raise a second time. Let the guard below name it.
+ if _is_dialog_gone_error(exc):
+ raise
+ log.exception("Dialog handler error, falling back to accept")
+ await _respond("accept", default_value or "")
+
+ except Exception as exc:
+ if not _is_dialog_gone_error(exc):
+ raise
+ log.warning("Dialog was gone before it could be answered", error=str(exc))
def set_dialog_handler(browser_context: BrowserContext) -> None:
diff --git a/skyvern/webeye/navigation.py b/skyvern/webeye/navigation.py
index d742a0e49..598bec719 100644
--- a/skyvern/webeye/navigation.py
+++ b/skyvern/webeye/navigation.py
@@ -94,6 +94,13 @@ async def _revalidate_navigation_response(response: object) -> None:
await revalidate_redirect_chain(response, validate_navigation_destination)
+def _navigation_status(response: object) -> int | None:
+ # Duck-typed like _navigation_hop_urls: whichever engine's navigation-response object this is, it
+ # exposes an int ``status``; anything else (None, a fake without it) yields None.
+ status = getattr(response, "status", None)
+ return status if isinstance(status, int) else None
+
+
# Progressive wait_until degradation. Degrading to `domcontentloaded` and
# then `commit` lets navigation succeed once the DOM or response is ready.
_DEGRADATION_MAP: dict[str, list[str]] = {
@@ -138,7 +145,10 @@ async def navigate_with_retry(
wait_until: Literal["load", "domcontentloaded", "commit"] = "load",
sleep: SleepFunc | None = None,
log_url: str | None = None,
-) -> None:
+) -> int | None:
+ # Returns the final navigation response's HTTP status when one is available (None when the
+ # navigation produced no response object). Additive: every caller today ignores the return; the
+ # value exists so the Task V3 loop can classify a dead/removed starting URL (a hard 404/410).
# Late-bound so a test patching ``asyncio.sleep`` reaches the retry backoff.
if sleep is None:
sleep = asyncio.sleep
@@ -174,7 +184,9 @@ async def navigate_with_retry(
LOG.info("Page loading time", loading_time=elapsed, url=display_url, wait_until=strategy)
await settle()
LOG.info("Successfully navigated to url", url=display_url, retry_time=attempt, wait_until=strategy)
- return
+ # The status is what lets the Task V3 loop classify a dead/removed starting URL; a
+ # navigation with no response object (about:blank, some continuations) yields None.
+ return _navigation_status(response)
except BlockedNavigationDestination as error:
# Blocked destinations are permanent; retrying re-issues the same request.
@@ -223,3 +235,6 @@ async def navigate_with_retry(
error=safe_error_str,
)
await sleep(1)
+
+ # Reached only when retry_times <= 0 (the loop never ran); a real navigation returns or raises inside.
+ return None
diff --git a/skyvern/webeye/real_browser_state.py b/skyvern/webeye/real_browser_state.py
index a4b144140..902620207 100644
--- a/skyvern/webeye/real_browser_state.py
+++ b/skyvern/webeye/real_browser_state.py
@@ -105,6 +105,9 @@ class RealBrowserState(BrowserState):
# A release retry after a transient DB failure must not repeat local CDP teardown.
self._remote_driver_detached = False
self._browser_state_diagnostic: BrowserStateDiagnostic | None = None
+ # HTTP status of the most recent navigate_to_url (None until one runs, or when it produced no
+ # response). Read by the Task V3 loop to classify a dead/removed starting URL; v1 ignores it.
+ self.last_navigation_status: int | None = None
self._ever_connected = browser_context is not None
self._close_requested = False
self._disconnect_listener_context: BrowserContext | None = None
@@ -332,7 +335,7 @@ class RealBrowserState(BrowserState):
retry_times: int = NAVIGATION_MAX_RETRY_TIME,
wait_until: Literal["load", "domcontentloaded", "commit"] = "load",
) -> None:
- await navigate_with_retry(
+ self.last_navigation_status = await navigate_with_retry(
navigate=lambda strategy: page.goto(url, timeout=settings.BROWSER_LOADING_TIMEOUT_MS, wait_until=strategy),
url=url,
retry_times=retry_times,
diff --git a/skyvern/webeye/utils/dom.py b/skyvern/webeye/utils/dom.py
index 1a913ad5f..e535224e6 100644
--- a/skyvern/webeye/utils/dom.py
+++ b/skyvern/webeye/utils/dom.py
@@ -108,6 +108,53 @@ def is_post_dispatch_click_timeout(
return "scheduled navigation" in str(exc).lower()
+def is_pointer_interception_error(exc: BaseException) -> bool:
+ """A Playwright actionability failure whose message names another element receiving the pointer
+ (``intercepts pointer events`` / ``intercepted by another element``). This is the repo's existing
+ interception signature idiom. It deliberately does NOT match detached / not-stable / not-visible /
+ disabled failures, which must retain the normal coordinate/JS fallback chain."""
+ message = str(exc).lower()
+ return "intercepts pointer events" in message or "intercepted by another element" in message
+
+
+# Return candidate text from the actual hit path only when the hit's boundary-child branch is the
+# adjacent preceding element sibling of the option's branch (the captured visible-label / option layout).
+# The boundary text is excluded so a broad container or a same-text following blocker cannot qualify.
+_POINTER_INTERCEPTOR_LOCAL_TEXT_JS = """(element) => {
+ const rect = element.getBoundingClientRect();
+ if (!rect || !Number.isFinite(rect.left) || !Number.isFinite(rect.top)
+ || rect.width <= 0 || rect.height <= 0) return [];
+ const hit = document.elementFromPoint(rect.left + rect.width / 2, rect.top + rect.height / 2);
+ if (!hit || hit === element || element.contains(hit)) return [];
+ let boundary = null;
+ let node = element.parentElement;
+ for (let depth = 0; depth < 2 && node; depth++) {
+ if (node === document.documentElement || node === document.body) break;
+ const tag = (node.tagName || "").toLowerCase();
+ if (tag === "html" || tag === "body") break;
+ if (node.contains(hit)) {
+ boundary = node;
+ break;
+ }
+ node = node.parentElement;
+ }
+ if (!boundary) return [];
+ let hitBranch = hit;
+ while (hitBranch && hitBranch.parentElement !== boundary) hitBranch = hitBranch.parentElement;
+ let targetBranch = element;
+ while (targetBranch && targetBranch.parentElement !== boundary) targetBranch = targetBranch.parentElement;
+ if (!hitBranch || !targetBranch || hitBranch === targetBranch
+ || hitBranch.nextElementSibling !== targetBranch) return [];
+ const texts = [];
+ node = hit;
+ for (let depth = 0; node && node !== boundary && depth < 8; depth++) {
+ texts.push(typeof node.innerText === "string" ? node.innerText : node.textContent || "");
+ node = node.parentElement;
+ }
+ return node === boundary ? texts : [];
+}"""
+
+
async def resolve_locator(
scrape_page: ScrapedPage,
page: Page,
@@ -1299,10 +1346,12 @@ class SkyvernElement:
incremental_page: IncrementalScrapePage | None = None,
timeout: float = settings.BROWSER_ACTION_TIMEOUT_MS,
engine_selection: BrowserEngineSelection | None = None,
+ intercept_js_fallback_label: str | None = None,
) -> None:
if not await self.wait_until_enabled(timeout=timeout):
raise InteractWithDisabledElement(element_id=self.get_id())
+ pointer_intercepted = False
try:
# Route through the active cursor strategy so alternate profiles can
# dispatch their own click sequence (explicit mouse.down/up).
@@ -1319,6 +1368,7 @@ class SkyvernElement:
element_id=self.get_id(),
)
return
+ pointer_intercepted = is_pointer_interception_error(exc)
if dom is not None:
# try to click on the blocking element
@@ -1338,6 +1388,25 @@ class SkyvernElement:
return
LOG.info("Failed to click on the blocking element", exc_info=True, element_id=self.get_id())
+ if intercept_js_fallback_label is not None and pointer_intercepted:
+ interceptor_matches_label = False
+ try:
+ await self.scroll_into_view(timeout=timeout)
+ interceptor_matches_label = await self._pointer_interceptor_matches_label(intercept_js_fallback_label)
+ except Exception:
+ interceptor_matches_label = False
+ if interceptor_matches_label:
+ try:
+ await self.click_in_javascript()
+ return
+ except Exception:
+ LOG.info("Failed intercept JS-click fallback", exc_info=True, element_id=self.get_id())
+ else:
+ LOG.info(
+ "Intercept JS-click fallback skipped: hit target lacks the expected local option label",
+ element_id=self.get_id(),
+ )
+
try:
await self.scroll_into_view(timeout=timeout)
await self.coordinate_click(page=page, timeout=timeout)
@@ -1353,6 +1422,25 @@ class SkyvernElement:
skyvern_frame = await SkyvernFrame.create_instance(self.get_frame())
await skyvern_frame.click_element_in_javascript(await self.get_element_handler())
+ async def _pointer_interceptor_matches_label(self, expected_label: str) -> bool:
+ normalized_expected = " ".join(expected_label.split()).casefold()
+ if not normalized_expected:
+ return False
+ try:
+ result = await SkyvernFrame.evaluate(
+ frame=self.get_frame(),
+ expression=_POINTER_INTERCEPTOR_LOCAL_TEXT_JS,
+ arg=await self.get_element_handler(),
+ )
+ except Exception:
+ return False
+ if not isinstance(result, list):
+ return False
+ return any(
+ isinstance(candidate, str) and " ".join(candidate.split()).casefold() == normalized_expected
+ for candidate in result
+ )
+
async def coordinate_click(
self, page: Page, timeout: float = settings.BROWSER_ACTION_TIMEOUT_MS, click_count: int = 1
) -> None:
diff --git a/skyvern/webeye/utils/page.py b/skyvern/webeye/utils/page.py
index 3f259aa3c..964bef64c 100644
--- a/skyvern/webeye/utils/page.py
+++ b/skyvern/webeye/utils/page.py
@@ -394,6 +394,24 @@ LOADING_INDICATOR_PROBE_JS = f"""
return [q(rect.left), q(rect.top), q(rect.width), q(rect.height)];
}};
+ // The broad `[class*="spinner"]` selector (index 0) also matches static <a> links whose class merely
+ // contains "spinner"; treat such an anchor as a non-match unless it is animating or explicitly busy/
+ // status/progressbar/determinate, so it neither blocks readiness nor enters the telemetry count.
+ const isInertAnchorSpinner = (el) => {{
+ try {{
+ if ((el.tagName || '').toLowerCase() !== 'a') return false;
+ if (isAnimated(el)) return false;
+ if (el.getAttribute('aria-busy') === 'true') return false;
+ const role = el.getAttribute('role');
+ if (role === 'status' || role === 'progressbar') return false;
+ const valuenow = el.getAttribute('aria-valuenow');
+ if (valuenow !== null && valuenow !== '' && !isNaN(Number(valuenow))) return false;
+ return true;
+ }} catch (e) {{
+ return false;
+ }}
+ }};
+
let first = null;
let count = 0;
for (let sel = 0; sel < selectors.length; sel++) {{
@@ -401,6 +419,7 @@ LOADING_INDICATOR_PROBE_JS = f"""
const elements = document.querySelectorAll(selectors[sel]);
for (const el of elements) {{
if (!isVisible(el)) continue;
+ if (sel === 0 && isInertAnchorSpinner(el)) continue;
count++;
if (first === null) {{
try {{
diff --git a/tests/unit/browser_extension/test_broker_client.py b/tests/unit/browser_extension/test_broker_client.py
index 15942f95b..8e003ca9b 100644
--- a/tests/unit/browser_extension/test_broker_client.py
+++ b/tests/unit/browser_extension/test_broker_client.py
@@ -107,6 +107,33 @@ class EventRelay:
return None
+class TabListRelay(EventRelay):
+ async def request(
+ self,
+ op: str,
+ args: dict,
+ timeout: float = 30.0,
+ *,
+ retain_until_terminal: bool = False,
+ on_registered: Callable[[], None] | None = None,
+ on_terminal: Callable[[], None] | None = None,
+ ) -> dict:
+ if op == "tabs.list":
+ if on_registered is not None:
+ on_registered()
+ if on_terminal is not None:
+ on_terminal()
+ return {"tabs": [dict(tab) for tab in self.scoped_tabs]}
+ return await super().request(
+ op,
+ args,
+ timeout,
+ retain_until_terminal=retain_until_terminal,
+ on_registered=on_registered,
+ on_terminal=on_terminal,
+ )
+
+
class ErrorRelay(EventRelay):
async def request(
self,
@@ -228,6 +255,40 @@ async def test_client_is_relay_compatible_and_fences_stale_disconnect() -> None:
await server.stop()
+async def test_client_lists_fresh_tabs_owned_by_its_lease() -> None:
+ server = BrowserExtensionBrokerServer(19778)
+ relay = TabListRelay("extension-secret", 19778, server._handle_extension_event, server._handle_disconnect)
+ server._relay = relay
+ client = BrokerClient(19778, _ignore_event, auto_spawn=False)
+ server_task = await _connect_over_socketpair(server, client)
+ try:
+ await _eventually(lambda: client.connected)
+ relay.scoped_tabs = [
+ {"tabId": 11, "url": "https://one.test", "active": True},
+ {"tabId": 12, "url": "https://two.test", "active": False},
+ ]
+ assert (await client.ensure_root_lease())["tabId"] == relay.scoped_tabs[0]["tabId"]
+ await client.request("tabs.activate", {"tabId": 12})
+
+ relay.scoped_tabs = [
+ {"tabId": 11, "url": "https://one.test", "active": False},
+ {"tabId": 12, "url": "https://two.test", "active": True},
+ {"tabId": 13, "url": "https://other-client.test", "active": False},
+ ]
+
+ expected_tabs = [
+ {"tabId": 11, "url": "https://one.test", "title": "", "active": False},
+ {"tabId": 12, "url": "https://two.test", "title": "", "active": True},
+ ]
+ assert await client.list_scoped_tabs() == expected_tabs
+ assert client.scoped_tabs == expected_tabs
+ finally:
+ await client.stop()
+ await asyncio.wait_for(server_task, 1.0)
+ await server.stop()
+
+
@pytest.mark.asyncio
async def test_connected_is_published_only_after_synthetic_hello_snapshot() -> None:
server = BrowserExtensionBrokerServer(19778)
diff --git a/tests/unit/browser_extension/test_extension_bridge_hardening.py b/tests/unit/browser_extension/test_extension_bridge_hardening.py
index ff2814deb..e2750b062 100644
--- a/tests/unit/browser_extension/test_extension_bridge_hardening.py
+++ b/tests/unit/browser_extension/test_extension_bridge_hardening.py
@@ -207,6 +207,164 @@ if (healthy.result.method !== "Runtime.evaluate") {{
assert result.returncode == 0, result.stderr
+def test_dom_evaluate_contract() -> None:
+ node = shutil.which("node")
+ if node is None:
+ pytest.skip("node is required for the extension DOM evaluation contract test")
+
+ extension_dir = Path(__file__).parents[3] / "skyvern" / "browser_extension" / "extension"
+ dom_uri = (extension_dir / "dom_router.js").as_uri()
+ protocol_uri = (extension_dir / "protocol.js").as_uri()
+ script = f"""
+const scriptCalls = [];
+globalThis.chrome = {{
+ userScripts: {{
+ async execute({{ target, world, injectImmediately, js }}) {{
+ scriptCalls.push({{ target, world, injectImmediately, js }});
+ try {{
+ return [{{ result: await globalThis.eval(js[0].code) }}];
+ }} catch (error) {{
+ return [{{ error: String(error?.message ?? error) }}];
+ }}
+ }},
+ }},
+}};
+
+const {{ evaluateDom }} = await import({json.dumps(dom_uri)});
+const {{ ERROR_CODES, ProtocolError }} = await import({json.dumps(protocol_uri)});
+
+let leaseChecks = 0;
+let controllableChecks = 0;
+let controllableUrl = "https://example.test/";
+const lease = {{ assertCurrent() {{ leaseChecks += 1; }} }};
+const tabScope = {{
+ async runTabOperation(tabId, operation) {{
+ if (tabId !== 7) throw new Error(`unexpected tab ID: ${{tabId}}`);
+ return operation(lease);
+ }},
+ async assertControllableLocked(tabId, currentLease) {{
+ if (tabId !== 7 || currentLease !== lease) throw new Error("scope check lost the tab lease");
+ controllableChecks += 1;
+ return {{ id: tabId, groupId: 700, url: controllableUrl }};
+ }},
+}};
+
+const evaluated = await evaluateDom(tabScope, {{
+ tabId: 7,
+ expression: "({{ answer: 6 * 7 }})",
+}});
+if (
+ evaluated.result?.answer !== 42 ||
+ scriptCalls.length !== 1 ||
+ scriptCalls[0].target?.tabId !== 7 ||
+ scriptCalls[0].world !== "MAIN" ||
+ scriptCalls[0].injectImmediately !== true ||
+ scriptCalls[0].js?.[0]?.code !== "({{ answer: 6 * 7 }})" ||
+ controllableChecks !== 2 ||
+ leaseChecks !== 1
+) {{
+ throw new Error(`DOM evaluation contract failed: ${{JSON.stringify({{
+ evaluated,
+ scriptCalls,
+ controllableChecks,
+ leaseChecks,
+ }})}}`);
+}}
+
+for (const [expression, expected] of [["false", false], ["0", 0], ["null", null]]) {{
+ const response = await evaluateDom(tabScope, {{ tabId: 7, expression }});
+ if (!Object.is(response.result, expected)) {{
+ throw new Error(`DOM evaluation changed a falsy result: ${{expression}}`);
+ }}
+}}
+const thrownEvaluationError = await evaluateDom(tabScope, {{
+ tabId: 7,
+ expression: "(() => {{ throw new Error('page failure'); }})()",
+}}).then(() => null, (error) => error);
+if (
+ thrownEvaluationError?.code !== ERROR_CODES.CDP_ERROR ||
+ !thrownEvaluationError.message.includes("page failure")
+) {{
+ throw new Error(`thrown page evaluation was not structured: ${{thrownEvaluationError?.message}}`);
+}}
+
+const invalidError = await evaluateDom(tabScope, {{
+ tabId: 7,
+ expression: "1 + 1",
+ extra: true,
+}}).then(() => null, (error) => error);
+if (invalidError?.code !== ERROR_CODES.OP_NOT_ALLOWED) {{
+ throw new Error(`invalid DOM arguments did not fail closed: ${{invalidError?.code}}`);
+}}
+
+const callsBeforeBlank = scriptCalls.length;
+controllableUrl = "about:blank";
+const blankError = await evaluateDom(tabScope, {{
+ tabId: 7,
+ expression: "1 + 1",
+}}).then(() => null, (error) => error);
+if (
+ blankError?.code !== ERROR_CODES.RESTRICTED_URL ||
+ scriptCalls.length !== callsBeforeBlank
+) {{
+ throw new Error(`about:blank reached MAIN evaluation: ${{blankError?.code}}`);
+}}
+controllableUrl = "https://example.test/";
+
+chrome.userScripts.execute = async () => {{ throw new Error("injection blocked"); }};
+const injectionError = await evaluateDom(tabScope, {{
+ tabId: 7,
+ expression: "1 + 1",
+}}).then(() => null, (error) => error);
+if (injectionError?.code !== ERROR_CODES.CDP_ERROR) {{
+ throw new Error(`failed injection was not structured: ${{injectionError?.code}}`);
+}}
+
+let revalidationChecks = 0;
+let failedInjectionCalls = 0;
+chrome.userScripts.execute = async () => {{
+ failedInjectionCalls += 1;
+ throw new Error("navigation interrupted injection");
+}};
+tabScope.assertControllableLocked = async (tabId, currentLease) => {{
+ if (tabId !== 7 || currentLease !== lease) throw new Error("scope check lost the tab lease");
+ revalidationChecks += 1;
+ if (revalidationChecks === 2) {{
+ throw new ProtocolError(
+ ERROR_CODES.RESTRICTED_URL,
+ "Chrome does not allow controlling this URL.",
+ );
+ }}
+ return {{ id: tabId, groupId: 700, url: "https://example.test/" }};
+}};
+const revokedError = await evaluateDom(tabScope, {{
+ tabId: 7,
+ expression: "1 + 1",
+}}).then(() => null, (error) => error);
+if (
+ revokedError?.code !== ERROR_CODES.RESTRICTED_URL ||
+ revalidationChecks !== 2 ||
+ failedInjectionCalls !== 1
+) {{
+ throw new Error(`failed injection hid scope revocation: ${{JSON.stringify({{
+ code: revokedError?.code,
+ revalidationChecks,
+ failedInjectionCalls,
+ }})}}`);
+}}
+"""
+
+ result = subprocess.run(
+ [node, "--input-type=module", "--eval", script],
+ capture_output=True,
+ text=True,
+ check=False,
+ timeout=10,
+ )
+
+ assert result.returncode == 0, result.stderr
+
+
def test_extension_reset_and_debugger_lifecycle_contract() -> None:
node = shutil.which("node")
if node is None:
@@ -223,6 +381,7 @@ const tabs = new Map();
const sessionState = {{}};
const debuggerAttached = new Set();
let createTab;
+let lastFocusedWindowId = 2;
globalThis.chrome = {{
alarms: {{ onAlarm: {{ addListener() {{}} }} }},
tabs: {{
@@ -235,6 +394,12 @@ globalThis.chrome = {{
if (!tab) throw new Error("missing tab");
return {{ ...tab }};
}},
+ async query(values) {{
+ return [...tabs.values()]
+ .filter((tab) => !values.active || tab.active === true)
+ .filter((tab) => !values.lastFocusedWindow || tab.windowId === lastFocusedWindowId)
+ .map((tab) => ({{ ...tab }}));
+ }},
async group({{ tabIds }}) {{
const tab = tabs.get(tabIds[0]);
if (tab) tab.groupId = 700;
@@ -292,6 +457,160 @@ const settleWithin = (promise, timeoutMs = 100) => Promise.race([
const scope = new TabScope({{ sendEvent: () => undefined, operationTimeoutMs: 20 }});
await scope.initialize();
+// tabs.list marks only the active tab in Chrome's last-focused window.
+tabs.set(18, {{ id: 18, windowId: 1, groupId: 700, url: "https://one.example", active: true }});
+tabs.set(19, {{ id: 19, windowId: 2, groupId: 700, url: "https://two.example", active: true }});
+scope.scopedTabIds.add(18);
+scope.scopedTabIds.add(19);
+scope.scopedGroupIds.set(18, 700);
+scope.scopedGroupIds.set(19, 700);
+const focusedTabs = (await scope.list()).tabs.filter((tab) => tab.active);
+if (focusedTabs.length !== 1 || focusedTabs[0].tabId !== 19) {{
+ throw new Error(`focused tab selection was ambiguous: ${{JSON.stringify(focusedTabs)}}`);
+}}
+scope.scopedTabIds.delete(18);
+scope.scopedTabIds.delete(19);
+scope.scopedGroupIds.delete(18);
+scope.scopedGroupIds.delete(19);
+tabs.delete(18);
+tabs.delete(19);
+
+
+// Closing a just-created tab must cancel its create operation after Chrome returns the tab id.
+const originalAddToScopeLocked = scope.addToScopeLocked.bind(scope);
+let addToScopeStarted = false;
+let releaseAddToScope;
+scope.addToScopeLocked = async (tab, lease) => {{
+ addToScopeStarted = true;
+ await new Promise((resolve) => {{ releaseAddToScope = resolve; }});
+ return originalAddToScopeLocked(tab, lease);
+}};
+createTab = undefined;
+const interruptedCreate = scope.create({{ url: "https://created.example" }}).then(
+ () => null,
+ (error) => error,
+);
+await waitUntil(() => typeof createTab === "function");
+const createdTab = {{ id: 22, windowId: 2, groupId: -1, url: "https://created.example" }};
+tabs.set(22, createdTab);
+createTab({{ ...createdTab }});
+await waitUntil(() => addToScopeStarted && scope.tabOperationLeases.has(22));
+tabs.delete(22);
+listeners.removed.forEach((listener) => listener(22));
+const interruptedCreateError = await settleWithin(interruptedCreate);
+if (interruptedCreateError?.code !== ERROR_CODES.TAB_NOT_FOUND) {{
+ throw new Error(`closed created tab did not invalidate create: ${{interruptedCreateError?.code}}`);
+}}
+releaseAddToScope();
+scope.addToScopeLocked = originalAddToScopeLocked;
+await waitUntil(() => !scope.tabOperationLeases.has(22));
+
+// User revocation must invalidate an active operation before the queued update handler runs.
+tabs.set(20, {{ id: 20, windowId: 1, groupId: 700, url: "https://revoked.example" }});
+scope.scopedTabIds.add(20);
+scope.scopedGroupIds.set(20, 700);
+const originalRemoveFromScopeLocked = scope.removeFromScopeLocked.bind(scope);
+let revocationCleanupStarted = false;
+let releaseRevocationCleanup;
+scope.removeFromScopeLocked = async (...args) => {{
+ if (args[0] === 20) {{
+ revocationCleanupStarted = true;
+ await new Promise((resolve) => {{ releaseRevocationCleanup = resolve; }});
+ }}
+ return originalRemoveFromScopeLocked(...args);
+}};
+let operationStarted = false;
+const revokedOperation = scope.runTabOperation(20, async () => {{
+ operationStarted = true;
+ return new Promise(() => undefined);
+}}).then(() => null, (error) => error);
+await waitUntil(() => operationStarted);
+tabs.get(20).groupId = -1;
+listeners.updated.forEach((listener) => listener(20, {{ groupId: -1 }}));
+const immediateRevocationError = await settleWithin(revokedOperation);
+if (immediateRevocationError?.code !== ERROR_CODES.TAB_NOT_SCOPED) {{
+ throw new Error(`group revocation did not invalidate active work: ${{immediateRevocationError?.code}}`);
+}}
+await waitUntil(() => revocationCleanupStarted);
+listeners.updated.forEach((listener) =>
+ listener(20, {{ url: "https://revoked.example/next" }}),
+);
+releaseRevocationCleanup();
+await waitUntil(() => !scope.scopedTabIds.has(20));
+if (scope.tabOperationLeases.has(20)) {{
+ throw new Error("revoked tab retained an operation lease");
+}}
+scope.removeFromScopeLocked = originalRemoveFromScopeLocked;
+tabs.delete(20);
+// Restored scope metadata must fail closed when it references no real group.
+tabs.set(14, {{ id: 14, windowId: 1, groupId: -1, url: "https://restore.example" }});
+sessionState.scopedTabIds = [14];
+sessionState.scopedTabGroupIds = {{ "14": -1 }};
+const restoredScope = new TabScope({{ sendEvent: () => undefined, operationTimeoutMs: 20 }});
+await restoredScope.initialize();
+if (restoredScope.scopedTabIds.has(14)) {{
+ throw new Error("invalid restored group metadata retained tab scope");
+}}
+sessionState.scopedTabIds = [];
+sessionState.scopedTabGroupIds = {{}};
+tabs.delete(14);
+// A stale positive group ID must not adopt a different controlled group.
+tabs.set(16, {{ id: 16, windowId: 1, groupId: 701, url: "https://stale-group.example" }});
+sessionState.scopedTabIds = [16];
+sessionState.scopedTabGroupIds = {{ "16": 700 }};
+const staleGroupScope = new TabScope({{ sendEvent: () => undefined, operationTimeoutMs: 20 }});
+await staleGroupScope.initialize();
+if (staleGroupScope.scopedTabIds.has(16)) {{
+ throw new Error("stale restored group ID adopted a different group");
+}}
+sessionState.scopedTabIds = [];
+sessionState.scopedTabGroupIds = {{}};
+tabs.delete(16);
+
+// Collection must revoke a tab when the controlled group is renamed.
+tabs.set(17, {{ id: 17, windowId: 1, groupId: 700, url: "https://renamed-group.example" }});
+scope.scopedTabIds.add(17);
+scope.scopedGroupIds.set(17, 700);
+const originalGroupGet = chrome.tabGroups.get;
+chrome.tabGroups.get = async (groupId) => ({{ id: groupId, title: "Renamed" }});
+const renamedTabs = await scope.collectScopedTabs(false);
+chrome.tabGroups.get = originalGroupGet;
+if (renamedTabs.length !== 0 || scope.scopedTabIds.has(17)) {{
+ throw new Error("renamed group remained observable");
+}}
+tabs.delete(17);
+// Popup inheritance must reject an opener whose controlled group was renamed.
+tabs.set(18, {{ id: 18, windowId: 1, groupId: 700, url: "https://opener.example" }});
+tabs.set(19, {{ id: 19, openerTabId: 18, windowId: 1, groupId: -1, url: "https://child.example" }});
+scope.scopedTabIds.add(18);
+scope.scopedGroupIds.set(18, 700);
+chrome.tabGroups.get = async (groupId) => ({{ id: groupId, title: "Renamed" }});
+await scope.handleTabCreated(tabs.get(19));
+chrome.tabGroups.get = originalGroupGet;
+if (
+ scope.scopedTabIds.has(18) ||
+ scope.scopedTabIds.has(19) ||
+ scope.createdTabIds.has(19)
+) {{
+ throw new Error("popup inherited scope from a revoked opener");
+}}
+tabs.delete(18);
+tabs.delete(19);
+
+// Group creation must roll back when Chrome cannot label Skyvern Controlled.
+tabs.set(15, {{ id: 15, windowId: 1, groupId: -1, url: "https://group-failure.example" }});
+const originalGroupUpdate = chrome.tabGroups.update;
+chrome.tabGroups.update = async () => {{ throw new Error("group update failed"); }};
+const groupFailure = await scope.shareTab(15).then(() => null, (error) => error);
+chrome.tabGroups.update = originalGroupUpdate;
+if (
+ groupFailure?.code !== ERROR_CODES.INTERNAL ||
+ scope.scopedTabIds.has(15) ||
+ tabs.get(15)?.groupId !== -1
+) {{
+ throw new Error(`group setup failed open: code=${{groupFailure?.code}} scoped=${{scope.scopedTabIds.has(15)}} group=${{tabs.get(15)?.groupId}}`);
+}}
+tabs.delete(15);
const originalRemove = chrome.tabs.remove;
let releaseRemove;
chrome.tabs.remove = (tabId) => {{
@@ -325,8 +644,9 @@ if (createError?.code !== ERROR_CODES.COMMAND_TIMEOUT || scope.scopedTabIds.has(
// Reset must quarantine an in-flight removal until the late Chrome result is
// reconciled, so the next ownership epoch cannot re-share the tab.
-tabs.set(13, {{ id: 13, windowId: 1, groupId: -1, url: "https://remove.example" }});
+tabs.set(13, {{ id: 13, windowId: 1, groupId: 700, url: "https://remove.example" }});
scope.scopedTabIds.add(13);
+scope.scopedGroupIds.set(13, 700);
const removeOutcome = scope.remove({{ tabId: 13 }}).then(
() => null,
(error) => error,
@@ -368,8 +688,9 @@ if (wedgedError?.code !== ERROR_CODES.COMMAND_TIMEOUT) {{
}}
for (const tabId of [11, 12, 21]) {{
- tabs.set(tabId, {{ id: tabId, windowId: 1, groupId: -1, url: "https://example.test" }});
+ tabs.set(tabId, {{ id: tabId, windowId: 1, groupId: 700, url: "https://example.test" }});
scope.scopedTabIds.add(tabId);
+ scope.scopedGroupIds.set(tabId, 700);
}}
const router = new DebuggerRouter({{
tabScope: scope,
diff --git a/tests/unit/browser_extension/test_mcp_glue.py b/tests/unit/browser_extension/test_mcp_glue.py
index 69a01cc6d..e525937bc 100644
--- a/tests/unit/browser_extension/test_mcp_glue.py
+++ b/tests/unit/browser_extension/test_mcp_glue.py
@@ -833,9 +833,10 @@ def test_browser_extension_install_copies_token_opens_chrome_and_prints_steps(
assert "1. Enable Developer mode." in result.stdout
assert "2. Click Load unpacked." in result.stdout
assert f"3. Select {extension_dir}." in result.stdout
- assert "4. Open the Skyvern Agent popup." in result.stdout
- assert "5. Paste the pairing token and click Connect." in result.stdout
- assert '6. Add tabs to the "Skyvern Controlled" group.' in result.stdout
+ assert "4. Open Skyvern Agent details and enable Allow User Scripts." in result.stdout
+ assert "5. Open the Skyvern Agent popup." in result.stdout
+ assert "6. Paste the pairing token and click Connect." in result.stdout
+ assert '7. Add tabs to the "Skyvern Controlled" group.' in result.stdout
assert "When your MCP server is running, pair with: skyvern browser extension-pair" in result.stdout
assert run.call_args_list == [
call(
@@ -873,6 +874,7 @@ def test_default_extension_install_describes_auto_enable_without_loading_legacy_
assert result.exit_code == 0
assert "its first broker start enables broker state automatically" in result.stdout
assert "skyvern browser extension-pair" in result.stdout
+ assert "Allow User Scripts" in result.stdout
assert "extension-broker-enable" not in result.stdout
token_loader.assert_not_called()
@@ -891,8 +893,9 @@ def test_browser_extension_install_attempts_one_click_pairing_when_bridge_is_lis
result = CliRunner().invoke(browser_app, ["extension-install"])
assert result.exit_code == 0
- assert "4. Approve pairing in the Skyvern Agent confirmation tab (one click)." in result.stdout
- assert '5. Add tabs to the "Skyvern Controlled" group.' in result.stdout
+ assert "4. Open Skyvern Agent details and enable Allow User Scripts." in result.stdout
+ assert "5. Approve pairing in the Skyvern Agent confirmation tab (one click)." in result.stdout
+ assert '6. Add tabs to the "Skyvern Controlled" group.' in result.stdout
assert "pairing token" not in result.stdout.lower()
launch_pairing.assert_called_once_with(20123)
load_token.assert_not_called()
diff --git a/tests/unit/browser_extension/test_protocol.py b/tests/unit/browser_extension/test_protocol.py
index 710ff8496..cc37195dc 100644
--- a/tests/unit/browser_extension/test_protocol.py
+++ b/tests/unit/browser_extension/test_protocol.py
@@ -75,6 +75,7 @@ def test_protocol_allowlists_match_contract() -> None:
"debugger.attach",
"debugger.detach",
"debugger.send",
+ "dom.evaluate",
"tabs.create",
"tabs.remove",
"tabs.activate",
@@ -117,6 +118,11 @@ def test_manifest_key_derives_extension_id() -> None:
derived_extension_id = "".join(chr(ord("a") + int(nibble, 16)) for nibble in digest_prefix)
assert derived_extension_id == EXTENSION_ID
+ assert "userScripts" in manifest["permissions"]
+ assert "activeTab" not in manifest["permissions"]
+ assert "scripting" not in manifest["permissions"]
+ assert manifest["minimum_chrome_version"] == "138"
+ assert manifest["host_permissions"] == ["http://*/*", "https://*/*"]
def test_package_extension_builds_store_upload_zip(tmp_path: Path) -> None:
@@ -128,6 +134,7 @@ def test_package_extension_builds_store_upload_zip(tmp_path: Path) -> None:
assert "key" not in packaged_manifest
assert "service_worker.js" in names
+ assert "dom_router.js" in names
assert "README.md" not in names
second_path = package_extension(tmp_path / "skyvern-agent-second.zip")
diff --git a/tests/unit/browser_extension/test_runtime.py b/tests/unit/browser_extension/test_runtime.py
index 5f2d37c00..046551f47 100644
--- a/tests/unit/browser_extension/test_runtime.py
+++ b/tests/unit/browser_extension/test_runtime.py
@@ -144,6 +144,28 @@ async def test_singleton_is_idempotent_and_late_binds_adapter_callbacks(monkeypa
assert adapters[0].disconnect_count == 1
+async def test_evaluate_routes_to_active_controlled_tab() -> None:
+ relay = MagicMock()
+ relay.ensure_root_lease = AsyncMock(return_value={"tabId": 17})
+ relay.list_scoped_tabs = AsyncMock(
+ return_value=[
+ {"tabId": 17, "active": False},
+ {"tabId": 18, "active": True},
+ ]
+ )
+ relay.request = AsyncMock(return_value={"result": {"answer": 42}})
+ runtime = BrowserExtensionRuntime(relay, MagicMock())
+
+ assert await runtime.evaluate("({ answer: 6 * 7 })") == {"answer": 42}
+ relay.ensure_root_lease.assert_awaited_once_with()
+ relay.list_scoped_tabs.assert_awaited_once_with()
+ relay.request.assert_awaited_once_with(
+ "dom.evaluate",
+ {"tabId": 18, "expression": "({ answer: 6 * 7 })"},
+ )
+
+
@pytest.mark.asyncio
async def test_open_pairing_page_uses_relay_nonce_without_exposing_token(monkeypatch: pytest.MonkeyPatch) -> None:
install_stubs(monkeypatch)
diff --git a/tests/unit/copilot_test_helpers.py b/tests/unit/copilot_test_helpers.py
index 228b3b3e6..3d3b0c485 100644
--- a/tests/unit/copilot_test_helpers.py
+++ b/tests/unit/copilot_test_helpers.py
@@ -2,10 +2,11 @@
from __future__ import annotations
+from collections.abc import Awaitable, Callable
from datetime import datetime, timezone
from types import SimpleNamespace
from typing import Any
-from unittest.mock import MagicMock
+from unittest.mock import AsyncMock, MagicMock
import pytest
@@ -269,3 +270,30 @@ def make_model_input_data(items: list[Any], *, instructions: str | None = None,
model_data=SimpleNamespace(input=list(items), instructions=instructions),
context=context,
)
+
+
+class FakeMCPServerManager:
+ def __init__(self, servers: object) -> None:
+ self.active_servers = servers
+
+ async def __aenter__(self) -> FakeMCPServerManager:
+ return self
+
+ async def __aexit__(self, *args: object) -> None:
+ return None
+
+
+def stub_copilot_agent_loop(
+ monkeypatch: pytest.MonkeyPatch, run_with_enforcement: Callable[..., Awaitable[object]]
+) -> None:
+ def fake_resolve_model_config(
+ _handler: object, *, copilot_config: object = None, llm_key_override: str | None = None
+ ) -> tuple[str, object, str, bool]:
+ return f"model-{llm_key_override or 'PRIMARY'}", object(), llm_key_override or "PRIMARY", True
+
+ monkeypatch.setattr(
+ "skyvern.forge.sdk.copilot.agent._resolve_live_browser_session_id", AsyncMock(return_value=None)
+ )
+ monkeypatch.setattr("agents.mcp.MCPServerManager", FakeMCPServerManager)
+ monkeypatch.setattr("skyvern.forge.sdk.copilot.model_resolver.resolve_model_config", fake_resolve_model_config)
+ monkeypatch.setattr("skyvern.forge.sdk.copilot.enforcement.run_with_enforcement", run_with_enforcement)
diff --git a/tests/unit/force_stub_app.py b/tests/unit/force_stub_app.py
index b50cc27fe..64bbdeb27 100644
--- a/tests/unit/force_stub_app.py
+++ b/tests/unit/force_stub_app.py
@@ -41,8 +41,6 @@ def create_forge_stub_app() -> ForgeApp:
# the real OSS base no-op so unit tests exercise the legacy in-process path.
fake_app_module.AGENT_FUNCTION.should_use_codeblock_runner = AsyncMock(return_value=False)
fake_app_module.AGENT_FUNCTION.execute_code_block_override = AsyncMock(return_value=None)
- # Record Browser v2 fails closed to v1, but _LazyNamespace would auto-mock it truthy.
- fake_app_module.AGENT_FUNCTION.is_record_browser_v2_enabled = AsyncMock(return_value=False)
base_agent_function = AgentFunction()
# Class constant, not a method — _LazyNamespace would auto-mock it into a non-iterable AsyncMock
# and break every caller that scans it for close-page phrases.
diff --git a/tests/unit/forge/sdk/routes/streaming/test_cdp_input_session.py b/tests/unit/forge/sdk/routes/streaming/test_cdp_input_session.py
index 48faee1d6..bde5731f7 100644
--- a/tests/unit/forge/sdk/routes/streaming/test_cdp_input_session.py
+++ b/tests/unit/forge/sdk/routes/streaming/test_cdp_input_session.py
@@ -6,7 +6,7 @@ import asyncio
import json
from types import SimpleNamespace
from typing import Any
-from unittest.mock import Mock, call
+from unittest.mock import Mock
import pytest
from fastapi import WebSocketDisconnect
@@ -19,68 +19,7 @@ from playwright.async_api import CDPSession
from playwright.async_api import Error as PlaywrightError
from playwright.async_api import TimeoutError as PlaywrightTimeoutError
-from skyvern.forge.sdk.routes.streaming import cdp_input, latency_probe
-from skyvern.services.browser_recording.v2.ledger import start_ledger, stop_ledger
-from skyvern.services.browser_recording.v2.tap import tap_pipelined
-
-
-def test_latency_probe_records_the_next_frame_and_clears_pending_input(monkeypatch: pytest.MonkeyPatch) -> None:
- histogram = Mock()
- monkeypatch.setattr(latency_probe, "input_to_frame_seconds", histogram)
- latency_probe.forget("pbs_latency")
-
- latency_probe.note_frame("pbs_latency", 1.0)
- latency_probe.set_recording("pbs_latency", True)
- latency_probe.note_input("pbs_latency", 2.0)
- latency_probe.note_frame("pbs_latency", 2.125)
- latency_probe.note_frame("pbs_latency", 2.25)
- latency_probe.set_recording("pbs_latency", False)
- latency_probe.note_input("pbs_latency", 3.0)
- latency_probe.note_frame("pbs_latency", 3.5)
-
- assert histogram.record.call_args_list == [
- call(0.125, {"recording": "on"}),
- call(0.5, {"recording": "off"}),
- ]
-
-
-def test_forget_clears_the_recording_gauge_so_a_dropped_session_is_not_latched_on(
- monkeypatch: pytest.MonkeyPatch,
-) -> None:
- """An abrupt disconnect never sends END_EXFILTRATION, so teardown's forget() is the only
- thing that can stop the next frame for that id being labelled recording=on."""
- histogram = Mock()
- monkeypatch.setattr(latency_probe, "input_to_frame_seconds", histogram)
-
- latency_probe.set_recording("pbs_dropped", True)
- latency_probe.forget("pbs_dropped")
- latency_probe.note_input("pbs_dropped", 1.0)
- latency_probe.note_frame("pbs_dropped", 1.25)
-
- assert histogram.record.call_args_list == [call(0.25, {"recording": "off"})]
- latency_probe.forget("pbs_dropped")
-
-
-def test_the_recording_cap_evicts_the_oldest_session_not_an_arbitrary_one(
- monkeypatch: pytest.MonkeyPatch,
-) -> None:
- histogram = Mock()
- monkeypatch.setattr(latency_probe, "input_to_frame_seconds", histogram)
- ids = [f"pbs_cap_{index}" for index in range(latency_probe.MAX_SESSIONS + 1)]
- for browser_session_id in ids:
- latency_probe.set_recording(browser_session_id, True)
-
- for browser_session_id in (ids[0], ids[1], ids[-1]):
- latency_probe.note_input(browser_session_id, 0.0)
- latency_probe.note_frame(browser_session_id, 1.0)
-
- assert histogram.record.call_args_list == [
- call(1.0, {"recording": "off"}),
- call(1.0, {"recording": "on"}),
- call(1.0, {"recording": "on"}),
- ]
- for browser_session_id in ids:
- latency_probe.forget(browser_session_id)
+from skyvern.forge.sdk.routes.streaming import cdp_input
class _RecordingPlaywrightTransport(Transport):
@@ -203,72 +142,6 @@ async def test_rebinds_when_the_working_page_changes(monkeypatch: pytest.MonkeyP
assert first.detached is True
-async def test_observer_attach_failure_does_not_kill_input_session(monkeypatch: pytest.MonkeyPatch) -> None:
- session = _FakeSession("first")
- page = _FakePage(session)
- attach_attempted = False
-
- async def _resolve(*args: Any, **kwargs: Any) -> _FakePage:
- return page
-
- class _RecordingSession:
- async def attach_page(self, page_key: str, cdp_session: _FakeSession) -> None:
- nonlocal attach_attempted
- attach_attempted = True
- raise RuntimeError("attach failed")
-
- monkeypatch.setattr(cdp_input, "_resolve_working_page", _resolve)
- monkeypatch.setattr(cdp_input, "get_session_v2", lambda browser_session_id: _RecordingSession())
- input_session = cdp_input.ActivePageCdpInputSession(
- browser_state=object(), # type: ignore[arg-type]
- entity_id="pbs-test",
- entity_type="browser_session",
- )
-
- assert await input_session.get_session() is session
- assert attach_attempted is True
-
-
-async def test_a_second_recording_attaches_its_own_observer_to_the_same_page(
- monkeypatch: pytest.MonkeyPatch,
-) -> None:
- """The input session outlives a recording, so the next recording must still get attached."""
- session = _FakeSession("first")
- page = _FakePage(session)
- recording_session: Any = None
- attached: list[tuple[str, _FakeSession]] = []
-
- async def _resolve(*args: Any, **kwargs: Any) -> _FakePage:
- return page
-
- class _RecordingSession:
- def __init__(self, name: str) -> None:
- self.name = name
-
- async def attach_page(self, page_key: str, cdp_session: _FakeSession) -> None:
- attached.append((self.name, cdp_session))
-
- monkeypatch.setattr(cdp_input, "_resolve_working_page", _resolve)
- monkeypatch.setattr(cdp_input, "get_session_v2", lambda browser_session_id: recording_session)
- input_session = cdp_input.ActivePageCdpInputSession(
- browser_state=object(), # type: ignore[arg-type]
- entity_id="pbs-test",
- entity_type="browser_session",
- )
-
- assert await input_session.get_session() is session
- recording_session = _RecordingSession("first-recording")
- assert await input_session.get_session(force_refresh=True) is session
- recording_session = None
- assert await input_session.get_session(force_refresh=True) is session
- recording_session = _RecordingSession("second-recording")
- assert await input_session.get_session(force_refresh=True) is session
-
- assert attached == [("first-recording", session), ("second-recording", session)]
-
-
class _FakeNavigablePage:
"""Stands in for the Playwright page `_dispatch_navigate_event` calls `goto()` on."""
@@ -377,7 +250,7 @@ class TestNavigateEvent:
channel = SimpleNamespace(interactor="agent", client_id="c1")
websocket = _FakeWebSocket([json.dumps({"type": "navigateEvent", "url": "https://example.com"})])
- await cdp_input._run_input_loop(websocket, channel, input_session, "browser_session_id", "pbs_test", None)
+ await cdp_input._run_input_loop(websocket, channel, input_session, "browser_session_id", "pbs_test")
assert page.goto_calls == []
assert websocket.sent_json == []
@@ -394,7 +267,7 @@ class TestNavigateEvent:
]
)
- await cdp_input._run_input_loop(websocket, channel, input_session, "browser_session_id", "pbs_test", None)
+ await cdp_input._run_input_loop(websocket, channel, input_session, "browser_session_id", "pbs_test")
assert page.goto_calls == ["https://example.com/path"]
assert websocket.sent_json == []
@@ -416,7 +289,7 @@ class TestNavigateEvent:
]
)
- await cdp_input._run_input_loop(websocket, channel, input_session, "browser_session_id", "pbs_test", None)
+ await cdp_input._run_input_loop(websocket, channel, input_session, "browser_session_id", "pbs_test")
assert page.goto_calls == ["https://unresolvable.invalid", "about:blank"]
assert page.goto_timeouts == [None, 5000]
@@ -454,7 +327,7 @@ class TestNavigateEvent:
]
)
- await cdp_input._run_input_loop(websocket, channel, input_session, "browser_session_id", "pbs_test", None)
+ await cdp_input._run_input_loop(websocket, channel, input_session, "browser_session_id", "pbs_test")
assert websocket.sent_json == []
assert websocket.closed == (4411, "dispatch_failed")
@@ -491,7 +364,7 @@ class TestNavigateEvent:
]
)
- await cdp_input._run_input_loop(websocket, channel, input_session, "browser_session_id", "pbs_test", None)
+ await cdp_input._run_input_loop(websocket, channel, input_session, "browser_session_id", "pbs_test")
assert page.goto_calls == ["https://public.invalid", "about:blank"]
assert input_dispatch_urls == ["about:blank"]
@@ -522,7 +395,7 @@ class TestNavigateEvent:
]
)
- await cdp_input._run_input_loop(websocket, channel, input_session, "browser_session_id", "pbs_test", None)
+ await cdp_input._run_input_loop(websocket, channel, input_session, "browser_session_id", "pbs_test")
assert page.goto_calls == ["https://public.invalid", "about:blank"]
assert input_dispatch_urls == ["about:blank"]
@@ -541,7 +414,7 @@ class TestNavigateEvent:
[json.dumps({"type": "navigateEvent", "url": "http://169.254.169.254/latest/meta-data/"})]
)
- await cdp_input._run_input_loop(websocket, channel, input_session, "browser_session_id", "pbs_test", None)
+ await cdp_input._run_input_loop(websocket, channel, input_session, "browser_session_id", "pbs_test")
assert page.goto_calls == []
assert websocket.sent_json == [{"kind": "navigate-error", "reason": "blocked"}]
@@ -554,7 +427,7 @@ class TestNavigateEvent:
channel = SimpleNamespace(interactor="user", client_id="c1")
websocket = _FakeWebSocket([json.dumps({"type": "navigateEvent", "url": " "})])
- await cdp_input._run_input_loop(websocket, channel, input_session, "browser_session_id", "pbs_test", None)
+ await cdp_input._run_input_loop(websocket, channel, input_session, "browser_session_id", "pbs_test")
assert page.goto_calls == []
assert websocket.sent_json == [{"kind": "navigate-error", "reason": "invalid_url"}]
@@ -566,7 +439,7 @@ class TestNavigateEvent:
channel = SimpleNamespace(interactor="user", client_id="c1")
websocket = _FakeWebSocket([json.dumps({"type": "navigateEvent", "url": "https://example.org/"})])
- await cdp_input._run_input_loop(websocket, channel, input_session, "browser_session_id", "pbs_test", None)
+ await cdp_input._run_input_loop(websocket, channel, input_session, "browser_session_id", "pbs_test")
assert page.goto_calls == ["https://example.org/"]
assert websocket.sent_json == []
@@ -582,7 +455,7 @@ class TestNavigateEvent:
channel = SimpleNamespace(interactor="user", client_id="c1")
websocket = _FakeWebSocket([json.dumps({"type": "navigateEvent", "url": "example.org"})])
- await cdp_input._run_input_loop(websocket, channel, input_session, "browser_session_id", "pbs_test", None)
+ await cdp_input._run_input_loop(websocket, channel, input_session, "browser_session_id", "pbs_test")
assert page.goto_calls == ["https://example.org"]
assert websocket.sent_json == []
@@ -604,7 +477,7 @@ class TestNavigateEvent:
channel = SimpleNamespace(interactor="user", client_id="c1")
websocket = _FakeWebSocket([json.dumps({"type": "navigateEvent", "url": "https://example.org/redirect"})])
- await cdp_input._run_input_loop(websocket, channel, input_session, "browser_session_id", "pbs_test", None)
+ await cdp_input._run_input_loop(websocket, channel, input_session, "browser_session_id", "pbs_test")
assert page.goto_calls == ["https://example.org/redirect", "about:blank"]
assert websocket.sent_json == [{"kind": "navigate-error", "reason": "blocked"}]
@@ -629,7 +502,7 @@ class TestNavigateEvent:
]
)
- await cdp_input._run_input_loop(websocket, channel, input_session, "browser_session_id", "pbs_test", None)
+ await cdp_input._run_input_loop(websocket, channel, input_session, "browser_session_id", "pbs_test")
assert page.goto_calls == ["https://example.org/redirect", "about:blank"]
assert page.goto_timeouts == [None, 5000]
@@ -661,7 +534,7 @@ class TestHistoryNavigation:
channel = SimpleNamespace(interactor="user", client_id="c1")
websocket = _FakeWebSocket([json.dumps({"type": "goBackEvent"})])
- await cdp_input._run_input_loop(websocket, channel, input_session, "browser_session_id", "pbs_test", None)
+ await cdp_input._run_input_loop(websocket, channel, input_session, "browser_session_id", "pbs_test")
assert _dispatched(session) == [("Page.navigateToHistoryEntry", {"entryId": 0})]
assert websocket.sent_json == []
@@ -673,7 +546,7 @@ class TestHistoryNavigation:
channel = SimpleNamespace(interactor="user", client_id="c1")
websocket = _FakeWebSocket([json.dumps({"type": "goForwardEvent"})])
- await cdp_input._run_input_loop(websocket, channel, input_session, "browser_session_id", "pbs_test", None)
+ await cdp_input._run_input_loop(websocket, channel, input_session, "browser_session_id", "pbs_test")
assert _dispatched(session) == [("Page.navigateToHistoryEntry", {"entryId": 1})]
@@ -684,7 +557,7 @@ class TestHistoryNavigation:
channel = SimpleNamespace(interactor="user", client_id="c1")
websocket = _FakeWebSocket([json.dumps({"type": "reloadEvent"})])
- await cdp_input._run_input_loop(websocket, channel, input_session, "browser_session_id", "pbs_test", None)
+ await cdp_input._run_input_loop(websocket, channel, input_session, "browser_session_id", "pbs_test")
assert _dispatched(session) == [("Page.reload", {})]
@@ -697,7 +570,7 @@ class TestHistoryNavigation:
channel = SimpleNamespace(interactor="user", client_id="c1")
websocket = _FakeWebSocket([json.dumps({"type": "goBackEvent"})])
- await cdp_input._run_input_loop(websocket, channel, input_session, "browser_session_id", "pbs_test", None)
+ await cdp_input._run_input_loop(websocket, channel, input_session, "browser_session_id", "pbs_test")
assert _dispatched(session) == []
assert websocket.sent_json == []
@@ -716,7 +589,7 @@ class TestHistoryNavigation:
channel = SimpleNamespace(interactor="user", client_id="c1")
websocket = _FakeWebSocket([json.dumps({"type": "goBackEvent"})])
- await cdp_input._run_input_loop(websocket, channel, input_session, "browser_session_id", "pbs_test", None)
+ await cdp_input._run_input_loop(websocket, channel, input_session, "browser_session_id", "pbs_test")
assert _dispatched(session) == []
assert websocket.sent_json == [{"kind": "navigate-error", "reason": "blocked"}]
@@ -728,7 +601,7 @@ class TestHistoryNavigation:
channel = SimpleNamespace(interactor="agent", client_id="c1")
websocket = _FakeWebSocket([json.dumps({"type": "goBackEvent"})])
- await cdp_input._run_input_loop(websocket, channel, input_session, "browser_session_id", "pbs_test", None)
+ await cdp_input._run_input_loop(websocket, channel, input_session, "browser_session_id", "pbs_test")
assert session.sent == []
@@ -758,7 +631,7 @@ async def test_pointer_burst_is_received_before_dispatches_complete() -> None:
]
)
loop_task = asyncio.create_task(
- cdp_input._run_input_loop(websocket, channel, input_session, "browser_session_id", "pbs_test", None)
+ cdp_input._run_input_loop(websocket, channel, input_session, "browser_session_id", "pbs_test")
)
try:
@@ -776,57 +649,6 @@ async def test_pointer_burst_is_received_before_dispatches_complete() -> None:
assert len(session.sent) == event_count
-async def test_pipelined_tap_is_ordered_before_semaphore_acquire(monkeypatch: pytest.MonkeyPatch) -> None:
- browser_session_id = "pbs_ledger_order"
- ledger = start_ledger(browser_session_id)
- order: list[str] = []
-
- class _OrderingSemaphore:
- def __init__(self, value: int) -> None:
- assert value > 0
-
- async def acquire(self) -> None:
- order.append("acquire")
-
- def release(self) -> None:
- pass
-
- def _recording_tap(*args: Any, **kwargs: Any) -> None:
- tap_pipelined(*args, **kwargs)
- order.append("tap")
-
- monkeypatch.setattr(cdp_input.asyncio, "Semaphore", _OrderingSemaphore)
- monkeypatch.setattr(cdp_input, "tap_pipelined", _recording_tap)
- input_session = _FakeInputSession(_FakeSession("s"))
- channel = SimpleNamespace(interactor="user", client_id="c1")
- websocket = _FakeWebSocket(
- [
- json.dumps(
- {
- "type": "mouseEvent",
- "eventType": "mousePressed",
- "x": 10,
- "y": 20,
- "button": "left",
- "clickCount": 1,
- "modifiers": 0,
- }
- )
- ]
- )
-
- try:
- await cdp_input._run_input_loop(
- websocket, channel, input_session, "browser_session_id", browser_session_id, browser_session_id
- )
-
- assert order[:2] == ["tap", "acquire"]
- assert [(row.seq, row.kind) for row in ledger.rows()] == [(1, "mouse_pressed")]
- finally:
- stop_ledger(browser_session_id)
-
-
@pytest.mark.asyncio
async def test_target_closed_background_dispatch_is_dropped_without_closing_input_channel() -> None:
dispatch_attempted = asyncio.Event()
@@ -840,7 +662,7 @@ async def test_target_closed_background_dispatch_is_dropped_without_closing_inpu
channel = SimpleNamespace(interactor="user", client_id="c1")
websocket = _BlockingWebSocket([json.dumps({"type": "wheelEvent", "x": 10, "y": 20, "deltaX": 0, "deltaY": 1})])
loop_task = asyncio.create_task(
- cdp_input._run_input_loop(websocket, channel, input_session, "browser_session_id", "pbs_test", None)
+ cdp_input._run_input_loop(websocket, channel, input_session, "browser_session_id", "pbs_test")
)
try:
@@ -862,7 +684,7 @@ async def test_background_dispatch_failure_closes_input_channel_once() -> None:
channel = SimpleNamespace(interactor="user", client_id="c1")
websocket = _BlockingWebSocket([json.dumps({"type": "wheelEvent", "x": 10, "y": 20, "deltaX": 0, "deltaY": 1})])
- await cdp_input._run_input_loop(websocket, channel, input_session, "browser_session_id", "pbs_test", None)
+ await cdp_input._run_input_loop(websocket, channel, input_session, "browser_session_id", "pbs_test")
assert websocket.close_calls == [(4411, "dispatch_failed")]
@@ -901,7 +723,7 @@ async def test_dispatched_input_event_records_wait_and_dispatch_latency(monkeypa
input_session = SimpleNamespace(get_session=_get_session, page=object())
loop_task = asyncio.create_task(
- cdp_input._run_input_loop(websocket, channel, input_session, "browser_session_id", "pbs_1", None)
+ cdp_input._run_input_loop(websocket, channel, input_session, "browser_session_id", "pbs_1")
)
async with asyncio.timeout(0.5):
while not fake_session.sent:
diff --git a/tests/unit/forge/sdk/routes/streaming/test_message_channel_recording_resilience.py b/tests/unit/forge/sdk/routes/streaming/test_message_channel_recording_resilience.py
index 17632c452..96dc832d6 100644
--- a/tests/unit/forge/sdk/routes/streaming/test_message_channel_recording_resilience.py
+++ b/tests/unit/forge/sdk/routes/streaming/test_message_channel_recording_resilience.py
@@ -18,8 +18,6 @@ never skips the draft flush or the channel close.
from __future__ import annotations
import asyncio
-import json
-import time
import typing as t
from contextlib import asynccontextmanager
from unittest.mock import AsyncMock, MagicMock
@@ -30,15 +28,7 @@ from playwright._impl._errors import Error as PlaywrightError
from starlette.websockets import WebSocketState
from skyvern.forge.sdk.routes.streaming.channels import message as message_module
-from skyvern.forge.sdk.routes.streaming.channels.message import (
- MessageKind,
- MessageOutError,
- MessageOutRecordingCommitted,
- loop_stream_messages,
-)
-from skyvern.services.browser_recording.types import ActionKind
-from skyvern.services.browser_recording.v2.ledger import Gesture, get_ledger, stop_ledger
-from skyvern.services.browser_recording.v2.session import discard_session_v2, get_session_v2
+from skyvern.forge.sdk.routes.streaming.channels.message import MessageKind, MessageOutError, loop_stream_messages
PBS_ID = "pbs_123"
WP_ID = "wpid_123"
@@ -53,7 +43,7 @@ END_EXFILTRATION_DATA = {"kind": MessageKind.END_EXFILTRATION.value}
RECORDING_REARM_CAPTURE_DATA = {"kind": MessageKind.RECORDING_REARM_CAPTURE.value}
-def _message_channel(receive_sequence: t.Iterable[object]) -> MagicMock:
+def _message_channel(receive_sequence: list[object]) -> MagicMock:
"""A MessageChannel double whose websocket replays ``receive_sequence``."""
message_channel = MagicMock()
message_channel.class_name = "MessageChannel"
@@ -385,297 +375,3 @@ async def test_recording_round_trip_still_works_when_target_is_healthy(
registry.stop_session.assert_awaited_once_with(PBS_ID)
assert _sent_error_kinds(message_channel) == []
message_channel.close.assert_awaited_once()
-
-
-class _FakeV2Session:
- def __init__(self, sealed: bool = False) -> None:
- self.browser_session_id = PBS_ID
- self.sealed = sealed
- self.paused = 0
- self.resumed = 0
- self.seals = 0
-
- async def seal(self) -> list[object]:
- self.sealed = True
- self.seals += 1
- return []
-
- def pause(self) -> None:
- self.paused += 1
-
- def resume(self) -> None:
- self.resumed += 1
-
- async def stop_ticker(self) -> None:
- return None
-
-
-def _set_record_browser_v2(monkeypatch: pytest.MonkeyPatch, enabled: bool) -> None:
- agent_function = MagicMock()
- agent_function.is_record_browser_v2_enabled = AsyncMock(return_value=enabled)
- monkeypatch.setattr(message_module.app, "AGENT_FUNCTION", agent_function)
-
-
-async def test_begin_exfiltration_under_v2_starts_a_session_and_injects_nothing(
- monkeypatch: pytest.MonkeyPatch,
-) -> None:
- """v2 owns the recording end to end: no ExfiltrationChannel, so no page scripts."""
- exfiltration_channel_class = MagicMock()
- message_channel = _message_channel([BEGIN_EXFILTRATION_DATA, END_EXFILTRATION_DATA, WebSocketDisconnect()])
- monkeypatch.setattr(message_module, "get_vnc_channel", lambda _client_id: MagicMock())
- monkeypatch.setattr(message_module, "ExfiltrationChannel", exfiltration_channel_class)
- registry = MagicMock()
- monkeypatch.setattr(message_module, "interpretation_registry", registry)
- _set_record_browser_v2(monkeypatch, True)
-
- started: list[str] = []
- session = _FakeV2Session()
- monkeypatch.setattr(
- message_module,
- "get_session_v2",
- lambda pbs_id: session if started else None,
- )
- monkeypatch.setattr(
- message_module,
- "start_session_v2",
- lambda **kwargs: started.append(kwargs["browser_session_id"]),
- )
-
- await loop_stream_messages(message_channel)
-
- assert started == [PBS_ID]
- exfiltration_channel_class.assert_not_called()
- registry.start_session.assert_not_called()
- # end-exfiltration seals but keeps the session: its ledger is the commit's only input.
- assert session.seals == 1
- assert _sent_error_kinds(message_channel) == []
-
-
-RECORDING_COMMIT_DATA = {"kind": MessageKind.RECORDING_COMMIT.value, "mode": "blocks", "draft_steps": None}
-
-
-def _seed_click_gestures() -> None:
- ledger = get_ledger(PBS_ID)
- assert ledger is not None
- for kind in ("mouse_pressed", "mouse_released"):
- ledger.append(
- Gesture(
- seq=0,
- t_received=1.0,
- kind=kind,
- page_key="page-1",
- url="https://example.test/form",
- x=1,
- y=2,
- button="left",
- click_count=1,
- selector="#search",
- role="button",
- accessible_name="Search",
- )
- )
-
-
-def _commit_script(commits: int) -> t.Iterator[object]:
- """begin -> record a click -> end -> commit, as the panel drives it."""
- yield BEGIN_EXFILTRATION_DATA
- _seed_click_gestures()
- yield END_EXFILTRATION_DATA
- for _ in range(commits):
- yield RECORDING_COMMIT_DATA
- yield WebSocketDisconnect()
-
-
-def _committed_messages(message_channel: MagicMock) -> list[MessageOutRecordingCommitted]:
- return [
- sent
- for call in message_channel.send_nowait.call_args_list
- for sent in call.kwargs.get("messages", [])
- if isinstance(sent, MessageOutRecordingCommitted)
- ]
-
-
-async def test_recording_commit_renders_the_sealed_session_then_drops_it(monkeypatch: pytest.MonkeyPatch) -> None:
- """The commit rides the messages socket because the ledger is process-local (plan §5 PR-6)."""
- message_channel = _message_channel(_commit_script(commits=2))
- monkeypatch.setattr(message_module, "get_vnc_channel", lambda _client_id: MagicMock())
- monkeypatch.setattr(message_module, "ExfiltrationChannel", MagicMock())
- monkeypatch.setattr(message_module, "interpretation_registry", MagicMock())
- _set_record_browser_v2(monkeypatch, True)
-
- try:
- await loop_stream_messages(message_channel)
- finally:
- discard_session_v2(PBS_ID)
- stop_ledger(PBS_ID)
-
- committed = _committed_messages(message_channel)
- assert len(committed) == 1
- assert committed[0].mode == "blocks"
- assert [block["block_type"] for block in committed[0].blocks] == ["action"]
- # The committed recording is gone: the second commit finds nothing to render.
- assert get_session_v2(PBS_ID) is None
- assert get_ledger(PBS_ID) is None
- assert _sent_error_kinds(message_channel) == [MessageKind.RECORDING_COMMIT.value]
-
-
-async def test_v2_teardown_still_finds_the_session_after_browser_session_goes_none(
- monkeypatch: pytest.MonkeyPatch,
-) -> None:
- """message_channel.browser_session can flip to None mid-recording (loop_verify_browser_session
- clears it on timeout/finalize without closing the socket). Teardown must still locate and
- seal the live v2 session instead of leaking it forever."""
- message_channel = _message_channel([BEGIN_EXFILTRATION_DATA, WebSocketDisconnect()])
- monkeypatch.setattr(message_module, "get_vnc_channel", lambda _client_id: MagicMock())
- monkeypatch.setattr(message_module, "ExfiltrationChannel", MagicMock())
- monkeypatch.setattr(message_module, "interpretation_registry", MagicMock())
- _set_record_browser_v2(monkeypatch, True)
-
- session = _FakeV2Session(sealed=True)
- monkeypatch.setattr(message_module, "get_session_v2", lambda pbs_id: session)
- monkeypatch.setattr(
- message_module, "start_session_v2", lambda **kwargs: message_channel.__setattr__("browser_session", None)
- )
- discarded: list[str] = []
- monkeypatch.setattr(message_module, "discard_session_v2", lambda pbs_id: discarded.append(pbs_id))
-
- await loop_stream_messages(message_channel)
-
- assert discarded == [PBS_ID]
-
-
-async def test_begin_exfiltration_with_v2_disabled_takes_the_v1_path(monkeypatch: pytest.MonkeyPatch) -> None:
- channel = _started_channel()
- message_channel = _message_channel([BEGIN_EXFILTRATION_DATA, END_EXFILTRATION_DATA, WebSocketDisconnect()])
- registry = _install_recording_doubles(monkeypatch, channel=channel)
- _set_record_browser_v2(monkeypatch, False)
-
- started: list[str] = []
- monkeypatch.setattr(message_module, "start_session_v2", lambda **kwargs: started.append("v2"))
-
- await loop_stream_messages(message_channel)
-
- assert started == []
- channel.start.assert_awaited_once()
- registry.start_session.assert_called_once()
- registry.stop_session.assert_awaited_once_with(PBS_ID)
-
-
-async def test_stale_v2_session_does_not_hijack_a_v1_recording(monkeypatch: pytest.MonkeyPatch) -> None:
- """The socket latches its recorder at begin-exfiltration; the v2 registry is not the switch."""
- channel = _started_channel()
- message_channel = _message_channel([BEGIN_EXFILTRATION_DATA, END_EXFILTRATION_DATA, WebSocketDisconnect()])
- registry = _install_recording_doubles(monkeypatch, channel=channel)
- _set_record_browser_v2(monkeypatch, False)
-
- stale = _FakeV2Session()
- monkeypatch.setattr(message_module, "get_session_v2", lambda pbs_id: stale)
-
- await loop_stream_messages(message_channel)
-
- assert stale.seals == 0
- channel.stop.assert_awaited_once()
- registry.stop_session.assert_awaited_once_with(PBS_ID)
-
-
-async def test_a_mid_socket_flag_flip_does_not_start_a_second_recorder(monkeypatch: pytest.MonkeyPatch) -> None:
- channel = _started_channel()
- message_channel = _message_channel(
- [BEGIN_EXFILTRATION_DATA, BEGIN_EXFILTRATION_DATA, END_EXFILTRATION_DATA, WebSocketDisconnect()]
- )
- registry = _install_recording_doubles(monkeypatch, channel=channel)
-
- agent_function = MagicMock()
- agent_function.is_record_browser_v2_enabled = AsyncMock(side_effect=[False, True])
- monkeypatch.setattr(message_module.app, "AGENT_FUNCTION", agent_function)
- started: list[str] = []
- monkeypatch.setattr(message_module, "start_session_v2", lambda **kwargs: started.append("v2"))
-
- await loop_stream_messages(message_channel)
-
- assert started == []
- assert agent_function.is_record_browser_v2_enabled.await_count == 1
- message_module.ExfiltrationChannel.assert_called_once()
- channel.rearm_all_pages.assert_awaited_once()
- registry.stop_session.assert_awaited_once_with(PBS_ID)
-
-
-async def test_v2_recording_reaches_the_panel_as_epoch_stamped_draft_steps(
- monkeypatch: pytest.MonkeyPatch,
-) -> None:
- """End to end over the real v2 session: a ledger row becomes a panel-ready draft step."""
- message_channel = _message_channel([])
- monkeypatch.setattr(message_module, "get_vnc_channel", lambda _client_id: MagicMock())
- monkeypatch.setattr(message_module, "ExfiltrationChannel", MagicMock())
- monkeypatch.setattr(message_module, "interpretation_registry", MagicMock())
- _set_record_browser_v2(monkeypatch, True)
- receive_count = 0
-
- async def receive_json() -> dict[str, str]:
- nonlocal receive_count
- receive_count += 1
- if receive_count == 1:
- return BEGIN_EXFILTRATION_DATA
- if receive_count == 2:
- ledger = get_ledger(PBS_ID)
- assert ledger is not None
- ledger.append(
- Gesture(
- seq=0,
- t_received=time.monotonic(),
- kind="mouse_pressed",
- page_key="page-1",
- url="https://example.test/form",
- x=1,
- y=2,
- button="left",
- click_count=1,
- accessible_name="Search",
- )
- )
- ledger.append(
- Gesture(
- seq=0,
- t_received=time.monotonic(),
- kind="key",
- page_key="page-1",
- url="https://example.test/form",
- key="s",
- text="hunter2",
- key_event_type="keyDown",
- accessible_name="Search",
- )
- )
- return END_EXFILTRATION_DATA
- raise WebSocketDisconnect()
-
- message_channel.websocket.receive_json = receive_json
-
- try:
- await loop_stream_messages(message_channel)
- finally:
- discard_session_v2(PBS_ID)
- stop_ledger(PBS_ID)
-
- updates = [
- sent
- for call in message_channel.send_nowait.call_args_list
- for sent in call.kwargs.get("messages", [])
- if isinstance(sent, message_module.MessageOutRecordingInterpretationUpdate)
- ]
- assert updates[-1].finalized is True
- steps = updates[-1].steps
- assert [(step.action_kind, step.label, step.navigation_goal) for step in steps] == [
- (ActionKind.CLICK, "Click Search", "Click Search"),
- (ActionKind.INPUT_TEXT, "Type into Search", "Type into Search"),
- ]
- now_epoch_ms = time.time() * 1000
- assert all(abs(now_epoch_ms - (step.timestamp_start or 0)) < 60_000 for step in steps)
- assert "hunter2" not in json.dumps([step.model_dump() for step in steps])
diff --git a/tests/unit/services/browser_recording/__init__.py b/tests/unit/services/browser_recording/__init__.py
deleted file mode 100644
index e69de29bb..000000000
diff --git a/tests/unit/services/browser_recording/v2/__init__.py b/tests/unit/services/browser_recording/v2/__init__.py
deleted file mode 100644
index e69de29bb..000000000
diff --git a/tests/unit/services/browser_recording/v2/_fakes.py b/tests/unit/services/browser_recording/v2/_fakes.py
deleted file mode 100644
index 2d0cdcc2d..000000000
--- a/tests/unit/services/browser_recording/v2/_fakes.py
+++ /dev/null
@@ -1,24 +0,0 @@
-from collections import defaultdict
-from collections.abc import Callable
-from typing import Any
-
-
-class FakeCdpSession:
- def __init__(self) -> None:
- self.sent: list[tuple[str, dict[str, Any]]] = []
- self.listeners_at_send: list[set[str]] = []
- self.listeners: dict[str, list[Callable[[dict[str, Any]], None]]] = defaultdict(list)
-
- async def send(self, method: str, params: dict[str, Any]) -> None:
- self.sent.append((method, params))
- self.listeners_at_send.append(set(self.listeners))
-
- def on(self, event: str, callback: Callable[[dict[str, Any]], None]) -> None:
- self.listeners[event].append(callback)
-
- def remove_listener(self, event: str, callback: Callable[[dict[str, Any]], None]) -> None:
- self.listeners[event].remove(callback)
-
- def fire(self, event: str, payload: dict[str, Any]) -> None:
- for callback in list(self.listeners[event]):
- callback(payload)
diff --git a/tests/unit/services/browser_recording/v2/test_keyfold.py b/tests/unit/services/browser_recording/v2/test_keyfold.py
deleted file mode 100644
index 3c8c630c4..000000000
--- a/tests/unit/services/browser_recording/v2/test_keyfold.py
+++ /dev/null
@@ -1,299 +0,0 @@
-import pytest
-
-from skyvern.services.browser_recording.v2.keyfold import Fact, fold
-from skyvern.services.browser_recording.v2.ledger import Gesture, GestureKind, GestureLedger
-
-
-def _gesture(seq: int, kind: GestureKind, **kwargs: object) -> Gesture:
- return Gesture(
- seq=seq,
- t_received=float(seq),
- kind=kind,
- page_key="page-1",
- url="https://example.test/form",
- **kwargs,
- )
-
-
- ("gestures", "expected"),
- [
- (
- [
- _gesture(1, "mouse_pressed", x=10, y=20, button="left", click_count=2),
- _gesture(2, "mouse_released", x=11, y=21, button="left", click_count=2),
- ],
- [("click", None, 0, None, "left", 2.0, [1, 2])],
- ),
- (
- [
- _gesture(1, "key", key="a", text="a", key_event_type="keyDown"),
- _gesture(2, "key", key="a", text="a", key_event_type="char"),
- _gesture(3, "key", key="a", key_event_type="keyUp"),
- _gesture(4, "key", key="Enter", key_event_type="rawKeyDown"),
- _gesture(5, "key", key="Enter", key_event_type="keyUp"),
- ],
- [
- ("type_text", None, 1, None, None, 1.0, [1]),
- ("press_key", None, 0, "Enter", None, 4.0, [4]),
- ],
- ),
- (
- [
- _gesture(1, "key", key="b", text="b", key_event_type="keyDown"),
- _gesture(2, "key", key="Tab", key_event_type="keyDown"),
- ],
- [
- ("type_text", None, 1, None, None, 1.0, [1]),
- ("press_key", None, 0, "Tab", None, 2.0, [2]),
- ],
- ),
- (
- [
- _gesture(1, "mouse_pressed", x=10, y=20, button="left", click_count=1),
- _gesture(2, "key", key="a", text="a", key_event_type="keyDown"),
- _gesture(3, "key", key="Tab", key_event_type="keyDown"),
- _gesture(4, "key", key="b", text="b", key_event_type="keyDown"),
- ],
- [
- ("click", None, 0, None, "left", 1.0, [1]),
- ("type_text", "a", 1, None, None, 2.0, [2]),
- ("press_key", None, 0, "Tab", None, 3.0, [3]),
- ("type_text", None, 1, None, None, 4.0, [4]),
- ],
- ),
- (
- [
- _gesture(1, "key", key="c", text="c", key_event_type="keyDown"),
- _gesture(2, "mouse_pressed", x=30, y=40, button="left", click_count=1),
- ],
- [
- ("type_text", None, 1, None, None, 1.0, [1]),
- ("click", None, 0, None, "left", 2.0, [2]),
- ],
- ),
- (
- [
- _gesture(1, "key", key="a", text="a", key_event_type="keyDown"),
- _gesture(2, "key", key="b", text="b", key_event_type="keyDown"),
- _gesture(3, "key", key="Backspace", key_event_type="rawKeyDown"),
- _gesture(4, "paste", text="cd"),
- _gesture(5, "key", key="ArrowLeft", key_event_type="rawKeyDown"),
- _gesture(6, "key", key="ArrowLeft", key_event_type="keyUp"),
- ],
- [
- ("type_text", None, 3, None, None, 4.0, [1, 2, 3, 4]),
- ("press_key", None, 0, "ArrowLeft", None, 5.0, [5]),
- ],
- ),
- (
- [
- _gesture(1, "key", key="a", text="a", modifiers=4, key_event_type="keyDown"),
- _gesture(2, "key", key="n", text="n", key_event_type="keyDown"),
- _gesture(3, "key", key="e", text="e", key_event_type="keyDown"),
- _gesture(4, "key", key="w", text="w", key_event_type="keyDown"),
- ],
- [
- ("press_key", None, 0, "a", None, 1.0, [1]),
- ("type_text", None, 3, None, None, 4.0, [2, 3, 4]),
- ],
- ),
- (
- [
- _gesture(1, "key", key="Escape", key_event_type="rawKeyDown"),
- _gesture(2, "key", key="a", text="a", key_event_type="keyDown"),
- _gesture(3, "key", key="Enter", key_event_type="rawKeyDown"),
- ],
- [
- ("press_key", None, 0, "Escape", None, 1.0, [1]),
- ("type_text", None, 1, None, None, 2.0, [2]),
- ("press_key", None, 0, "Enter", None, 3.0, [3]),
- ],
- ),
- (
- [
- _gesture(1, "key", key="Backspace", key_event_type="rawKeyDown"),
- _gesture(2, "key", key="Backspace", key_event_type="rawKeyDown"),
- _gesture(3, "key", key="x", text="x", key_event_type="keyDown"),
- ],
- [
- ("press_key", None, 0, "Backspace", None, 1.0, [1]),
- ("press_key", None, 0, "Backspace", None, 2.0, [2]),
- ("type_text", None, 1, None, None, 3.0, [3]),
- ],
- ),
- (
- [_gesture(1, "mouse_pressed", x=10, y=20, button="left", click_count=1)],
- [("click", None, 0, None, "left", 1.0, [1])],
- ),
- (
- [
- _gesture(1, "key", key="a", text="a", key_event_type="keyDown"),
- _gesture(2, "navigate", target_url="https://example.test/next"),
- ],
- [("type_text", None, 1, None, None, 1.0, [1])],
- ),
- (
- [
- _gesture(1, "mouse_pressed", button="left", click_count=1),
- _gesture(2, "mouse_pressed", button="right", click_count=1),
- _gesture(3, "mouse_released", button="left", click_count=1),
- _gesture(4, "mouse_released", button="right", click_count=1),
- ],
- [
- ("click", None, 0, None, "left", 3.0, [1, 3]),
- ("click", None, 0, None, "right", 4.0, [2, 4]),
- ],
- ),
- (
- [_gesture(1, "key", key="A", text="A", modifiers=8, key_event_type="keyDown")],
- [("type_text", None, 1, None, None, 1.0, [1])],
- ),
- (
- [
- _gesture(1, "key", key="a", text="a", key_event_type="keyDown"),
- _gesture(2, "key", key="ArrowLeft", key_event_type="rawKeyDown"),
- _gesture(3, "key", key="b", text="b", key_event_type="keyDown"),
- ],
- [
- ("type_text", None, 1, None, None, 1.0, [1]),
- ("press_key", None, 0, "ArrowLeft", None, 2.0, [2]),
- ("type_text", None, 1, None, None, 3.0, [3]),
- ],
- ),
- # The caret moved before the delete, so Backspace must not pop the earlier run's
- # character: the whole "a" plus the backspace would vanish from the recording.
- (
- [
- _gesture(1, "key", key="a", text="a", key_event_type="keyDown"),
- _gesture(2, "key", key="ArrowLeft", key_event_type="rawKeyDown"),
- _gesture(3, "key", key="Backspace", key_event_type="rawKeyDown"),
- ],
- [
- ("type_text", None, 1, None, None, 1.0, [1]),
- ("press_key", None, 0, "ArrowLeft", None, 2.0, [2]),
- ("press_key", None, 0, "Backspace", None, 3.0, [3]),
- ],
- ),
- # A press whose release never came before the navigation must not claim the next
- # release on that button, which belongs to a click on the new page.
- (
- [
- _gesture(1, "mouse_pressed", x=1, y=2, button="left", click_count=1),
- _gesture(2, "navigate"),
- _gesture(3, "mouse_pressed", x=3, y=4, button="left", click_count=1),
- _gesture(4, "mouse_released", button="left", click_count=1),
- ],
- [
- ("click", None, 0, None, "left", 1.0, [1]),
- ("click", None, 0, None, "left", 4.0, [3, 4]),
- ],
- ),
- ],
-)
-def test_fold_scripted_gestures(
- gestures: list[Gesture],
- expected: list[tuple[str, str | None, int, str | None, str | None, float, list[int]]],
-) -> None:
- facts = fold(gestures)
-
- assert [
- (
- fact.kind,
- fact.typed_value,
- fact.typed_length,
- fact.key,
- fact.button,
- fact.t_end,
- fact.gesture_seqs,
- )
- for fact in facts
- ] == expected
-
-
-def test_secret_values_are_absent_from_reprs_and_survive_redaction_as_lengths() -> None:
- secret = "private-value"
- gesture = _gesture(1, "key", key=secret, text=secret, key_event_type="keyDown")
- ledger = GestureLedger("pbs-secret")
- ledger.append(gesture)
- fact = Fact(
- kind="type_text",
- t_start=1.0,
- t_end=1.0,
- page_key="page-1",
- url="https://example.test/form",
- typed_value=secret,
- typed_length=len(secret),
- )
-
- assert secret not in repr(gesture)
- assert secret not in repr(ledger)
- assert secret not in repr(fact)
-
- fact.redact()
-
- assert fact.typed_value is None
- assert fact.typed_length == len(secret)
-
-
-def test_fold_copies_focus_metadata_and_clears_it_after_tab() -> None:
- focus = _gesture(
- 1,
- "mouse_pressed",
- selector="#password",
- role="textbox",
- accessible_name="Password",
- tag="INPUT",
- input_type="password",
- is_secret=True,
- )
-
- facts = fold(
- [
- focus,
- _gesture(2, "key", key="a", text="a", key_event_type="keyDown"),
- _gesture(3, "key", key="Tab", key_event_type="keyDown"),
- _gesture(4, "key", key="b", text="b", key_event_type="keyDown"),
- ]
- )
-
- first_run = facts[1]
- second_run = facts[3]
- assert (
- first_run.selector,
- first_run.role,
- first_run.accessible_name,
- first_run.tag,
- first_run.input_type,
- ) == ("#password", "textbox", "Password", "INPUT", "password")
- assert first_run.typed_value is None
- assert first_run.typed_length == 1
- assert second_run.selector is None
- assert second_run.typed_value is None
- assert second_run.typed_length == 1
-
-
-def test_fold_clears_focus_and_redacts_run_started_after_navigation() -> None:
- focus = _gesture(
- 1,
- "mouse_pressed",
- selector="#username",
- role="textbox",
- accessible_name="Username",
- tag="INPUT",
- input_type="text",
- is_secret=False,
- )
-
- facts = fold(
- [
- focus,
- _gesture(2, "navigate"),
- _gesture(3, "key", key="a", text="a", key_event_type="keyDown"),
- ]
- )
-
- run_after_navigation = facts[-1]
- assert run_after_navigation.selector is None
- assert run_after_navigation.typed_value is None
- assert run_after_navigation.typed_length == 1
diff --git a/tests/unit/services/browser_recording/v2/test_observation.py b/tests/unit/services/browser_recording/v2/test_observation.py
deleted file mode 100644
index 670c990e8..000000000
--- a/tests/unit/services/browser_recording/v2/test_observation.py
+++ /dev/null
@@ -1,279 +0,0 @@
-import asyncio
-from typing import Any
-
-import pytest
-
-from skyvern.services.browser_recording.v2 import observation
-from skyvern.services.browser_recording.v2.ledger import Gesture, GestureKind, GestureLedger, start_ledger, stop_ledger
-from skyvern.services.browser_recording.v2.observation import Observer, get_observer, start_observer, stop_observer
-from tests.unit.services.browser_recording.v2._fakes import FakeCdpSession
-
-
-def _gesture(
- *,
- t_received: float,
- kind: GestureKind = "mouse_pressed",
- key: str | None = None,
- page_key: str = "page-1",
-) -> Gesture:
- return Gesture(
- seq=0,
- t_received=t_received,
- kind=kind,
- page_key=page_key,
- url="https://example.test/start",
- key=key,
- )
-
-
-async def test_page_enables_are_sent_together_after_listener_registration() -> None:
- started = {"Page.enable": asyncio.Event(), "Network.enable": asyncio.Event()}
-
- class _ConcurrentEnableSession(FakeCdpSession):
- async def send(self, method: str, params: dict[str, Any]) -> None:
- await super().send(method, params)
- started[method].set()
- other = "Network.enable" if method == "Page.enable" else "Page.enable"
- await started[other].wait()
-
- ledger = GestureLedger("pbs-concurrent-enables")
- session = _ConcurrentEnableSession()
-
- await asyncio.wait_for(Observer(ledger).attach_page_session("page-1", session), timeout=0.1)
-
- assert all("Page.frameNavigated" in listeners for listeners in session.listeners_at_send)
-
-
-async def test_navigation_attaches_to_a_recent_click_and_is_otherwise_standalone(
- monkeypatch: pytest.MonkeyPatch,
-) -> None:
- now = 1.0
- monkeypatch.setattr(observation, "monotonic", lambda: now)
- ledger = GestureLedger("pbs-observation")
- click = ledger.append(_gesture(t_received=now))
- ledger.append(_gesture(t_received=1.2, page_key="page-2"))
- session = FakeCdpSession()
- observer = Observer(ledger)
- await observer.attach_page_session("page-1", session)
-
- now = 1.5
- session.fire(
- "Page.frameStartedNavigating",
- {"frameId": "frame-1", "url": "https://example.test/redirecting"},
- )
- now = 2.0
- session.fire("Page.frameNavigated", {"frame": {"id": "frame-1", "url": "https://example.test/next"}})
- now = 5.0
- session.fire("Page.frameNavigated", {"frame": {"id": "frame-1", "url": "https://example.test/later"}})
- session.fire(
- "Page.frameNavigated",
- {"frame": {"id": "frame-2", "parentId": "frame-1", "url": "https://example.test/embedded"}},
- )
-
- assert [(effect.seq, effect.url, effect.caused_by_seq, effect.is_main_frame) for effect in ledger.effects()] == [
- (3, "https://example.test/next", click.seq, True),
- (4, "https://example.test/later", None, True),
- (5, "https://example.test/embedded", None, False),
- ]
-
-
-async def test_stale_pending_navigation_does_not_swallow_commit(monkeypatch: pytest.MonkeyPatch) -> None:
- now = 1.0
- monkeypatch.setattr(observation, "monotonic", lambda: now)
- ledger = GestureLedger("pbs-stale-navigation")
- click = ledger.append(_gesture(t_received=now))
- session = FakeCdpSession()
- observer = Observer(ledger)
- await observer.attach_page_session("page-1", session)
-
- session.fire("Page.frameStartedNavigating", {"frameId": "frame-1", "url": "https://example.test/start"})
- now = 5.0
- session.fire("Page.frameNavigated", {"frame": {"id": "frame-1", "url": "https://example.test/end"}})
-
- assert [(effect.url, effect.caused_by_seq) for effect in ledger.effects()] == [
- ("https://example.test/start", click.seq),
- ("https://example.test/end", None),
- ]
-
-
-async def test_navigation_that_completes_while_paused_does_not_backfill_the_destination(
- monkeypatch: pytest.MonkeyPatch,
-) -> None:
- now = 1.0
- monkeypatch.setattr(observation, "monotonic", lambda: now)
- ledger = GestureLedger("pbs-paused-navigation")
- click = ledger.append(_gesture(t_received=now))
- session = FakeCdpSession()
- observer = Observer(ledger)
- await observer.attach_page_session("page-1", session)
-
- session.fire("Page.frameStartedNavigating", {"frameId": "frame-1", "url": "https://example.test/start"})
- ledger.paused = True
- now = 1.5
- session.fire("Page.frameNavigated", {"frame": {"id": "frame-1", "url": "https://example.test/kept-out"}})
-
- assert [(effect.url, effect.caused_by_seq) for effect in ledger.effects()] == [
- ("https://example.test/start", click.seq),
- ]
-
-
-async def test_network_activity_settles_once_for_the_preceding_gesture(
- monkeypatch: pytest.MonkeyPatch,
-) -> None:
- now = 1.0
- monkeypatch.setattr(observation, "monotonic", lambda: now)
- monkeypatch.setattr(observation, "SETTLE_QUIET_MS", 1)
- ledger = GestureLedger("pbs-settle")
- click = ledger.append(_gesture(t_received=now))
- session = FakeCdpSession()
- observer = Observer(ledger)
- await observer.attach_page_session("page-1", session)
-
- now = 1.1
- session.fire("Network.requestWillBeSent", {"requestId": "1", "frameId": "frame-1"})
- now = 1.3
- session.fire("Network.loadingFinished", {"requestId": "1"})
- await asyncio.sleep(0.01)
-
- assert [(effect.kind, effect.caused_by_seq, effect.busy_ms) for effect in ledger.effects()] == [
- ("network_settle", click.seq, 300)
- ]
-
- no_gesture_ledger = GestureLedger("pbs-no-gesture")
- no_gesture_session = FakeCdpSession()
- no_gesture_observer = Observer(no_gesture_ledger)
- await no_gesture_observer.attach_page_session("page-1", no_gesture_session)
- now = 2.0
- no_gesture_session.fire("Network.requestWillBeSent", {"requestId": "2", "frameId": "frame-1"})
- await asyncio.sleep(0.01)
-
- assert no_gesture_ledger.effects() == []
-
-
-async def test_network_settle_survives_moves_and_anchors_to_the_action(monkeypatch: pytest.MonkeyPatch) -> None:
- now = 1.0
- monkeypatch.setattr(observation, "monotonic", lambda: now)
- monkeypatch.setattr(observation, "SETTLE_QUIET_MS", 1)
- ledger = GestureLedger("pbs-moving-settle")
- click = ledger.append(_gesture(t_received=now))
- for kind in ("mouse_released", "wheel", "mouse_moved"):
- now += 0.1
- ledger.append(_gesture(t_received=now, kind=kind))
- session = FakeCdpSession()
- observer = Observer(ledger)
- await observer.attach_page_session("page-1", session)
-
- now = 1.4
- session.fire("Network.requestWillBeSent", {"requestId": "1"})
- now = 1.5
- ledger.append(_gesture(t_received=now, kind="mouse_moved"))
- await asyncio.sleep(0.01)
-
- assert [(effect.caused_by_seq, effect.busy_ms) for effect in ledger.effects()] == [(click.seq, 400)]
-
-
-async def test_network_settle_is_capped_after_continuous_activity(monkeypatch: pytest.MonkeyPatch) -> None:
- now = 1.0
- monkeypatch.setattr(observation, "monotonic", lambda: now)
- ledger = GestureLedger("pbs-capped-settle")
- click = ledger.append(_gesture(t_received=now))
- session = FakeCdpSession()
- observer = Observer(ledger)
- await observer.attach_page_session("page-1", session)
-
- for now in (2.0, 10.0, 16.1):
- session.fire("Network.requestWillBeSent", {"requestId": str(now)})
-
- assert [(effect.caused_by_seq, effect.busy_ms, effect.detail) for effect in ledger.effects()] == [
- (click.seq, 15_000, {"capped": True})
- ]
-
-
-async def test_dialog_and_file_chooser_are_observed_without_interception() -> None:
- ledger = GestureLedger("pbs-page-effects")
- session = FakeCdpSession()
- observer = Observer(ledger)
- await observer.attach_page_session("page-1", session)
-
- session.fire("Page.javascriptDialogOpening", {"type": "alert", "message": "page text"})
- session.fire("Page.fileChooserOpened", {"frameId": "frame-1", "mode": "selectSingle", "backendNodeId": 9})
-
- assert [(effect.kind, effect.detail) for effect in ledger.effects()] == [
- ("dialog", {"type": "alert"}),
- ("file_chooser", {"mode": "selectSingle", "backendNodeId": 9}),
- ]
- assert "Page.handleJavaScriptDialog" not in [method for method, _ in session.sent]
- assert "Page.setInterceptFileChooserDialog" not in [method for method, _ in session.sent]
- assert all("Page.javascriptDialogOpening" in listeners for listeners in session.listeners_at_send)
-
-
-async def test_detach_removes_listeners() -> None:
- ledger = GestureLedger("pbs-detach")
- session = FakeCdpSession()
- observer = Observer(ledger)
- await observer.attach_page_session("page-1", session)
-
- observer.detach()
- session.fire("Page.javascriptDialogOpening", {"type": "confirm"})
- session.fire("Page.frameNavigated", {"frame": {"id": "frame-1", "url": "https://example.test/next"}})
-
- assert ledger.effects() == []
-
-
-async def test_browser_targets_are_filtered_and_deduplicated() -> None:
- ledger = GestureLedger("pbs-targets")
- session = FakeCdpSession()
- observer = Observer(ledger)
- await observer.attach_browser_session(session)
-
- session.fire(
- "Target.targetCreated",
- {"targetInfo": {"targetId": "worker-1", "type": "service_worker", "url": "https://example.test/worker"}},
- )
- page = {"targetInfo": {"targetId": "page-1", "type": "page", "url": "https://example.test/one"}}
- session.fire("Target.targetCreated", page)
- session.fire("Target.targetCreated", page)
- session.fire("Target.targetInfoChanged", page)
- session.fire(
- "Target.targetInfoChanged",
- {"targetInfo": {"targetId": "page-1", "type": "page", "url": "https://example.test/two"}},
- )
-
- assert [(effect.target_id, effect.url) for effect in ledger.effects()] == [
- ("page-1", "https://example.test/one"),
- ("page-1", "https://example.test/two"),
- ]
- assert set(session.listeners) == {"Target.targetCreated", "Target.targetInfoChanged"}
- assert session.listeners_at_send == [{"Target.targetCreated", "Target.targetInfoChanged"}]
-
-
-async def test_stop_ledger_detaches_observer_via_hook() -> None:
- browser_session_id = "pbs-stop-observer"
- ledger = start_ledger(browser_session_id)
- observer = start_observer(browser_session_id, ledger)
- session = FakeCdpSession()
- await observer.attach_page_session("page-1", session)
-
- try:
- stop_ledger(browser_session_id)
-
- assert all(not callbacks for callbacks in session.listeners.values())
- assert get_observer(browser_session_id) is None
- replacement_ledger = start_ledger(browser_session_id)
- replacement_observer = start_observer(browser_session_id, replacement_ledger)
- assert replacement_observer is not observer
- assert replacement_observer.ledger is replacement_ledger
- finally:
- stop_ledger(browser_session_id)
- stop_observer(browser_session_id)
diff --git a/tests/unit/services/browser_recording/v2/test_render.py b/tests/unit/services/browser_recording/v2/test_render.py
deleted file mode 100644
index 4c94a1a4e..000000000
--- a/tests/unit/services/browser_recording/v2/test_render.py
+++ /dev/null
@@ -1,216 +0,0 @@
-import json
-from collections.abc import Iterator
-
-import pytest
-
-from skyvern.services.browser_recording.v2.ledger import Effect, Gesture, GestureKind, get_ledger, stop_ledger
-from skyvern.services.browser_recording.v2.render import render_blocks, render_code
-from skyvern.services.browser_recording.v2.session import (
- RecordingSessionV2,
- discard_session_v2,
- start_session_v2,
-)
-
-PBS_ID = "pbs_render_v2"
-URL = "https://example.test/form"
-EMAIL_VALUE = "alpha"
-PASSWORD_VALUE = "omega"
-
-
[email protected](autouse=True)
-def _clean_registry() -> Iterator[None]:
- discard_session_v2(PBS_ID)
- stop_ledger(PBS_ID)
- yield
- discard_session_v2(PBS_ID)
- stop_ledger(PBS_ID)
-
-
-def _session() -> RecordingSessionV2:
- return start_session_v2(
- browser_session_id=PBS_ID,
- organization_id="org_123",
- workflow_permanent_id="wpid_123",
- on_update=lambda _update: None,
- )
-
-
-class _Script:
- def __init__(self, session: RecordingSessionV2) -> None:
- ledger = get_ledger(PBS_ID)
- assert ledger is not None
- self.ledger = ledger
- self.clock = 0.0
-
- def _tick(self) -> float:
- self.clock += 1.0
- return self.clock
-
- def gesture(self, kind: GestureKind, **kwargs: object) -> None:
- self.ledger.append(Gesture(seq=0, t_received=self._tick(), kind=kind, page_key="page-1", url=URL, **kwargs))
-
- def navigate(self, url: str = URL, *, is_main_frame: bool = True) -> None:
- self.ledger.append_effect(
- Effect(
- seq=0,
- t_received=self._tick(),
- kind="navigation",
- page_key="page-1",
- url=url,
- is_main_frame=is_main_frame,
- )
- )
-
- def click(self, **target: object) -> None:
- self.gesture("mouse_pressed", x=10, y=20, button="left", click_count=1, **target)
- self.gesture("mouse_released", x=10, y=20, button="left", click_count=1)
-
- def type_text(self, text: str) -> None:
- for character in text:
- self.gesture("key", key=character, text=character, key_event_type="keyDown")
-
-
-def _scripted_session() -> RecordingSessionV2:
- session = _session()
- script = _Script(session)
- script.navigate()
- script.click(selector="#search", role="button", accessible_name="Search", tag="button")
- script.click(selector="#email", role="textbox", accessible_name="Email", tag="input", input_type="email")
- script.type_text(EMAIL_VALUE)
- script.click(
- selector="#password",
- role="textbox",
- accessible_name="Password",
- tag="input",
- input_type="password",
- is_secret=True,
- )
- script.type_text(PASSWORD_VALUE)
- script.gesture("key", key="Enter", key_event_type="keyDown")
- session.interpret()
- return session
-
-
-async def test_render_blocks_emits_tier1_blocks_and_blank_parameters() -> None:
- result = render_blocks(_scripted_session())
-
- assert [block["block_type"] for block in result.blocks] == [
- "goto_url",
- "action",
- "action",
- "action",
- "action",
- "action",
- "action",
- ]
- assert [block["title"] for block in result.blocks if block["block_type"] == "action"] == [
- "Click Search",
- "Click Email",
- "Type into Email",
- "Click Password",
- "Type into Password",
- "Press Enter",
- ]
- assert [parameter["key"] for parameter in result.parameters] == ["email", "password"]
- assert all(parameter["default_value"] == "" for parameter in result.parameters)
-
- typed_blocks = [block for block in result.blocks if block.get("parameter_keys")]
- assert [block["parameter_keys"] for block in typed_blocks] == [["email"], ["password"]]
-
- rendered = json.dumps({"blocks": result.blocks, "parameters": result.parameters})
- assert "typed_length" not in rendered
- assert EMAIL_VALUE not in rendered
- assert PASSWORD_VALUE not in rendered
- assert result.diagnostics["dropped"] == 0
- assert result.diagnostics["unlocatable"] == 0
-
-
-async def test_render_code_emits_located_code_without_typed_values() -> None:
- result = render_code(_scripted_session())
-
- assert result is not None
- assert result.mode == "code"
- code = "\n".join(str(block["code"]) for block in result.blocks)
- assert "#search" in code
- assert "#email" in code
- assert "#password" in code
-
- rendered = json.dumps({"blocks": result.blocks, "parameters": result.parameters})
- assert EMAIL_VALUE not in rendered
- assert PASSWORD_VALUE not in rendered
- assert "typed_length" not in rendered
- assert all(parameter["default_value"] == "" for parameter in result.parameters)
- assert result.parameters
-
-
-async def test_render_code_falls_back_when_a_click_has_no_locator() -> None:
- session = _session()
- script = _Script(session)
- script.navigate()
- script.click(selector="#search", role="button", accessible_name="Search")
- script.click()
- session.interpret()
-
- assert render_code(session) is None
- assert render_blocks(session).diagnostics["unlocatable"] == 1
-
-
-async def test_a_sub_frame_navigation_is_not_a_step_in_either_renderer() -> None:
- """Only main-frame navigations are user intent; an ad iframe must not split the script."""
- session = _session()
- script = _Script(session)
- script.navigate()
- script.click(selector="#search", role="button", accessible_name="Search")
- script.navigate("https://ads.example.test/frame", is_main_frame=False)
- script.click(selector="#next", role="button", accessible_name="Next")
- session.interpret()
-
- blocks = render_blocks(session)
- assert [block["block_type"] for block in blocks.blocks] == ["goto_url", "action", "action"]
-
- code = render_code(session)
- assert code is not None
- assert len(code.blocks) == 1
-
-
-async def test_consecutive_navigations_render_the_same_way_in_both_renderers() -> None:
- session = _session()
- script = _Script(session)
- script.navigate("https://example.test/one")
- script.navigate("https://example.test/two")
- script.click(selector="#search", role="button", accessible_name="Search")
- session.interpret()
-
- blocks = render_blocks(session)
- assert [block["url"] for block in blocks.blocks if block["block_type"] == "goto_url"] == [
- "https://example.test/one",
- "https://example.test/two",
- ]
-
- code = render_code(session)
- assert code is not None
- rendered = "\n".join(str(block["code"]) for block in code.blocks)
- assert rendered.count("https://example.test/one") == 1
- assert rendered.count("https://example.test/two") == 1
-
-
-async def test_closed_shadow_row_renders_the_host_selector() -> None:
- session = _session()
- script = _Script(session)
- script.navigate()
- script.click(selector="#host", role="button", accessible_name="Submit", shadow_path=["#inner-button"])
- session.interpret()
-
- result = render_code(session)
-
- assert result is not None
- code = "\n".join(str(block["code"]) for block in result.blocks)
- assert "#host" in code
- assert "#inner-button" not in code
- assert any("closed shadow root" in note for note in result.notes)
diff --git a/tests/unit/services/browser_recording/v2/test_resolver.py b/tests/unit/services/browser_recording/v2/test_resolver.py
deleted file mode 100644
index e6613b031..000000000
--- a/tests/unit/services/browser_recording/v2/test_resolver.py
+++ /dev/null
@@ -1,542 +0,0 @@
-import asyncio
-from collections import defaultdict, deque
-from types import SimpleNamespace
-from typing import Any
-
-import pytest
-
-from skyvern.services.browser_recording.v2.keyfold import fold
-from skyvern.services.browser_recording.v2.ledger import Gesture, GestureLedger
-from skyvern.services.browser_recording.v2.resolver import Resolver
-
-_UNIQUE_MATCH = {"nodeIds": [1]}
-
-
-class _ScriptedSession:
- def __init__(self, responses: dict[str, list[dict[str, Any] | Exception]]) -> None:
- self.responses = {method: deque(values) for method, values in responses.items()}
- self.calls: list[tuple[str, dict[str, Any]]] = []
-
- async def send(self, method: str, params: dict[str, Any]) -> dict[str, Any]:
- self.calls.append((method, params))
- queue = self.responses.get(method)
- if not queue:
- if method == "DOM.enable":
- return {}
- if method == "DOM.querySelectorAll":
- return _UNIQUE_MATCH
- raise AssertionError(f"unscripted CDP call: {method}")
- response = queue.popleft()
- if isinstance(response, Exception):
- raise response
- return response
-
-
-def _gesture(**fields: Any) -> Gesture:
- return Gesture(
- seq=1,
- t_received=1.0,
- kind="mouse_pressed",
- page_key="page-1",
- url="https://example.test/form",
- x=fields.pop("x", 12),
- y=fields.pop("y", 34),
- **fields,
- )
-
-
-def _input_responses(
- *, input_type: str = "text", node_id: int = 8, frame_id: str = "main", element_id: str = "email"
-) -> dict[str, list]:
- return {
- "DOM.getDocument": [{"root": {"nodeId": 1}}],
- "Target.getTargetInfo": [{"targetInfo": {"targetId": "target-1"}}],
- "DOM.getNodeForLocation": [{"backendNodeId": 7, "frameId": frame_id}],
- "DOM.describeNode": [
- {
- "node": {
- "nodeId": node_id,
- "backendNodeId": 7,
- "nodeName": "INPUT",
- "frameId": frame_id,
- "attributes": [
- "id",
- element_id,
- "name",
- "email",
- "type",
- input_type,
- "aria-label",
- "Email address",
- ],
- }
- }
- ],
- "Accessibility.getPartialAXTree": [
- {
- "nodes": [
- {
- "role": {"value": "textbox"},
- "name": {"value": "Email address"},
- "properties": [],
- }
- ]
- }
- ],
- }
-
-
-class _Frame:
- """Only the attributes a Playwright ``Frame`` really exposes; notably no frame id."""
-
- def __init__(self, url: str, name: str, parent_frame: "_Frame | None" = None) -> None:
- self.url = url
- self.name = name
- self.parent_frame = parent_frame
-
-
-def _page(frames: list[Any] | None = None, new_cdp_session: Any = None) -> SimpleNamespace:
- context = SimpleNamespace(new_cdp_session=new_cdp_session) if new_cdp_session else SimpleNamespace()
- return SimpleNamespace(frames=frames or [], context=context)
-
-
-async def _drain(resolver: Resolver) -> None:
- await asyncio.gather(*tuple(resolver._tasks))
-
-
-async def test_resolves_input_on_existing_session_and_prefers_stable_id() -> None:
- session = _ScriptedSession(_input_responses())
- gesture = _gesture()
- resolver = Resolver(GestureLedger("pbs-resolve"))
-
- resolver.on_gesture(gesture, session, _page())
- await _drain(resolver)
-
- assert gesture.backend_node_id == 7
- assert gesture.frame_id == "main"
- assert gesture.target_id == "target-1"
- assert gesture.selector == "#email"
- assert gesture.role == "textbox"
- assert gesture.accessible_name == "Email address"
- assert gesture.tag == "INPUT"
- assert gesture.input_type == "text"
- assert gesture.is_secret is False
- methods = [method for method, _ in session.calls]
- assert methods.index("DOM.enable") < methods.index("DOM.getNodeForLocation")
- assert (
- "DOM.getNodeForLocation",
- {
- "x": 12,
- "y": 34,
- "includeUserAgentShadowDOM": False,
- "ignorePointerEventsNone": False,
- },
- ) in session.calls
- assert ("DOM.querySelectorAll", {"nodeId": 1, "selector": "#email"}) in session.calls
- assert "Accessibility.enable" not in methods
-
-
-async def test_password_resolution_redacts_the_folded_run() -> None:
- session = _ScriptedSession(_input_responses(input_type="password"))
- press = _gesture()
- resolver = Resolver(GestureLedger("pbs-secret"))
-
- resolver.on_gesture(press, session, _page())
- await _drain(resolver)
- facts = fold(
- [
- press,
- Gesture(
- seq=2,
- t_received=2.0,
- kind="key",
- page_key=press.page_key,
- url=press.url,
- key="s",
- text="s",
- key_event_type="keyDown",
- ),
- Gesture(
- seq=3,
- t_received=3.0,
- kind="key",
- page_key=press.page_key,
- url=press.url,
- key="e",
- text="e",
- key_event_type="keyDown",
- ),
- ]
- )
-
- assert press.is_secret is True
- assert facts[1].kind == "type_text"
- assert facts[1].typed_value is None
- assert facts[1].typed_length == 2
- assert facts[1].selector == "#email"
-
-
-async def test_synthetic_id_falls_back_to_name() -> None:
- session = _ScriptedSession(_input_responses(element_id="field-123"))
- gesture = _gesture()
- resolver = Resolver(GestureLedger("pbs-synthetic-id"))
-
- resolver.on_gesture(gesture, session, _page())
- await _drain(resolver)
-
- assert gesture.selector == 'input[name="email"]'
-
-
-async def test_ambiguous_candidate_falls_through_to_a_unique_one() -> None:
- responses = _input_responses()
- responses["DOM.describeNode"] = [
- {
- "node": {
- "nodeId": 8,
- "backendNodeId": 7,
- "nodeName": "INPUT",
- "frameId": "main",
- "attributes": ["aria-label", "Email address", "data-testid", "email-field", "type", "text"],
- }
- }
- ]
- responses["DOM.querySelectorAll"] = [{"nodeIds": [4, 5]}, {"nodeIds": [4]}]
- session = _ScriptedSession(responses)
- gesture = _gesture()
- resolver = Resolver(GestureLedger("pbs-ambiguous"))
-
- resolver.on_gesture(gesture, session, _page())
- await _drain(resolver)
-
- assert [params["selector"] for method, params in session.calls if method == "DOM.querySelectorAll"] == [
- 'input[aria-label="Email address"]',
- '[data-testid="email-field"]',
- ]
- assert gesture.selector == '[data-testid="email-field"]'
-
-
-async def test_structural_fallback_carries_nth_of_type() -> None:
- responses = _input_responses()
- responses["DOM.describeNode"] = [
- {"node": {"nodeId": 8, "parentId": 9, "backendNodeId": 7, "nodeName": "INPUT", "frameId": "main"}},
- {
- "node": {
- "nodeId": 9,
- "parentId": 11,
- "backendNodeId": 4,
- "nodeType": 1,
- "nodeName": "DIV",
- "children": [
- {"nodeType": 1, "nodeName": "INPUT", "backendNodeId": 5},
- {"nodeType": 1, "nodeName": "INPUT", "backendNodeId": 6},
- {"nodeType": 1, "nodeName": "INPUT", "backendNodeId": 7},
- ],
- }
- },
- {
- "node": {
- "nodeId": 11,
- "backendNodeId": 2,
- "nodeType": 9,
- "nodeName": "#document",
- "children": [
- {"nodeType": 1, "nodeName": "DIV", "backendNodeId": 3},
- {"nodeType": 1, "nodeName": "DIV", "backendNodeId": 4},
- ],
- }
- },
- ]
- responses["Accessibility.getFullAXTree"] = [
- {
- "nodes": [
- {"role": {"value": "textbox"}, "name": {"value": "Email address"}, "backendDOMNodeId": 6},
- {"role": {"value": "textbox"}, "name": {"value": "Email address"}, "backendDOMNodeId": 7},
- ]
- }
- ]
- session = _ScriptedSession(responses)
- gesture = _gesture()
- resolver = Resolver(GestureLedger("pbs-structural"))
-
- resolver.on_gesture(gesture, session, _page())
- await _drain(resolver)
-
- assert gesture.selector == "div:nth-of-type(2) > input:nth-of-type(3)"
-
-
-async def test_same_process_iframe_stays_on_parent_session() -> None:
- session = _ScriptedSession(_input_responses(frame_id="child-frame"))
- opened: list[Any] = []
-
- async def new_cdp_session(frame: Any) -> Any:
- opened.append(frame)
- raise AssertionError("same-process iframe must stay on the parent session")
-
- gesture = _gesture(x=110, y=220)
- resolver = Resolver(GestureLedger("pbs-same-process"))
-
- resolver.on_gesture(gesture, session, _page(new_cdp_session=new_cdp_session))
- await _drain(resolver)
-
- assert gesture.backend_node_id == 7
- assert gesture.frame_id == "child-frame"
- assert gesture.tag == "INPUT"
- assert opened == []
- assert [method for method, _ in session.calls].count("DOM.getNodeForLocation") == 1
-
-
-async def test_oopif_maps_frame_tree_to_one_cached_child_session_and_translates_coordinates() -> None:
- iframe_node = {
- "node": {
- "nodeId": 21,
- "backendNodeId": 20,
- "nodeName": "IFRAME",
- "frameId": "child-frame",
- }
- }
- box_model = {"model": {"content": [100, 200, 300, 200, 300, 400, 100, 400]}}
- frame_tree = {
- "frameTree": {
- "frame": {"id": "main", "url": "https://example.test/form"},
- "childFrames": [{"frame": {"id": "child-frame", "url": "https://pay.test/widget", "name": "pay"}}],
- }
- }
- parent = _ScriptedSession(
- {
- "DOM.getDocument": [{"root": {"nodeId": 1}}],
- "Target.getTargetInfo": [{"targetInfo": {"targetId": "target-1"}}],
- "DOM.getNodeForLocation": [
- {"backendNodeId": 20, "frameId": "child-frame"},
- {"backendNodeId": 20, "frameId": "child-frame"},
- ],
- "DOM.describeNode": [iframe_node, iframe_node],
- "Page.getFrameTree": [frame_tree, frame_tree],
- "DOM.getBoxModel": [box_model, box_model],
- }
- )
- child_responses = _input_responses(frame_id="child-frame")
- child_responses["Target.getTargetInfo"] = []
- child_responses["DOM.getNodeForLocation"] = [
- {"backendNodeId": 7, "frameId": "child-frame"},
- {"backendNodeId": 7, "frameId": "child-frame"},
- ]
- child_responses["DOM.describeNode"] *= 2
- child_responses["DOM.getDocument"] *= 2
- child_responses["Accessibility.getPartialAXTree"] *= 2
- child = _ScriptedSession(child_responses)
- main_frame = _Frame("https://example.test/form", "")
- child_frame = _Frame("https://pay.test/widget", "pay", main_frame)
- opened: defaultdict[int, int] = defaultdict(int)
-
- async def new_cdp_session(target_frame: Any) -> _ScriptedSession:
- opened[id(target_frame)] += 1
- return child
-
- page = _page([main_frame, child_frame], new_cdp_session)
- resolver = Resolver(GestureLedger("pbs-oopif"))
- gestures = [_gesture(x=115, y=225), _gesture(x=120, y=230)]
-
- for gesture in gestures:
- resolver.on_gesture(gesture, parent, page)
- await _drain(resolver)
-
- assert [gesture.frame_id for gesture in gestures] == ["child-frame", "child-frame"]
- assert [gesture.selector for gesture in gestures] == ["#email", "#email"]
- assert opened == {id(child_frame): 1}
- child_hits = [params for method, params in child.calls if method == "DOM.getNodeForLocation"]
- assert child_hits == [
- {
- "x": 15,
- "y": 25,
- "includeUserAgentShadowDOM": False,
- "ignorePointerEventsNone": False,
- },
- {
- "x": 20,
- "y": 30,
- "includeUserAgentShadowDOM": False,
- "ignorePointerEventsNone": False,
- },
- ]
-
-
-async def test_two_same_url_unnamed_oopifs_resolve_in_the_frame_that_was_clicked() -> None:
- """Two identical cross-origin widgets on one page: url+name can't tell them apart, so the
- child session has to confirm its own frame id or the click resolves in the wrong document."""
- iframe_node = {"node": {"nodeId": 21, "backendNodeId": 20, "nodeName": "IFRAME", "frameId": "second-widget"}}
- frame_tree = {
- "frameTree": {
- "frame": {"id": "main", "url": "https://example.test/form"},
- "childFrames": [
- {"frame": {"id": "first-widget", "url": "https://pay.test/widget"}},
- {"frame": {"id": "second-widget", "url": "https://pay.test/widget"}},
- ],
- }
- }
- parent = _ScriptedSession(
- {
- "Target.getTargetInfo": [{"targetInfo": {"targetId": "target-1"}}],
- "DOM.getNodeForLocation": [{"backendNodeId": 20, "frameId": "second-widget"}],
- "DOM.describeNode": [iframe_node],
- "Page.getFrameTree": [frame_tree],
- "DOM.getBoxModel": [{"model": {"content": [100, 200, 300, 200, 300, 400, 100, 400]}}],
- }
- )
- wrong = _ScriptedSession({"Page.getFrameTree": [{"frameTree": {"frame": {"id": "first-widget"}}}]})
- right_responses = _input_responses(frame_id="second-widget", element_id="card")
- right_responses["Target.getTargetInfo"] = []
- right_responses["DOM.getNodeForLocation"] = [{"backendNodeId": 7, "frameId": "second-widget"}]
- right_responses["Page.getFrameTree"] = [{"frameTree": {"frame": {"id": "second-widget"}}}]
- right = _ScriptedSession(right_responses)
- main_frame = _Frame("https://example.test/form", "")
- first = _Frame("https://pay.test/widget", "", main_frame)
- second = _Frame("https://pay.test/widget", "", main_frame)
- sessions = {id(first): wrong, id(second): right}
-
- async def new_cdp_session(target_frame: Any) -> _ScriptedSession:
- return sessions[id(target_frame)]
-
- resolver = Resolver(GestureLedger("pbs-twin-oopif"))
- gesture = _gesture(x=115, y=225)
-
- resolver.on_gesture(gesture, parent, _page([main_frame, first, second], new_cdp_session))
- await _drain(resolver)
-
- assert gesture.frame_id == "second-widget"
- assert gesture.selector == "#card"
-
-
-async def test_a_navigation_on_the_same_session_does_not_reuse_a_stale_document_root() -> None:
- """DOM node ids are invalidated on every document swap; a cached root makes the uniqueness
- check query a node id that no longer exists, and every locator degrades silently."""
- responses = _input_responses()
- responses["DOM.getDocument"] = [{"root": {"nodeId": 1}}, {"root": {"nodeId": 42}}]
- responses["Target.getTargetInfo"] *= 2
- responses["DOM.getNodeForLocation"] *= 2
- responses["DOM.describeNode"] *= 2
- responses["Accessibility.getPartialAXTree"] *= 2
- session = _ScriptedSession(responses)
- resolver = Resolver(GestureLedger("pbs-nav"))
-
- for _ in range(2):
- resolver.on_gesture(_gesture(), session, _page())
- await _drain(resolver)
-
- roots = [params["nodeId"] for method, params in session.calls if method == "DOM.querySelectorAll"]
- assert roots == [1, 42]
- assert [method for method, _ in session.calls].count("DOM.enable") == 1
-
-
-async def test_closed_shadow_target_uses_host_selector_and_inner_path() -> None:
- responses = _input_responses()
- responses["DOM.describeNode"] = [
- {
- "node": {
- "nodeId": 8,
- "parentId": 9,
- "backendNodeId": 7,
- "nodeName": "INPUT",
- "frameId": "main",
- "attributes": ["id", "inner", "type", "text"],
- }
- },
- {"node": {"nodeId": 9, "parentId": 10, "nodeType": 11, "shadowRootType": "closed"}},
- {
- "node": {
- "nodeId": 10,
- "nodeType": 1,
- "nodeName": "SECRET-FIELD",
- "attributes": ["id", "field-host"],
- }
- },
- ]
- session = _ScriptedSession(responses)
- resolver = Resolver(GestureLedger("pbs-shadow"))
- gesture = _gesture()
-
- resolver.on_gesture(gesture, session, _page())
- await _drain(resolver)
-
- assert gesture.selector == "#field-host"
- assert gesture.shadow_path == ["#inner"]
- assert ("DOM.querySelectorAll", {"nodeId": 9, "selector": "#inner"}) in session.calls
-
-
-async def test_forget_session_drops_the_per_session_caches() -> None:
- responses = _input_responses()
- responses["DOM.getDocument"] *= 2
- responses["Target.getTargetInfo"] *= 2
- responses["DOM.getNodeForLocation"] *= 2
- responses["DOM.describeNode"] *= 2
- responses["Accessibility.getPartialAXTree"] *= 2
- session = _ScriptedSession(responses)
- resolver = Resolver(GestureLedger("pbs-forget"))
-
- resolver.on_gesture(_gesture(), session, _page())
- await _drain(resolver)
- resolver.forget_session(session)
- resolver.on_gesture(_gesture(), session, _page())
- await _drain(resolver)
-
- methods = [method for method, _ in session.calls]
- assert methods.count("DOM.getDocument") == 2
- assert methods.count("Target.getTargetInfo") == 2
-
-
-async def test_resolution_failures_are_swallowed_and_close_cancels_pending_tasks() -> None:
- failing = _ScriptedSession({"Target.getTargetInfo": [RuntimeError("send failed")]})
- page = _page()
- resolver = Resolver(GestureLedger("pbs-failure"))
- gesture = _gesture()
-
- resolver.on_gesture(gesture, failing, page)
- await _drain(resolver)
-
- started = asyncio.Event()
-
- class _PendingSession:
- async def send(self, method: str, params: dict[str, Any]) -> dict[str, Any]:
- started.set()
- await asyncio.Event().wait()
- return {}
-
- pending_gesture = _gesture()
- resolver.on_gesture(pending_gesture, _PendingSession(), page)
- await started.wait()
- tasks = tuple(resolver._tasks)
- resolver.close()
- await asyncio.gather(*tasks, return_exceptions=True)
-
- facts = fold(
- [
- pending_gesture,
- Gesture(
- seq=2,
- t_received=2.0,
- kind="key",
- page_key=pending_gesture.page_key,
- url=pending_gesture.url,
- key="s",
- text="s",
- key_event_type="keyDown",
- ),
- ]
- )
-
- assert gesture.selector is None
- assert tasks
- assert all(task.cancelled() for task in tasks)
- assert facts[1].typed_value is None
- assert facts[1].typed_length == 1
diff --git a/tests/unit/services/browser_recording/v2/test_session.py b/tests/unit/services/browser_recording/v2/test_session.py
deleted file mode 100644
index 003ca70f7..000000000
--- a/tests/unit/services/browser_recording/v2/test_session.py
+++ /dev/null
@@ -1,186 +0,0 @@
-from collections.abc import Iterator
-
-import pytest
-
-from skyvern.services.browser_recording.v2 import session as session_module
-from skyvern.services.browser_recording.v2.ledger import Effect, Gesture, GestureKind, get_ledger, stop_ledger
-from skyvern.services.browser_recording.v2.session import (
- RecordingSessionV2,
- RecordingUpdateV2,
- discard_session_v2,
- start_session_v2,
- stop_session_v2,
-)
-from tests.unit.services.browser_recording.v2._fakes import FakeCdpSession
-
-PBS_ID = "pbs_session_v2"
-URL = "https://example.test/form"
-
-
[email protected](autouse=True)
-def _clean_registry() -> Iterator[None]:
- discard_session_v2(PBS_ID)
- stop_ledger(PBS_ID)
- yield
- discard_session_v2(PBS_ID)
- stop_ledger(PBS_ID)
-
-
-def _start(updates: list[RecordingUpdateV2]) -> RecordingSessionV2:
- return start_session_v2(
- browser_session_id=PBS_ID,
- organization_id="org_123",
- workflow_permanent_id="wpid_123",
- on_update=updates.append,
- )
-
-
-def _gesture(seq: int, kind: GestureKind, **kwargs: object) -> Gesture:
- return Gesture(seq=seq, t_received=float(seq), kind=kind, page_key="page-1", url=URL, **kwargs)
-
-
-async def test_scripted_gestures_and_effects_become_deterministic_steps() -> None:
- updates: list[RecordingUpdateV2] = []
- session = _start(updates)
- ledger = get_ledger(PBS_ID)
- assert ledger is not None
-
- click = ledger.append(
- _gesture(0, "mouse_pressed", x=10, y=20, button="left", click_count=1, accessible_name="Search")
- )
- ledger.append(_gesture(0, "mouse_released", x=10, y=20, button="left", click_count=1))
- ledger.append(_gesture(0, "key", key="h", text="h", key_event_type="keyDown", accessible_name="Search"))
- ledger.append(_gesture(0, "key", key="i", text="i", key_event_type="keyDown"))
- ledger.append_effect(
- Effect(seq=0, t_received=9.0, kind="network_settle", page_key="page-1", caused_by_seq=click.seq, busy_ms=420)
- )
- ledger.append_effect(
- Effect(
- seq=0,
- t_received=10.0,
- kind="navigation",
- page_key="page-1",
- url="https://example.test/results?q=hi",
- is_main_frame=True,
- )
- )
- ledger.append_effect(
- Effect(seq=0, t_received=11.0, kind="navigation", page_key="page-1", url="https://ads.test/frame")
- )
-
- session.interpret()
- steps = session.steps
-
- assert [(step.kind, step.title) for step in steps] == [
- ("click", "Click Search"),
- ("type_text", "Type into Search"),
- ("goto_url", "Go to example.test/results"),
- ]
- assert steps[0].step_id == f"{PBS_ID}:1"
- assert steps[0].settle_ms == 420
- assert steps[1].typed_length == 2
- assert steps[1].gesture_seqs == [3, 4]
- assert updates[-1].session_revision == len(updates)
-
-
-async def test_pause_drops_gestures_and_resume_restores_capture() -> None:
- from skyvern.services.browser_recording.v2.tap import tap_pipelined
-
- updates: list[RecordingUpdateV2] = []
- session = _start(updates)
- page = object()
-
- session.pause()
- tap_pipelined(PBS_ID, "keyEvent", {"type": "keyDown", "key": "a", "text": "a"}, 1.0, page, None)
- paused_effect = session.ledger.append_effect(
- Effect(seq=0, t_received=1.0, kind="navigation", page_key="page-1", url=URL, is_main_frame=True)
- )
- session.interpret()
- assert paused_effect is None
- assert session.ledger.effects() == []
- assert session.steps == []
-
- session.resume()
- tap_pipelined(PBS_ID, "keyEvent", {"type": "keyDown", "key": "b", "text": "b"}, 2.0, page, None)
- session.interpret()
- assert [step.typed_length for step in session.steps] == [1]
-
-
-async def test_seal_returns_final_steps_and_marks_finalized() -> None:
- updates: list[RecordingUpdateV2] = []
- session = _start(updates)
- ledger = get_ledger(PBS_ID)
- assert ledger is not None
- ledger.append(_gesture(0, "mouse_pressed", x=1, y=2, button="left", click_count=1, tag="BUTTON"))
-
- steps = await stop_session_v2(PBS_ID)
-
- assert [step.title for step in steps] == ["Click button"]
- assert session.sealed is True
- assert updates[-1].finalized is True
- assert updates[-1].pending is False
- assert updates[-1].is_snapshot is True
- assert updates[-1].steps == steps
-
-
-async def test_stopping_leaves_no_capture_behind() -> None:
- updates: list[RecordingUpdateV2] = []
- session = _start(updates)
- cdp_session = FakeCdpSession()
- await session.attach_page("page-1", cdp_session)
- ledger = get_ledger(PBS_ID)
- assert ledger is not None
- ledger.append(_gesture(0, "mouse_pressed", x=1, y=2, button="left", click_count=1, tag="BUTTON"))
-
- await stop_session_v2(PBS_ID)
-
- assert ledger.append(_gesture(0, "key", key="a", text="a")) is None
- assert ledger.append_effect(Effect(seq=0, t_received=1.0, kind="navigation", page_key="page-1")) is None
- assert [step.title for step in session.steps] == ["Click button"]
- assert get_ledger(PBS_ID) is None
- assert all(not callbacks for callbacks in cdp_session.listeners.values())
-
-
-async def test_abandoned_unsealed_sessions_are_capped_so_their_ledgers_cannot_leak() -> None:
- """A socket that drops without sealing keeps its session on purpose so a reconnect can
- resume it, so nothing else ever reaches stop_ledger for a client that never comes back."""
- ids = [f"pbs_abandoned_{index}" for index in range(session_module.MAX_LIVE_SESSIONS + 1)]
- try:
- for browser_session_id in ids:
- start_session_v2(
- browser_session_id=browser_session_id,
- organization_id="org_123",
- workflow_permanent_id=None,
- on_update=lambda _update: None,
- )
-
- assert len(session_module.sessions_v2) <= session_module.MAX_LIVE_SESSIONS
- assert get_ledger(ids[0]) is None
- assert get_ledger(ids[-1]) is not None
- finally:
- for browser_session_id in ids:
- discard_session_v2(browser_session_id)
- stop_ledger(browser_session_id)
-
-
-async def test_reconnect_reuses_the_session_and_re_emits_a_snapshot() -> None:
- first: list[RecordingUpdateV2] = []
- session = _start(first)
- ledger = get_ledger(PBS_ID)
- assert ledger is not None
- ledger.append(_gesture(0, "mouse_pressed", x=1, y=2, button="left", click_count=1, tag="A"))
- session.interpret()
-
- second: list[RecordingUpdateV2] = []
- reconnected = _start(second)
-
- assert reconnected is session
- assert second[-1].is_snapshot is True
- assert [step.title for step in second[-1].steps] == ["Click a"]
- assert second[-1].session_revision > first[-1].session_revision
diff --git a/tests/unit/services/browser_recording/v2/test_tap.py b/tests/unit/services/browser_recording/v2/test_tap.py
deleted file mode 100644
index b7d8d404f..000000000
--- a/tests/unit/services/browser_recording/v2/test_tap.py
+++ /dev/null
@@ -1,124 +0,0 @@
-from types import SimpleNamespace
-from unittest.mock import Mock
-
-from skyvern.services.browser_recording.v2.ledger import get_ledger, start_ledger, stop_ledger
-from skyvern.services.browser_recording.v2.resolver import start_resolver
-from skyvern.services.browser_recording.v2.tap import tap_navigation, tap_paste, tap_pipelined
-
-
-def test_tap_pipelined_is_inert_without_a_ledger_and_appends_validated_mouse_fields_with_one() -> None:
- browser_session_id = "pbs-tap"
- page = SimpleNamespace(url="https://example.test/form")
- validated = {
- "type": "mousePressed",
- "x": 12,
- "y": 34,
- "button": "left",
- "clickCount": 2,
- "modifiers": 4,
- }
- stop_ledger(browser_session_id)
-
- cdp_session = SimpleNamespace()
-
- tap_pipelined(browser_session_id, "mouseEvent", validated, 1.25, page, cdp_session)
-
- assert get_ledger(browser_session_id) is None
-
- ledger = start_ledger(browser_session_id)
- try:
- tap_pipelined(browser_session_id, "mouseEvent", validated, 1.25, page, cdp_session)
- tap_pipelined(browser_session_id, "mouseEvent", validated, 1.5, SimpleNamespace(), cdp_session)
-
- assert [row.seq for row in ledger.rows()] == [1, 2]
- row = ledger.rows()[0]
- assert row.kind == "mouse_pressed"
- assert row.t_received == 1.25
- assert row.page_key == str(id(page))
- assert row.url == page.url
- assert (row.x, row.y, row.button, row.click_count, row.modifiers) == (12, 34, "left", 2, 4)
- assert ledger.rows()[1].url == ""
- finally:
- stop_ledger(browser_session_id)
-
-
-def test_tap_pipelined_schedules_resolution_for_mouse_pressed_only() -> None:
- browser_session_id = "pbs-resolver-tap"
- ledger = start_ledger(browser_session_id)
- resolver = start_resolver(browser_session_id, ledger)
- resolver.on_gesture = Mock()
- page = SimpleNamespace(url="https://example.test/form")
- cdp_session = SimpleNamespace()
-
- try:
- tap_pipelined(
- browser_session_id,
- "mouseEvent",
- {"type": "mousePressed", "x": 12, "y": 34},
- 1.0,
- page,
- cdp_session,
- )
- tap_pipelined(
- browser_session_id,
- "mouseEvent",
- {"type": "mouseMoved", "x": 13, "y": 35},
- 2.0,
- page,
- cdp_session,
- )
-
- resolver.on_gesture.assert_called_once_with(ledger.rows()[0], cdp_session, page)
- finally:
- stop_ledger(browser_session_id)
-
-
-def test_tap_paste_uses_the_latest_ledger_page_identity_or_empty_strings() -> None:
- browser_session_id = "pbs-paste"
- stop_ledger(browser_session_id)
- ledger = start_ledger(browser_session_id)
- page = SimpleNamespace()
- try:
- tap_paste(browser_session_id, "first", 1.0)
- tap_navigation(browser_session_id, "reloadEvent", {}, 2.0, page)
- tap_paste(browser_session_id, "second", 3.0)
-
- first, navigation, second = ledger.rows()
- assert (first.page_key, first.url) == ("", "")
- assert navigation.url == ""
- assert (second.page_key, second.url) == (navigation.page_key, navigation.url)
- finally:
- stop_ledger(browser_session_id)
-
-
-def test_tap_failure_is_logged_and_never_reaches_the_input_path(monkeypatch) -> None:
- browser_session_id = "pbs-guard"
- stop_ledger(browser_session_id)
- ledger = start_ledger(browser_session_id)
- try:
- monkeypatch.setattr(ledger, "append", Mock(side_effect=RuntimeError("recorder bug")))
-
- tap_pipelined(browser_session_id, "mouseEvent", {"type": "mousePressed"}, 1.0, SimpleNamespace(), None)
- tap_navigation(browser_session_id, "reloadEvent", {}, 2.0, SimpleNamespace())
- tap_paste(browser_session_id, "text", 3.0)
- finally:
- stop_ledger(browser_session_id)
-
-
-def test_consecutive_mouse_moves_collapse_to_the_latest_so_they_cannot_evict_discrete_gestures() -> None:
- browser_session_id = "pbs-moves"
- stop_ledger(browser_session_id)
- ledger = start_ledger(browser_session_id)
- page = SimpleNamespace(url="https://example.test/")
- try:
- tap_pipelined(browser_session_id, "mouseEvent", {"type": "mousePressed", "x": 1, "y": 1}, 1.0, page, None)
- for i in range(ledger.capacity + 10):
- tap_pipelined(browser_session_id, "mouseEvent", {"type": "mouseMoved", "x": i, "y": 0}, 2.0 + i, page, None)
- tap_pipelined(
- browser_session_id, "mouseEvent", {"type": "mouseMoved", "x": 5, "y": 5}, 9.0, SimpleNamespace(), None
- )
-
- kinds = [(row.kind, row.x) for row in ledger.rows()]
- assert kinds == [("mouse_pressed", 1), ("mouse_moved", ledger.capacity + 9), ("mouse_moved", 5)]
- finally:
- stop_ledger(browser_session_id)
diff --git a/tests/unit/test_agent_cleanup_download_suffix.py b/tests/unit/test_agent_cleanup_download_suffix.py
index ed8d5852c..21948382d 100644
--- a/tests/unit/test_agent_cleanup_download_suffix.py
+++ b/tests/unit/test_agent_cleanup_download_suffix.py
@@ -872,3 +872,148 @@ async def test_wait_for_in_flight_downloads_completes_normally_when_should_cance
assert completed is True
assert cancelled is False
+
+
+async def test_finalize_skips_session_copy_whose_bytes_already_in_run_dir(tmp_path) -> None:
+ # A persistent-session blob: download lands in BOTH the session downloads dir and the run dir
+ # (the eager blob carve-out). Finalization must not materialize a second physical copy of
+ # identical bytes, or FileUploadBlock uploads the same statement twice and the customer's
+ # second signed S3 upload URL 403s (SKY-14276).
+ agent = ForgeAgent()
+ task = _make_task(workflow_run_id="wr-dedupe")
+ task.browser_session_id = "pbs-1"
+
+ download_dir = tmp_path / "downloads"
+ download_dir.mkdir()
+ statement_bytes = b"STATEMENT-BYTES-A"
+ (download_dir / "run-copy.pdf").write_bytes(statement_bytes) # the eager blob carve-out copy
+
+ session_uri = "s3://bucket/browser_sessions/pbs-1/downloads/Statement.pdf"
+ aws_client = MagicMock()
+ aws_client.download_file = AsyncMock(return_value=statement_bytes)
+
+ with (
+ patch("skyvern.forge.agent.get_path_for_workflow_download_directory", return_value=download_dir),
+ patch("skyvern.forge.agent.skyvern_context.current", return_value=None),
+ patch("skyvern.forge.agent.get_aws_client", return_value=aws_client),
+ patch("skyvern.forge.agent.app") as mock_app,
+ ):
+ mock_app.STORAGE.list_downloaded_files_in_browser_session = AsyncMock(return_value=[session_uri])
+ await agent._finalize_downloaded_files_for_task(
+ task,
+ organization_id=task.organization_id,
+ download_suffix=None,
+ list_files_before=[],
+ randomize_if_missing=False,
+ )
+
+ remaining = sorted(p.name for p in download_dir.iterdir())
+ assert remaining == ["run-copy.pdf"], f"session copy should be deduped by content, got {remaining}"
+ assert (download_dir / "run-copy.pdf").read_bytes() == statement_bytes
+
+
+async def test_finalize_materializes_session_download_when_run_dir_empty(tmp_path) -> None:
+ # Load-bearing: on a non-blob persistent session the run dir is empty (SESSION_DIR suppression),
+ # so finalization MUST still materialize the one session download — otherwise FileUploadBlock
+ # fails the block with an empty run dir. Content dedupe must not regress this.
+ agent = ForgeAgent()
+ task = _make_task(workflow_run_id="wr-materialize")
+ task.browser_session_id = "pbs-2"
+
+ download_dir = tmp_path / "downloads"
+ download_dir.mkdir()
+
+ session_uri = "s3://bucket/browser_sessions/pbs-2/downloads/OnlyStatement.pdf"
+ aws_client = MagicMock()
+ aws_client.download_file = AsyncMock(return_value=b"ONLY-STATEMENT-BYTES")
+
+ with (
+ patch("skyvern.forge.agent.get_path_for_workflow_download_directory", return_value=download_dir),
+ patch("skyvern.forge.agent.skyvern_context.current", return_value=None),
+ patch("skyvern.forge.agent.get_aws_client", return_value=aws_client),
+ patch("skyvern.forge.agent.app") as mock_app,
+ ):
+ mock_app.STORAGE.list_downloaded_files_in_browser_session = AsyncMock(return_value=[session_uri])
+ await agent._finalize_downloaded_files_for_task(
+ task,
+ organization_id=task.organization_id,
+ download_suffix=None,
+ list_files_before=[],
+ randomize_if_missing=False,
+ )
+
+ remaining = sorted(p.name for p in download_dir.iterdir())
+ assert remaining == ["OnlyStatement.pdf"], f"the single session download must be materialized, got {remaining}"
+
+
+async def test_finalize_local_only_skips_checksum_snapshot(tmp_path) -> None:
+ # Only s3://, gs:// session candidates consult the run-dir checksum snapshot. A local-only
+ # finalization has no such candidate, so finalize must not hash the run dir at all (SKY-14276).
+ agent = ForgeAgent()
+ task = _make_task() # browser_session_id = None -> no session-storage candidate
+ download_dir = tmp_path / "downloads"
+ download_dir.mkdir()
+
+ checksum_spy = MagicMock(return_value="deadbeef")
+ with (
+ patch("skyvern.forge.agent.get_path_for_workflow_download_directory", return_value=download_dir),
+ patch("skyvern.forge.agent.list_files_in_directory", return_value=["uuid-file.zip"]),
+ patch("skyvern.forge.agent.rename_file", MagicMock()),
+ patch("skyvern.forge.agent.calculate_sha256_for_file", checksum_spy),
+ patch("skyvern.forge.agent.skyvern_context.current", return_value=None),
+ ):
+ await agent._finalize_downloaded_files_for_task(
+ task,
+ organization_id=task.organization_id,
+ download_suffix="req-123",
+ list_files_before=[],
+ randomize_if_missing=False,
+ )
+
+ checksum_spy.assert_not_called()
+
+
+async def test_finalize_materializes_session_download_matching_baseline_before(tmp_path) -> None:
+ # A genuinely-new persistent-session download can happen to share bytes with a baseline file that
+ # was already in the run dir before this task (an earlier task's download or a staged input). That
+ # baseline sits in list_files_before, so it is NOT this task's eager carve-out duplicate. Finalization
+ # must still materialize the new session object (and apply its distinct download_suffix), not skip it
+ # by hashing the whole run dir against the baseline (SKY-14276).
+ agent = ForgeAgent()
+ task = _make_task(workflow_run_id="wr-baseline-collision")
+ task.browser_session_id = "pbs-3"
+
+ download_dir = tmp_path / "downloads"
+ download_dir.mkdir()
+ shared_bytes = b"SHARED-BYTES-BASELINE-AND-SESSION"
+ baseline_path = download_dir / "baseline-from-earlier-task.pdf"
+ baseline_path.write_bytes(shared_bytes)
+
+ session_uri = "s3://bucket/browser_sessions/pbs-3/downloads/NewStatement.pdf"
+ aws_client = MagicMock()
+ aws_client.download_file = AsyncMock(return_value=shared_bytes)
+
+ with (
+ patch("skyvern.forge.agent.get_path_for_workflow_download_directory", return_value=download_dir),
+ patch("skyvern.forge.agent.skyvern_context.current", return_value=None),
+ patch("skyvern.forge.agent.get_aws_client", return_value=aws_client),
+ patch("skyvern.forge.agent.app") as mock_app,
+ ):
+ mock_app.STORAGE.list_downloaded_files_in_browser_session = AsyncMock(return_value=[session_uri])
+ await agent._finalize_downloaded_files_for_task(
+ task,
+ organization_id=task.organization_id,
+ download_suffix="req-999",
+ list_files_before=[str(baseline_path)],
+ randomize_if_missing=False,
+ )
+
+ remaining = sorted(p.name for p in download_dir.iterdir())
+ assert remaining == ["baseline-from-earlier-task.pdf", "req-999.pdf"], (
+ f"new session download must be materialized under its suffix, not deduped against the baseline, got {remaining}"
+ )
+ assert (download_dir / "req-999.pdf").read_bytes() == shared_bytes
diff --git a/tests/unit/test_agent_task_v3.py b/tests/unit/test_agent_task_v3.py
index 5d1cf19c5..1483349eb 100644
--- a/tests/unit/test_agent_task_v3.py
+++ b/tests/unit/test_agent_task_v3.py
@@ -28,6 +28,7 @@ from skyvern.forge.sdk.core.skyvern_context import SkyvernContext
from skyvern.forge.sdk.db.enums import TaskType
from skyvern.forge.sdk.db.utils import hydrate_action
from skyvern.forge.sdk.experimentation.providers import BaseExperimentationProvider
+from skyvern.forge.sdk.experimentation.workflow_block_engine import DISABLE_TASK_V3_FLAG
from skyvern.forge.sdk.models import Step, StepStatus
from skyvern.forge.sdk.schemas.tasks import TaskStatus
from skyvern.forge.sdk.workflow.models.block import (
@@ -1059,6 +1060,45 @@ async def test_execute_step_bare_task_with_verification_url_dispatches_to_v3() -
step_engine_mock.assert_not_awaited()
+async def test_explicit_v3_block_consumes_enabled_dispatch_seam_without_legacy_fallback() -> None:
+ provider = MagicMock(spec=BaseExperimentationProvider)
+ provider.is_feature_enabled_cached = AsyncMock(return_value=False)
+ block = _make_block(TaskBlock, label="pure_task", engine=agent_module.RunEngine.skyvern_v3)
+
+ v3_mock, step_engine_mock = await _run_execute_step_gate(
+ engine=agent_module.RunEngine.skyvern_v3,
+ task_block=block,
+ experimentation_provider=provider,
+ workflow_run_id="wr_task_v3_pure",
+ )
+
+ v3_mock.assert_awaited_once()
+ step_engine_mock.assert_not_awaited()
+ disable_call = provider.is_feature_enabled_cached.await_args
+ assert disable_call.args == (DISABLE_TASK_V3_FLAG, "wr_task_v3_pure")
+ assert disable_call.kwargs["properties"] == {
+ "organization_id": make_organization(datetime.now(UTC)).organization_id
+ }
+
+
+async def test_disabled_v3_dispatch_is_not_credited_as_pure() -> None:
+ provider = MagicMock(spec=BaseExperimentationProvider)
+ provider.is_feature_enabled_cached = AsyncMock(return_value=True)
+ block = _make_block(TaskBlock, label="disabled_pure_task", engine=agent_module.RunEngine.skyvern_v3)
+
+ v3_mock, step_engine_mock = await _run_execute_step_gate(
+ engine=agent_module.RunEngine.skyvern_v3,
+ task_block=block,
+ experimentation_provider=provider,
+ workflow_run_id="wr_task_v3_disabled",
+ )
+
+ v3_mock.assert_not_awaited()
+ step_engine_mock.assert_awaited_once()
+
+
# ---------------------------------------------------------------------------
# P2b: complete_on_download wiring -- the completion_probe/completion_blocker
# handed to run_task_v3_agent_loop, backed by the same finalize-and-rename path
diff --git a/tests/unit/test_browser_effect_sink_enumeration.py b/tests/unit/test_browser_effect_sink_enumeration.py
index 72a8b178c..c1f43f67b 100644
--- a/tests/unit/test_browser_effect_sink_enumeration.py
+++ b/tests/unit/test_browser_effect_sink_enumeration.py
@@ -53,7 +53,7 @@ _DISCOVERED_BROWSER_API_CALLS = {
"check": 2,
"click": 3,
"dblclick": 1,
- "evaluate": 2,
+ "evaluate": 3,
"fill": 1,
"focus": 2,
"goto": 2,
@@ -101,7 +101,10 @@ _EVALUATE_CALLERS = {
}
),
"skyvern/webeye/real_browser_state.py": Counter({"stop_page_loading": 1}),
- "skyvern/webeye/utils/dom.py": Counter({"apply_secret_visual_mask": 1, "blur": 1}),
+ # read-only hit-test geometry check gating the custom-select intercept JS fallback
+ "skyvern/webeye/utils/dom.py": Counter(
+ {"apply_secret_visual_mask": 1, "blur": 1, "_pointer_interceptor_matches_label": 1}
+ ),
}
@@ -210,21 +213,21 @@ def test_discovered_browser_api_lower_bound_is_stable() -> None:
}
assert observed == _DISCOVERED_BROWSER_API_CALLS
- assert sum(sum(methods.values()) for methods in observed.values()) == 155
+ assert sum(sum(methods.values()) for methods in observed.values()) == 156
handler_candidates = _candidate_signatures("skyvern/webeye/actions/handler.py", _CANDIDATE_METHODS)
classified_non_browser = Counter(
{signature: count for signature, count in handler_candidates.items() if signature in _NON_BROWSER_CANDIDATES}
)
assert classified_non_browser == _NON_BROWSER_CANDIDATES
assert sum(_NON_BROWSER_CANDIDATES.values()) == 5
- assert sum(sum(methods.values()) for methods in observed.values()) - sum(_NON_BROWSER_CANDIDATES.values()) == 150
+ assert sum(sum(methods.values()) for methods in observed.values()) - sum(_NON_BROWSER_CANDIDATES.values()) == 151
def test_every_raw_evaluate_call_is_classified() -> None:
observed = {path: callers for path in _owned_source_paths() if (callers := _callers_for_method(path, "evaluate"))}
assert observed == _EVALUATE_CALLERS
- assert sum(sum(callers.values()) for callers in observed.values()) == 24
+ assert sum(sum(callers.values()) for callers in observed.values()) == 25
def test_every_cdp_dispatch_is_classified_by_exact_command() -> None:
diff --git a/tests/unit/test_browser_header_sanitization.py b/tests/unit/test_browser_header_sanitization.py
index 7c880d620..90166c3cd 100644
--- a/tests/unit/test_browser_header_sanitization.py
+++ b/tests/unit/test_browser_header_sanitization.py
@@ -68,6 +68,7 @@ class _FakeAgentFunction:
self.route_handlers_allowed = route_handlers_allowed
self.route_permission_checks = 0
self.extension_setup_calls = 0
+ self.header_route_origins: list[Any] = []
def strip_proxy_session_extra_http_headers(
self,
@@ -85,6 +86,9 @@ class _FakeAgentFunction:
async def setup_browser_context_extensions(self, **kwargs: Any) -> None:
self.extension_setup_calls += 1
+ def on_origin_scoped_headers_route_installed(self, browser_context: Any, target_origin: Any) -> None:
+ self.header_route_origins.append(target_origin)
+
async def _factory_context(
monkeypatch: pytest.MonkeyPatch,
diff --git a/tests/unit/test_code_block_downloads.py b/tests/unit/test_code_block_downloads.py
index 170ea0046..aabc5b567 100644
--- a/tests/unit/test_code_block_downloads.py
+++ b/tests/unit/test_code_block_downloads.py
@@ -11,6 +11,7 @@ Covers the three acceptance behaviors:
import asyncio
import hashlib
+import json
import os
from collections.abc import Callable
from contextlib import asynccontextmanager
@@ -21,6 +22,7 @@ from unittest.mock import AsyncMock
import pytest
from structlog.testing import capture_logs
+from skyvern.constants import BROWSER_DOWNLOADING_SUFFIX
from skyvern.exceptions import (
DownloadFileMaxWaitingTime,
DownloadSaveIncompleteError,
@@ -28,6 +30,9 @@ from skyvern.exceptions import (
ScriptTerminationException,
)
from skyvern.forge.agent_functions import AgentFunction
+from skyvern.forge.sdk.api.files import classify_download_visibility, observe_download_dir
+from skyvern.forge.sdk.artifact.storage import s3 as s3_module
+from skyvern.forge.sdk.artifact.storage.s3 import S3Storage
from skyvern.forge.sdk.browser_network_egress_monitor import BrowserNetworkEgressMonitor
from skyvern.forge.sdk.copilot.reached_download_target import (
block_output_has_registered_download,
@@ -2427,3 +2432,342 @@ async def test_failing_session_block_that_never_downloaded_invents_no_evidence(
claim.assert_awaited()
output = result.output_parameter_value
assert output is None or not output.get("downloaded_file_urls")
+
+
+_DOWNLOAD_ENTRY_SENTINEL = "quarterly-policy-summary-sentinel.pdf"
+
+
+def _keyed_fingerprints(monkeypatch: pytest.MonkeyPatch) -> None:
+ monkeypatch.setattr("skyvern.forge.sdk.core.hashing.settings.SECRET_KEY", "download-observation-fingerprint-key")
+
+
+def test_observe_download_dir_separates_landed_bytes_from_in_flight(tmp_path, monkeypatch: pytest.MonkeyPatch) -> None:
+ _keyed_fingerprints(monkeypatch)
+ (tmp_path / _DOWNLOAD_ENTRY_SENTINEL).write_bytes(b"%PDF-1.4 sentinel")
+ (tmp_path / f"partial-{_DOWNLOAD_ENTRY_SENTINEL}{BROWSER_DOWNLOADING_SUFFIX}").write_bytes(b"%PDF")
+
+ observation = observe_download_dir(tmp_path)
+
+ assert observation.entry_count == 2
+ assert observation.total_bytes == 21
+ assert observation.in_flight_count == 1
+ assert observation.dir_missing is False
+ assert observation.read_failed is False
+ assert observation.entry_fps_truncated is False
+ assert len(set(observation.entry_fps)) == 2
+ assert "unkeyed" not in observation.entry_fps
+ rendered = repr(observation)
+ assert _DOWNLOAD_ENTRY_SENTINEL not in rendered
+ assert "policy-summary" not in rendered
+ assert ".pdf" not in rendered
+
+
+def test_observe_download_dir_caps_and_flags_truncated_fingerprints(tmp_path, monkeypatch: pytest.MonkeyPatch) -> None:
+ _keyed_fingerprints(monkeypatch)
+ for index in range(11):
+ (tmp_path / f"{index}-{_DOWNLOAD_ENTRY_SENTINEL}").write_bytes(b"x")
+
+ observation = observe_download_dir(tmp_path)
+
+ assert observation.entry_count == 11
+ assert len(observation.entry_fps) == 10
+ assert observation.entry_fps_truncated is True
+ assert _DOWNLOAD_ENTRY_SENTINEL not in repr(observation)
+
+
+def test_observe_download_dir_survives_a_path_scandir_rejects(tmp_path) -> None:
+ """The helper promises never to raise; scandir rejects an embedded null with ValueError."""
+ observation = observe_download_dir(tmp_path / "bad\x00name")
+
+ assert observation.read_failed is True
+ assert observation.entry_count == 0
+
+
+def test_observe_download_dir_reports_missing_directory(tmp_path) -> None:
+ observation = observe_download_dir(tmp_path / "never-created")
+
+ assert observation.dir_missing is True
+ assert observation.read_failed is False
+ assert observation.entry_count == 0
+
+
[email protected](hasattr(os, "geteuid") and os.geteuid() == 0, reason="root ignores directory permissions")
+def test_observe_download_dir_reports_unreadable_directory_instead_of_zero(tmp_path) -> None:
+ blocked = tmp_path / "blocked"
+ blocked.mkdir()
+ (blocked / _DOWNLOAD_ENTRY_SENTINEL).write_bytes(b"x")
+ os.chmod(blocked, 0o000)
+ try:
+ observation = observe_download_dir(blocked)
+ finally:
+ os.chmod(blocked, 0o700)
+
+ assert observation.read_failed is True
+ assert observation.dir_missing is False
+ assert observation.entry_count == 0
+ assert _DOWNLOAD_ENTRY_SENTINEL not in repr(observation)
+
+
+def _empty_read_rows(logs: list[dict]) -> list[dict]:
+ return [entry for entry in logs if entry.get("event") == "downloads.empty_read"]
+
+
+def _artifact_row_storage(
+ monkeypatch: pytest.MonkeyPatch, *, keyring: str | None, file_infos: list[FileInfo]
+) -> S3Storage:
+ monkeypatch.setattr(s3_module.settings, "ARTIFACT_CONTENT_HMAC_KEYRING", keyring)
+ monkeypatch.setattr(s3_module, "_file_infos_from_download_artifacts", AsyncMock(return_value=file_infos))
+ return S3Storage()
+
+
+async def test_downloads_read_stays_silent_when_artifact_rows_resolve(monkeypatch: pytest.MonkeyPatch) -> None:
+ resolved = [FileInfo(url="https://example.test/a")]
+ storage = _artifact_row_storage(monkeypatch, keyring="k1:secret", file_infos=resolved)
+ monkeypatch.setattr(storage, "_list_download_artifacts_safe", AsyncMock(return_value=([SimpleNamespace()], False)))
+
+ with capture_logs() as logs:
+ assert await storage.get_downloaded_files("o_1", "wr_1") == resolved
+
+ assert _empty_read_rows(logs) == []
+
+
+async def test_downloads_empty_read_reports_unresolvable_rows(monkeypatch: pytest.MonkeyPatch) -> None:
+ storage = _artifact_row_storage(monkeypatch, keyring="k1:secret", file_infos=[])
+ monkeypatch.setattr(storage, "_list_download_artifacts_safe", AsyncMock(return_value=([SimpleNamespace()], False)))
+
+ with capture_logs() as logs:
+ assert await storage.get_downloaded_files("o_1", "wr_1") == []
+
+ row = _empty_read_rows(logs)[0]
+ assert row["download_row_count"] == 1
+ assert row["rows_present_but_unresolvable"] is True
+ assert row["rows_lookup_failed"] is False
+ assert row["skip_fired"] is False
+ assert row["listed"] is False
+
+
+async def test_downloads_empty_read_reports_listing_skip(monkeypatch: pytest.MonkeyPatch) -> None:
+ storage = _artifact_row_storage(monkeypatch, keyring="k1:secret", file_infos=[])
+ monkeypatch.setattr(storage, "_list_download_artifacts_safe", AsyncMock(return_value=([], False)))
+ monkeypatch.setattr(storage, "_skip_empty_downloads_listing", AsyncMock(return_value=True))
+ listing = AsyncMock(return_value=[])
+ monkeypatch.setattr(storage, "_get_downloaded_files_via_s3_listing", listing)
+
+ with capture_logs() as logs:
+ assert await storage.get_downloaded_files("o_1", "wr_1") == []
+
+ row = _empty_read_rows(logs)[0]
+ assert row["download_row_count"] == 0
+ assert row["skip_fired"] is True
+ assert row["listed"] is False
+ listing.assert_not_awaited()
+
+
+async def test_downloads_empty_read_reports_failed_row_lookup_as_unknown_count(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ storage = _artifact_row_storage(monkeypatch, keyring="k1:secret", file_infos=[])
+ monkeypatch.setattr(
+ s3_module.app.DATABASE.artifacts,
+ "list_artifacts_for_run_by_type",
+ AsyncMock(side_effect=RuntimeError("database unavailable")),
+ )
+ monkeypatch.setattr(storage, "_skip_empty_downloads_listing", AsyncMock(return_value=False))
+ monkeypatch.setattr(storage, "_get_downloaded_files_via_s3_listing", AsyncMock(return_value=[]))
+
+ with capture_logs() as logs:
+ assert await storage.get_downloaded_files("o_1", "wr_1") == []
+
+ row = _empty_read_rows(logs)[0]
+ assert row["download_row_count"] is None
+ assert row["rows_lookup_failed"] is True
+ assert row["listed"] is True
+
+
+async def test_downloads_empty_read_reports_unqueried_rows_on_legacy_path(monkeypatch: pytest.MonkeyPatch) -> None:
+ storage = _artifact_row_storage(monkeypatch, keyring="", file_infos=[])
+ monkeypatch.setattr(storage, "_get_downloaded_files_via_s3_listing", AsyncMock(return_value=[]))
+
+ with capture_logs() as logs:
+ assert await storage.get_downloaded_files("o_1", "wr_1") == []
+
+ row = _empty_read_rows(logs)[0]
+ assert row["download_row_count"] is None
+ assert row["rows_lookup_failed"] is False
+ assert row["listed"] is True
+
+
+def test_observe_download_dir_moves_on_same_name_same_size_overwrite(tmp_path, monkeypatch: pytest.MonkeyPatch) -> None:
+ _keyed_fingerprints(monkeypatch)
+ target = tmp_path / _DOWNLOAD_ENTRY_SENTINEL
+ target.write_bytes(b"%PDF-1.4 sentinel")
+ before = observe_download_dir(tmp_path)
+ rewritten_at = before.newest_mtime_ns + 1_000_000_000
+ target.write_bytes(b"%PDF-1.4 replaced")
+ os.utime(target, ns=(rewritten_at, rewritten_at))
+
+ after = observe_download_dir(tmp_path)
+
+ assert after.entry_count == before.entry_count
+ assert after.total_bytes == before.total_bytes
+ assert after.in_flight_count == before.in_flight_count
+ assert after.newest_mtime_ns > before.newest_mtime_ns
+ fields = classify_download_visibility(
+ pre=before,
+ settled=after,
+ post=after,
+ alt_pre=None,
+ alt_post=None,
+ listed_run_id="wr_1",
+ workflow_run_id="wr_1",
+ download_binding_kind=None,
+ )
+ assert fields["landed_during_settle"] is True
+
+
+def test_classify_reports_unknown_movement_when_a_snapshot_could_not_be_read(
+ tmp_path, monkeypatch: pytest.MonkeyPatch
+) -> None:
+ _keyed_fingerprints(monkeypatch)
+ listed = tmp_path / "listed"
+ listed.mkdir()
+ (listed / _DOWNLOAD_ENTRY_SENTINEL).write_bytes(b"%PDF-1.4 already here")
+ os.chmod(listed, 0o000)
+ try:
+ pre = observe_download_dir(listed)
+ finally:
+ os.chmod(listed, 0o700)
+ readable = observe_download_dir(listed)
+
+ assert pre.read_failed is True
+ assert readable.total_bytes > 0
+
+ fields = classify_download_visibility(
+ pre=pre,
+ settled=readable,
+ post=readable,
+ alt_pre=None,
+ alt_post=None,
+ listed_run_id="wr_1",
+ workflow_run_id="wr_1",
+ download_binding_kind=None,
+ )
+
+ assert fields["landed_during_settle"] is None
+ assert fields["landed_after_settle"] is False
+
+
+def test_classify_reports_unknown_alt_deltas_when_the_alternate_scan_failed(
+ tmp_path, monkeypatch: pytest.MonkeyPatch
+) -> None:
+ _keyed_fingerprints(monkeypatch)
+ listed = tmp_path / "listed"
+ listed.mkdir()
+ alt = tmp_path / "alt"
+ alt.mkdir()
+ (alt / _DOWNLOAD_ENTRY_SENTINEL).write_bytes(b"%PDF-1.4 sentinel")
+ os.chmod(alt, 0o000)
+ try:
+ alt_pre = observe_download_dir(alt)
+ finally:
+ os.chmod(alt, 0o700)
+ alt_post = observe_download_dir(alt)
+ listed_observation = observe_download_dir(listed)
+
+ assert alt_pre.read_failed is True
+ assert alt_post.entry_count == 1
+
+ fields = classify_download_visibility(
+ pre=listed_observation,
+ settled=listed_observation,
+ post=listed_observation,
+ alt_pre=alt_pre,
+ alt_post=alt_post,
+ listed_run_id="wr_dl_1",
+ workflow_run_id="wr_1",
+ download_binding_kind=None,
+ )
+
+ assert fields["alt_entry_delta"] is None
+ assert fields["alt_bytes_delta"] is None
+ assert fields["alt_moved"] is None
+
+
+def test_classify_reads_alternate_dir_as_a_delta_not_an_absolute_count(
+ tmp_path, monkeypatch: pytest.MonkeyPatch
+) -> None:
+ _keyed_fingerprints(monkeypatch)
+ listed = tmp_path / "listed"
+ listed.mkdir()
+ alt = tmp_path / "alt"
+ alt.mkdir()
+ (alt / f"sibling-block-{_DOWNLOAD_ENTRY_SENTINEL}").write_bytes(b"left behind earlier")
+ listed_observation = observe_download_dir(listed)
+ alt_pre = observe_download_dir(alt)
+
+ def classify(alt_post):
+ return classify_download_visibility(
+ pre=listed_observation,
+ settled=listed_observation,
+ post=listed_observation,
+ alt_pre=alt_pre,
+ alt_post=alt_post,
+ listed_run_id="dr_1",
+ workflow_run_id="wr_1",
+ download_binding_kind=None,
+ )
+
+ stale_only = classify(observe_download_dir(alt))
+ assert stale_only["alt_entry_delta"] == 0
+ assert stale_only["alt_moved"] is False
+ assert stale_only["download_run_id_differs"] is True
+
+ (alt / _DOWNLOAD_ENTRY_SENTINEL).write_bytes(b"%PDF-1.4 sentinel")
+ moved = classify(observe_download_dir(alt))
+
+ assert moved["alt_entry_delta"] == 1
+ assert moved["alt_moved"] is True
+ assert moved["landed_during_settle"] is False
+ assert _DOWNLOAD_ENTRY_SENTINEL not in json.dumps(moved)
+ assert "sibling-block" not in json.dumps(moved)
+
+
+async def test_failed_row_lookup_still_lists_instead_of_reporting_no_downloads(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ """A DB blip must not be answered with an empty download list.
+
+ The cutover skip exists to avoid listing when a run provably has no rows; a lookup that
+ failed proves nothing, so the legitimate case has to keep its route through the listing.
+ """
+ listed = [FileInfo(url="https://example.test/real")]
+ storage = _artifact_row_storage(monkeypatch, keyring="k1:secret", file_infos=[])
+ monkeypatch.setattr(storage, "_list_download_artifacts_safe", AsyncMock(return_value=([], True)))
+ skip = AsyncMock(return_value=True)
+ monkeypatch.setattr(storage, "_skip_empty_downloads_listing", skip)
+ monkeypatch.setattr(storage, "_get_downloaded_files_via_s3_listing", AsyncMock(return_value=listed))
+
+ assert await storage.get_downloaded_files("o_1", "wr_blip") == listed
+ skip.assert_not_awaited()
+
+
+async def test_downloads_empty_read_reports_every_empty_read_for_a_run(monkeypatch: pytest.MonkeyPatch) -> None:
+ """A run reads empty once at block baseline and again after registration; both must be reported.
+
+ Suppressing the repeat would silence the post-registration read this signal exists to explain.
+ """
+ storage = _artifact_row_storage(monkeypatch, keyring="", file_infos=[])
+ monkeypatch.setattr(storage, "_get_downloaded_files_via_s3_listing", AsyncMock(return_value=[]))
+
+ with capture_logs() as repeated:
+ await storage.get_downloaded_files("o_1", "wr_repeat")
+ await storage.get_downloaded_files("o_1", "wr_repeat")
+
+ assert len(_empty_read_rows(repeated)) == 2
diff --git a/tests/unit/test_collapse_fanout_gates.py b/tests/unit/test_collapse_fanout_gates.py
index 4735e4a8d..bb3a0b203 100644
--- a/tests/unit/test_collapse_fanout_gates.py
+++ b/tests/unit/test_collapse_fanout_gates.py
@@ -2,7 +2,7 @@ import asyncio
import inspect
from types import SimpleNamespace
from typing import Any
-from unittest.mock import MagicMock, Mock
+from unittest.mock import AsyncMock, MagicMock, Mock
import posthog
import pytest
@@ -610,3 +610,43 @@ async def test_agent_mode_flag_off_keeps_custom_select_llm_path(monkeypatch: pyt
assert outcome["script_mode"] is False
assert outcome["family_gate_enabled"] is False
assert outcome["outcome"] == "llm_fallback_family_off"
+
+
+async def test_deterministic_seam_does_not_request_intercept_js_fallback(monkeypatch: pytest.MonkeyPatch) -> None:
+ """The deterministic seam keeps the physical fallback chain: its option click must not request the
+ early synthetic JS fallback, whose readback here is not strict enough to prevent a false success."""
+ provider = FakeExperimentationProvider({CUSTOM_FLAG: True, UMBRELLA_FLAG: True})
+ _set_provider(monkeypatch, provider)
+ monkeypatch.setattr(handler.app, "AGENT_FUNCTION", AgentFunction())
+ monkeypatch.setattr(handler, "_read_custom_select_matched_state", AsyncMock(return_value=None))
+ monkeypatch.setattr(handler, "_resolve_custom_select_readback_scope_element", AsyncMock(return_value=None))
+ monkeypatch.setattr(handler, "_anchor_is_combobox_input", AsyncMock(return_value=False))
+ monkeypatch.setattr(handler, "_custom_select_scope_confirms_committed", AsyncMock(return_value=(False, "none")))
+ monkeypatch.setattr(
+ handler, "_verify_custom_select_option_with_settle", AsyncMock(return_value=(True, "matched_state"))
+ )
+
+ element = MagicMock()
+ element.get_attr = AsyncMock(return_value="option")
+ element.scroll_into_view = AsyncMock(return_value=None)
+ element.click = AsyncMock(return_value=None)
+
+ async def _get_element(element_id: str) -> Any:
+ return element
+
+ result = await handler._select_deterministic_custom_option(
+ target_value="Blocked",
+ get_option_candidates=lambda: [
+ {"label": "Blocked", "value": "Blocked", "element_id": "opt1", "is_choice_input": False}
+ ],
+ field_context={"field": "Status"},
+ page=MagicMock(),
+ get_skyvern_element=_get_element,
+ task=_task(),
+ execute=True,
+ )
+
+ element.click.assert_awaited_once()
+ assert element.click.await_args.kwargs.get("intercept_js_fallback_label") is None
+ assert result is not None and isinstance(result[0], handler.ActionSuccess)
diff --git a/tests/unit/test_copilot_account_choices.py b/tests/unit/test_copilot_account_choices.py
index 2af1e4ea7..06315260a 100644
--- a/tests/unit/test_copilot_account_choices.py
+++ b/tests/unit/test_copilot_account_choices.py
@@ -14,6 +14,19 @@ from skyvern.forge.sdk.copilot.context import (
adopt_model_authored_context,
record_approved_credentials_in_global_llm_context,
)
+from skyvern.forge.sdk.copilot.run_outcome import RecordedRunOutcome
+from skyvern.forge.sdk.copilot.terminal_envelope import (
+ TerminalOutcomeEnvelope,
+ assemble_terminal_envelope,
+ render_terminal_message,
+)
+from skyvern.forge.sdk.copilot.tools.credentials import (
+ _approved_run_credential_ids,
+ _credential_run_approval_blocker_signal,
+ _credential_run_approval_error,
+ _extract_credential_ids_for_labels,
+ _parsed_workflow_definition,
+)
from skyvern.forge.sdk.copilot.turn_outcome import (
connected_account_choice_context,
selected_connected_account_id,
@@ -454,3 +467,206 @@ async def test_model_authored_context_cannot_forge_a_connection_approval(
adopted = adopt_model_authored_context("", forged.model_dump(mode="json"))
assert adopted.approved_connections == []
+
+
+EDITOR_BOUND_ACCOUNT_ID = "goac_editor_bound"
+NAMED_PICK_ACCOUNT_ID = "goac_named_pick"
+STALE_ACCOUNT_ID = "goac_stale"
+EMPTY_WORKFLOW_YAML = "workflow_definition:\n blocks: []\n"
+SHEETS_BLOCK_LABEL = "write"
+
+
+def _sheets_workflow_yaml(connection_id: str) -> str:
+ return (
+ "workflow_definition:\n"
+ " blocks:\n"
+ f" - label: {SHEETS_BLOCK_LABEL}\n"
+ " block_type: google_sheets_write\n"
+ f" credential_id: {connection_id}\n"
+ )
+
+
+def _dispatch_credential_ids(workflow_yaml: str) -> list[str]:
+ return _extract_credential_ids_for_labels(_parsed_workflow_definition(workflow_yaml), [SHEETS_BLOCK_LABEL])
+
+
+def _terminal_envelope(run_outcomes: list[RecordedRunOutcome]) -> TerminalOutcomeEnvelope:
+ envelope = assemble_terminal_envelope(
+ response_type="REPLY",
+ verified=True,
+ workflow_applied=False,
+ proposal_disposition="no_proposal",
+ run_outcomes=run_outcomes,
+ blocker_reason=None,
+ halt_kind=None,
+ attempted=None,
+ workflow_mutated=True,
+ workflow_attempted=True,
+ )
+ assert envelope is not None
+ return envelope
+
+
+async def test_editor_bound_account_keeps_run_authority_from_resolution_through_the_dispatch_gate(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ monkeypatch.setattr(
+ request_policy_module.google_oauth_service,
+ "get_credentials_for_org",
+ AsyncMock(return_value=[_google(EDITOR_BOUND_ACCOUNT_ID, "Google Sheets")]),
+ )
+ saved_yaml = _sheets_workflow_yaml(EDITOR_BOUND_ACCOUNT_ID)
+
+ resolved = await request_policy_module._build_request_policy_bootstrap(
+ user_message="run the workflow",
+ workflow_yaml=saved_yaml,
+ chat_history=[],
+ global_llm_context="",
+ organization_id="org-1",
+ persisted_workflow_yaml=saved_yaml,
+ selected_connected_account_id=None,
+ )
+
+ assert resolved.run_approved_google_connection_ids == [EDITOR_BOUND_ACCOUNT_ID]
+
+ next_turn = await request_policy_module._build_request_policy_bootstrap(
+ user_message="add a step that emails me when it finishes",
+ workflow_yaml=EMPTY_WORKFLOW_YAML,
+ chat_history=[],
+ global_llm_context="",
+ organization_id="org-1",
+ persisted_workflow_yaml=saved_yaml,
+ )
+
+ dispatched_ids = _dispatch_credential_ids(saved_yaml)
+
+ assert dispatched_ids == [EDITOR_BOUND_ACCOUNT_ID]
+ assert next_turn.run_approved_google_connection_ids == [EDITOR_BOUND_ACCOUNT_ID]
+ assert EDITOR_BOUND_ACCOUNT_ID in _approved_run_credential_ids(next_turn)
+ assert _credential_run_approval_error(dispatched_ids, next_turn) is None
+ assert _credential_run_approval_blocker_signal(dispatched_ids, next_turn) is None
+
+
+async def test_named_account_with_no_server_owned_choice_selects_nothing_and_stays_blocked(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ lookup = AsyncMock(return_value=[_google(NAMED_PICK_ACCOUNT_ID, "Sheets Writer", email_address="[email protected]")])
+ monkeypatch.setattr(request_policy_module.google_oauth_service, "get_credentials_for_org", lookup)
+ named_message = "use my Sheets Writer google account"
+
+ policy = await request_policy_module._build_request_policy_bootstrap(
+ user_message=named_message,
+ workflow_yaml=EMPTY_WORKFLOW_YAML,
+ chat_history=[],
+ global_llm_context="",
+ organization_id="org-1",
+ persisted_workflow_yaml=None,
+ selected_connected_account_id=None,
+ )
+
+ assert policy.selected_connected_account_id is None
+ assert policy.run_approved_google_connection_ids == []
+ lookup.assert_not_awaited()
+ assert _approved_run_credential_ids(policy) == set()
+ assert _credential_run_approval_error([NAMED_PICK_ACCOUNT_ID], policy) is not None
+
+ offered = TurnOutcome(
+ response_kind=ResponseKind.CLARIFY,
+ connected_account_choices=[
+ ConnectedAccountChoice(connection_id=NAMED_PICK_ACCOUNT_ID, name="Sheets Writer", state="active")
+ ],
+ )
+
+ assert selected_connected_account_id(offered, named_message) is None
+ assert f'"connection_id":"{NAMED_PICK_ACCOUNT_ID}"' in connected_account_choice_context(offered, named_message)
+
+
+async def test_named_account_pick_keeps_run_authority_from_resolution_through_the_dispatch_gate(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ monkeypatch.setattr(
+ request_policy_module.google_oauth_service,
+ "get_credentials_for_org",
+ AsyncMock(return_value=[_google(NAMED_PICK_ACCOUNT_ID, "Sheets Writer", email_address="[email protected]")]),
+ )
+ draft = _sheets_workflow_yaml(NAMED_PICK_ACCOUNT_ID)
+
+ picked = await request_policy_module._build_request_policy_bootstrap(
+ user_message=NAMED_PICK_ACCOUNT_ID,
+ workflow_yaml=draft,
+ chat_history=[],
+ global_llm_context="",
+ organization_id="org-1",
+ selected_connected_account_id=NAMED_PICK_ACCOUNT_ID,
+ )
+
+ assert picked.run_approved_google_connection_ids == [NAMED_PICK_ACCOUNT_ID]
+
+ carried = record_approved_credentials_in_global_llm_context(
+ make_copilot_ctx(workflow_yaml=draft, request_policy=picked),
+ "",
+ )
+ assert carried is not None
+
+ next_turn = await request_policy_module._build_request_policy_bootstrap(
+ user_message="run it now",
+ workflow_yaml=draft,
+ chat_history=[],
+ global_llm_context=carried,
+ organization_id="org-1",
+ persisted_workflow_yaml=None,
+ )
+
+ dispatched_ids = _dispatch_credential_ids(draft)
+
+ assert dispatched_ids == [NAMED_PICK_ACCOUNT_ID]
+ assert next_turn.run_approved_google_connection_ids == [NAMED_PICK_ACCOUNT_ID]
+ assert NAMED_PICK_ACCOUNT_ID in _approved_run_credential_ids(next_turn)
+ assert _credential_run_approval_error(dispatched_ids, next_turn) is None
+ assert _credential_run_approval_blocker_signal(dispatched_ids, next_turn) is None
+
+
+async def test_editor_bound_account_that_is_no_longer_active_is_refused_at_the_dispatch_gate(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ monkeypatch.setattr(
+ request_policy_module.google_oauth_service,
+ "get_credentials_for_org",
+ AsyncMock(return_value=[_google("goac_other_active", "Another account")]),
+ )
+ saved_yaml = _sheets_workflow_yaml(STALE_ACCOUNT_ID)
+
+ policy = await request_policy_module._build_request_policy_bootstrap(
+ user_message="run the workflow",
+ workflow_yaml=saved_yaml,
+ chat_history=[],
+ global_llm_context="",
+ organization_id="org-1",
+ persisted_workflow_yaml=saved_yaml,
+ )
+
+ dispatched_ids = _dispatch_credential_ids(saved_yaml)
+
+ assert dispatched_ids == [STALE_ACCOUNT_ID]
+ assert policy.persisted_workflow_credential_ids == [STALE_ACCOUNT_ID]
+ assert policy.run_approved_google_connection_ids == []
+ assert STALE_ACCOUNT_ID not in _approved_run_credential_ids(policy)
+ assert _credential_run_approval_error(dispatched_ids, policy) is not None
+
+ blocker = _credential_run_approval_blocker_signal(dispatched_ids, policy)
+
+ assert blocker is not None
+ assert blocker.blocker_kind == "authority_denied"
+ assert blocker.internal_reason_code == "unapproved_google_connection_reference"
+
+
+def test_terminal_without_a_run_receipt_reports_no_run() -> None:
+ envelope = _terminal_envelope([])
+ message, replaced = render_terminal_message(envelope, "ok", False)
+
+ assert replaced
+ assert "I ran the workflow" not in message
diff --git a/tests/unit/test_copilot_banned_block_policy.py b/tests/unit/test_copilot_banned_block_policy.py
index ce03b42eb..68f180201 100644
--- a/tests/unit/test_copilot_banned_block_policy.py
+++ b/tests/unit/test_copilot_banned_block_policy.py
@@ -39,11 +39,15 @@ from skyvern.forge.sdk.copilot.tools import (
)
from skyvern.forge.sdk.copilot.tools.banned_blocks import (
_COPILOT_CODE_ONLY_BROWSER_BANNED_BLOCK_TYPES,
+ _TASK_V3_PURE_BANNED_BLOCK_TYPES,
+ _TASK_V3_PURE_TASK_BLOCK_TYPES,
CopilotBlockPolicyStatus,
_code_only_browser_authoring_prompt,
_code_only_browser_schema_guidance,
+ _task_v3_pure_policy_violations,
)
from skyvern.forge.sdk.copilot.tools.mcp_hooks import _validate_block_pre_hook
+from skyvern.forge.sdk.workflow.models.block import _TASK_V3_SUPPORTED_BLOCK_TYPES
from skyvern.schemas.runs import ProxyLocation
_CODE_ONLY_UNAVAILABLE = tuple(
@@ -87,6 +91,12 @@ def _code_only_ctx(prior_yaml: str | None = None) -> MagicMock:
return ctx
+def _task_v3_pure_ctx(prior_yaml: str | None = None) -> MagicMock:
+ ctx = _ctx(prior_yaml=prior_yaml)
+ ctx.block_authoring_policy = BlockAuthoringPolicy.TASK_V3_PURE
+ return ctx
+
+
@pytest.fixture
def ctx() -> MagicMock:
return _ctx()
@@ -190,6 +200,10 @@ def test_code_only_policy_table_derives_unavailable_types() -> None:
assert "native_allowed" not in {status.value for status in CopilotBlockPolicyStatus}
+def test_task_v3_pure_policy_table_derives_unavailable_types() -> None:
+ assert _TASK_V3_PURE_BANNED_BLOCK_TYPES == frozenset({"code", "task_v2"})
+
+
@pytest.mark.parametrize("block_type", _CODE_ONLY_UNAVAILABLE)
@pytest.mark.asyncio
async def test_code_only_schema_pre_hook_rejects_table_entries(block_type: str, code_only_ctx: MagicMock) -> None:
@@ -213,6 +227,287 @@ async def test_code_only_schema_pre_hook_normalizes_case_whitespace_and_alias(co
assert "focused `code` blocks" in result["error"]
+async def test_task_v3_pure_schema_exposes_real_task_and_catalog() -> None:
+ ctx = _task_v3_pure_ctx()
+
+ task_result = await _get_block_schema_pre_hook({"block_type": "task"}, ctx)
+ assert task_result is not None
+ assert task_result["ok"] is True
+ assert task_result["data"]["block_type"] == "task"
+ assert task_result["data"]["schema"]["properties"]["engine"]["const"] == "skyvern-3.0"
+ assert "default" not in task_result["data"]["schema"]["properties"]["engine"]
+ assert "engine" in task_result["data"]["schema"]["required"]
+
+ listed = await _get_block_schema_post_hook(
+ {"ok": True, "data": {"block_types": {"navigation": "Navigate", "code": "Code"}, "count": 2}},
+ raw={},
+ ctx=ctx,
+ )
+ assert set(_TASK_V3_PURE_TASK_BLOCK_TYPES).issubset(listed["data"]["block_types"])
+ assert "code" not in listed["data"]["block_types"]
+ assert "task_v2" not in listed["data"]["block_types"]
+
+ navigation = await _get_block_schema_post_hook(
+ {
+ "ok": True,
+ "data": {
+ "block_type": "navigation",
+ "schema": {"properties": {"engine": {"$ref": "#/$defs/WorkflowBlockEngine"}}},
+ },
+ },
+ raw={},
+ ctx=ctx,
+ )
+ assert navigation["data"]["schema"]["properties"]["engine"] == {
+ "type": "string",
+ "const": "skyvern-3.0",
+ "description": "Required by the active Task-V3-pure authoring policy.",
+ }
+ assert "engine" in navigation["data"]["schema"]["required"]
+
+
[email protected]("block_type", sorted(_TASK_V3_PURE_TASK_BLOCK_TYPES))
+def test_task_v3_pure_accepts_all_supported_task_types_with_exact_engine(block_type: str) -> None:
+ block = {"block_type": block_type, "label": f"{block_type}_block", "engine": "skyvern-3.0"}
+
+ assert _task_v3_pure_policy_violations(_yaml(block)) == []
+
+
+def test_task_v3_pure_contract_matches_runtime_supported_type_set() -> None:
+ assert _TASK_V3_PURE_TASK_BLOCK_TYPES == frozenset(
+ block_type.value for block_type in _TASK_V3_SUPPORTED_BLOCK_TYPES
+ )
+
+
+def test_task_v3_pure_keeps_engine_less_workflow_vocabulary_available() -> None:
+ submitted = _yaml(
+ {"block_type": "goto_url", "label": "open", "url": "https://example.com"},
+ {"block_type": "wait", "label": "wait", "wait_sec": 1},
+ {"block_type": "http_request", "label": "request", "url": "https://example.com/api"},
+ {"block_type": "google_sheets_read", "label": "sheet", "spreadsheet_id": "sheet"},
+ {"block_type": "human_interaction", "label": "review", "recipients": ["[email protected]"]},
+ )
+
+ assert _task_v3_pure_policy_violations(submitted) == []
+
+
[email protected]("engine", [None, "skyvern-1.0", "skyvern-2.0", "openai-cua"])
+def test_task_v3_pure_rejects_omitted_or_non_v3_engines(engine: str | None) -> None:
+ block = {"block_type": "navigation", "label": "navigate", "navigation_goal": "Go"}
+ if engine is not None:
+ block["engine"] = engine
+
+ violations = _task_v3_pure_policy_violations(_yaml(block))
+
+ assert [violation.code for violation in violations] == ["engine_not_skyvern_v3"]
+
+
[email protected]("block_type", ["code", "task_v2"])
+def test_task_v3_pure_rejects_unavailable_executor_blocks(block_type: str) -> None:
+ violations = _task_v3_pure_policy_violations(_yaml({"block_type": block_type, "label": "unsafe"}))
+
+ assert [violation.code for violation in violations] == ["block_type_unavailable"]
+
+
+def test_task_v3_pure_rejects_nested_legacy_task_and_unsupported_validation() -> None:
+ submitted = _yaml(
+ {
+ "block_type": "for_loop",
+ "label": "loop",
+ "loop_over_parameter_key": "items",
+ "loop_blocks": [
+ {"block_type": "task", "label": "nested", "engine": "skyvern-1.0"},
+ {
+ "block_type": "validation",
+ "label": "download_validation",
+ "engine": "skyvern-3.0",
+ "complete_on_download": True,
+ },
+ ],
+ }
+ )
+
+ violations = _task_v3_pure_policy_violations(submitted)
+
+ assert [(violation.label, violation.code) for violation in violations] == [
+ ("nested", "engine_not_skyvern_v3"),
+ ("download_validation", "unsupported_v3_combination"),
+ ]
+
+
+async def test_task_v3_pure_update_requires_full_definition_migration() -> None:
+ legacy = _yaml({"block_type": "task", "label": "legacy", "engine": "skyvern-1.0"})
+ unrelated_edit = _yaml(
+ {"block_type": "task", "label": "legacy", "engine": "skyvern-1.0"},
+ {"block_type": "wait", "label": "new_wait", "wait_sec": 1},
+ )
+ ctx = _task_v3_pure_ctx(prior_yaml=legacy)
+
+ with patch("skyvern.forge.sdk.copilot.tools.workflow_update._process_workflow_yaml") as process:
+ result = await _update_workflow({"workflow_yaml": unrelated_edit}, ctx)
+
+ assert result["ok"] is False
+ assert result["block_id"] == "banned_blocks"
+ assert result["data"]["violations"] == [
+ {
+ "label": "legacy",
+ "block_type": "task",
+ "code": "engine_not_skyvern_v3",
+ "guidance": "Set the submitted block engine exactly to `skyvern-3.0`.",
+ }
+ ]
+ process.assert_not_called()
+
+
+def test_task_v3_pure_control_flow_allows_parameter_and_jinja_but_rejects_prompt_paths() -> None:
+ submitted = _yaml(
+ {
+ "block_type": "for_loop",
+ "label": "parameter_loop",
+ "loop_over_parameter_key": "items",
+ "loop_variable_reference": "{{items}}",
+ "loop_blocks": [{"block_type": "wait", "label": "wait", "wait_sec": 1}],
+ },
+ {
+ "block_type": "for_loop",
+ "label": "prompt_loop",
+ "loop_over_parameter_key": "items",
+ "loop_variable_reference": "the rows currently visible on the page",
+ "loop_blocks": [{"block_type": "wait", "label": "wait_again", "wait_sec": 1}],
+ },
+ {
+ "block_type": "while_loop",
+ "label": "jinja_loop",
+ "condition": {"criteria_type": "jinja2_template", "expression": "{{ has_more }}"},
+ "loop_blocks": [{"block_type": "wait", "label": "wait_more", "wait_sec": 1}],
+ },
+ {
+ "block_type": "conditional",
+ "label": "prompt_branch",
+ "branch_conditions": [
+ {
+ "criteria": {"criteria_type": "prompt", "expression": "Is the page complete?"},
+ "next_block_label": "wait",
+ }
+ ],
+ },
+ )
+
+ violations = _task_v3_pure_policy_violations(submitted)
+
+ assert [(violation.label, violation.code) for violation in violations] == [
+ ("prompt_loop", "synthetic_task_control_flow"),
+ ("prompt_branch", "synthetic_task_control_flow"),
+ ]
+
+
+def test_task_v3_pure_control_flow_honors_default_jinja_criteria_type() -> None:
+ submitted = _yaml(
+ {
+ "block_type": "while_loop",
+ "label": "default_jinja_loop",
+ "condition": {"expression": "{{ has_more }}"},
+ "loop_blocks": [{"block_type": "wait", "label": "wait", "wait_sec": 1}],
+ },
+ {
+ "block_type": "conditional",
+ "label": "default_jinja_branch",
+ "branch_conditions": [
+ {
+ "criteria": {"expression": "{{ should_continue }}"},
+ "next_block_label": "wait",
+ }
+ ],
+ },
+ )
+
+ assert _task_v3_pure_policy_violations(submitted) == []
+
+
+async def test_task_v3_pure_validate_block_uses_the_same_structural_contract() -> None:
+ ctx = _task_v3_pure_ctx()
+
+ rejected = await _validate_block_pre_hook(
+ {"block_json": json.dumps({"block_type": "navigation", "label": "navigate", "navigation_goal": "Go"})},
+ ctx,
+ )
+ accepted = await _validate_block_pre_hook(
+ {
+ "block_json": json.dumps(
+ {
+ "block_type": "navigation",
+ "label": "navigate",
+ "navigation_goal": "Go",
+ "engine": "skyvern-3.0",
+ }
+ )
+ },
+ ctx,
+ )
+
+ assert rejected is not None
+ assert rejected["data"]["violations"][0]["code"] == "engine_not_skyvern_v3"
+ assert accepted is None
+
+
+async def test_task_v3_pure_update_rejects_raw_omitted_engine_before_conversion() -> None:
+ submitted = _yaml({"block_type": "navigation", "label": "navigate", "navigation_goal": "Go"})
+ ctx = _task_v3_pure_ctx()
+
+ with patch("skyvern.forge.sdk.copilot.tools.workflow_update._process_workflow_yaml") as process:
+ result = await _update_workflow({"workflow_yaml": submitted}, ctx)
+
+ assert result["ok"] is False
+ assert result["block_id"] == "banned_blocks"
+ assert result["data"]["violations"][0]["code"] == "engine_not_skyvern_v3"
+ process.assert_not_called()
+
+
+async def test_task_v3_pure_update_preserves_submitted_v3_engine_bytes() -> None:
+ submitted = _yaml(
+ {"block_type": "navigation", "label": "navigate", "navigation_goal": "Go", "engine": "skyvern-3.0"}
+ )
+ ctx = _task_v3_pure_ctx()
+ fake_workflow = MagicMock()
+ for attr in (
+ "title",
+ "description",
+ "workflow_definition",
+ "proxy_location",
+ "webhook_callback_url",
+ "persist_browser_session",
+ "model",
+ "max_screenshot_scrolls",
+ "extra_http_headers",
+ "run_with",
+ "ai_fallback",
+ "cache_key",
+ "run_sequentially",
+ "sequential_key",
+ ):
+ setattr(fake_workflow, attr, None)
+
+ with (
+ patch(
+ "skyvern.forge.sdk.copilot.tools.workflow_update._process_workflow_yaml",
+ return_value=fake_workflow,
+ ) as process,
+ patch("skyvern.forge.sdk.copilot.tools.workflow_update.app") as mock_app,
+ ):
+ mock_app.WORKFLOW_SERVICE.get_workflow = AsyncMock(return_value=None)
+ mock_app.WORKFLOW_SERVICE.update_workflow_definition = AsyncMock()
+ result = await _update_workflow({"workflow_yaml": submitted}, ctx)
+
+ assert result["ok"] is True
+ assert process.await_args.kwargs["workflow_yaml"] == submitted
+ assert ctx.workflow_yaml == submitted
+
+
@pytest.mark.asyncio
async def test_code_only_post_hook_scrubs_all_policy_table_entries(code_only_ctx: MagicMock) -> None:
result = {
diff --git a/tests/unit/test_copilot_code_block_persist_seam.py b/tests/unit/test_copilot_code_block_persist_seam.py
index 4653f28ac..5052e2973 100644
--- a/tests/unit/test_copilot_code_block_persist_seam.py
+++ b/tests/unit/test_copilot_code_block_persist_seam.py
@@ -57,14 +57,16 @@ def _ctx(workflow_yaml: str = "") -> CopilotContext:
return ctx
-def _code_yaml(code: str, *, label: str = "submit_search") -> str:
+def _code_yaml(code: str, *, label: str = "submit_search", prompt: str | None = None) -> str:
indented = "\n".join(f" {line}" for line in textwrap.dedent(code).strip().splitlines())
+ prompt_line = f" prompt: {json.dumps(prompt, ensure_ascii=False)}\n" if prompt is not None else ""
return (
"title: Search\n"
"workflow_definition:\n"
" blocks:\n"
" - block_type: code\n"
f" label: {label}\n"
+ f"{prompt_line}"
" code: |\n"
f"{indented}\n"
)
@@ -189,6 +191,55 @@ async def test_accept_path_persists_model_yaml_and_code_exactly(monkeypatch: pyt
assert "imposed_substitutions" not in result["data"]
+async def test_accept_path_preserves_model_authored_goal_prompt_bytes(monkeypatch: pytest.MonkeyPatch) -> None:
+ persisted: list[str] = []
+ _stub_successful_update(monkeypatch, persisted)
+ authored_prompt = 'Open the result, then return its visible "Status" — unchanged.'
+ submitted = _code_yaml(
+ 'return {"output": {"status": await page.get_by_role("status").inner_text()}}',
+ prompt=authored_prompt,
+ )
+ ctx = _ctx()
+
+ result = await _update_workflow(
+ {"workflow_yaml": submitted, "code_artifact_metadata": []},
+ ctx,
+ allow_missing_credentials=True,
+ )
+
+ assert result["ok"] is True
+ assert persisted == [submitted]
+ assert persisted[0].encode() == submitted.encode()
+ submitted_block = workflow_blocks(parse_workflow_yaml(submitted))[0]
+ persisted_block = workflow_blocks(parse_workflow_yaml(persisted[0]))[0]
+ assert submitted_block["prompt"] == authored_prompt
+ assert persisted_block["prompt"] == authored_prompt
+
+
+async def test_accept_path_does_not_synthesize_an_omitted_goal_prompt(monkeypatch: pytest.MonkeyPatch) -> None:
+ persisted: list[str] = []
+ _stub_successful_update(monkeypatch, persisted)
+ submitted = _code_yaml('return {"output": {"status": "complete"}}')
+ assert "prompt:" not in submitted
+ ctx = _ctx()
+
+ result = await _update_workflow(
+ {"workflow_yaml": submitted, "code_artifact_metadata": []},
+ ctx,
+ allow_missing_credentials=True,
+ )
+
+ assert result["ok"] is True
+ assert persisted == [submitted]
+ assert persisted[0].encode() == submitted.encode()
+ submitted_block = workflow_blocks(parse_workflow_yaml(submitted))[0]
+ persisted_block = workflow_blocks(parse_workflow_yaml(persisted[0]))[0]
+ assert "prompt" not in submitted_block
+ assert "prompt" not in persisted_block
+
+
@pytest.mark.asyncio
async def test_requested_output_contract_does_not_rewrite_model_code(monkeypatch: pytest.MonkeyPatch) -> None:
_stub_successful_update(monkeypatch)
diff --git a/tests/unit/test_copilot_code_mode_opt_out.py b/tests/unit/test_copilot_code_mode_opt_out.py
index 8991b8737..784df46b2 100644
--- a/tests/unit/test_copilot_code_mode_opt_out.py
+++ b/tests/unit/test_copilot_code_mode_opt_out.py
@@ -11,6 +11,7 @@ from skyvern.forge.agent_functions import AgentFunction
from skyvern.forge.sdk.copilot.config import (
BlockAuthoringPolicy,
CopilotConfig,
+ block_authoring_policy_for_request,
block_authoring_policy_from_code_only_mode,
download_scout_act_required_for_policy,
)
@@ -306,6 +307,14 @@ def test_code_block_settings_helper_selects_policy() -> None:
assert block_authoring_policy_from_code_only_mode(False) == BlockAuthoringPolicy.STANDARD
[email protected]("fallback_code_block_mode", [False, True])
+def test_build_with_unspecified_code_mode_selects_task_v3_pure(fallback_code_block_mode: bool) -> None:
+ assert (
+ block_authoring_policy_for_request(None, "build", fallback_code_block_mode=fallback_code_block_mode)
+ == BlockAuthoringPolicy.TASK_V3_PURE
+ )
+
+
def test_download_scout_act_requirement_follows_code_only_policy() -> None:
assert download_scout_act_required_for_policy(BlockAuthoringPolicy.CODE_ONLY_BROWSER) is True
assert download_scout_act_required_for_policy("code_only_browser") is True
@@ -330,3 +339,36 @@ async def test_base_agent_function_request_config_uses_env_policy(monkeypatch: p
assert config is not None
assert config.block_authoring_policy == BlockAuthoringPolicy.CODE_ONLY_BROWSER
+
+
+async def test_base_agent_function_build_without_code_access_selects_task_v3_pure(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ monkeypatch.setattr(settings, "WORKFLOW_COPILOT_CODE_BLOCK_MODE", False)
+
+ config = await AgentFunction().get_copilot_config_for_request(
+ "o_test",
+ code_block_mode=None,
+ composer_mode="build",
+ )
+
+ assert config is not None
+ assert config.block_authoring_policy == BlockAuthoringPolicy.TASK_V3_PURE
+
+
+async def test_base_request_config_preserves_get_copilot_config_override() -> None:
+ agent_function = AgentFunction()
+ delegated_config = CopilotConfig()
+ agent_function.get_copilot_config = MagicMock(return_value=delegated_config) # type: ignore[method-assign]
+
+ config = await agent_function.get_copilot_config_for_request(
+ "o_test",
+ code_block_mode=False,
+ composer_mode="build",
+ )
+
+ assert config is delegated_config
+ assert config.block_authoring_policy == BlockAuthoringPolicy.TASK_V3_PURE
+ agent_function.get_copilot_config.assert_called_once_with(False)
diff --git a/tests/unit/test_copilot_enforcement_pruning.py b/tests/unit/test_copilot_enforcement_pruning.py
index d72d7e280..61bb91059 100644
--- a/tests/unit/test_copilot_enforcement_pruning.py
+++ b/tests/unit/test_copilot_enforcement_pruning.py
@@ -1155,3 +1155,92 @@ class TestMcpProvenanceSurvivesPruning:
summary = json.loads(_summarize_tool_output(json.dumps(payload)))
assert MCP_RESULT_PROVENANCE_KEY not in summary
+
+
+class TestPageEvidenceCompaction:
+ """Collapsing an older inspect_page_for_composition result to {"ok": true, "_summarized": ...}
+ tells the model it has page evidence while leaving it none."""
+
+ FILLER = "x" * 9000
+
+ def _packet(self, *, session: str, forms: list[dict], nav: list[dict]) -> str:
+ return json.dumps(
+ {
+ "ok": True,
+ "data": {
+ "source_tool": "inspect_page_for_composition",
+ "source_browser_session_id": session,
+ "current_url": "https://example.test/app/",
+ "inspected_url": "https://example.test/app/",
+ "page_title": "Analytics",
+ "forms": forms,
+ "navigation_targets": nav,
+ "visible_text_excerpt": self.FILLER,
+ "key_value_relations": [{"key": "Visitors", "value": "9.42K", "noise": self.FILLER}],
+ },
+ }
+ )
+
+ def _signed_out(self) -> str:
+ return self._packet(
+ session="pbs_cold",
+ forms=[{"fields": [{"id": "email", "label": "Email"}, {"id": "password", "label": "Password"}]}],
+ nav=[],
+ )
+
+ def _signed_in(self) -> str:
+ return self._packet(session="pbs_warm", forms=[], nav=[{"id": "navWebAnalytics", "text": "Web analytics"}])
+
+ def test_page_evidence_is_not_collapsed_to_a_hollow_success(self) -> None:
+ compacted = json.loads(_summarize_tool_output(self._signed_out()))
+
+ assert compacted.keys() != {"ok", "_summarized"}, "an observation became a success placeholder"
+ assert "page_evidence" in compacted
+
+ def test_two_browser_states_keep_their_own_facts_and_provenance(self) -> None:
+ cold = json.loads(_summarize_tool_output(self._signed_out()))["page_evidence"]
+ warm = json.loads(_summarize_tool_output(self._signed_in()))["page_evidence"]
+
+ assert cold["source_browser_session_id"] == "pbs_cold"
+ assert warm["source_browser_session_id"] == "pbs_warm"
+ assert cold["current_url"] == warm["current_url"], "same URL — only the browser state differs"
+ assert "email" in json.dumps(cold["forms"]), "the sign-in fields are what the cold state carries"
+ assert not warm.get("forms")
+ assert "navWebAnalytics" in json.dumps(warm["navigation_targets"])
+
+ def test_raw_excerpts_are_dropped_before_facts(self) -> None:
+ compacted = _summarize_tool_output(self._signed_out())
+
+ assert self.FILLER not in compacted, "raw excerpts and derived relations go first"
+ assert len(compacted) < len(self._signed_out()) / 4
+
+ def test_a_crowded_page_cannot_defeat_compaction(self) -> None:
+ """Per-list bounds alone would let a page with many forms and links compact to roughly the
+ size it arrived at, which is the opposite of what this pass is for."""
+ lists = {
+ key: [{"id": f"{key}-{index}", "text": "y" * 380} for index in range(12)]
+ for key in (
+ "forms",
+ "navigation_targets",
+ "result_containers",
+ "clickable_controls",
+ "challenge_controls",
+ "modal_overlays",
+ "page_obstructions",
+ )
+ }
+ crowded = json.dumps(
+ {
+ "ok": True,
+ "data": {
+ "source_tool": "inspect_page_for_composition",
+ "inspected_url": "https://example.test/app/",
+ **lists,
+ },
+ }
+ )
+
+ compacted = _summarize_tool_output(crowded)
+
+ assert len(compacted) < 5000, f"compacted output was {len(compacted)} chars"
+ assert json.loads(compacted)["page_evidence"]["forms"], "the first facts still survive"
diff --git a/tests/unit/test_copilot_entrypoint.py b/tests/unit/test_copilot_entrypoint.py
index fb10ef43f..5dc44b146 100644
--- a/tests/unit/test_copilot_entrypoint.py
+++ b/tests/unit/test_copilot_entrypoint.py
@@ -1,12 +1,21 @@
from __future__ import annotations
+import json
+from types import SimpleNamespace
+from typing import Any
+from unittest.mock import AsyncMock, MagicMock
+
import pytest
+from skyvern.forge.sdk.copilot.agent import run_copilot_agent
from skyvern.forge.sdk.copilot.entrypoint import (
anchor_recovers_entrypoint,
extract_anchor_entry_url,
extract_in_turn_entry_url,
+ resolve_turn_entrypoint_url,
)
+from skyvern.forge.sdk.schemas.workflow_copilot import WorkflowCopilotChatRequest
+from tests.unit.copilot_test_helpers import stub_copilot_agent_loop
@pytest.mark.parametrize(
@@ -67,3 +76,125 @@ def test_anchor_recovery_supplies_missing_current_url() -> None:
anchor_recovers_entrypoint("continue", "", "", "earlier https://anchor.example/start")
== "https://anchor.example/start"
)
+
+
+def test_the_eval_seed_outranks_every_other_rung() -> None:
+ assert (
+ resolve_turn_entrypoint_url(
+ eval_entrypoint_url="https://seed.example",
+ in_turn_entrypoint="https://message.example/start",
+ anchor_entrypoint="https://anchor.example/start",
+ persisted_entrypoint_url="https://persisted.example/start",
+ current_entrypoint_url="https://current.example/start",
+ )
+ == "https://seed.example"
+ )
+
+
+ ("in_turn", "anchor", "persisted", "current", "expected"),
+ [
+ (
+ "https://message.example/start",
+ "https://anchor.example/s",
+ "https://p.example/s",
+ None,
+ "https://message.example/start",
+ ),
+ (None, "https://anchor.example/s", "https://p.example/s", None, "https://anchor.example/s"),
+ (None, None, "https://p.example/s", None, "https://p.example/s"),
+ (
+ None,
+ "https://anchor.example/s",
+ "https://p.example/s",
+ "https://current.example/s",
+ "https://current.example/s",
+ ),
+ (None, None, None, None, None),
+ ],
+)
+def test_without_an_eval_seed_the_existing_ladder_is_unchanged(
+ in_turn: str | None,
+ anchor: str | None,
+ persisted: str | None,
+ current: str | None,
+ expected: str | None,
+) -> None:
+ assert (
+ resolve_turn_entrypoint_url(
+ eval_entrypoint_url=None,
+ in_turn_entrypoint=in_turn,
+ anchor_entrypoint=anchor,
+ persisted_entrypoint_url=persisted,
+ current_entrypoint_url=current,
+ )
+ == expected
+ )
+
+
+async def _capture_seeded_turn(
+ monkeypatch: pytest.MonkeyPatch, *, seed: str, global_llm_context: str | None
+) -> dict[str, Any]:
+ captured: dict[str, Any] = {}
+
+ async def capture_turn(**kwargs: Any) -> SimpleNamespace:
+ captured["ctx"] = kwargs["ctx"]
+ captured["initial_input"] = kwargs["initial_input"]
+ return SimpleNamespace(final_output=json.dumps({"type": "REPLY", "user_response": "ok"}), new_items=[])
+
+ stub_copilot_agent_loop(monkeypatch, capture_turn)
+
+ await run_copilot_agent(
+ stream=MagicMock(),
+ organization_id="org-1",
+ chat_request=WorkflowCopilotChatRequest(
+ workflow_permanent_id="wfp-1",
+ workflow_id="wf-1",
+ workflow_copilot_chat_id="chat-1",
+ message="build it, starting at https://message.example/start",
+ workflow_yaml="",
+ ),
+ chat_history=[],
+ global_llm_context=global_llm_context,
+ debug_run_info_text="",
+ llm_api_handler=SimpleNamespace(llm_key="PRIMARY"),
+ raw_secret_safety_handler=AsyncMock(
+ return_value={"version": "1", "state": "clean", "handling": "none", "citations": []}
+ ),
+ api_key="sk-test",
+ eval_entrypoint_url=seed,
+ )
+ return captured
+
+
[email protected]("seed", ["https://www.google.com", "https://example.com"])
+async def test_the_eval_seed_reaches_the_turn_context_before_the_agent_loop(
+ monkeypatch: pytest.MonkeyPatch, seed: str
+) -> None:
+ captured = await _capture_seeded_turn(monkeypatch, seed=seed, global_llm_context=None)
+
+ assert captured["ctx"].resolved_discovery_entrypoint_url == seed
+ assert seed in captured["initial_input"]
+
+
+async def test_a_legacy_prose_context_still_receives_the_seed(monkeypatch: pytest.MonkeyPatch) -> None:
+ captured = await _capture_seeded_turn(
+ monkeypatch, seed="https://seed.example", global_llm_context="the user wants a scraper"
+ )
+
+ assert '"entrypoint_url": "https://seed.example"' in captured["initial_input"]
+ assert "the user wants a scraper" in captured["initial_input"]
+
+
+async def test_an_unparsable_structured_context_is_not_erased_by_the_seed(monkeypatch: pytest.MonkeyPatch) -> None:
+ unparsable = '{"user_goal": "buy a widget", "credential_approvals": [truncated'
+ captured = await _capture_seeded_turn(monkeypatch, seed="https://seed.example", global_llm_context=unparsable)
+
+ assert unparsable in captured["initial_input"]
+ assert "https://seed.example" not in captured["initial_input"]
+ # A seed the model never saw must not still win the ladder, or the turn resolves seeded
+ # while reasoning unseeded and the benchmark row claims a seed that did nothing.
+ assert captured["ctx"].resolved_discovery_entrypoint_url == "https://message.example/start"
diff --git a/tests/unit/test_copilot_model_telemetry.py b/tests/unit/test_copilot_model_telemetry.py
index da37a69e0..de1a6829d 100644
--- a/tests/unit/test_copilot_model_telemetry.py
+++ b/tests/unit/test_copilot_model_telemetry.py
@@ -183,6 +183,49 @@ async def _stream_response(model: LitellmModel) -> tuple[list[Any], list[tuple[i
return events, telemetry_seen
+async def test_model_adapter_attaches_exact_tools_for_nonstream_and_stream_requests(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ attached: list[list[Any]] = []
+
+ async def fake_get_response(*_args: Any, **_kwargs: Any) -> SimpleNamespace:
+ return SimpleNamespace(output=[])
+
+ async def fake_stream_response(*_args: Any, **_kwargs: Any) -> AsyncIterator[str]:
+ yield "done"
+
+ monkeypatch.setattr(model_telemetry_module, "attach_tool_surface_to_pending_capture", attached.append)
+ monkeypatch.setattr(LitellmModel, "get_response", fake_get_response)
+ monkeypatch.setattr(LitellmModel, "stream_response", fake_stream_response)
+ model = CopilotLitellmModel(model="openai/gpt-5.6", next_model_call_index=lambda: 1)
+
+ await model.get_response(
+ system_instructions="system",
+ input=[{"role": "user", "content": "hello"}],
+ model_settings=ModelSettings(),
+ tools=[_lookup_number],
+ output_schema=None,
+ handoffs=[],
+ tracing=ModelTracing.DISABLED,
+ )
+ streamed = [
+ event
+ async for event in model.stream_response(
+ system_instructions="system",
+ input=[{"role": "user", "content": "hello"}],
+ model_settings=ModelSettings(),
+ tools=[_lookup_number],
+ output_schema=None,
+ handoffs=[],
+ tracing=ModelTracing.DISABLED,
+ )
+ ]
+
+ assert attached == [[_lookup_number], [_lookup_number]]
+ assert streamed == ["done"]
+
+
@pytest.mark.asyncio
async def test_nonstream_capture_preserves_request_and_result(monkeypatch: pytest.MonkeyPatch) -> None:
requests: list[bytes] = []
diff --git a/tests/unit/test_copilot_output_utils.py b/tests/unit/test_copilot_output_utils.py
index 1e59a1518..6f0f5c24e 100644
--- a/tests/unit/test_copilot_output_utils.py
+++ b/tests/unit/test_copilot_output_utils.py
@@ -466,7 +466,7 @@ class TestSanitization:
sanitized = sanitize_tool_result_for_llm("update_workflow", result)
assert "_workflow" not in sanitized
- def test_large_schema_truncated(self) -> None:
+ def test_large_incidental_schema_truncated(self) -> None:
from skyvern.forge.sdk.copilot.output_utils import sanitize_tool_result_for_llm
big_schema = {f"field_{i}": {"type": "string"} for i in range(200)}
@@ -474,9 +474,21 @@ class TestSanitization:
"ok": True,
"data": {"schema": big_schema},
}
- sanitized = sanitize_tool_result_for_llm("get_block_schema", result)
+ sanitized = sanitize_tool_result_for_llm("run_blocks_and_collect_debug", result)
assert sanitized["data"]["schema"]["_truncated"] is True
+ def test_get_block_schema_returns_the_schema_it_was_called_for(self) -> None:
+ """The truncation steer says to call get_block_schema for the block type — so applying it to
+ that call's own answer leaves the model no route to the fields it asked for."""
+ from skyvern.forge.sdk.copilot.output_utils import sanitize_tool_result_for_llm
+
+ big_schema = {f"field_{i}": {"type": "string"} for i in range(200)}
+ result = {"ok": True, "data": {"block_type": "code", "schema": big_schema}}
+
+ sanitized = sanitize_tool_result_for_llm("get_block_schema", result)
+
+ assert sanitized["data"]["schema"] == big_schema
+
def test_run_blocks_sanitizer_preserves_compact_packet_fields(self) -> None:
from skyvern.forge.sdk.copilot.output_utils import sanitize_tool_result_for_llm
diff --git a/tests/unit/test_copilot_screenshot_handling.py b/tests/unit/test_copilot_screenshot_handling.py
index 2cdb6495d..993957b75 100644
--- a/tests/unit/test_copilot_screenshot_handling.py
+++ b/tests/unit/test_copilot_screenshot_handling.py
@@ -25,6 +25,7 @@ from skyvern.forge.sdk.copilot.screenshot_utils import (
from skyvern.forge.sdk.copilot.session_factory import copilot_call_model_input_filter
from skyvern.forge.sdk.copilot.tools.run_execution import (
NO_PERSISTED_END_URL,
+ RECORDED_FAILURE_RESPONSE_MAX_CHARS,
_attach_action_traces,
_attach_failed_block_screenshots,
_dispatched_end_url,
@@ -728,7 +729,55 @@ class TestAttachActionTraces:
await _attach_action_traces([block], [result], "org-1")
- assert len(result["action_trace"][0]["response"]) == 300
+ assert len(result["action_trace"][0]["response"]) == RECORDED_FAILURE_RESPONSE_MAX_CHARS
+
+ @pytest.mark.asyncio
+ async def test_a_call_log_keeps_the_lines_naming_what_blocked_the_click(
+ self, monkeypatch: pytest.MonkeyPatch
+ ) -> None:
+ """Verbatim output from a real Playwright click blocked by an overlay, where the cause
+ is in the trailing lines. Cut those and what survives reads like a bad locator, so the
+ model repairs the selector instead of dismissing the overlay."""
+ call_log = (
+ "TimeoutError: Locator.click: Timeout 3000ms exceeded.\n"
+ "Call log:\n"
+ ' - waiting for locator("#grid label.size--will-restock").first\n'
+ ' - locator resolved to <label data-i="0" class="size size--will-restock">s0</label>\n'
+ " - attempting click action\n"
+ " 2 × waiting for element to be visible, enabled and stable\n"
+ " - element is visible, enabled and stable\n"
+ " - scrolling into view if needed\n"
+ " - done scrolling\n"
+ " - <div></div> intercepts pointer events\n"
+ " - retrying click action\n"
+ " - waiting 20ms\n"
+ " 2 × waiting for element to be visible, enabled and stable\n"
+ " - element is visible, enabled and stable\n"
+ " - scrolling into view if needed\n"
+ " - done scrolling\n"
+ " - <div></div> intercepts pointer events\n"
+ " - retrying click action\n"
+ " - waiting 100ms\n"
+ )
+ assert len(call_log) > 500
+
+ block = self._make_block("task-1", "failed")
+ result: dict[str, Any] = {"label": "add_to_cart", "status": "failed"}
+ actions = [
+ self._make_action("task-1", "click", "failed", None, None, response=call_log, output={"code_line": 18})
+ ]
+
+ mock_db = MagicMock()
+ mock_db.tasks = MagicMock()
+ mock_db.tasks.get_recent_actions_for_tasks = AsyncMock(return_value=actions)
+ _install_mock_database(monkeypatch, mock_db)
+
+ await _attach_action_traces([block], [result], "org-1")
+
+ projected = result["action_trace"][0]["response"]
+ assert "locator resolved to" in projected
+ assert "element is visible, enabled and stable" in projected
+ assert "intercepts pointer events" in projected
@pytest.mark.asyncio
async def test_a_non_recorder_failed_action_keeps_its_response_out_of_the_trace(
diff --git a/tests/unit/test_copilot_session_factory.py b/tests/unit/test_copilot_session_factory.py
index 6a9dffcbf..6cd907cab 100644
--- a/tests/unit/test_copilot_session_factory.py
+++ b/tests/unit/test_copilot_session_factory.py
@@ -2,6 +2,7 @@
from __future__ import annotations
+import hashlib
import json
from pathlib import Path
from types import SimpleNamespace
@@ -298,6 +299,9 @@ class TestModelInputCapture:
assert list(tmp_path.iterdir()) == []
def test_capture_records_instructions_and_input(self, tmp_path: Any, monkeypatch: Any) -> None:
+ from agents import FunctionTool
+
+ from skyvern.forge.sdk.copilot.model_input_capture import attach_tool_surface_to_pending_capture
from skyvern.forge.sdk.copilot.session_factory import copilot_call_model_input_filter
monkeypatch.setenv("COPILOT_DUMP_MODEL_INPUTS", str(tmp_path))
@@ -313,6 +317,21 @@ class TestModelInputCapture:
context=SimpleNamespace(eval_capture_case_id="ask_or_build"),
)
)
+ attach_tool_surface_to_pending_capture(
+ [
+ FunctionTool(
+ name="inspect_page",
+ description="Return structured page evidence.",
+ params_json_schema={
+ "type": "object",
+ "properties": {"selector": {"type": "string"}},
+ "required": ["selector"],
+ },
+ on_invoke_tool=lambda _ctx, _args: None,
+ strict_json_schema=False,
+ )
+ ]
+ )
dumps = sorted(tmp_path.glob("call-*.json"))
assert len(dumps) == 1
@@ -322,6 +341,27 @@ class TestModelInputCapture:
assert payload["capture_case_id"] == "ask_or_build"
# A context the derivation helper cannot read must not cost the run its model call.
assert payload["requested_output_paths"] == []
+ assert payload["tool_surface"] == {
+ "version": "copilot-model-tool-surface-v1",
+ "tools": [
+ {
+ "name": "inspect_page",
+ "description": "Return structured page evidence.",
+ "params_json_schema": {
+ "type": "object",
+ "properties": {"selector": {"type": "string"}},
+ "required": ["selector"],
+ },
+ "strict_json_schema": False,
+ }
+ ],
+ }
+ assert (
+ payload["tool_surface_sha256"]
+ == hashlib.sha256(
+ json.dumps(payload["tool_surface"], sort_keys=True, separators=(",", ":")).encode()
+ ).hexdigest()
+ )
def test_capture_records_a_call_whichever_shape_carries_the_context(
self, tmp_path: Path, monkeypatch: pytest.MonkeyPatch
diff --git a/tests/unit/test_copilot_terminal_envelope.py b/tests/unit/test_copilot_terminal_envelope.py
index 89d7ae048..eabea5bea 100644
--- a/tests/unit/test_copilot_terminal_envelope.py
+++ b/tests/unit/test_copilot_terminal_envelope.py
@@ -471,6 +471,21 @@ def test_render_terminal_message_stopped_degraded_envelope_uses_minimal_honest_s
assert rendered == "I stopped without confirming the goal was met."
+def test_render_terminal_message_stopped_with_a_recorded_run_reports_that_it_ran() -> None:
+ envelope = TerminalOutcomeEnvelope(
+ next_state="stopped",
+ verified=False,
+ run_verdict="not_evaluated",
+ run_display_reason=None,
+ response_kind="stopped",
+ )
+
+ rendered, replaced = render_terminal_message(envelope, "legacy", cancelled=False)
+
+ assert replaced is True
+ assert rendered == "I ran the workflow. The latest recorded run completed."
+
+
def test_render_terminal_message_no_run_blocker_stop_keeps_blocker_evidence() -> None:
blocker = "The site demands SSO before any page loads."
envelope = TerminalOutcomeEnvelope(
diff --git a/tests/unit/test_cors.py b/tests/unit/test_cors.py
index 3712f3559..0705cc8df 100644
--- a/tests/unit/test_cors.py
+++ b/tests/unit/test_cors.py
@@ -1,4 +1,41 @@
-from skyvern.cors import credentialed_cors_allow_origin_regex, credentialed_cors_allow_origins
+import httpx
+import pytest
+from fastapi import FastAPI
+
+from skyvern.cors import cors_allows_any_origin, credentialed_cors_allow_origin_regex, credentialed_cors_allow_origins
+from skyvern.forge import api_app as forge_api_app
+
+
+async def test_wildcard_allowed_origins_allow_any_origin_without_credentials(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ monkeypatch.setattr(forge_api_app.settings, "ALLOWED_ORIGINS", ["*"])
+ monkeypatch.setattr(forge_api_app.settings, "ALLOWED_ORIGIN_REGEX", None)
+ app = FastAPI()
+
+ @app.get("/probe")
+ async def probe() -> dict[str, bool]:
+ return {"ok": True}
+
+ forge_api_app.add_credentialed_cors_middleware(app)
+
+ async with httpx.AsyncClient(transport=httpx.ASGITransport(app=app), base_url="http://testserver") as client:
+ response = await client.options(
+ "/probe",
+ headers={"Origin": "https://ui.selfhosted.test", "Access-Control-Request-Method": "GET"},
+ )
+
+ assert response.status_code == 200
+ assert response.headers["access-control-allow-origin"] == "*"
+ assert "access-control-allow-credentials" not in response.headers
+
+
+def test_cors_allows_any_origin_requires_exact_wildcard() -> None:
+ assert cors_allows_any_origin(["*"]) is True
+ assert cors_allows_any_origin([" * "]) is True
+ assert cors_allows_any_origin(["*.example.test"]) is False
+ assert cors_allows_any_origin(["https://app.example.test", ""]) is False
def test_credentialed_cors_allow_origins_drops_wildcards() -> None:
diff --git a/tests/unit/test_dialog_handler_records_to_context.py b/tests/unit/test_dialog_handler_records_to_context.py
index 11703e0de..a94c117bf 100644
--- a/tests/unit/test_dialog_handler_records_to_context.py
+++ b/tests/unit/test_dialog_handler_records_to_context.py
@@ -243,3 +243,78 @@ class TestAcceptancePreflight:
browser_context.on = MagicMock()
dialog_handler.set_dialog_handler(browser_context)
assert len(registrations) == 1
+
+
+class _DriverError(Exception):
+ """Stands in for the deployed driver's error type, which is deliberately NOT the
+ ``playwright.async_api.Error`` the handler module imports — a class-based ``except`` would
+ miss every one of these, so the guard has to match on message text."""
+
+
+VANISHED_DIALOG_MESSAGES = (
+ "Dialog.accept: Protocol error (Page.handleJavaScriptDialog): No dialog is showing",
+ "Dialog.accept: Target page, context or browser has been closed",
+)
+
+
+class TestVanishedDialogGuard:
+ """SKY-15057: answering a dialog races the page. When the dialog is already gone, every
+ response path raises from inside a pyee listener, so an unguarded raise escapes into asyncio's
+ default exception handler — logged at error, stripped of every context field bound here."""
+
+ @pytest.mark.parametrize("message", VANISHED_DIALOG_MESSAGES)
+ @pytest.mark.asyncio
+ async def test_alert_accept_losing_the_race_does_not_propagate(
+ self, isolated_context: SkyvernContext, message: str
+ ) -> None:
+ # Driven through the registered listener, not the handler directly: the escape happens when
+ # the listener's coroutine raises, so the registration seam is part of what has to hold.
+ registered: dict[str, object] = {}
+ page = MagicMock()
+ page.on = lambda event, handler: registered.update({event: handler})
+ browser_context = MagicMock()
+ browser_context.pages = [page]
+ browser_context.on = MagicMock()
+ dialog_handler.set_dialog_handler(browser_context)
+
+ dialog = _make_dialog("alert", "The value of '47' is invalid.")
+ dialog.accept = AsyncMock(side_effect=_DriverError(message))
+
+ await registered["dialog"](dialog)
+
+ @pytest.mark.asyncio
+ async def test_a_respond_routed_accept_losing_the_race_does_not_propagate(
+ self, isolated_context: SkyvernContext
+ ) -> None:
+ dialog = _make_dialog("confirm", "Are you sure?")
+ dialog.accept = AsyncMock(side_effect=_DriverError(VANISHED_DIALOG_MESSAGES[0]))
+
+ await dialog_handler._handle_dialog(dialog, page=MagicMock())
+
+ @pytest.mark.asyncio
+ async def test_an_unrelated_driver_error_still_propagates(self, isolated_context: SkyvernContext) -> None:
+ # The guard names one expected outcome; it is not a blanket swallow of driver failures.
+ dialog = _make_dialog("alert", "message")
+ dialog.accept = AsyncMock(side_effect=_DriverError("Dialog.accept: Protocol error: something else"))
+
+ with pytest.raises(_DriverError):
+ await dialog_handler._handle_dialog(dialog, page=MagicMock())
+
+ @pytest.mark.asyncio
+ async def test_a_vanished_dialog_is_not_retried_as_a_fallback_accept(
+ self, isolated_context: SkyvernContext, monkeypatch: pytest.MonkeyPatch
+ ) -> None:
+ # The LLM path's error arm falls back to accept. A vanished dialog reaching it would answer
+ # a dialog we decided to DISMISS, log the race at error, and raise a second time on the way
+ # out — so the race has to skip the fallback rather than be caught by it.
+ isolated_context.navigation_goal = "goal"
+ monkeypatch.setattr(dialog_handler.prompt_engine, "load_prompt", lambda *a, **k: "prompt")
+ monkeypatch.setattr(
+ dialog_handler.app, "SECONDARY_LLM_API_HANDLER", AsyncMock(return_value={"action": "dismiss"})
+ )
+ dialog = _make_dialog("confirm", "Are you sure?")
+ dialog.dismiss = AsyncMock(side_effect=_DriverError(VANISHED_DIALOG_MESSAGES[0]))
+
+ await dialog_handler._handle_dialog(dialog, page=MagicMock())
+
+ dialog.accept.assert_not_awaited()
diff --git a/tests/unit/test_download_dir_rebind.py b/tests/unit/test_download_dir_rebind.py
index 2cc43dcce..b04a0f869 100644
--- a/tests/unit/test_download_dir_rebind.py
+++ b/tests/unit/test_download_dir_rebind.py
@@ -13,6 +13,7 @@ from types import SimpleNamespace
from unittest.mock import AsyncMock, MagicMock, patch
import pytest
+from structlog.testing import capture_logs
from skyvern.forge.sdk.api.files import get_download_dir, resolve_run_download_id
from skyvern.forge.sdk.core.http_request_authorization import RunScopedRedirectHopAuthorizer
@@ -497,6 +498,61 @@ async def test_listener_falls_back_to_kwargs_without_context(tmp_path: Path) ->
assert captured.get("task_id") == "task_kwarg"
+_SENTINEL_STEM = "zz-sentinel-suggested-stem"
+_SENTINEL_QUERY_NAME = "zz-sentinel-query-stem"
+
+
+async def _run_listener(download: MagicMock) -> list[dict[str, object]]:
+ events: list[dict[str, object]] = []
+
+ def capture(_msg: str, **kwargs: object) -> None:
+ events.append(kwargs)
+
+ captured_handler: dict[str, object] = {}
+ browser_context = MagicMock()
+ browser_context.on = lambda _event, handler: captured_handler.setdefault("handler", handler)
+ browser_context.pages = []
+ set_download_file_listener(browser_context, workflow_run_id="wr_priv", task_id="task_priv")
+
+ page = MagicMock()
+ page_handlers: dict[str, object] = {}
+ page.on = lambda _event, handler: page_handlers.setdefault("download", handler)
+ captured_handler["handler"](page)
+
+ with (
+ patch("skyvern.webeye.browser_factory.current", return_value=None),
+ patch("skyvern.webeye.browser_factory.LOG.info", side_effect=capture),
+ patch("skyvern.webeye.browser_factory.LOG.debug", side_effect=capture),
+ ):
+ await page_handlers["download"](download)
+ return events
+
+
[email protected]("path_kind", ["absent_on_connection", "extensionless_suggestion", "url_query_filename"])
+async def test_listener_never_logs_a_raw_download_filename(tmp_path: Path, path_kind: str) -> None:
+ download = MagicMock()
+ download.suggested_filename = _SENTINEL_STEM
+ download.url = "https://example.com/d"
+ if path_kind == "absent_on_connection":
+ download.path = AsyncMock(return_value=tmp_path / "never-written")
+ else:
+ landed = tmp_path / "landed"
+ landed.write_bytes(b"data")
+ download.path = AsyncMock(return_value=landed)
+ if path_kind == "url_query_filename":
+ download.url = f"https://example.com/d?filename={_SENTINEL_QUERY_NAME}.pdf"
+
+ events = await _run_listener(download)
+
+ assert events, "the listener emitted no row for this path"
+ logged = " ".join(f"{key}={value}" for event in events for key, value in event.items())
+ assert _SENTINEL_STEM not in logged
+ assert _SENTINEL_QUERY_NAME not in logged
+ expected_field = "filename_fp" if path_kind == "url_query_filename" else "suggested_filename_fp"
+ assert any(expected_field in event for event in events)
+
+
@pytest.mark.asyncio
async def test_browser_manager_adoption_rebinds_to_run_dir() -> None:
"""The persistent-session attach path rebinds the adopted CDP downloadPath to the run dir."""
@@ -1420,6 +1476,52 @@ async def test_block_non_adoption_reused_browser_rebinds_to_second_run() -> None
assert params["downloadPath"].endswith("/wr_second")
+async def test_register_downloaded_files_reports_visibility_for_a_non_secure_engine(
+ tmp_path, monkeypatch: pytest.MonkeyPatch
+) -> None:
+ """The row is emitted from the shared registration seam, so engines are comparable.
+
+ Emitting only from the secure-runner dispatch would make the population engine-biased,
+ the same defect the unregistered-intent signal avoids by firing from every engine.
+ """
+ sentinel = "quarterly-policy-summary-sentinel.pdf"
+ monkeypatch.setattr("skyvern.forge.sdk.api.files.settings.DOWNLOAD_PATH", str(tmp_path))
+ monkeypatch.setattr("skyvern.forge.sdk.core.hashing.settings.SECRET_KEY", "download-observation-fingerprint-key")
+ run_dir = tmp_path / "wr_block"
+ run_dir.mkdir()
+ (run_dir / sentinel).write_bytes(b"%PDF-1.4 sentinel")
+
+ block = CodeBlock.__new__(CodeBlock)
+ with patch("skyvern.forge.sdk.workflow.models.block.app") as mock_app:
+ mock_app.STORAGE.save_downloaded_files = AsyncMock()
+ mock_app.STORAGE.get_downloaded_files = AsyncMock(return_value=[])
+
+ with capture_logs() as logs:
+ await block._register_downloaded_files(
+ engine="inline",
+ organization_id="org_1",
+ workflow_run_id="wr_block",
+ workflow_run_block_id="wrb_x",
+ )
+
+ rows = [entry for entry in logs if entry.get("event") == "codeblock.download_registration_visibility"]
+ assert len(rows) == 1
+ row = rows[0]
+ # The seam row is a separate emission site from the secure wrapper, so AC2 is asserted here too.
+ assert row["post_entry_count"] == 1
+ assert row["post_entry_fps"]
+ rendered = repr(row)
+ assert sentinel not in rendered
+ assert "policy-summary" not in rendered
+ assert ".pdf" not in rendered
+ assert row["engine"] == "inline"
+ assert row["boundary"] == "register"
+ assert row["landed_during_settle"] is None
+ # The engine-neutral row still has to answer AC1's timing question on its own.
+ assert row["landed_between_snapshots"] is False
+
+
@pytest.mark.asyncio
async def test_register_downloaded_files_uses_download_run_id_as_storage_key() -> None:
"""_register_downloaded_files keys storage on download_run_id, not the raw workflow_run_id."""
@@ -1431,6 +1533,7 @@ async def test_register_downloaded_files_uses_download_run_id_as_storage_key() -
mock_app.STORAGE.get_downloaded_files = AsyncMock(return_value=[])
await block._register_downloaded_files(
+ engine="inline",
organization_id="org_1",
workflow_run_id="wr_block",
workflow_run_block_id="wrb_x",
@@ -1452,6 +1555,7 @@ async def test_register_downloaded_files_defaults_to_workflow_run_id() -> None:
mock_app.STORAGE.get_downloaded_files = AsyncMock(return_value=[])
await block._register_downloaded_files(
+ engine="inline",
organization_id="org_1",
workflow_run_id="wr_block",
workflow_run_block_id="wrb_x",
diff --git a/tests/unit/test_element_click_navigation_timeout_skips_fallback.py b/tests/unit/test_element_click_navigation_timeout_skips_fallback.py
index e9ace0edf..4bc07b21f 100644
--- a/tests/unit/test_element_click_navigation_timeout_skips_fallback.py
+++ b/tests/unit/test_element_click_navigation_timeout_skips_fallback.py
@@ -8,7 +8,22 @@ import pytest
from playwright.async_api import TimeoutError as PlaywrightTimeoutError
from skyvern.webeye.utils import dom as dom_module
-from skyvern.webeye.utils.dom import SkyvernElement, is_post_dispatch_click_timeout
+from skyvern.webeye.utils.dom import SkyvernElement, is_pointer_interception_error, is_post_dispatch_click_timeout
+
+_POINTER_INTERCEPT_MSG = (
+ "Locator.click: Timeout 5000ms exceeded.\n"
+ "Call log:\n"
+ " - attempting click action\n"
+ ' - <div class="option-label">Yes</div> intercepts pointer events\n'
+ " - retrying click action\n"
+)
+
+_UNSTABLE_MSG = (
+ "Locator.click: Timeout 5000ms exceeded.\n"
+ "Call log:\n"
+ " - waiting for element to be visible, enabled and stable\n"
+ " - element is not stable\n"
+)
_NAVIGATION_TIMEOUT_MSG = (
"Locator.click: Timeout 10000ms exceeded.\n"
@@ -83,6 +98,7 @@ def _make_element() -> SkyvernElement:
elem.find_blocking_element = AsyncMock(return_value=(None, False)) # type: ignore[method-assign]
elem.coordinate_click = AsyncMock(return_value=None) # type: ignore[method-assign]
elem.click_in_javascript = AsyncMock(return_value=None) # type: ignore[method-assign]
+ elem._pointer_interceptor_matches_label = AsyncMock(return_value=True) # type: ignore[method-assign]
return elem
@@ -295,3 +311,138 @@ class TestBlockingElementFallbackPostDispatch:
blocking_locator.click.assert_awaited_once()
elem.coordinate_click.assert_awaited_once()
+
+
+class TestPointerInterceptionClassifier:
+ """The interception predicate must match only the pointer-interception signature idiom,
+ not other actionability failures (detached/unstable/not-visible/disabled)."""
+
+ def test_intercepts_pointer_events_message_matches(self) -> None:
+ assert is_pointer_interception_error(PlaywrightTimeoutError(_POINTER_INTERCEPT_MSG))
+
+ def test_intercepted_by_another_element_message_matches(self) -> None:
+ assert is_pointer_interception_error(RuntimeError("element is intercepted by another element"))
+
+ def test_case_insensitive(self) -> None:
+ assert is_pointer_interception_error(RuntimeError("DIV INTERCEPTS POINTER EVENTS"))
+
+ def test_unstable_detached_not_visible_do_not_match(self) -> None:
+ assert is_pointer_interception_error(PlaywrightTimeoutError(_UNSTABLE_MSG)) is False
+ assert is_pointer_interception_error(RuntimeError("element is not attached to the DOM")) is False
+ assert is_pointer_interception_error(RuntimeError("element is not visible")) is False
+ assert is_pointer_interception_error(RuntimeError("element is not enabled")) is False
+
+
+ ("expected_label", "candidate_texts", "expected"),
+ [
+ pytest.param(" YES\noption ", ["Yes Option"], True, id="normalized-label-match"),
+ pytest.param("Yes", ["Loading", "Validating"], False, id="local-label-mismatch"),
+ pytest.param(" \n ", [""], False, id="empty-label-fails-closed"),
+ pytest.param("Yes", None, False, id="non-list-evaluation-result-fails-closed"),
+ ],
+)
+async def test_pointer_interceptor_label_contract(
+ monkeypatch: pytest.MonkeyPatch,
+ expected_label: str,
+ candidate_texts: list[str] | None,
+ expected: bool,
+) -> None:
+ elem = _make_element()
+ elem.get_frame = MagicMock(return_value=MagicMock()) # type: ignore[method-assign]
+ elem.get_element_handler = AsyncMock(return_value=MagicMock()) # type: ignore[method-assign]
+ evaluate = AsyncMock(return_value=candidate_texts)
+ monkeypatch.setattr(dom_module.SkyvernFrame, "evaluate", evaluate)
+
+ assert await SkyvernElement._pointer_interceptor_matches_label(elem, expected_label) is expected
+ if expected_label.strip():
+ evaluate.assert_awaited_once()
+ else:
+ evaluate.assert_not_called()
+
+
+async def test_pointer_interceptor_label_contract_fails_closed_on_evaluation_error(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ elem = _make_element()
+ elem.get_frame = MagicMock(return_value=MagicMock()) # type: ignore[method-assign]
+ elem.get_element_handler = AsyncMock(return_value=MagicMock()) # type: ignore[method-assign]
+ monkeypatch.setattr(dom_module.SkyvernFrame, "evaluate", AsyncMock(side_effect=RuntimeError("evaluation failed")))
+
+ assert await SkyvernElement._pointer_interceptor_matches_label(elem, "Yes") is False
+
+
+async def test_intercept_js_fallback_engages_only_on_pointer_interception(monkeypatch: pytest.MonkeyPatch) -> None:
+ """A positively classified pointer-interception failure whose interceptor is within the target's
+ bounded container takes the early synthetic JS click, so the coordinate fallback is skipped."""
+ elem = _make_element()
+ monkeypatch.setattr(
+ dom_module.EventStrategyFactory,
+ "click_element",
+ AsyncMock(side_effect=PlaywrightTimeoutError(_POINTER_INTERCEPT_MSG)),
+ )
+
+ await elem.click(page=MagicMock(), dom=None, timeout=1000.0, intercept_js_fallback_label="Yes")
+
+ elem._pointer_interceptor_matches_label.assert_awaited_once_with("Yes")
+ elem.click_in_javascript.assert_awaited_once()
+ elem.coordinate_click.assert_not_called()
+
+
+async def test_intercept_js_fallback_skips_when_interceptor_outside_bounded_container(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ """Even for a pointer-interception failure, an interceptor that does not share the target's bounded
+ container (an unrelated document-level overlay) must NOT take the early JS click; the coordinate
+ path stays reachable so the caller can fail closed with the blocker intact."""
+ elem = _make_element()
+ elem._pointer_interceptor_matches_label = AsyncMock(return_value=False) # type: ignore[method-assign]
+ monkeypatch.setattr(
+ dom_module.EventStrategyFactory,
+ "click_element",
+ AsyncMock(side_effect=PlaywrightTimeoutError(_POINTER_INTERCEPT_MSG)),
+ )
+
+ await elem.click(page=MagicMock(), dom=None, timeout=1000.0, intercept_js_fallback_label="Yes")
+
+ elem.coordinate_click.assert_awaited_once()
+ elem.click_in_javascript.assert_not_called()
+
+
+async def test_intercept_js_fallback_ignores_unrelated_actionability_failure(monkeypatch: pytest.MonkeyPatch) -> None:
+ """An unrelated actionability failure (unstable/detached/covered) must NOT invoke the early synthetic
+ JS click regardless of geometry; the pre-existing coordinate path stays reachable."""
+ elem = _make_element()
+ monkeypatch.setattr(
+ dom_module.EventStrategyFactory,
+ "click_element",
+ AsyncMock(side_effect=PlaywrightTimeoutError(_UNSTABLE_MSG)),
+ )
+
+ await elem.click(page=MagicMock(), dom=None, timeout=1000.0, intercept_js_fallback_label="Yes")
+
+ elem.coordinate_click.assert_awaited_once()
+ elem.click_in_javascript.assert_not_called()
+ elem._pointer_interceptor_matches_label.assert_not_called()
+
+
+async def test_intercept_js_fallback_defaults_off_even_on_interception(monkeypatch: pytest.MonkeyPatch) -> None:
+ """Without the opt-in, even a pointer-interception failure keeps the coordinate path as the first
+ fallback — the early JS click is off by default."""
+ elem = _make_element()
+ monkeypatch.setattr(
+ dom_module.EventStrategyFactory,
+ "click_element",
+ AsyncMock(side_effect=PlaywrightTimeoutError(_POINTER_INTERCEPT_MSG)),
+ )
+
+ await elem.click(page=MagicMock(), dom=None, timeout=1000.0)
+
+ elem.coordinate_click.assert_awaited_once()
+ elem.click_in_javascript.assert_not_called()
diff --git a/tests/unit/test_explicit_submit_sequential_click_bypass.py b/tests/unit/test_explicit_submit_sequential_click_bypass.py
index 5cc8b36dc..d34451ece 100644
--- a/tests/unit/test_explicit_submit_sequential_click_bypass.py
+++ b/tests/unit/test_explicit_submit_sequential_click_bypass.py
@@ -8,18 +8,25 @@ existing ``handle_sequential_click_for_dropdown`` path.
from __future__ import annotations
+from collections import defaultdict
+from collections.abc import Callable
+from datetime import UTC, datetime
+from types import SimpleNamespace
from unittest.mock import AsyncMock, MagicMock
import pytest
import skyvern.webeye.actions.handler as handler_module
+from skyvern.forge.sdk.models import StepStatus
from skyvern.webeye.actions.actions import ClickAction
from skyvern.webeye.actions.handler import (
+ ActionHandler,
handle_click_action,
handle_sequential_click_with_submit_bypass,
)
from skyvern.webeye.actions.responses import ActionSuccess
from skyvern.webeye.utils.dom import SkyvernElement
+from tests.unit.helpers import make_organization, make_step, make_task
def _el(*, element_id: str, tag_name: str, attributes: dict | None = None) -> SkyvernElement:
@@ -283,3 +290,327 @@ class TestHandleClickActionIntegration:
sequential_mock.assert_awaited_once()
incremental.stop_listen_dom_increment.assert_awaited_once()
assert isinstance(results[-1], ActionSuccess)
+
+
+class _FakePage:
+ """Minimal Playwright-page stand-in that records event listeners and can emit
+ to them, so a synthesized download during the click window is observable and
+ listener-leak assertions are exact."""
+
+ def __init__(self, url: str = "https://example.com/form") -> None:
+ self.url = url
+ self._listeners: dict[str, list[Callable]] = defaultdict(list)
+
+ def on(self, event: str, callback: Callable) -> None:
+ self._listeners[event].append(callback)
+
+ def off(self, event: str, callback: Callable) -> None:
+ if callback in self._listeners[event]:
+ self._listeners[event].remove(callback)
+
+ remove_listener = off
+
+ async def evaluate(self, *args: object, **kwargs: object) -> bool:
+ return False
+
+ def emit(self, event: str, arg: object) -> None:
+ for callback in list(self._listeners[event]):
+ callback(arg)
+
+ def listener_count(self, event: str) -> int:
+ return len(self._listeners[event])
+
+
+def false_click_eligible() -> object:
+ token = handler_module._false_click_download_eligible.set(True)
+ yield
+ handler_module._false_click_download_eligible.reset(token)
+
+
+class TestFileDownloadFalseClickBypass:
+ """A file-download block observing a same-action download should skip the expensive
+ post-click dropdown/custom-select rescrape, gated by the ``file_download_false_click_eligible``
+ authority. It must not fabricate download registration and must leak no listeners."""
+
+ def _clickable_element(self) -> SkyvernElement:
+ static = {"id": "E1", "tagName": "button", "attributes": {}}
+ el = SkyvernElement(MagicMock(), MagicMock(), static)
+ el.is_disabled = AsyncMock(return_value=False) # type: ignore[method-assign]
+ el.scroll_into_view = AsyncMock() # type: ignore[method-assign]
+ el.get_frame = MagicMock(return_value=MagicMock()) # type: ignore[method-assign]
+ el.get_element_handler = AsyncMock(return_value=MagicMock()) # type: ignore[method-assign]
+ return el
+
+ def _wire(self, monkeypatch: pytest.MonkeyPatch, element: SkyvernElement) -> tuple[AsyncMock, AsyncMock, MagicMock]:
+ dom_mock = MagicMock()
+ dom_mock.get_skyvern_element_by_id = AsyncMock(return_value=element)
+ monkeypatch.setattr(handler_module, "DomUtil", MagicMock(return_value=dom_mock))
+ monkeypatch.setattr(handler_module, "get_or_create_wait_config", AsyncMock(return_value=MagicMock()))
+ monkeypatch.setattr(handler_module, "get_wait_time", MagicMock(return_value=0))
+ monkeypatch.setattr(handler_module.SkyvernFrame, "create_instance", AsyncMock(return_value=MagicMock()))
+
+ incremental = MagicMock()
+ incremental.start_listen_dom_increment = AsyncMock()
+ incremental.stop_listen_dom_increment = AsyncMock()
+ monkeypatch.setattr(handler_module, "IncrementalScrapePage", MagicMock(return_value=incremental))
+
+ chain_click_mock = AsyncMock(return_value=[ActionSuccess()])
+ monkeypatch.setattr(handler_module, "chain_click", chain_click_mock)
+ sequential_mock = AsyncMock(return_value=None)
+ monkeypatch.setattr(handler_module, "handle_sequential_click_for_dropdown", sequential_mock)
+ return chain_click_mock, sequential_mock, incremental
+
+ async def _run(self, page: _FakePage) -> list:
+ return await handle_click_action(ClickAction(element_id="E1"), page, MagicMock(), MagicMock(), MagicMock())
+
+ @pytest.mark.asyncio
+ async def test_same_page_download_bypasses_sequential(
+ self, monkeypatch: pytest.MonkeyPatch, false_click_eligible: object
+ ) -> None:
+ page = _FakePage()
+ chain_click_mock, sequential_mock, incremental = self._wire(monkeypatch, self._clickable_element())
+
+ async def emit_download(*args: object, **kwargs: object) -> list:
+ page.emit("download", MagicMock(name="download"))
+ return [ActionSuccess()]
+
+ chain_click_mock.side_effect = emit_download
+
+ results = await self._run(page)
+
+ chain_click_mock.assert_awaited_once()
+ sequential_mock.assert_not_called()
+ incremental.stop_listen_dom_increment.assert_awaited_once()
+ assert results == chain_click_mock.return_value
+ assert results[-1].download_triggered is None
+ assert results[-1].downloaded_files is None
+ assert page.listener_count("download") == 0
+ assert page.listener_count("popup") == 0
+
+ @pytest.mark.asyncio
+ async def test_popup_download_bypasses_sequential(
+ self, monkeypatch: pytest.MonkeyPatch, false_click_eligible: object
+ ) -> None:
+ page = _FakePage()
+ popup = _FakePage("https://example.com/popup")
+ chain_click_mock, sequential_mock, _ = self._wire(monkeypatch, self._clickable_element())
+
+ async def emit_popup_download(*args: object, **kwargs: object) -> list:
+ page.emit("popup", popup)
+ popup.emit("download", MagicMock(name="download"))
+ return [ActionSuccess()]
+
+ chain_click_mock.side_effect = emit_popup_download
+
+ results = await self._run(page)
+
+ sequential_mock.assert_not_called()
+ assert results == chain_click_mock.return_value
+ assert page.listener_count("download") == 0
+ assert page.listener_count("popup") == 0
+ assert popup.listener_count("download") == 0
+
+ @pytest.mark.asyncio
+ async def test_no_download_runs_sequential(
+ self, monkeypatch: pytest.MonkeyPatch, false_click_eligible: object
+ ) -> None:
+ page = _FakePage()
+ chain_click_mock, sequential_mock, _ = self._wire(monkeypatch, self._clickable_element())
+
+ results = await self._run(page)
+
+ chain_click_mock.assert_awaited_once()
+ sequential_mock.assert_awaited_once()
+ assert isinstance(results[-1], ActionSuccess)
+ assert page.listener_count("download") == 0
+ assert page.listener_count("popup") == 0
+
+ @pytest.mark.asyncio
+ async def test_not_eligible_ignores_download(self, monkeypatch: pytest.MonkeyPatch) -> None:
+ # No ``false_click_eligible`` fixture: an ordinary (non-file-download) click that happens
+ # to emit a download must still run the standard sequential path — the bypass is gated.
+ page = _FakePage()
+ chain_click_mock, sequential_mock, _ = self._wire(monkeypatch, self._clickable_element())
+
+ async def emit_download(*args: object, **kwargs: object) -> list:
+ page.emit("download", MagicMock(name="download"))
+ return [ActionSuccess()]
+
+ chain_click_mock.side_effect = emit_download
+
+ await self._run(page)
+
+ sequential_mock.assert_awaited_once()
+ assert page.listener_count("download") == 0
+ assert page.listener_count("popup") == 0
+
+ @pytest.mark.asyncio
+ async def test_download_queued_after_click_bypasses_sequential(
+ self, monkeypatch: pytest.MonkeyPatch, false_click_eligible: object
+ ) -> None:
+ # Real Playwright delivers the ``download`` event on a later event-loop turn, after the
+ # click await resolves — the common case for a dynamically-registered handler with no
+ # static ``onclick`` attribute (``has_onclick_attr`` False, so no 1s animation wait yields
+ # between the two bypass checks). Schedule the emit via ``call_soon`` instead of emitting
+ # synchronously inside the click, and the bypass must still fire.
+ import asyncio
+
+ page = _FakePage()
+ chain_click_mock, sequential_mock, incremental = self._wire(monkeypatch, self._clickable_element())
+
+ async def emit_download_next_turn(*args: object, **kwargs: object) -> list:
+ asyncio.get_running_loop().call_soon(page.emit, "download", MagicMock(name="download"))
+ return [ActionSuccess()]
+
+ chain_click_mock.side_effect = emit_download_next_turn
+
+ results = await self._run(page)
+
+ chain_click_mock.assert_awaited_once()
+ sequential_mock.assert_not_called()
+ incremental.stop_listen_dom_increment.assert_awaited_once()
+ assert results == chain_click_mock.return_value
+ assert page.listener_count("download") == 0
+ assert page.listener_count("popup") == 0
+
+ @pytest.mark.asyncio
+ async def test_listeners_removed_on_exception(
+ self, monkeypatch: pytest.MonkeyPatch, false_click_eligible: object
+ ) -> None:
+ page = _FakePage()
+ chain_click_mock, _, incremental = self._wire(monkeypatch, self._clickable_element())
+ chain_click_mock.side_effect = RuntimeError("boom")
+
+ with pytest.raises(RuntimeError):
+ await self._run(page)
+
+ incremental.stop_listen_dom_increment.assert_awaited_once()
+ assert page.listener_count("download") == 0
+ assert page.listener_count("popup") == 0
+
+
+class TestHandleActionPublicPathFalseClickBypass:
+ """Drive the real public ``ActionHandler.handle_action`` entry point with the popup-grace
+ setting at its production default of 0. The fixture-based tests above preset the ContextVar
+ directly, so they cannot catch a wiring regression where ``handle_action`` only arms the
+ bypass probe under grace > 0 — the activation defect the reviewer flagged. Here the probe
+ must be armed purely from ``file_download_false_click_eligible``, independent of grace."""
+
+ def _clickable_element(self) -> SkyvernElement:
+ static = {"id": "E1", "tagName": "button", "attributes": {}}
+ el = SkyvernElement(MagicMock(), MagicMock(), static)
+ el.is_disabled = AsyncMock(return_value=False) # type: ignore[method-assign]
+ el.scroll_into_view = AsyncMock() # type: ignore[method-assign]
+ el.get_frame = MagicMock(return_value=MagicMock()) # type: ignore[method-assign]
+ el.get_element_handler = AsyncMock(return_value=MagicMock()) # type: ignore[method-assign]
+ return el
+
+ def _wire_click_internals(
+ self, monkeypatch: pytest.MonkeyPatch, element: SkyvernElement
+ ) -> tuple[AsyncMock, AsyncMock, MagicMock]:
+ dom_mock = MagicMock()
+ dom_mock.get_skyvern_element_by_id = AsyncMock(return_value=element)
+ monkeypatch.setattr(handler_module, "DomUtil", MagicMock(return_value=dom_mock))
+ monkeypatch.setattr(handler_module, "get_or_create_wait_config", AsyncMock(return_value=MagicMock()))
+ monkeypatch.setattr(handler_module, "get_wait_time", MagicMock(return_value=0))
+ monkeypatch.setattr(handler_module.SkyvernFrame, "create_instance", AsyncMock(return_value=MagicMock()))
+
+ incremental = MagicMock()
+ incremental.start_listen_dom_increment = AsyncMock()
+ incremental.stop_listen_dom_increment = AsyncMock()
+ monkeypatch.setattr(handler_module, "IncrementalScrapePage", MagicMock(return_value=incremental))
+
+ chain_click_mock = AsyncMock(return_value=[ActionSuccess()])
+ monkeypatch.setattr(handler_module, "chain_click", chain_click_mock)
+ sequential_mock = AsyncMock(return_value=None)
+ monkeypatch.setattr(handler_module, "handle_sequential_click_for_dropdown", sequential_mock)
+ return chain_click_mock, sequential_mock, incremental
+
+ def _wire_action_wrapper(self, monkeypatch: pytest.MonkeyPatch) -> None:
+ # Importing ``cloud`` (e.g. via a tests/cloud file collected earlier in the shard)
+ # registers CLICK setup/teardown hooks on these class-level dicts, which would
+ # short-circuit ``_handle_action`` before the real click handler. Isolate the
+ # public-path tests from that global registration, matching the idiom in
+ # test_action_execution_timeout.py / test_input_text_tel_card_routing.py.
+ monkeypatch.setattr(ActionHandler, "_setup_action_types", {})
+ monkeypatch.setattr(ActionHandler, "_teardown_action_types", {})
+ app_mock = MagicMock()
+ app_mock.BROWSER_MANAGER.get_for_task.return_value = MagicMock()
+ app_mock.AGENT_FUNCTION.wait_for_challenge_solver = AsyncMock()
+ app_mock.DATABASE.workflow_params.create_action = AsyncMock(return_value=SimpleNamespace(action_id="a-1"))
+ monkeypatch.setattr(handler_module, "app", app_mock)
+ monkeypatch.setattr(handler_module, "preflight_action", MagicMock(return_value=None))
+ # Pin the production default explicitly so the test proves the bypass no longer depends on grace.
+ monkeypatch.setattr(handler_module.settings, "FILE_DOWNLOAD_FALSE_CLICK_POPUP_GRACE_SECONDS", 0)
+
+ def _context(self) -> tuple:
+ now = datetime.now(UTC)
+ organization = make_organization(now)
+ task = make_task(now, organization)
+ step = make_step(now, task, step_id="step-1", status=StepStatus.created, order=0, output=None)
+ return task, step
+
+ def _scraped_page(self) -> MagicMock:
+ scraped_page = MagicMock()
+ scraped_page.id_to_element_dict = {"E1": {"id": "E1"}}
+ return scraped_page
+
+ @pytest.mark.asyncio
+ async def test_grace_zero_same_page_download_bypasses_sequential(self, monkeypatch: pytest.MonkeyPatch) -> None:
+ task, step = self._context()
+ action = ClickAction(element_id="E1", download=False)
+ chain_click_mock, sequential_mock, incremental = self._wire_click_internals(
+ monkeypatch, self._clickable_element()
+ )
+ self._wire_action_wrapper(monkeypatch)
+ page = _FakePage()
+
+ async def emit_download(*args: object, **kwargs: object) -> list:
+ page.emit("download", MagicMock(name="download"))
+ return [ActionSuccess()]
+
+ chain_click_mock.side_effect = emit_download
+
+ results = await ActionHandler.handle_action(
+ self._scraped_page(), task, step, page, action, file_download_false_click_eligible=True
+ )
+
+ chain_click_mock.assert_awaited_once()
+ # The expensive dropdown/custom-select rescrape was skipped because the same-action download
+ # was observed — reachable through the public path even with grace at its default of 0.
+ sequential_mock.assert_not_called()
+ incremental.stop_listen_dom_increment.assert_awaited_once()
+ assert results == chain_click_mock.return_value
+ # No download registration was fabricated; persistence stays owned by the download path.
+ assert results[-1].download_triggered is None
+ assert results[-1].downloaded_files is None
+ assert page.listener_count("download") == 0
+ assert page.listener_count("popup") == 0
+ # ContextVar was reset on exit — no leak into the next action in this task.
+ assert handler_module._false_click_download_eligible.get() is False
+
+ @pytest.mark.asyncio
+ async def test_grace_zero_not_eligible_runs_sequential(self, monkeypatch: pytest.MonkeyPatch) -> None:
+ # Control: without the file-download false-click authority, an ordinary click that happens to
+ # emit a download must still run the standard sequential path, and the probe stays disarmed.
+ task, step = self._context()
+ action = ClickAction(element_id="E1", download=False)
+ chain_click_mock, sequential_mock, _ = self._wire_click_internals(monkeypatch, self._clickable_element())
+ self._wire_action_wrapper(monkeypatch)
+ page = _FakePage()
+
+ async def emit_download(*args: object, **kwargs: object) -> list:
+ page.emit("download", MagicMock(name="download"))
+ return [ActionSuccess()]
+
+ chain_click_mock.side_effect = emit_download
+
+ await ActionHandler.handle_action(
+ self._scraped_page(), task, step, page, action, file_download_false_click_eligible=False
+ )
+
+ sequential_mock.assert_awaited_once()
+ assert page.listener_count("download") == 0
+ assert page.listener_count("popup") == 0
+ assert handler_module._false_click_download_eligible.get() is False
diff --git a/tests/unit/test_forge_log.py b/tests/unit/test_forge_log.py
index 61e9c47ee..b227f1aa3 100644
--- a/tests/unit/test_forge_log.py
+++ b/tests/unit/test_forge_log.py
@@ -43,3 +43,14 @@ def test_kwarg_correlation_id_is_searchable_without_context() -> None:
event_dict = add_log_context(None, "info", {"msg": "Begin browser session", "browser_session_id": "pbs_2"})
assert event_dict["msg"] == "Begin browser session | browser_session_id=pbs_2"
+
+
+def test_codeblock_execution_path_is_a_field_not_a_msg_suffix() -> None:
+ # The arm is a grouping facet for the secure-vs-legacy monitors, not a correlation id,
+ # so it must stay out of the searchable-id suffix (SKY-13848 bounds what goes into msg).
+ context = SkyvernContext(workflow_run_id="wr_1", codeblock_execution_path="secure_runner")
+ with patch.object(skyvern_context, "current", return_value=context):
+ event_dict = add_log_context(None, "warning", {"msg": "Block failed"})
+
+ assert event_dict["codeblock_execution_path"] == "secure_runner"
+ assert event_dict["msg"] == "Block failed | workflow_run_id=wr_1"
diff --git a/tests/unit/test_incompatible_element_guards.py b/tests/unit/test_incompatible_element_guards.py
index 579d5f43b..cefef1f41 100644
--- a/tests/unit/test_incompatible_element_guards.py
+++ b/tests/unit/test_incompatible_element_guards.py
@@ -6,6 +6,7 @@ import pytest
from playwright.async_api import Error as PlaywrightError
from skyvern.exceptions import InvalidElementForTextInput
+from skyvern.webeye.actions import handler
from skyvern.webeye.actions.handler import (
_is_selected_engine_error,
_is_selected_engine_timeout,
@@ -158,3 +159,68 @@ async def test_input_clear_classifies_incompatible_element(monkeypatch: pytest.M
monkeypatch.setattr("skyvern.webeye.utils.dom.EventStrategyFactory.clear_field", _raise)
with pytest.raises(InvalidElementForTextInput):
await element.input_clear()
+
+
+# --------------------------------------------------------------------------- #
+# _strict_date_mask_order / _canonical_iso_date — deterministic date canonicalization.
+# A live <input type=date> takes only YYYY-MM-DD; a locale value is canonicalized only when the
+# day/month order is unambiguous, and prose / first-letter lookalikes never define an order.
+# --------------------------------------------------------------------------- #
+def test_strict_date_mask_order_accepts_real_masks() -> None:
+ assert handler._strict_date_mask_order("mm/dd/yyyy") == ("m", "d", "y")
+ assert handler._strict_date_mask_order("dd-mm-yyyy") == ("d", "m", "y")
+ assert handler._strict_date_mask_order("yyyy.mm.dd") == ("y", "m", "d")
+ assert handler._strict_date_mask_order("d/m/yyyy") == ("d", "m", "y")
+
+
+def test_strict_date_mask_order_rejects_prose_and_lookalikes() -> None:
+ for prose in (
+ "Date Must Yield",
+ "Day Month Year",
+ "Start date",
+ "mm/dd/yy",
+ "mm/mm/yyyy",
+ "mm/yyyy",
+ "day mm/dd/yyyy",
+ ):
+ assert handler._strict_date_mask_order(prose) is None
+ assert handler._strict_date_mask_order(None) is None
+ assert handler._strict_date_mask_order("") is None
+
+
+ ("text", "placeholder", "expected"),
+ [
+ # already ISO stays ISO
+ ("2026-08-23", None, "2026-08-23"),
+ # a strict mask decides the order, so the same digits canonicalize both ways
+ ("03/04/2026", "mm/dd/yyyy", "2026-03-04"),
+ ("03/04/2026", "dd/mm/yyyy", "2026-04-03"),
+ ("2026.08.23", "yyyy.mm.dd", "2026-08-23"),
+ ("08/23/2026", "mm/dd/yyyy", "2026-08-23"),
+ # no mask: only an unambiguous reading is accepted (a part > 12 pins the day)
+ ("23/08/2026", None, "2026-08-23"),
+ ("08/23/2026", None, "2026-08-23"),
+ # no mask and both parts <= 12 -- ambiguous, refuse rather than guess a date
+ ("03/04/2026", None, None),
+ # prose / first-letter lookalikes must not define an order (the mask blocker)
+ ("03/04/2026", "Date Must Yield", None),
+ ("03/04/2026", "Day Month Year", None),
+ ("03/04/2026", "Start date", None),
+ # partial year, duplicate, missing, extra tokens are rejected
+ ("03/04/26", "mm/dd/yy", None),
+ ("03/04/2026", "mm/mm/yyyy", None),
+ ("03/2026", "mm/yyyy", None),
+ ("03/04/2026", "day mm/dd/yyyy", None),
+ # calendar correctness: invalid month/day, non-leap Feb 29, valid leap Feb 29
+ ("13/04/2026", "mm/dd/yyyy", None),
+ ("02/30/2026", "mm/dd/yyyy", None),
+ ("02/29/2027", "mm/dd/yyyy", None),
+ ("02/29/2028", "mm/dd/yyyy", "2028-02-29"),
+ # not a date, or a non-four-digit year value
+ ("hello", "mm/dd/yyyy", None),
+ ("08/23/26", "mm/dd/yyyy", None),
+ ],
+)
+def test_canonical_iso_date(text: str, placeholder: str | None, expected: str | None) -> None:
+ assert handler._canonical_iso_date(text, placeholder) == expected
diff --git a/tests/unit/test_input_text_combobox_commit.py b/tests/unit/test_input_text_combobox_commit.py
index e90bf2c0b..81b5bf00a 100644
--- a/tests/unit/test_input_text_combobox_commit.py
+++ b/tests/unit/test_input_text_combobox_commit.py
@@ -1519,3 +1519,51 @@ async def test_search_bar_no_settle_when_enabled_nested_span_target_present() ->
assert inc.get_incremental_element_tree.await_count == 1 # initial read only, no settle re-read
select_mock.assert_awaited_once()
assert select_mock.await_args.kwargs["target_value"] == _TARGET
+
+
+# --------------------------------------------------------------------------- #
+# _custom_select_committed_readback_confirms — the pre-ownership-recovery gate.
+# A strict scope read can miss a commit the chosen option itself reflects; the gate honors a visibly
+# committed pick before ownership-dependent recovery, but only on an exact-label + committed signal.
+# --------------------------------------------------------------------------- #
+async def test_committed_readback_confirms_selected_option_with_exact_label() -> None:
+ element = MagicMock()
+ state = {"label": "Yes", "role": "option", "selectedAttr": True}
+ with patch.object(handler, "_read_custom_select_matched_state", AsyncMock(return_value=state)):
+ assert await handler._custom_select_committed_readback_confirms(element, "Yes") is True
+
+
+async def test_committed_readback_rejects_label_mismatch() -> None:
+ element = MagicMock()
+ state = {"label": "No", "role": "option", "selectedAttr": True}
+ with patch.object(handler, "_read_custom_select_matched_state", AsyncMock(return_value=state)):
+ assert await handler._custom_select_committed_readback_confirms(element, "Yes") is False
+
+
+async def test_committed_readback_rejects_unreadable_state() -> None:
+ # A None read-back (unreadable / errored seam) is never success — no fail-open.
+ element = MagicMock()
+ with patch.object(handler, "_read_custom_select_matched_state", AsyncMock(return_value=None)):
+ assert await handler._custom_select_committed_readback_confirms(element, "Yes") is False
+
+
+async def test_committed_readback_rejects_single_select_highlight() -> None:
+ # aria-selected on a single-select option is a keyboard highlight, not a commit; not success.
+ element = MagicMock()
+ state = {"label": "Yes", "role": "option", "ariaSelected": True, "inMultiselectable": False}
+ with patch.object(handler, "_read_custom_select_matched_state", AsyncMock(return_value=state)):
+ assert await handler._custom_select_committed_readback_confirms(element, "Yes") is False
+
+
+async def test_committed_readback_rejects_blank_requested_value() -> None:
+ # An empty expected label cannot be exact-matched; short-circuit before reading, never success.
+ element = MagicMock()
+ read = AsyncMock(return_value={"label": "Yes", "selectedAttr": True})
+ with patch.object(handler, "_read_custom_select_matched_state", read):
+ assert await handler._custom_select_committed_readback_confirms(element, " ") is False
+ read.assert_not_awaited()
diff --git a/tests/unit/test_mcp_browser_tools.py b/tests/unit/test_mcp_browser_tools.py
index a1da9657a..b78d4b947 100644
--- a/tests/unit/test_mcp_browser_tools.py
+++ b/tests/unit/test_mcp_browser_tools.py
@@ -10,6 +10,7 @@ from unittest.mock import AsyncMock, MagicMock, Mock, call
import pytest
+from skyvern.browser_extension.runtime import BrowserExtensionRuntime
from skyvern.cli.core import browser_ops
from skyvern.cli.core import result as result_mod
from skyvern.cli.core import session_manager
@@ -1152,6 +1153,58 @@ async def test_click_native_option_sdk_equivalent_quotes_observed_strings(
_assert_sdk_equivalent_parses(result)
+async def test_evaluate_uses_direct_extension_runtime(monkeypatch: pytest.MonkeyPatch) -> None:
+ get_page = AsyncMock(side_effect=AssertionError("extension evaluation must bypass Playwright"))
+ evaluate = AsyncMock(return_value={"answer": 42})
+ runtime = SimpleNamespace(evaluate=evaluate)
+ monkeypatch.setattr(mcp_browser, "get_page", get_page)
+ monkeypatch.setattr(
+ mcp_browser,
+ "get_current_session",
+ lambda: SimpleNamespace(context=BrowserContext(mode="extension")),
+ )
+ monkeypatch.setattr(
+ BrowserExtensionRuntime,
+ "instance",
+ classmethod(lambda _cls: runtime),
+ )
+
+ result = await mcp_browser.skyvern_evaluate(expression="({ answer: 6 * 7 })")
+
+ assert result["ok"] is True
+ assert result["data"]["result"] == {"answer": 42}
+ evaluate.assert_awaited_once_with("({ answer: 6 * 7 })")
+ get_page.assert_not_awaited()
+
+
+async def test_evaluate_does_not_reclaim_tab_without_active_extension_session(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ get_page = AsyncMock(side_effect=session_manager.BrowserNotAvailableError("No active browser session"))
+ evaluate = AsyncMock(side_effect=AssertionError("closed extension session must not evaluate"))
+ runtime = SimpleNamespace(evaluate=evaluate)
+ monkeypatch.setattr(mcp_browser, "get_page", get_page)
+ monkeypatch.setattr(
+ mcp_browser,
+ "get_current_session",
+ lambda: SimpleNamespace(context=None),
+ )
+ monkeypatch.setattr(
+ BrowserExtensionRuntime,
+ "instance",
+ classmethod(lambda _cls: runtime),
+ )
+
+ result = await mcp_browser.skyvern_evaluate(expression="document.title")
+
+ assert result["ok"] is False
+ assert result["error"]["code"] == mcp_browser.ErrorCode.NO_ACTIVE_BROWSER
+ evaluate.assert_not_awaited()
+ get_page.assert_awaited_once_with(session_id=None, cdp_url=None)
+
+
@pytest.mark.asyncio
async def test_evaluate_sdk_equivalent_truncates_before_quoting(monkeypatch: pytest.MonkeyPatch) -> None:
_sdk_equivalent_page(monkeypatch)
diff --git a/tests/unit/test_no_available_option.py b/tests/unit/test_no_available_option.py
index e1b717a00..34e771e12 100644
--- a/tests/unit/test_no_available_option.py
+++ b/tests/unit/test_no_available_option.py
@@ -2127,3 +2127,161 @@ class TestSameLevelClickMarksWidgetMutation:
skyvern_context.reset()
assert excinfo.value.widget_mutated is True
+
+
+def _already_open_anchor(
+ *,
+ expanded: bool | None = True,
+ anchor_sk: str = "anchor-sk",
+ listbox_dom: str = "listbox-dom",
+) -> dict:
+ # domUtils scrapes aria-expanded as a real bool, so mirror that shape here rather than a string.
+ attributes: dict = {"role": "combobox", "aria-controls": listbox_dom, "id": "anchor-dom"}
+ if expanded is not None:
+ attributes["aria-expanded"] = expanded
+ return {"id": anchor_sk, "tagName": "div", "attributes": attributes, "children": []}
+
+
+def _already_open_option(sk: str, label: str) -> dict:
+ return {
+ "id": sk,
+ "tagName": "li",
+ "attributes": {"role": "option"},
+ "text": label,
+ "interactable": True,
+ "children": [],
+ }
+
+
+def _already_open_listbox(
+ *, options: list[dict], listbox_sk: str = "listbox-sk", listbox_dom: str = "listbox-dom"
+) -> dict:
+ return {
+ "id": listbox_sk,
+ "tagName": "ul",
+ "attributes": {"role": "listbox", "id": listbox_dom},
+ "children": list(options),
+ }
+
+
+def _already_open_pages(
+ *, anchor: dict, listbox: dict, extra_elements: list[dict] | None = None
+) -> tuple[SimpleNamespace, SimpleNamespace]:
+ """Before/after scraped pages whose strict new-element diff is empty because the combobox is already open."""
+ elements = [anchor, listbox, *listbox["children"], *(extra_elements or [])]
+ tree_root = {"id": "root", "tagName": "div", "attributes": {}, "children": [anchor, listbox]}
+ before = SimpleNamespace(id_to_css_dict={})
+ after = SimpleNamespace(
+ id_to_css_dict={},
+ id_to_element_dict={anchor["id"]: anchor},
+ elements=elements,
+ element_tree_trimmed=[tree_root],
+ )
+ return before, after
+
+
+def _install_dom_after_open(monkeypatch: pytest.MonkeyPatch, *, interactable_ids: set[str]) -> MagicMock:
+ def _element_for(element_id: str) -> MagicMock:
+ element = MagicMock()
+ element.is_interactable = MagicMock(return_value=element_id in interactable_ids)
+ element.get_attr = AsyncMock(return_value=None)
+ element.scroll_into_view = AsyncMock()
+ element.click = AsyncMock()
+ return element
+
+ dom_after_open = MagicMock()
+ dom_after_open.get_skyvern_element_by_id = AsyncMock(side_effect=_element_for)
+ monkeypatch.setattr(handler, "DomUtil", MagicMock(return_value=dom_after_open))
+ return dom_after_open
+
+
+async def _run_emerging_already_open(before: SimpleNamespace, after: SimpleNamespace) -> handler.ActionResult:
+ return await handler.select_from_emerging_elements(
+ current_element_id="anchor-sk",
+ options=handler.CustomSelectPromptOptions(target_value="Alpha"),
+ page=MagicMock(),
+ scraped_page=before,
+ scraped_page_after_open=after,
+ step=SimpleNamespace(step_id="step-1"),
+ task=_task(), # type: ignore[arg-type]
+ engine_selection=None,
+ )
+
+
+class TestAlreadyOpenOwnedListboxRecovery:
+ """SKY-14931: when the combobox is already open, select from its uniquely aria-owned listbox
+ instead of raising no-incremental — and stay fail-closed on closed/ambiguous/empty widgets."""
+
+ @pytest.mark.asyncio
+ async def test_selects_from_already_open_owned_listbox_instead_of_raising(
+ self, monkeypatch: pytest.MonkeyPatch
+ ) -> None:
+ anchor = _already_open_anchor()
+ listbox = _already_open_listbox(
+ options=[_already_open_option("opt-a", "Alpha"), _already_open_option("opt-b", "Beta")]
+ )
+ before, after = _already_open_pages(anchor=anchor, listbox=listbox)
+ _install_dom_after_open(monkeypatch, interactable_ids={"opt-a", "opt-b"})
+ monkeypatch.setattr(handler, "json_to_html", MagicMock(return_value="<li>Alpha</li>"))
+ deterministic = AsyncMock(return_value=(handler.ActionSuccess(), "Alpha"))
+ monkeypatch.setattr(handler, "_select_deterministic_custom_option", deterministic)
+
+ with skyvern_context.scoped(SkyvernContext(tz_info=UTC)):
+ result = await _run_emerging_already_open(before, after)
+
+ assert isinstance(result, handler.ActionSuccess)
+ assert deterministic.await_count == 1
+ candidates = deterministic.await_args.kwargs["get_option_candidates"]()
+ assert {candidate["label"] for candidate in candidates} == {"Alpha", "Beta"}
+
+ @pytest.mark.asyncio
+ async def test_closed_combobox_stays_fail_closed(self, monkeypatch: pytest.MonkeyPatch) -> None:
+ anchor = _already_open_anchor(expanded=False)
+ listbox = _already_open_listbox(options=[_already_open_option("opt-a", "Alpha")])
+ before, after = _already_open_pages(anchor=anchor, listbox=listbox)
+ _install_dom_after_open(monkeypatch, interactable_ids={"opt-a"})
+ deterministic = AsyncMock(return_value=(handler.ActionSuccess(), "Alpha"))
+ monkeypatch.setattr(handler, "_select_deterministic_custom_option", deterministic)
+
+ with (
+ skyvern_context.scoped(SkyvernContext(tz_info=UTC)),
+ pytest.raises(NoIncrementalElementFoundForCustomSelection),
+ ):
+ await _run_emerging_already_open(before, after)
+
+ deterministic.assert_not_awaited()
+
+ @pytest.mark.asyncio
+ async def test_ambiguous_owning_anchor_stays_fail_closed(self, monkeypatch: pytest.MonkeyPatch) -> None:
+ anchor = _already_open_anchor()
+ duplicate_anchor = _already_open_anchor(anchor_sk="anchor-sk-2")
+ listbox = _already_open_listbox(options=[_already_open_option("opt-a", "Alpha")])
+ before, after = _already_open_pages(anchor=anchor, listbox=listbox, extra_elements=[duplicate_anchor])
+ _install_dom_after_open(monkeypatch, interactable_ids={"opt-a"})
+ deterministic = AsyncMock(return_value=(handler.ActionSuccess(), "Alpha"))
+ monkeypatch.setattr(handler, "_select_deterministic_custom_option", deterministic)
+
+ with (
+ skyvern_context.scoped(SkyvernContext(tz_info=UTC)),
+ pytest.raises(NoIncrementalElementFoundForCustomSelection),
+ ):
+ await _run_emerging_already_open(before, after)
+
+ deterministic.assert_not_awaited()
+
+ @pytest.mark.asyncio
+ async def test_empty_owned_listbox_stays_fail_closed(self, monkeypatch: pytest.MonkeyPatch) -> None:
+ anchor = _already_open_anchor()
+ listbox = _already_open_listbox(options=[])
+ before, after = _already_open_pages(anchor=anchor, listbox=listbox)
+ _install_dom_after_open(monkeypatch, interactable_ids=set())
+ deterministic = AsyncMock(return_value=(handler.ActionSuccess(), "Alpha"))
+ monkeypatch.setattr(handler, "_select_deterministic_custom_option", deterministic)
+
+ with (
+ skyvern_context.scoped(SkyvernContext(tz_info=UTC)),
+ pytest.raises(NoIncrementalElementFoundForCustomSelection),
+ ):
+ await _run_emerging_already_open(before, after)
+
+ deterministic.assert_not_awaited()
diff --git a/tests/unit/test_real_browser_state_navigate.py b/tests/unit/test_real_browser_state_navigate.py
index 7f27c76f4..243e1957d 100644
--- a/tests/unit/test_real_browser_state_navigate.py
+++ b/tests/unit/test_real_browser_state_navigate.py
@@ -115,6 +115,29 @@ async def test_navigation_accepts_public_caller_destination(
assert all(thread_id != event_loop_thread for thread_id in resolver_threads)
[email protected]("http_status", [200, 404, 410])
+async def test_navigate_to_url_records_last_navigation_status(
+ browser_state: RealBrowserState,
+ monkeypatch: pytest.MonkeyPatch,
+ http_status: int,
+) -> None:
+ # The Task V3 loop reads last_navigation_status to classify a dead/removed starting URL, so a
+ # navigation must record the final response's HTTP status on the state (not leave it unset).
+ def resolves_public(host: str, port: int | None, *args: object, **kwargs: object) -> list[object]:
+ return [(socket.AF_INET, socket.SOCK_STREAM, 0, "", ("93.184.216.34", port or 0))]
+
+ monkeypatch.setattr("skyvern.utils.url_validators.socket.getaddrinfo", resolves_public)
+ url = "https://public.example.test/path"
+ response = SimpleNamespace(status=http_status, request=SimpleNamespace(url=url, redirected_from=None))
+ page = MagicMock()
+ page.goto = AsyncMock(return_value=response)
+
+ await browser_state.navigate_to_url(page=page, url=url)
+
+ assert browser_state.last_navigation_status == http_status
+
+
@pytest.mark.asyncio
async def test_navigate_to_url_accepts_allowed_loopback_destination(
browser_state: RealBrowserState,
diff --git a/tests/unit/test_taskv3_engine.py b/tests/unit/test_taskv3_engine.py
index 7a7c900c8..862979e8b 100644
--- a/tests/unit/test_taskv3_engine.py
+++ b/tests/unit/test_taskv3_engine.py
@@ -66,6 +66,73 @@ async def test_engine_accepts_first_finish() -> None:
assert outcome.status == "completed" and outcome.turns == 1
+async def test_navigate_through_a_payload_ref_redirect_masks_the_landing_url(monkeypatch: pytest.MonkeyPatch) -> None:
+ """A payload ref that redirects hands its provenance to the landing URL: the real navigate tool
+ derives a ref for it, the engine's context holds the same dict, and the boundary masks it."""
+ import skyvern.utils.url_validators as urlv
+
+ monkeypatch.setattr(urlv, "validate_fetch_url", lambda url: url) # no DNS in unit tests
+ signed = "https://files.example.test/uploads/deadbeef/resume.pdf?token=eyJhbGciOiJIUzI1NiJ9.c2lnbmVk.QQ"
+ landing = "https://cdn.example.test/blob/resume.pdf?X-Amz-Signature=0123456789abcdef0123456789abcdef"
+
+ class _RedirectingPage(_FakePage):
+ async def goto(self, url: str, timeout: int | None = None, wait_until: str | None = None) -> None:
+ await super().goto(url, timeout, wait_until)
+ self.url = landing
+
+ token = mask_opaque_urls({"file": signed}).masked["file"]
+ caller = _ScriptedCaller([[("navigate", {"url": token})], [("finish", {"status": "completed", "reason": "done"})]])
+ ctx = SkyvernContext(task_id="tsk_redirect")
+ skyvern_context.set(ctx)
+ try:
+ await run_task_v3_agent_loop(
+ page_provider=_fixed_page_provider(_RedirectingPage()),
+ llm_caller=caller,
+ goal="g",
+ parameters={"file": signed},
+ )
+ finally:
+ skyvern_context.reset()
+ navigate_message = next(m["content"] for m in caller.message_history if m.get("role") == "tool")
+ assert "0123456789abcdef" not in navigate_message and navigate_message.startswith("navigated to opaque_url_")
+ assert landing in ctx.opaque_url_refs.values()
+
+
+async def test_engine_overwrites_opaque_url_refs_so_a_prior_blocks_refs_never_bleed() -> None:
+ """The masking boundary reads ctx.opaque_url_refs, and one SkyvernContext is shared across every
+ task block in a workflow run. The engine must OVERWRITE that field with the current task's refs —
+ the minted set, or empty when the task mints none — never merge or leave a prior block's stale
+ entry. Otherwise a later block masks a URL to a token only the earlier block's resolver can
+ reverse, which the model then cannot round-trip back through a tool call."""
+ signed = "https://files.example.test/uploads/deadbeef/resume.pdf?token=eyJhbGciOiJIUzI1NiJ9.c2lnbmVk.QQ"
+ ctx = SkyvernContext(task_id="tsk_prior")
+ ctx.opaque_url_refs = {"opaque_url_stale00": "https://old.example.test/x?token=STALE"}
+ skyvern_context.set(ctx)
+ try:
+ await run_task_v3_agent_loop(
+ page_provider=_fixed_page_provider(_FakePage()),
+ llm_caller=_ScriptedCaller([[("finish", {"status": "completed", "reason": "done"})]]),
+ goal="g",
+ parameters={"file": signed},
+ )
+ # Overwritten with exactly this task's refs; the prior block's stale entry is gone.
+ assert ctx.opaque_url_refs == mask_opaque_urls({"file": signed}).refs
+ assert "opaque_url_stale00" not in ctx.opaque_url_refs
+
+ await run_task_v3_agent_loop(
+ page_provider=_fixed_page_provider(_FakePage()),
+ llm_caller=_ScriptedCaller([[("finish", {"status": "completed", "reason": "done"})]]),
+ goal="g",
+ parameters={"first_name": "John"},
+ )
+ # A task that mints no refs resets the field to empty, not the previous task's refs.
+ assert ctx.opaque_url_refs == {}
+ finally:
+ skyvern_context.reset()
+
+
@pytest.mark.asyncio
async def test_engine_terminate_accepted_immediately() -> None:
script = [[("finish", {"status": "terminated", "reason": "CAPTCHA blocks the form"})]]
@@ -752,3 +819,73 @@ async def test_engine_drops_download_hooks_in_page_free_mode(monkeypatch: pytest
assert finish_kwargs["verification_blocker"] is None
assert DOWNLOAD_COMPLETION_GUIDANCE not in loop_kwargs["system_prompt"]
assert DOWNLOAD_REQUIRED_GUIDANCE not in loop_kwargs["system_prompt"]
+
+
[email protected]("page_free", [False, True])
+async def test_engine_system_prompt_carries_the_current_date(monkeypatch: pytest.MonkeyPatch, page_free: bool) -> None:
+ # A relative-date goal ("two weeks from today") is unanswerable without a reference date; the
+ # model was observed typing past dates. The date is computed at assembly, never hardcoded.
+ from datetime import UTC, datetime
+
+ from skyvern.forge.taskv3 import engine as engine_mod
+ from skyvern.forge.taskv3.loop import LoopOutcome
+
+ loop_kwargs: dict[str, Any] = {}
+
+ async def fake_loop(**kwargs: Any) -> LoopOutcome:
+ loop_kwargs.update(kwargs)
+ return LoopOutcome(status="completed", reason="ok")
+
+ monkeypatch.setattr(engine_mod, "run_agent_tool_loop", fake_loop)
+ before = datetime.now(UTC)
+ await run_task_v3_agent_loop(
+ page_provider=_fixed_page_provider(_FakePage()),
+ llm_caller=_ScriptedCaller([]),
+ goal="fill in the date available: two weeks from today",
+ page_free=page_free,
+ )
+ after = datetime.now(UTC)
+ system_prompt = loop_kwargs["system_prompt"]
+ assert any(
+ f"Today's date is {d.strftime('%Y-%m-%d')} ({d.strftime('%A')})" in system_prompt for d in (before, after)
+ ), system_prompt[-300:]
+
+
+async def test_engine_system_prompt_dates_in_the_runs_timezone(monkeypatch: pytest.MonkeyPatch) -> None:
+ # The browser runs in the proxy's timezone (browser_factory sets ctx.tz_info); the stated date
+ # must be that zone's today, or UTC drifts a day ahead of/behind the page every evening.
+ from datetime import UTC, datetime
+ from zoneinfo import ZoneInfo
+
+ from skyvern.forge.taskv3 import engine as engine_mod
+ from skyvern.forge.taskv3.loop import LoopOutcome
+
+ loop_kwargs: dict[str, Any] = {}
+
+ async def fake_loop(**kwargs: Any) -> LoopOutcome:
+ loop_kwargs.update(kwargs)
+ return LoopOutcome(status="completed", reason="ok")
+
+ monkeypatch.setattr(engine_mod, "run_agent_tool_loop", fake_loop)
+ # One of the two extreme zones is always on a different calendar day than UTC.
+ tz = next(
+ z
+ for z in (ZoneInfo("Pacific/Kiritimati"), ZoneInfo("Etc/GMT+12"))
+ if datetime.now(z).date() != datetime.now(UTC).date()
+ )
+ ctx = SkyvernContext(task_id="tsk_tz")
+ ctx.tz_info = tz
+ skyvern_context.set(ctx)
+ try:
+ await run_task_v3_agent_loop(
+ page_provider=_fixed_page_provider(_FakePage()),
+ llm_caller=_ScriptedCaller([]),
+ goal="fill in the date available: two weeks from today",
+ )
+ finally:
+ skyvern_context.reset()
+ system_prompt = loop_kwargs["system_prompt"]
+ assert f"Today's date is {datetime.now(tz).strftime('%Y-%m-%d')}" in system_prompt, system_prompt[-200:]
+ assert f"Today's date is {datetime.now(UTC).strftime('%Y-%m-%d')}" not in system_prompt
diff --git a/tests/unit/test_taskv3_loop.py b/tests/unit/test_taskv3_loop.py
index b4c3cd763..cd303fc38 100644
--- a/tests/unit/test_taskv3_loop.py
+++ b/tests/unit/test_taskv3_loop.py
@@ -14,6 +14,7 @@ import hashlib
import json
import random
import time
+from types import SimpleNamespace
from typing import Any
import pytest
@@ -27,6 +28,8 @@ from skyvern.forge.taskv3.loop import (
ACTION_LOOP_REASON_PREFIX,
FAILURE_EVIDENCE_MIN_TOOL_CALLS,
FAILURE_EVIDENCE_MIN_TURNS,
+ NAV_DEAD_END_REASON_PREFIX,
+ NAVIGATION_DEAD_END_STATUSES,
NO_TOOL_CALL_NUDGE,
PERCEPTION_STALL_NUDGE_AFTER,
PERCEPTION_STALL_REASON_PREFIX,
@@ -48,6 +51,7 @@ from skyvern.forge.taskv3.loop import (
make_finish_tool,
run_agent_tool_loop,
)
+from skyvern.forge.taskv3.opaque_refs import mask_opaque_urls
class _ScriptedCaller:
@@ -58,6 +62,12 @@ class _ScriptedCaller:
self.calls = 0
self.message_history: list[dict[str, Any]] = []
self.sent_tools: list[dict[str, Any]] | None = None
+ # Model the real LLMCaller.llm_config the engine dereferences to gate the vision `look` tool.
+ self.llm_config = SimpleNamespace(supports_vision=True)
+ # Per-call record of the transient screenshots= arg the loop passed, and the image-block
+ # count the built request would carry (message_history images + this turn's screenshots).
+ self.screenshots_per_call: list[list[bytes] | None] = []
+ self.image_blocks_per_call: list[int] = []
def supports_tool_choice(self) -> bool:
return True
@@ -72,8 +82,20 @@ class _ScriptedCaller:
use_message_history: bool = False,
raw_response: bool = False,
tool_choice: str | None = None,
+ screenshots: list[bytes] | None = None,
) -> dict[str, Any]:
self.sent_tools = tools
+ self.screenshots_per_call.append(list(screenshots) if screenshots else None)
+ # The built request = the re-seeded transcript plus this turn's transient screenshots. Mirror
+ # llm_messages_builder_with_history: history images (there should be none) + one block per
+ # screenshot appended to a trailing user message.
+ history_images = sum(
+ 1
+ for msg in self.message_history
+ for part in (msg.get("content") if isinstance(msg.get("content"), list) else [])
+ if isinstance(part, dict) and part.get("type") in ("image_url", "image")
+ )
+ self.image_blocks_per_call.append(history_images + (len(screenshots) if screenshots else 0))
turn = self._script[self.calls] if self.calls < len(self._script) else []
self.calls += 1
message: dict[str, Any] = {"content": "reasoning..."}
@@ -145,6 +167,72 @@ async def test_perception_is_on_demand_never_injected() -> None:
assert len(click_calls) == 2
+def _look_tool(sink: list[tuple[str, dict[str, Any]]], *, image: bytes = b"\x89PNG-fake") -> ToolSpec:
+ """A `look`-shaped tool: returns a text legend AND a transient screenshot the loop must show the
+ model on the next call only (never persisted to the transcript)."""
+
+ async def handler(args: dict[str, Any]) -> ToolResult:
+ sink.append(("look", args))
+ return ToolResult.ok("[1] button 'Next'", screenshots=[image])
+
+ return ToolSpec(
+ name="look",
+ description="look",
+ parameters={"type": "object", "properties": {}},
+ handler=handler,
+ compactable=True,
+ )
+
+
+async def test_look_image_is_ephemeral_gone_the_turn_after() -> None:
+ # Operator constraint: the annotated screenshot rides exactly ONE request (the turn after look)
+ # and the request the turn AFTER that carries zero image blocks — the accumulation regression.
+ look_calls: list[tuple[str, dict[str, Any]]] = []
+ click_calls: list[tuple[str, dict[str, Any]]] = []
+ tools = [_look_tool(look_calls), _recording_tool("click", click_calls), make_finish_tool()]
+ script = [
+ [("look", {})], # turn 1: model looks
+ [("click", {"mark": 1})], # turn 2: model acts on what it saw
+ [("finish", {"status": "completed", "reason": "ok"})], # turn 3
+ ]
+ outcome, caller = await _run(script, tools)
+
+ assert outcome.status == "completed"
+ # turn 1 request: no image yet; turn 2 request: the look image; turn 3 request: gone.
+ assert caller.image_blocks_per_call[0] == 0
+ assert caller.image_blocks_per_call[1] == 1
+ assert caller.image_blocks_per_call[2] == 0
+ # The transcript the loop re-seeds each turn never holds an image block.
+ for msg in caller.message_history:
+ content = msg.get("content")
+ if isinstance(content, list):
+ assert all(not (isinstance(p, dict) and p.get("type") in ("image_url", "image")) for p in content)
+
+
+async def test_n_looks_add_exactly_n_images_total() -> None:
+ # Cost law: N looks add exactly N images across the whole run, not N x remaining turns.
+ look_calls: list[tuple[str, dict[str, Any]]] = []
+ click_calls: list[tuple[str, dict[str, Any]]] = []
+ tools = [_look_tool(look_calls), _recording_tool("click", click_calls), make_finish_tool()]
+ script = [
+ [("look", {})],
+ [("click", {"mark": 1})],
+ [("look", {})],
+ [("click", {"mark": 2})],
+ [("finish", {"status": "completed", "reason": "ok"})],
+ ]
+ outcome, caller = await _run(script, tools)
+
+ assert outcome.status == "completed"
+ assert len(look_calls) == 2
+ total_images = sum(len(s) for s in caller.screenshots_per_call if s)
+ assert total_images == 2
+ # And no single request ever carries more than the one image just produced.
+ assert max(caller.image_blocks_per_call) == 1
+
+
@pytest.mark.asyncio
async def test_action_batching_multiple_tool_calls_one_turn() -> None:
click_calls: list[tuple[str, dict[str, Any]]] = []
@@ -232,6 +320,127 @@ async def test_terminal_finish_with_failed_status() -> None:
assert outcome.reason == "blocked by captcha"
+def _navigate_tool(dead_end_status: int | None = None) -> ToolSpec:
+ async def handler(args: dict[str, Any]) -> ToolResult:
+ data: dict[str, Any] = {"page_state_changed": True}
+ if dead_end_status is not None:
+ data["navigation_dead_end"] = dead_end_status
+ return ToolResult.ok("navigated", data=data)
+
+ return ToolSpec(
+ name="navigate",
+ description="navigate",
+ parameters={"type": "object", "properties": {"url": {"type": "string"}}},
+ handler=handler,
+ )
+
+
+async def test_navigate_dead_end_terminates_run() -> None:
+ # A navigate that landed on a dead/removed posting (HTTP 404/410) must end the run as `terminated`,
+ # matching v1 — NOT left to the model's finish choice (which defaults to failed at agent.py).
+ tools = [_navigate_tool(dead_end_status=404), make_finish_tool()]
+ script = [
+ [("navigate", {"url": "https://jobs.example.test/acme/closed"})],
+ [("finish", {"status": "completed", "reason": "should never run"})],
+ ]
+ outcome, _ = await _run(script, tools)
+
+ assert outcome.status == "terminated"
+ assert outcome.reason.startswith(NAV_DEAD_END_REASON_PREFIX)
+
+
+async def test_navigate_without_dead_end_does_not_terminate() -> None:
+ # Anti-over-route: an ordinary navigation (no dead-end signal) must NOT be reclassified — the run
+ # proceeds and finishes on the model's own verdict.
+ tools = [_navigate_tool(dead_end_status=None), make_finish_tool()]
+ script = [
+ [("navigate", {"url": "https://jobs.example.test/acme/123"})],
+ [("finish", {"status": "completed", "reason": "applied"})],
+ ]
+ outcome, _ = await _run(script, tools)
+
+ assert outcome.status == "completed"
+ assert outcome.reason == "applied"
+
+
+async def test_batched_dead_end_then_live_navigate_recovers() -> None:
+ # The system prompt tells the model to batch aggressively. A turn that batches a speculative
+ # navigate that 404s WITH a fallback navigate to a live page must NOT be terminated on the first
+ # of the batch — the fallback runs and the run proceeds to the model's own verdict.
+ live = _navigate_tool(dead_end_status=None)
+ dead = _navigate_tool(dead_end_status=404)
+ tools = [
+ ToolSpec(name="navigate_dead", description="d", parameters=dead.parameters, handler=dead.handler),
+ ToolSpec(name="navigate_live", description="l", parameters=live.parameters, handler=live.handler),
+ make_finish_tool(),
+ ]
+ script = [
+ [("navigate_dead", {"url": "https://jobs.example.test/acme/closed"}), ("navigate_live", {"url": "x"})],
+ [("finish", {"status": "completed", "reason": "applied to the live one"})],
+ ]
+ outcome, _ = await _run(script, tools)
+
+ assert outcome.status == "completed"
+ assert outcome.reason == "applied to the live one"
+
+
[email protected]("status", sorted(NAVIGATION_DEAD_END_STATUSES))
+async def test_initial_navigation_dead_end_terminates_before_loop(status: int) -> None:
+ # The dominant dead-posting case: the task's STARTING url is dead. It is navigated during browser
+ # setup (before this loop), so the model never calls the `navigate` tool — it just observes the dead
+ # page and finishes (defaulting to failed). The loop must classify the pre-loop status and end
+ # `terminated` WITHOUT ever calling the model.
+ outcome, caller = await _run(
+ [[("finish", {"status": "completed", "reason": "should never run"})]],
+ [make_finish_tool()],
+ initial_navigation_status=status,
+ )
+
+ assert outcome.status == "terminated"
+ assert outcome.reason.startswith(NAV_DEAD_END_REASON_PREFIX)
+ assert caller.calls == 0 # short-circuited before the first LLM call — deterministic, not model-driven
+ assert outcome.turns == 0
+
+
[email protected]("status", [None, 200, 302, 401, 403, 429, 500, 503])
+async def test_initial_navigation_non_dead_end_runs_normally(status: int | None) -> None:
+ # Anti-over-route: a reachable/soft/recoverable starting status must NOT short-circuit — the run
+ # proceeds and finishes on the model's own verdict.
+ outcome, caller = await _run(
+ [[("finish", {"status": "completed", "reason": "applied"})]],
+ [make_finish_tool()],
+ initial_navigation_status=status,
+ )
+
+ assert outcome.status == "completed"
+ assert outcome.reason == "applied"
+ assert caller.calls == 1
+
+
+async def test_initial_navigation_dead_end_yields_canceled_when_cancelling() -> None:
+ # A run canceled during setup must persist as `canceled` (and stay unbilled), not be pre-empted
+ # into `terminated` by the pre-loop dead-end fast path — cancellation is checked first, exactly as
+ # the first loop turn would.
+ async def _cancel() -> bool:
+ return True
+
+ outcome, caller = await _run(
+ [[("finish", {"status": "completed", "reason": "x"})]],
+ [make_finish_tool()],
+ initial_navigation_status=404,
+ should_cancel=_cancel,
+ )
+
+ assert outcome.status == "canceled"
+ assert caller.calls == 0
+
+
@pytest.mark.asyncio
async def test_verification_blocker_refuses_completed_but_not_failed() -> None:
async def _blocked() -> str | None:
@@ -3137,6 +3346,95 @@ async def test_model_hidden_secret_values_are_scrubbed_from_the_tool_message_the
assert ctx.model_hidden_values == {hidden_url, hidden_token}
+async def test_payload_signed_urls_are_masked_to_their_token_across_every_tool_result_surface() -> None:
+ """The single model-facing masking boundary: a resolved payload signed URL echoed by ANY tool
+ result — a navigate/select/type success echo AND a handler-raised tool_error — is rewritten to
+ the SAME opaque token the prompt masker minted (masking by PROVENANCE/membership, not shape),
+ while a benign signing-shaped live-page URL that was never in the payload passes through
+ untouched. This subsumes the per-surface masks and covers the surfaces they forgot."""
+ signed = (
+ "https://files.example.test/uploads/a1b2c3d4e5f6/resume.pdf"
+ "?token=eyJhbGciOiJIUzI1NiJ9.c2lnbmVk.Q29ycmVjdEhvcnNlQmF0dGVyeVN0YXBsZTAxMjM0NTY3ODk"
+ )
+ signature_slice = "eyJhbGciOiJIUzI1NiJ9.c2lnbmVk"
+ # A live-page URL that is_signed_url() flags by shape but was never in the payload.
+ benign = "https://jobs.example.test/apply?token=abcdefABCDEF0123456789ghijklMNOPqrstuvwx"
+ # The browser reports a payload URL back canonicalized ("/" path inserted, default port dropped),
+ # which is how the real navigate tool echoes page.url — the boundary must still recognize it.
+ pathless = "https://files.example.test:443?token=eyJhbGciOiJIUzI1NiJ9.cGF0aGxlc3M.Q29ycmVjdEhvcnNl"
+ pathless_browser_form = "https://files.example.test/?token=eyJhbGciOiJIUzI1NiJ9.cGF0aGxlc3M.Q29ycmVjdEhvcnNl"
+
+ refs = mask_opaque_urls({"file": signed, "link": pathless})
+ token = refs.masked["file"]
+ pathless_token = refs.masked["link"]
+
+ async def navigate_handler(_args: dict[str, Any]) -> ToolResult:
+ return ToolResult.ok(f"navigated to {signed}, then {pathless_browser_form}.")
+
+ async def select_handler(_args: dict[str, Any]) -> ToolResult:
+ return ToolResult.error(f"no option matched {signed!r}")
+
+ async def type_handler(_args: dict[str, Any]) -> ToolResult:
+ return ToolResult.ok(f"typed, committed {signed}")
+
+ async def boom_handler(_args: dict[str, Any]) -> ToolResult:
+ raise ValueError(f"download failed for {signed}")
+
+ async def benign_handler(_args: dict[str, Any]) -> ToolResult:
+ return ToolResult.ok(f"you are on {benign} now")
+
+ # A redirect landing URL derived mid-task (navigate) is masked from that moment on.
+ landing = "https://cdn.example.test/blob/resume.pdf?X-Amz-Signature=deadbeefdeadbeefdeadbeefdeadbeef"
+
+ async def redirect_handler(_args: dict[str, Any]) -> ToolResult:
+ refs.derive(landing)
+ return ToolResult.ok(f"navigated to {landing}")
+
+ empty = {"type": "object", "properties": {}}
+ tools = [
+ ToolSpec(name="redirect", description="r", parameters=empty, handler=redirect_handler),
+ ToolSpec(name="navigate", description="n", parameters=empty, handler=navigate_handler),
+ ToolSpec(name="select", description="s", parameters=empty, handler=select_handler),
+ ToolSpec(name="type", description="t", parameters=empty, handler=type_handler),
+ ToolSpec(name="boom", description="b", parameters=empty, handler=boom_handler),
+ ToolSpec(name="benign", description="g", parameters=empty, handler=benign_handler),
+ make_finish_tool(),
+ ]
+ # The loop skips the rest of a batch after a tool errors, so the error/raise surfaces each get
+ # their own turn; the boundary must mask every one regardless of batching.
+ script = [
+ [("navigate", {}), ("type", {}), ("benign", {}), ("redirect", {})],
+ [("select", {})],
+ [("boom", {})],
+ [("finish", {"status": "completed", "reason": "done"})],
+ ]
+
+ ctx = SkyvernContext(task_id="tsk_opaque")
+ ctx.opaque_url_refs = refs.refs
+ skyvern_context.set(ctx)
+ try:
+ outcome, caller = await _run(script, tools)
+ finally:
+ skyvern_context.reset()
+
+ assert outcome.status == "completed"
+ tool_messages = {m["name"]: m["content"] for m in caller.message_history if m.get("role") == "tool"}
+ # The raw signed bytes appear NOWHERE in the model-facing transcript.
+ assert all(signature_slice not in m["content"] for m in caller.message_history if m.get("role") == "tool")
+ assert all("cGF0aGxlc3M" not in m["content"] for m in caller.message_history if m.get("role") == "tool")
+ # Every echoing surface — success and error — shows the SAME token the prompt masker minted.
+ assert tool_messages["navigate"] == f"navigated to {token}, then {pathless_token}."
+ assert token in tool_messages["select"]
+ assert token in tool_messages["type"]
+ assert token in tool_messages["boom"]
+ # A benign signing-shaped live-page URL never in the payload is left intact (membership, not shape).
+ assert tool_messages["benign"] == f"you are on {benign} now"
+ assert "deadbeef" not in tool_messages["redirect"] and tool_messages["redirect"].startswith(
+ "navigated to opaque_url_"
+ )
+
+
@pytest.mark.asyncio
async def test_on_pre_action_fires_before_dispatch_only_for_submit_shaped_actions() -> None:
# The pre-action hook fires BEFORE the handler runs (after it the page may be the confirmation
diff --git a/tests/unit/test_taskv3_opaque_refs.py b/tests/unit/test_taskv3_opaque_refs.py
index fd0bac95d..75037c994 100644
--- a/tests/unit/test_taskv3_opaque_refs.py
+++ b/tests/unit/test_taskv3_opaque_refs.py
@@ -7,6 +7,7 @@ from typing import Any, Callable
import pytest
+from skyvern.forge.sdk.core.skyvern_context import opaque_url_echo_forms, opaque_url_echo_window
from skyvern.forge.taskv3.opaque_refs import is_signed_url, mask_opaque_urls
SIGNED = (
@@ -592,3 +593,165 @@ def test_mask_matches_html_entity_escaped_multiparam_ref() -> None:
masked = refs.mask(page_html)
assert "X-Amz-Signature=" not in masked
assert token in masked
+
+
+ ("payload_url", "browser_form"),
+ [
+ # page.url inserts the "/" path a pathless payload URL omitted.
+ ("https://example.test?token=abcdefghijklmnop0123", "https://example.test/?token=abcdefghijklmnop0123"),
+ # Default port dropped, host lower-cased.
+ ("https://Example.test:443/f?token=abcdefghijklmnop0123", "https://example.test/f?token=abcdefghijklmnop0123"),
+ # Percent-escapes re-cased and a raw space encoded on the way through the browser.
+ (
+ "https://example.test/a%2fb/c d?X-Amz-Signature=abcdef0123456789abcdef0123456789",
+ "https://example.test/a%2Fb/c%20d?X-Amz-Signature=abcdef0123456789abcdef0123456789",
+ ),
+ # Dot segments, raw and percent-encoded, resolved by the URL validator before the browser sees them.
+ ("https://example.test/a/../f?token=abcdefghijklmnop0123", "https://example.test/f?token=abcdefghijklmnop0123"),
+ (
+ "https://example.test/a/%2e%2e/f?token=abcdefghijklmnop0123",
+ "https://example.test/f?token=abcdefghijklmnop0123",
+ ),
+ # An internationalized host is punycoded by the URL validator before the browser sees it.
+ (
+ "https://Bücher.example/f?token=abcdefghijklmnop0123",
+ "https://xn--bcher-kva.example/f?token=abcdefghijklmnop0123",
+ ),
+ # An IPv6 literal host is compressed by the URL validator before the browser sees it.
+ (
+ "https://[2606:4700:4700:0:0:0:0:1111]:443/f?token=abcdefghijklmnop0123",
+ "https://[2606:4700:4700::1111]/f?token=abcdefghijklmnop0123",
+ ),
+ # A query name that is also a legacy HTML entity (&copy) must not be entity-decoded in the raw ref.
+ (
+ "https://Example.test:443/f?token=abcdefghijklmnop0123&copy=x",
+ "https://example.test/f?token=abcdefghijklmnop0123&copy=x",
+ ),
+ # A literal apostrophe is legal in a path and survives the browser unchanged.
+ (
+ "https://Example.test:443/a'b?token=abcdefghijklmnop0123",
+ "https://example.test/a'b?token=abcdefghijklmnop0123",
+ ),
+ # A non-BMP path character is echoed as a 12-character escape: the echo is far longer than the ref.
+ (
+ "https://example.test/" + "\U0001f600" * 50 + "?token=abcdefghijklmnop0123",
+ "https://example.test/" + "%F0%9F%98%80" * 50 + "?token=abcdefghijklmnop0123",
+ ),
+ # Chromium percent-encodes ^ and | in a path where the URL validator keeps them raw.
+ (
+ "https://example.test/a^b|c?token=abcdefghijklmnop0123",
+ "https://example.test/a%5Eb%7Cc?token=abcdefghijklmnop0123",
+ ),
+ # A payload URL that legitimately ends in a punctuation character keeps it through the browser.
+ (
+ "https://Example.test:443/f?token=abcdefghijklmnop0123&name=foo)",
+ "https://example.test/f?token=abcdefghijklmnop0123&name=foo)",
+ ),
+ ],
+)
+def test_mask_matches_browser_normalized_form_of_payload_ref(payload_url: str, browser_form: str) -> None:
+ refs = mask_opaque_urls({"file": payload_url})
+ token = next(iter(refs.refs))
+ assert browser_form != payload_url
+ # Prose read-back with trailing punctuation, as a navigate echo renders it.
+ masked = refs.mask(f"navigated to {browser_form}.")
+ assert masked == f"navigated to {token}."
+ # And inside entity-escaped HTML.
+ assert refs.mask(f'<a href="{browser_form.replace("&", "&amp;")}">x</a>') == f'<a href="{token}">x</a>'
+ # Quoted and possessive prose around the URL is not part of it.
+ assert refs.mask(f"'{browser_form}' then {browser_form}'s page") == f"'{token}' then {token}'s page"
+
+
+def test_echo_window_covers_every_form_the_masker_matches() -> None:
+ url = "https://Example.test:443/\U0001f4c4?token=abcdefghijklmnop0123&x=1"
+ forms = opaque_url_echo_forms(url)
+ canonical = "https://example.test/%F0%9F%93%84?token=abcdefghijklmnop0123&x=1"
+ assert set(forms) == {url, url.replace("&", "&amp;"), canonical, canonical.replace("&", "&amp;")}
+ # Every form is masked whole, and the window is at least as wide as the widest of them.
+ refs = mask_opaque_urls({"file": url})
+ token = next(iter(refs.refs))
+ assert all(refs.mask(f"see {form} now") == f"see {token} now" for form in forms)
+ assert opaque_url_echo_window([url]) >= max(len(form) for form in forms)
+ assert opaque_url_echo_window([]) == 16
+
+
+def test_mask_canonical_match_prefers_the_longer_of_two_refs_that_meet_at_an_apostrophe() -> None:
+ short = "https://Example.test:443/0123456789abcdef0123456789abcdef"
+ refs = mask_opaque_urls({"a": short, "b": short + "'foo?token=abcdefghijklmnop0123"})
+ long_token = refs.masked["b"]
+ echoed = "https://example.test/0123456789abcdef0123456789abcdef'foo?token=abcdefghijklmnop0123"
+ assert refs.mask(f"at {echoed}.") == f"at {long_token}."
+
+
+def test_mask_canonical_match_finds_the_boundary_after_many_apostrophes_inside_a_ref() -> None:
+ refs = mask_opaque_urls({"file": "https://Example.test:443/" + "a'" * 12 + "b?token=abcdefghijklmnop0123"})
+ token = next(iter(refs.refs))
+ browser_form = "https://example.test/" + "a'" * 12 + "b?token=abcdefghijklmnop0123"
+ assert refs.mask(f"{browser_form}'s page") == f"{token}'s page"
+
+
+def test_mask_canonical_match_covers_every_ref_in_one_apostrophe_joined_span() -> None:
+ refs = mask_opaque_urls(
+ {
+ "a": "https://Example.test:443/p1?token=abcdefghijklmnop0123",
+ "b": "https://Example.test:443/p2?token=abcdefghijklmnop0124",
+ }
+ )
+ token_a, token_b = (
+ (t for t, u in refs.refs.items() if u.endswith("0123")),
+ (t for t, u in refs.refs.items() if u.endswith("0124")),
+ )
+ token_a, token_b = next(token_a), next(token_b)
+ a, b = "https://example.test/p1?token=abcdefghijklmnop0123", "https://example.test/p2?token=abcdefghijklmnop0124"
+ # Two refs joined by a bare quote are still each masked.
+ assert refs.mask(f"'{a}','{b}'") == f"'{token_a}','{token_b}'"
+
+
+def test_mask_canonical_match_is_bounded_on_long_punctuation_runs() -> None:
+ refs = mask_opaque_urls({"file": "https://Example.test:443/f?token=abcdefghijklmnop0123"})
+ token = next(iter(refs.refs))
+ run = "." * 50_000
+ started = time.perf_counter()
+ assert refs.mask(f"at https://example.test/f?token=abcdefghijklmnop0123{run}") == f"at {token}{run}"
+ assert time.perf_counter() - started < 2.0
+
+
+def test_mask_canonical_match_handles_thousands_of_quote_glued_copies_iteratively() -> None:
+ refs = mask_opaque_urls({"file": "https://Example.test:443/f?token=abcdefghijklmnop0123"})
+ token = next(iter(refs.refs))
+ echoed = "https://example.test/f?token=abcdefghijklmnop0123"
+
+ def timed(copies: int) -> float:
+ started = time.perf_counter()
+ assert refs.mask("'".join([echoed] * copies)) == "'".join([token] * copies)
+ return time.perf_counter() - started
+
+ # Linear, not quadratic: four times the copies costs well under sixteen times the work.
+ assert timed(4000) < 6 * max(timed(1000), 0.005)
+
+
+def test_mask_canonical_match_is_still_by_membership() -> None:
+ refs = mask_opaque_urls({"file": "https://example.test?token=abcdefghijklmnop0123"})
+ # Same host and shape, different credential: not ours, so not masked.
+ prose = "now at https://example.test/?token=abcdefghijklmnop0124"
+ assert refs.mask(prose) == prose
+ # A ref that ends in punctuation is not the same resource as the live URL without it.
+ refs = mask_opaque_urls({"file": "https://example.test/f?token=abcdefghijklmnop0123&n=foo)"})
+ prose = "now at https://example.test/f?token=abcdefghijklmnop0123&n=foo."
+ assert refs.mask(prose) == prose
+
+
+def test_mask_canonical_match_keeps_path_delimiter_escapes_distinct() -> None:
+ # A browser never decodes %2F in a path (it is a structural delimiter there), so a payload ref
+ # with an escaped slash and a live URL with a real slash are different resources.
+ refs = mask_opaque_urls({"file": "https://example.test/files%2Fsecret/x?token=abcdefghijklmnop0123"})
+ prose = "at https://example.test/files/secret/x?token=abcdefghijklmnop0123."
+ assert refs.mask(prose) == prose
+ # Case of the escape is still canonical.
+ token = next(iter(refs.refs))
+ assert refs.mask("at https://example.test/files%2fsecret/x?token=abcdefghijklmnop0123.") == f"at {token}."
+ # A query value the browser keeps encoded is a different URL from its decoded spelling.
+ refs = mask_opaque_urls({"file": "https://example.test/f?token=abcdefghijklmnop0123&next=a%2Fb"})
+ prose = "at https://example.test/f?token=abcdefghijklmnop0123&next=a/b."
+ assert refs.mask(prose) == prose
diff --git a/tests/unit/test_taskv3_tools.py b/tests/unit/test_taskv3_tools.py
index 745dbd0e4..d2fb597d5 100644
--- a/tests/unit/test_taskv3_tools.py
+++ b/tests/unit/test_taskv3_tools.py
@@ -13,20 +13,158 @@ import json
import re
import time
from collections.abc import AsyncIterator
+from html import escape as html_escape
from pathlib import Path
+from types import SimpleNamespace
from typing import Any, Awaitable, Callable
import pytest
-from structlog.testing import capture_logs
# Captured at import (before the _fast_upload_settle autouse fixture rebinds the module attr) so the
# delay-specific test can exercise the real function while other upload tests skip the sleep.
-from skyvern.forge.taskv3.tools import PAGE_UNAVAILABLE_ERROR, _is_host_anchored_selector
+from playwright.async_api import Error as _PlaywrightError
+from structlog.testing import capture_logs
+
+from skyvern.forge.taskv3.tools import (
+ NAVIGATION_DEAD_END_STATUSES,
+ PAGE_UNAVAILABLE_ERROR,
+ _annotate_screenshot,
+ _invalid_selector_result,
+ _is_host_anchored_selector,
+ _normalize_selector,
+)
from skyvern.forge.taskv3.tools import _upload_submit_delay as _REAL_UPLOAD_SUBMIT_DELAY
-from skyvern.forge.taskv3.tools import build_browser_tools
+from skyvern.forge.taskv3.tools import (
+ build_browser_tools,
+)
from tests.unit.test_taskv3_loop import _ScriptedCaller
+def test_classify_commit_matrix() -> None:
+ from skyvern.forge.taskv3.tools import CommitStatus, _classify_commit
+
+ S = {"checked": True} # a readable committable post-state
+
+ # INV-2 right to answer: no readable committable post-state -> unverified.
+ assert _classify_commit({"checked": False}, 1, None) == CommitStatus.UNVERIFIED
+ assert _classify_commit({"checked": False}, 1, {"value": None}) == CommitStatus.UNVERIFIED
+ # ...and an unreadable pre-state (with no value-specific truth) is unverified, not a false verdict.
+ assert _classify_commit(None, 1, S) == CommitStatus.UNVERIFIED
+
+ # Widget-agnostic committing direction: any committable field moving is a commit.
+ assert _classify_commit({"checked": False}, 1, {"checked": True}) == CommitStatus.OK
+ assert _classify_commit({"value": "a"}, 1, {"value": "ab"}) == CommitStatus.OK
+ assert _classify_commit({"selected": False}, 1, {"selected": True}) == CommitStatus.OK
+ # No field moved -> did-not-commit.
+ assert _classify_commit({"checked": True}, 1, {"checked": True}) == CommitStatus.DID_NOT_COMMIT
+
+ # INV-1 identity guards the CONFIDENT answer only: a commit read off n != 1 is unverified...
+ assert _classify_commit({"checked": False}, 0, S) == CommitStatus.UNVERIFIED
+ assert _classify_commit({"checked": False}, 2, S) == CommitStatus.UNVERIFIED
+ # ...but a readable did-not-commit is reported whatever n is — only an error halts a batched turn,
+ # and a queued submit must not run on a field the readback says is unfilled.
+ assert _classify_commit({"checked": True}, 2, {"checked": True}) == CommitStatus.DID_NOT_COMMIT
+ assert _classify_commit({"checked": True}, 0, {"checked": True}) == CommitStatus.DID_NOT_COMMIT
+
+ # committed_value overrides the generic rule with a caller's value-specific truth (the typeahead
+ # site, whose token-overlap tolerance lives in JS) under the same ranking.
+ assert _classify_commit(None, 1, S, committed_value=True) == CommitStatus.OK
+ assert _classify_commit(None, 1, S, committed_value=False) == CommitStatus.DID_NOT_COMMIT
+ assert _classify_commit(None, 0, S, committed_value=True) == CommitStatus.UNVERIFIED
+ assert _classify_commit(None, 2, S, committed_value=False) == CommitStatus.DID_NOT_COMMIT
+
+
+def test_match_menu_option_matrix() -> None:
+ from skyvern.forge.taskv3.tools import _match_menu_option
+
+ opts = [
+ {"n": 1, "text": "Analytics"},
+ {"n": 2, "text": "Engineering"},
+ {"n": 3, "text": "People Operations"},
+ ]
+ # Exact normalized match (case/whitespace-insensitive) wins.
+ assert _match_menu_option("Analytics", opts) == 1
+ assert _match_menu_option(" analytics ", opts) == 1
+ assert _match_menu_option("PEOPLE OPERATIONS", opts) == 3
+ # FORWARD token-prefix only: a short observed value matches the fuller option label.
+ assert _match_menu_option("People", opts) == 3
+ eeo = [{"n": 1, "text": "Yes"}, {"n": 2, "text": "No"}, {"n": 3, "text": "Decline to self-identify"}]
+ assert _match_menu_option("Decline", eeo) == 3
+ # REVERSE is refused: a longer value must NOT commit a shorter, more-general option — the fuller row
+ # may simply be unrendered (virtualised list), so committing "People Operations" for a "…Team" value
+ # or "New" for "New York" would be a silent wrong success.
+ assert _match_menu_option("People Operations Team", opts) is None
+ assert _match_menu_option("New York", [{"n": 1, "text": "New"}, {"n": 2, "text": "Newark"}]) is None
+ # CRITICAL: a value that is only an incidental SUBSTRING of an option is NOT matched — "No" is inside
+ # "prefer not to answer" but must never commit the "No" row on a sensitive question.
+ assert _match_menu_option("Prefer not to answer", eeo) is None
+ # ...and an abbreviation that is not a whole-token prefix is not guessed at either.
+ assert _match_menu_option("Eng", opts) is None
+ # Apostrophe/quote folding comes from the shared exact/stem matcher.
+ assert _match_menu_option("Masters Degree", [{"n": 1, "text": "Master's Degree"}, {"n": 2, "text": "PhD"}]) == 1
+ # No match -> None (hand the options back to the model, don't guess).
+ assert _match_menu_option("Legal", opts) is None
+ assert _match_menu_option("", opts) is None
+ # Exact wins even when a token-prefix is otherwise ambiguous: "Yes" is an exact row despite
+ # "Yes, I consent" sharing its first token.
+ yn = [{"n": 1, "text": "Yes"}, {"n": 2, "text": "Yes, I consent"}, {"n": 3, "text": "No"}]
+ assert _match_menu_option("Yes", yn) == 1
+ # Ambiguous forward-prefix with no exact match -> None, never an arbitrary pick.
+ ambiguous = [{"n": 1, "text": "United States Minor"}, {"n": 2, "text": "United States Major"}]
+ assert _match_menu_option("United States", ambiguous) is None
+ # A row missing a usable index is ignored rather than crashing.
+ assert _match_menu_option("Analytics", [{"n": None, "text": "Analytics"}, {"n": 5, "text": "Analytics"}]) == 5
+ # A leading comma token is folded away, so a short value forward-prefix-matches a punctuated label
+ # ("Yes" -> "Yes, I consent") instead of silently missing on the attached comma.
+ punct = [{"n": 1, "text": "Yes, I consent"}, {"n": 2, "text": "No"}]
+ assert _match_menu_option("Yes", punct) == 1
+ # A slash is left intact so a combined single option is NOT prefix-matched by one of its halves.
+ assert _match_menu_option("Yes", [{"n": 1, "text": "Yes/No"}, {"n": 2, "text": "Maybe"}]) is None
+
+
+def test_annotate_screenshot_downscales_and_draws_marks() -> None:
+ import io as _io
+
+ from PIL import Image
+
+ buf = _io.BytesIO()
+ Image.new("RGB", (1600, 900), (0, 0, 0)).save(buf, format="PNG")
+ out = _annotate_screenshot(buf.getvalue(), [{"n": 1, "x": 100, "y": 100, "w": 200, "h": 80}], vw=800)
+ img = Image.open(_io.BytesIO(out)).convert("RGB")
+ # Operator constraint: downscale to ~1024w so the ephemeral image stays cheap.
+ assert img.width == 1024
+ # A red box was drawn on the all-black frame — proves marks are rendered server-side.
+ colors = {c for _, c in img.getcolors(maxcolors=100000) or []}
+ assert any(r > 200 and g < 80 and b < 80 for (r, g, b) in colors)
+
+
+def test_look_tool_gated_on_vision_capability() -> None:
+ async def provider() -> Any:
+ return None
+
+ names_default = {t.name for t in build_browser_tools(provider)}
+ assert "look" in names_default # default: offered
+ names_vision = {t.name for t in build_browser_tools(provider, vision_enabled=True)}
+ assert "look" in names_vision
+ names_blind = {t.name for t in build_browser_tools(provider, vision_enabled=False)}
+ # A non-vision model would drop the screenshot before the request, so look is not advertised.
+ assert "look" not in names_blind
+ # The rest of the toolset is unchanged whether or not look is present.
+ assert names_blind == names_vision - {"look"}
+
+
+def test_annotate_screenshot_no_downscale_when_already_small() -> None:
+ import io as _io
+
+ from PIL import Image
+
+ buf = _io.BytesIO()
+ Image.new("RGB", (640, 480), (0, 0, 0)).save(buf, format="PNG")
+ out = _annotate_screenshot(buf.getvalue(), [{"n": 2, "x": 10, "y": 10, "w": 50, "h": 20}], vw=640)
+ img = Image.open(_io.BytesIO(out)).convert("RGB")
+ assert img.width == 640
+
+
def _has_playwright_browser() -> bool:
try:
from playwright.sync_api import sync_playwright # noqa: PLC0415
@@ -43,9 +181,27 @@ _skip_no_browser = pytest.mark.skipif(
)
+class _FakeRequest:
+ """Minimal stand-in for a Playwright request, exposing the attributes the upload-activity probe
+ reads. Defaults describe an upload-like dispatch (POST xhr)."""
+
+ def __init__(
+ self, method: str = "POST", resource_type: str = "xhr", url: str = "https://api.example.test/upload"
+ ) -> None:
+ self.method = method
+ self.resource_type = resource_type
+ self.url = url
+ self.post_data: str | None = None
+
+
class _FakeElement:
- def __init__(self) -> None:
+ def __init__(self, page: Any = None) -> None:
self.calls: list[tuple[str, Any]] = []
+ self._page = page
+ self._files: list[Any] = []
+ # Default: model an immediate-upload form — attaching a file makes the site dispatch an upload
+ # request, so upload-activity is observed. Tests that need a silent no-op set this False.
+ self.emit_upload_on_set = True
async def inner_html(self) -> str:
return "<div>inner</div>"
@@ -55,13 +211,33 @@ class _FakeElement:
async def set_input_files(self, paths: Any) -> None:
self.calls.append(("set_input_files", paths))
+ self._files = list(paths) if isinstance(paths, (list, tuple)) else [paths]
+ if self._page is not None and self.emit_upload_on_set:
+ self._page._emit_request(_FakeRequest())
+
+ async def evaluate(self, _js: str, _arg: Any = None) -> Any:
+ # The file-input readback the populate check runs after set_input_files.
+ return len(self._files)
class _FakePage:
def __init__(self) -> None:
self.url = "https://example.test/apply"
self.calls: list[tuple[str, dict[str, Any]]] = []
- self.element = _FakeElement()
+ self.element = _FakeElement(self)
+ self._request_listeners: list[Any] = []
+
+ def on(self, event: str, callback: Any) -> None:
+ if event == "request":
+ self._request_listeners.append(callback)
+
+ def remove_listener(self, event: str, callback: Any) -> None:
+ if event == "request" and callback in self._request_listeners:
+ self._request_listeners.remove(callback)
+
+ def _emit_request(self, request: Any) -> None:
+ for cb in list(self._request_listeners):
+ cb(request)
async def eval_on_selector(self, selector: str, js: str) -> str:
# Field-type probe: report a non-typeahead type so legacy tests exercise the plain fill path.
@@ -313,6 +489,161 @@ async def test_navigate_and_wait(monkeypatch: pytest.MonkeyPatch) -> None:
assert any(c[0] == "wait_for_selector" for c in page.calls)
+async def _navigate_status(monkeypatch: pytest.MonkeyPatch, status: int | None) -> Any:
+ import skyvern.utils.url_validators as urlv
+
+ monkeypatch.setattr(urlv, "validate_fetch_url", lambda url: url)
+ page = _FakePage()
+
+ async def _goto(url: str, timeout: int | None = None, wait_until: str | None = None) -> Any:
+ page.url = url
+ page.calls.append(("goto", {"url": url}))
+ return None if status is None else SimpleNamespace(status=status)
+
+ page.goto = _goto # type: ignore[assignment]
+ tools = build_browser_tools(_fixed_page_provider(page))
+ return await _tool(tools, "navigate").handler({"url": "https://jobs.example.test/acme/123"})
+
+
[email protected]("status", sorted(NAVIGATION_DEAD_END_STATUSES))
+async def test_navigate_flags_dead_end_on_hard_404_or_410(monkeypatch: pytest.MonkeyPatch, status: int) -> None:
+ # A genuinely dead/removed posting (HTTP 404/410) is a non-capability dead-end: v1 routes it to
+ # terminated; v3 must surface a deterministic signal the loop maps to terminated rather than
+ # leaving failed/terminated to the model's finish-tool discretion.
+ r = await _navigate_status(monkeypatch, status)
+ assert r.status == "ok"
+ assert (r.data or {}).get("navigation_dead_end") == status
+
+
[email protected]("status", [None, 200, 302, 401, 403, 429, 500, 503])
+async def test_navigate_does_not_flag_dead_end_for_non_dead_statuses(
+ monkeypatch: pytest.MonkeyPatch, status: int | None
+) -> None:
+ # NARROW: only hard "resource does not exist / gone". Auth (401/403), rate-limit (429), transient
+ # server errors (5xx), redirects (3xx) and OK are NOT dead-ends — a real capability failure or a
+ # recoverable condition must stay unflagged so it is never over-routed to terminated.
+ r = await _navigate_status(monkeypatch, status)
+ assert r.status == "ok"
+ assert "navigation_dead_end" not in (r.data or {})
+
+
+def _reload_guard_tools(monkeypatch: pytest.MonkeyPatch, filled: int) -> tuple[Any, list[Any]]:
+ import skyvern.forge.taskv3.tools as tools_module
+ import skyvern.utils.url_validators as urlv
+
+ monkeypatch.setattr(urlv, "validate_fetch_url", lambda url: url)
+
+ async def _filled(_page: Any) -> int:
+ return filled
+
+ monkeypatch.setattr(tools_module, "_count_filled_fields", _filled)
+ page = _FakePage() # page.url == https://example.test/apply
+ return page, build_browser_tools(_fixed_page_provider(page))
+
+
+async def test_navigate_refuses_destructive_same_url_reload_with_filled_state(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ # SKY-15092(A): navigating to the URL we are already on is a full reload that discards in-progress
+ # form state (filled fields, an attached file). It must be refused, not silently reload and wipe
+ # verified-good progress. RED against pre-guard code, which reloaded unconditionally.
+ page, tools = _reload_guard_tools(monkeypatch, filled=2)
+ r = await _tool(tools, "navigate").handler({"url": page.url})
+ assert r.status == "error", r.content
+ assert "discard" in r.content
+ assert not any(c[0] == "goto" for c in page.calls) # never reloaded
+
+
+async def test_navigate_same_url_reload_allowed_on_confirming_repeat(monkeypatch: pytest.MonkeyPatch) -> None:
+ # The guard is recoverable: an intentional reset is honored — a second navigate to the same URL
+ # confirms intent and proceeds.
+ page, tools = _reload_guard_tools(monkeypatch, filled=2)
+ r1 = await _tool(tools, "navigate").handler({"url": page.url})
+ assert r1.status == "error"
+ r2 = await _tool(tools, "navigate").handler({"url": page.url})
+ assert r2.status == "ok", r2.content
+ assert any(c[0] == "goto" for c in page.calls)
+
+
+async def test_navigate_to_a_different_url_is_never_guarded(monkeypatch: pytest.MonkeyPatch) -> None:
+ # NEGATIVE: the guard must not touch normal multi-page navigation — a DIFFERENT url proceeds even
+ # with filled fields on the current page.
+ page, tools = _reload_guard_tools(monkeypatch, filled=5)
+ r = await _tool(tools, "navigate").handler({"url": "https://example.test/apply/step-2"})
+ assert r.status == "ok", r.content
+ assert any(c[0] == "goto" for c in page.calls)
+
+
+async def test_navigate_same_url_reload_with_no_filled_state_proceeds(monkeypatch: pytest.MonkeyPatch) -> None:
+ # Nothing to protect: a same-URL reload of a page with no filled fields proceeds normally.
+ page, tools = _reload_guard_tools(monkeypatch, filled=0)
+ r = await _tool(tools, "navigate").handler({"url": page.url})
+ assert r.status == "ok", r.content
+ assert any(c[0] == "goto" for c in page.calls)
+
+
+async def test_navigate_intervening_navigation_resets_the_confirm(monkeypatch: pytest.MonkeyPatch) -> None:
+ # Leaving the page and returning clears the pending confirm, so a fresh same-URL reload is refused
+ # again rather than silently auto-confirmed by a stale pending from an earlier refusal.
+ page, tools = _reload_guard_tools(monkeypatch, filled=3)
+ same = page.url
+
+ async def nav(url: str) -> Any:
+ return await _tool(tools, "navigate").handler({"url": url})
+
+ assert (await nav(same)).status == "error" # refuse; pending set
+ assert (await nav("https://example.test/other")).status == "ok" # leave; pending cleared
+ assert (await nav(same)).status == "ok" # return (fresh load, different from /other)
+ assert (await nav(same)).status == "error" # reload again → refused fresh, not auto-confirmed
+
+
+async def test_navigate_rerefuses_when_at_risk_state_grew_after_refusal(monkeypatch: pytest.MonkeyPatch) -> None:
+ # A stale confirm must NOT wipe state that GREW after the refusal (e.g. a file attached in between):
+ # the repeat is re-refused because more is now at risk than when the model was first warned.
+ import skyvern.forge.taskv3.tools as tools_module
+ import skyvern.utils.url_validators as urlv
+
+ monkeypatch.setattr(urlv, "validate_fetch_url", lambda url: url)
+ seq = [2, 3] # refusal sees 2 filled fields; the repeat sees 3 (a file was attached in between)
+
+ async def _filled(_page: Any) -> int:
+ return seq.pop(0) if seq else 3
+
+ monkeypatch.setattr(tools_module, "_count_filled_fields", _filled)
+ page = _FakePage()
+ tools = build_browser_tools(_fixed_page_provider(page))
+ assert (await _tool(tools, "navigate").handler({"url": page.url})).status == "error" # filled=2, refuse
+ r2 = await _tool(tools, "navigate").handler({"url": page.url}) # filled=3 > 2 → re-refuse
+ assert r2.status == "error", r2.content
+ assert not any(c[0] == "goto" for c in page.calls) # never reloaded — the grown state is protected
+
+
+@_skip_no_browser
+async def test_filled_state_probe_counts_an_attached_file_input(tmp_path: Any) -> None:
+ # The guard's filled-state oracle MUST count a file input holding a file — the pre-submit form
+ # serializer deliberately does not, and an attached resume is exactly the progress the guard
+ # protects. Real Chromium so files.length reflects a genuine attach.
+ from skyvern.forge.taskv3.tools import _count_filled_fields # noqa: PLC0415
+
+ cv = tmp_path / "cv.pdf"
+ cv.write_bytes(b"%PDF-1.4 cv")
+ async with _content_page('<form><input type="file" id="cv"><input type="text" id="name"></form>') as page:
+ assert await _count_filled_fields(page) == 0
+ await page.set_input_files("#cv", str(cv))
+ assert await _count_filled_fields(page) >= 1
+ await page.fill("#name", "John Doe")
+ assert await _count_filled_fields(page) >= 2
+
+
@pytest.mark.asyncio
async def test_navigate_validates_url_before_goto(monkeypatch: pytest.MonkeyPatch) -> None:
# A model-chosen URL must go through the repo's SSRF/URL validation before page.goto.
@@ -610,34 +941,87 @@ async def test_navigate_resolves_secret_placeholder_before_goto(monkeypatch: pyt
class _TypeaheadFakePage:
"""Fake page for the BEHAVIORAL typeahead path. `evaluate` stands in for the JS suggestion-finder
(_FIND_SUGGESTION_JS, identified by the data-tv3-sugg tag it sets) and the commit-verifier
- (_VERIFY_COMMIT_JS, identified by its `closest` call), so type()/select_combobox control flow can be
+ (_VERIFY_COMMIT_JS, identified by its `noSuggestionList` flag), so type()/select_combobox control flow can be
driven without a real DOM. `field_type` feeds the pre-probe input-type check; `suggestion` is what the
finder returns (None => the page rendered nothing that overlaps the value); `committed` is the value
the verifier reads back after the suggestion is clicked."""
def __init__(
- self, *, field_type: str = "text", suggestion: dict[str, Any] | None = None, committed: str = ""
+ self,
+ *,
+ field_type: str = "text",
+ suggestion: dict[str, Any] | None = None,
+ committed: str | None = "",
+ match_count: int | None = None,
+ reach: str = "",
+ node_name: str = "input",
+ disabled: bool = False,
) -> None:
self._field_type = field_type
self._suggestion = suggestion
self._committed = committed
+ self._match_count = match_count
+ self._reach = reach
+ self._node_name = node_name
+ self._disabled = disabled
self.calls: list[tuple[str, Any]] = []
self.clicked_suggestion = False
+ def locator(self, selector: str) -> Any:
+ # Only modelled when a test sets match_count; otherwise raise so the tool fail-opens to n==1,
+ # exactly as it does when a real page cannot count the selector.
+ if self._match_count is None:
+ raise RuntimeError("locator not modelled")
+
+ class _FakeLocator:
+ def __init__(self, n: int) -> None:
+ self._n = n
+
+ async def count(self) -> int:
+ return self._n
+
+ return _FakeLocator(self._match_count)
+
async def eval_on_selector(self, selector: str, js: str) -> str:
return self._field_type
async def evaluate(self, js: str, arg: Any = None) -> Any:
# Order matters: the verify JS also references data-tv3-sugg (its list-closed check), so match
- # the verifier (identified by its `closest` call) first, then the finder.
- if "closest" in js:
+ # the verifier (identified by its `noSuggestionList` flag) first, then the finder.
+ # The native-vs-custom probe (_SELECT_VISIBILITY_JS, identified by its `proxied` field): reports
+ # the element's nodeName + disabled so select_option can gate native (<select>) vs custom.
+ if "proxied" in js:
+ return {
+ "exists": True,
+ "nodeName": self._node_name,
+ "visible": True,
+ "disabled": self._disabled,
+ "proxied": False,
+ }
+ if "noSuggestionList" in js:
return self._committed
if "data-tv3-sugg" in js:
return self._suggestion
- # The probe-reach question. This fake models a plain light-DOM field, so every check we run
- # against it is genuinely runnable and no claim should be withheld.
+ # The typeable-vs-open-list gate the shared commit path runs before typing. This fake models a
+ # real typeahead <input>, so it is typeable unless its field type is one an <input> cannot type
+ # into — mirroring _ANCHOR_TYPEABLE_JS's NONTEXT set.
+ if "isContentEditable" in js:
+ return self._field_type not in {
+ "checkbox",
+ "radio",
+ "button",
+ "submit",
+ "reset",
+ "file",
+ "image",
+ "range",
+ "color",
+ "hidden",
+ }
+ # The probe-reach question. Defaults to "" (a plain light-DOM field, every check runnable, no
+ # claim withheld); a test sets reach="component"/"unprobeable" to model a field the check cannot reach.
if "'unprobeable'" in js:
- return ""
+ return self._reach
return None
async def click(self, selector: str, timeout: int | None = None) -> None:
@@ -654,6 +1038,16 @@ class _TypeaheadFakePage:
async def press(self, selector: str, key: str) -> None:
self.calls.append(("press", (selector, key)))
+ async def select_option(
+ self,
+ selector: str,
+ label: str | None = None,
+ value: str | None = None,
+ timeout: int | None = None,
+ force: bool = False,
+ ) -> None:
+ self.calls.append(("select_option", {"selector": selector, "label": label, "value": value}))
+
async def _instant_sleep(*_a: Any, **_k: Any) -> None:
return None
@@ -731,6 +1125,156 @@ async def test_select_combobox_fails_loud_when_no_suggestion_reacts(monkeypatch:
assert r.status == "error" and "NOT filled" in r.content
+async def test_type_typeahead_that_remounts_after_commit_is_unverified_not_a_false_error(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ # INV-1: after the suggestion is clicked the field re-resolves to n!=1 (the widget remounted or
+ # removed its input), so there is no stable element to read the commit off. That is ok-unverified —
+ # a false "did not commit — NOT filled" would halt the batch on a field that may well have committed.
+ import asyncio as _a
+
+ monkeypatch.setattr(_a, "sleep", _instant_sleep)
+ page = _TypeaheadFakePage(
+ field_type="text", suggestion={"text": "Lisbon", "score": 2}, committed=None, match_count=0
+ )
+ tools = build_browser_tools(_fixed_page_provider(page))
+ r = await _tool(tools, "type").handler({"selector": "#city", "text": "Lisbon"})
+ assert page.clicked_suggestion
+ assert r.status == "ok", r.content
+ assert "re-resolved to 0 elements" in r.content, r.content
+ assert "NOT filled" not in r.content, r.content
+
+
+async def test_select_combobox_that_remounts_after_commit_is_unverified_not_a_false_error(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ # INV-1 for the explicit-combobox consumer: same remount, same soft verdict — not a false hard error.
+ import asyncio as _a
+
+ monkeypatch.setattr(_a, "sleep", _instant_sleep)
+ page = _TypeaheadFakePage(
+ field_type="text", suggestion={"text": "Lisbon", "score": 2}, committed=None, match_count=0
+ )
+ tools = build_browser_tools(_fixed_page_provider(page))
+ r = await _tool(tools, "select_combobox").handler({"selector": "#city", "value": "Lisbon"})
+ assert page.clicked_suggestion
+ assert r.status == "ok", r.content
+ assert "re-resolved to 0 elements" in r.content, r.content
+ assert "did not commit" not in r.content, r.content
+
+
+async def test_type_readable_empty_field_is_a_hard_error_even_inside_a_component(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ # Readability (INV-2) and commit are separate dimensions: a field that reads back EMPTY was readable,
+ # so it did-not-commit (hard error), even when the reach probe would soften an UNREADABLE field in the
+ # same component. Guards the split — collapsing "read empty" into "unreadable" would soften a rejected
+ # required field to ok-unverified and let a batch proceed on an empty field.
+ import asyncio as _a
+
+ monkeypatch.setattr(_a, "sleep", _instant_sleep)
+ page = _TypeaheadFakePage(
+ field_type="text", suggestion={"text": "Lisbon", "score": 2}, committed="", match_count=1, reach="component"
+ )
+ tools = build_browser_tools(_fixed_page_provider(page))
+ r = await _tool(tools, "type").handler({"selector": "#city", "text": "Lisbon"})
+ assert page.clicked_suggestion
+ assert r.status == "error", r.content
+ assert "NOT filled" in r.content, r.content
+ assert "could not be verified" not in r.content, r.content
+
+
+async def test_type_readable_empty_field_that_re_resolves_ambiguously_is_still_a_hard_error(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ # A readback that positively reads the field EMPTY outranks INV-1: the field is known unfilled, and
+ # only an error halts the rest of a batched turn (a queued submit must not run on it). n != 1 may
+ # soften a confident commit to "re-observe", never a did-not-commit to ok.
+ import asyncio as _a
+
+ monkeypatch.setattr(_a, "sleep", _instant_sleep)
+ page = _TypeaheadFakePage(field_type="text", suggestion={"text": "Lisbon", "score": 2}, committed="", match_count=2)
+ tools = build_browser_tools(_fixed_page_provider(page))
+ r = await _tool(tools, "type").handler({"selector": "#city", "text": "Lisbon"})
+ assert page.clicked_suggestion
+ assert r.status == "error", r.content
+ assert "NOT filled" in r.content, r.content
+ assert "could not be verified" not in r.content, r.content
+
+
+async def test_select_combobox_readable_empty_field_that_re_resolves_ambiguously_is_still_a_hard_error(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ # Same fail-closed ranking at the explicit-combobox site branch, which `type` does not exercise.
+ import asyncio as _a
+
+ monkeypatch.setattr(_a, "sleep", _instant_sleep)
+ page = _TypeaheadFakePage(field_type="text", suggestion={"text": "Lisbon", "score": 2}, committed="", match_count=2)
+ tools = build_browser_tools(_fixed_page_provider(page))
+ r = await _tool(tools, "select_combobox").handler({"selector": "#city", "value": "Lisbon"})
+ assert page.clicked_suggestion
+ assert r.status == "error", r.content
+ assert "did not commit" in r.content, r.content
+ assert "could not be verified" not in r.content, r.content
+
+
+async def test_select_option_diverts_custom_combobox_to_shared_commit(monkeypatch: pytest.MonkeyPatch) -> None:
+ # A non-<select> target (nodeName != 'select') must route into the shared commit path — type +
+ # click the suggestion — and NOT call page.select_option (which would throw on a custom combobox).
+ import asyncio as _a
+
+ monkeypatch.setattr(_a, "sleep", _instant_sleep)
+ page = _TypeaheadFakePage(
+ field_type="text",
+ node_name="input",
+ suggestion={"text": "Analytics", "score": 2},
+ committed="Analytics",
+ match_count=1,
+ )
+ tools = build_browser_tools(_fixed_page_provider(page))
+ r = await _tool(tools, "select_option").handler({"selector": "#dept", "label": "Analytics"})
+ assert r.status == "ok", r.content
+ assert page.clicked_suggestion # committed via the typeahead path
+ assert not any(c[0] == "select_option" for c in page.calls) # never hit the native <select> API
+
+
+async def test_select_option_native_select_uses_native_path(monkeypatch: pytest.MonkeyPatch) -> None:
+ # A real <select> (nodeName == 'select') keeps the native path — dispatch page.select_option, no typing.
+ import asyncio as _a
+
+ monkeypatch.setattr(_a, "sleep", _instant_sleep)
+ page = _TypeaheadFakePage(node_name="select", suggestion={"text": "United States", "score": 2})
+ tools = build_browser_tools(_fixed_page_provider(page))
+ r = await _tool(tools, "select_option").handler({"selector": "#country", "label": "United States"})
+ assert r.status == "ok", r.content
+ assert ("select_option", {"selector": "#country", "label": "United States", "value": None}) in page.calls
+ assert not page.clicked_suggestion
+
+
+async def test_select_option_disabled_custom_combobox_reports_disabled(monkeypatch: pytest.MonkeyPatch) -> None:
+ # A disabled control is refused with the accurate "is disabled" message BEFORE the custom divert —
+ # not the typeable-gate refusal, and nothing is typed.
+ import asyncio as _a
+
+ monkeypatch.setattr(_a, "sleep", _instant_sleep)
+ page = _TypeaheadFakePage(
+ field_type="text", node_name="input", disabled=True, suggestion={"text": "Analytics", "score": 2}
+ )
+ tools = build_browser_tools(_fixed_page_provider(page))
+ r = await _tool(tools, "select_option").handler({"selector": "#dept", "label": "Analytics"})
+ assert r.status == "error", r.content
+ assert "disabled" in r.content, r.content
+ assert not page.clicked_suggestion
+
+
# --- DOM-level tests: exercise the REAL finder/pre-snapshot JS against a live page, so the safeguards
# (reaction-gate, container-vs-row, nav-exclusion) are actually executed, not mocked by a fake page. ---
@@ -3282,6 +3826,40 @@ async def test_download_signal_survives_compaction_end_to_end_through_loop(tmp_p
assert any("Downloaded: report.pdf" in m["content"] for m in observe_msgs) # notice survives on a live message
+async def test_navigate_dead_end_terminates_run_through_real_handler(monkeypatch: pytest.MonkeyPatch) -> None:
+ # End-to-end through the REAL navigate handler and the REAL loop (not a fake tool): a model-issued
+ # navigate that lands on a hard 404 must end the run `terminated`, even though the model then tries
+ # to finish `completed`. Reverting the tools.py dead-end flag makes this go `completed` (RED).
+ import skyvern.utils.url_validators as urlv
+ from skyvern.forge.taskv3.loop import make_finish_tool, run_agent_tool_loop
+
+ monkeypatch.setattr(urlv, "validate_fetch_url", lambda url: url)
+ page = _FakePage()
+
+ async def _goto(url: str, timeout: int | None = None, wait_until: str | None = None) -> Any:
+ page.url = url
+ page.calls.append(("goto", {"url": url}))
+ return SimpleNamespace(status=404)
+
+ page.goto = _goto # type: ignore[assignment]
+ all_tools = build_browser_tools(_fixed_page_provider(page)) + [make_finish_tool()]
+ script = [
+ [("navigate", {"url": "https://jobs.example.test/acme/closed"})],
+ [("finish", {"status": "completed", "reason": "should not win"})],
+ ]
+ outcome = await run_agent_tool_loop(
+ llm_caller=_ScriptedCaller(script),
+ system_prompt="sys",
+ user_prompt="goal",
+ tools=all_tools,
+ max_turns=10,
+ max_tool_calls=20,
+ )
+
+ assert outcome.status == "terminated"
+
+
# --- Commit-verified click-open dropdown selection. The staging specimen: a click-open
# filter popover that toggles open/closed on trigger clicks and REMOUNTS its option nodes each open,
# so ids from a prior observe go stale and every toggle click returns an uninformative ok. The click
@@ -4138,30 +4716,296 @@ async def test_dom_a_radiogroup_category_reports_its_children_and_the_leaf_commi
assert await page.evaluate("() => window.__commits") == 1
+_REVEAL_HIDDEN_MENU_FIXTURE_HTML = """
+<!doctype html><html><body style="margin:0">
+ <div id="trigger" tabindex="0"
+ style="position:absolute;top:40px;left:40px;width:320px;height:28px;border:1px solid #888">Choose one</div>
+ <script>
+ window.__commits = 0;
+ var CATS = {'Referral': ['Current employee', 'Former employee'], 'Event': ['Career fair', 'Conference']};
+ var ROW = 'min-height:26px;padding:2px 6px;';
+ document.getElementById('trigger').addEventListener('click', function () {
+ var ex = document.getElementById('list');
+ if (ex) { ex.remove(); return; }
+ var list = document.createElement('div');
+ list.id = 'list';
+ list.setAttribute('style', 'position:absolute;top:74px;left:40px;width:320px;background:#fff;border:1px solid #ccc');
+ Object.keys(CATS).forEach(function (name) {
+ var row = document.createElement('div');
+ row.setAttribute('role', 'option');
+ row.setAttribute('aria-haspopup', 'true');
+ row.setAttribute('style', ROW);
+ row.appendChild(document.createTextNode(name));
+ var kids = [];
+ CATS[name].forEach(function (k) {
+ var kid = document.createElement('div');
+ kid.setAttribute('role', 'option');
+ kid.setAttribute('aria-checked', 'false');
+ // Pre-exists as a DOM DESCENDANT of the category row, hidden until the row is clicked.
+ kid.setAttribute('style', ROW + 'padding-left:18px;display:none');
+ kid.textContent = k;
+ kid.addEventListener('click', function (ev) {
+ ev.stopPropagation();
+ kid.setAttribute('aria-checked', 'true');
+ window.__commits++;
+ });
+ row.appendChild(kid);
+ kids.push(kid);
+ });
+ row.addEventListener('click', function (ev) {
+ ev.stopPropagation();
+ if (kids[0].style.display !== 'none') return; // already expanded
+ // Reveal the pre-existing hidden descendants; the category itself commits nothing.
+ kids.forEach(function (x) { x.setAttribute('style', ROW + 'padding-left:18px;display:block'); });
+ });
+ list.appendChild(row);
+ });
+ document.body.appendChild(list);
+ });
+ </script>
+</body></html>
+"""
+
+
@_skip_no_browser
@pytest.mark.asyncio
-async def test_dom_a_real_commit_survives_the_click_also_revealing_more_rows() -> None:
- # A row can commit AND reveal dependent options in one click. The selection attribute settles
- # it, so the commit must still be reported -- reading the new rows as "this only expanded"
- # would swallow a selection that really happened.
- async with _role_menu_page() as page:
- await page.evaluate("() => { window.__revealOnPick = 1; }")
+async def test_dom_a_category_revealing_pre_existing_hidden_children_reports_them_not_a_false_commit() -> None:
+ # SKY-14741 click-channel fix: a category whose leaf rows PRE-EXIST as hidden DESCENDANTS and are
+ # revealed (display:none->block) on click commits nothing, so the click must report the revealed
+ # children rather than a false "Selected option 'Referral'". RED today: _grew keys on child-count,
+ # which is unchanged by a display-only reveal, so the state change reads as a commit.
+ async with _live_page(_REVEAL_HIDDEN_MENU_FIXTURE_HTML) as page:
tools = build_browser_tools(_fixed_page_provider(page))
click = _tool(tools, "click")
- assert "opened a menu of 4 options" in (await click.handler({"selector": "#trigger"})).content
- r = await click.handler({"selector": '[data-tv3-menu="2"]'})
- assert r.status == "ok"
- assert "Selected option 'Job board' — its state changed (the menu stayed open)." in r.content
- assert "opened a menu of" not in r.content
- assert await page.evaluate("() => window.__commits") == 1
+ assert "opened a menu of 2 options" in (await click.handler({"selector": "#trigger"})).content
+ r2 = await click.handler({"selector": '[data-tv3-menu="1"]'})
+ assert await page.evaluate("() => window.__commits") == 0, r2.content
+ assert "opened a menu of 2 options" in r2.content, r2.content
+ assert "Current employee" in r2.content and "Former employee" in r2.content, r2.content
+ r3 = await click.handler({"selector": '[data-tv3-menu="1"]'})
+ assert r3.status == "ok", r3.content
+ assert await page.evaluate("() => window.__commits") == 1, r3.content
-@_skip_no_browser
-async def test_dom_hover_marking_a_row_selected_is_not_read_as_the_click_committing() -> None:
- # Playwright hovers before it clicks, so a row the widget marks aria-selected on hover would
- # otherwise hand the commit check a selection that the click did not make -- and a parent that
- # only expanded would report a commit instead of its child rows.
+_REVEAL_HIDDEN_ABSOLUTE_FIXTURE_HTML = """
+<!doctype html><html><body style="margin:0">
+ <div id="trigger" tabindex="0"
+ style="position:absolute;top:40px;left:40px;width:320px;height:28px;border:1px solid #888">Choose one</div>
+ <script>
+ window.__commits = 0;
+ var CATS = {'Referral': ['Current employee', 'Former employee'], 'Event': ['Career fair', 'Conference']};
+ document.getElementById('trigger').addEventListener('click', function () {
+ var ex = document.getElementById('list');
+ if (ex) { ex.remove(); return; }
+ var list = document.createElement('div');
+ list.id = 'list';
+ list.setAttribute('style', 'position:absolute;top:74px;left:40px;width:320px;background:#fff;border:1px solid #ccc');
+ var top = 120;
+ Object.keys(CATS).forEach(function (name) {
+ var row = document.createElement('div');
+ row.setAttribute('role', 'option');
+ row.setAttribute('aria-haspopup', 'true');
+ row.setAttribute('style', 'position:relative;height:26px;padding:2px 6px;');
+ row.appendChild(document.createTextNode(name));
+ var kids = [];
+ CATS[name].forEach(function (k, i) {
+ var kid = document.createElement('div');
+ kid.setAttribute('role', 'option');
+ kid.setAttribute('aria-checked', 'false');
+ // Descendant of the row, but rendered OUT OF FLOW (absolute) — revealing it does not change
+ // the row's own height or child count, so only the visible-descendant-row signal moves.
+ kid.setAttribute('style', 'position:absolute;left:400px;top:' + (i * 24) + 'px;width:200px;height:22px;display:none');
+ kid.textContent = k;
+ kid.addEventListener('click', function (ev) {
+ ev.stopPropagation();
+ kid.setAttribute('aria-checked', 'true');
+ window.__commits++;
+ });
+ row.appendChild(kid);
+ kids.push(kid);
+ });
+ row.addEventListener('click', function (ev) {
+ ev.stopPropagation();
+ if (kids[0].style.display !== 'none') return;
+ kids.forEach(function (x, i) {
+ x.setAttribute('style', 'position:absolute;left:400px;top:' + (i * 24) + 'px;width:200px;height:22px;display:block');
+ });
+ });
+ list.appendChild(row);
+ top += 30;
+ });
+ document.body.appendChild(list);
+ });
+ </script>
+</body></html>
+"""
+
+
+@_skip_no_browser
+async def test_dom_a_category_revealing_out_of_flow_hidden_children_reports_them_not_a_false_commit() -> None:
+ # Pins the visible-descendant-row (optVis) signal specifically: the leaves are DESCENDANTS of the
+ # clicked row but rendered position:absolute, so revealing them leaves the row's own height and
+ # child count unchanged — only the count of visible descendant rows rises. Deleting optVis reds this
+ # (height/child-count alone cannot see the expansion) while the in-flow test above stays green.
+ async with _live_page(_REVEAL_HIDDEN_ABSOLUTE_FIXTURE_HTML) as page:
+ tools = build_browser_tools(_fixed_page_provider(page))
+ click = _tool(tools, "click")
+ assert "opened a menu of 2 options" in (await click.handler({"selector": "#trigger"})).content
+ r2 = await click.handler({"selector": '[data-tv3-menu="1"]'})
+ assert await page.evaluate("() => window.__commits") == 0, r2.content
+ assert "opened a menu of 2 options" in r2.content, r2.content
+ assert "Current employee" in r2.content and "Former employee" in r2.content, r2.content
+
+
+_HOVER_REVEAL_COMMIT_FIXTURE_HTML = """
+<!doctype html><html><head><style>
+ .kids { display: none; }
+ .cat:hover .kids { display: block; }
+</style></head><body style="margin:0">
+ <div id="trigger" tabindex="0"
+ style="position:absolute;top:40px;left:40px;width:320px;height:28px;border:1px solid #888">Choose one</div>
+ <script>
+ window.__commits = 0;
+ document.getElementById('trigger').addEventListener('click', function () {
+ var ex = document.getElementById('list');
+ if (ex) { ex.remove(); return; }
+ var list = document.createElement('div');
+ list.id = 'list';
+ list.setAttribute('style', 'position:absolute;top:74px;left:40px;width:320px;background:#fff;border:1px solid #ccc');
+ ['Benefits', 'Payroll'].forEach(function (name) {
+ var row = document.createElement('div');
+ row.className = 'cat';
+ row.setAttribute('role', 'option');
+ row.setAttribute('aria-checked', 'false');
+ row.setAttribute('style', 'min-height:26px;padding:2px 6px;');
+ row.appendChild(document.createTextNode(name));
+ var kids = document.createElement('div');
+ kids.className = 'kids';
+ ['Preview A', 'Preview B'].forEach(function (k) {
+ var kid = document.createElement('div');
+ kid.setAttribute('role', 'option');
+ kid.setAttribute('style', 'min-height:22px');
+ kid.textContent = k;
+ kids.appendChild(kid);
+ });
+ row.appendChild(kids);
+ // Commits on click; the descendants only appear on :hover, which Playwright does before the click.
+ row.addEventListener('click', function (ev) {
+ ev.stopPropagation();
+ row.setAttribute('aria-checked', 'true');
+ window.__commits++;
+ });
+ list.appendChild(row);
+ });
+ document.body.appendChild(list);
+ });
+ </script>
+</body></html>
+"""
+
+
+@_skip_no_browser
+async def test_dom_a_commit_whose_hover_reveals_a_preview_is_still_a_commit_not_a_menu() -> None:
+ # A row that COMMITS on click but reveals descendant rows on CSS :hover (Playwright hovers before it
+ # clicks) must report the commit, not a fabricated "opened a menu": the hover-revealed rows are the
+ # hover's doing and are re-baselined out. RED if optVis is missing from the hover re-baseline tuple,
+ # where the pre-hover optVis=0 baseline would make the still-hovered reveal read as a click expansion.
+ async with _live_page(_HOVER_REVEAL_COMMIT_FIXTURE_HTML) as page:
+ tools = build_browser_tools(_fixed_page_provider(page))
+ click = _tool(tools, "click")
+ assert "opened a menu of 2 options" in (await click.handler({"selector": "#trigger"})).content
+ r2 = await click.handler({"selector": '[data-tv3-menu="1"]'})
+ assert await page.evaluate("() => window.__commits") == 1, r2.content
+ assert "opened a menu" not in r2.content, r2.content
+
+
+_REVEAL_HIDDEN_CHECKBOX_FIXTURE_HTML = """
+<!doctype html><html><body style="margin:0">
+ <div id="trigger" tabindex="0"
+ style="position:absolute;top:40px;left:40px;width:320px;height:28px;border:1px solid #888">Choose one</div>
+ <script>
+ window.__commits = 0;
+ var CATS = {'Referral': ['Current employee', 'Former employee'], 'Event': ['Career fair', 'Conference']};
+ document.getElementById('trigger').addEventListener('click', function () {
+ var ex = document.getElementById('list');
+ if (ex) { ex.remove(); return; }
+ var list = document.createElement('div');
+ list.id = 'list';
+ list.setAttribute('style', 'position:absolute;top:74px;left:40px;width:320px;background:#fff;border:1px solid #ccc');
+ Object.keys(CATS).forEach(function (name) {
+ var row = document.createElement('div');
+ row.setAttribute('role', 'option');
+ row.setAttribute('aria-haspopup', 'true');
+ row.setAttribute('style', 'position:relative;height:26px;padding:2px 6px;');
+ row.appendChild(document.createTextNode(name));
+ var kids = [];
+ CATS[name].forEach(function (k, i) {
+ var kid = document.createElement('div');
+ kid.setAttribute('role', 'checkbox'); // multi-select leaf; not in the pre-fix optVis role set
+ kid.setAttribute('aria-checked', 'false');
+ kid.setAttribute('style', 'position:absolute;left:400px;top:' + (i * 24) + 'px;width:200px;height:22px;display:none');
+ kid.textContent = k;
+ row.appendChild(kid);
+ kids.push(kid);
+ });
+ row.addEventListener('click', function (ev) {
+ ev.stopPropagation();
+ if (kids[0].style.display !== 'none') return;
+ kids.forEach(function (x, i) {
+ x.setAttribute('style', 'position:absolute;left:400px;top:' + (i * 24) + 'px;width:200px;height:22px;display:block');
+ });
+ });
+ list.appendChild(row);
+ });
+ document.body.appendChild(list);
+ });
+ </script>
+</body></html>
+"""
+
+
+@_skip_no_browser
+async def test_dom_a_category_revealing_out_of_flow_checkbox_children_reports_them() -> None:
+ # The reveal signal must use the same row roles the menu finder reports on: a multi-select category
+ # whose leaves are role=checkbox, revealed out of flow, must still be reported (not a false commit).
+ # RED before _visRows was widened from {option,menuitem,treeitem,row} to the full menu-row role set.
+ async with _live_page(_REVEAL_HIDDEN_CHECKBOX_FIXTURE_HTML) as page:
+ tools = build_browser_tools(_fixed_page_provider(page))
+ click = _tool(tools, "click")
+ assert "opened a menu of 2 options" in (await click.handler({"selector": "#trigger"})).content
+ r2 = await click.handler({"selector": '[data-tv3-menu="1"]'})
+ assert await page.evaluate("() => window.__commits") == 0, r2.content
+ assert "opened a menu of 2 options" in r2.content, r2.content
+ assert "Current employee" in r2.content and "Former employee" in r2.content, r2.content
+
+
+@_skip_no_browser
+async def test_dom_a_real_commit_survives_the_click_also_revealing_more_rows() -> None:
+ # A row can commit AND reveal dependent options in one click. The selection attribute settles
+ # it, so the commit must still be reported -- reading the new rows as "this only expanded"
+ # would swallow a selection that really happened.
+ async with _role_menu_page() as page:
+ await page.evaluate("() => { window.__revealOnPick = 1; }")
+ tools = build_browser_tools(_fixed_page_provider(page))
+ click = _tool(tools, "click")
+ assert "opened a menu of 4 options" in (await click.handler({"selector": "#trigger"})).content
+ r = await click.handler({"selector": '[data-tv3-menu="2"]'})
+ assert r.status == "ok"
+ assert "Selected option 'Job board' — its state changed (the menu stayed open)." in r.content
+ assert "opened a menu of" not in r.content
+ assert await page.evaluate("() => window.__commits") == 1
+
+
+@_skip_no_browser
+async def test_dom_hover_marking_a_row_selected_is_not_read_as_the_click_committing() -> None:
+ # Playwright hovers before it clicks, so a row the widget marks aria-selected on hover would
+ # otherwise hand the commit check a selection that the click did not make -- and a parent that
+ # only expanded would report a commit instead of its child rows.
async with _role_menu_page() as page:
await page.evaluate("() => { window.__ariaOnHover = 1; }")
tools = build_browser_tools(_fixed_page_provider(page))
@@ -4797,6 +5641,53 @@ _HIDDEN_CHECKBOX_REVERTS_HTML = """
"""
+# A change listener that also clones the control makes the selector re-resolve to two elements after
+# the action, so the readback's did-not-commit (or commit) is read off an n != 1 target.
+_HIDDEN_SELECT_REVERTS_AND_CLONES_HTML = """
+<!doctype html><html><body>
+ <label for="country">Country</label>
+ <select id="country" style="display:none">
+ <option value="">Pick</option>
+ <option value="us">United States</option>
+ </select>
+ <script>
+ document.getElementById('country').addEventListener('change', e => {
+ e.target.value = '';
+ e.target.insertAdjacentHTML('afterend', '<select id="country" style="display:none"><option value="">Pick</option></select>');
+ });
+ </script>
+</body></html>
+"""
+
+_HIDDEN_SELECT_COMMITS_AND_CLONES_HTML = """
+<!doctype html><html><body>
+ <label for="country">Country</label>
+ <select id="country" style="display:none">
+ <option value="">Pick</option>
+ <option value="us">United States</option>
+ </select>
+ <script>
+ document.getElementById('country').addEventListener('change', e => {
+ e.target.insertAdjacentHTML('afterend', '<select id="country" style="display:none"><option value="">Pick</option></select>');
+ });
+ </script>
+</body></html>
+"""
+
+_HIDDEN_CHECKBOX_REVERTS_AND_CLONES_HTML = """
+<!doctype html><html><body>
+ <label for="agree" style="display:inline-block;width:200px;height:24px">I agree</label>
+ <input id="agree" type="checkbox" style="position:absolute;width:0;height:0;opacity:0">
+ <script>
+ document.getElementById('agree').addEventListener('change', e => {
+ e.target.checked = false;
+ e.target.insertAdjacentHTML('afterend', '<input id="agree" type="checkbox" style="position:absolute;width:0;height:0;opacity:0">');
+ });
+ </script>
+</body></html>
+"""
+
+
_SHADOW_FIXTURE_HTML = """
<h1 id="posting-title">Software Engineer</h1>
<p id="blurb">This role sits on the platform team, and the posting body runs long enough that the
@@ -6140,6 +7031,32 @@ async def test_select_option_on_hidden_native_select_fails_loud_when_change_does
assert "did NOT commit" in r.content
+@_skip_no_browser
+async def test_select_option_that_reverts_and_re_resolves_ambiguously_still_fails_loud() -> None:
+ # The native select positively reads back unselected, so the did-not-commit error (which halts the
+ # rest of a batched turn) must survive the selector now matching two elements.
+ async with _content_page(_HIDDEN_SELECT_REVERTS_AND_CLONES_HTML) as page:
+ tools = build_browser_tools(_fixed_page_provider(page))
+ r = await _tool(tools, "select_option").handler({"selector": "#country", "label": "United States"})
+ assert await page.locator("#country").count() == 2, "fixture is not armed"
+ assert r.status == "error", r.content
+ assert "did NOT commit" in r.content, r.content
+
+
+@_skip_no_browser
+async def test_select_option_that_commits_but_re_resolves_ambiguously_is_unverified() -> None:
+ # INV-1 downgrades only the confident answer: the value committed, but it was read off one of two
+ # matches, so the result is ok-unverified with a re-observe cue rather than a confident "selected".
+ async with _content_page(_HIDDEN_SELECT_COMMITS_AND_CLONES_HTML) as page:
+ tools = build_browser_tools(_fixed_page_provider(page))
+ r = await _tool(tools, "select_option").handler({"selector": "#country", "label": "United States"})
+ assert await page.locator("#country").count() == 2, "fixture is not armed"
+ assert r.status == "ok", r.content
+ assert "re-resolved to 2 elements" in r.content and "re-observe" in r.content, r.content
+
+
@_skip_no_browser
@pytest.mark.asyncio
async def test_typing_into_a_component_control_does_not_claim_a_check_we_could_not_run() -> None:
@@ -6288,6 +7205,17 @@ async def test_click_on_skinned_checkbox_fails_loud_when_toggle_does_not_commit(
assert "did NOT commit" in r.content
+@_skip_no_browser
+async def test_click_on_skinned_checkbox_that_reverts_and_re_resolves_ambiguously_still_fails_loud() -> None:
+ async with _content_page(_HIDDEN_CHECKBOX_REVERTS_AND_CLONES_HTML) as page:
+ tools = build_browser_tools(_fixed_page_provider(page))
+ r = await _tool(tools, "click").handler({"selector": "#agree"})
+ assert await page.locator("#agree").count() == 2, "fixture is not armed"
+ assert r.status == "error", r.content
+ assert "did NOT commit" in r.content, r.content
+
+
_HIDDEN_NATIVE_EDGES_HTML = """
<!doctype html><html><body>
<label for="state">State</label>
@@ -6389,92 +7317,514 @@ async def test_a_widget_that_unmounts_its_own_input_is_not_called_a_component()
assert r.status == "error" and "NOT filled" in r.content, r
+# --- SKY-14741: no-match error enrichment for drilldown/category typeaheads (RED-first). The rows a
+# leaf is nested under (aria-haspopup + hidden nested children, like a real drilldown menu) are
+# structurally present but never visible-match by text, so the finder correctly returns nothing --
+# today that dead end reports the bare "no autocomplete suggestion matched" string with no hint the
+# visible rows are expandable categories. ---
+
+_TYPEAHEAD_DRILLDOWN_FIXTURE_HTML = """
+<!doctype html><html><body style="margin:0">
+ <input id="reason" type="text" autocomplete="off"
+ style="position:absolute;top:40px;left:40px;width:260px;height:24px">
+ <script>
+ var inp = document.getElementById('reason');
+ var CATEGORIES = [
+ { label: 'Employment', kids: ['Current employee', 'Former employee'] },
+ { label: 'Referral', kids: ['Friend', 'Colleague'] }
+ ];
+ inp.addEventListener('input', function () {
+ var old = document.getElementById('dd');
+ if (old) old.remove();
+ if (!inp.value) return;
+ var dd = document.createElement('div');
+ dd.id = 'dd';
+ dd.setAttribute('style', 'position:absolute;top:70px;left:40px;width:260px;background:#fff');
+ CATEGORIES.forEach(function (cat) {
+ var row = document.createElement('div');
+ row.setAttribute('role', 'option');
+ row.setAttribute('aria-haspopup', 'true');
+ row.setAttribute('style', 'height:26px;display:block');
+ row.textContent = cat.label;
+ cat.kids.forEach(function (k) {
+ var kid = document.createElement('div');
+ kid.setAttribute('role', 'option');
+ kid.textContent = k;
+ // Hidden until the category row is expanded by clicking it, like a real drilldown menu --
+ // present in the DOM for a classifier to see, invisible to the finder's own geometry scan.
+ kid.setAttribute('style', 'display:none');
+ row.appendChild(kid);
+ });
+ dd.appendChild(row);
+ });
+ document.body.appendChild(dd);
+ });
+ </script>
+</body></html>
+"""
+
+
+def _reacting_leaf_list_html(field_id: str, options: list[str]) -> str:
+ # Shared by the no-regression / classifier-precision guards below: a plain typeahead whose
+ # reacting dropdown holds only ordinary leaf rows (role=option, no aria-haspopup, no nested
+ # children) -- never expandable, so the no-match error must stay in its current bare form.
+ opts_js = ", ".join(json.dumps(o) for o in options)
+ return f"""
+<!doctype html><html><body style="margin:0">
+ <input id="{field_id}" type="text" autocomplete="off"
+ style="position:absolute;top:40px;left:40px;width:260px;height:24px">
+ <script>
+ var inp = document.getElementById('{field_id}');
+ var OPTIONS = [{opts_js}];
+ inp.addEventListener('input', function () {{
+ var old = document.getElementById('dd');
+ if (old) old.remove();
+ if (!inp.value) return;
+ var dd = document.createElement('div');
+ dd.id = 'dd';
+ dd.setAttribute('style', 'position:absolute;top:70px;left:40px;width:260px;background:#fff');
+ OPTIONS.forEach(function (t) {{
+ var row = document.createElement('div');
+ row.setAttribute('role', 'option');
+ row.setAttribute('style', 'height:26px;display:block');
+ row.textContent = t;
+ dd.appendChild(row);
+ }});
+ document.body.appendChild(dd);
+ }});
+ </script>
+</body></html>
+"""
+
+
@_skip_no_browser
@pytest.mark.asyncio
-async def test_forced_select_refuses_disabled_select() -> None:
- async with _content_page(_HIDDEN_NATIVE_EDGES_HTML) as page:
+async def test_select_combobox_no_match_enumerates_expandable_categories() -> None:
+ # RED (SKY-14741): "Current employee" exists only inside the hidden, expandable "Employment"
+ # category (aria-haspopup=true + >=2 nested child rows) -- the finder correctly never matches it
+ # by text, so today's bare "no autocomplete suggestion matched" error gives the model no hint the
+ # visible rows are expandable and it blind-clicks until the run dies at budget. This must
+ # eventually enumerate the category rows as clickable [data-tv3-menu="N"] targets.
+ async with _live_page(_TYPEAHEAD_DRILLDOWN_FIXTURE_HTML) as page:
tools = build_browser_tools(_fixed_page_provider(page))
- r = await _tool(tools, "select_option").handler({"selector": "#locked", "label": "A"})
- assert r.status == "error" and "disabled" in r.content
- assert await page.eval_on_selector("#locked", "el => el.value") == ""
+ r = await _tool(tools, "select_combobox").handler({"selector": "#reason", "value": "Current employee"})
+ assert r.status == "error", r.content
+ assert "Employment" in r.content, r.content
+ assert "Referral" in r.content, r.content
+ assert "data-tv3-menu" in r.content, r.content
@_skip_no_browser
@pytest.mark.asyncio
-async def test_an_unreadable_root_is_disclosed_on_the_very_first_observe() -> None:
- # The regression: the throwing root was seen only by the marker gather's catch, which swallowed
- # it, so the first observe minted an unverified marker, disclosed nothing, and the payload
- # changed on turn two of a completely static page. The disclosure now also reaches this page
- # from the post-write resolvesTo, so what is pinned here is the end state — disclosed and
- # byte-stable — not which catch produced it; the gather's own catch is held separately below.
- async with _live_page(
- """<button style="display:block;width:80px;height:20px">Nameless</button>
- <div id="poison" style="display:block;width:40px;height:20px"></div>
- <script>
- var sr = document.getElementById('poison').attachShadow({mode: 'open'});
- sr.innerHTML = '<span>inert</span>';
- sr.querySelectorAll = () => { throw new Error('poisoned'); };
- </script>"""
- ) as page:
+async def test_select_combobox_flat_no_match_error_is_byte_identical_no_regression_guard() -> None:
+ # NO-REGRESSION GUARD, not a RED test -- passes today and must keep passing once the drilldown
+ # enrichment lands: a flat list with zero expandable rows must keep the CURRENT bare no-match
+ # string byte-for-byte (no category enumeration, no data-tv3-menu).
+ async with _live_page(_reacting_leaf_list_html("city", ["Lisbon", "Porto"])) as page:
tools = build_browser_tools(_fixed_page_provider(page))
- first = await _tool(tools, "observe").handler({})
- again = await _tool(tools, "observe").handler({})
- assert "part of this page could not be queried" in first.content, first.content
- assert first.content == again.content, f"static page churned:\n{first.content}\n---\n{again.content}"
+ r = await _tool(tools, "select_combobox").handler({"selector": "#city", "value": "Springfield"})
+ assert r.status == "error", r.content
+ assert r.content == (
+ "no autocomplete suggestion matched 'Springfield' for #city; the field is NOT filled "
+ "— do not assume success or move on as if it were"
+ )
@_skip_no_browser
@pytest.mark.asyncio
-async def test_observe_bounds_hidden_natives_and_points_file_inputs_at_file_upload() -> None:
- async with _content_page(_HIDDEN_NATIVE_EDGES_HTML) as page:
+async def test_select_combobox_no_match_never_reports_genuine_leaves_as_categories() -> None:
+ # Classifier-precision guard (CP hardening point 1): rows with no aria-haspopup and no nested
+ # children are genuine leaves. A no-match error must never mistag one as an expandable category.
+ async with _live_page(_reacting_leaf_list_html("dept", ["Engineering", "Marketing", "Sales"])) as page:
tools = build_browser_tools(_fixed_page_provider(page))
- r = await _tool(tools, "observe").handler({})
- assert r.status == "ok"
- listed = [line for line in r.content.splitlines() if line.startswith("[") and "hidden-native" in line]
- assert len(listed) == 40
- assert "note: 40 native control(s)" in r.content
- assert "could not be described" in r.content # the overflow is disclosed, not silently dropped
- cv_line = next(line for line in listed if "[#cv]" in line)
- assert "file_upload" in cv_line and "click" not in cv_line
+ r = await _tool(tools, "select_combobox").handler({"selector": "#dept", "value": "Legal"})
+ assert r.status == "error", r.content
+ assert "data-tv3-menu" not in r.content, r.content
+ assert r.content == (
+ "no autocomplete suggestion matched 'Legal' for #dept; the field is NOT filled "
+ "— do not assume success or move on as if it were"
+ )
-_LABEL_WRAPS_BUTTON_HTML = """
-<!doctype html><html><body>
- <label style="display:inline-block;width:240px;height:40px">
- <input id="opt" type="checkbox" style="position:absolute;width:0;height:0;opacity:0">
- <button id="danger" type="button" style="width:240px;height:40px" onclick="window.__fired = true">Submit</button>
- </label>
+_GROUPED_LISTBOX_FIXTURE_HTML = """
+<!doctype html><html><body style="margin:0">
+ <input id="fruit" type="text" autocomplete="off"
+ style="position:absolute;top:40px;left:40px;width:260px;height:24px">
+ <script>
+ var inp = document.getElementById('fruit');
+ inp.addEventListener('input', function () {
+ var old = document.getElementById('dd');
+ if (old) old.remove();
+ if (!inp.value) return;
+ var dd = document.createElement('div');
+ dd.id = 'dd';
+ dd.setAttribute('role', 'listbox');
+ dd.setAttribute('style', 'position:absolute;top:70px;left:40px;width:260px;background:#fff');
+ // A canonical ARIA grouped listbox: role=group is a static section label wrapping already-visible
+ // option leaves, NOT an expandable drilldown. It carries no aria-haspopup/aria-expanded.
+ var grp = document.createElement('div');
+ grp.setAttribute('role', 'group');
+ grp.setAttribute('aria-label', 'Citrus');
+ grp.setAttribute('style', 'display:block');
+ ['Orange', 'Lemon'].forEach(function (t) {
+ var row = document.createElement('div');
+ row.setAttribute('role', 'option');
+ row.setAttribute('style', 'height:22px;display:block');
+ row.textContent = t;
+ grp.appendChild(row);
+ });
+ dd.appendChild(grp);
+ document.body.appendChild(dd);
+ });
+ </script>
</body></html>
"""
@_skip_no_browser
@pytest.mark.asyncio
-async def test_a_host_whose_shadow_root_read_throws_is_disclosed() -> None:
- # A throwing shadowRoot accessor costs the element AND its whole root: the root never reaches the
- # set uniqueness is counted across, so a duplicate living in there reads as unique and the printed
- # line clicks the other one. Nothing can prevent that — the executor pierces where we cannot look
- # — so the payload must at least say that part of the page went unread.
- async with _live_page(
- """<style>x-hide,x-vis{display:block;width:120px;height:24px}</style>
- <x-hide></x-hide><x-vis></x-vis>
- <script>
- var leaf = '<style>button{display:block;width:120px;height:22px}</style><button id="ctrl">';
- var hidden = document.querySelector('x-hide');
- hidden.attachShadow({mode: 'open'}).innerHTML = leaf + 'DECOY</button>';
- Object.defineProperty(hidden, 'shadowRoot', {get: function () { throw new Error('sealed'); }});
- document.querySelector('x-vis').attachShadow({mode: 'open'}).innerHTML = leaf + 'INTENDED</button>';
- </script>"""
- ) as page:
- # Armed only if the executor resolves both: with one match there is no wrong element to reach.
- assert await page.locator("#ctrl").count() == 2, "fixture is not armed"
+async def test_select_combobox_grouped_listbox_is_not_reported_as_a_drilldown_category() -> None:
+ # Classifier-precision guard (CP hardening point 1, false-expandable direction): a role=group
+ # wrapping already-visible option leaves is a section label, not an expandable category. Tagging it
+ # would tell the model to "click to expand" a wrapper that commits nothing -- a dead click on a
+ # confident wrong instruction. RED against the classifier's first cut, which qualified any row with
+ # >=2 nested option descendants regardless of role.
+ async with _live_page(_GROUPED_LISTBOX_FIXTURE_HTML) as page:
tools = build_browser_tools(_fixed_page_provider(page))
- r = await _tool(tools, "observe").handler({})
- assert "part of this page could not be queried" in r.content, r.content
+ r = await _tool(tools, "select_combobox").handler({"selector": "#fruit", "value": "Cherry"})
+ assert r.status == "error", r.content
+ assert "data-tv3-menu" not in r.content, r.content
+ assert r.content == (
+ "no autocomplete suggestion matched 'Cherry' for #fruit; the field is NOT filled "
+ "— do not assume success or move on as if it were"
+ )
-@_skip_no_browser
+_FILTER_TO_ZERO_FIXTURE_HTML = """
+<!doctype html><html><body style="margin:0">
+ <input id="city" role="combobox" aria-autocomplete="list" type="text" autocomplete="off"
+ style="position:absolute;top:40px;left:40px;width:260px;height:24px">
+ <script>
+ var inp = document.getElementById('city');
+ var OPTIONS = ['Lisbon', 'Porto', 'Braga'];
+ // A genuinely FILTERING typeahead: an absent value narrows the list to zero option rows (renders a
+ // bare "No options" line, no role=option). Nothing new for _FIND_MENU_JS to count -- the only signal
+ // that this is searchable is aria-autocomplete=list.
+ inp.addEventListener('input', function () {
+ var old = document.getElementById('dd'); if (old) old.remove();
+ if (!inp.value) return;
+ var m = OPTIONS.filter(function (o) { return o.toLowerCase().indexOf(inp.value.toLowerCase()) >= 0; });
+ var dd = document.createElement('div'); dd.id = 'dd'; dd.setAttribute('role', 'listbox');
+ dd.setAttribute('style', 'position:absolute;top:70px;left:40px;width:260px;background:#fff');
+ if (m.length === 0) {
+ var e = document.createElement('div'); e.textContent = 'No options';
+ e.setAttribute('style', 'height:26px'); dd.appendChild(e);
+ } else {
+ m.forEach(function (t) {
+ var row = document.createElement('div'); row.setAttribute('role', 'option');
+ row.setAttribute('style', 'height:26px'); row.textContent = t; dd.appendChild(row);
+ });
+ }
+ document.body.appendChild(dd);
+ });
+ </script>
+</body></html>
+"""
+
+
+@_skip_no_browser
+async def test_select_combobox_searchable_filter_to_zero_reads_plain_no_match() -> None:
+ # A searchable combobox (aria-autocomplete=list) that filters to ZERO rows on an absent value leaves
+ # no new rows for the reaction probe to count -- but it is still a genuine no-match, NOT a
+ # non-searchable click-to-open to reopen. The ARIA contract is the fallback signal: report the plain
+ # no-match rather than falling through to open->observe->pick.
+ async with _live_page(_FILTER_TO_ZERO_FIXTURE_HTML) as page:
+ tools = build_browser_tools(_fixed_page_provider(page))
+ r = await _tool(tools, "select_combobox").handler({"selector": "#city", "value": "Springfield"})
+ assert r.status == "error", r.content
+ assert "data-tv3-menu" not in r.content, r.content
+ assert r.content == (
+ "no autocomplete suggestion matched 'Springfield' for #city; the field is NOT filled "
+ "— do not assume success or move on as if it were"
+ )
+
+
+def _reacting_special_row_html(field_id: str, row_attrs: str, label: str) -> str:
+ # A reacting dropdown with a single row carrying arbitrary attributes and no nested option
+ # children -- for probing whether a lone aria signal (expanded/disabled) should qualify it.
+ return f"""
+<!doctype html><html><body style="margin:0">
+ <input id="{field_id}" type="text" autocomplete="off"
+ style="position:absolute;top:40px;left:40px;width:260px;height:24px">
+ <script>
+ var inp = document.getElementById('{field_id}');
+ inp.addEventListener('input', function () {{
+ var old = document.getElementById('dd');
+ if (old) old.remove();
+ if (!inp.value) return;
+ var dd = document.createElement('div');
+ dd.id = 'dd';
+ dd.setAttribute('role', 'listbox');
+ dd.setAttribute('style', 'position:absolute;top:70px;left:40px;width:260px;background:#fff');
+ var row = document.createElement('div');
+ row.setAttribute('role', 'option');
+ {row_attrs}
+ row.setAttribute('style', 'height:26px;display:block');
+ row.textContent = {label!r};
+ dd.appendChild(row);
+ document.body.appendChild(dd);
+ }});
+ </script>
+</body></html>
+"""
+
+
+@_skip_no_browser
+async def test_select_combobox_already_expanded_row_is_not_reported_as_a_category() -> None:
+ # Precision guard: aria-expanded="true" is already open -- clicking it would toggle it CLOSED, not
+ # reveal options. Only a collapsed row (aria-expanded="false") is a category worth clicking. RED
+ # against the classifier's first cut, which treated mere presence of aria-expanded as a signal.
+ html = _reacting_special_row_html("sec", "row.setAttribute('aria-expanded', 'true');", "Open section")
+ async with _live_page(html) as page:
+ tools = build_browser_tools(_fixed_page_provider(page))
+ r = await _tool(tools, "select_combobox").handler({"selector": "#sec", "value": "Nonexistent"})
+ assert r.status == "error", r.content
+ assert "data-tv3-menu" not in r.content, r.content
+
+
+@_skip_no_browser
+async def test_select_combobox_disabled_category_is_not_reported() -> None:
+ # Precision guard: a disabled row is a dead click even if it carries an expand affordance, so it
+ # must never be offered as a clickable category.
+ html = _reacting_special_row_html(
+ "svc", "row.setAttribute('aria-haspopup', 'true'); row.setAttribute('aria-disabled', 'true');", "Locked"
+ )
+ async with _live_page(html) as page:
+ tools = build_browser_tools(_fixed_page_provider(page))
+ r = await _tool(tools, "select_combobox").handler({"selector": "#svc", "value": "Nonexistent"})
+ assert r.status == "error", r.content
+ assert "data-tv3-menu" not in r.content, r.content
+
+
+_NAV_ROW_FIXTURE_HTML = """
+<!doctype html><html><body style="margin:0">
+ <a role="menuitem" href="/products" aria-haspopup="true"
+ style="position:absolute;top:8px;left:40px;width:120px;height:20px">Products</a>
+ <input id="reason" type="text" autocomplete="off"
+ style="position:absolute;top:40px;left:40px;width:260px;height:24px">
+ <script>
+ var inp = document.getElementById('reason');
+ inp.addEventListener('input', function () {
+ var old = document.getElementById('dd');
+ if (old) old.remove();
+ if (!inp.value) return;
+ var dd = document.createElement('div');
+ dd.id = 'dd';
+ dd.setAttribute('role', 'listbox');
+ dd.setAttribute('style', 'position:absolute;top:70px;left:40px;width:260px;background:#fff');
+ ['Alpha', 'Beta'].forEach(function (t) {
+ var row = document.createElement('div');
+ row.setAttribute('role', 'option');
+ row.setAttribute('style', 'height:22px;display:block');
+ row.textContent = t;
+ dd.appendChild(row);
+ });
+ document.body.appendChild(dd);
+ });
+ </script>
+</body></html>
+"""
+
+
+@_skip_no_browser
+async def test_select_combobox_navigational_row_is_not_reported_as_a_category() -> None:
+ # P0 precision guard: an <a href>/<button> row navigates away when clicked, destroying the
+ # partially filled form. It must never be offered as a category even with aria-haspopup, mirroring
+ # _FIND_SUGGESTION_JS's own nav exclusion.
+ async with _live_page(_NAV_ROW_FIXTURE_HTML) as page:
+ tools = build_browser_tools(_fixed_page_provider(page))
+ r = await _tool(tools, "select_combobox").handler({"selector": "#reason", "value": "Gamma"})
+ assert r.status == "error", r.content
+ assert "data-tv3-menu" not in r.content, r.content
+ assert "Products" not in r.content, r.content
+
+
+@_skip_no_browser
+async def test_select_combobox_haspopup_but_already_expanded_row_is_not_reported() -> None:
+ # Precision guard: aria-haspopup + aria-expanded="true" is an already-open popup; a click collapses
+ # it. The haspopup arm must not override the already-open exclusion.
+ html = _reacting_special_row_html(
+ "svc", "row.setAttribute('aria-haspopup', 'true'); row.setAttribute('aria-expanded', 'true');", "Open"
+ )
+ async with _live_page(html) as page:
+ tools = build_browser_tools(_fixed_page_provider(page))
+ r = await _tool(tools, "select_combobox").handler({"selector": "#svc", "value": "Nonexistent"})
+ assert r.status == "error", r.content
+ assert "data-tv3-menu" not in r.content, r.content
+
+
+@_skip_no_browser
+async def test_select_combobox_reports_a_haspopup_only_category() -> None:
+ # Positive mutation-power for the aria-haspopup arm: a row qualifying on aria-haspopup ALONE (no
+ # nested children, no aria-expanded) must be reported. Deleting the hasPopup arm reds this.
+ html = _reacting_special_row_html("svc", "row.setAttribute('aria-haspopup', 'true');", "Benefits")
+ async with _live_page(html) as page:
+ tools = build_browser_tools(_fixed_page_provider(page))
+ r = await _tool(tools, "select_combobox").handler({"selector": "#svc", "value": "Nonexistent"})
+ assert r.status == "error", r.content
+ assert "data-tv3-menu" in r.content and "Benefits" in r.content, r.content
+
+
+@_skip_no_browser
+async def test_select_combobox_reports_a_collapsed_only_category() -> None:
+ # Positive mutation-power for the aria-expanded arm: a row qualifying on aria-expanded="false" ALONE
+ # (collapsed, no haspopup, no children) must be reported. Deleting the hasExpanded arm reds this.
+ html = _reacting_special_row_html("svc", "row.setAttribute('aria-expanded', 'false');", "Benefits")
+ async with _live_page(html) as page:
+ tools = build_browser_tools(_fixed_page_provider(page))
+ r = await _tool(tools, "select_combobox").handler({"selector": "#svc", "value": "Nonexistent"})
+ assert r.status == "error", r.content
+ assert "data-tv3-menu" in r.content and "Benefits" in r.content, r.content
+
+
+_NESTED_ONLY_FIXTURE_HTML = """
+<!doctype html><html><body style="margin:0">
+ <input id="reason" type="text" autocomplete="off"
+ style="position:absolute;top:40px;left:40px;width:260px;height:24px">
+ <script>
+ var inp = document.getElementById('reason');
+ inp.addEventListener('input', function () {
+ var old = document.getElementById('dd');
+ if (old) old.remove();
+ if (!inp.value) return;
+ var dd = document.createElement('div');
+ dd.id = 'dd';
+ dd.setAttribute('role', 'listbox');
+ dd.setAttribute('style', 'position:absolute;top:70px;left:40px;width:260px;background:#fff');
+ var row = document.createElement('div');
+ row.setAttribute('role', 'option'); // no aria-haspopup, no aria-expanded
+ row.setAttribute('style', 'height:26px;display:block');
+ row.appendChild(document.createTextNode('Benefits'));
+ ['Dental', 'Vision'].forEach(function (t) {
+ var kid = document.createElement('div');
+ kid.setAttribute('role', 'option');
+ kid.textContent = t;
+ kid.setAttribute('style', 'height:22px;display:none');
+ row.appendChild(kid);
+ });
+ dd.appendChild(row);
+ document.body.appendChild(dd);
+ });
+ </script>
+</body></html>
+"""
+
+
+@_skip_no_browser
+async def test_select_combobox_reports_a_nested_children_only_category() -> None:
+ # Positive mutation-power for the nested-children arm: a role=option row with >=2 nested option
+ # children and NO aria signal must be reported. Deleting the childCount arm reds this.
+ async with _live_page(_NESTED_ONLY_FIXTURE_HTML) as page:
+ tools = build_browser_tools(_fixed_page_provider(page))
+ r = await _tool(tools, "select_combobox").handler({"selector": "#reason", "value": "Nonexistent"})
+ assert r.status == "error", r.content
+ assert "data-tv3-menu" in r.content and "Benefits" in r.content, r.content
+
+
+@_skip_no_browser
+async def test_forced_select_refuses_disabled_select() -> None:
+ async with _content_page(_HIDDEN_NATIVE_EDGES_HTML) as page:
+ tools = build_browser_tools(_fixed_page_provider(page))
+ r = await _tool(tools, "select_option").handler({"selector": "#locked", "label": "A"})
+ assert r.status == "error" and "disabled" in r.content
+ assert await page.eval_on_selector("#locked", "el => el.value") == ""
+
+
+@_skip_no_browser
+async def test_an_unreadable_root_is_disclosed_on_the_very_first_observe() -> None:
+ # The regression: the throwing root was seen only by the marker gather's catch, which swallowed
+ # it, so the first observe minted an unverified marker, disclosed nothing, and the payload
+ # changed on turn two of a completely static page. The disclosure now also reaches this page
+ # from the post-write resolvesTo, so what is pinned here is the end state — disclosed and
+ # byte-stable — not which catch produced it; the gather's own catch is held separately below.
+ async with _live_page(
+ """<button style="display:block;width:80px;height:20px">Nameless</button>
+ <div id="poison" style="display:block;width:40px;height:20px"></div>
+ <script>
+ var sr = document.getElementById('poison').attachShadow({mode: 'open'});
+ sr.innerHTML = '<span>inert</span>';
+ sr.querySelectorAll = () => { throw new Error('poisoned'); };
+ </script>"""
+ ) as page:
+ tools = build_browser_tools(_fixed_page_provider(page))
+ first = await _tool(tools, "observe").handler({})
+ again = await _tool(tools, "observe").handler({})
+ assert "part of this page could not be queried" in first.content, first.content
+ assert first.content == again.content, f"static page churned:\n{first.content}\n---\n{again.content}"
+
+
+@_skip_no_browser
+async def test_observe_bounds_hidden_natives_and_points_file_inputs_at_file_upload() -> None:
+ async with _content_page(_HIDDEN_NATIVE_EDGES_HTML) as page:
+ tools = build_browser_tools(_fixed_page_provider(page))
+ r = await _tool(tools, "observe").handler({})
+ assert r.status == "ok"
+ listed = [line for line in r.content.splitlines() if line.startswith("[") and "hidden-native" in line]
+ assert len(listed) == 40
+ assert "note: 40 native control(s)" in r.content
+ assert "could not be described" in r.content # the overflow is disclosed, not silently dropped
+ cv_line = next(line for line in listed if "[#cv]" in line)
+ assert "file_upload" in cv_line and "click" not in cv_line
+
+
+_LABEL_WRAPS_BUTTON_HTML = """
+<!doctype html><html><body>
+ <label style="display:inline-block;width:240px;height:40px">
+ <input id="opt" type="checkbox" style="position:absolute;width:0;height:0;opacity:0">
+ <button id="danger" type="button" style="width:240px;height:40px" onclick="window.__fired = true">Submit</button>
+ </label>
+</body></html>
+"""
+
+
+@_skip_no_browser
+async def test_a_host_whose_shadow_root_read_throws_is_disclosed() -> None:
+ # A throwing shadowRoot accessor costs the element AND its whole root: the root never reaches the
+ # set uniqueness is counted across, so a duplicate living in there reads as unique and the printed
+ # line clicks the other one. Nothing can prevent that — the executor pierces where we cannot look
+ # — so the payload must at least say that part of the page went unread.
+ async with _live_page(
+ """<style>x-hide,x-vis{display:block;width:120px;height:24px}</style>
+ <x-hide></x-hide><x-vis></x-vis>
+ <script>
+ var leaf = '<style>button{display:block;width:120px;height:22px}</style><button id="ctrl">';
+ var hidden = document.querySelector('x-hide');
+ hidden.attachShadow({mode: 'open'}).innerHTML = leaf + 'DECOY</button>';
+ Object.defineProperty(hidden, 'shadowRoot', {get: function () { throw new Error('sealed'); }});
+ document.querySelector('x-vis').attachShadow({mode: 'open'}).innerHTML = leaf + 'INTENDED</button>';
+ </script>"""
+ ) as page:
+ # Armed only if the executor resolves both: with one match there is no wrong element to reach.
+ assert await page.locator("#ctrl").count() == 2, "fixture is not armed"
+ tools = build_browser_tools(_fixed_page_provider(page))
+ r = await _tool(tools, "observe").handler({})
+ assert "part of this page could not be queried" in r.content, r.content
+
+
+@_skip_no_browser
async def test_a_root_only_the_marker_gather_reaches_is_still_disclosed() -> None:
# Nothing else on this page learns the root is unreadable: every control sits inside a component
# under a reused id, so resolvesTo short-circuits on the duplicate two roots before it reaches the
@@ -7570,6 +8920,8 @@ async def test_observe_line_count_matches_its_header_across_hostile_attribute_va
f'<div id="a7" role="button" aria-label="x{payload}" style="width:40px;height:20px">x</div>',
f'<select id="a8"><option value="x{payload}">x{payload}</option></select>',
f'<fieldset><legend>x{payload}</legend><input id="a9" type="checkbox"></fieldset>',
+ # A placeholder demoted to a hint by an associated label still reaches the rendered line.
+ f'<label for="a10">Named</label><input id="a10" placeholder="x{payload}">',
]
async with _live_page("".join(hostile) + '<button id="real">Real</button>') as page:
tools = build_browser_tools(_fixed_page_provider(page))
@@ -7873,12 +9225,16 @@ _SHARED_ID_DROPZONES_HTML = """
<ds-drop id="dz-b"></ds-drop>
<ds-drop class="anon"></ds-drop>
<script>
+ // An immediate-upload form: attaching a file dispatches an upload request. Absolute URL so the
+ // request is dispatched (and observed) even though it fails against no server.
+ function upl() { fetch('https://api.example.test/upload', {method: 'POST', body: new FormData()}).catch(function () {}); }
function mk(hostId, inputId, labelText) {
var r = document.getElementById(hostId).attachShadow({mode: 'open'});
r.innerHTML =
'<label for="' + inputId + '" style="display:inline-block;width:240px;height:40px">' +
labelText + '</label>' +
'<input type="file" id="' + inputId + '" style="position:absolute;width:0;height:0;opacity:0">';
+ r.getElementById(inputId).addEventListener('change', upl);
}
mk('dz-single', 'resume-unique', 'Upload resume (only one)');
mk('dz-a', 'resume', 'Upload resume');
@@ -10017,6 +11373,8 @@ async def test_file_upload_settles_and_delays_after_set_input_files(monkeypatch:
async def rec_set_input_files(paths: Any) -> None:
order.append("upload")
+ page.element._files = list(paths)
+ page._emit_request(_FakeRequest()) # immediate-upload form acknowledges the attach
monkeypatch.setattr(page.element, "set_input_files", rec_set_input_files)
@@ -10041,81 +11399,475 @@ async def test_file_upload_settles_and_delays_after_set_input_files(monkeypatch:
assert order == ["upload", "settle", "delay"]
+def _patch_upload_dwell(monkeypatch: pytest.MonkeyPatch, tools_module: Any) -> None:
+ async def _noop_settle(_page: Any) -> None:
+ return None
+
+ async def _noop_delay() -> None:
+ return None
+
+ monkeypatch.setattr(tools_module, "_settle_after_upload", _noop_settle)
+ monkeypatch.setattr(tools_module, "_upload_submit_delay", _noop_delay)
+
+
+def _patch_upload_download(monkeypatch: pytest.MonkeyPatch) -> None:
+ import skyvern.forge.sdk.api.files as files_module
+
+ async def _fake(source: str, output_dir: str | None = None, organization_id: str | None = None) -> str:
+ return "/tmp/cv.pdf"
+
+ monkeypatch.setattr(files_module, "download_file", _fake)
+
+
@pytest.mark.asyncio
-async def test_non_upload_actions_do_not_settle_or_delay(monkeypatch: pytest.MonkeyPatch) -> None:
- # The dwell is upload-specific: click/type must NOT incur the settle or the delay, so the tool
- # loop is not globally slowed. This guards against the dwell drifting up into the shared loop.
+async def test_file_upload_no_upload_activity_returns_actionable_error_not_false_ok(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ # The core fix: set_input_files can populate the control at the Playwright layer yet the site
+ # register nothing (post-navigation the change handler is not wired) — zero upload requests
+ # dispatched. file_upload must return a recoverable non-OK there, not a confident OK that makes the
+ # agent submit with no file. A submit-time-upload form lands here too as an accepted false-negative.
+ # RED against pre-fix code, which returned "uploaded 1 file" regardless of activity.
import skyvern.forge.taskv3.tools as tools_module
page = _FakePage()
- called: list[str] = []
+ page.element.emit_upload_on_set = False # file lands in the input, but the site never reacts
+ _patch_upload_dwell(monkeypatch, tools_module)
+ _patch_upload_download(monkeypatch)
- async def rec_settle(_page: Any) -> None:
- called.append("settle")
+ tools = build_browser_tools(_fixed_page_provider(page))
+ r = await _tool(tools, "file_upload").handler({"selector": "#cv", "file": "resume.pdf"})
- async def rec_delay() -> None:
- called.append("delay")
+ assert r.status == "error", r.content
+ assert "no upload activity" in r.content
+ assert "uploaded 1 file" not in r.content
+ # The file was still attached at the Playwright layer, so the staged-download key must persist so
+ # the download-signal wrapper still suppresses the staged file.
+ assert (r.data or {}).get("staged_download") == "cv.pdf"
+ # The request listener must be removed after the call — no leaked/accumulating listeners.
+ assert page._request_listeners == []
- monkeypatch.setattr(tools_module, "_settle_after_upload", rec_settle)
- monkeypatch.setattr(tools_module, "_upload_submit_delay", rec_delay)
+
+async def test_file_upload_confirms_when_upload_activity_observed(monkeypatch: pytest.MonkeyPatch) -> None:
+ # An immediate-upload form dispatches an upload request when the file is attached; file_upload then
+ # reports the confident OK and cleans up its listener.
+ import skyvern.forge.taskv3.tools as tools_module
+
+ page = _FakePage() # default emit_upload_on_set=True → an upload request is dispatched
+ _patch_upload_dwell(monkeypatch, tools_module)
+ _patch_upload_download(monkeypatch)
tools = build_browser_tools(_fixed_page_provider(page))
- await _tool(tools, "click").handler({"selector": "#submit"})
- await _tool(tools, "type").handler({"selector": "#first", "text": "John"})
- await _tool(tools, "select_option").handler({"selector": "#country", "label": "United States"})
+ r = await _tool(tools, "file_upload").handler({"selector": "#cv", "file": "resume.pdf"})
- assert called == []
+ assert r.status == "ok", r.content
+ assert "uploaded 1 file" in r.content
+ assert page._request_listeners == []
@pytest.mark.asyncio
-async def test_upload_submit_delay_mirrors_v1_inter_action_default(monkeypatch: pytest.MonkeyPatch) -> None:
- # The delay must mirror v1's inter_action_delay default: random.uniform(base, 2*base), base=0.5.
+async def test_file_upload_not_populated_returns_did_not_attach_error(monkeypatch: pytest.MonkeyPatch) -> None:
+ # Layer 1 populate check: if set_input_files leaves the control holding no file (wrong element, a
+ # reset, or a detach mid-call), file_upload reports "did not attach" rather than a false OK.
import skyvern.forge.taskv3.tools as tools_module
- bounds: list[tuple[float, float]] = []
- slept: list[Any] = []
+ page = _FakePage()
+ page.element.emit_upload_on_set = False
- def rec_uniform(a: float, b: float) -> float:
- bounds.append((a, b))
- return a
+ async def _empty_files(_js: str, _arg: Any = None) -> Any:
+ return 0
- async def rec_sleep(s: Any) -> None:
- slept.append(s)
+ monkeypatch.setattr(page.element, "evaluate", _empty_files)
+ _patch_upload_dwell(monkeypatch, tools_module)
+ _patch_upload_download(monkeypatch)
- monkeypatch.setattr(tools_module.random, "uniform", rec_uniform)
- monkeypatch.setattr(tools_module.asyncio, "sleep", rec_sleep)
+ tools = build_browser_tools(_fixed_page_provider(page))
+ r = await _tool(tools, "file_upload").handler({"selector": "#cv", "file": "resume.pdf"})
- # Real function (autouse no-ops the module attr for speed); exercise the actual arithmetic.
- await _REAL_UPLOAD_SUBMIT_DELAY()
+ assert r.status == "error", r.content
+ assert "did not attach" in r.content
+ assert page._request_listeners == []
- assert bounds == [(0.5, 1.0)]
- assert slept == [0.5]
+class _FakeDropzonePage(_FakePage):
+ """A page whose rendered text the test controls, so the filename-shown readback around
+ set_input_files sees a before/after difference (or not)."""
-async def test_settle_after_upload_reuses_v1_wait_for_upload_processing(monkeypatch: pytest.MonkeyPatch) -> None:
- # The settle must reuse v1's exact _wait_for_upload_processing (not a divergent reimplementation),
- # so both engines settle identically after an upload.
- import skyvern.forge.taskv3.tools as tools_module
- import skyvern.webeye.actions.handler as handler_module
+ def __init__(self, text: str = "Upload your resume") -> None:
+ super().__init__()
+ self.text = text
+ self.text_reads = 0
- seen: list[Any] = []
+ async def evaluate(self, js: str, *args: Any) -> Any:
+ if "innerText" in js:
+ self.text_reads += 1
+ return self.text
+ return await super().evaluate(js)
- async def fake_wait(page: Any, engine_selection: Any = None) -> None:
- seen.append(page)
- monkeypatch.setattr(handler_module, "_wait_for_upload_processing", fake_wait)
+def _consume_and_clear(page: _FakeDropzonePage, *, upload: bool, show: bool) -> Any:
+ """Site JS for a consume-and-clear dropzone: read the file off the input, optionally dispatch the
+ upload, optionally render the filename, then reset the input so files.length reads 0."""
- sentinel = object()
- await tools_module._settle_after_upload(sentinel)
+ async def _set(paths: Any) -> None:
+ page.element._files = list(paths)
+ if upload:
+ page._emit_request(_FakeRequest(method="POST", resource_type="xhr"))
+ if show:
+ page.text = page.text + "\nAttached: cv.pdf [remove]"
+ page.element._files = []
- assert seen == [sentinel]
+ return _set
@pytest.mark.asyncio
-async def test_settle_after_upload_swallows_errors(monkeypatch: pytest.MonkeyPatch) -> None:
- # The upload already succeeded before the settle runs; a settle failure (e.g. an engine-specific
- # error) must NOT propagate and turn the completed upload into a tool failure.
+async def test_file_upload_consume_and_clear_dropzone_with_upload_activity_is_ok(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ # A consume-and-clear dropzone reads input.files on change, uploads the file, shows it, then resets
+ # the input so the same control can accept another drop. Layer 1 then reads files.length == 0 AFTER
+ # a genuine upload; the file's own name newly on the page proves the site took it — a success, not
+ # "did not attach". RED against pre-fix code, which errored on files.length == 0 unconditionally.
+ import skyvern.forge.taskv3.tools as tools_module
+
+ page = _FakeDropzonePage()
+ monkeypatch.setattr(page.element, "set_input_files", _consume_and_clear(page, upload=True, show=True))
+ _patch_upload_dwell(monkeypatch, tools_module)
+ _patch_upload_download(monkeypatch)
+
+ tools = build_browser_tools(_fixed_page_provider(page))
+ r = await _tool(tools, "file_upload").handler({"selector": "#cv", "file": "resume.pdf"})
+
+ assert r.status == "ok", r.content
+ assert "uploaded 1 file" in r.content
+ assert "Attached: cv.pdf" in r.content # the site's own words travel with the confirmation
+ assert (r.data or {}).get("staged_download") == "cv.pdf"
+ assert page._request_listeners == []
+
+
+async def test_file_upload_consume_and_clear_without_network_activity_is_recoverable_error(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ # The input was cleared and the page names the file, but nothing was dispatched: a client-side
+ # rejection looks exactly like this (it names the file it refused and sends nothing), so this is
+ # not a confirmation. It is a recoverable error that carries the page's own words, never an OK.
+ import skyvern.forge.taskv3.tools as tools_module
+
+ page = _FakeDropzonePage()
+ monkeypatch.setattr(page.element, "set_input_files", _consume_and_clear(page, upload=False, show=True))
+ _patch_upload_dwell(monkeypatch, tools_module)
+ _patch_upload_download(monkeypatch)
+
+ tools = build_browser_tools(_fixed_page_provider(page))
+ r = await _tool(tools, "file_upload").handler({"selector": "#cv", "file": "resume.pdf"})
+
+ assert r.status == "error", r.content
+ assert "re-observe" in r.content
+ assert "Attached: cv.pdf" in r.content
+ assert "uploaded 1 file" not in r.content
+
+
+async def test_file_upload_rejection_banner_naming_the_file_is_not_a_confirmation(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ # Server-side rejection: the file was dispatched, the site refused it and cleared the input, and the
+ # banner names the file. Upload activity plus the name newly shown would otherwise read as success;
+ # the rejection wording around the name vetoes that, in the safe direction only.
+ import skyvern.forge.taskv3.tools as tools_module
+
+ page = _FakeDropzonePage()
+
+ async def _upload_then_reject(paths: Any) -> None:
+ page.element._files = list(paths)
+ page._emit_request(_FakeRequest(method="POST", resource_type="xhr"))
+ page.text = page.text + "\nError: cv.pdf exceeds the 2MB size limit and was not uploaded."
+ page.element._files = []
+
+ monkeypatch.setattr(page.element, "set_input_files", _upload_then_reject)
+ _patch_upload_dwell(monkeypatch, tools_module)
+ _patch_upload_download(monkeypatch)
+
+ tools = build_browser_tools(_fixed_page_provider(page))
+ r = await _tool(tools, "file_upload").handler({"selector": "#cv", "file": "resume.pdf"})
+
+ assert r.status == "error", r.content
+ assert "uploaded 1 file" not in r.content
+ assert "exceeds the 2MB size limit" in r.content
+
+
+async def test_file_upload_empty_input_with_ambient_post_only_still_errors(monkeypatch: pytest.MonkeyPatch) -> None:
+ # The hole the consume-and-clear branch must not open: a genuine no-op (the site never took the
+ # file) on a busy page whose ambient POST xhr traffic makes the activity probe read true. Nothing
+ # shows the file, so this stays a recoverable error — never a submit-without-file.
+ import skyvern.forge.taskv3.tools as tools_module
+
+ page = _FakeDropzonePage()
+
+ async def _no_op_with_ambient_post(paths: Any) -> None:
+ page._emit_request(_FakeRequest(method="POST", resource_type="xhr", url="https://api.example.test/beat"))
+
+ monkeypatch.setattr(page.element, "set_input_files", _no_op_with_ambient_post)
+ _patch_upload_dwell(monkeypatch, tools_module)
+ _patch_upload_download(monkeypatch)
+
+ tools = build_browser_tools(_fixed_page_provider(page))
+ r = await _tool(tools, "file_upload").handler({"selector": "#cv", "file": "resume.pdf"})
+
+ assert r.status == "error", r.content
+ assert "did not attach" in r.content
+ assert page._request_listeners == []
+
+
+async def test_file_upload_empty_input_with_unrelated_text_containing_the_stem_still_errors(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ # Only the file's FULL name counts, as a whole token: a banner that lazy-loads during the settle
+ # window and happens to contain the stem ("test" in "test environment"), or a different file whose
+ # name contains this one ("oldtest.pdf", "old-test.pdf", "test.pdf.bak"), must not read as the site
+ # showing this file.
+ import skyvern.forge.sdk.api.files as files_module
+ import skyvern.forge.taskv3.tools as tools_module
+
+ page = _FakeDropzonePage()
+
+ async def _no_op_then_unrelated_text(paths: Any) -> None:
+ page.text = page.text + (
+ "\nThis is a test environment banner. Previously attached: oldtest.pdf, old-test.pdf, test.pdf.bak"
+ )
+
+ async def _stage_test_pdf(source: str, output_dir: str | None = None, organization_id: str | None = None) -> str:
+ return "/tmp/test.pdf"
+
+ monkeypatch.setattr(page.element, "set_input_files", _no_op_then_unrelated_text)
+ monkeypatch.setattr(files_module, "download_file", _stage_test_pdf)
+ _patch_upload_dwell(monkeypatch, tools_module)
+
+ tools = build_browser_tools(_fixed_page_provider(page))
+ r = await _tool(tools, "file_upload").handler({"selector": "#cv", "file": "test.pdf"})
+
+ assert r.status == "error", r.content
+ assert "did not attach" in r.content
+
+
+async def test_file_upload_empty_input_with_preexisting_filename_mention_still_errors(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ # Diff guard: the page already said "cv.pdf" before the attach (a prior attempt, or instructions
+ # naming the expected file). Present-after alone is not evidence; only absent-before AND present-after is.
+ import skyvern.forge.taskv3.tools as tools_module
+
+ page = _FakeDropzonePage(text="Please upload cv.pdf")
+ monkeypatch.setattr(page.element, "set_input_files", _consume_and_clear(page, upload=True, show=False))
+ _patch_upload_dwell(monkeypatch, tools_module)
+ _patch_upload_download(monkeypatch)
+
+ tools = build_browser_tools(_fixed_page_provider(page))
+ r = await _tool(tools, "file_upload").handler({"selector": "#cv", "file": "resume.pdf"})
+
+ assert r.status == "error", r.content
+ assert "did not attach" in r.content
+
+
+async def test_file_upload_empty_input_with_unreadable_page_text_fails_closed(monkeypatch: pytest.MonkeyPatch) -> None:
+ # A DOM read failure on this branch must fall to the recoverable error, never to a new OK: the OK
+ # here is what lets the model submit, so it needs positive evidence.
+ import skyvern.forge.taskv3.tools as tools_module
+
+ page = _FakeDropzonePage()
+
+ async def _raise(js: str, *args: Any) -> Any:
+ if "innerText" in js:
+ raise RuntimeError("execution context destroyed")
+ return await _FakePage.evaluate(page, js)
+
+ monkeypatch.setattr(page, "evaluate", _raise)
+ monkeypatch.setattr(page.element, "set_input_files", _consume_and_clear(page, upload=True, show=True))
+ _patch_upload_dwell(monkeypatch, tools_module)
+ _patch_upload_download(monkeypatch)
+
+ tools = build_browser_tools(_fixed_page_provider(page))
+ r = await _tool(tools, "file_upload").handler({"selector": "#cv", "file": "resume.pdf"})
+
+ assert r.status == "error", r.content
+ assert "did not attach" in r.content
+
+
+@_skip_no_browser
+async def test_page_shows_filename_reads_rendered_text_only_across_shadow_roots() -> None:
+ # The readback must see the filename a dropzone renders inside a shadow root, and must NOT see it in
+ # hidden nodes, <script> or <style> text (document level or inside a shadow root): a config blob that
+ # mentions the name is not the site showing the file. Real Chromium, since innerText semantics are
+ # exactly what is under test.
+ from skyvern.forge.taskv3.tools import _mentions_filename, _page_rendered_text # noqa: PLC0415
+
+ html = (
+ "<div id=host></div><div style='display:none'>hidden-cv.pdf</div>"
+ '<script type=\'application/json\'>{"f":"cv.pdf"}</script>'
+ "<script>const h = document.getElementById('host').attachShadow({mode:'open'});"
+ "h.innerHTML = \"<style>.a{content:'cv.pdf'}</style><span id=chip hidden>cv.pdf</span>\";</script>"
+ )
+ async with _content_page(html) as page:
+ assert not _mentions_filename(await _page_rendered_text(page) or "", "/tmp/cv.pdf")
+ await page.evaluate(
+ "() => { document.getElementById('host').shadowRoot.getElementById('chip').hidden = false; }"
+ )
+ assert _mentions_filename(await _page_rendered_text(page) or "", "/tmp/cv.pdf")
+
+
+ "rendered",
+ [
+ # A benign chip first, the rejection naming the file again elsewhere: every mention counts.
+ "Selected file: cv.pdf\n" + "x" * 300 + "\nError: cv.pdf could not be uploaded due to size limits.",
+ # The rejection sits well past any fixed window around the name.
+ "cv.pdf " + "please keep files under the size limit shown in the sidebar. " * 3 + "error uploading, retry",
+ # Hedged phrasing with words between "not" and the verb.
+ "cv.pdf will not be uploaded, please try again later",
+ # Contractions and plain refusal verbs.
+ "Sorry, we can't accept cv.pdf right now.",
+ "cv.pdf was denied by the virus scanner",
+ "Upload of cv.pdf unsuccessful — please try uploading again",
+ "cv.pdf: we don't support this file type",
+ "Something went wrong with cv.pdf",
+ "cv.pdf is too\n large for this form",
+ ],
+)
+async def test_file_upload_rejection_anywhere_in_newly_rendered_text_vetoes(
+ monkeypatch: pytest.MonkeyPatch, rendered: str
+) -> None:
+ # The veto reads everything the site newly rendered, not a window around the first mention.
+ import skyvern.forge.taskv3.tools as tools_module
+
+ page = _FakeDropzonePage()
+
+ async def _upload_then_reject(paths: Any) -> None:
+ page.element._files = list(paths)
+ page._emit_request(_FakeRequest(method="POST", resource_type="xhr"))
+ page.text = page.text + "\n" + rendered
+ page.element._files = []
+
+ monkeypatch.setattr(page.element, "set_input_files", _upload_then_reject)
+ _patch_upload_dwell(monkeypatch, tools_module)
+ _patch_upload_download(monkeypatch)
+
+ tools = build_browser_tools(_fixed_page_provider(page))
+ r = await _tool(tools, "file_upload").handler({"selector": "#cv", "file": "resume.pdf"})
+
+ assert r.status == "error", r.content
+ assert "uploaded 1 file" not in r.content
+ assert "cv.pdf" in r.content
+
+
+async def test_file_upload_ignores_non_upload_network_noise(monkeypatch: pytest.MonkeyPatch) -> None:
+ # The activity probe must DISCRIMINATE: unrelated background traffic (a GET, an analytics image
+ # beacon) is not an upload. A page firing only such noise during the upload window is still a
+ # no-activity case, so the check does not false-confirm on ambient traffic.
+ import skyvern.forge.taskv3.tools as tools_module
+
+ page = _FakePage()
+
+ async def _set_with_noise(paths: Any) -> None:
+ page.element._files = list(paths)
+ page._emit_request(_FakeRequest(method="GET", resource_type="image", url="https://cdn.test/ping.gif"))
+ page._emit_request(_FakeRequest(method="POST", resource_type="ping", url="https://cdn.test/beacon"))
+
+ monkeypatch.setattr(page.element, "set_input_files", _set_with_noise)
+ _patch_upload_dwell(monkeypatch, tools_module)
+ _patch_upload_download(monkeypatch)
+
+ tools = build_browser_tools(_fixed_page_provider(page))
+ r = await _tool(tools, "file_upload").handler({"selector": "#cv", "file": "resume.pdf"})
+
+ assert r.status == "error", r.content
+ assert "no upload activity" in r.content
+ assert page._request_listeners == []
+
+
+async def test_non_upload_actions_do_not_settle_or_delay(monkeypatch: pytest.MonkeyPatch) -> None:
+ # The dwell is upload-specific: click/type must NOT incur the settle or the delay, so the tool
+ # loop is not globally slowed. This guards against the dwell drifting up into the shared loop.
+ import skyvern.forge.taskv3.tools as tools_module
+
+ page = _FakePage()
+ called: list[str] = []
+
+ async def rec_settle(_page: Any) -> None:
+ called.append("settle")
+
+ async def rec_delay() -> None:
+ called.append("delay")
+
+ monkeypatch.setattr(tools_module, "_settle_after_upload", rec_settle)
+ monkeypatch.setattr(tools_module, "_upload_submit_delay", rec_delay)
+
+ tools = build_browser_tools(_fixed_page_provider(page))
+ await _tool(tools, "click").handler({"selector": "#submit"})
+ await _tool(tools, "type").handler({"selector": "#first", "text": "John"})
+ await _tool(tools, "select_option").handler({"selector": "#country", "label": "United States"})
+
+ assert called == []
+
+
+async def test_upload_submit_delay_mirrors_v1_inter_action_default(monkeypatch: pytest.MonkeyPatch) -> None:
+ # The delay must mirror v1's inter_action_delay default: random.uniform(base, 2*base), base=0.5.
+ import skyvern.forge.taskv3.tools as tools_module
+
+ bounds: list[tuple[float, float]] = []
+ slept: list[Any] = []
+
+ def rec_uniform(a: float, b: float) -> float:
+ bounds.append((a, b))
+ return a
+
+ async def rec_sleep(s: Any) -> None:
+ slept.append(s)
+
+ monkeypatch.setattr(tools_module.random, "uniform", rec_uniform)
+ monkeypatch.setattr(tools_module.asyncio, "sleep", rec_sleep)
+
+ # Real function (autouse no-ops the module attr for speed); exercise the actual arithmetic.
+ await _REAL_UPLOAD_SUBMIT_DELAY()
+
+ assert bounds == [(0.5, 1.0)]
+ assert slept == [0.5]
+
+
+async def test_settle_after_upload_reuses_v1_wait_for_upload_processing(monkeypatch: pytest.MonkeyPatch) -> None:
+ # The settle must reuse v1's exact _wait_for_upload_processing (not a divergent reimplementation),
+ # so both engines settle identically after an upload.
+ import skyvern.forge.taskv3.tools as tools_module
+ import skyvern.webeye.actions.handler as handler_module
+
+ seen: list[Any] = []
+
+ async def fake_wait(page: Any, engine_selection: Any = None) -> None:
+ seen.append(page)
+
+ monkeypatch.setattr(handler_module, "_wait_for_upload_processing", fake_wait)
+
+ sentinel = object()
+ await tools_module._settle_after_upload(sentinel)
+
+ assert seen == [sentinel]
+
+
+async def test_settle_after_upload_swallows_errors(monkeypatch: pytest.MonkeyPatch) -> None:
+ # The upload already succeeded before the settle runs; a settle failure (e.g. an engine-specific
+ # error) must NOT propagate and turn the completed upload into a tool failure.
import skyvern.forge.taskv3.tools as tools_module
import skyvern.webeye.actions.handler as handler_module
@@ -10148,6 +11900,87 @@ def _refs_for(*urls: str) -> Any:
return mask_opaque_urls({f"u{i}": url for i, url in enumerate(urls)})
+async def test_navigate_derives_a_ref_only_for_a_redirect_reached_through_a_payload_ref(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ import skyvern.utils.url_validators as urlv
+
+ monkeypatch.setattr(urlv, "validate_fetch_url", lambda url: url)
+ landing = "https://cdn.example.test/blob/resume.pdf?X-Amz-Signature=0123456789abcdef0123456789abcdef"
+
+ class _RedirectingPage(_FakePage):
+ async def goto(self, url: str, timeout: int | None = None, wait_until: str | None = None) -> None:
+ await super().goto(url, timeout, wait_until)
+ self.url = landing
+
+ refs = _refs_for(_SIGNED_REF_URL)
+ token = next(iter(refs.refs))
+ tools = build_browser_tools(
+ _fixed_page_provider(_RedirectingPage()), resolve_typed_text=refs.chain(None), opaque_refs=refs
+ )
+ r = await _tool(tools, "navigate").handler({"url": token})
+ assert landing in refs.refs.values() and refs.mask(r.content).startswith("navigated to opaque_url_")
+
+ # A failed navigation reports its cause, but every URL Playwright names in it came from following the
+ # ref, so they are shown as the token; and a non-http landing (an error page) derives nothing.
+ class _FailingPage(_FakePage):
+ async def goto(self, url: str, timeout: int | None = None, wait_until: str | None = None) -> None:
+ raise RuntimeError(f"page.goto: net::ERR_NAME_NOT_RESOLVED at {landing}")
+
+ refs = _refs_for(_SIGNED_REF_URL)
+ tools = build_browser_tools(
+ _fixed_page_provider(_FailingPage()), resolve_typed_text=refs.chain(None), opaque_refs=refs
+ )
+ r = await _tool(tools, "navigate").handler({"url": token})
+ assert (
+ r.status == "error" and "X-Amz" not in r.content and token in r.content and "ERR_NAME_NOT_RESOLVED" in r.content
+ )
+ assert landing not in refs.refs.values()
+ # The request text is model-supplied: it must never act as a replacement pattern.
+ r = await _tool(tools, "navigate").handler({"url": token + "\\g<0>"})
+ assert r.status == "error" and "X-Amz" not in r.content
+
+ class _ErrorPage(_FakePage):
+ async def goto(self, url: str, timeout: int | None = None, wait_until: str | None = None) -> None:
+ self.url = "chrome-error://chromewebdata/"
+
+ refs = _refs_for(_SIGNED_REF_URL)
+ tools = build_browser_tools(
+ _fixed_page_provider(_ErrorPage()), resolve_typed_text=refs.chain(None), opaque_refs=refs
+ )
+ r = await _tool(tools, "navigate").handler({"url": token})
+ assert r.content == "navigated to chrome-error://chromewebdata/" and len(refs.refs) == 1
+ # A credential placeholder is substituted too, but it is not payload provenance: a redirect reached
+ # through one derives nothing, and its navigation failure is reported as raised.
+ refs = _refs_for(_SIGNED_REF_URL)
+ tools = build_browser_tools(
+ _fixed_page_provider(_RedirectingPage()),
+ resolve_typed_text=refs.chain(
+ lambda t: "https://portal.example.test/login?sso=1" if t == "placeholder_sso" else t
+ ),
+ opaque_refs=refs,
+ )
+ r = await _tool(tools, "navigate").handler({"url": "placeholder_sso"})
+ assert landing not in refs.refs.values() and r.content == f"navigated to {landing}"
+ with pytest.raises(RuntimeError):
+ tools = build_browser_tools(
+ _fixed_page_provider(_FailingPage()),
+ resolve_typed_text=refs.chain(
+ lambda t: "https://portal.example.test/login?sso=1" if t == "placeholder_sso" else t
+ ),
+ opaque_refs=refs,
+ )
+ await _tool(tools, "navigate").handler({"url": "placeholder_sso"})
+ # A model-chosen live URL that happens to redirect to a signed page has no payload provenance.
+ refs = _refs_for(_SIGNED_REF_URL)
+ tools = build_browser_tools(
+ _fixed_page_provider(_RedirectingPage()), resolve_typed_text=refs.chain(None), opaque_refs=refs
+ )
+ r = await _tool(tools, "navigate").handler({"url": "https://jobs.example.test/apply"})
+ assert landing not in refs.refs.values() and refs.mask(r.content) == f"navigated to {landing}"
+
+
@pytest.mark.asyncio
async def test_observe_masks_payload_ref_page_url() -> None:
page = _FakePage()
@@ -10197,40 +12030,11 @@ async def test_get_html_leaves_inline_signing_shaped_benign_url_unmasked() -> No
assert "opaque_url_" not in result.content
-async def _run_file_upload_with_failing_download(source: str, opaque_refs: Any, error_url: str) -> Any:
- page = _FakePage()
- tools = build_browser_tools(_fixed_page_provider(page), opaque_refs=opaque_refs)
- import skyvern.forge.sdk.api.files as files_module
-
- async def failing_download_file(
- source: str, output_dir: str | None = None, organization_id: str | None = None
- ) -> str:
- raise Exception(f"Failed to download managed storage file: {error_url}")
-
- original = files_module.download_file
- files_module.download_file = failing_download_file # type: ignore[assignment]
- try:
- return await _tool(tools, "file_upload").handler({"selector": "#cv", "file": source})
- finally:
- files_module.download_file = original
-
-
-async def test_file_upload_masks_payload_ref_in_download_error() -> None:
- result = await _run_file_upload_with_failing_download(_SIGNED_REF_URL, _refs_for(_SIGNED_REF_URL), _SIGNED_REF_URL)
- assert result.status == "error"
- assert _SIGNED_REF_ARTIFACT not in result.content
- assert "opaque_url_" in result.content
-
-
-async def test_file_upload_leaves_signing_shaped_benign_url_in_download_error_unmasked() -> None:
- result = await _run_file_upload_with_failing_download(
- _FP_SIGNED_SHAPED_URL, _refs_for(_SIGNED_REF_URL), _FP_SIGNED_SHAPED_URL
- )
- assert result.status == "error"
- assert _FP_SIGNED_SHAPED_URL in result.content
- assert "opaque_url_" not in result.content
+# file_upload no longer masks its own download-error: it propagates the exception to the loop's
+# generic tool_error, which the single model-facing boundary (hide_from_model) masks by membership.
+# That path — a raising handler's tool_error masked to its token, and a benign signing-shaped URL
+# left intact — is covered at the loop entry point by
+# test_taskv3_loop.test_payload_signed_urls_are_masked_to_their_token_across_every_tool_result_surface.
@pytest.mark.asyncio
@@ -10293,3 +12097,350 @@ async def test_observe_leaves_benign_page_text_unmasked() -> None:
result = await _tool(tools, "observe").handler({})
assert _FP_SIGNED_SHAPED_URL in result.content
assert "opaque_url_" not in result.content
+
+
+# Selector-robustness guard (SKY-14600): a model-emitted invalid bare `#<id>` (digit/UUID-leading) is
+# normalized to the equivalent, always-valid `[id="..."]` form; any residual unparseable selector becomes
+# an actionable single-tool error instead of a naked patchright crash that aborts the whole batched turn.
+# Real patchright/playwright messages, captured verbatim from a headless-chromium probe. These are
+# LIBRARY-INTERNAL strings and are version-coupled: the classifier matches on them by design (the
+# exception class differs between patchright and playwright, the wording does not). RED-proofed here so
+# a library upgrade that rewords them breaks THIS test loudly instead of silently disarming the guard.
+_PW_INVALID_ID_MSG = (
+ "Page.query_selector: SyntaxError: Failed to execute 'querySelectorAll' on 'Document': "
+ "'#3c421ef6-1234-5678-9abc-def012345678' is not a valid selector."
+)
+_PW_PARSE_MSG = 'Page.click: Unexpected token "" while parsing selector "div["'
+
+
+ "selector,expected",
+ [
+ # Invalid-as-bare ids (leading digit / hyphen-digit / lone hyphen) -> rewritten to [id="..."].
+ ("#3c421ef6-1234-5678-9abc-def012345678", '[id="3c421ef6-1234-5678-9abc-def012345678"]'),
+ ("#9", '[id="9"]'),
+ ("#-9x", '[id="-9x"]'),
+ ("#-", '[id="-"]'),
+ # Valid selectors -> returned byte-identical.
+ ("#normalid", "#normalid"),
+ ("#--9x", "#--9x"), # double-hyphen leading is VALID CSS (probe: resolves, no raise)
+ ("#a3c", "#a3c"), # digit present but not leading
+ ("#_x", "#_x"),
+ ("#foo .bar", "#foo .bar"),
+ ("#foo.bar", "#foo.bar"),
+ ("#foo:hover", "#foo:hover"),
+ (".cls", ".cls"),
+ ("input", "input"),
+ ('[id="x"]', '[id="x"]'),
+ ('[data-tv3-act="3"]', '[data-tv3-act="3"]'),
+ ],
+)
+def test_normalize_selector_table(selector: str, expected: str) -> None:
+ assert _normalize_selector(selector) == expected
+
+
+def test_normalize_selector_never_alters_valid_selectors() -> None:
+ # The passthrough property IS the safety case: a selector that already parses must come out
+ # byte-identical, so normalization can never change WHICH element an action targets.
+ valid = [
+ "#normalid",
+ "#--9x",
+ "#a3c",
+ "#_x",
+ "#x-9",
+ "#café", # non-ASCII identifier-start is valid
+ "#foo .bar",
+ "#foo.bar",
+ "#foo:hover",
+ "#foo[disabled]",
+ "#a\\31 b", # a correctly digit-escaped id is already valid
+ ".cls",
+ ".a.b.c",
+ "div",
+ "*",
+ "input[type=file]",
+ '[id="9lead"]',
+ '[name="first name"]',
+ '[data-tv3="k1"]',
+ '[data-tv3-menu="2"]',
+ "#form #field",
+ "button.primary",
+ "ul > li:first-child",
+ "a[href^='https']",
+ ]
+ for s in valid:
+ assert _normalize_selector(s) == s, f"normalization altered a valid selector: {s!r}"
+
+
+def test_normalize_selector_leaves_unsafe_or_unquotable_ids_untouched() -> None:
+ # An id carrying a quote, backslash, whitespace, or a combinator/pseudo char must NEVER be wrapped
+ # into [id="..."] (it would malform or change the selector). The regex excludes them, so each of
+ # these passes through unchanged rather than being rewritten.
+ for s in ['#a"b', "#a'b", "#a\\5c", "#a\\ b", "#a b", "#a[b", "#a>b", "#a:b", "#a.b", "#a,b"]:
+ out = _normalize_selector(s)
+ assert out == s, f"unsafe id was rewritten: {s!r} -> {out!r}"
+ assert not (out.startswith('[id="') and out != s)
+
+
+def test_invalid_selector_result_matches_real_playwright_messages() -> None:
+ for msg in (_PW_INVALID_ID_MSG, _PW_PARSE_MSG):
+ r = _invalid_selector_result("#3c", _PlaywrightError(msg))
+ assert r is not None
+ assert r.status == "error"
+ assert "valid CSS selector" in r.content
+
+
+def test_invalid_selector_result_ignores_non_selector_errors() -> None:
+ # Narrow match: timeouts, teardown, and other failures must be RE-RAISED (return None), not
+ # swallowed as an actionable selector error.
+ for msg in (
+ "Page.click: Timeout 30000ms exceeded.",
+ "Target page, context or browser has been closed",
+ "net::ERR_CONNECTION_REFUSED",
+ ):
+ assert _invalid_selector_result("#3c", _PlaywrightError(msg)) is None
+
+
+class _RaisingQueryPage(_FakePage):
+ """Mirrors production: query_selector raises the real invalid-selector Error for any selector that
+ isn't a valid attribute form; a `[id=...]`/`[name=...]` selector resolves normally."""
+
+ async def query_selector(self, selector: str) -> Any:
+ self.calls.append(("query_selector", {"selector": selector}))
+ if not selector.startswith("["):
+ raise _PlaywrightError(_PW_INVALID_ID_MSG)
+ return self.element
+
+
+def _patch_download(monkeypatch: pytest.MonkeyPatch) -> None:
+ import skyvern.forge.sdk.api.files as files_module
+
+ async def _fake(source: str, output_dir: str | None = None, organization_id: str | None = None) -> str:
+ return "/tmp/downloaded.pdf"
+
+ monkeypatch.setattr(files_module, "download_file", _fake)
+
+
+async def test_file_upload_unparseable_selector_returns_actionable_error_not_crash(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ # A malformed, NON-normalizable selector must become an actionable single-tool error, not a naked
+ # patchright raise that aborts the batch. RED when the guard's except is reverted (handler raises).
+ _patch_download(monkeypatch)
+ page = _RaisingQueryPage()
+ tools = build_browser_tools(_fixed_page_provider(page))
+ result = await _tool(tools, "file_upload").handler({"selector": "div[", "file": "/tmp/cv.pdf"})
+ assert result.status == "error"
+ assert "valid CSS selector" in result.content
+
+
+async def test_file_upload_invalid_selector_does_not_stage_phantom_download(
+ monkeypatch: pytest.MonkeyPatch, tmp_path: Path
+) -> None:
+ # With downloads_dir active, an invalid selector must fail BEFORE the source is fetched, so nothing
+ # is staged for the download-signal wrapper to misread as a browser download (which sets
+ # download_notice and can wrongly complete a complete-on-download run). RED if the download precedes
+ # selector resolution: the staged upload lands in downloads_dir and the guard's error omits it.
+ import skyvern.forge.sdk.api.files as files_module
+
+ called = {"n": 0}
+
+ async def fake_download_file(source: str, output_dir: str | None = None, organization_id: str | None = None) -> str:
+ called["n"] += 1
+ staged = Path(output_dir or str(tmp_path)) / "staged_resume.pdf"
+ staged.write_bytes(b"resume bytes")
+ return str(staged)
+
+ monkeypatch.setattr(files_module, "download_file", fake_download_file)
+ page = _RaisingQueryPage()
+ tools = build_browser_tools(_fixed_page_provider(page), downloads_dir=str(tmp_path))
+ result = await _tool(tools, "file_upload").handler({"selector": "div[", "file": "https://example.test/cv.pdf"})
+
+ assert result.status == "error"
+ assert "valid CSS selector" in result.content
+ assert called["n"] == 0
+ assert not (result.data or {}).get("download_notice")
+
+
+async def test_file_upload_normalizes_digit_leading_id_into_success(monkeypatch: pytest.MonkeyPatch) -> None:
+ # The dominant crash shape (digit/UUID-leading `#id`) is normalized to `[id="..."]` BEFORE the
+ # naked query_selector, turning a batch-aborting crash into a successful upload. RED without
+ # normalization (the bare `#3c...` would raise, yielding an error instead of ok).
+ _patch_download(monkeypatch)
+ page = _RaisingQueryPage()
+ tools = build_browser_tools(_fixed_page_provider(page))
+ result = await _tool(tools, "file_upload").handler(
+ {"selector": "#3c421ef6-1234-5678-9abc-def012345678", "file": "/tmp/cv.pdf"}
+ )
+ assert result.status == "ok"
+ assert ("set_input_files", ["/tmp/downloaded.pdf"]) in page.element.calls
+ assert ("query_selector", {"selector": '[id="3c421ef6-1234-5678-9abc-def012345678"]'}) in page.calls
+
+
+async def test_click_normalizes_model_supplied_invalid_bare_id() -> None:
+ # Nesting: for an act_by_mark tool with a MODEL-SUPPLIED selector (no mark), the guard normalizes
+ # the selector the handler actually acts on — page.click receives the [id="..."] form, not `#3c...`.
+ page = _FakePage()
+ tools = build_browser_tools(_fixed_page_provider(page))
+ await _tool(tools, "click").handler({"selector": "#3c421ef6-1234-5678-9abc-def012345678"})
+ assert ("click", {"selector": '[id="3c421ef6-1234-5678-9abc-def012345678"]'}) in page.calls
+
+
+async def test_click_leaves_valid_selector_untouched_through_the_stack() -> None:
+ # Guard must not interfere with a valid selector anywhere in the act_by_mark/preflight stack.
+ page = _FakePage()
+ tools = build_browser_tools(_fixed_page_provider(page))
+ await _tool(tools, "click").handler({"selector": "#normalid"})
+ assert ("click", {"selector": "#normalid"}) in page.calls
+
+
+_LABELED_INPUT_WITH_FORMAT_PLACEHOLDER_HTML = """
+<!doctype html><html><body><form>
+ <label for="start">Date Available *</label>
+ <input id="start" type="text" placeholder="dd/mm/yyyy">
+ <label for="first">First Name *</label>
+ <input id="first" type="text">
+</form></body></html>
+"""
+
+
+@_skip_no_browser
+async def test_observe_names_a_field_by_its_label_not_its_placeholder() -> None:
+ # A design system that marks required-ness only with a `*` inside the <label> gave the model
+ # 'dd/mm/yyyy' for a required date field: the placeholder outranked the associated label, so
+ # the one field the label named as required was the one field with no visible required signal.
+ async with _content_page(_LABELED_INPUT_WITH_FORMAT_PLACEHOLDER_HTML) as page:
+ tools = build_browser_tools(_fixed_page_provider(page))
+ r = await _tool(tools, "observe").handler({})
+ line = next(ln for ln in r.content.splitlines() if ln.startswith("[#start]"))
+ assert "Date Available *" in line
+ assert "dd/mm/yyyy" in line # the format hint is what makes the value typeable
+
+
+@_skip_no_browser
+async def test_look_legend_names_a_field_by_its_label_not_its_placeholder() -> None:
+ # Same weakness as observe's, on the act-by-mark path: the legend took the placeholder over the
+ # associated <label>, so the required marker the label carried never reached the model.
+ async with _content_page(_LABELED_INPUT_WITH_FORMAT_PLACEHOLDER_HTML) as page:
+ tools = build_browser_tools(_fixed_page_provider(page))
+ r = await _tool(tools, "look").handler({})
+ line = next(ln for ln in r.content.splitlines() if ln.startswith("[1] "))
+ assert "Date Available *" in line
+ assert "dd/mm/yyyy" in line # the format hint is what makes the value typeable
+
+
+@_skip_no_browser
+async def test_look_legend_masks_a_minted_url_carried_by_a_placeholder() -> None:
+ # The hint is capped for display like the label; masking is by provenance over the WHOLE URL, so
+ # the cap must come after it or the legend prints a signed fragment the masker can no longer see.
+ html = f'<form><label for="doc">Résumé link</label><input id="doc" placeholder="{_SIGNED_REF_URL}"></form>'
+ async with _content_page(html) as page:
+ tools = build_browser_tools(_fixed_page_provider(page), opaque_refs=_refs_for(_SIGNED_REF_URL))
+ r = await _tool(tools, "look").handler({})
+ assert _SIGNED_REF_ARTIFACT not in r.content
+ assert "opaque_url_" in r.content
+
+
+# A payload URL long enough to hit observe's per-field display caps (label 140, value 100,
+# placeholder 60). Masking is by provenance over the WHOLE URL, so a cap applied before the masker
+# runs leaves a truncated URL the masker cannot recognise -- and the signing tail with it.
+_LONG_SIGNED_REF_URL = (
+ "https://files.example.test/uploads/a1b2c3d4/resume.pdf"
+ "?X-Amz-Algorithm=AWS4-HMAC-SHA256&X-Amz-Credential=AKIAEXAMPLE%2F20260827%2Fus-east-1%2Fs3%2Faws4_request"
+ "&X-Amz-Date=20260827T000000Z&X-Amz-Expires=3600&X-Amz-SignedHeaders=host"
+ "&X-Amz-Signature=0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef"
+)
+_LONG_SIGNED_REF_ARTIFACT = "X-Amz-Credential=AKIAEXAMPLE"
+
+
+@_skip_no_browser
+ "carrier",
+ [
+ "value",
+ "placeholder",
+ "label",
+ "group",
+ "invalid",
+ "spinbutton",
+ "slotted",
+ "prefixed",
+ "huge",
+ "alert",
+ "alert_prefixed_huge",
+ "canonical",
+ "escaped",
+ ],
+)
+async def test_observe_masks_a_minted_url_longer_than_its_display_caps(carrier: str) -> None:
+ assert len(_LONG_SIGNED_REF_URL) > 200
+ url = _LONG_SIGNED_REF_URL
+ if carrier == "group":
+ # Group text is the description of a field named by nothing; capped at 200 for display.
+ html = f'<form><p id="hint">Upload at {_LONG_SIGNED_REF_URL}</p><input id="doc" aria-describedby="hint"></form>'
+ elif carrier == "invalid":
+ # A custom validity message echoes whatever the page put in it, at a 140 display cap.
+ html = (
+ '<form><input id="doc" value="x">'
+ f"<script>document.getElementById('doc').setCustomValidity('Not {_LONG_SIGNED_REF_URL}')</script></form>"
+ )
+ elif carrier == "spinbutton":
+ # A widget spinbutton reports its value through aria-valuenow, not .value.
+ html = f'<div role="spinbutton" tabindex="0" aria-valuenow="{_LONG_SIGNED_REF_URL}">42</div>'
+ elif carrier == "slotted":
+ # A single-control component is captioned by its host's light-DOM text.
+ html = (
+ f"<x-field>{_LONG_SIGNED_REF_URL}</x-field><script>customElements.define('x-field', class extends "
+ "HTMLElement { connectedCallback() { const r = this.attachShadow({mode: 'open'}); "
+ "r.innerHTML = '<slot></slot><input id=\"doc\">'; } })</script>"
+ )
+ elif carrier == "prefixed":
+ # A URL just under the retained width, behind a short visible prefix: the carrier as a whole
+ # exceeds a fixed retain cap even though the URL alone does not.
+ url = _LONG_SIGNED_REF_URL + "&X-Amz-Policy=" + "p" * (1990 - len(_LONG_SIGNED_REF_URL))
+ html = f'<form><input id="doc" value="Download: {url}"></form>'
+ elif carrier == "huge":
+ # A URL longer than any fixed retain cap.
+ url = _LONG_SIGNED_REF_URL + "&X-Amz-Policy=" + "p" * 2400
+ html = f'<form><input id="doc" value="{url}"></form>'
+ elif carrier == "alert":
+ # The page-text digest: a status message that echoes the URL, longer than its 300 display cap.
+ html = f'<div role="alert">Saved your document to {_LONG_SIGNED_REF_URL} for review</div><input id="doc">'
+ elif carrier == "canonical":
+ # The browser echoes a payload URL in canonical form: each non-ASCII char becomes a 12-char
+ # percent-escape, so the echoed text is far longer than the URL the width was sized from.
+ from skyvern.forge.sdk.core.skyvern_context import canonical_url # noqa: PLC0415
+
+ url = _LONG_SIGNED_REF_URL + "#" + "\U0001f4c4" * 300
+ html = f'<form><input id="doc" value="{canonical_url(url)}"></form>'
+ elif carrier == "escaped":
+ # The page authored the URL entity-escaped once too often, so the DOM-decoded value still holds
+ # `&amp;` for every query separator and is longer than the raw or canonical URL.
+ url = _LONG_SIGNED_REF_URL + "&p=1" * 500
+ html = f'<form><input id="doc" value="{html_escape(html_escape(url))}"></form>'
+ elif carrier == "alert_prefixed_huge":
+ # The widest display window (page text, 300) with a prefix wider than any other window, then
+ # a URL just under the retain floor: the retain margin must be sized for THIS window.
+ url = _LONG_SIGNED_REF_URL + "&X-Amz-Policy=" + "p" * (1990 - len(_LONG_SIGNED_REF_URL))
+ html = f'<div role="alert">{"Please wait. " * 20}{url}</div><input id="doc">'
+ elif carrier == "value":
+ html = f'<form><input id="doc" value="{_LONG_SIGNED_REF_URL}"></form>'
+ elif carrier == "placeholder":
+ html = f'<form><label for="doc">Résumé link</label><input id="doc" placeholder="{_LONG_SIGNED_REF_URL}"></form>'
+ else:
+ html = f'<form><input id="doc" aria-label="{_LONG_SIGNED_REF_URL}"></form>'
+ async with _content_page(html) as page:
+ tools = build_browser_tools(_fixed_page_provider(page), opaque_refs=_refs_for(url))
+ r = await _tool(tools, "observe").handler({})
+ line = next(ln for ln in r.content.splitlines() if ln.startswith("[#doc]") or "spinbutton" in ln)
+ assert _LONG_SIGNED_REF_ARTIFACT not in r.content
+ assert "opaque_url_" in (r.content if carrier.startswith("alert") else line)
diff --git a/tests/unit/test_workflow_copilot_prompt_rewrite.py b/tests/unit/test_workflow_copilot_prompt_rewrite.py
index 27ae40c9b..beb0d200a 100644
--- a/tests/unit/test_workflow_copilot_prompt_rewrite.py
+++ b/tests/unit/test_workflow_copilot_prompt_rewrite.py
@@ -1,29 +1,118 @@
from __future__ import annotations
+import json
+from collections.abc import Callable
+from functools import lru_cache
from types import SimpleNamespace
-from unittest.mock import MagicMock
+from typing import Any
import pytest
+from skyvern.forge import app
+from skyvern.forge.agent_functions import AgentFunction
+from skyvern.forge.sdk.copilot.agent import _build_dynamic_system_prompt, _build_tool_usage_guide
from skyvern.forge.sdk.copilot.config import BlockAuthoringPolicy, CopilotConfig
from skyvern.forge.sdk.copilot.context import CopilotContext
+from skyvern.forge.sdk.copilot.mcp_adapter import _copilot_to_call_tool_result
from skyvern.forge.sdk.copilot.request_policy import RequestPolicy
+from skyvern.forge.sdk.copilot.tools import NATIVE_TOOLS, _build_skyvern_mcp_overlays
from skyvern.forge.sdk.copilot.tools.banned_blocks import _code_only_browser_authoring_prompt
from skyvern.forge.sdk.copilot.tools.mcp_hooks import (
_get_block_schema_post_hook,
_get_workflow_knowledge_post_hook,
)
+from skyvern.schemas.workflows import CodeBlockYAML
-def _code_only_ctx() -> MagicMock:
- ctx = MagicMock()
- ctx.block_authoring_policy = BlockAuthoringPolicy.CODE_ONLY_BROWSER
- ctx.code_only_code_schema_seen = False
- return ctx
+# _build_dynamic_system_prompt stamps the current time once per call, so two renders
+# built separately never compare equal.
+@lru_cache(maxsize=1)
+def _production_instructions() -> Callable[..., object]:
+ config = CopilotConfig(
+ security_rules="CUSTOM SECURITY RULE",
+ block_authoring_policy=BlockAuthoringPolicy.CODE_ONLY_BROWSER,
+ )
+ overlays = _build_skyvern_mcp_overlays(config.block_authoring_policy)
+ tool_info = [(tool.name, tool.description or "") for tool in NATIVE_TOOLS]
+ tool_info.extend((name, overlay.description or "") for name, overlay in overlays.items())
+ return _build_dynamic_system_prompt(tool_usage_guide=_build_tool_usage_guide(tool_info), config=config)
+
+
+def _render_production_prompt(workflow_yaml: str = "") -> str:
+ instructions = _production_instructions()
+ ctx = CopilotContext(
+ organization_id="org_test",
+ workflow_id="workflow_test",
+ workflow_permanent_id="wpid_test",
+ workflow_yaml=workflow_yaml,
+ browser_session_id=None,
+ stream=SimpleNamespace(), # type: ignore[arg-type]
+ workflow_copilot_chat_id="chat_test",
+ request_policy=RequestPolicy(),
+ )
+ return str(instructions(SimpleNamespace(context=ctx), None))
+
+
+def _sentence_containing(prompt: str, needle: str) -> str:
+ return next((sentence for sentence in prompt.split(". ") if needle in sentence), "")
+
+
+def _code_only_ctx() -> SimpleNamespace:
+ return SimpleNamespace(
+ block_authoring_policy=BlockAuthoringPolicy.CODE_ONLY_BROWSER,
+ code_only_code_schema_seen=False,
+ scout_trajectory=[],
+ )
+
+
+def _code_schema_result() -> dict[str, Any]:
+ return {"ok": True, "data": {"block_type": "code", "schema": CodeBlockYAML.model_json_schema()}}
+
+
+async def test_code_only_code_schema_requires_a_non_null_goal(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ monkeypatch.setattr(app, "AGENT_FUNCTION", AgentFunction())
+ code_only = await _get_block_schema_post_hook(_code_schema_result(), {}, _code_only_ctx())
+
+ code_only_schema = code_only["data"]["schema"]
+ prompt_schema = code_only_schema["properties"]["prompt"]
+ assert "prompt" in code_only_schema["required"]
+ assert prompt_schema["type"] == "string"
+ assert "anyOf" not in prompt_schema
+ assert "oneOf" not in prompt_schema
+
+ model_result = _copilot_to_call_tool_result(code_only, "get_block_schema")
+ model_payload = json.loads(model_result.content[0].text)
+ model_schema = model_payload["data"]["schema"]
+ assert "prompt" in model_schema["required"]
+ assert model_schema["properties"]["prompt"]["type"] == "string"
@pytest.mark.asyncio
-async def test_code_schema_is_the_discoverable_home_for_runtime_helpers() -> None:
+async def test_standard_code_schema_keeps_prompt_optional_for_legacy_blocks() -> None:
+ standard_ctx = SimpleNamespace(block_authoring_policy=BlockAuthoringPolicy.STANDARD)
+ standard = await _get_block_schema_post_hook(_code_schema_result(), {}, standard_ctx)
+ standard_schema = standard["data"]["schema"]
+
+ assert "prompt" not in standard_schema["required"]
+ assert {option.get("type") for option in standard_schema["properties"]["prompt"]["anyOf"]} == {
+ "string",
+ "null",
+ }
+
+
+def test_legacy_code_block_yaml_does_not_synthesize_an_omitted_prompt() -> None:
+ legacy_block = CodeBlockYAML(block_type="code", label="legacy_code", code="return None")
+
+ assert legacy_block.prompt is None
+ assert "prompt" not in legacy_block.model_dump(exclude_none=True)
+
+
+async def test_code_schema_is_the_discoverable_home_for_runtime_helpers(monkeypatch: pytest.MonkeyPatch) -> None:
+ monkeypatch.setattr(app, "AGENT_FUNCTION", AgentFunction())
result = {"ok": True, "data": {"block_type": "code"}}
rendered = await _get_block_schema_post_hook(result, {"block_type": "code"}, _code_only_ctx())
@@ -60,33 +149,8 @@ def test_code_only_policy_is_short_and_contains_no_settled_block_conversion_stee
def test_rendered_prompt_keeps_security_ask_telemetry_and_workflow_wide_edit_scope() -> None:
- from skyvern.forge.sdk.copilot.agent import _build_dynamic_system_prompt, _build_tool_usage_guide
- from skyvern.forge.sdk.copilot.tools import NATIVE_TOOLS, _build_skyvern_mcp_overlays
-
- config = CopilotConfig(
- security_rules="CUSTOM SECURITY RULE",
- block_authoring_policy=BlockAuthoringPolicy.CODE_ONLY_BROWSER,
- )
- overlays = _build_skyvern_mcp_overlays(config.block_authoring_policy)
- tool_info = [(tool.name, tool.description or "") for tool in NATIVE_TOOLS]
- tool_info.extend((name, overlay.description or "") for name, overlay in overlays.items())
- instructions = _build_dynamic_system_prompt(tool_usage_guide=_build_tool_usage_guide(tool_info), config=config)
-
- def render(workflow_yaml: str) -> str:
- ctx = CopilotContext(
- organization_id="org_test",
- workflow_id="workflow_test",
- workflow_permanent_id="wpid_test",
- workflow_yaml=workflow_yaml,
- browser_session_id=None,
- stream=SimpleNamespace(), # type: ignore[arg-type]
- workflow_copilot_chat_id="chat_test",
- request_policy=RequestPolicy(),
- )
- return str(instructions(SimpleNamespace(context=ctx), None))
-
- new_workflow_prompt = render("")
- settled_login_prompt = render(
+ new_workflow_prompt = _render_production_prompt("")
+ settled_login_prompt = _render_production_prompt(
"workflow_definition:\n blocks:\n - block_type: login\n label: existing_login\n"
)
@@ -94,3 +158,14 @@ def test_rendered_prompt_keeps_security_ask_telemetry_and_workflow_wide_edit_sco
assert "CUSTOM SECURITY RULE" in new_workflow_prompt
assert '"ask_subject"' in new_workflow_prompt
assert "ACTIVE BLOCK AUTHORING POLICY: CODE-ONLY BROWSER MODE" in new_workflow_prompt
+
+
+def test_ask_carve_out_gates_money_and_destruction_and_never_a_site_sent_message() -> None:
+ prompt = _render_production_prompt()
+ carve_out = _sentence_containing(prompt, "spends money")
+
+ assert "spends money" in carve_out
+ assert "destroys something the user cannot restore" in carve_out
+ # A page click that makes the site email its own account holder is not the workflow
+ # sending anything, and no permission clause may read it as one.
+ assert "message or email" not in prompt
diff --git a/tests/unit/test_workflow_copilot_route.py b/tests/unit/test_workflow_copilot_route.py
index 5a1e8aae3..d1c1d8167 100644
--- a/tests/unit/test_workflow_copilot_route.py
+++ b/tests/unit/test_workflow_copilot_route.py
@@ -31,6 +31,7 @@ from skyvern.forge.agent_functions import AgentFunction
from skyvern.forge.sdk.api.llm.exceptions import LLMProviderError
from skyvern.forge.sdk.artifact.models import ArtifactType
from skyvern.forge.sdk.copilot import agent as agent_module
+from skyvern.forge.sdk.copilot.browser_ablation import CopilotEvalMode
from skyvern.forge.sdk.copilot.canonical_ownership import workflow_content_fingerprint
from skyvern.forge.sdk.copilot.context import AgentResult, TurnNarrativePayload
from skyvern.forge.sdk.copilot.enforcement import TOTAL_TIMEOUT_SECONDS
@@ -112,6 +113,7 @@ def _make_chat_request(
code_block: bool | None = None,
keep_pending_proposal: bool = False,
idempotency_key: str | None = None,
+ eval_entrypoint_url: str | None = None,
) -> WorkflowCopilotChatRequest:
return WorkflowCopilotChatRequest(
workflow_permanent_id="wpid-1",
@@ -124,6 +126,7 @@ def _make_chat_request(
code_block=code_block,
keep_pending_proposal=keep_pending_proposal,
idempotency_key=idempotency_key,
+ eval_entrypoint_url=eval_entrypoint_url,
)
@@ -1452,7 +1455,11 @@ async def test_flag_on_mid_stream_disconnect_restores_when_persisted_and_not_aut
restore_mock, _ = setup_new_copilot_mocks(monkeypatch, chat, original_workflow, agent_result)
- response = await workflow_copilot_chat_post(api_key_request, _make_chat_request(), organization)
+ response = await workflow_copilot_chat_post(
+ api_key_request,
+ _make_chat_request(mode="build", code_block=False),
+ organization,
+ )
assert response is captured["sentinel"]
stream = MagicMock()
@@ -1465,6 +1472,12 @@ async def test_flag_on_mid_stream_disconnect_restores_when_persisted_and_not_aut
assert callable(handler)
await handler(stream)
+ app.AGENT_FUNCTION.get_copilot_config_for_request.assert_awaited_once_with(
+ "org-1",
+ code_block_mode=False,
+ composer_mode="build",
+ )
+
if expect_restore:
restore_mock.assert_awaited_once()
else:
@@ -4102,3 +4115,187 @@ def test_a_client_side_http_error_stays_the_products_own_answer() -> None:
assert (
workflow_copilot_route._http_exception_failure_kind(HTTPException(status_code=403, detail="forbidden")) is None
)
+
+
+def _eval_header_request() -> MagicMock:
+ request = MagicMock()
+ request.headers = {"x-copilot-eval": "odysseys"}
+ return request
+
+
+def _install_v2_dispatch(
+ monkeypatch: pytest.MonkeyPatch, *, eval_inputs_enabled: bool, eval_organization_ids: list[str] | None = None
+) -> AsyncMock:
+ monkeypatch.setattr(settings, "WORKFLOW_COPILOT_ODYSSEYS_EVAL_INPUTS_ENABLED", eval_inputs_enabled)
+ monkeypatch.setattr(
+ settings,
+ "WORKFLOW_COPILOT_ODYSSEYS_EVAL_ORGANIZATION_IDS",
+ ["org-1"] if eval_organization_ids is None else eval_organization_ids,
+ )
+ monkeypatch.setattr(settings, "ENABLE_WORKFLOW_COPILOT_V2", True)
+ new_copilot_mock = AsyncMock(return_value=object())
+ monkeypatch.setattr(
+ "skyvern.forge.sdk.routes.workflow_copilot._new_copilot_chat_post",
+ new_copilot_mock,
+ )
+ return new_copilot_mock
+
+
+async def test_eval_entrypoint_url_is_rejected_when_the_eval_setting_is_off(
+ monkeypatch: pytest.MonkeyPatch, organization: SimpleNamespace
+) -> None:
+ new_copilot_mock = _install_v2_dispatch(monkeypatch, eval_inputs_enabled=False)
+
+ with pytest.raises(HTTPException) as excinfo:
+ await workflow_copilot_chat_post(
+ _eval_header_request(),
+ _make_chat_request(eval_entrypoint_url="https://seed.example"),
+ organization,
+ )
+
+ assert excinfo.value.status_code == 400
+ new_copilot_mock.assert_not_awaited()
+
+
+async def test_eval_entrypoint_url_is_rejected_when_the_caller_org_is_not_allowlisted(
+ monkeypatch: pytest.MonkeyPatch, organization: SimpleNamespace
+) -> None:
+ new_copilot_mock = _install_v2_dispatch(
+ monkeypatch, eval_inputs_enabled=True, eval_organization_ids=["some-other-eval-org"]
+ )
+
+ with pytest.raises(HTTPException) as excinfo:
+ await workflow_copilot_chat_post(
+ _eval_header_request(),
+ _make_chat_request(eval_entrypoint_url="https://seed.example"),
+ organization,
+ )
+
+ assert excinfo.value.status_code == 400
+ new_copilot_mock.assert_not_awaited()
+
+
+async def test_eval_entrypoint_url_is_rejected_when_the_eval_header_is_absent(
+ monkeypatch: pytest.MonkeyPatch, anon_request: MagicMock, organization: SimpleNamespace
+) -> None:
+ new_copilot_mock = _install_v2_dispatch(monkeypatch, eval_inputs_enabled=True)
+
+ with pytest.raises(HTTPException) as excinfo:
+ await workflow_copilot_chat_post(
+ anon_request,
+ _make_chat_request(eval_entrypoint_url="https://seed.example"),
+ organization,
+ )
+
+ assert excinfo.value.status_code == 400
+ new_copilot_mock.assert_not_awaited()
+
+
+ "eval_entrypoint_url",
+ [
+ "file:///etc/passwd",
+ "javascript:alert(1)",
+ "https://",
+ "not a url",
+ "https://exa mple.com",
+ "https://example.com:bad/path",
+ "https://:443",
+ "https://example.com/a b",
+ "https://user:[email protected]",
+ " https://seed.example ",
+ # A caller past all three gates still cannot aim the browser at cloud metadata or a
+ # private range; the navigation guard refuses these too, this is the earlier 400.
+ "http://169.254.169.254/latest/meta-data/",
+ "http://10.0.0.5/internal",
+ "http://metadata.google.internal/computeMetadata/v1/",
+ ],
+)
+async def test_a_non_http_eval_entrypoint_url_is_rejected_with_both_gates_open(
+ monkeypatch: pytest.MonkeyPatch, organization: SimpleNamespace, eval_entrypoint_url: str
+) -> None:
+ new_copilot_mock = _install_v2_dispatch(monkeypatch, eval_inputs_enabled=True)
+
+ with pytest.raises(HTTPException) as excinfo:
+ await workflow_copilot_chat_post(
+ _eval_header_request(),
+ _make_chat_request(eval_entrypoint_url=eval_entrypoint_url),
+ organization,
+ )
+
+ assert excinfo.value.status_code == 400
+ new_copilot_mock.assert_not_awaited()
+
+
[email protected]("eval_mode", [None, CopilotEvalMode.BROWSER_ABLATION])
+async def test_an_admitted_eval_entrypoint_url_reaches_the_agent_path_byte_exact(
+ monkeypatch: pytest.MonkeyPatch, organization: SimpleNamespace, eval_mode: CopilotEvalMode | None
+) -> None:
+ new_copilot_mock = _install_v2_dispatch(monkeypatch, eval_inputs_enabled=True)
+ monkeypatch.setattr(settings, "WORKFLOW_COPILOT_BROWSER_ABLATION_ENABLED", True)
+ monkeypatch.setattr(settings, "WORKFLOW_COPILOT_BROWSER_ABLATION_ORGANIZATION_IDS", [organization.organization_id])
+ request = _eval_header_request()
+ if eval_mode is not None:
+ request.headers["x-copilot-eval-mode"] = eval_mode.value
+
+ await workflow_copilot_chat_post(
+ request,
+ _make_chat_request(eval_entrypoint_url="https://seed.example"),
+ organization,
+ )
+
+ assert new_copilot_mock.await_args.kwargs["eval_entrypoint_url"] == "https://seed.example"
+ assert new_copilot_mock.await_args.kwargs.get("eval_mode") == eval_mode
+
+
+async def test_the_entrypoint_gate_answers_before_the_eval_mode_gate(
+ monkeypatch: pytest.MonkeyPatch, organization: SimpleNamespace
+) -> None:
+ new_copilot_mock = _install_v2_dispatch(monkeypatch, eval_inputs_enabled=False)
+ monkeypatch.setattr(settings, "WORKFLOW_COPILOT_BROWSER_ABLATION_ENABLED", False)
+ request = _eval_header_request()
+ request.headers["x-copilot-eval-mode"] = CopilotEvalMode.BROWSER_ABLATION.value
+
+ with pytest.raises(HTTPException) as excinfo:
+ await workflow_copilot_chat_post(
+ request,
+ _make_chat_request(eval_entrypoint_url="https://seed.example"),
+ organization,
+ )
+
+ assert excinfo.value.status_code == 400
+ new_copilot_mock.assert_not_awaited()
+
+
+async def test_an_eval_entrypoint_url_is_rejected_on_the_legacy_copilot_path(
+ monkeypatch: pytest.MonkeyPatch, organization: SimpleNamespace
+) -> None:
+ new_copilot_mock = _install_v2_dispatch(monkeypatch, eval_inputs_enabled=True)
+
+ with pytest.raises(HTTPException) as excinfo:
+ await workflow_copilot_chat_post(
+ _eval_header_request(),
+ _make_chat_request(mode="ask", eval_entrypoint_url="https://seed.example"),
+ organization,
+ )
+
+ assert excinfo.value.status_code == 400
+ new_copilot_mock.assert_not_awaited()
+
+
+async def test_a_request_without_an_eval_entrypoint_url_reaches_the_agent_path_unchanged(
+ monkeypatch: pytest.MonkeyPatch, anon_request: MagicMock, organization: SimpleNamespace
+) -> None:
+ new_copilot_mock = _install_v2_dispatch(monkeypatch, eval_inputs_enabled=False)
+
+ await workflow_copilot_chat_post(anon_request, _make_chat_request(), organization)
+
+ assert new_copilot_mock.await_args.kwargs["eval_entrypoint_url"] is None
diff --git a/tests/unit/test_workflow_runtime_completion.py b/tests/unit/test_workflow_runtime_completion.py
index dab8b6344..09d0d54bb 100644
--- a/tests/unit/test_workflow_runtime_completion.py
+++ b/tests/unit/test_workflow_runtime_completion.py
@@ -97,6 +97,14 @@ _DERIVED_CONTRACT = {
}
+def _downloaded_file(name: str, *, artifact_id: str | None = None):
+ """What ``get_downloaded_files`` actually returns: a FileInfo, never a bare filename.
+
+ A bare string makes the grader raise on ``.artifact_id``, and the raise is swallowed into an
+ ungraded ``completed`` — a green that proves nothing about delivery."""
+ return SimpleNamespace(artifact_id=artifact_id, filename=name, checksum=None, file_size=None)
+
+
def _wire_finalize(monkeypatch, *, contract, downloaded):
"""A WorkflowService with just enough wired to exercise the finalize status decision."""
from skyvern.forge.sdk.workflow.service import WorkflowService
@@ -126,7 +134,14 @@ def _wire_finalize(monkeypatch, *, contract, downloaded):
monkeypatch.setattr(
service_module.app,
"STORAGE",
- SimpleNamespace(get_downloaded_files=AsyncMock(return_value=list(downloaded))),
+ SimpleNamespace(
+ get_downloaded_files=AsyncMock(
+ return_value=[
+ entry if hasattr(entry, "artifact_id") else _downloaded_file(entry, artifact_id=f"a_{index}")
+ for index, entry in enumerate(downloaded)
+ ]
+ )
+ ),
)
return service, run, statuses
@@ -197,6 +212,31 @@ async def test_finalize_completes_a_run_that_produced_its_declared_file(monkeypa
assert statuses == [WorkflowRunStatus.completed]
+async def test_a_run_that_delivered_fewer_files_than_declared_is_terminated(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ """Proves the grader actually ran rather than raising its way to `completed`.
+
+ The neighbouring completes-on-delivery case cannot tell those apart: a grader that raises is
+ swallowed and leaves the run completed, which is the same status a satisfied contract writes.
+ A shortfall is only reachable when grading really executed."""
+ contract = {
+ "schema_version": 1,
+ "criteria": [{"id": "declared_download", "kind": "registered_download", "min_count": 2}],
+ }
+ service, run, statuses = _wire_finalize(monkeypatch, contract=contract, downloaded=["invoice.pdf"])
+
+ await service._finalize_workflow_run_status(
+ workflow_run_id=run.workflow_run_id,
+ workflow_run=run,
+ pre_finally_status=WorkflowRunStatus.running,
+ pre_finally_failure_reason=None,
+ )
+
+ assert statuses == [WorkflowRunStatus.terminated]
+
+
@pytest.mark.asyncio
async def test_finalize_leaves_a_contract_less_workflow_alone(monkeypatch: pytest.MonkeyPatch) -> None:
service, run, statuses = _wire_finalize(monkeypatch, contract=None, downloaded=[])
diff --git a/tests/unit/test_workflow_service_managed_browser_profile.py b/tests/unit/test_workflow_service_managed_browser_profile.py
index 44d60a7fa..98dabd93e 100644
--- a/tests/unit/test_workflow_service_managed_browser_profile.py
+++ b/tests/unit/test_workflow_service_managed_browser_profile.py
@@ -17,7 +17,6 @@ from skyvern.forge.sdk.workflow.browser_profile_key import (
from skyvern.forge.sdk.workflow.models.block import BlockType
from skyvern.forge.sdk.workflow.models.workflow import WorkflowRunStatus
from skyvern.forge.sdk.workflow.service import (
- CODE_BLOCK_SESSION_TIMEOUT_MINUTES,
WorkflowBrowserCleanupResult,
WorkflowService,
)
@@ -150,7 +149,6 @@ def _patch_execute_workflow_deps(
monkeypatch.setattr(svc, "get_workflow_output_parameters", AsyncMock(return_value=[]))
monkeypatch.setattr(svc, "_collect_inherited_workflow_system_prompt", AsyncMock(return_value=None))
monkeypatch.setattr(svc, "auto_create_browser_session_if_needed", AsyncMock(return_value=None))
- monkeypatch.setattr(svc, "auto_create_browser_session_for_code_block_if_needed", AsyncMock(return_value=None))
monkeypatch.setattr(svc, "_browser_profile_is_managed", AsyncMock(return_value=False))
monkeypatch.setattr(svc, "_execute_workflow_blocks", AsyncMock(return_value=(refreshed_run, set())))
monkeypatch.setattr(svc, "generate_script_if_needed", AsyncMock())
@@ -364,41 +362,6 @@ async def test_auto_create_browser_session_for_human_interaction_loads_managed_p
)
-async def test_auto_create_browser_session_for_code_block_loads_managed_profile_pin(
- monkeypatch: pytest.MonkeyPatch,
-) -> None:
- create_session = AsyncMock(return_value=SimpleNamespace(persistent_browser_session_id="pbs_test"))
- monkeypatch.setattr(app.PERSISTENT_SESSIONS_MANAGER, "create_session", create_session)
- monkeypatch.setattr(
- app.AGENT_FUNCTION,
- "should_auto_create_browser_session_for_code_block",
- AsyncMock(return_value=True),
- )
- workflow = SimpleNamespace(
- workflow_id="wf_1",
- workflow_permanent_id="wpid_test",
- workflow_definition=SimpleNamespace(blocks=[SimpleNamespace(block_type=BlockType.CODE, loop_blocks=[])]),
- )
-
- browser_session = await WorkflowService().auto_create_browser_session_for_code_block_if_needed(
- "o_test",
- workflow,
- workflow_run_id="wr_test",
- browser_profile_id="bp_managed",
- )
-
- assert browser_session.persistent_browser_session_id == "pbs_test"
- create_session.assert_awaited_once_with(
- organization_id="o_test",
- timeout_minutes=CODE_BLOCK_SESSION_TIMEOUT_MINUTES,
- browser_profile_id="bp_managed",
- proxy_location=None,
- inherit_profile_proxy=True,
- workflow_run_id="wr_test",
- )
-
-
@pytest.mark.asyncio
async def test_browser_profile_is_managed_distinguishes_user_profiles(monkeypatch: pytest.MonkeyPatch) -> None:
get_browser_profile = AsyncMock(return_value=SimpleNamespace(is_managed=False))
@@ -829,40 +792,6 @@ def _patch_session_backed_run(monkeypatch: pytest.MonkeyPatch, svc: WorkflowServ
return close_session
-def _patch_code_block_session(monkeypatch: pytest.MonkeyPatch, svc: WorkflowService) -> AsyncMock:
- close_session = _patch_session_backed_run(monkeypatch, svc)
- monkeypatch.setattr(
- svc,
- "auto_create_browser_session_for_code_block_if_needed",
- AsyncMock(return_value=SimpleNamespace(persistent_browser_session_id="pbs_code_block")),
- )
- return close_session
-
-
[email protected]("terminal_status", [WorkflowRunStatus.completed, WorkflowRunStatus.failed])
-async def test_execute_workflow_closes_auto_created_code_block_session(
- monkeypatch: pytest.MonkeyPatch,
- terminal_status: WorkflowRunStatus,
-) -> None:
- workflow = _execute_workflow()
- terminal_run = _execute_workflow_run(terminal_status)
- order: list[str] = []
-
- svc = WorkflowService()
- _patch_execute_workflow_deps(monkeypatch, svc, workflow, _execute_workflow_run(WorkflowRunStatus.running))
- close_session = _patch_code_block_session(monkeypatch, svc)
- _patch_browser_cleanup(monkeypatch, svc, order)
- _patch_finalize(monkeypatch, svc, order, terminal_run)
-
- result = await _run_execute_workflow(svc)
-
- assert result is terminal_run
- # Positional assertion pins the arg-name-free contract: the cloud manager names the second
- # parameter session_id while the OSS protocol names it browser_session_id.
- close_session.assert_awaited_once_with("o_test", "pbs_code_block")
-
-
@pytest.mark.asyncio
async def test_execute_workflow_does_not_close_caller_supplied_session(
monkeypatch: pytest.MonkeyPatch,
@@ -907,111 +836,3 @@ async def test_execute_workflow_does_not_close_human_interaction_session(
assert result is completed_run
close_session.assert_not_awaited()
-
-
-async def test_execute_workflow_completes_cleanup_when_code_block_session_close_fails(
- monkeypatch: pytest.MonkeyPatch,
-) -> None:
- workflow = _execute_workflow()
- completed_run = _execute_workflow_run(WorkflowRunStatus.completed)
- order: list[str] = []
-
- svc = WorkflowService()
- _patch_execute_workflow_deps(monkeypatch, svc, workflow, _execute_workflow_run(WorkflowRunStatus.running))
- close_session = _patch_code_block_session(monkeypatch, svc)
- close_session.side_effect = RuntimeError("close failed")
- _patch_browser_cleanup(monkeypatch, svc, order)
- _patch_finalize(monkeypatch, svc, order, completed_run)
-
- result = await _run_execute_workflow(svc)
-
- assert result is completed_run
- close_session.assert_awaited_once()
-
-
-async def test_execute_workflow_closes_code_block_session_when_begin_session_fails(
- monkeypatch: pytest.MonkeyPatch,
-) -> None:
- workflow = _execute_workflow()
- failed_run = _execute_workflow_run(WorkflowRunStatus.failed)
- order: list[str] = []
-
- svc = WorkflowService()
- _patch_execute_workflow_deps(monkeypatch, svc, workflow, _execute_workflow_run(WorkflowRunStatus.running))
- close_session = _patch_code_block_session(monkeypatch, svc)
- monkeypatch.setattr(
- app.PERSISTENT_SESSIONS_MANAGER, "begin_session", AsyncMock(side_effect=RuntimeError("begin failed"))
- )
- monkeypatch.setattr(svc, "mark_workflow_run_as_failed", AsyncMock(return_value=failed_run))
- _patch_browser_cleanup(monkeypatch, svc, order)
-
- result = await _run_execute_workflow(svc)
-
- assert result is failed_run
- close_session.assert_awaited_once_with("o_test", "pbs_code_block")
-
-
-async def test_code_block_session_close_deferred_while_child_runs_active(
- monkeypatch: pytest.MonkeyPatch,
-) -> None:
- workflow = _execute_workflow()
- completed_run = _execute_workflow_run(WorkflowRunStatus.completed)
- order: list[str] = []
-
- svc = WorkflowService()
- _patch_execute_workflow_deps(monkeypatch, svc, workflow, _execute_workflow_run(WorkflowRunStatus.running))
- close_session = _patch_code_block_session(monkeypatch, svc)
- cleanup_result = _browser_cleanup_result()
- cleanup_result.child_workflow_run_ids = ["wr_child"]
- monkeypatch.setattr(
- svc,
- "_clean_up_workflow_browser",
- AsyncMock(side_effect=lambda **_kwargs: order.append("teardown") or cleanup_result),
- )
- monkeypatch.setattr(
- service_module.app.DATABASE.workflow_runs,
- "get_workflow_runs_by_parent_workflow_run_id",
- AsyncMock(return_value=[_execute_workflow_run(WorkflowRunStatus.running)]),
- )
- _patch_finalize(monkeypatch, svc, order, completed_run)
-
- result = await _run_execute_workflow(svc)
-
- assert result is completed_run
- close_session.assert_not_awaited()
-
-
-async def test_clean_up_workflow_closes_code_block_session_when_webhook_raises(
- monkeypatch: pytest.MonkeyPatch,
-) -> None:
- svc = WorkflowService()
- workflow = _execute_workflow()
- completed_run = _execute_workflow_run(WorkflowRunStatus.completed)
- close_session = _patch_session_backed_run(monkeypatch, svc)
- monkeypatch.setattr(app.AGENT_FUNCTION, "on_workflow_run_terminal", AsyncMock())
- monkeypatch.setattr(app.ARTIFACT_MANAGER, "wait_for_upload_aiotasks", AsyncMock())
- monkeypatch.setattr(app.STORAGE, "save_downloaded_files", AsyncMock())
- monkeypatch.setattr(
- service_module.app,
- "WORKFLOW_CONTEXT_MANAGER",
- SimpleNamespace(remove_workflow_run_context=lambda _workflow_run_id: None),
- )
- monkeypatch.setattr(service_module.skyvern_context, "current", lambda: None)
- monkeypatch.setattr(svc, "_schedule_credential_fallback_retry", lambda _workflow_run: None)
- monkeypatch.setattr(svc, "execute_workflow_webhook", AsyncMock(side_effect=RuntimeError("webhook down")))
-
- with pytest.raises(RuntimeError, match="webhook down"):
- await svc.clean_up_workflow(
- workflow=workflow,
- workflow_run=completed_run,
- api_key=None,
- browser_session_id="pbs_code_block",
- browser_cleanup_result=_browser_cleanup_result(),
- code_block_browser_session_id="pbs_code_block",
- )
-
- close_session.assert_awaited_once_with("o_test", "pbs_code_block")
diff --git a/tests/unit_tests/test_streaming_screencast.py b/tests/unit_tests/test_streaming_screencast.py
index a34096a21..f677ddb02 100644
--- a/tests/unit_tests/test_streaming_screencast.py
+++ b/tests/unit_tests/test_streaming_screencast.py
@@ -223,12 +223,16 @@ class _FakeCdpSession:
self.handlers: dict[str, object] = {}
self.sent: list[tuple[str, dict]] = []
self.detached = False
+ self.fail_methods: set[str] = set()
+ self.fail_after_calls: dict[str, int] = {}
def on(self, event: str, handler: object) -> None:
self.handlers[event] = handler
async def send(self, method: str, params: dict | None = None) -> dict:
self.sent.append((method, params or {}))
+ if method in self.fail_methods and self.methods_sent().count(method) > self.fail_after_calls.get(method, 0):
+ raise RuntimeError(f"{method} refused")
if method == "Page.captureScreenshot":
return {"data": "primed"}
return {}
diff --git a/tests/unit_tests/webeye/test_navigation_retry.py b/tests/unit_tests/webeye/test_navigation_retry.py
index 1d9b8bf92..375d0f5ca 100644
--- a/tests/unit_tests/webeye/test_navigation_retry.py
+++ b/tests/unit_tests/webeye/test_navigation_retry.py
@@ -362,12 +362,29 @@ async def test_navigate_with_retry_allows_public_navigation_without_response() -
navigate = AsyncMock(return_value=None)
settle = AsyncMock()
- await navigate_with_retry(
+ status = await navigate_with_retry(
navigate=navigate, url="https://example.com/", retry_times=3, settle=settle, sleep=AsyncMock()
)
navigate.assert_awaited_once()
settle.assert_awaited_once()
+ assert status is None # no response object -> no status to carry
+
+
[email protected]("http_status", [200, 404, 410, 500])
+async def test_navigate_with_retry_returns_final_response_status(http_status: int) -> None:
+ # The status is what lets the Task V3 loop classify a dead/removed starting URL, so navigate_with_retry
+ # must surface the FINAL response's HTTP status (not swallow it as it did before).
+ response = _redirect_response("https://example.com/")
+ response.status = http_status # type: ignore[attr-defined]
+ navigate = AsyncMock(return_value=response)
+
+ result = await navigate_with_retry(
+ navigate=navigate, url="https://example.com/", retry_times=3, settle=AsyncMock(), sleep=AsyncMock()
+ )
+
+ assert result == http_status
# Empty and about:blank targets are non-egressing continuation/reconnect URLs that reach