Skip to content

Automate browser based workflows with AI

SWCE 6/7: attribute exposure events to flag variants (#8244)

Marc Kelechava7f5eaea6e65b
diff --git a/.env.example b/.env.example
index 004fcd264..170c5903a 100644
--- a/.env.example
+++ b/.env.example
@@ -144,6 +144,11 @@ DATABASE_STRING="postgresql+psycopg://skyvern@localhost/skyvern"
# PORT: Port to run the agent on.
PORT=8000
+# API_LIMIT_CONCURRENCY: uvicorn answers 503 without dispatching to ASGI once open connections
+# or in-flight requests reach this. Counts idle keep-alives and long-lived /stream sockets, so
+# size it against concurrent connections per process. Leave empty or set 0 for no limit.
+# API_LIMIT_CONCURRENCY=512
+
# Analytics configuration:
# ANALYTICS_ID: Distinct analytics ID (a UUID is generated if left blank).
ANALYTICS_ID="anonymous"
diff --git a/alembic/versions/2026_08_21_2229-613e4f756671_add_slug_to_organizations.py b/alembic/versions/2026_08_21_2229-613e4f756671_add_slug_to_organizations.py
new file mode 100644
index 000000000..3205b3e29
--- /dev/null
+++ b/alembic/versions/2026_08_21_2229-613e4f756671_add_slug_to_organizations.py
@@ -0,0 +1,37 @@
+"""add slug to organizations
+
+Revision ID: 613e4f756671
+Revises: 2c948904bb50
+Create Date: 2026-08-21T22:29:43.807483+00:00
+
+"""
+
+from typing import Sequence, Union
+
+import sqlalchemy as sa
+
+from alembic import op
+
+# revision identifiers, used by Alembic.
+revision: str = "613e4f756671"
+down_revision: Union[str, None] = "2c948904bb50"
+branch_labels: Union[str, Sequence[str], None] = None
+depends_on: Union[str, Sequence[str], None] = None
+
+
+def upgrade() -> None:
+ op.execute("SET LOCAL lock_timeout = '5s'")
+ op.add_column("organizations", sa.Column("slug", sa.String(), nullable=True))
+ op.create_index(
+ "uq_organizations_slug",
+ "organizations",
+ ["slug"],
+ unique=True,
+ postgresql_where=sa.text("slug IS NOT NULL"),
+ )
+
+
+def downgrade() -> None:
+ op.execute("SET LOCAL lock_timeout = '5s'")
+ op.drop_index("uq_organizations_slug", table_name="organizations")
+ op.drop_column("organizations", "slug")
diff --git a/skyvern-frontend/src/routes/browserSessions/BrowserSessionStream.test.tsx b/skyvern-frontend/src/routes/browserSessions/BrowserSessionStream.test.tsx
index bbebd40f3..c7c869431 100644
--- a/skyvern-frontend/src/routes/browserSessions/BrowserSessionStream.test.tsx
+++ b/skyvern-frontend/src/routes/browserSessions/BrowserSessionStream.test.tsx
@@ -6,12 +6,13 @@ import { act, render, screen, waitFor } from "@testing-library/react";
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
import { useSettingsStore } from "@/store/SettingsStore";
-import { BrowserSessionStream } from "./BrowserSessionStream";
import {
- diagnosticForStatus,
+ STREAM_MAX_RECONNECT_DELAY_MS,
isTerminalStreamStatus,
shouldReconnectStream,
-} from "./BrowserSessionStream.utils";
+} from "@/routes/streaming/streamLifecycle";
+import { BrowserSessionStream } from "./BrowserSessionStream";
+import { diagnosticForStatus } from "./BrowserSessionStream.utils";
const env = vi.hoisted(() => ({
wssBaseUrl: "ws://127.0.0.1:8000/api/v1",
@@ -560,7 +561,10 @@ describe("BrowserSessionStream reconnect lifecycle", () => {
},
);
});
- await act(async () => vi.advanceTimersByTimeAsync(1000));
+ // Retries back off, so the longest gap covers every attempt in the budget.
+ await act(async () =>
+ vi.advanceTimersByTimeAsync(STREAM_MAX_RECONNECT_DELAY_MS),
+ );
}
expect(FakeStreamSocket.instances).toHaveLength(22);
@@ -573,12 +577,49 @@ describe("BrowserSessionStream reconnect lifecycle", () => {
},
);
});
- await act(async () => vi.advanceTimersByTimeAsync(1000));
+ await act(async () =>
+ vi.advanceTimersByTimeAsync(STREAM_MAX_RECONNECT_DELAY_MS),
+ );
expect(FakeStreamSocket.instances).toHaveLength(22);
expect(screen.queryByTestId("stream-frame")).toBeNull();
expect(screen.getByText("Stream connection dropped")).toBeTruthy();
});
+ it("retires the stale frame and reconnects when the stream ends non-terminally (SKY-14617)", async () => {
+ vi.useFakeTimers();
+ vi.stubGlobal("WebSocket", FakeStreamSocket);
+ render(<BrowserSessionStream browserSessionId="pbs_stale" />);
+ await act(async () => Promise.resolve());
+ const socket = FakeStreamSocket.instances[0]!;
+
+ act(() => {
+ socket.emitStreamMessage({
+ status: "running",
+ screenshot: "last-live-frame",
+ });
+ });
+ act(() => {
+ vi.advanceTimersToNextFrame();
+ });
+ expect(screen.getByTestId("stream-frame")).toBeTruthy();
+
+ // What the backend sends once its screencast loop returns for a session that is
+ // still alive: a bare, non-terminal status, then a clean close.
+ act(() => {
+ socket.emitStreamMessage({ status: "running" });
+ });
+ expect(screen.queryByTestId("stream-frame")).toBeNull();
+ expect(
+ screen.getByText("This live view has stopped updating"),
+ ).toBeTruthy();
+
+ act(() => {
+ socket.emit("close", { code: 1000, reason: "" });
+ });
+ await act(async () => vi.advanceTimersByTimeAsync(1000));
+ expect(FakeStreamSocket.instances).toHaveLength(2);
+ });
+
it("terminal status closes once, clears the frame and store, and never retries", async () => {
vi.useFakeTimers();
vi.stubGlobal("WebSocket", FakeStreamSocket);
@@ -653,31 +694,33 @@ describe("BrowserSessionStream reconnect lifecycle", () => {
});
describe("shouldReconnectStream", () => {
- it("reconnects non-terminal stream closes below the attempt limit", () => {
+ it("reconnects a clean server close, not only an abnormal one (SKY-14617)", () => {
expect(
shouldReconnectStream({
closeCode: 1006,
closeReason: "",
- terminalStatusSeen: false,
+ streamFinished: false,
reconnectAttempts: 0,
}),
).toBe(true);
- });
-
- it("does not reconnect terminal, VNC fallback, normal, or exhausted stream closes", () => {
+ // The server closes cleanly once its screencast loop ends, which for a live
+ // entity used to mean no reconnect at all and a frozen frame on screen.
expect(
shouldReconnectStream({
closeCode: 1000,
closeReason: "",
- terminalStatusSeen: true,
+ streamFinished: false,
reconnectAttempts: 0,
}),
- ).toBe(false);
+ ).toBe(true);
+ });
+
+ it("does not reconnect a finished, transport-switched, or exhausted stream", () => {
expect(
shouldReconnectStream({
closeCode: 1000,
closeReason: "",
- terminalStatusSeen: false,
+ streamFinished: true,
reconnectAttempts: 0,
}),
).toBe(false);
@@ -685,7 +728,7 @@ describe("shouldReconnectStream", () => {
shouldReconnectStream({
closeCode: 4001,
closeReason: "use-vnc-streaming",
- terminalStatusSeen: false,
+ streamFinished: false,
reconnectAttempts: 0,
}),
).toBe(false);
@@ -693,7 +736,7 @@ describe("shouldReconnectStream", () => {
shouldReconnectStream({
closeCode: 1006,
closeReason: "",
- terminalStatusSeen: false,
+ streamFinished: false,
reconnectAttempts: 20,
}),
).toBe(false);
diff --git a/skyvern-frontend/src/routes/browserSessions/BrowserSessionStream.tsx b/skyvern-frontend/src/routes/browserSessions/BrowserSessionStream.tsx
index a1b76cb2d..5315b56b1 100644
--- a/skyvern-frontend/src/routes/browserSessions/BrowserSessionStream.tsx
+++ b/skyvern-frontend/src/routes/browserSessions/BrowserSessionStream.tsx
@@ -14,12 +14,22 @@ import {
type StreamDiagnostic,
} from "@/routes/streaming/StreamDiagnostics";
import {
- STREAM_MAX_RECONNECT_ATTEMPTS,
- STREAM_RECONNECT_DELAY_MS,
+ BROWSER_SESSION_STREAM_SUBJECT,
diagnosticForStatus,
+} from "./BrowserSessionStream.utils";
+import {
+ STREAM_ABNORMAL_CLOSE_CODE,
+ STREAM_STALE_FRAME_AFTER_ATTEMPTS,
+ STREAM_VNC_FALLBACK_CLOSE_CODE,
+ STREAM_VNC_FALLBACK_CLOSE_REASON,
+ diagnosticForReconnectExhausted,
+ diagnosticForStreamEnded,
+ isStreamStatusOnlyMessage,
isTerminalStreamStatus,
+ reconnectHint,
shouldReconnectStream,
-} from "./BrowserSessionStream.utils";
+ streamReconnectDelayMs,
+} from "@/routes/streaming/streamLifecycle";
import { useSettingsStore } from "@/store/SettingsStore";
type StreamMessage = {
@@ -38,16 +48,11 @@ const STARTING_DIAGNOSTIC: StreamDiagnostic = {
pending: true,
};
-function diagnosticForReconnectExhausted(): StreamDiagnostic {
- return {
- title: "Stream connection dropped",
- detail: "The browser stream disconnected and could not reconnect.",
- hint: "Refresh the editor or create a new browser session.",
- };
-}
-
function diagnosticForClose(event: CloseEvent): StreamDiagnostic {
- if (event.code === 4001 || event.reason === "use-vnc-streaming") {
+ if (
+ event.code === STREAM_VNC_FALLBACK_CLOSE_CODE ||
+ event.reason === STREAM_VNC_FALLBACK_CLOSE_REASON
+ ) {
return {
title: "Backend wants to use VNC streaming",
detail:
@@ -55,10 +60,10 @@ function diagnosticForClose(event: CloseEvent): StreamDiagnostic {
hint: "Check BROWSER_STREAMING_MODE on the backend and the runtime config response.",
};
}
- if (event.code === 1006) {
+ if (event.code === STREAM_ABNORMAL_CLOSE_CODE) {
return {
title: "The connection slipped away",
- detail: "The browser stream WebSocket closed before sending a frame.",
+ detail: "The browser stream WebSocket dropped without closing cleanly.",
hint: "Check that the API server is running and reachable from the UI.",
};
}
@@ -121,8 +126,12 @@ function BrowserSessionStream({
const rafRef = useRef<number | null>(null);
const lastCommittedTokenRef = useRef<number>(0);
const reconnectAttemptsRef = useRef(0);
- const terminalStatusSeenRef = useRef(false);
+ const streamFinishedRef = useRef(false);
const reconnectTimerRef = useRef<ReturnType<typeof setTimeout> | null>(null);
+ // Why the stream stopped, when the server told us before closing. Survives into
+ // the close handler so a reconnect notice augments that reason instead of
+ // replacing it with a generic "closed with code 1000".
+ const streamEndedDiagnosticRef = useRef<StreamDiagnostic | null>(null);
// The CDP input socket must be wired whenever the stream can be controlled,
// whether by default interaction or via the take-control button.
@@ -172,7 +181,8 @@ function BrowserSessionStream({
setDiagnostic(STARTING_DIAGNOSTIC);
hasFrameRef.current = false;
reconnectAttemptsRef.current = 0;
- terminalStatusSeenRef.current = false;
+ streamFinishedRef.current = false;
+ streamEndedDiagnosticRef.current = null;
const clearReconnectTimer = () => {
if (reconnectTimerRef.current) {
@@ -252,6 +262,7 @@ function BrowserSessionStream({
if (message.screenshot) {
hasFrameRef.current = true;
reconnectAttemptsRef.current = 0;
+ streamEndedDiagnosticRef.current = null;
const token = markMessage();
pendingFrameRef.current = {
token,
@@ -276,19 +287,44 @@ function BrowserSessionStream({
onActivityRef.current?.();
}
const isTerminal = isTerminalStreamStatus(message.status);
+ // A bare status frame is the server signing off. After frames have flowed
+ // that ends the live view even when the status itself is non-terminal --
+ // the session outlives the screencast, and rendering its last frame as
+ // current is what left viewers staring at a dead browser (SKY-14617).
+ const streamEnded =
+ isTerminal ||
+ (hasFrameRef.current && isStreamStatusOnlyMessage(message));
if (message.status && (isTerminal || !message.screenshot)) {
- setDiagnostic(diagnosticForStatus(message.status));
+ const endedDiagnostic =
+ streamEnded && !isTerminal
+ ? diagnosticForStreamEnded({
+ status: message.status,
+ subject: BROWSER_SESSION_STREAM_SUBJECT,
+ })
+ : diagnosticForStatus(message.status);
+ streamEndedDiagnosticRef.current = streamEnded
+ ? endedDiagnostic
+ : null;
+ setDiagnostic(endedDiagnostic);
}
- if (isTerminal) {
- terminalStatusSeenRef.current = true;
+ if (streamEnded) {
// Drop the last frame: keeping it leaves a dead, still-interactive
- // screenshot covering the terminal status panel.
+ // screenshot covering the status panel.
clearPendingFrame();
+ hasFrameRef.current = false;
setStreamImgSrc("");
+ // Only a terminal status forecloses reconnecting; a live session whose
+ // screencast ended is exactly the case worth redialling.
+ if (isTerminal) {
+ streamFinishedRef.current = true;
+ }
socket.close();
}
} catch (e) {
console.error("Failed to parse message", e);
+ // The backend only sends non-JSON text to reject credentials, and
+ // retrying that would just burn the reconnect budget in silence.
+ streamFinishedRef.current = true;
setDiagnostic({
title: "The stream said something funny",
detail: "The browser sent a message the UI couldn't parse.",
@@ -313,44 +349,57 @@ function BrowserSessionStream({
clearPendingFrame();
socketRef.current = null;
- if (
- !cancelled &&
- !hasFrameRef.current &&
- !terminalStatusSeenRef.current
- ) {
- setDiagnostic(diagnosticForClose(event));
+ // Prefer the reason the server gave over "the socket closed": after a clean
+ // close those are the same event, and only the former says anything useful.
+ const closeDiagnostic =
+ streamEndedDiagnosticRef.current ?? diagnosticForClose(event);
+ if (!cancelled && !hasFrameRef.current && !streamFinishedRef.current) {
+ setDiagnostic(closeDiagnostic);
}
const canReconnect =
!cancelled &&
shouldReconnectStream({
closeCode: event.code,
closeReason: event.reason,
- terminalStatusSeen: terminalStatusSeenRef.current,
+ streamFinished: streamFinishedRef.current,
reconnectAttempts: reconnectAttemptsRef.current,
});
if (canReconnect) {
+ const delayMs = streamReconnectDelayMs(reconnectAttemptsRef.current);
reconnectAttemptsRef.current += 1;
+ if (
+ hasFrameRef.current &&
+ reconnectAttemptsRef.current > STREAM_STALE_FRAME_AFTER_ATTEMPTS
+ ) {
+ hasFrameRef.current = false;
+ setStreamImgSrc("");
+ }
if (!hasFrameRef.current) {
setDiagnostic({
- ...diagnosticForClose(event),
- hint: `Reconnecting in ${STREAM_RECONNECT_DELAY_MS / 1000}s (${reconnectAttemptsRef.current}/${STREAM_MAX_RECONNECT_ATTEMPTS}).`,
+ ...closeDiagnostic,
+ hint: reconnectHint(reconnectAttemptsRef.current),
});
}
clearReconnectTimer();
reconnectTimerRef.current = setTimeout(() => {
reconnectTimerRef.current = null;
void connect();
- }, STREAM_RECONNECT_DELAY_MS);
+ }, delayMs);
} else if (
!cancelled &&
- !terminalStatusSeenRef.current &&
- hasFrameRef.current &&
- reconnectAttemptsRef.current >= STREAM_MAX_RECONNECT_ATTEMPTS
+ !streamFinishedRef.current &&
+ // A transport switch is the caller's cue to re-mount on VNC, not a drop.
+ event.code !== STREAM_VNC_FALLBACK_CLOSE_CODE &&
+ event.reason !== STREAM_VNC_FALLBACK_CLOSE_REASON
) {
+ // Out of retries with nothing live behind the last frame: say so instead
+ // of leaving that frame up as if it were current.
hasFrameRef.current = false;
setStreamImgSrc("");
- setDiagnostic(diagnosticForReconnectExhausted());
+ setDiagnostic(
+ diagnosticForReconnectExhausted(BROWSER_SESSION_STREAM_SUBJECT),
+ );
}
});
}
diff --git a/skyvern-frontend/src/routes/browserSessions/BrowserSessionStream.utils.ts b/skyvern-frontend/src/routes/browserSessions/BrowserSessionStream.utils.ts
index cd6f02cfb..0a91836f3 100644
--- a/skyvern-frontend/src/routes/browserSessions/BrowserSessionStream.utils.ts
+++ b/skyvern-frontend/src/routes/browserSessions/BrowserSessionStream.utils.ts
@@ -1,48 +1,7 @@
import type { StreamDiagnostic } from "@/routes/streaming/StreamDiagnostics";
+import { isTerminalStreamStatus } from "@/routes/streaming/streamLifecycle";
-const TERMINAL_STREAM_STATUSES = new Set([
- "completed",
- "failed",
- "timeout",
- "session_expired",
- "not_found",
-]);
-
-const STREAM_RECONNECT_DELAY_MS = 1000;
-const STREAM_MAX_RECONNECT_ATTEMPTS = 20;
-const STREAM_ABNORMAL_CLOSE_CODE = 1006;
-const STREAM_VNC_FALLBACK_CLOSE_CODE = 4001;
-const STREAM_VNC_FALLBACK_CLOSE_REASON = "use-vnc-streaming";
-
-function isTerminalStreamStatus(status: string) {
- return TERMINAL_STREAM_STATUSES.has(status);
-}
-
-function shouldReconnectStream({
- closeCode,
- closeReason,
- terminalStatusSeen,
- reconnectAttempts,
-}: {
- closeCode: number;
- closeReason: string;
- terminalStatusSeen: boolean;
- reconnectAttempts: number;
-}) {
- if (terminalStatusSeen) {
- return false;
- }
- if (
- closeCode === STREAM_VNC_FALLBACK_CLOSE_CODE ||
- closeReason === STREAM_VNC_FALLBACK_CLOSE_REASON
- ) {
- return false;
- }
- if (closeCode !== STREAM_ABNORMAL_CLOSE_CODE) {
- return false;
- }
- return reconnectAttempts < STREAM_MAX_RECONNECT_ATTEMPTS;
-}
+const BROWSER_SESSION_STREAM_SUBJECT = "browser session";
function diagnosticForStatus(status: string): StreamDiagnostic {
switch (status) {
@@ -82,6 +41,15 @@ function diagnosticForStatus(status: string): StreamDiagnostic {
hint: "Start a new browser session to try again.",
};
default:
+ // A terminal status with no copy of its own is still over, so it must not
+ // fall through to the "still working on it" animation.
+ if (isTerminalStreamStatus(status)) {
+ return {
+ title: "This browser session is no longer live",
+ detail: `There's no browser left to stream — status: ${status}.`,
+ hint: "Start a new browser session to keep working.",
+ };
+ }
return {
title: "Waiting for browser frames",
detail: `The stream is connected and the session status is ${status}.`,
@@ -90,10 +58,4 @@ function diagnosticForStatus(status: string): StreamDiagnostic {
}
}
-export {
- STREAM_MAX_RECONNECT_ATTEMPTS,
- STREAM_RECONNECT_DELAY_MS,
- diagnosticForStatus,
- isTerminalStreamStatus,
- shouldReconnectStream,
-};
+export { BROWSER_SESSION_STREAM_SUBJECT, diagnosticForStatus };
diff --git a/skyvern-frontend/src/routes/history/RunHistory.tsx b/skyvern-frontend/src/routes/history/RunHistory.tsx
index 5cabc6b13..e2c05d8e8 100644
--- a/skyvern-frontend/src/routes/history/RunHistory.tsx
+++ b/skyvern-frontend/src/routes/history/RunHistory.tsx
@@ -14,7 +14,6 @@ import {
} from "@/components/ui/select";
import { Tip } from "@/components/Tip";
import {
- Status,
TaskRunListItem,
TaskRunType,
TriggerType,
@@ -95,28 +94,10 @@ import {
import { useRowSelection } from "@/hooks/useRowSelection";
import { RunBulkActionBar } from "@/routes/runs/RunBulkActionBar";
import { RunRowActions } from "@/routes/runs/RunRowActions";
-
-const statusValues = new Set<string>(Object.values(Status));
-function isKnownStatus(value: string): value is Status {
- return statusValues.has(value);
-}
-
-function parseStatusParam(raw: string | null): Array<Status> {
- if (!raw) {
- return [];
- }
- const seen = new Set<Status>();
- const out: Array<Status> = [];
- for (const token of raw.split(",")) {
- const trimmed = token.trim();
- if (trimmed === "" || !isKnownStatus(trimmed) || seen.has(trimmed)) {
- continue;
- }
- seen.add(trimmed);
- out.push(trimmed);
- }
- return out;
-}
+import {
+ isKnownStatus,
+ parseStatusParam,
+} from "@/routes/runs/statusFilterParam";
const runTypeGroupValues = new Set<string>(Object.values(RunTypeGroup));
diff --git a/skyvern-frontend/src/routes/runs/statusFilterParam.ts b/skyvern-frontend/src/routes/runs/statusFilterParam.ts
new file mode 100644
index 000000000..6ec36d3ed
--- /dev/null
+++ b/skyvern-frontend/src/routes/runs/statusFilterParam.ts
@@ -0,0 +1,31 @@
+import { Status } from "@/api/types";
+
+const statusValues = new Set<string>(Object.values(Status));
+
+function isKnownStatus(value: string): value is Status {
+ return statusValues.has(value);
+}
+
+/**
+ * Parses the shared `?status=` run-list contract — a comma-separated list of
+ * statuses. Unknown and duplicate tokens are dropped so a hand-edited URL
+ * cannot make the runs request 422.
+ */
+function parseStatusParam(raw: string | null): Array<Status> {
+ if (!raw) {
+ return [];
+ }
+ const seen = new Set<Status>();
+ const out: Array<Status> = [];
+ for (const token of raw.split(",")) {
+ const trimmed = token.trim();
+ if (trimmed === "" || !isKnownStatus(trimmed) || seen.has(trimmed)) {
+ continue;
+ }
+ seen.add(trimmed);
+ out.push(trimmed);
+ }
+ return out;
+}
+
+export { isKnownStatus, parseStatusParam };
diff --git a/skyvern-frontend/src/routes/streaming/streamLifecycle.ts b/skyvern-frontend/src/routes/streaming/streamLifecycle.ts
new file mode 100644
index 000000000..0612319a3
--- /dev/null
+++ b/skyvern-frontend/src/routes/streaming/streamLifecycle.ts
@@ -0,0 +1,140 @@
+import type { StreamDiagnostic } from "@/routes/streaming/StreamDiagnostics";
+
+/**
+ * Shared lifecycle policy for the screencast WebSocket, so the same server status
+ * means the same thing to every consumer. `timeout` in particular is emitted by the
+ * backend for both browser sessions and workflow runs and used to be terminal for
+ * one consumer and invisible to the other (SKY-14617).
+ */
+
+// Covers both entity-final statuses (a run/session that is over) and stream-final
+// ones (the backend gave up before or during the screencast). Either way the server
+// returns right after sending it, so no further frames can arrive on this socket.
+const TERMINAL_STREAM_STATUSES = new Set([
+ "completed",
+ "failed",
+ "terminated",
+ "canceled",
+ "timed_out",
+ "timeout",
+ "session_expired",
+ "not_found",
+]);
+
+const STREAM_RECONNECT_DELAY_MS = 1000;
+const STREAM_MAX_RECONNECT_DELAY_MS = 15000;
+const STREAM_MAX_RECONNECT_ATTEMPTS = 20;
+// A frame survives the first few retries so a momentary blip doesn't flash a panel,
+// then goes: past this the picture is stale enough that showing it is a lie.
+const STREAM_STALE_FRAME_AFTER_ATTEMPTS = 3;
+const STREAM_ABNORMAL_CLOSE_CODE = 1006;
+const STREAM_VNC_FALLBACK_CLOSE_CODE = 4001;
+const STREAM_VNC_FALLBACK_CLOSE_REASON = "use-vnc-streaming";
+
+type StreamStatusMessage = {
+ status?: string;
+ screenshot?: string;
+ format?: string;
+ viewport_width?: number;
+ viewport_height?: number;
+ url?: string;
+};
+
+function isTerminalStreamStatus(status: string) {
+ return TERMINAL_STREAM_STATUSES.has(status);
+}
+
+/**
+ * The backend's `_send_status` frame carries a status and nothing else, and it only
+ * sends one when it is about to stop streaming. Frames always carry pixels, so a bare
+ * status is the stream signing off rather than a mid-stream update.
+ */
+function isStreamStatusOnlyMessage(message: StreamStatusMessage): boolean {
+ return (
+ Boolean(message.status) &&
+ !message.screenshot &&
+ message.url === undefined &&
+ message.format === undefined &&
+ message.viewport_width === undefined &&
+ message.viewport_height === undefined
+ );
+}
+
+function streamReconnectDelayMs(reconnectAttempts: number): number {
+ return Math.min(
+ STREAM_RECONNECT_DELAY_MS * 2 ** reconnectAttempts,
+ STREAM_MAX_RECONNECT_DELAY_MS,
+ );
+}
+
+function shouldReconnectStream({
+ closeCode,
+ closeReason,
+ streamFinished,
+ reconnectAttempts,
+}: {
+ closeCode: number;
+ closeReason: string;
+ // The stream said its last word: a terminal status, or a frame the client could
+ // not parse (the backend only sends non-JSON text for credential failures).
+ streamFinished: boolean;
+ reconnectAttempts: number;
+}) {
+ if (streamFinished) {
+ return false;
+ }
+ if (
+ closeCode === STREAM_VNC_FALLBACK_CLOSE_CODE ||
+ closeReason === STREAM_VNC_FALLBACK_CLOSE_REASON
+ ) {
+ return false;
+ }
+ // Any other close is worth retrying, including a clean one: the server closes
+ // cleanly after the screencast loop ends, and the entity behind it is often still
+ // live, so returning here used to leave a frozen frame and no reconnect.
+ return reconnectAttempts < STREAM_MAX_RECONNECT_ATTEMPTS;
+}
+
+function diagnosticForStreamEnded({
+ status,
+ subject,
+}: {
+ status: string;
+ subject: string;
+}): StreamDiagnostic {
+ return {
+ title: "This live view has stopped updating",
+ detail: `The browser stream ended while the ${subject} is still ${status}, so the last frame you saw is no longer current.`,
+ };
+}
+
+function diagnosticForReconnectExhausted(subject: string): StreamDiagnostic {
+ return {
+ title: "Stream connection dropped",
+ detail: "The browser stream disconnected and could not reconnect.",
+ hint: `Refresh the page to pick the ${subject} back up.`,
+ };
+}
+
+function reconnectHint(reconnectAttempts: number): string {
+ const seconds =
+ Math.round(streamReconnectDelayMs(reconnectAttempts - 1) / 100) / 10;
+ return `Reconnecting in ${seconds}s (${reconnectAttempts}/${STREAM_MAX_RECONNECT_ATTEMPTS}).`;
+}
+
+export {
+ STREAM_ABNORMAL_CLOSE_CODE,
+ STREAM_MAX_RECONNECT_ATTEMPTS,
+ STREAM_MAX_RECONNECT_DELAY_MS,
+ STREAM_RECONNECT_DELAY_MS,
+ STREAM_STALE_FRAME_AFTER_ATTEMPTS,
+ STREAM_VNC_FALLBACK_CLOSE_CODE,
+ STREAM_VNC_FALLBACK_CLOSE_REASON,
+ diagnosticForReconnectExhausted,
+ diagnosticForStreamEnded,
+ isStreamStatusOnlyMessage,
+ isTerminalStreamStatus,
+ reconnectHint,
+ shouldReconnectStream,
+ streamReconnectDelayMs,
+};
diff --git a/skyvern-frontend/src/routes/workflows/WorkflowPage.test.tsx b/skyvern-frontend/src/routes/workflows/WorkflowPage.test.tsx
index 2e53e097e..7b4f6eef7 100644
--- a/skyvern-frontend/src/routes/workflows/WorkflowPage.test.tsx
+++ b/skyvern-frontend/src/routes/workflows/WorkflowPage.test.tsx
@@ -1,7 +1,22 @@
// @vitest-environment jsdom
-import { cleanup, render, screen, within } from "@testing-library/react";
+import {
+ act,
+ cleanup,
+ fireEvent,
+ render,
+ screen,
+ waitFor,
+ within,
+} from "@testing-library/react";
import { afterEach, describe, expect, it, vi } from "vitest";
-import { MemoryRouter, Route, Routes, useLocation } from "react-router-dom";
+import {
+ MemoryRouter,
+ Route,
+ Routes,
+ RouterProvider,
+ createMemoryRouter,
+ useLocation,
+} from "react-router-dom";
import { Status, type WorkflowRunApiResponse } from "@/api/types";
import CloudContext from "@/store/CloudContext";
@@ -35,11 +50,38 @@ vi.mock("@/util/env", () => ({
}));
vi.mock("@/components/StatusFilterDropdown", () => ({
- StatusFilterDropdown: () => <div data-testid="status-filter" />,
+ StatusFilterDropdown: ({
+ values,
+ onChange,
+ }: {
+ values: Array<Status>;
+ onChange: (values: Array<Status>) => void;
+ }) => (
+ <div data-testid="status-filter" data-values={values.join(",")}>
+ <button type="button" onClick={() => onChange([Status.Failed])}>
+ Filter failed
+ </button>
+ <button type="button" onClick={() => onChange([])}>
+ Clear status filter
+ </button>
+ </div>
+ ),
}));
vi.mock("@/components/TableSearchInput", () => ({
- TableSearchInput: () => <input aria-label="Search runs by input" />,
+ TableSearchInput: ({
+ value,
+ onChange,
+ }: {
+ value: string;
+ onChange: (value: string) => void;
+ }) => (
+ <input
+ aria-label="Search runs by input"
+ value={value}
+ onChange={(event) => onChange(event.target.value)}
+ />
+ ),
}));
vi.mock("./WorkflowActions", () => ({
@@ -65,7 +107,7 @@ vi.mock("./hooks/useWorkflowQuery", () => ({
}));
vi.mock("./hooks/useWorkflowRunsQuery", () => ({
- useWorkflowRunsQuery: () => mockWorkflowRunsQuery(),
+ useWorkflowRunsQuery: (props: unknown) => mockWorkflowRunsQuery(props),
}));
vi.mock("./hooks/useWorkflowTagsBatchQuery", () => ({
@@ -290,3 +332,111 @@ describe("WorkflowPage analytics button", () => {
).toBeNull();
});
});
+
+describe("Past Runs list state in the URL", () => {
+ function locationSearch(container: HTMLElement): string {
+ return (
+ container
+ .querySelector('[data-testid="location-search"]')
+ ?.getAttribute("data-search") ?? ""
+ );
+ }
+
+ it("restores the search term and status filter from the URL", () => {
+ const { container } = renderWorkflowPage({
+ initialEntries: ["/workflows/wpid_abc123?search=invoice&status=failed"],
+ workflowRuns: [makeWorkflowRun({ workflow_run_id: "wr_match" })],
+ });
+
+ expect(
+ (screen.getByLabelText("Search runs by input") as HTMLInputElement).value,
+ ).toBe("invoice");
+ expect(
+ container
+ .querySelector('[data-testid="status-filter"]')
+ ?.getAttribute("data-values"),
+ ).toBe("failed");
+ expect(mockWorkflowRunsQuery).toHaveBeenCalledWith(
+ expect.objectContaining({
+ search: "invoice",
+ statusFilters: [Status.Failed],
+ }),
+ );
+ });
+
+ it("writes the search term to the URL and drops it once cleared", () => {
+ const { container } = renderWorkflowPage({
+ initialEntries: ["/workflows/wpid_abc123?page=2"],
+ // A non-empty page keeps the empty-page rollback effect from rewriting
+ // ?page= on its own, so the reset below is the search handler's doing.
+ workflowRuns: [makeWorkflowRun({ workflow_run_id: "wr_1" })],
+ });
+ const input = screen.getByLabelText("Search runs by input");
+
+ fireEvent.change(input, { target: { value: "invoice" } });
+
+ expect(locationSearch(container)).toContain("search=invoice");
+ expect(locationSearch(container)).toContain("page=1");
+ expect(
+ (screen.getByLabelText("Search runs by input") as HTMLInputElement).value,
+ ).toBe("invoice");
+
+ fireEvent.change(input, { target: { value: "" } });
+
+ expect(locationSearch(container)).not.toContain("search=");
+ });
+
+ it("restores the query after opening a run and going back", async () => {
+ mockFeatureFlagEnabled.mockReturnValue(true);
+ mockWorkflowRunsQuery.mockReturnValue({
+ data: [makeWorkflowRun({ workflow_run_id: "wr_1" })],
+ isLoading: false,
+ });
+ const router = createMemoryRouter(
+ [
+ { path: "/workflows/:workflowPermanentId", element: <WorkflowPage /> },
+ { path: "*", element: <div>run detail</div> },
+ ],
+ { initialEntries: ["/workflows/wpid_abc123"] },
+ );
+
+ render(
+ <CloudContext.Provider value={true}>
+ <PageSlotsProvider value={{}}>
+ <RouterProvider router={router} />
+ </PageSlotsProvider>
+ </CloudContext.Provider>,
+ );
+
+ fireEvent.change(screen.getByLabelText("Search runs by input"), {
+ target: { value: "invoice" },
+ });
+ fireEvent.click(screen.getByText("wr_1"));
+ await waitFor(() => expect(screen.getByText("run detail")).toBeTruthy());
+
+ await act(async () => {
+ await router.navigate(-1);
+ });
+
+ expect(
+ (screen.getByLabelText("Search runs by input") as HTMLInputElement).value,
+ ).toBe("invoice");
+ expect(mockWorkflowRunsQuery).toHaveBeenLastCalledWith(
+ expect.objectContaining({ search: "invoice" }),
+ );
+ });
+
+ it("writes the status filter to the URL and drops it once cleared", () => {
+ const { container } = renderWorkflowPage();
+
+ fireEvent.click(screen.getByRole("button", { name: "Filter failed" }));
+
+ expect(locationSearch(container)).toContain("status=failed");
+
+ fireEvent.click(
+ screen.getByRole("button", { name: "Clear status filter" }),
+ );
+
+ expect(locationSearch(container)).not.toContain("status=");
+ });
+});
diff --git a/skyvern-frontend/src/routes/workflows/WorkflowPage.tsx b/skyvern-frontend/src/routes/workflows/WorkflowPage.tsx
index aa101a1ee..2243f609f 100644
--- a/skyvern-frontend/src/routes/workflows/WorkflowPage.tsx
+++ b/skyvern-frontend/src/routes/workflows/WorkflowPage.tsx
@@ -8,7 +8,7 @@ import {
} from "@radix-ui/react-icons";
import { Tip } from "@/components/Tip";
-import { Status, WorkflowRunStatusApiResponse } from "@/api/types";
+import { WorkflowRunStatusApiResponse } from "@/api/types";
import { StatusBadge } from "@/components/StatusBadge";
import { CredentialFallbackRetryBadge } from "@/components/CredentialFallbackRetryBadge";
import { StatusFilterDropdown } from "@/components/StatusFilterDropdown";
@@ -99,6 +99,7 @@ import {
import { useRowSelection } from "@/hooks/useRowSelection";
import { RunBulkActionBar } from "@/routes/runs/RunBulkActionBar";
import { RunRowActions } from "@/routes/runs/RunRowActions";
+import { parseStatusParam } from "@/routes/runs/statusFilterParam";
import { WorkflowReliabilityPanel } from "./workflowRun/WorkflowReliabilityPanel";
import { RunOutcomeRiskMarker } from "./workflowRun/RunOutcomeRiskMarker";
import { useRunsHealSummaryBatchQuery } from "./hooks/useRunsHealSummaryBatchQuery";
@@ -120,13 +121,22 @@ function WorkflowPage() {
[searchParams],
);
const page = searchParams.get("page") ? Number(searchParams.get("page")) : 1;
- const [statusFilters, setStatusFilters] = useState<Array<Status>>([]);
+ const statusFilters = useMemo(
+ () => parseStatusParam(searchParams.get("status")),
+ [searchParams],
+ );
const navigate = useNavigate();
const studioEnabled = useWorkflowStudioEnabled();
const PAGE_SIZE_OPTIONS = ["10", "25", "50"];
const pageSize = Number(searchParams.get("page_size") || "10");
- const [search, setSearch] = useState("");
+ // The URL owns the query so a navigate-in-then-back round trip restores it;
+ // the mirrored state keeps typing instant instead of awaiting the navigation.
+ const searchParam = searchParams.get("search") ?? "";
+ const [search, setSearch] = useState(searchParam);
+ useEffect(() => {
+ setSearch(searchParam);
+ }, [searchParam]);
const [debouncedSearch] = useDebounce(search, 500);
const [openRunParams, setOpenRunParams] = useState<string | null>(null);
const { matchesParameter } = useKeywordSearch(debouncedSearch);
@@ -359,6 +369,11 @@ function WorkflowPage() {
onChange={(value) => {
setSearch(value);
const params = new URLSearchParams(searchParams);
+ if (value === "") {
+ params.delete("search");
+ } else {
+ params.set("search", value);
+ }
params.set("page", "1");
setSearchParams(params, { replace: true });
}}
@@ -382,7 +397,16 @@ function WorkflowPage() {
) : null}
<StatusFilterDropdown
values={statusFilters}
- onChange={setStatusFilters}
+ onChange={(filters) => {
+ const params = new URLSearchParams(searchParams);
+ if (filters.length === 0) {
+ params.delete("status");
+ } else {
+ params.set("status", filters.join(","));
+ }
+ params.set("page", "1");
+ setSearchParams(params, { replace: true });
+ }}
/>
</div>
</div>
diff --git a/skyvern-frontend/src/routes/workflows/copilot/narrativeState.hydrationParity.fixture.json b/skyvern-frontend/src/routes/workflows/copilot/narrativeState.hydrationParity.fixture.json
new file mode 100644
index 000000000..12841aaec
--- /dev/null
+++ b/skyvern-frontend/src/routes/workflows/copilot/narrativeState.hydrationParity.fixture.json
@@ -0,0 +1,186 @@
+{
+ "payload": {
+ "turnId": "turn-replay",
+ "turnIndex": 0,
+ "designStarted": true,
+ "designEnded": true,
+ "draft": {
+ "blockCount": 1,
+ "blockLabels": [
+ "log_in"
+ ],
+ "summary": null
+ },
+ "blocks": [
+ {
+ "label": "log_in",
+ "blockType": "task",
+ "state": "completed",
+ "lastSeenIteration": 1,
+ "activity": [],
+ "startedAt": null,
+ "endedAt": "2026-08-20T23:13:50.173506+00:00",
+ "workflowRunBlockId": "wrb_replay"
+ }
+ ],
+ "terminal": "response",
+ "terminalMessage": "done",
+ "narrativeSummary": "done",
+ "priorBlockCount": null,
+ "designActivity": [
+ {
+ "kind": "tool_call",
+ "text": "Updating workflow\u2026",
+ "iteration": 0,
+ "toolName": "update_workflow",
+ "displayLabel": "Updating workflow",
+ "id": "tc-c1",
+ "timestamp": "2026-08-20T23:13:50.173271+00:00"
+ },
+ {
+ "kind": "tool_result",
+ "text": "Workflow updated (2 blocks)",
+ "iteration": 0,
+ "toolName": "update_workflow",
+ "displayLabel": "Updating workflow",
+ "success": true,
+ "id": "tr-c1",
+ "timestamp": "2026-08-20T23:13:50.173320+00:00"
+ },
+ {
+ "kind": "tool_call",
+ "text": "Editing block \"Log In\"\u2026",
+ "iteration": 1,
+ "toolName": "edit_block",
+ "displayLabel": "Editing block \"Log In\"",
+ "id": "tc-c2",
+ "timestamp": "2026-08-20T23:13:50.173387+00:00"
+ },
+ {
+ "kind": "narration",
+ "text": "Refining the workflow's code",
+ "iteration": 1,
+ "id": "n-1-2026-08-20T23:13:50.173435+00:00",
+ "timestamp": "2026-08-20T23:13:50.173435+00:00"
+ },
+ {
+ "kind": "tool_call",
+ "text": "Testing workflow\u2026",
+ "iteration": 2,
+ "toolName": "update_and_run_blocks",
+ "displayLabel": "Testing workflow",
+ "id": "tc-c3",
+ "timestamp": "2026-08-20T23:13:50.173449+00:00"
+ },
+ {
+ "kind": "tool_result",
+ "text": "Updated the workflow and ran it",
+ "iteration": 2,
+ "toolName": "update_and_run_blocks",
+ "displayLabel": "Testing workflow",
+ "success": true,
+ "id": "tr-c3",
+ "timestamp": "2026-08-20T23:13:50.173462+00:00"
+ },
+ {
+ "kind": "tool_result",
+ "text": "Updated the workflow and ran it",
+ "iteration": 1,
+ "toolName": "update_and_run_blocks",
+ "displayLabel": "Testing workflow",
+ "success": true,
+ "id": "tr-c4",
+ "timestamp": "2026-08-20T23:13:50.173482+00:00"
+ }
+ ],
+ "startedAt": null,
+ "endedAt": "2026-08-20T23:13:50.173521+00:00"
+ },
+ "updates": [
+ {
+ "type": "design_start",
+ "timestamp": "2026-08-20T23:13:50.173245Z"
+ },
+ {
+ "type": "tool_call",
+ "tool_name": "update_workflow",
+ "display_label": "Updating workflow",
+ "tool_input": {},
+ "iteration": 0,
+ "tool_call_id": "c1",
+ "timestamp": "2026-08-20T23:13:50.173271Z"
+ },
+ {
+ "type": "tool_result",
+ "tool_name": "update_workflow",
+ "display_label": "Updating workflow",
+ "success": true,
+ "summary": "Workflow updated (2 blocks)",
+ "iteration": 0,
+ "tool_call_id": "c1",
+ "detail": null,
+ "workflow_run_id": null,
+ "timestamp": "2026-08-20T23:13:50.173320Z"
+ },
+ {
+ "type": "tool_call",
+ "tool_name": "edit_block",
+ "display_label": "Editing block \"Log In\"",
+ "tool_input": {
+ "label": "log_in"
+ },
+ "iteration": 1,
+ "tool_call_id": "c2",
+ "timestamp": "2026-08-20T23:13:50.173387Z"
+ },
+ {
+ "type": "narration",
+ "narration": "Refining the workflow's code",
+ "iteration": 1,
+ "timestamp": "2026-08-20T23:13:50.173435Z"
+ },
+ {
+ "type": "tool_call",
+ "tool_name": "update_and_run_blocks",
+ "display_label": "Testing workflow",
+ "tool_input": {},
+ "iteration": 2,
+ "tool_call_id": "c3",
+ "timestamp": "2026-08-20T23:13:50.173449Z"
+ },
+ {
+ "type": "tool_result",
+ "tool_name": "update_and_run_blocks",
+ "display_label": "Testing workflow",
+ "success": true,
+ "summary": "Updated the workflow and ran it",
+ "iteration": 2,
+ "tool_call_id": "c3",
+ "detail": null,
+ "workflow_run_id": null,
+ "timestamp": "2026-08-20T23:13:50.173462Z"
+ },
+ {
+ "type": "tool_result",
+ "tool_name": "update_and_run_blocks",
+ "display_label": "Testing workflow",
+ "success": true,
+ "summary": "Updated the workflow and ran it",
+ "iteration": 1,
+ "tool_call_id": "c4",
+ "detail": null,
+ "workflow_run_id": null,
+ "timestamp": "2026-08-20T23:13:50.173482Z"
+ },
+ {
+ "type": "block_progress",
+ "workflow_run_block_id": "wrb_replay",
+ "workflow_run_id": "wr_replay",
+ "block_label": "log_in",
+ "block_type": "task",
+ "status": "completed",
+ "iteration": 1,
+ "timestamp": "2026-08-20T23:13:50.173506Z"
+ }
+ ]
+}
diff --git a/skyvern-frontend/src/routes/workflows/copilot/narrativeState.hydrationParity.test.ts b/skyvern-frontend/src/routes/workflows/copilot/narrativeState.hydrationParity.test.ts
new file mode 100644
index 000000000..2eb27dab8
--- /dev/null
+++ b/skyvern-frontend/src/routes/workflows/copilot/narrativeState.hydrationParity.test.ts
@@ -0,0 +1,109 @@
+import { describe, expect, it } from "vitest";
+
+import capture from "./narrativeState.hydrationParity.fixture.json";
+import {
+ ActivityEntry,
+ EMPTY_NARRATIVE,
+ NarrativeEvent,
+ TurnNarrativeState,
+ applyNarrativeEvent,
+ formatElapsed,
+ hydrateNarrativeFromPayload,
+} from "./narrativeState";
+
+// Produced by dev_scripts/replay_narrative_timestamp_parity.py driving the real
+// streaming_adapter emit path, so neither leg here is a hand-written shape.
+const liveUpdates = capture.updates as unknown as NarrativeEvent[];
+const persistedPayload = capture.payload as unknown as Record<string, unknown>;
+
+function groupedDuration(entries: ActivityEntry[]): string | null {
+ const stamps = entries
+ .map((entry) => entry.timestamp)
+ .filter((stamp): stamp is string => typeof stamp === "string");
+ if (stamps.length === 0) return null;
+ return formatElapsed(stamps[0]!, stamps[stamps.length - 1]!);
+}
+
+// A narration entry's id embeds its own ISO timestamp, and the live and persisted
+// sides serialize UTC differently ("Z" versus "+00:00"), so pair those by iteration.
+function pairKey(entry: ActivityEntry): string {
+ return entry.kind === "narration" ? `n-${entry.iteration}` : entry.id;
+}
+
+function replayLive(): TurnNarrativeState {
+ return liveUpdates.reduce<TurnNarrativeState>(
+ (state, event) => applyNarrativeEvent(state, event),
+ { ...EMPTY_NARRATIVE },
+ );
+}
+
+describe("activity timestamp parity across hydration", () => {
+ it("stamps every persisted entry with the clock read its live update carried", () => {
+ const live = replayLive();
+ const hydrated = hydrateNarrativeFromPayload(persistedPayload);
+ expect(hydrated).not.toBeNull();
+
+ const liveById = new Map(live.designActivity.map((e) => [pairKey(e), e]));
+ expect(hydrated!.designActivity.length).toBeGreaterThan(0);
+ for (const entry of hydrated!.designActivity) {
+ expect(entry.timestamp).toBeTypeOf("string");
+ const twin = liveById.get(pairKey(entry));
+ expect(twin, `no live entry for ${entry.id}`).toBeDefined();
+ expect(Date.parse(entry.timestamp!)).toBe(Date.parse(twin!.timestamp!));
+ }
+ });
+
+ it("renders the same grouped duration live and after a hydrated reload", () => {
+ const liveDuration = groupedDuration(replayLive().designActivity);
+ const hydratedDuration = groupedDuration(
+ hydrateNarrativeFromPayload(persistedPayload)!.designActivity,
+ );
+ expect(liveDuration).not.toBeNull();
+ expect(hydratedDuration).toBe(liveDuration);
+ });
+
+ it("hydrates a payload whose entries and blocks lack the new keys", () => {
+ const olderBackendPayload = {
+ turnId: "turn-old",
+ turnIndex: 0,
+ designStarted: true,
+ designEnded: true,
+ draft: null,
+ blocks: [
+ {
+ label: "log_in",
+ blockType: "task",
+ state: "completed",
+ lastSeenIteration: 0,
+ activity: [],
+ startedAt: null,
+ endedAt: null,
+ },
+ ],
+ terminal: "response",
+ terminalMessage: "done",
+ narrativeSummary: null,
+ priorBlockCount: null,
+ designActivity: [
+ {
+ kind: "tool_call",
+ text: "Updating workflow…",
+ iteration: 0,
+ toolName: "update_workflow",
+ displayLabel: "Updating workflow",
+ id: "tc-c1",
+ },
+ ],
+ startedAt: null,
+ endedAt: null,
+ };
+
+ const hydrated = hydrateNarrativeFromPayload(olderBackendPayload);
+
+ expect(hydrated).not.toBeNull();
+ expect(hydrated!.designActivity).toHaveLength(1);
+ expect(hydrated!.designActivity[0]!.timestamp).toBeUndefined();
+ expect(hydrated!.blocks[0]!.workflowRunBlockId).toBe("");
+ expect(groupedDuration(hydrated!.designActivity)).toBeNull();
+ });
+});
diff --git a/skyvern-frontend/src/routes/workflows/copilot/narrativeState.ts b/skyvern-frontend/src/routes/workflows/copilot/narrativeState.ts
index d0384c419..3311ea2f0 100644
--- a/skyvern-frontend/src/routes/workflows/copilot/narrativeState.ts
+++ b/skyvern-frontend/src/routes/workflows/copilot/narrativeState.ts
@@ -234,6 +234,9 @@ export interface ActivityEntry {
// Consecutive same-tool retries folded into this row by
// condenseActivityEntries. Unset outside that transform.
attempts?: number;
+ // 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;
}
// Closed vocabulary of the backend TurnOutcome.response_kind enum. Unknown
@@ -549,6 +552,7 @@ function buildActivityFromToolCall(
toolName: event.tool_name,
displayLabel,
id: `tc-${event.tool_call_id}`,
+ timestamp: event.timestamp ?? undefined,
};
}
@@ -577,6 +581,7 @@ function buildActivityFromToolResult(
displayLabel,
success: event.success,
id: `tr-${event.tool_call_id}`,
+ timestamp: event.timestamp ?? undefined,
};
}
@@ -588,6 +593,7 @@ function buildActivityFromNarration(
text: event.narration,
iteration: event.iteration,
id: `n-${event.iteration}-${event.timestamp}`,
+ timestamp: event.timestamp,
};
}
@@ -816,10 +822,10 @@ export function isBlockOk(
);
}
-// Labels that occur exactly once in the given set — the only labels safe to
-// key recorded actions on when the run-block id is missing (the terminal
-// narrative_payload drops workflowRunBlockId). Loop iterations reuse a label,
-// so an ambiguous label falls back to today's drop rather than mis-attributing.
+// Labels that occur exactly once in the given set — the only labels safe to key
+// recorded actions on when the run-block id is missing (a block that never
+// reported progress, or an older backend). Loop iterations reuse a label, so an
+// ambiguous label falls back to today's drop rather than mis-attributing.
function uniqueLabelSet(labels: Array<string | undefined>): Set<string> {
const counts = new Map<string, number>();
for (const label of labels) {
@@ -1088,13 +1094,10 @@ export function applyNarrativeEvent(
case "response": {
const hydrated = hydrateNarrativeFromPayload(event.narrative_payload);
if (hydrated) {
- // The BE narrative_payload drops workflowRunBlockId and the client-only
- // recordedActions. Re-associate each hydrated block with the live block
- // of the same label to restore its real run-block id (and carry any
- // recordedActions). Restoring the real id keeps this frozen turn keyed
- // by id, so a later test run that reuses a label matches by id and can't
- // graft its actions onto this turn. Unique labels only — loop iterations
- // reuse a label and can't be told apart without the id.
+ // The BE narrative_payload carries no client-only recordedActions, and
+ // omits workflowRunBlockId for a block that never reported progress.
+ // Re-associating by label carries both across, but only for a label that
+ // occurs once — loop iterations reuse one and can't be told apart.
const liveById = new Map(
prev.blocks
.filter((b) => b.workflowRunBlockId !== "")
@@ -1234,6 +1237,7 @@ function normalizeActivityEntries(raw: unknown): ActivityEntry[] {
typeof o.displayLabel === "string" ? o.displayLabel : undefined,
success: typeof o.success === "boolean" ? o.success : undefined,
id: o.id,
+ timestamp: typeof o.timestamp === "string" ? o.timestamp : undefined,
});
}
return out;
diff --git a/skyvern-frontend/src/routes/workflows/copilot/workflowCopilotTypes.ts b/skyvern-frontend/src/routes/workflows/copilot/workflowCopilotTypes.ts
index ec46a67f3..6d6bdcde2 100644
--- a/skyvern-frontend/src/routes/workflows/copilot/workflowCopilotTypes.ts
+++ b/skyvern-frontend/src/routes/workflows/copilot/workflowCopilotTypes.ts
@@ -223,6 +223,7 @@ export interface WorkflowCopilotToolCallUpdate {
tool_input: Record<string, unknown>;
iteration: number;
tool_call_id: string;
+ timestamp?: string | null;
}
export interface WorkflowCopilotToolResultUpdate {
@@ -234,6 +235,7 @@ export interface WorkflowCopilotToolResultUpdate {
iteration: number;
tool_call_id: string;
detail?: string | null;
+ timestamp?: string | null;
}
export interface WorkflowCopilotCondensingUpdate {
diff --git a/skyvern-frontend/src/routes/workflows/workflowRun/WorkflowRunStream.test.tsx b/skyvern-frontend/src/routes/workflows/workflowRun/WorkflowRunStream.test.tsx
new file mode 100644
index 000000000..f8d3fd5ff
--- /dev/null
+++ b/skyvern-frontend/src/routes/workflows/workflowRun/WorkflowRunStream.test.tsx
@@ -0,0 +1,151 @@
+import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
+import { act, render, screen } from "@testing-library/react";
+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
+
+import { WorkflowRunStream } from "./WorkflowRunStream";
+
+vi.mock("@/util/env", () => ({
+ getCredentialParam: vi.fn(async () => "apikey=test"),
+}));
+
+vi.mock("@/hooks/useCredentialGetter", () => {
+ // Stable identity: the stream effect keys on it, and a fresh function per
+ // render would tear the socket down and clear the frame on every state change.
+ const credentialGetter = async () => null;
+ return { useCredentialGetter: () => credentialGetter };
+});
+
+vi.mock("@/hooks/useFirstParam", () => ({
+ useFirstParam: () => "wr_test",
+}));
+
+vi.mock("../hooks/useWorkflowRunWithWorkflowQuery", () => ({
+ useWorkflowRunWithWorkflowQuery: () => ({
+ data: {
+ status: "running",
+ workflow_run_id: "wr_test",
+ workflow: { workflow_permanent_id: "wpid_test" },
+ },
+ }),
+}));
+
+vi.mock("@/components/ui/use-toast", () => ({
+ toast: vi.fn(),
+}));
+
+vi.mock("@/routes/streaming/InteractiveStreamView", () => ({
+ InteractiveStreamView: ({ streamImgSrc }: { streamImgSrc: string }) => (
+ <div data-frame={streamImgSrc} data-testid="stream-frame" />
+ ),
+}));
+
+class FakeStreamSocket {
+ static instances: FakeStreamSocket[] = [];
+
+ close = vi.fn();
+
+ private listeners: Record<string, Array<(event: unknown) => void>> = {};
+
+ constructor() {
+ FakeStreamSocket.instances.push(this);
+ }
+
+ addEventListener(type: string, listener: (event: unknown) => void) {
+ this.listeners[type] = [...(this.listeners[type] ?? []), listener];
+ }
+
+ removeEventListener() {}
+
+ emit(type: string, event: unknown) {
+ for (const listener of this.listeners[type] ?? []) {
+ listener(event);
+ }
+ }
+
+ emitStreamMessage(message: Record<string, unknown>) {
+ this.emit("message", { data: JSON.stringify(message) });
+ }
+}
+
+function renderStream() {
+ const queryClient = new QueryClient({
+ defaultOptions: { queries: { retry: false } },
+ });
+ return render(
+ <QueryClientProvider client={queryClient}>
+ <WorkflowRunStream workflowRunId="wr_test" alwaysShowStream />
+ </QueryClientProvider>,
+ );
+}
+
+async function streamOneFrame() {
+ renderStream();
+ await act(async () => Promise.resolve());
+ const socket = FakeStreamSocket.instances[0]!;
+ act(() => {
+ socket.emitStreamMessage({ status: "running", screenshot: "live-frame" });
+ });
+ expect(screen.getByTestId("stream-frame")).toBeTruthy();
+ return socket;
+}
+
+describe("WorkflowRunStream lifecycle", () => {
+ beforeEach(() => {
+ FakeStreamSocket.instances.length = 0;
+ vi.clearAllMocks();
+ vi.useFakeTimers();
+ vi.stubGlobal("WebSocket", FakeStreamSocket);
+ });
+
+ afterEach(() => {
+ vi.useRealTimers();
+ vi.unstubAllGlobals();
+ });
+
+ it("retires the stale frame and reconnects when the stream ends non-terminally (SKY-14617)", async () => {
+ const socket = await streamOneFrame();
+
+ // What the backend sends once its screencast loop returns for a run that is
+ // still going: a bare, non-terminal status, then a clean close.
+ act(() => {
+ socket.emitStreamMessage({ status: "running" });
+ });
+ expect(screen.queryByTestId("stream-frame")).toBeNull();
+ expect(
+ screen.getByText("This live view has stopped updating"),
+ ).toBeTruthy();
+
+ act(() => {
+ socket.emit("close", { code: 1000, reason: "" });
+ });
+ await act(async () => vi.advanceTimersByTimeAsync(1000));
+ expect(FakeStreamSocket.instances).toHaveLength(2);
+ });
+
+ it("reports and retries a close that arrives after frames (SKY-14617)", async () => {
+ const socket = await streamOneFrame();
+
+ act(() => {
+ socket.emit("close", { code: 1006, reason: "" });
+ });
+ await act(async () => vi.advanceTimersByTimeAsync(1000));
+
+ expect(FakeStreamSocket.instances).toHaveLength(2);
+ });
+
+ it("treats timeout as terminal, matching BrowserSessionStream", async () => {
+ const socket = await streamOneFrame();
+
+ act(() => {
+ socket.emitStreamMessage({ status: "timeout" });
+ });
+ expect(screen.queryByTestId("stream-frame")).toBeNull();
+ expect(screen.getByText("The browser's gone strangely quiet")).toBeTruthy();
+
+ act(() => {
+ socket.emit("close", { code: 1000, reason: "" });
+ });
+ await act(async () => vi.advanceTimersByTimeAsync(1000));
+ expect(FakeStreamSocket.instances).toHaveLength(1);
+ });
+});
diff --git a/skyvern-frontend/src/routes/workflows/workflowRun/WorkflowRunStream.tsx b/skyvern-frontend/src/routes/workflows/workflowRun/WorkflowRunStream.tsx
index 6f30a0c75..f0284c803 100644
--- a/skyvern-frontend/src/routes/workflows/workflowRun/WorkflowRunStream.tsx
+++ b/skyvern-frontend/src/routes/workflows/workflowRun/WorkflowRunStream.tsx
@@ -13,6 +13,22 @@ import {
StreamStatusPanel,
type StreamDiagnostic,
} from "@/routes/streaming/StreamDiagnostics";
+import {
+ STREAM_ABNORMAL_CLOSE_CODE,
+ STREAM_STALE_FRAME_AFTER_ATTEMPTS,
+ diagnosticForReconnectExhausted,
+ diagnosticForStreamEnded,
+ isStreamStatusOnlyMessage,
+ isTerminalStreamStatus,
+ reconnectHint,
+ shouldReconnectStream,
+ streamReconnectDelayMs,
+} from "@/routes/streaming/streamLifecycle";
+import {
+ WORKFLOW_RUN_STREAM_SUBJECT,
+ diagnosticForStatus,
+ isWorkflowRunFinalStatus,
+} from "./WorkflowRunStream.utils";
type StreamMessage = {
task_id?: string;
@@ -31,40 +47,11 @@ const STARTING_DIAGNOSTIC: StreamDiagnostic = {
pending: true,
};
-function diagnosticForStatus(status: string): StreamDiagnostic {
- switch (status) {
- case "not_found":
- return {
- title: "We've misplaced this agent run",
- detail: "The backend can't find it for your org.",
- };
- case "timeout":
- return {
- title: "The browser's gone strangely quiet",
- detail: "The run started, but no active page showed up to stream.",
- hint: "Check backend logs for browser launch errors or a streaming-mode mismatch.",
- };
- case "completed":
- case "failed":
- case "terminated":
- return {
- title: "This agent run has wrapped up",
- detail: `It's no longer live — status: ${status}.`,
- };
- default:
- return {
- title: "Waiting for browser frames",
- detail: `The stream is connected and the run status is ${status}.`,
- pending: true,
- };
- }
-}
-
function diagnosticForClose(event: CloseEvent): StreamDiagnostic {
- if (event.code === 1006) {
+ if (event.code === STREAM_ABNORMAL_CLOSE_CODE) {
return {
title: "The connection slipped away",
- detail: "The browser stream WebSocket closed before sending a frame.",
+ detail: "The browser stream WebSocket dropped without closing cleanly.",
hint: "Check that the API server is running and reachable from the UI.",
};
}
@@ -119,6 +106,13 @@ function WorkflowRunStream({
const socketRef = useRef<WebSocket | null>(null);
const hasFrameRef = useRef(false);
+ const reconnectAttemptsRef = useRef(0);
+ const streamFinishedRef = useRef(false);
+ const reconnectTimerRef = useRef<ReturnType<typeof setTimeout> | null>(null);
+ // Why the stream stopped, when the server told us before closing. Survives into
+ // the close handler so a reconnect notice augments that reason instead of
+ // replacing it with a generic "closed with code 1000".
+ const streamEndedDiagnosticRef = useRef<StreamDiagnostic | null>(null);
const inputWsUrl =
interactive && workflowRunId
@@ -144,22 +138,36 @@ function WorkflowRunStream({
}
setDiagnostic(STARTING_DIAGNOSTIC);
hasFrameRef.current = false;
+ reconnectAttemptsRef.current = 0;
+ streamFinishedRef.current = false;
+ streamEndedDiagnosticRef.current = null;
let cancelled = false;
+ const clearReconnectTimer = () => {
+ if (reconnectTimerRef.current) {
+ clearTimeout(reconnectTimerRef.current);
+ reconnectTimerRef.current = null;
+ }
+ };
+
async function run() {
const credentialParam = await getCredentialParam(credentialGetter);
if (cancelled) {
return;
}
- if (socketRef.current) {
- socketRef.current.close();
- }
- socketRef.current = new WebSocket(
+ socketRef.current?.close();
+ const socket = new WebSocket(
`${wssBaseUrl}/stream/workflow_runs/${workflowRunId}?${credentialParam}`,
);
+ socketRef.current = socket;
- socketRef.current.addEventListener("open", () => {
+ const isCurrentSocket = () => !cancelled && socketRef.current === socket;
+
+ socket.addEventListener("open", () => {
+ if (!isCurrentSocket()) {
+ return;
+ }
setDiagnostic({
title: "Hooked up to the stream",
detail: "Just waiting for the backend to hand us a browser.",
@@ -167,11 +175,16 @@ function WorkflowRunStream({
});
});
- socketRef.current.addEventListener("message", (event) => {
+ socket.addEventListener("message", (event) => {
+ if (!isCurrentSocket()) {
+ return;
+ }
try {
const message: StreamMessage = JSON.parse(event.data);
if (message.screenshot) {
hasFrameRef.current = true;
+ reconnectAttemptsRef.current = 0;
+ streamEndedDiagnosticRef.current = null;
setStreamImgSrc(message.screenshot);
}
if (message.format) {
@@ -186,15 +199,42 @@ function WorkflowRunStream({
if (message.url) {
onUrlChangeRef.current?.(message.url);
}
- if (!message.screenshot && message.status) {
- setDiagnostic(diagnosticForStatus(message.status));
+ const isTerminal = isTerminalStreamStatus(message.status);
+ // A bare status frame is the server signing off. After frames have flowed
+ // that ends the live view even when the status itself is non-terminal --
+ // the run outlives the screencast, and rendering its last frame as
+ // current is what left viewers staring at a dead browser (SKY-14617).
+ const streamEnded =
+ isTerminal ||
+ (hasFrameRef.current && isStreamStatusOnlyMessage(message));
+ if (message.status && (isTerminal || !message.screenshot)) {
+ const endedDiagnostic =
+ streamEnded && !isTerminal
+ ? diagnosticForStreamEnded({
+ status: message.status,
+ subject: WORKFLOW_RUN_STREAM_SUBJECT,
+ })
+ : diagnosticForStatus(message.status);
+ streamEndedDiagnosticRef.current = streamEnded
+ ? endedDiagnostic
+ : null;
+ setDiagnostic(endedDiagnostic);
}
- if (
- message.status === "completed" ||
- message.status === "failed" ||
- message.status === "terminated"
- ) {
- socketRef.current?.close();
+ if (streamEnded) {
+ // Drop the last frame: keeping it leaves a dead, still-interactive
+ // screenshot covering the status panel.
+ hasFrameRef.current = false;
+ setStreamImgSrc("");
+ // Only a terminal status forecloses reconnecting; a live run whose
+ // screencast ended is exactly the case worth redialling.
+ if (isTerminal) {
+ streamFinishedRef.current = true;
+ }
+ socket.close();
+ }
+ // A stream-level status such as `timeout` says nothing about the run, so
+ // only a genuinely final one refreshes the run's own queries.
+ if (isWorkflowRunFinalStatus(message.status)) {
queryClient.invalidateQueries({
queryKey: ["workflowRuns"],
});
@@ -232,6 +272,9 @@ function WorkflowRunStream({
}
} catch (e) {
console.error("Failed to parse message", e);
+ // The backend only sends non-JSON text to reject credentials, and
+ // retrying that would just burn the reconnect budget in silence.
+ streamFinishedRef.current = true;
setDiagnostic({
title: "The stream said something funny",
detail: "The browser sent a message the UI couldn't parse.",
@@ -239,27 +282,79 @@ function WorkflowRunStream({
}
});
- socketRef.current.addEventListener("error", () => {
+ socket.addEventListener("error", () => {
+ if (!isCurrentSocket()) {
+ return;
+ }
setDiagnostic({
title: "The stream hit a snag",
detail: "The connection ran into a network or server error.",
});
});
- socketRef.current.addEventListener("close", (event) => {
- if (!cancelled && !hasFrameRef.current) {
- setDiagnostic(diagnosticForClose(event));
+ socket.addEventListener("close", (event) => {
+ if (socketRef.current !== socket) {
+ return;
}
socketRef.current = null;
+
+ // Prefer the reason the server gave over "the socket closed": after a clean
+ // close those are the same event, and only the former says anything useful.
+ const closeDiagnostic =
+ streamEndedDiagnosticRef.current ?? diagnosticForClose(event);
+ if (!cancelled && !hasFrameRef.current && !streamFinishedRef.current) {
+ setDiagnostic(closeDiagnostic);
+ }
+ const canReconnect =
+ !cancelled &&
+ shouldReconnectStream({
+ closeCode: event.code,
+ closeReason: event.reason,
+ streamFinished: streamFinishedRef.current,
+ reconnectAttempts: reconnectAttemptsRef.current,
+ });
+
+ if (canReconnect) {
+ const delayMs = streamReconnectDelayMs(reconnectAttemptsRef.current);
+ reconnectAttemptsRef.current += 1;
+ if (
+ hasFrameRef.current &&
+ reconnectAttemptsRef.current > STREAM_STALE_FRAME_AFTER_ATTEMPTS
+ ) {
+ hasFrameRef.current = false;
+ setStreamImgSrc("");
+ }
+ if (!hasFrameRef.current) {
+ setDiagnostic({
+ ...closeDiagnostic,
+ hint: reconnectHint(reconnectAttemptsRef.current),
+ });
+ }
+ clearReconnectTimer();
+ reconnectTimerRef.current = setTimeout(() => {
+ reconnectTimerRef.current = null;
+ void run();
+ }, delayMs);
+ } else if (!cancelled && !streamFinishedRef.current) {
+ // Out of retries with nothing live behind the last frame: say so instead
+ // of leaving that frame up as if it were current.
+ hasFrameRef.current = false;
+ setStreamImgSrc("");
+ setDiagnostic(
+ diagnosticForReconnectExhausted(WORKFLOW_RUN_STREAM_SUBJECT),
+ );
+ }
});
}
- run();
+ void run();
return () => {
cancelled = true;
- if (socketRef.current) {
- socketRef.current.close();
+ clearReconnectTimer();
+ const socket = socketRef.current;
+ if (socket) {
socketRef.current = null;
+ socket.close();
}
};
}, [
diff --git a/skyvern-frontend/src/routes/workflows/workflowRun/WorkflowRunStream.utils.ts b/skyvern-frontend/src/routes/workflows/workflowRun/WorkflowRunStream.utils.ts
new file mode 100644
index 000000000..60a85fa8a
--- /dev/null
+++ b/skyvern-frontend/src/routes/workflows/workflowRun/WorkflowRunStream.utils.ts
@@ -0,0 +1,58 @@
+import type { StreamDiagnostic } from "@/routes/streaming/StreamDiagnostics";
+import { isTerminalStreamStatus } from "@/routes/streaming/streamLifecycle";
+
+const WORKFLOW_RUN_STREAM_SUBJECT = "agent run";
+
+// The statuses that mean the run itself is over, as opposed to the stream giving up
+// on a run that is still going. Only these are worth refreshing run queries for.
+const WORKFLOW_RUN_FINAL_STATUSES = new Set([
+ "completed",
+ "failed",
+ "terminated",
+]);
+
+function isWorkflowRunFinalStatus(status: string) {
+ return WORKFLOW_RUN_FINAL_STATUSES.has(status);
+}
+
+function diagnosticForStatus(status: string): StreamDiagnostic {
+ switch (status) {
+ case "not_found":
+ return {
+ title: "We've misplaced this agent run",
+ detail: "The backend can't find it for your org.",
+ };
+ case "timeout":
+ return {
+ title: "The browser's gone strangely quiet",
+ detail: "The run started, but no active page showed up to stream.",
+ hint: "Check backend logs for browser launch errors or a streaming-mode mismatch.",
+ };
+ case "completed":
+ return {
+ title: "This agent run has wrapped up",
+ detail: `It's no longer live — status: ${status}.`,
+ tone: "success",
+ };
+ default:
+ // A terminal status with no copy of its own is still over, so it must not
+ // fall through to the "still working on it" animation.
+ if (isTerminalStreamStatus(status)) {
+ return {
+ title: "This agent run has wrapped up",
+ detail: `It's no longer live — status: ${status}.`,
+ };
+ }
+ return {
+ title: "Waiting for browser frames",
+ detail: `The stream is connected and the run status is ${status}.`,
+ pending: true,
+ };
+ }
+}
+
+export {
+ WORKFLOW_RUN_STREAM_SUBJECT,
+ diagnosticForStatus,
+ isWorkflowRunFinalStatus,
+};
diff --git a/skyvern/browser_extension/broker_client.py b/skyvern/browser_extension/broker_client.py
index f960514b4..0ec21e64f 100644
--- a/skyvern/browser_extension/broker_client.py
+++ b/skyvern/browser_extension/broker_client.py
@@ -158,7 +158,7 @@ class BrokerClient:
if self.connected:
return True
result = await self._control_request(
- "extension.wait_connected", {"timeout": min(max(timeout, 0.0), 35.0)}, timeout + 1
+ "extension.wait_connected", {"timeout": min(max(timeout, 0.0), 45.0)}, timeout + 1
)
connected = result.get("connected") is True
if connected:
@@ -654,6 +654,11 @@ def _ensure_broker_process(port: int, paths: BrokerPaths) -> subprocess.Popen[by
try:
readiness = read_readiness(read_fd, timeout=STARTUP_TIMEOUT_SECONDS)
+ if readiness["status"] == "READY" and readiness["port"] != port:
+ raise BrowserExtensionBrokerError(
+ "INVALID_READINESS",
+ "Broker readiness response is invalid",
+ )
except BrowserExtensionBrokerError as exc:
_terminate_spawned_process(process)
log_thread.join(timeout=1.0)
diff --git a/skyvern/browser_extension/broker_server.py b/skyvern/browser_extension/broker_server.py
index 8ee7b7810..4f9997592 100644
--- a/skyvern/browser_extension/broker_server.py
+++ b/skyvern/browser_extension/broker_server.py
@@ -802,8 +802,8 @@ class BrowserExtensionBrokerServer:
"quarantines": [],
}
if op == "extension.wait_connected":
- timeout = args.get("timeout", 35.0)
- if isinstance(timeout, bool) or not isinstance(timeout, (int, float)) or not 0 <= timeout <= 35:
+ timeout = args.get("timeout", 45.0)
+ if isinstance(timeout, bool) or not isinstance(timeout, (int, float)) or not 0 <= timeout <= 45:
raise BrowserExtensionBrokerError("INVALID_REQUEST", "Connection wait timeout is invalid")
return {"connected": await self._wait_client_ready(connection, relay, float(timeout))}
if (
diff --git a/skyvern/browser_extension/broker_state.py b/skyvern/browser_extension/broker_state.py
index 2e2ee3836..aa2adb0e7 100644
--- a/skyvern/browser_extension/broker_state.py
+++ b/skyvern/browser_extension/broker_state.py
@@ -666,6 +666,14 @@ def read_readiness(fd: int, *, timeout: float = STARTUP_TIMEOUT_SECONDS) -> dict
raise BrowserExtensionBrokerError("INVALID_READINESS", "Broker readiness response is invalid") from exc
if not isinstance(value, dict) or value.get("status") not in {"READY", "ERROR"}:
raise BrowserExtensionBrokerError("INVALID_READINESS", "Broker readiness response is invalid")
+ if value["status"] == "READY":
+ port = value.get("port")
+ if type(port) is not int or not 1 <= port <= 65535:
+ raise BrowserExtensionBrokerError("INVALID_READINESS", "Broker readiness response is invalid")
+ else:
+ code = value.get("code")
+ if not isinstance(code, str) or not code:
+ raise BrowserExtensionBrokerError("INVALID_READINESS", "Broker readiness response is invalid")
return value
diff --git a/skyvern/browser_extension/cdp_adapter.py b/skyvern/browser_extension/cdp_adapter.py
index d7521a336..89e247dea 100644
--- a/skyvern/browser_extension/cdp_adapter.py
+++ b/skyvern/browser_extension/cdp_adapter.py
@@ -10,7 +10,11 @@ from typing import Any, Protocol
import structlog
from aiohttp import WSMsgType, web
-from skyvern.browser_extension.errors import BrowserExtensionError, ExtensionRequestError
+from skyvern.browser_extension.errors import (
+ BrowserExtensionBrokerError,
+ BrowserExtensionError,
+ ExtensionRequestError,
+)
from skyvern.browser_extension.protocol import is_cdp_method_allowed
from skyvern.browser_extension.relay import _MAX_WS_MESSAGE_BYTES
from skyvern.browser_extension.target_registry import VirtualTargetRegistry
@@ -236,7 +240,7 @@ class ExtensionCdpAdapter:
await self._handle_session_command(ws, request_id, session_id, method, params)
else:
await self._handle_root_command(ws, request_id, method, params)
- except ExtensionRequestError as exc:
+ except (ExtensionRequestError, BrowserExtensionBrokerError) as exc:
error = {"code": -32000, "message": f"{exc.code}: {exc.message}"}
response = {"id": request_id, "error": error}
if isinstance(session_id, str):
@@ -349,9 +353,10 @@ class ExtensionCdpAdapter:
params: dict,
response_session_id: str | None,
) -> None:
+ previous_auto_attach = self._auto_attach
self._auto_attach = params.get("autoAttach") is True
- await self._reply(ws, request_id, {}, response_session_id)
if not self._auto_attach:
+ await self._reply(ws, request_id, {}, response_session_id)
return
tabs = [tab for tab in self._relay.scoped_tabs if isinstance(tab, dict)]
if not tabs:
@@ -374,32 +379,37 @@ class ExtensionCdpAdapter:
tab_id = created["tabId"]
if type(tab_id) is not int:
raise BrowserExtensionError("Created tab id is invalid")
- tabs = [{"tabId": tab_id, "url": "about:blank", "title": ""}]
- except Exception as exc:
- LOG.debug(
- "browser_extension_auto_attach_target_skipped",
- error_type=type(exc).__name__,
- )
- return
- for tab in tabs:
- tab_id = tab.get("tabId")
- if type(tab_id) is not int:
- continue
- generation = self._active_scope_generation(tab_id)
- if generation is None:
- continue
- try:
+ except BaseException:
+ self._auto_attach = previous_auto_attach
+ raise
+ tabs = [{"tabId": tab_id, "url": "about:blank", "title": ""}]
+
+ newly_attached: list[tuple[int, str, int]] = []
+ try:
+ for tab in tabs:
+ tab_id = tab.get("tabId")
+ if type(tab_id) is not int:
+ continue
+ generation = self._active_scope_generation(tab_id)
+ if generation is None:
+ continue
attached = await self._ensure_attached(tab, generation=generation)
if attached is not None:
target_id, is_new = attached
if is_new:
- await self._emit_attached(tab_id, target_id, generation)
- except Exception as exc:
- LOG.debug(
- "browser_extension_auto_attach_target_skipped",
- tab_id=tab_id,
- error_type=type(exc).__name__,
+ newly_attached.append((tab_id, target_id, generation))
+ except BaseException:
+ self._auto_attach = previous_auto_attach
+ for attached_tab_id, _, _ in reversed(newly_attached):
+ await self._discard_failed_attachment_safely(
+ attached_tab_id,
+ suppress_interrupts=True,
)
+ raise
+
+ await self._reply(ws, request_id, {}, response_session_id)
+ for tab_id, target_id, generation in newly_attached:
+ await self._emit_attached(tab_id, target_id, generation)
async def _set_discover_targets(
self,
@@ -787,6 +797,13 @@ class ExtensionCdpAdapter:
await self._handle_tab_added(tab, include_opener=False, generation=generation)
async def _handle_tab_added(self, params: dict, include_opener: bool, generation: int) -> None:
+ if self._auto_attach:
+ async with self._root_target_setup_lock:
+ await self._handle_tab_added_locked(params, include_opener, generation)
+ return
+ await self._handle_tab_added_locked(params, include_opener, generation)
+
+ async def _handle_tab_added_locked(self, params: dict, include_opener: bool, generation: int) -> None:
tab_id = params.get("tabId")
if type(tab_id) is not int:
return
@@ -857,34 +874,70 @@ class ExtensionCdpAdapter:
if not self._scope_is_current(tab_id, generation):
return None
is_new = tab_id not in self._attached_tabs
- real_target_id: str | None = None
if is_new:
+ debugger_attached = False
+ attachment_committed = False
+ cleanup_suppress_interrupts = True
try:
- await self._relay.request("debugger.attach", {"tabId": tab_id})
- except ExtensionRequestError as exc:
- if "already attached" not in exc.message.lower():
- raise
- real_target_id = await self._fetch_main_frame_id(tab_id)
- if not self._scope_is_current(tab_id, generation):
- return None
- target_id = self._register_tab(tab, opener_id, real_target_id)
+ try:
+ await self._relay.request("debugger.attach", {"tabId": tab_id})
+ debugger_attached = True
+ except ExtensionRequestError as exc:
+ if exc.code != "CDP_ERROR" or "already attached" not in exc.message.lower():
+ raise
+ debugger_attached = True
+ real_target_id = await self._fetch_main_frame_id(tab_id)
+ if not self._scope_is_current(tab_id, generation):
+ cleanup_suppress_interrupts = False
+ return None
+ target_id = self._register_tab(tab, opener_id, real_target_id)
+ self._attached_tabs.add(tab_id)
+ attachment_committed = True
+ finally:
+ if debugger_attached and not attachment_committed:
+ await self._discard_failed_attachment_safely(
+ tab_id,
+ suppress_interrupts=cleanup_suppress_interrupts,
+ )
+ return target_id, is_new
+ target_id = self._register_tab(tab, opener_id)
self._attached_tabs.add(tab_id)
return target_id, is_new
+ async def _discard_failed_attachment_safely(
+ self,
+ tab_id: int,
+ *,
+ suppress_interrupts: bool,
+ ) -> None:
+ try:
+ await asyncio.shield(self._discard_failed_attachment(tab_id))
+ except Exception:
+ pass
+ except BaseException:
+ if suppress_interrupts:
+ pass
+ else:
+ raise
+
async def _fetch_main_frame_id(self, tab_id: int) -> str | None:
# Playwright resolves the main frame's session by targetId, so the exposed
# page targetId must equal Chrome's real main-frame id for this tab.
- try:
- tree = await self._relay.request(
- "debugger.send",
- {"tabId": tab_id, "method": "Page.getFrameTree", "params": {}},
- )
- except ExtensionRequestError:
- return None
+ tree = await self._relay.request(
+ "debugger.send",
+ {"tabId": tab_id, "method": "Page.getFrameTree", "params": {}},
+ )
frame = tree.get("result", {}).get("frameTree", {}).get("frame", {})
frame_id = frame.get("id") if isinstance(frame, dict) else None
return frame_id if isinstance(frame_id, str) and frame_id else None
+ async def _discard_failed_attachment(self, tab_id: int) -> None:
+ try:
+ await self._relay.request("debugger.detach", {"tabId": tab_id}, timeout=2.0)
+ except BrowserExtensionError:
+ pass
+ self._forget_tab(tab_id)
+
def _register_tab(self, tab: dict, opener_id: str | None = None, target_id_override: str | None = None) -> str:
tab_id = tab["tabId"]
raw_url = tab.get("url")
diff --git a/skyvern/browser_extension/extension/bridge_connection.js b/skyvern/browser_extension/extension/bridge_connection.js
index a617ecd46..6a539a71a 100644
--- a/skyvern/browser_extension/extension/bridge_connection.js
+++ b/skyvern/browser_extension/extension/bridge_connection.js
@@ -12,10 +12,16 @@ import {
const PING_INTERVAL_MS = 20_000;
const SILENCE_TIMEOUT_MS = 45_000;
const CONNECT_TIMEOUT_MS = 10_000;
-const RECONNECT_MAX_MS = 10_000;
+const RECONNECT_MAX_MS = 30_000;
+const REQUEST_TIMEOUT_MS = 29_000;
+const RECONNECT_ALARM_PERIOD_MINUTES = 0.5;
const AUTH_EXT_CONTEXT = "skyvern-ext-v1|";
const AUTH_SERVER_CONTEXT = "skyvern-srv-v1|";
+export function nextReconnectDelay(delayMs) {
+ return Math.min(delayMs * 2, RECONNECT_MAX_MS);
+}
+
function bytesToBase64Url(bytes) {
let binary = "";
for (const byte of bytes) {
@@ -83,6 +89,7 @@ export class BridgeConnection {
onReset,
onEvent = async () => undefined,
onStateChange,
+ requestTimeoutMs = REQUEST_TIMEOUT_MS,
}) {
this.onRequest = onRequest;
this.onAuthenticated = onAuthenticated;
@@ -106,6 +113,8 @@ export class BridgeConnection {
this.serverNonce = null;
this.hmacKey = null;
this.messageQueue = Promise.resolve();
+ this.inflightRequests = new Set();
+ this.requestTimeoutMs = requestTimeoutMs;
chrome.alarms.onAlarm.addListener((alarm) => {
if (alarm.name === BRIDGE_ALARM_NAME) {
@@ -124,13 +133,19 @@ export class BridgeConnection {
this.token =
typeof stored.pairingToken === "string" ? stored.pairingToken : "";
this.enabled = stored.enabled === true;
- await chrome.alarms.create(BRIDGE_ALARM_NAME, { periodInMinutes: 0.5 });
+ await this.ensureReconnectAlarm();
this.notifyState();
if (this.enabled && this.token) {
await this.kick();
}
}
+ async ensureReconnectAlarm() {
+ await chrome.alarms.create(BRIDGE_ALARM_NAME, {
+ periodInMinutes: RECONNECT_ALARM_PERIOD_MINUTES,
+ });
+ }
+
getStatus() {
return {
connected: this.authenticated,
@@ -168,6 +183,7 @@ export class BridgeConnection {
"A pairing token is required.",
);
}
+ await this.ensureReconnectAlarm();
this.enabled = true;
this.lastError = "";
this.reconnectDelayMs = 1_000;
@@ -224,19 +240,7 @@ export class BridgeConnection {
});
socket.addEventListener("message", (event) => {
if (generation === this.connectionGeneration) {
- const handling = this.messageQueue
- .catch(() => undefined)
- .then(() => {
- if (
- generation !== this.connectionGeneration ||
- this.socket !== socket
- ) {
- return undefined;
- }
- return this.handleMessage(event.data);
- });
- this.messageQueue = handling;
- void handling;
+ this.enqueueIncomingMessage(event.data, generation, socket);
}
});
socket.addEventListener("error", () => {
@@ -257,7 +261,27 @@ export class BridgeConnection {
});
}
- async handleMessage(rawMessage) {
+ enqueueIncomingMessage(rawMessage, generation, socket) {
+ const handling = this.messageQueue
+ .catch(() => undefined)
+ .then(() => {
+ if (
+ generation !== this.connectionGeneration ||
+ this.socket !== socket
+ ) {
+ return undefined;
+ }
+ return this.handleMessage(rawMessage, generation, socket);
+ });
+ this.messageQueue = handling;
+ void handling;
+ }
+
+ async handleMessage(
+ rawMessage,
+ generation = this.connectionGeneration,
+ socket = this.socket,
+ ) {
this.lastMessageAt = Date.now();
let message;
try {
@@ -292,7 +316,7 @@ export class BridgeConnection {
return;
}
if (message.type === MESSAGE_TYPES.REQUEST) {
- await this.handleRequest(message);
+ this.startRequest(message, generation, socket);
return;
}
if (message.type === MESSAGE_TYPES.EVENT) {
@@ -364,6 +388,16 @@ export class BridgeConnection {
}
}
+ startRequest(message, generation, socket) {
+ const request = this.handleRequest(message, generation, socket).catch(
+ () => {
+ this.failConnection("The local bridge connection failed.");
+ },
+ );
+ this.inflightRequests.add(request);
+ request.finally(() => this.inflightRequests.delete(request));
+ }
+
async handleAuthMessage(message) {
if (
message.type === MESSAGE_TYPES.AUTH_CHALLENGE &&
@@ -414,6 +448,7 @@ export class BridgeConnection {
this.authenticated = true;
this.lastError = "";
this.reconnectDelayMs = 1_000;
+ await this.ensureReconnectAlarm();
this.notifyState();
await this.onAuthenticated();
return;
@@ -425,32 +460,62 @@ export class BridgeConnection {
);
}
- async handleRequest(message) {
+ async handleRequest(message, generation, socket) {
if (typeof message.id !== "string" || typeof message.op !== "string") {
this.failConnection("The local bridge sent an invalid request.");
return;
}
try {
- const result = await this.onRequest(message.op, message.args);
- this.sendRaw({
- v: PROTOCOL_VERSION,
- type: MESSAGE_TYPES.RESPONSE,
- id: message.id,
- ok: true,
- result,
- });
+ let timeoutId;
+ const result = await Promise.race([
+ this.onRequest(message.op, message.args),
+ new Promise((_, reject) => {
+ timeoutId = setTimeout(
+ () =>
+ reject(
+ new ProtocolError(
+ ERROR_CODES.COMMAND_TIMEOUT,
+ `Extension command timed out: ${message.op}`,
+ ),
+ ),
+ this.requestTimeoutMs,
+ );
+ }),
+ ]).finally(() => clearTimeout(timeoutId));
+ this.sendResponse(
+ {
+ v: PROTOCOL_VERSION,
+ type: MESSAGE_TYPES.RESPONSE,
+ id: message.id,
+ ok: true,
+ result,
+ },
+ generation,
+ socket,
+ );
} catch (error) {
- this.sendRaw({
- v: PROTOCOL_VERSION,
- type: MESSAGE_TYPES.RESPONSE,
- id: message.id,
- ok: false,
- error: protocolErrorEnvelope(error),
- });
+ this.sendResponse(
+ {
+ v: PROTOCOL_VERSION,
+ type: MESSAGE_TYPES.RESPONSE,
+ id: message.id,
+ ok: false,
+ error: protocolErrorEnvelope(error),
+ },
+ generation,
+ socket,
+ );
}
}
+ sendResponse(message, generation, socket) {
+ if (generation !== this.connectionGeneration || this.socket !== socket) {
+ return false;
+ }
+ return this.sendRaw(message);
+ }
+
sendEvent(event, params) {
if (!this.authenticated) {
return false;
@@ -515,10 +580,7 @@ export class BridgeConnection {
return;
}
const delay = this.reconnectDelayMs;
- this.reconnectDelayMs = Math.min(
- this.reconnectDelayMs * 2,
- RECONNECT_MAX_MS,
- );
+ this.reconnectDelayMs = nextReconnectDelay(this.reconnectDelayMs);
this.reconnectTimer = setTimeout(() => {
this.reconnectTimer = null;
void this.kick();
diff --git a/skyvern/browser_extension/extension/debugger_router.js b/skyvern/browser_extension/extension/debugger_router.js
index 5deda7596..6c80d040a 100644
--- a/skyvern/browser_extension/extension/debugger_router.js
+++ b/skyvern/browser_extension/extension/debugger_router.js
@@ -9,19 +9,42 @@ import {
} from "./protocol.js";
const CHILD_AUTO_ATTACH_TIMEOUT_MS = 2_000;
+const ATTACH_TIMEOUT_MS = 10_000;
+const COMMAND_TIMEOUT_MS = 25_000;
+const RECOVERY_TIMEOUT_MS = 2_000;
+const OPERATION_DEADLINE_MARGIN_MS = 500;
const LEAF_TARGET_TYPES = new Set([
"service_worker",
"shared_worker",
"worker",
]);
+function debuggerErrorReason(error) {
+ const reason = error instanceof Error ? error.message.trim() : "";
+ return reason ? reason.slice(0, 200) : "unknown reason";
+}
+
export class DebuggerRouter {
- constructor({ tabScope, sendEvent, onAttachedChange }) {
+ constructor({
+ tabScope,
+ sendEvent,
+ onAttachedChange,
+ attachTimeoutMs = ATTACH_TIMEOUT_MS,
+ commandTimeoutMs = COMMAND_TIMEOUT_MS,
+ recoveryTimeoutMs = RECOVERY_TIMEOUT_MS,
+ operationDeadlineMarginMs = OPERATION_DEADLINE_MARGIN_MS,
+ }) {
this.tabScope = tabScope;
this.sendEvent = sendEvent;
this.onAttachedChange = onAttachedChange;
this.attachedTabs = new Set();
+ this.attachStates = new Map();
this.childTargets = new Map();
+ this.attachTimeoutMs = attachTimeoutMs;
+ this.commandTimeoutMs = commandTimeoutMs;
+ this.recoveryTimeoutMs = recoveryTimeoutMs;
+ this.operationDeadlineMarginMs = operationDeadlineMarginMs;
+ this.stateSequence = 0;
chrome.debugger.onEvent.addListener((source, method, params) => {
void this.handleDebuggerEvent(source, method, params);
@@ -36,28 +59,61 @@ export class DebuggerRouter {
}
async reset() {
- const attachedTabIds = [...this.attachedTabs];
+ const attachedTabIds = [
+ ...new Set([...this.attachedTabs, ...this.attachStates.keys()]),
+ ];
const results = await Promise.all(
attachedTabIds.map(async (tabId) => {
+ const priorState = this.attachStates.get(tabId);
+ if (!this.attachedTabs.has(tabId) && priorState?.status === "failed") {
+ this.attachStates.delete(tabId);
+ return true;
+ }
+ if (
+ !this.attachedTabs.has(tabId) &&
+ ["attaching", "orphaned_attach"].includes(priorState?.status)
+ ) {
+ this.attachStates.set(tabId, {
+ ...priorState,
+ status: "orphaned_attach",
+ });
+ if (!(await this.isDebuggerStillAttached(tabId))) {
+ return true;
+ }
+ }
+ const token = priorState?.token ?? this.nextStateToken();
+ this.attachStates.set(tabId, { status: "detaching", token });
+ const detachPromise = Promise.resolve().then(() =>
+ chrome.debugger.detach({ tabId }),
+ );
try {
- await chrome.debugger.detach({ tabId });
+ await this.withTimeout(() => detachPromise, this.recoveryTimeoutMs);
} catch {
+ this.trackLateDetach(tabId, token, detachPromise);
if (await this.isDebuggerStillAttached(tabId)) {
+ this.quarantineTab(tabId, token, "detach_failed");
return false;
}
}
- this.attachedTabs.delete(tabId);
- this.forgetChildTargets(tabId);
+ this.clearDetachedState(tabId, token);
return true;
}),
);
+ for (const [tabId, state] of this.attachStates) {
+ if (state.status === "failed" && !this.attachedTabs.has(tabId)) {
+ this.attachStates.delete(tabId);
+ }
+ }
this.onAttachedChange();
return { failedTabCount: results.filter((detached) => !detached).length };
}
async isDebuggerStillAttached(tabId) {
try {
- const targets = await chrome.debugger.getTargets();
+ const targets = await this.withTimeout(
+ () => chrome.debugger.getTargets(),
+ this.recoveryTimeoutMs,
+ );
return targets.some(
(target) => target.tabId === tabId && target.attached,
);
@@ -69,23 +125,84 @@ export class DebuggerRouter {
async attach(args) {
const values = requireArgs(args);
const tabId = requireTabId(values.tabId);
- return this.tabScope.runTabOperation(tabId, async () => {
- await this.ensureStillControllableLocked(tabId);
+ return this.tabScope.runTabOperation(tabId, async (lease) => {
+ await this.ensureStillControllableLocked(tabId, lease);
if (this.attachedTabs.has(tabId)) {
+ this.attachStates.set(tabId, { status: "attached" });
return {};
}
- try {
- await chrome.debugger.attach({ tabId }, "1.3");
- } catch {
- await this.ensureStillControllableLocked(tabId);
+ const existingState = this.attachStates.get(tabId);
+ if (existingState !== undefined) {
throw new ProtocolError(
- ERROR_CODES.CDP_ERROR,
- "Chrome could not attach the debugger to this tab.",
+ ERROR_CODES.ATTACH_FAILED,
+ existingState.reason ||
+ "A debugger attach attempt is already unresolved.",
);
}
+ const token = this.nextStateToken();
+ const attachPromise = Promise.resolve().then(() =>
+ chrome.debugger.attach({ tabId }, "1.3"),
+ );
+ this.attachStates.set(tabId, { status: "attaching", token });
+ let timedOut = false;
+ try {
+ await this.withTimeout(
+ () => attachPromise,
+ this.attachTimeoutMs,
+ () => {
+ timedOut = true;
+ return new ProtocolError(
+ ERROR_CODES.ATTACH_FAILED,
+ "Chrome debugger attach timed out.",
+ );
+ },
+ );
+ } catch (error) {
+ const attachError =
+ error instanceof ProtocolError &&
+ error.code === ERROR_CODES.ATTACH_FAILED
+ ? error
+ : new ProtocolError(
+ ERROR_CODES.ATTACH_FAILED,
+ `Chrome rejected debugger attachment: ${debuggerErrorReason(error)}`,
+ );
+ if (timedOut) {
+ this.attachStates.set(tabId, {
+ status: "orphaned_attach",
+ token,
+ reason: attachError.message,
+ });
+ this.trackLateAttach(tabId, token, attachPromise);
+ } else if (this.attachStates.get(tabId)?.token === token) {
+ if (lease.isCurrent()) {
+ this.attachStates.set(tabId, {
+ status: "failed",
+ token,
+ reason: attachError.message,
+ });
+ } else {
+ this.attachStates.delete(tabId);
+ }
+ }
+ throw attachError;
+ }
+ if (
+ !lease.isCurrent() ||
+ this.attachStates.get(tabId)?.token !== token ||
+ this.attachStates.get(tabId)?.status !== "attaching"
+ ) {
+ this.attachStates.set(tabId, {
+ status: "orphaned_attach",
+ token,
+ reason: "attach_cancelled",
+ });
+ this.trackLateAttach(tabId, token, Promise.resolve());
+ lease.assertCurrent();
+ }
this.attachedTabs.add(tabId);
+ this.attachStates.set(tabId, { status: "attached", token });
this.onAttachedChange();
- await this.ensureStillControllableLocked(tabId);
+ await this.ensureStillControllableLocked(tabId, lease);
return {};
});
}
@@ -93,26 +210,58 @@ export class DebuggerRouter {
async detach(args) {
const values = requireArgs(args);
const tabId = requireTabId(values.tabId);
- return this.tabScope.runTabOperation(tabId, async () => {
+ return this.tabScope.runTabOperation(tabId, async (lease) => {
await this.tabScope.assertScoped(tabId);
if (!this.attachedTabs.has(tabId)) {
- await this.tabScope.handleDebuggerDetachLocked(tabId);
+ await this.tabScope.handleDebuggerDetachLocked(tabId, lease);
return {};
}
+ if (
+ this.attachStates.has(tabId) &&
+ this.attachStates.get(tabId)?.status !== "attached"
+ ) {
+ throw new ProtocolError(
+ ERROR_CODES.DEBUGGER_DETACHED,
+ "The debugger is not attached to this tab.",
+ );
+ }
+ const token = this.nextStateToken();
+ const detachPromise = Promise.resolve().then(() =>
+ chrome.debugger.detach({ tabId }),
+ );
+ this.attachStates.set(tabId, { status: "detaching", token });
+ let timedOut = false;
try {
- await chrome.debugger.detach({ tabId });
+ await this.withTimeout(
+ () => detachPromise,
+ this.recoveryTimeoutMs,
+ () => {
+ timedOut = true;
+ return new Error("timeout");
+ },
+ );
} catch {
- if (await this.isDebuggerStillAttached(tabId)) {
+ if (timedOut) {
+ this.quarantineTab(tabId, token, "detach_timeout");
+ this.trackLateDetach(tabId, token, detachPromise);
+ } else if (await this.isDebuggerStillAttached(tabId)) {
+ this.attachStates.set(tabId, { status: "attached", token });
throw new ProtocolError(
ERROR_CODES.CDP_ERROR,
"Chrome could not detach the debugger from this tab.",
);
+ } else {
+ this.clearDetachedState(tabId, token);
+ await this.tabScope.handleDebuggerDetachLocked(tabId, lease);
+ return {};
}
+ throw new ProtocolError(
+ ERROR_CODES.DEBUGGER_DETACHED,
+ "The debugger is not attached to this tab.",
+ );
}
- this.attachedTabs.delete(tabId);
- this.forgetChildTargets(tabId);
- this.onAttachedChange();
- await this.tabScope.handleDebuggerDetachLocked(tabId);
+ this.clearDetachedState(tabId, token);
+ await this.tabScope.handleDebuggerDetachLocked(tabId, lease);
return {};
});
}
@@ -120,12 +269,12 @@ export class DebuggerRouter {
async send(args) {
const values = requireArgs(args);
const tabId = requireTabId(values.tabId);
- let commandPromise;
- let commandError;
- let skippedLeafAutoAttach = false;
- await this.tabScope.runTabOperation(tabId, async () => {
- await this.ensureStillControllableLocked(tabId);
- if (!this.attachedTabs.has(tabId)) {
+ return this.tabScope.runTabOperation(tabId, async (lease) => {
+ await this.ensureStillControllableLocked(tabId, lease);
+ if (
+ !this.attachedTabs.has(tabId) ||
+ this.attachStates.get(tabId)?.status !== "attached"
+ ) {
throw new ProtocolError(
ERROR_CODES.DEBUGGER_DETACHED,
"The debugger is not attached to this tab.",
@@ -166,53 +315,66 @@ export class DebuggerRouter {
childTarget?.tabId === tabId &&
LEAF_TARGET_TYPES.has(childTarget?.type)
) {
- skippedLeafAutoAttach = true;
- return;
+ return { result: {} };
}
const target =
values.sessionId === undefined
? { tabId }
: { tabId, sessionId: values.sessionId };
- // Initiate under the per-tab chain, then release it before awaiting the response.
+ const childAutoAttach =
+ values.method === "Target.setAutoAttach" &&
+ values.sessionId !== undefined;
+ const commandTimeoutMs = this.commandTimeoutWithinLease(
+ lease,
+ childAutoAttach ? CHILD_AUTO_ATTACH_TIMEOUT_MS : this.commandTimeoutMs,
+ childAutoAttach ? 0 : this.recoveryTimeoutMs * 2,
+ values.method,
+ );
+ let result;
try {
- commandPromise =
- values.method === "Target.setAutoAttach" &&
- values.sessionId !== undefined
- ? this.sendCommandWithTimeout(
- target,
- values.method,
- values.params ?? {},
- CHILD_AUTO_ATTACH_TIMEOUT_MS,
- )
- : chrome.debugger.sendCommand(
- target,
- values.method,
- values.params ?? {},
- );
+ result = await (childAutoAttach
+ ? this.sendCommandWithTimeout(
+ target,
+ values.method,
+ values.params ?? {},
+ commandTimeoutMs,
+ )
+ : this.sendCommandWithTimeout(
+ target,
+ values.method,
+ values.params ?? {},
+ commandTimeoutMs,
+ ));
} catch (error) {
- commandError = error;
+ if (
+ error instanceof ProtocolError &&
+ error.code === ERROR_CODES.COMMAND_TIMEOUT
+ ) {
+ if (lease.isCurrent() && !childAutoAttach) {
+ await this.recoverTimedOutCommandLocked(tabId);
+ }
+ throw error;
+ }
+ await this.ensureStillControllableLocked(tabId, lease);
+ throw new ProtocolError(
+ ERROR_CODES.CDP_ERROR,
+ "Chrome rejected the CDP command.",
+ );
}
- });
- if (skippedLeafAutoAttach) {
- return { result: {} };
- }
-
- let result;
- try {
- if (commandError !== undefined) {
- throw commandError;
+ lease.assertCurrent();
+ await this.ensureStillControllableLocked(tabId, lease);
+ if (
+ !this.attachedTabs.has(tabId) ||
+ this.attachStates.get(tabId)?.status !== "attached"
+ ) {
+ throw new ProtocolError(
+ ERROR_CODES.DEBUGGER_DETACHED,
+ "The debugger is not attached to this tab.",
+ );
}
- result = await commandPromise;
- } catch {
- await this.assertCanSend(tabId);
- throw new ProtocolError(
- ERROR_CODES.CDP_ERROR,
- "Chrome rejected the CDP command.",
- );
- }
- await this.assertCanSend(tabId);
- return { result: result ?? {} };
+ return { result: result ?? {} };
+ });
}
async assertCanSend(tabId) {
@@ -228,12 +390,49 @@ export class DebuggerRouter {
}
async sendCommandWithTimeout(target, method, params, timeoutMs) {
+ return this.withTimeout(
+ () => chrome.debugger.sendCommand(target, method, params),
+ timeoutMs,
+ () =>
+ new ProtocolError(
+ ERROR_CODES.COMMAND_TIMEOUT,
+ `Chrome debugger command timed out: ${method}`,
+ ),
+ );
+ }
+
+ commandTimeoutWithinLease(
+ lease,
+ requestedTimeoutMs,
+ recoveryReserveMs,
+ method,
+ ) {
+ if (typeof lease.remainingMs !== "function") {
+ return requestedTimeoutMs;
+ }
+ const availableMs = Math.floor(
+ lease.remainingMs() - recoveryReserveMs - this.operationDeadlineMarginMs,
+ );
+ if (availableMs <= 0) {
+ throw new ProtocolError(
+ ERROR_CODES.COMMAND_TIMEOUT,
+ `Chrome debugger command timed out before it could start: ${method}`,
+ );
+ }
+ return Math.min(requestedTimeoutMs, availableMs);
+ }
+
+ async withTimeout(
+ operation,
+ timeoutMs,
+ timeoutError = () => new Error("timeout"),
+ ) {
let timeoutId;
try {
return await Promise.race([
- chrome.debugger.sendCommand(target, method, params),
+ Promise.resolve().then(operation),
new Promise((_, reject) => {
- timeoutId = setTimeout(() => reject(new Error("timeout")), timeoutMs);
+ timeoutId = setTimeout(() => reject(timeoutError()), timeoutMs);
}),
]);
} finally {
@@ -241,6 +440,35 @@ export class DebuggerRouter {
}
}
+ async recoverTimedOutCommandLocked(tabId) {
+ const token = this.nextStateToken();
+ this.attachStates.set(tabId, { status: "recovering", token });
+ const detachPromise = Promise.resolve().then(() =>
+ chrome.debugger.detach({ tabId }),
+ );
+ let timedOut = false;
+ try {
+ await this.withTimeout(
+ () => detachPromise,
+ this.recoveryTimeoutMs,
+ () => {
+ timedOut = true;
+ return new Error("timeout");
+ },
+ );
+ this.clearDetachedState(tabId, token);
+ } catch {
+ if (timedOut) {
+ this.quarantineTab(tabId, token, "command_timeout");
+ this.trackLateDetach(tabId, token, detachPromise);
+ } else if (await this.isDebuggerStillAttached(tabId)) {
+ this.quarantineTab(tabId, token, "command_timeout_detach_failed");
+ } else {
+ this.clearDetachedState(tabId, token);
+ }
+ }
+ }
+
async detachIfAttached(tabId) {
return this.tabScope.runTabOperation(tabId, () =>
this.detachIfAttachedLocked(tabId),
@@ -249,24 +477,144 @@ export class DebuggerRouter {
async detachIfAttachedLocked(tabId) {
if (!this.attachedTabs.has(tabId)) {
+ if (
+ !["attaching", "orphaned_attach"].includes(
+ this.attachStates.get(tabId)?.status,
+ )
+ ) {
+ this.attachStates.delete(tabId);
+ }
return;
}
+ const token = this.nextStateToken();
+ const detachPromise = Promise.resolve().then(() =>
+ chrome.debugger.detach({ tabId }),
+ );
+ this.attachStates.set(tabId, { status: "detaching", token });
+ let timedOut = false;
try {
- await chrome.debugger.detach({ tabId });
+ await this.withTimeout(
+ () => detachPromise,
+ this.recoveryTimeoutMs,
+ () => {
+ timedOut = true;
+ return new Error("timeout");
+ },
+ );
} catch {
- this.attachedTabs.delete(tabId);
- this.forgetChildTargets(tabId);
- this.onAttachedChange();
+ if (timedOut) {
+ this.quarantineTab(tabId, token, "detach_timeout");
+ this.trackLateDetach(tabId, token, detachPromise);
+ } else if (!(await this.isDebuggerStillAttached(tabId))) {
+ this.clearDetachedState(tabId, token);
+ } else {
+ this.quarantineTab(tabId, token, "detach_failed");
+ }
+ return;
+ }
+ this.clearDetachedState(tabId, token);
+ }
+
+ nextStateToken() {
+ this.stateSequence += 1;
+ return this.stateSequence;
+ }
+
+ clearDetachedState(tabId, token = null) {
+ if (token !== null && this.attachStates.get(tabId)?.token !== token) {
return;
}
this.attachedTabs.delete(tabId);
+ this.attachStates.delete(tabId);
+ this.forgetChildTargets(tabId);
+ this.onAttachedChange();
+ }
+
+ quarantineTab(tabId, token, reason) {
+ this.attachedTabs.delete(tabId);
+ this.attachStates.set(tabId, { status: "quarantined", token, reason });
this.forgetChildTargets(tabId);
this.onAttachedChange();
}
- async ensureStillControllableLocked(tabId) {
+ trackLateAttach(tabId, token, attachPromise) {
+ void attachPromise
+ .then(
+ () => this.compensateLateAttach(tabId, token),
+ () => this.clearLateAttachFailure(tabId, token),
+ )
+ .catch(() => undefined);
+ }
+
+ async compensateLateAttach(tabId, token) {
+ await this.tabScope.runTabOperation(tabId, async () => {
+ if (this.attachStates.get(tabId)?.token !== token) {
+ return;
+ }
+ const detachPromise = Promise.resolve().then(() =>
+ chrome.debugger.detach({ tabId }),
+ );
+ this.attachStates.set(tabId, { status: "detaching", token });
+ let timedOut = false;
+ try {
+ await this.withTimeout(
+ () => detachPromise,
+ this.recoveryTimeoutMs,
+ () => {
+ timedOut = true;
+ return new Error("timeout");
+ },
+ );
+ this.clearDetachedState(tabId, token);
+ } catch {
+ if (timedOut) {
+ this.quarantineTab(tabId, token, "late_attach_detach_timeout");
+ this.trackLateDetach(tabId, token, detachPromise);
+ } else if (await this.isDebuggerStillAttached(tabId)) {
+ this.quarantineTab(tabId, token, "late_attach_detach_failed");
+ } else {
+ this.clearDetachedState(tabId, token);
+ }
+ }
+ });
+ }
+
+ async clearLateAttachFailure(tabId, token) {
+ await this.tabScope.runTabOperation(tabId, async () => {
+ if (
+ this.attachStates.get(tabId)?.token === token &&
+ !this.attachedTabs.has(tabId)
+ ) {
+ this.attachStates.delete(tabId);
+ }
+ });
+ }
+
+ trackLateDetach(tabId, token, detachPromise) {
+ void detachPromise
+ .then(
+ () =>
+ this.tabScope.runTabOperation(tabId, async () => {
+ this.clearDetachedState(tabId, token);
+ }),
+ () =>
+ this.tabScope.runTabOperation(tabId, async () => {
+ if (this.attachStates.get(tabId)?.token !== token) {
+ return;
+ }
+ if (await this.isDebuggerStillAttached(tabId)) {
+ this.quarantineTab(tabId, token, "detach_failed");
+ } else {
+ this.clearDetachedState(tabId, token);
+ }
+ }),
+ )
+ .catch(() => undefined);
+ }
+
+ async ensureStillControllableLocked(tabId, lease = null) {
try {
- await this.tabScope.assertControllableLocked(tabId);
+ await this.tabScope.assertControllableLocked(tabId, lease);
} catch (error) {
await this.detachIfAttachedLocked(tabId);
throw error;
@@ -292,7 +640,8 @@ export class DebuggerRouter {
async handleDebuggerEvent(source, method, params) {
if (
!Number.isInteger(source.tabId) ||
- !this.tabScope.isScoped(source.tabId)
+ !this.tabScope.isScoped(source.tabId) ||
+ this.tabScope.isQuarantined?.(source.tabId) === true
) {
return;
}
@@ -324,15 +673,17 @@ export class DebuggerRouter {
if (!Number.isInteger(source.tabId)) {
return;
}
- await this.tabScope.runTabOperation(source.tabId, async () => {
+ await this.tabScope.runTabOperation(source.tabId, async (lease) => {
+ lease.assertCurrent();
this.attachedTabs.delete(source.tabId);
+ this.attachStates.delete(source.tabId);
this.forgetChildTargets(source.tabId);
this.onAttachedChange();
this.sendEvent(EVENTS.DEBUGGER_DETACHED, {
tabId: source.tabId,
reason: typeof reason === "string" ? reason : "unknown",
});
- await this.tabScope.handleDebuggerDetachLocked(source.tabId);
+ await this.tabScope.handleDebuggerDetachLocked(source.tabId, lease);
});
}
diff --git a/skyvern/browser_extension/extension/protocol.js b/skyvern/browser_extension/extension/protocol.js
index baa8cfcac..8884fbf88 100644
--- a/skyvern/browser_extension/extension/protocol.js
+++ b/skyvern/browser_extension/extension/protocol.js
@@ -45,9 +45,11 @@ export const ERROR_CODES = Object.freeze({
TAB_NOT_FOUND: "TAB_NOT_FOUND",
TAB_NOT_SCOPED: "TAB_NOT_SCOPED",
RESTRICTED_URL: "RESTRICTED_URL",
+ ATTACH_FAILED: "ATTACH_FAILED",
DEBUGGER_DETACHED: "DEBUGGER_DETACHED",
CDP_METHOD_NOT_ALLOWED: "CDP_METHOD_NOT_ALLOWED",
CDP_ERROR: "CDP_ERROR",
+ COMMAND_TIMEOUT: "COMMAND_TIMEOUT",
INTERNAL: "INTERNAL",
});
diff --git a/skyvern/browser_extension/extension/tab_scope.js b/skyvern/browser_extension/extension/tab_scope.js
index 73ceb98c7..5fd54e452 100644
--- a/skyvern/browser_extension/extension/tab_scope.js
+++ b/skyvern/browser_extension/extension/tab_scope.js
@@ -14,6 +14,7 @@ const SKYVERN_GROUP_TITLE = "Skyvern Controlled";
const SKYVERN_GROUP_COLOR = "purple";
const TAB_GROUP_ID_NONE = -1;
const ANY_GROUP_ID = Symbol("anyGroupId");
+const TAB_OPERATION_TIMEOUT_MS = 28_000;
function tabUrl(tab) {
return tab.pendingUrl || tab.url || "";
@@ -26,15 +27,19 @@ function isTabRestricted(tab) {
}
export class TabScope {
- constructor({ sendEvent }) {
+ constructor({ sendEvent, operationTimeoutMs = TAB_OPERATION_TIMEOUT_MS }) {
this.sendEvent = sendEvent;
this.scopedTabIds = new Set();
+ this.quarantinedTabIds = new Set();
this.scopedGroupIds = new Map();
this.createdTabIds = new Set();
this.expectedGroupTransitions = new Map();
this.tabOperations = new Map();
this.debuggerRouter = null;
this.activeOperationCount = 0;
+ this.operationGeneration = 0;
+ this.operationLeases = new Set();
+ this.operationTimeoutMs = operationTimeoutMs;
this.operationsIdle = Promise.resolve();
this.resolveOperationsIdle = null;
this.resetting = false;
@@ -116,6 +121,15 @@ export class TabScope {
this.resetFinished = new Promise((resolve) => {
this.resolveResetFinished = resolve;
});
+ this.operationGeneration += 1;
+ for (const lease of this.operationLeases) {
+ lease.cancel(
+ new ProtocolError(
+ ERROR_CODES.COMMAND_TIMEOUT,
+ "The extension operation was cancelled by reset.",
+ ),
+ );
+ }
await this.operationsIdle;
}
@@ -164,6 +178,10 @@ export class TabScope {
return this.scopedTabIds.has(tabId);
}
+ isQuarantined(tabId) {
+ return this.quarantinedTabIds.has(tabId);
+ }
+
async assertScoped(tabId) {
await this.ready;
if (!this.scopedTabIds.has(tabId)) {
@@ -174,20 +192,22 @@ export class TabScope {
}
}
- async assertControllableLocked(tabId) {
+ async assertControllableLocked(tabId, lease = null) {
await this.assertScoped(tabId);
+ lease?.assertCurrent();
let tab;
try {
tab = await this.getTab(tabId);
} catch (error) {
- if (this.scopedTabIds.has(tabId)) {
- await this.removeFromScopeLocked(tabId, "closed", true);
+ if (lease?.isCurrent() !== false && this.scopedTabIds.has(tabId)) {
+ await this.removeFromScopeLocked(tabId, "closed", true, lease);
}
throw error;
}
+ lease?.assertCurrent();
await this.assertScoped(tabId);
if (isTabRestricted(tab)) {
- await this.removeFromScopeLocked(tabId, "unshared", true);
+ await this.removeFromScopeLocked(tabId, "unshared", true, lease);
throw new ProtocolError(
ERROR_CODES.RESTRICTED_URL,
"Chrome does not allow controlling this URL.",
@@ -199,8 +219,15 @@ export class TabScope {
async shareTab(tabId) {
await this.ready;
const validTabId = requireTabId(tabId);
- return this.runTabOperation(validTabId, async () => {
+ return this.runTabOperation(validTabId, async (lease) => {
+ if (this.quarantinedTabIds.has(validTabId)) {
+ throw new ProtocolError(
+ ERROR_CODES.COMMAND_TIMEOUT,
+ "The requested tab is still being reconciled after reset.",
+ );
+ }
const tab = await this.getTab(validTabId);
+ lease.assertCurrent();
if (isTabRestricted(tab)) {
throw new ProtocolError(
ERROR_CODES.RESTRICTED_URL,
@@ -210,7 +237,8 @@ export class TabScope {
if (this.scopedTabIds.has(validTabId)) {
return {};
}
- const scopedTab = await this.addToScopeLocked(tab);
+ const scopedTab = await this.addToScopeLocked(tab, lease);
+ lease.assertCurrent();
this.sendEvent(EVENTS.SCOPE_TAB_ADDED, {
...this.publicTab(scopedTab, false),
origin: "shared",
@@ -222,9 +250,10 @@ export class TabScope {
async unshareTab(tabId) {
await this.ready;
const validTabId = requireTabId(tabId);
- return this.runTabOperation(validTabId, async () => {
+ return this.runTabOperation(validTabId, async (lease) => {
await this.assertScoped(validTabId);
- await this.removeFromScopeLocked(validTabId, "unshared", true);
+ lease.assertCurrent();
+ await this.removeFromScopeLocked(validTabId, "unshared", true, lease);
return {};
});
}
@@ -241,26 +270,33 @@ export class TabScope {
"Chrome does not allow creating this URL.",
);
}
- let tab;
- try {
- tab = await chrome.tabs.create({ url });
- } catch {
- throw new ProtocolError(
- ERROR_CODES.INTERNAL,
- "Chrome could not create the tab.",
- );
- }
- if (!Number.isInteger(tab.id)) {
- throw new ProtocolError(
- ERROR_CODES.TAB_NOT_FOUND,
- "Chrome did not return a tab identifier.",
- );
- }
- return this.runTabOperation(tab.id, async () => {
+ return this.runTabOperation(Symbol("tabs.create"), async (lease) => {
+ let tab;
+ try {
+ tab = await chrome.tabs.create({ url });
+ } catch {
+ throw new ProtocolError(
+ ERROR_CODES.INTERNAL,
+ "Chrome could not create the tab.",
+ );
+ }
+ if (!lease.isCurrent()) {
+ if (Number.isInteger(tab.id)) {
+ void chrome.tabs.remove(tab.id).catch(() => undefined);
+ }
+ lease.assertCurrent();
+ }
+ if (!Number.isInteger(tab.id)) {
+ throw new ProtocolError(
+ ERROR_CODES.TAB_NOT_FOUND,
+ "Chrome did not return a tab identifier.",
+ );
+ }
this.createdTabIds.add(tab.id);
- await this.persistScope();
+ await this.persistScope(lease);
try {
- const scopedTab = await this.addToScopeLocked(tab);
+ const scopedTab = await this.addToScopeLocked(tab, lease);
+ lease.assertCurrent();
this.sendEvent(EVENTS.SCOPE_TAB_ADDED, {
...this.publicTab(scopedTab, false),
origin: "created",
@@ -280,18 +316,37 @@ export class TabScope {
async remove(args) {
const values = requireArgs(args);
const tabId = requireTabId(values.tabId);
- return this.runTabOperation(tabId, async () => {
+ return this.runTabOperation(tabId, async (lease) => {
const created = this.createdTabIds.has(tabId);
if (this.scopedTabIds.has(tabId)) {
- await this.assertControllableLocked(tabId);
+ await this.assertControllableLocked(tabId, lease);
} else if (!created) {
throw new ProtocolError(
ERROR_CODES.TAB_NOT_SCOPED,
"The requested tab is not shared.",
);
}
+ if (this.quarantinedTabIds.has(tabId)) {
+ throw new ProtocolError(
+ ERROR_CODES.COMMAND_TIMEOUT,
+ "The requested tab is still being reconciled after reset.",
+ );
+ }
+ this.quarantinedTabIds.add(tabId);
+ lease.assertCurrent();
+ let removePromise;
+ try {
+ removePromise = chrome.tabs.remove(tabId);
+ } catch (error) {
+ this.quarantinedTabIds.delete(tabId);
+ throw error;
+ }
+ const trackedRemove = Promise.resolve(removePromise).finally(() => {
+ this.quarantinedTabIds.delete(tabId);
+ });
+ void trackedRemove.catch(() => undefined);
try {
- await chrome.tabs.remove(tabId);
+ await trackedRemove;
} catch {
if (!this.scopedTabIds.has(tabId)) {
if (created) {
@@ -314,11 +369,12 @@ export class TabScope {
"The requested tab was not found.",
);
}
+ lease.assertCurrent();
this.createdTabIds.delete(tabId);
if (this.scopedTabIds.has(tabId)) {
- await this.removeFromScopeLocked(tabId, "closed", false);
+ await this.removeFromScopeLocked(tabId, "closed", false, lease);
} else {
- await this.persistScope();
+ await this.persistScope(lease);
}
return {};
});
@@ -327,8 +383,8 @@ export class TabScope {
async activate(args) {
const values = requireArgs(args);
const tabId = requireTabId(values.tabId);
- return this.runTabOperation(tabId, async () => {
- const tab = await this.assertControllableLocked(tabId);
+ return this.runTabOperation(tabId, async (lease) => {
+ const tab = await this.assertControllableLocked(tabId, lease);
try {
await chrome.tabs.update(tabId, { active: true });
if (Number.isInteger(tab.windowId)) {
@@ -340,7 +396,8 @@ export class TabScope {
"The requested tab was not found.",
);
}
- await this.assertControllableLocked(tabId);
+ lease.assertCurrent();
+ await this.assertControllableLocked(tabId, lease);
return {};
});
}
@@ -356,10 +413,11 @@ export class TabScope {
return this.collectScopedTabs(false);
}
- async handleDebuggerDetachLocked(tabId) {
+ async handleDebuggerDetachLocked(tabId, lease = null) {
await this.ready;
+ lease?.assertCurrent();
if (this.scopedTabIds.has(tabId)) {
- await this.removeFromScopeLocked(tabId, "detached", false);
+ await this.removeFromScopeLocked(tabId, "detached", false, lease);
}
}
@@ -368,14 +426,16 @@ export class TabScope {
if (!Number.isInteger(tab.id) || !Number.isInteger(tab.openerTabId)) {
return;
}
- await this.runTabOperation(tab.id, async () => {
+ 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();
+ await this.persistScope(lease);
try {
- const scopedTab = await this.addToScopeLocked(tab);
+ const scopedTab = await this.addToScopeLocked(tab, lease);
+ lease.assertCurrent();
this.sendEvent(EVENTS.TABS_CREATED, {
tabId: scopedTab.id,
openerTabId: tab.openerTabId,
@@ -394,27 +454,29 @@ export class TabScope {
async handleTabRemoved(tabId) {
await this.ready;
- await this.runTabOperation(tabId, async () => {
+ 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);
+ await this.removeFromScopeLocked(tabId, "closed", false, lease);
} else if (ownershipChanged) {
- await this.persistScope();
+ await this.persistScope(lease);
}
});
}
async handleTabUpdated(tabId, changeInfo, expectedGroupTransition = null) {
await this.ready;
- await this.runTabOperation(tabId, async () => {
+ 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);
+ await this.removeFromScopeLocked(tabId, "unshared", true, lease);
return;
}
if (
@@ -430,11 +492,13 @@ export class TabScope {
} 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) {
@@ -442,12 +506,13 @@ export class TabScope {
}
if (controlledGroup !== null) {
this.scopedGroupIds.set(tabId, tab.groupId);
- await this.persistScope();
+ await this.persistScope(lease);
+ lease.assertCurrent();
await this.updateControlledGroup(tab.groupId);
return;
}
if (expectedGroupId !== undefined) {
- await this.removeFromScopeLocked(tabId, "unshared", true);
+ await this.removeFromScopeLocked(tabId, "unshared", true, lease);
}
return;
}
@@ -456,15 +521,26 @@ export class TabScope {
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",
@@ -496,33 +572,51 @@ export class TabScope {
return !tabExists;
}
- async addToScopeLocked(tab) {
+ async addToScopeLocked(tab, lease = null) {
if (!Number.isInteger(tab.id)) {
throw new ProtocolError(
ERROR_CODES.TAB_NOT_FOUND,
"The requested tab was not found.",
);
}
+ lease?.assertCurrent();
+ if (this.quarantinedTabIds.has(tab.id)) {
+ throw new ProtocolError(
+ ERROR_CODES.COMMAND_TIMEOUT,
+ "The requested tab is still being reconciled after reset.",
+ );
+ }
this.scopedTabIds.add(tab.id);
- await this.persistScope();
- await this.groupTabLocked(tab);
- return this.assertControllableLocked(tab.id);
+ await this.persistScope(lease);
+ lease?.assertCurrent();
+ await this.groupTabLocked(tab, lease);
+ lease?.assertCurrent();
+ return this.assertControllableLocked(tab.id, lease);
}
- async addGroupedTabToScopeLocked(tab, groupId) {
+ async addGroupedTabToScopeLocked(tab, groupId, lease = null) {
if (!Number.isInteger(tab.id)) {
throw new ProtocolError(
ERROR_CODES.TAB_NOT_FOUND,
"The requested tab was not found.",
);
}
+ lease?.assertCurrent();
+ if (this.quarantinedTabIds.has(tab.id)) {
+ throw new ProtocolError(
+ ERROR_CODES.COMMAND_TIMEOUT,
+ "The requested tab is still being reconciled after reset.",
+ );
+ }
this.scopedTabIds.add(tab.id);
this.scopedGroupIds.set(tab.id, groupId);
- await this.persistScope();
- return this.assertControllableLocked(tab.id);
+ await this.persistScope(lease);
+ lease?.assertCurrent();
+ return this.assertControllableLocked(tab.id, lease);
}
- async removeFromScopeLocked(tabId, reason, detach) {
+ async removeFromScopeLocked(tabId, reason, detach, lease = null) {
+ lease?.assertCurrent();
if (!this.scopedTabIds.delete(tabId)) {
return;
}
@@ -533,17 +627,21 @@ export class TabScope {
if (detach && this.debuggerRouter !== null) {
await this.debuggerRouter.detachIfAttachedLocked(tabId);
}
+ lease?.assertCurrent();
} finally {
try {
- await this.persistScope();
+ await this.persistScope(lease);
+ lease?.assertCurrent();
} finally {
+ lease?.assertCurrent();
await this.ungroupTabLocked(tabId, scopedGroupId);
+ lease?.assertCurrent();
this.sendEvent(EVENTS.SCOPE_TAB_REMOVED, { tabId, reason });
}
}
}
- async groupTabLocked(tab) {
+ async groupTabLocked(tab, lease = null) {
const tabId = tab.id;
if (!Number.isInteger(tabId) || !Number.isInteger(tab.windowId)) {
return;
@@ -551,6 +649,7 @@ export class TabScope {
let groupId;
try {
const groups = await chrome.tabGroups.query({ windowId: tab.windowId });
+ lease?.assertCurrent();
const existingGroup = groups.find(
(group) => group.title === SKYVERN_GROUP_TITLE,
);
@@ -565,18 +664,24 @@ export class TabScope {
})
: await chrome.tabs.group({ tabIds: [tabId] });
grouped = true;
+ lease?.assertCurrent();
} finally {
if (!grouped) {
this.clearExpectedGroupTransition(tabId, transition);
}
}
- } catch {
+ } catch (error) {
+ lease?.assertCurrent();
this.scopedGroupIds.delete(tabId);
- await this.persistScope();
+ await this.persistScope(lease);
+ if (error instanceof ProtocolError) {
+ throw error;
+ }
return;
}
+ lease?.assertCurrent();
this.scopedGroupIds.set(tabId, groupId);
- await this.persistScope();
+ await this.persistScope(lease);
await this.updateControlledGroup(groupId);
}
@@ -655,25 +760,32 @@ export class TabScope {
}
async collectScopedTabs(includeActive) {
+ const generation = this.operationGeneration;
const tabs = [];
for (const tabId of [...this.scopedTabIds]) {
- const tab = await this.runTabOperation(tabId, async () => {
- if (!this.scopedTabIds.has(tabId)) {
- return null;
- }
- let scopedTab;
- try {
- scopedTab = await chrome.tabs.get(tabId);
- } catch {
- await this.removeFromScopeLocked(tabId, "closed", false);
- return null;
- }
- if (isTabRestricted(scopedTab)) {
- await this.removeFromScopeLocked(tabId, "unshared", true);
- return null;
- }
- return this.publicTab(scopedTab, includeActive);
- });
+ const tab = await this.runTabOperation(
+ tabId,
+ async (lease) => {
+ 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;
+ }
+ return this.publicTab(scopedTab, includeActive);
+ },
+ generation,
+ );
if (tab !== null) {
tabs.push(tab);
}
@@ -717,48 +829,86 @@ export class TabScope {
if (ownershipChanged) {
await this.persistScope();
}
+ const generation = this.operationGeneration;
for (const tabId of [...this.scopedTabIds]) {
- await this.runTabOperation(tabId, async () => {
- let tab;
- try {
- tab = await chrome.tabs.get(tabId);
- } catch {
- await this.removeFromScopeLocked(tabId, "closed", false);
- return;
- }
- if (isTabRestricted(tab)) {
- await this.removeFromScopeLocked(tabId, "unshared", true);
- return;
- }
- const expectedGroupId = this.scopedGroupIds.get(tabId);
- if (expectedGroupId !== undefined && tab.groupId !== expectedGroupId) {
- const controlledGroup = await this.getControlledGroup(tab.groupId);
- if (controlledGroup === null) {
- await this.removeFromScopeLocked(tabId, "unshared", true);
- } else {
- this.scopedGroupIds.set(tabId, tab.groupId);
- await this.persistScope();
- await this.updateControlledGroup(tab.groupId);
+ await this.runTabOperation(
+ tabId,
+ async (lease) => {
+ let tab;
+ try {
+ tab = await chrome.tabs.get(tabId);
+ } catch {
+ lease.assertCurrent();
+ await this.removeFromScopeLocked(tabId, "closed", false, lease);
+ return;
}
- } else if (expectedGroupId === undefined) {
- await this.groupTabLocked(tab);
- }
- });
+ lease.assertCurrent();
+ if (isTabRestricted(tab)) {
+ await this.removeFromScopeLocked(tabId, "unshared", true, lease);
+ return;
+ }
+ const expectedGroupId = this.scopedGroupIds.get(tabId);
+ if (
+ 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);
+ }
+ },
+ generation,
+ );
}
}
- async runTabOperation(tabId, operation) {
+ async runTabOperation(
+ tabId,
+ operation,
+ expectedGeneration = this.operationGeneration,
+ ) {
while (this.resetting) {
await this.resetFinished;
}
+ if (expectedGeneration !== this.operationGeneration) {
+ throw new ProtocolError(
+ ERROR_CODES.COMMAND_TIMEOUT,
+ "The extension operation was cancelled by reset.",
+ );
+ }
+ const deadlineMs = Date.now() + this.operationTimeoutMs;
+ const lease = this.createOperationLease(deadlineMs);
+ const timeoutId = setTimeout(
+ () => {
+ lease.cancel(
+ new ProtocolError(
+ ERROR_CODES.COMMAND_TIMEOUT,
+ "The extension tab operation timed out.",
+ ),
+ );
+ },
+ Math.max(0, deadlineMs - Date.now()),
+ );
if (this.activeOperationCount === 0) {
this.operationsIdle = new Promise((resolve) => {
this.resolveOperationsIdle = resolve;
});
}
this.activeOperationCount += 1;
+ this.operationLeases.add(lease);
const previous = this.tabOperations.get(tabId) ?? Promise.resolve();
- const current = previous.catch(() => undefined).then(operation);
+ const current = previous
+ .catch(() => undefined)
+ .then(() => this.runOperationWithLease(lease, operation));
this.tabOperations.set(tabId, current);
try {
return await current;
@@ -766,6 +916,8 @@ export class TabScope {
if (this.tabOperations.get(tabId) === current) {
this.tabOperations.delete(tabId);
}
+ this.operationLeases.delete(lease);
+ clearTimeout(timeoutId);
this.activeOperationCount -= 1;
if (this.activeOperationCount === 0) {
this.resolveOperationsIdle?.();
@@ -774,12 +926,63 @@ export class TabScope {
}
}
- async persistScope() {
- const groupIds = Object.fromEntries(this.scopedGroupIds);
- await chrome.storage.session.set({
+ createOperationLease(deadlineMs) {
+ const generation = this.operationGeneration;
+ let rejectInvalidated;
+ let cancelled = false;
+ let cancellationError = null;
+ const invalidated = new Promise((_, reject) => {
+ rejectInvalidated = reject;
+ });
+ void invalidated.catch(() => undefined);
+ return {
+ invalidated,
+ isCurrent: () => !cancelled && generation === this.operationGeneration,
+ remainingMs: () => Math.max(0, deadlineMs - Date.now()),
+ assertCurrent: () => {
+ if (cancelled || generation !== this.operationGeneration) {
+ throw (
+ cancellationError ??
+ new ProtocolError(
+ ERROR_CODES.COMMAND_TIMEOUT,
+ "The extension operation is no longer current.",
+ )
+ );
+ }
+ },
+ cancel: (error) => {
+ if (cancelled) {
+ return;
+ }
+ cancelled = true;
+ cancellationError = error;
+ rejectInvalidated(error);
+ },
+ };
+ }
+
+ async runOperationWithLease(lease, operation) {
+ lease.assertCurrent();
+ return Promise.race([
+ Promise.resolve().then(() => operation(lease)),
+ lease.invalidated,
+ ]);
+ }
+
+ async persistScope(lease = null) {
+ const values = {
[SCOPED_TAB_IDS_KEY]: [...this.scopedTabIds],
- [SCOPED_GROUP_IDS_KEY]: groupIds,
+ [SCOPED_GROUP_IDS_KEY]: Object.fromEntries(this.scopedGroupIds),
[CREATED_TAB_IDS_KEY]: [...this.createdTabIds],
- });
+ };
+ await chrome.storage.session.set(values);
+ if (lease !== null && !lease.isCurrent()) {
+ await chrome.storage.session.set({
+ [SCOPED_TAB_IDS_KEY]: [...this.scopedTabIds],
+ [SCOPED_GROUP_IDS_KEY]: Object.fromEntries(this.scopedGroupIds),
+ [CREATED_TAB_IDS_KEY]: [...this.createdTabIds],
+ });
+ lease.assertCurrent();
+ }
}
}
diff --git a/skyvern/browser_extension/protocol.py b/skyvern/browser_extension/protocol.py
index f1afa7047..37b583e45 100644
--- a/skyvern/browser_extension/protocol.py
+++ b/skyvern/browser_extension/protocol.py
@@ -43,9 +43,11 @@ ERROR_CODES = frozenset(
"TAB_NOT_FOUND",
"TAB_NOT_SCOPED",
"RESTRICTED_URL",
+ "ATTACH_FAILED",
"DEBUGGER_DETACHED",
"CDP_METHOD_NOT_ALLOWED",
"CDP_ERROR",
+ "COMMAND_TIMEOUT",
"INTERNAL",
}
)
diff --git a/skyvern/cli/core/result.py b/skyvern/cli/core/result.py
index 358461aa9..17da97ba9 100644
--- a/skyvern/cli/core/result.py
+++ b/skyvern/cli/core/result.py
@@ -1,9 +1,12 @@
from __future__ import annotations
+import functools
import time
+from collections.abc import Awaitable, Callable
+from contextvars import ContextVar
from dataclasses import dataclass, field
from datetime import datetime, timezone
-from typing import Any
+from typing import Any, ParamSpec, TypeVar
# Module-level flag: when True, make_result() strips fields that waste AI context
# tokens (echoed inputs, sdk_equivalent, browser_context, timing, empty collections).
@@ -152,17 +155,65 @@ def make_error(
}
+_P = ParamSpec("_P")
+_R = TypeVar("_R")
+
+_pending_attach: ContextVar[int | None] = ContextVar("mcp_pending_attach", default=None)
+
+
+def _record_attach(started: float) -> None:
+ elapsed_ms = int((time.perf_counter() - started) * 1000)
+ _pending_attach.set((_pending_attach.get() or 0) + elapsed_ms)
+
+
+def _take_attach() -> int | None:
+ pending = _pending_attach.get()
+ _pending_attach.set(None)
+ return pending
+
+
+def drop_pending_attach() -> None:
+ """Called at MCP tool dispatch so an attach whose tool never opened a Timer cannot reach the next call."""
+ _pending_attach.set(None)
+
+
+def restore_pending_attach(attach_ms: int | None) -> None:
+ """Hand an attach a finished Timer already claimed to the next Timer of the same tool call."""
+ if attach_ms:
+ _pending_attach.set((_pending_attach.get() or 0) + attach_ms)
+
+
+def count_browser_attach(fn: Callable[_P, Awaitable[_R]]) -> Callable[_P, Awaitable[_R]]:
+ """Report the browser attach a tool does before opening its Timer as that tool's own attach mark."""
+
+ @functools.wraps(fn)
+ async def counted(*args: _P.args, **kwargs: _P.kwargs) -> _R:
+ started = time.perf_counter()
+ try:
+ return await fn(*args, **kwargs)
+ finally:
+ _record_attach(started)
+
+ return counted
+
+
class Timer:
def __init__(self) -> None:
self._start: float = 0
+ self._attach_ms: int | None = None
self._marks: dict[str, int] = {}
def __enter__(self) -> Timer:
self._start = time.perf_counter()
+ self._attach_ms = _take_attach()
return self
def __exit__(self, *args: Any) -> None:
- self._marks["total"] = int((time.perf_counter() - self._start) * 1000)
+ elapsed_ms = int((time.perf_counter() - self._start) * 1000)
+ if self._attach_ms is not None:
+ self._marks["attach"] = self._attach_ms
+ self._marks["total"] = elapsed_ms
+ _pending_attach.set(None)
def mark(self, name: str) -> None:
self._marks[name] = int((time.perf_counter() - self._start) * 1000)
diff --git a/skyvern/cli/core/session_manager.py b/skyvern/cli/core/session_manager.py
index 5dd67cea7..9d245e70c 100644
--- a/skyvern/cli/core/session_manager.py
+++ b/skyvern/cli/core/session_manager.py
@@ -23,7 +23,7 @@ from skyvern.webeye.browser_errors import is_context_lost_message, is_target_clo
from .api_key_hash import hash_api_key_for_cache
from .client import get_active_api_key, get_skyvern, has_api_key_override
-from .result import BrowserContext, ErrorCode, make_error
+from .result import BrowserContext, ErrorCode, count_browser_attach, make_error
from .trajectory_store import delete_session_trajectories
LOG = structlog.get_logger(__name__)
@@ -547,6 +547,7 @@ def _extension_browser_is_connected(browser: SkyvernBrowser) -> bool:
return False
+@count_browser_attach
async def resolve_browser(
session_id: str | None = None,
cdp_url: str | None = None,
diff --git a/skyvern/cli/mcp_tools/_common.py b/skyvern/cli/mcp_tools/_common.py
index 28368af3c..b87c289af 100644
--- a/skyvern/cli/mcp_tools/_common.py
+++ b/skyvern/cli/mcp_tools/_common.py
@@ -5,7 +5,15 @@ from __future__ import annotations
from typing import Any
from skyvern.cli.core.artifacts import get_artifact_dir, save_artifact
-from skyvern.cli.core.result import Artifact, BrowserContext, ErrorCode, Timer, make_error, make_result
+from skyvern.cli.core.result import (
+ Artifact,
+ BrowserContext,
+ ErrorCode,
+ Timer,
+ make_error,
+ make_result,
+ restore_pending_attach,
+)
from skyvern.client.errors import NotFoundError
DIRECT_TARGET_DESCRIPTION = "Direct target: deterministic, 0 LLM calls."
@@ -105,6 +113,7 @@ __all__ = [
"raw_http_delete",
"raw_http_get",
"raw_http_post",
+ "restore_pending_attach",
"raw_http_put",
"save_artifact",
]
diff --git a/skyvern/cli/mcp_tools/browser.py b/skyvern/cli/mcp_tools/browser.py
index b35b30a7d..bfd101f4f 100644
--- a/skyvern/cli/mcp_tools/browser.py
+++ b/skyvern/cli/mcp_tools/browser.py
@@ -86,6 +86,7 @@ from ._common import (
Timer,
make_error,
make_result,
+ restore_pending_attach,
save_artifact,
)
from ._element_state import (
@@ -323,7 +324,9 @@ def _coordinate_target(x: float | None, y: float | None, selector: str | None) -
def _add_timing_prefix(timing_ms: dict[str, int], elapsed_ms: int) -> dict[str, int]:
- return {name: elapsed_ms + duration for name, duration in timing_ms.items()}
+ # Every mark but "attach" is an offset from the timer's start; "attach" is a duration that ran
+ # before it, so shifting it would inflate what the attach itself cost.
+ return {name: duration if name == "attach" else elapsed_ms + duration for name, duration in timing_ms.items()}
def _truncate_error_message(message: str) -> str:
@@ -1895,6 +1898,7 @@ async def skyvern_select_option(
},
timing_ms=custom_timer.timing_ms,
)
+ restore_pending_attach(custom_timer.timing_ms.get("attach"))
with Timer() as timer:
try:
diff --git a/skyvern/cli/mcp_tools/session.py b/skyvern/cli/mcp_tools/session.py
index 2ceae8cdc..0b08b97a5 100644
--- a/skyvern/cli/mcp_tools/session.py
+++ b/skyvern/cli/mcp_tools/session.py
@@ -5,6 +5,7 @@ from typing import Annotated, Any
from pydantic import Field
+from skyvern.browser_extension.errors import BrowserExtensionBrokerError
from skyvern.browser_extension.runtime import BrowserExtensionRuntime, broker_mode_enabled
from skyvern.cli.core.action_log import drain_action_log_events
from skyvern.cli.core.api_key_hash import hash_api_key_for_cache
@@ -59,6 +60,28 @@ def _broker_extension_not_connected_guidance(*, pairing_opened: bool) -> str:
)
+def _broker_extension_not_connected_hint() -> str:
+ return (
+ "Verify that Chrome is running and the Skyvern Agent extension is enabled. "
+ "The extension checks for the broker every 30 seconds."
+ )
+
+
+def _browser_extension_start_hint(error: Exception) -> str:
+ if isinstance(error, BrowserExtensionBrokerError):
+ if error.code in {"INVALID_READINESS", "STARTUP_TIMEOUT"}:
+ return (
+ "Inspect ~/.skyvern/run/browser-extension/<port>/startup.log, stop any stale Skyvern MCP "
+ "process, and retry."
+ )
+ if error.code == "PORT_IN_USE":
+ return (
+ "Stop the process using the configured localhost port, or set SKYVERN_BROWSER_EXTENSION_PORT "
+ "to a free port and use the same port in the Skyvern Agent popup."
+ )
+ return "Failed to start or connect to the Skyvern browser extension"
+
+
def _session_api_key_hash() -> str | None:
api_key = get_active_api_key()
if not api_key:
@@ -189,7 +212,7 @@ async def skyvern_browser_session_create(
error=make_error(
ErrorCode.BROWSER_NOT_FOUND,
guidance,
- "",
+ _broker_extension_not_connected_hint() if broker_mode else "",
),
)
except Exception as e:
@@ -200,7 +223,7 @@ async def skyvern_browser_session_create(
error=make_error(
ErrorCode.SDK_ERROR,
str(e),
- "Failed to start or connect to the Skyvern browser extension",
+ _browser_extension_start_hint(e),
),
)
@@ -220,7 +243,7 @@ async def skyvern_browser_session_create(
error=make_error(
ErrorCode.BROWSER_NOT_FOUND,
guidance,
- "",
+ _broker_extension_not_connected_hint() if broker_mode else "",
),
)
return make_result(
diff --git a/skyvern/cli/mcp_tools/telemetry.py b/skyvern/cli/mcp_tools/telemetry.py
index d6277d393..49a4325e2 100644
--- a/skyvern/cli/mcp_tools/telemetry.py
+++ b/skyvern/cli/mcp_tools/telemetry.py
@@ -13,6 +13,7 @@ from fastmcp.server.middleware import CallNext, Middleware, MiddlewareContext
from skyvern import analytics
from skyvern.cli.core.perception_telemetry import MCPPerceptionCounters, perception_counters_scope
+from skyvern.cli.core.result import drop_pending_attach
from skyvern.forge.sdk.forge_log import current_codeblock_log_redactor
LOG = structlog.get_logger(__name__)
@@ -257,6 +258,7 @@ class MCPTelemetryMiddleware(Middleware):
) -> Any:
tool_name = getattr(context.message, "name", None)
start = time.perf_counter()
+ drop_pending_attach()
with perception_counters_scope() as counters:
try:
result = await call_next(context)
diff --git a/skyvern/cli/run_commands.py b/skyvern/cli/run_commands.py
index 96d26d34b..266601ad5 100644
--- a/skyvern/cli/run_commands.py
+++ b/skyvern/cli/run_commands.py
@@ -359,6 +359,7 @@ def run_server() -> None:
factory=True,
# uvloop can double-close a recycled fd after create_connection cancellation (MagicStack/uvloop#740).
loop="asyncio",
+ timeout_keep_alive=settings.UVICORN_TIMEOUT_KEEP_ALIVE,
ws="websockets-sansio",
# Let cdp_input emit its 120s setup-time close before Uvicorn's liveness timeout.
ws_ping_interval=20.0,
diff --git a/skyvern/config.py b/skyvern/config.py
index c25de57a2..15a1bf6aa 100644
--- a/skyvern/config.py
+++ b/skyvern/config.py
@@ -272,6 +272,14 @@ class Settings(BaseSettings):
SELF_HEAL_MAX_ACTIONS: int = 15
SELF_HEAL_WALL_CLOCK_BUDGET_SECONDS: int = 300
PORT: int = 8000
+ # uvicorn answers 503 without dispatching to ASGI once *either* open connections or in-flight
+ # requests reach this. Open connections is the binding term -- idle keep-alives and long-lived
+ # /stream sockets all count -- so size it against connections per task, not request concurrency.
+ # Set it empty or 0 to disable shedding.
+ API_LIMIT_CONCURRENCY: int | None = Field(default=512, gt=0)
+ # Must exceed the load balancer's idle timeout (infra/terraform/production/alb.tf); otherwise
+ # the ALB reuses a connection the server already closed and answers the client with a 502.
+ UVICORN_TIMEOUT_KEEP_ALIVE: int = 125
ALLOWED_ORIGINS: list[str] = ["*"]
ALLOWED_ORIGIN_REGEX: str | None = None
BLOCKED_HOSTS: list[str] = ["localhost"]
@@ -922,6 +930,14 @@ class Settings(BaseSettings):
return self
+ @field_validator("API_LIMIT_CONCURRENCY", mode="before")
+ @classmethod
+ def _api_limit_concurrency_unlimited_sentinels(cls, value: Any) -> Any:
+ # gt=0 otherwise leaves the unlimited setting unreachable from the environment.
+ if value is None or str(value).strip().lower() in ("", "0", "none", "null"):
+ return None
+ return value
+
@field_validator("WORKER_STALL_DUMP_SECONDS", mode="before")
@classmethod
def _worker_stall_dump_seconds_or_default(cls, value: Any) -> int:
diff --git a/skyvern/core/script_generations/real_skyvern_page_ai.py b/skyvern/core/script_generations/real_skyvern_page_ai.py
index c6052c6b2..f002b57bf 100644
--- a/skyvern/core/script_generations/real_skyvern_page_ai.py
+++ b/skyvern/core/script_generations/real_skyvern_page_ai.py
@@ -127,7 +127,7 @@ def _render_template_with_label(template: str, label: str | None = None) -> str:
if isinstance(current_value, dict):
block_reference_data.update(current_value)
else:
- LOG.warning(
+ LOG.debug(
f"Script service: Parameter {label} has a registered reference value, going to overwrite it by block metadata"
)
@@ -277,9 +277,12 @@ class RealSkyvernPageAi(SkyvernPageAi):
task_id = context.task_id if context else None
task = await app.DATABASE.tasks.get_task(task_id, organization_id) if task_id and organization_id else None
if organization_id and task and step:
- actions = parse_actions(
- task, step.step_id, step.order, self.scraped_page, json_response.get("actions", [])
- )
+ actions = parse_actions(task, step.step_id, step.order, self.scraped_page, actions_json)
+ if not actions:
+ raise SkyvernActionFailed(
+ f"AI returned no usable click action for intention: {intention}. "
+ "The proposed action could not be parsed."
+ )
action = cast(ClickAction, actions[0])
# Run the registered click setup (e.g. the selected-state guard) the
@@ -544,6 +547,10 @@ class RealSkyvernPageAi(SkyvernPageAi):
else:
if is_unresolved_totp_value(transformed_value):
raise NoTOTPSecretFound()
+ if not selector:
+ raise SkyvernActionFailed(
+ "Input text failed: no selector was provided and no intention was given to locate the element"
+ )
locator = self.page.locator(selector)
await handler_utils.input_sequentially(locator, transformed_value, timeout=timeout)
return value
diff --git a/skyvern/forge/__main__.py b/skyvern/forge/__main__.py
index aa5d3c909..6016ebe91 100644
--- a/skyvern/forge/__main__.py
+++ b/skyvern/forge/__main__.py
@@ -85,11 +85,16 @@ if __name__ == "__main__":
# Omit log_level= so uvicorn.Config.configure_logging() doesn't reset setup_logger()'s uvicorn.error WARNING.
access_log=False,
log_config={"version": 1, "disable_existing_loggers": False},
+ # The event loop is single-threaded, so an unbounded queue degrades every request in it,
+ # including the load balancer's health check. uvicorn's shed is path-blind, so this has to
+ # stay above real per-task connection counts or it costs the heartbeat it is protecting.
+ limit_concurrency=settings.API_LIMIT_CONCURRENCY,
# uvloop can double-close a recycled fd after create_connection cancellation (MagicStack/uvloop#740).
loop="asyncio",
reload=reload,
reload_excludes=reload_excludes,
factory=True,
+ timeout_keep_alive=settings.UVICORN_TIMEOUT_KEEP_ALIVE,
ws="websockets-sansio",
# Let cdp_input emit its 120s setup-time close before Uvicorn's liveness timeout.
ws_ping_interval=20.0,
diff --git a/skyvern/forge/agent.py b/skyvern/forge/agent.py
index 363fa079f..2ea4c8d04 100644
--- a/skyvern/forge/agent.py
+++ b/skyvern/forge/agent.py
@@ -12,7 +12,7 @@ from asyncio.exceptions import CancelledError
from dataclasses import dataclass
from datetime import UTC, datetime
from pathlib import Path
-from typing import Any, Literal, Tuple, cast
+from typing import Any, Iterable, Literal, Tuple, cast
import structlog
from openai.types.responses.response import Response as OpenAIResponse
@@ -139,6 +139,8 @@ from skyvern.forge.sdk.schemas.files import FileInfo
from skyvern.forge.sdk.schemas.organizations import Organization
from skyvern.forge.sdk.schemas.tasks import Task, TaskRequest, TaskResponse, TaskStatus
from skyvern.forge.sdk.schemas.totp_codes import OTPType
+from skyvern.forge.sdk.services.bitwarden import BitwardenConstants
+from skyvern.forge.sdk.services.credentials import AzureVaultConstants, OnePasswordConstants, parse_totp_config
from skyvern.forge.sdk.submission import shadow as submission_shadow
from skyvern.forge.sdk.trace import VerificationTrigger, apply_context_attrs, traced, traced_span
from skyvern.forge.sdk.workflow.context_manager import WorkflowRunContext
@@ -161,7 +163,12 @@ from skyvern.schemas.steps import AgentStepOutput
from skyvern.services import run_service, service_utils
from skyvern.services.action_service import get_action_history
from skyvern.services.error_detection_service import detect_user_defined_errors_for_task
-from skyvern.services.otp_service import describe_webhook_contract_failure, poll_otp_value, resolve_otp_value
+from skyvern.services.otp_service import (
+ describe_webhook_contract_failure,
+ extract_totp_from_navigation_inputs,
+ poll_otp_value,
+ resolve_otp_value,
+)
from skyvern.services.webhook_delivery import (
WEBHOOK_DELIVERY_MAX_ATTEMPTS,
deliver_webhook_with_retries,
@@ -423,6 +430,81 @@ def _classify_reasoning_kind(reasoning: str | None) -> str:
return "literal" if any(s in text for s in _LITERAL_REASONING_SIGNALS) else "semantic"
+def _has_multi_field_totp_shape(observations: Iterable[tuple[str, Any]]) -> bool:
+ """True when ``observations`` BEGIN with 4+ consecutive single-digit INPUT_TEXT actions.
+
+ ``observations`` are normalized ``(action_type, text)`` pairs. The run must start at action-list
+ index 0: the multi-field execution path (``_handle_multi_field_totp_sequence``) generates and
+ caches the TOTP only for the digit whose absolute ``action_index == 0`` and expects that cache to
+ already exist for every later digit. A leading non-TOTP action pushes the first digit to index 1,
+ so the handler never seeds the cache and every digit fails with a cache miss. Requiring the
+ single-digit run to begin at index 0 keeps this shared shape check aligned with that runtime
+ invariant. Actions after the run (e.g. a model-requested submit click) are irrelevant and may
+ remain. Shared behind both the raw-dict first-plan predicate and the parsed-Action detector.
+ """
+ single_digit_run = 0
+ for action_type, text in observations:
+ if action_type == ActionType.INPUT_TEXT.value and isinstance(text, str) and len(text) == 1 and text.isdigit():
+ single_digit_run += 1
+ if single_digit_run >= 4:
+ return True
+ else:
+ return False
+ return False
+
+
+def _first_plan_carries_consumable_totp(actions: list[Any], multi_field_secret_ready: bool) -> bool:
+ """Whether the first-pass plan already carries a shape the existing runtime materializes into a
+ credential TOTP at DOM-write time: a multi-field single-digit sequence backed by a runtime secret
+ stash. A literal digit string, a bare placeholder, a provider marker, or a
+ ``get_verification_code`` action is not runtime-consumable on this v1 two-pass seam, so it keeps
+ the polling re-plan.
+
+ The multi-field arm is only consumable when the runtime already holds the code the multi-field
+ execution path types per digit — the existing ``totp_codes[f"{task_id}_secret"]`` stash. Without
+ it the runtime cannot materialize the digits, so ``multi_field_secret_ready`` gates that arm.
+ """
+ if not multi_field_secret_ready:
+ return False
+ observations = (
+ (str(action.get("action_type") or "").lower(), action.get("text")) if isinstance(action, dict) else ("", None)
+ for action in actions
+ )
+ return _has_multi_field_totp_shape(observations)
+
+
+def _first_plan_carries_single_field_credential_totp(
+ actions: list[Any], workflow_run_context: WorkflowRunContext | None, active_credential_parameter_key: str | None
+) -> bool:
+ """Recognize the single-field credential placeholder consumed by the input handler at runtime."""
+ if not workflow_run_context or not actions:
+ return False
+ if any(not isinstance(action, dict) for action in actions):
+ return False
+ if str(actions[0].get("action_type") or "").upper() != ActionType.INPUT_TEXT.value.upper():
+ return False
+ if any(
+ str(action.get("action_type") or "").upper() == ActionType.INPUT_TEXT.value.upper() for action in actions[1:]
+ ):
+ return False
+ text = actions[0].get("text")
+ if not isinstance(text, str) or text not in workflow_run_context.secrets:
+ return False
+ key = workflow_run_context.find_credential_parameter_key_for_secret(text)
+ if not key or workflow_run_context.values.get(key, {}).get("totp") != text:
+ return False
+ if active_credential_parameter_key is not None and active_credential_parameter_key != key:
+ return False
+ resolved = workflow_run_context.get_original_secret_value_or_none(text)
+ if resolved not in {BitwardenConstants.TOTP, OnePasswordConstants.TOTP, AzureVaultConstants.TOTP}:
+ return False
+ secret_key = workflow_run_context.totp_secret_value_key(text)
+ if secret_key not in workflow_run_context.secrets:
+ return False
+ secret = workflow_run_context.get_original_secret_value_or_none(secret_key)
+ return bool(secret and parse_totp_config(secret))
+
+
def record_validation_span_attrs(span: Any, task: Task, actions: list[Action]) -> None:
"""Attach ``validation.decision`` and ``validation.reasoning_kind`` to
``span`` when ``task`` is a ``TaskType.validation`` step whose first parsed
@@ -1106,6 +1188,7 @@ class ForgeAgent:
run_task_v3_agent_loop,
taskv3_runaway_backstops,
)
+ from skyvern.forge.taskv3.loop import DEFAULT_MAX_SETTLE_DEFERRALS
# Workflow-block tasks re-resolve the live working page on every tool call, so a click that
# opens a new tab/popup is followed (mirrors the step engine's get_working_page re-fetch).
@@ -1121,12 +1204,23 @@ class ForgeAgent:
# loss is contained by the loop's per-tool-call error handling.
return await browser_state.must_get_working_page()
+ async def _fingerprint_page() -> Any:
+ # get (not must_get): recovery at finish time could navigate and induce duplicate
+ # actions, so a lost page yields None and the verdict is accepted as-is.
+ return await browser_state.get_working_page()
+
else:
initial_page = await browser_state.must_get_working_page()
async def _page_provider() -> Any:
return initial_page
+ async def _fingerprint_page() -> Any:
+ # The fingerprint MUST sample the page the tools act on. Bare tasks pin one page for
+ # the run, and browser_state.get_working_page() would both return the newest tab
+ # (wrong page after any popup) and repoint the working page as a side effect.
+ return None if initial_page.is_closed() else initial_page
+
llm_caller = LLMCaller(llm_key=await _resolve_task_v3_llm_key(task))
parameters = coerce_v3_parameters(task.navigation_payload)
context = skyvern_context.current()
@@ -1365,25 +1459,23 @@ class ForgeAgent:
if len(login_credential_keys) == 1:
credential_parameter_key = login_credential_keys[0]
- _page_fingerprint = None
- if task_block is not None:
- # One cheap DOM sample per call: a content hash plus length and element count, so a swap
- # that preserves the page's shape still changes the fingerprint. Peeks with the
- # NON-recovering accessor — recovery at finish time could navigate and induce duplicate
- # actions; a lost page returns None (nothing to verify; accept the verdict as-is).
- # Errors propagate: the finish gate treats them as unknown, never as settled. Timing and
- # its deadline/cancellation bounds live with the gate, not here.
- # Fenced to block tasks so the live bare-task arm's finish path is unchanged.
- async def _page_fingerprint() -> str | None:
- peek = await browser_state.get_working_page()
- if peek is None:
- return None
- probe_js = (
- "() => { if (!document.body) return '0'; const s = document.body.innerHTML;"
- " let h = 0; for (let i = 0; i < s.length; i++) h = (Math.imul(h, 31) + s.charCodeAt(i)) | 0;"
- " return h + ':' + s.length + ':' + document.querySelectorAll('*').length; }"
- )
- return await peek.evaluate(probe_js)
+ # One cheap DOM sample per call: a content hash plus length and element count, so a swap
+ # that preserves the page's shape still changes the fingerprint. A lost page returns None
+ # (nothing to verify; accept the verdict as-is). Errors propagate: the finish gate treats
+ # them as unknown, never as settled. Timing and its deadline/cancellation bounds live with
+ # the gate, not here. Built for both populations — the failure-evidence gate needs a sampler
+ # to run at all — over the same page accessor each population's tools use, so the evidence
+ # is sampled from the page the model actually acted on.
+ async def _page_fingerprint() -> str | None:
+ peek = await _fingerprint_page()
+ if peek is None:
+ return None
+ probe_js = (
+ "() => { if (!document.body) return '0'; const s = document.body.innerHTML;"
+ " let h = 0; for (let i = 0; i < s.length; i++) h = (Math.imul(h, 31) + s.charCodeAt(i)) | 0;"
+ " return h + ':' + s.length + ':' + document.querySelectorAll('*').length; }"
+ )
+ return await peek.evaluate(probe_js)
resolve_typed_text = None
if task_block is not None:
@@ -1416,6 +1508,10 @@ class ForgeAgent:
resolve_typed_text=resolve_typed_text,
page_free=page_free_validation,
page_fingerprint=_page_fingerprint,
+ # The 2026-08-18 scoping decision kept the completed-side settle probe off the
+ # bare-task arm. Fenced by its own deferral budget so it does not also disable
+ # the failure-evidence gate that shares the sampler (SKY-14598).
+ max_settle_deferrals=DEFAULT_MAX_SETTLE_DEFERRALS if task_block is not None else 0,
llm_caller=llm_caller,
goal=goal,
parameters=parameters,
@@ -3352,6 +3448,14 @@ class ForgeAgent:
engine: RunEngine = RunEngine.openai_cua,
) -> tuple[list[Action], OpenAIResponse | None]:
cua_model = app.OPENAI_CUA_MODEL
+ # The CUA tool must declare the browser's real viewport so returned coordinates land in the
+ # page's own space. The live viewport can be smaller than the settings default, so read it
+ # from the scraped page rather than assuming BROWSER_WIDTH/HEIGHT.
+ cua_window_dimension = (
+ cast(Resolution, scraped_page.window_dimension)
+ if scraped_page.window_dimension
+ else Resolution(width=settings.BROWSER_WIDTH, height=settings.BROWSER_HEIGHT)
+ )
if not previous_response:
# this is the first step
first_response: OpenAIResponse = await app.OPENAI_CLIENT.responses.create(
@@ -3359,8 +3463,8 @@ class ForgeAgent:
tools=[
{
"type": "computer_use_preview",
- "display_width": settings.BROWSER_WIDTH,
- "display_height": settings.BROWSER_HEIGHT,
+ "display_width": cua_window_dimension["width"],
+ "display_height": cua_window_dimension["height"],
"environment": "browser",
}
],
@@ -3449,8 +3553,8 @@ class ForgeAgent:
tools=[
{
"type": "computer_use_preview",
- "display_width": settings.BROWSER_WIDTH,
- "display_height": settings.BROWSER_HEIGHT,
+ "display_width": cua_window_dimension["width"],
+ "display_height": cua_window_dimension["height"],
"environment": "browser",
}
],
@@ -3490,8 +3594,8 @@ class ForgeAgent:
tools=[
{
"type": "computer_use_preview",
- "display_width": settings.BROWSER_WIDTH,
- "display_height": settings.BROWSER_HEIGHT,
+ "display_width": cua_window_dimension["width"],
+ "display_height": cua_window_dimension["height"],
"environment": "browser",
}
],
@@ -3554,6 +3658,9 @@ class ForgeAgent:
if uses_new_computer_tool:
type = "computer_20251124"
betas = ["computer-use-2025-11-24"]
+ # These are placeholder dimensions: LLMCaller.call rewrites display_*_px to the screenshot
+ # resize target derived from the live window_dimension (passed below) before the request, so
+ # a dynamic viewport is already reflected there. Do not special-case it here.
tools = [
{
"type": type,
@@ -5579,39 +5686,17 @@ class ForgeAgent:
Returns:
bool: True if this is a multi-field TOTP sequence
"""
- # Must have at least 4 actions (minimum for TOTP)
- if len(actions) < 4:
- return False
-
- # Check if we have multiple consecutive single-digit INPUT_TEXT actions
- consecutive_single_digits = 0
- max_consecutive = 0
-
- for action in actions:
- if (
- action.action_type == ActionType.INPUT_TEXT
- and hasattr(action, "text")
- and action.text
- and len(action.text) == 1
- and action.text.isdigit()
- ):
- consecutive_single_digits += 1
- max_consecutive = max(max_consecutive, consecutive_single_digits)
- else:
- # If we hit a non-single-digit action, reset consecutive counter
- consecutive_single_digits = 0
-
- # Consider it a multi-field TOTP if we have 4+ consecutive single-digit inputs
- # This is more reliable than just counting total single digits
- # We use 4+ as the threshold to avoid false positives with single TOTP fields
- is_multi_field_totp = max_consecutive >= 4
+ observations = (
+ (
+ action.action_type.value if isinstance(action.action_type, ActionType) else "",
+ getattr(action, "text", None),
+ )
+ for action in actions
+ )
+ is_multi_field_totp = _has_multi_field_totp_shape(observations)
if is_multi_field_totp:
- LOG.debug(
- "Detected multi-field TOTP sequence",
- max_consecutive=max_consecutive,
- total_actions=len(actions),
- )
+ LOG.debug("Detected multi-field TOTP sequence", total_actions=len(actions))
return is_multi_field_totp
@@ -5838,7 +5923,7 @@ class ForgeAgent:
artifact_type=ArtifactType.SCREENSHOT_FINAL,
data=screenshot,
)
- except TargetClosedError:
+ except (TargetClosedError, ScreenshotTargetClosed):
LOG.warning(
"Failed to take screenshot before sending task response, page is closed",
)
@@ -7606,6 +7691,45 @@ class ForgeAgent:
):
return json_response, []
+ # The first plan may already carry a runtime-consumable multi-field TOTP shape backed by the
+ # runtime secret stash. In that case the existing per-digit execution path resolves it, so the
+ # polling verification re-plan is redundant and would discard the first plan. Magic-link
+ # verification and payload OTP both outrank it and are resolved on their own paths, so the skip
+ # never runs ahead of them.
+ runtime_context = skyvern_context.current()
+ workflow_run_id = getattr(task, "workflow_run_id", None)
+ workflow_run_context = None
+ if workflow_run_id and app.WORKFLOW_CONTEXT_MANAGER.has_workflow_run_context(workflow_run_id):
+ workflow_run_context = app.WORKFLOW_CONTEXT_MANAGER.get_workflow_run_context(workflow_run_id)
+ multi_field_secret_ready = bool(runtime_context and runtime_context.totp_codes.get(f"{task.task_id}_secret"))
+ first_plan_actions = json_response.get("actions")
+ if (
+ should_resolve_verification_code
+ and not should_verify_by_magic_link
+ and isinstance(first_plan_actions, list)
+ and _first_plan_carries_consumable_totp(first_plan_actions, multi_field_secret_ready)
+ and extract_totp_from_navigation_inputs(task.navigation_payload) is None
+ ):
+ LOG.info(
+ "Keeping first-pass credential TOTP plan; skipping verification re-plan",
+ task_id=task.task_id,
+ )
+ return json_response, []
+
+ if (
+ should_resolve_verification_code
+ and not should_verify_by_magic_link
+ and isinstance(first_plan_actions, list)
+ and _first_plan_carries_single_field_credential_totp(
+ first_plan_actions,
+ workflow_run_context,
+ getattr(runtime_context, "active_credential_parameter_key", None),
+ )
+ and extract_totp_from_navigation_inputs(task.navigation_payload) is None
+ ):
+ LOG.info("Keeping first-pass single-field credential TOTP plan", task_id=task.task_id)
+ return json_response, []
+
if should_resolve_verification_code:
json_response = await self.handle_potential_verification_code(
task, step, scraped_page, browser_state, json_response
diff --git a/skyvern/forge/api_app.py b/skyvern/forge/api_app.py
index 8d93ef7de..765166819 100644
--- a/skyvern/forge/api_app.py
+++ b/skyvern/forge/api_app.py
@@ -15,7 +15,6 @@ from pydantic import ValidationError
from skyvern.exceptions import require_server_extra_modules
require_server_extra_modules("skyvern.forge.api_app", ("fastapi", "starlette", "starlette_context"))
-
from fastapi import FastAPI, Response, status
from fastapi.exception_handlers import request_validation_exception_handler
from fastapi.exceptions import RequestValidationError
@@ -23,6 +22,8 @@ from fastapi.middleware.cors import CORSMiddleware
from fastapi.openapi.utils import get_openapi
from fastapi.responses import JSONResponse
from fastapi.routing import APIRoute
+from sqlalchemy import inspect, text
+from sqlalchemy.engine import Connection
from starlette.datastructures import MutableHeaders
from starlette.requests import ClientDisconnect, HTTPConnection, Request
from starlette.types import ASGIApp, Message, Receive, Scope, Send
@@ -228,6 +229,18 @@ def register_agent_route_aliases(fastapi_app: FastAPI) -> None:
route.include_in_schema = False
+def _upgrade_sqlite_organization_slug(connection: Connection) -> None:
+ """Add the organization slug column and index to an existing local SQLite database."""
+ inspector = inspect(connection)
+ if "organizations" not in inspector.get_table_names():
+ return
+ if "slug" not in {column["name"] for column in inspector.get_columns("organizations")}:
+ connection.execute(text("ALTER TABLE organizations ADD COLUMN slug VARCHAR"))
+ connection.execute(
+ text("CREATE UNIQUE INDEX IF NOT EXISTS uq_organizations_slug ON organizations (slug) WHERE slug IS NOT NULL")
+ )
+
+
async def _bootstrap_sqlite() -> None:
"""Auto-bootstrap SQLite on first server start.
@@ -240,6 +253,7 @@ async def _bootstrap_sqlite() -> None:
db = forge_app.DATABASE
async with db.engine.begin() as conn:
await conn.run_sync(Base.metadata.create_all)
+ await conn.run_sync(_upgrade_sqlite_organization_slug)
# Preserve an existing API key if it's a real value (not the skeleton default).
# settings.SKYVERN_API_KEY already incorporates env vars and .env via pydantic-settings.
diff --git a/skyvern/forge/log_redaction.py b/skyvern/forge/log_redaction.py
index a6c42b92b..0b5fde68b 100644
--- a/skyvern/forge/log_redaction.py
+++ b/skyvern/forge/log_redaction.py
@@ -25,7 +25,14 @@ REDACTED = "****"
# Request headers dropped wholesale from request logs. proxy-authorization and
# set-cookie carry credentials too and are classified as such by other modules.
-SENSITIVE_HEADERS = {"authorization", "proxy-authorization", "cookie", "set-cookie", "x-api-key"}
+SENSITIVE_HEADERS = {
+ "authorization",
+ "proxy-authorization",
+ "cookie",
+ "set-cookie",
+ "x-api-key",
+ "x-posthog-attribution",
+}
# Exact field names that are always redacted. Use a set for O(1) lookup
# instead of regex substring matching to avoid false positives like
diff --git a/skyvern/forge/prompts/skyvern/workflow-copilot-agent.j2 b/skyvern/forge/prompts/skyvern/workflow-copilot-agent.j2
index af8c7d293..0092854da 100644
--- a/skyvern/forge/prompts/skyvern/workflow-copilot-agent.j2
+++ b/skyvern/forge/prompts/skyvern/workflow-copilot-agent.j2
@@ -50,8 +50,6 @@ TOOL USAGE INSTRUCTIONS:
You have tools available in this run. Use them to build better workflows:
{{ tool_usage_guide }}
-IMPORTANT: NEVER call the same tool more than twice in a row. If a tool succeeded, move on to the NEXT step — do not repeat the same call. Each tool call should advance your progress toward the goal.
-
ASK-vs-EDIT ROUTING:
Use one decision tree for the latest turn. If the latest turn OR prior context establishes a build/edit goal and the needed target, condition, value, or action is resolvable from `chat_history`, current `workflow_yaml`, `global_llm_context`, or debugger run information, edit the workflow and call `update_and_run_blocks` once the correction is clear. This includes diagnostic symptom follow-ups on the same workflow after an explicit edit goal. Use `ASK_QUESTION` only when a required target, condition, value, or action is still missing after checking all context, when a diagnostic complaint has no prior edit goal, or when mismatched/anonymized block references cannot be resolved by explicit position, semantic role, or a unique candidate. Explicit user positions win literally; when a reference could be ordinal or semantic, match existing labels and `block_type` first, then fall back to ordinal.
Before answering a runtime symptom with workflow-knowledge-base prose, verify any named workflow entity (block label, workflow parameter key, or {% raw %}`{{ name.output... }}`{% endraw %} Jinja reference) is present in the current workflow YAML or latest debugger run information. The current workflow is the source of truth. If the named entity is absent but chat history contains a plausible pending build/edit, create or correct the real workflow blocks and call `update_and_run_blocks`; if the pending build/edit still lacks a required input, respond with `ASK_QUESTION` naming both the absent entity and missing requirement. Only use docs-inline when no pending workflow build/edit remains.
@@ -93,15 +91,8 @@ Use the Skyvern MCP browser tools to gather ground-truth evidence in ANY phase o
- When you already have a verified prefix or a live browser page that advanced beyond the workflow's entrypoint, continue from that evidence. Do not turn the observed current page into a new workflow entrypoint and rerun the whole workflow from the start. Preserve unchanged upstream labels and text, and pass `block_labels` for only the missing downstream frontier.
CRITICAL RULES WHEN USING DIRECT BROWSER TOOLS:
-- If you call navigate_browser, you MUST call at least one observation tool (evaluate, get_browser_screenshot, click, type_text, scroll, select_option, press_key, or console_messages) before responding.
- NEVER answer questions about page content, link counts, link targets, or page structure from memory or training data. Use evaluate or get_browser_screenshot.
-- Use evaluate for reading/inspection; do NOT use evaluate to click or type. Use click and type_text for interactions.
- Prefer locator reads in persisted `code` blocks: `page.locator(...)`, `page.get_by_role(...)`, and methods such as `inner_text`, `text_content`, `get_attribute`, `count`, `is_visible`. Locators auto-wait; `page.evaluate` does not, so a raw evaluate that worked while you were looking at the page can run too early on replay. `page.evaluate` is permitted when you are replaying an expression you already proved on this page and no locator read expresses it; `page.evaluate_handle`, `page.request`, and `page.context` remain unavailable. Address the content you are reading: when the value you need is text on the page, target the element that carries it — `get_by_text`, `get_by_role`, or a selector you verified on this page — rather than reading the whole document and scanning the result. You saw the rendered page while scouting, so you can name that text. Reading `body`/`html`/`:root` is a last resort: it makes the block depend on unrelated page copy, and the readiness wait that precedes it then has no real precondition to encode.
-- CSS SELECTORS: interactions target elements by CSS selector, which is instant and deterministic. The selectors reported by page inspection are verified to match exactly one element, so prefer copying one of those over composing your own. When a shared class matches many elements (e.g. one Add-to-Cart per result row), scope the selector to the specific item (its container, a unique attribute, or `:nth-of-type`). If a selector does not resolve or the action fails, observe the page again — with `evaluate`, `inspect_page_for_composition`, or `get_browser_screenshot`, whichever answers the question — and derive a better selector. jQuery pseudo-selectors (:contains(), :eq(), :first, :visible, :has()) are NOT valid — use standard selectors like 'button.classname', 'a[href*="keyword"]', '#id', 'tr:nth-of-type(2) td a'.
-- SCROLL: Use scroll to reveal content below the fold. Provide direction (up/down/left/right) and optionally amount in pixels, a selector for the scrollable container, or an intent to scroll a specific element into view.
-- SELECT_OPTION: Use select_option for <select> dropdowns. Provide the value and a selector to target the element. For free-text inputs, use type_text instead.
-- PRESS_KEY: Use press_key for keyboard actions — Enter to submit forms, Tab to advance focus, Escape to close dialogs. Optionally provide a selector to focus an element first.
-- CONSOLE_MESSAGES: Use console_messages(level='error') to check for JavaScript errors when diagnosing page issues. This is read-only.
- A FAILED SCOUT CLICK IS NOT A DEAD END: "element is hidden, disabled, or intercepted by another element" usually means an overlay/modal (cookie banner, marketing popup) is covering it — and the click itself often dismisses that overlay. Do NOT abandon the route, navigate away, or redesign the workflow because one scout click failed: re-inspect the current page and retry the same target; the overlay or transient state has typically cleared. (Retrying a click that did NOT act is fine — that is distinct from replaying an earlier add/submit that already succeeded, which would duplicate its effect; see the next rule.)
- A FAILED ACTION MAY HAVE LANDED: if a click/type/submit reports failure but could have changed the page (a navigation, a cart/count change, a new modal), inspect the current page before retrying. Re-firing a non-idempotent action (add to cart, submit) can duplicate its effect — confirm whether it already happened, then decide.
- AFTER A PAGE-CHANGING ACTION: wait for the new state to settle before reading it; if a read fails transiently because the page navigated mid-read, re-observe once rather than restarting the flow.
@@ -184,8 +175,9 @@ IMPORTANT WORKFLOW RULES:
- "goto_url" for direct URL navigation grounded in user-provided or observed same-site URLs.
* Use `goto_url` for direct URL navigation and for URL patterns grounded in user-provided values or observed same-site evidence. Do NOT invent website-specific paths or query parameters from memory. Put follow-up UI actions in subsequent normal workflow blocks.
* When revising after a run, do not replace a discovered/user-requested entrypoint with the browser's current results URL just because it worked once. Current URLs often contain server/session state; preserve the reusable path and use current-page evidence to improve downstream blocks.
-* Commit a draft workflow as soon as you have observed every page its blocks act on — not as soon as a reusable block sequence merely looks plausible. Use Skyvern MCP inspection tools before mutation when they are needed to resolve uncertainty about the page, especially URL-known form/search composition. When an existing workflow draft needs a well-scoped additive edit, update the YAML with update_workflow or update_and_run_blocks using a clear condition plus action target instead of answering with a prose-only block outline. Do not ask for confirmation when the workflow can be updated and tested.
-* Scout each page you will act on with the fast browser tools before you author the blocks that act on it. Drive the live browser through the goal path (navigate_browser, click, type_text, scroll, select_option, press_key) and call `inspect_page_for_composition` on every page you will act on — including pages reached only by clicking and pages behind a login — BEFORE authoring those blocks. `inspect_page_for_composition(target_url=...)` navigates to that URL itself and reports the reached `current_url`, so once you have inspected a URL you are already on it — do NOT then call `navigate_browser` to a URL you just inspected. A control or state that appears only after an interaction (a Delete control after an Add click, a cart after add-to-cart, the secure area after login) must be observed live by performing that interaction first; do not assume the post-interaction page from the page before it. Block-runs validate a finished workflow — they do not discover an unknown route, so do not run blocks just to see what a page looks like; for a login wall, author and run the `login` block (referencing a saved credential by id), then resume scouting from the authenticated page.
+* Commit a draft workflow as soon as each block is grounded in an observation of the page that block acts on — not as soon as a reusable block sequence merely looks plausible. Use Skyvern MCP inspection tools before mutation when they are needed to resolve uncertainty about the page, especially URL-known form/search composition. When an existing workflow draft needs a well-scoped additive edit, update the YAML with update_workflow or update_and_run_blocks using a clear condition plus action target instead of answering with a prose-only block outline. Do not ask for confirmation when the workflow can be updated and tested.
+* Ground each page-dependent block in run evidence or live observation of the page it acts on. A completed run may provide the route to the next page; do not assume facts about a page that has not yet been reached.
+* Minimize user-visible wait. When direct browser observation and a workflow run can answer the same current uncertainty, use direct observation. Use a workflow run when testing persisted behavior or when execution is required to reach the next state. A completed run is valid evidence for the page it reached.
* Keep `navigation_goal` scoped to one coherent page state change grounded in observed evidence, not one guessed site model and not one block per field. Do not pre-author row/detail expansion from the user's words alone: first run or inspect your way to the actual results page, then use live result-page evidence to decide whether expansion controls exist. If requested details are already visible or no explicit expansion affordance is observed, skip the expansion block and go straight to an `extraction` block. The final stage of visible results -> extract should still use an `extraction` block for data capture, not another `navigation` block. Prefer the most specific block that fits the step — use a more specific block (`action` for a single action, `login` for authentication, `file_download` for downloads, `extraction` for data) over `navigation`, and reach for `navigation` only when the step is best expressed as a goal for the agent to work out rather than a specific named action (see CHOOSING A BLOCK in the knowledge base).
* When extracting table-like or list-like records (locations, affiliations, prices, inventory, line items, statuses), iterate the actual row/item elements (`tr`, `[role="row"]`, or equivalent repeated item containers) and read fields from that same row/item. Do NOT scan broad containers such as `section`, `.card`, `article`, or `li` and then infer fields from mixed text; that can combine several rows into one record. Derive summary fields only from the parsed row objects, not from broad page text.
* When a successful search/open-details block reaches a details or profile page, include the visible details/profile page label in the block's returned `evidence_text`. Keep structured record fields focused on the requested data; use the page label only as supporting evidence.
diff --git a/skyvern/forge/request_logging.py b/skyvern/forge/request_logging.py
index ea644dce3..c2b9d1c69 100644
--- a/skyvern/forge/request_logging.py
+++ b/skyvern/forge/request_logging.py
@@ -5,6 +5,7 @@ import re
import time
import typing
from contextvars import ContextVar
+from dataclasses import dataclass
from functools import partial
import structlog
@@ -45,6 +46,9 @@ _SENSITIVE_ENDPOINTS = {
_SENSITIVE_ENDPOINT_PATTERNS = (re.compile(r"^(?:POST|PUT) /(?:api/)?v1/credentials(?:/.*)?$"),)
_MAX_BODY_LENGTH = 1000
_READ_METHODS = frozenset({"GET", "HEAD", "OPTIONS"})
+# 404/405 are dominated by internet scanners and MCP clients probing GET for an SSE stream;
+# there is nothing to act on, so they stay out of the warn tier.
+_ROUTINE_CLIENT_ERROR_STATUSES = frozenset({404, 405})
_MAX_RESPONSE_READ_BYTES = 1024 * 1024 # 1 MB — skip logging bodies larger than this
_BINARY_PLACEHOLDER = "<binary>"
_LOGGABLE_CONTENT_TYPES = {"text/", "application/json"}
@@ -58,6 +62,43 @@ _raw_request_stream_success_logger: ContextVar[typing.Callable[[int, str], None]
)
+@dataclass
+class _RequestIdentity:
+ organization_id: str | None = None
+ organization_name: str | None = None
+
+
+_request_identity: ContextVar[_RequestIdentity | None] = ContextVar("raw_request_identity", default=None)
+
+
+def set_request_organization(organization_id: str | None, organization_name: str | None = None) -> None:
+ """Attribute the in-flight ``api.raw_request`` record to the authenticated organization.
+
+ Auth resolves in a child task of this middleware, and a ContextVar rebound there never
+ reaches the middleware that emits the record. Mutating the holder bound before
+ ``call_next`` does, because the child inherits the same object.
+ """
+ identity = _request_identity.get()
+ if identity is None:
+ return
+ if organization_id:
+ identity.organization_id = organization_id
+ if organization_name:
+ identity.organization_name = organization_name
+
+
+def _organization_log_fields() -> dict[str, str]:
+ identity = _request_identity.get()
+ if identity is None:
+ return {}
+ fields: dict[str, str] = {}
+ if identity.organization_id:
+ fields["organization_id"] = identity.organization_id
+ if identity.organization_name:
+ fields["organization_name"] = identity.organization_name
+ return fields
+
+
def _sanitize_headers(headers: typing.Mapping[str, str]) -> dict[str, str]:
sanitized: dict[str, str] = {}
for key, value in headers.items():
@@ -175,6 +216,7 @@ def _log_unhandled_request(
headers=headers,
exc_info=True,
duration_seconds=time.monotonic() - start_time,
+ **_organization_log_fields(),
)
except Exception:
pass
@@ -193,7 +235,7 @@ def _log_request(
) -> None:
if status_code >= 500:
log_method = LOG.error
- elif status_code >= 400:
+ elif status_code >= 400 and status_code not in _ROUTINE_CLIENT_ERROR_STATUSES:
log_method = LOG.warning
else:
log_method = LOG.info
@@ -211,6 +253,7 @@ def _log_request(
# backwards-compat: keep error_body for existing Datadog queries
error_body=response_body if status_code >= 400 else None,
duration_seconds=time.monotonic() - start_time,
+ **_organization_log_fields(),
)
except Exception:
pass
@@ -229,6 +272,7 @@ async def log_raw_request_middleware(request: Request, call_next: Callable[[Requ
return await call_next(request)
start_time = time.monotonic()
+ _request_identity.set(_RequestIdentity())
try:
body_bytes = await request.body()
except ClientDisconnect:
diff --git a/skyvern/forge/sdk/copilot/agent.py b/skyvern/forge/sdk/copilot/agent.py
index 9dd39e26a..177f0bddb 100644
--- a/skyvern/forge/sdk/copilot/agent.py
+++ b/skyvern/forge/sdk/copilot/agent.py
@@ -151,6 +151,7 @@ from skyvern.forge.sdk.copilot.runtime import (
BrowserProbeOutcome,
_browser_context_attachability,
)
+from skyvern.forge.sdk.copilot.runtime_authoring_repair import OBSTRUCTION_SUMMARY_MAX_CHARS
from skyvern.forge.sdk.copilot.secret_redaction import redact_raw_secrets_for_structured_prompt
from skyvern.forge.sdk.copilot.secret_scrub import registered_scrub_values
from skyvern.forge.sdk.copilot.streaming_adapter import (
@@ -680,8 +681,8 @@ def _clean_authoring_repair_prompt_atom(value: str, *, max_chars: int = 160) ->
return cleaned[:max_chars]
-def _render_authoring_repair_prompt_list(items: list[str], *, max_items: int = 20) -> str:
- cleaned = [_clean_authoring_repair_prompt_atom(item) for item in items[:max_items]]
+def _render_authoring_repair_prompt_list(items: list[str], *, max_items: int = 20, max_chars: int = 160) -> str:
+ cleaned = [_clean_authoring_repair_prompt_atom(item, max_chars=max_chars) for item in items[:max_items]]
return ", ".join(item for item in cleaned if item) or "(none)"
@@ -848,6 +849,11 @@ def _code_authoring_repair_context_prompt(ctx: CopilotContext | None) -> str:
lines.append(
f"page_challenges: {_render_authoring_repair_prompt_list(repair_context.page_challenge_summaries)}"
)
+ if repair_context.page_obstruction_summaries:
+ rendered_obstructions = _render_authoring_repair_prompt_list(
+ repair_context.page_obstruction_summaries, max_chars=OBSTRUCTION_SUMMARY_MAX_CHARS
+ )
+ lines.append(f"page_obstructions: {rendered_obstructions}")
if repair_context.reason_code == "metadata_reject":
if repair_context.runtime_failure_reason:
lines.append(
@@ -1719,6 +1725,7 @@ def _build_narrative_payload(
else:
block_type = str(block_type_value or "task")
raw_status = ctx.block_state_map.get(label)
+ run_identity = ctx.block_run_identity_map.get(label)
block_entry: NarrativeBlock = {
"label": label,
"blockType": block_type,
@@ -1726,11 +1733,13 @@ def _build_narrative_payload(
raw_status,
drafted_fallback=ctx.has_staged_proposal,
),
- "lastSeenIteration": 0,
+ "lastSeenIteration": run_identity.iteration if run_identity is not None else 0,
"activity": list(block_activity.get(label, [])),
"startedAt": ctx.block_started_at_map.get(label),
"endedAt": ctx.block_ended_at_map.get(label),
}
+ if run_identity is not None:
+ block_entry["workflowRunBlockId"] = run_identity.workflow_run_block_id
if recorded_outcome is not None and label in outcome_labels:
block_entry["outcome"] = recorded_outcome.verdict
block_entry["outcomeRole"] = recorded_outcome.role
diff --git a/skyvern/forge/sdk/copilot/blocker_signal.py b/skyvern/forge/sdk/copilot/blocker_signal.py
index fc063ef00..b64b88eaa 100644
--- a/skyvern/forge/sdk/copilot/blocker_signal.py
+++ b/skyvern/forge/sdk/copilot/blocker_signal.py
@@ -6,13 +6,16 @@ import re
from collections.abc import Mapping
from dataclasses import dataclass
from types import MappingProxyType
-from typing import Any, Literal, Protocol
+from typing import TYPE_CHECKING, Any, Literal, Protocol
import structlog
from pydantic import BaseModel, ConfigDict, Field, field_serializer, model_validator
from skyvern.forge.sdk.copilot.run_outcome import TERMINAL_CHALLENGE_BLOCKER_REASON_CODES
+if TYPE_CHECKING:
+ from skyvern.forge.sdk.copilot.context import BlockRunIdentity
+
BlockerKind = Literal[
"authority_denied",
"tool_error",
@@ -199,6 +202,7 @@ class _ActiveRunEvidenceResetCtx(Protocol):
block_state_map: dict[str, str]
block_started_at_map: dict[str, str]
block_ended_at_map: dict[str, str]
+ block_run_identity_map: dict[str, BlockRunIdentity]
def terminal_evidence_from_ctx(ctx: _TerminalEvidenceCtx) -> TerminalEvidence:
@@ -238,6 +242,7 @@ def clear_active_run_evidence_on_workflow_edit(ctx: _ActiveRunEvidenceResetCtx)
ctx.block_state_map = {}
ctx.block_started_at_map = {}
ctx.block_ended_at_map = {}
+ ctx.block_run_identity_map = {}
SCHEMA_INCOMPATIBILITY_REASON_CODE = "schema_incompatibility"
diff --git a/skyvern/forge/sdk/copilot/composition_browser_expressions.py b/skyvern/forge/sdk/copilot/composition_browser_expressions.py
index 39fb07fde..f3dd75bf5 100644
--- a/skyvern/forge/sdk/copilot/composition_browser_expressions.py
+++ b/skyvern/forge/sdk/copilot/composition_browser_expressions.py
@@ -174,6 +174,29 @@ def selector_match_count_expression(css_selector: str) -> str:
return f"(() => {{ try {{ return document.querySelectorAll({sel}).length; }} catch (e) {{ return -1; }}}})()"
+_JS_SELECTOR_CANDIDATES_HELPER = (
+ "const collectCandidates = (el, requested) => {"
+ " const esc = (v) => window.CSS && CSS.escape ? CSS.escape(String(v)) : String(v);"
+ " const attr = (n, k) => n && n.getAttribute ? String(n.getAttribute(k) || '') : '';"
+ " const tag = (el.tagName || '*').toLowerCase();"
+ " const candidates = [];"
+ " const add = (selector, source) => {"
+ " if (!selector || candidates.some((item) => item.selector === selector)) return;"
+ " let matches = []; try { matches = Array.from(document.querySelectorAll(selector)); } catch (e) { return; }"
+ " if (matches.includes(el)) candidates.push({selector: selector, source: source});"
+ " };"
+ " add(requested, 'requested');"
+ " const id = attr(el, 'id'); if (id) add('#' + esc(id), 'id');"
+ " const name = attr(el, 'name'); if (name) add(tag + '[name=\"' + name.replaceAll('\\\\', '\\\\\\\\').replaceAll('\"', '\\\"') + '\"]', 'name');"
+ " const aria = attr(el, 'aria-label'); if (aria) add(tag + '[aria-label=\"' + aria.replaceAll('\\\\', '\\\\\\\\').replaceAll('\"', '\\\"') + '\"]', 'aria_label');"
+ " const type = attr(el, 'type'); if (type) add(tag + '[type=\"' + type.replaceAll('\\\\', '\\\\\\\\').replaceAll('\"', '\\\"') + '\"]', 'type');"
+ " const classes = Array.from(el.classList || []).filter(Boolean);"
+ " if (classes.length) add(tag + classes.map((value) => '.' + esc(value)).join(''), 'class_list');"
+ " return candidates;"
+ "};"
+)
+
+
def selector_candidates_expression(css_selector: str) -> str:
"""Return every bounded CSS identity observed for the selected source-page element.
@@ -186,23 +209,64 @@ def selector_candidates_expression(css_selector: str) -> str:
f" const requested = {sel};"
" let el = null; try { el = document.querySelector(requested); } catch (e) { return []; }"
" if (!el) return [];"
- " const esc = (v) => window.CSS && CSS.escape ? CSS.escape(String(v)) : String(v);"
- " const attr = (n, k) => n && n.getAttribute ? String(n.getAttribute(k) || '') : '';"
- " const tag = (el.tagName || '*').toLowerCase();"
- " const candidates = [];"
- " const add = (selector, source) => {"
- " if (!selector || candidates.some((item) => item.selector === selector)) return;"
- " let matches = []; try { matches = Array.from(document.querySelectorAll(selector)); } catch (e) { return; }"
- " if (matches.includes(el)) candidates.push({selector: selector, source: source});"
+ f" {_JS_SELECTOR_CANDIDATES_HELPER}"
+ " return collectCandidates(el, requested);"
+ "})()"
+ )
+
+
+# Each fact is computed in its own try so a failing sub-read leaves the others populated. Supplying
+# role/name skips the element read, which is what lets a role-engine selector — not valid CSS — count.
+def scout_pre_action_expression(css_selector: str, role: str | None = None, name: str | None = None) -> str:
+ sel = json.dumps(css_selector)
+ parsed_role = json.dumps(role or "")
+ parsed_name = json.dumps(name or "")
+ return (
+ "(() => {"
+ f" {_JS_TEXT_HELPER}"
+ f" {_JS_IS_EDITABLE_HELPER}"
+ f" {_JS_IMPLICIT_ROLE_HELPER}"
+ f" {_JS_NAME_FROM_CONTENT_ROLES}"
+ f" {_JS_ACCESSIBLE_NAME_HELPER}"
+ f" {_JS_SELECTOR_CANDIDATES_HELPER}"
+ f" const requested = {sel};"
+ f" const parsedRole = {parsed_role};"
+ f" const parsedName = {parsed_name};"
+ " let el = null;"
+ " try { el = document.querySelector(requested); } catch (e) { el = null; }"
+ " let roleName = null;"
+ " if (parsedRole || parsedName) roleName = { role: parsedRole, accessible_name: parsedName };"
+ " else if (el) {"
+ " try {"
+ " const r = text(el.getAttribute('role')) || implicitRole(el);"
+ " const n = accessibleName(el, r);"
+ " if (r || n) roleName = { role: r, accessible_name: n };"
+ " } catch (e) { roleName = null; }"
+ " }"
+ " const targetRole = roleName ? roleName.role : '';"
+ " const targetName = roleName ? roleName.accessible_name : '';"
+ " let roleNameMatchCount = -1;"
+ " if (targetRole && targetName) {"
+ " try {"
+ " let count = 0;"
+ " for (const node of document.querySelectorAll('*')) {"
+ " const r = text(node.getAttribute('role')) || implicitRole(node);"
+ " if (r !== targetRole) continue;"
+ " if (accessibleName(node, r) === targetName) count++;"
+ " }"
+ " roleNameMatchCount = count;"
+ " } catch (e) { roleNameMatchCount = -1; }"
+ " }"
+ " let selectorMatchCount = -1;"
+ " try { selectorMatchCount = document.querySelectorAll(requested).length; } catch (e) { selectorMatchCount = -1; }"
+ " let candidates = [];"
+ " try { candidates = el ? collectCandidates(el, requested) : []; } catch (e) { candidates = []; }"
+ " return {"
+ " role_name: roleName,"
+ " role_name_match_count: roleNameMatchCount,"
+ " selector_match_count: selectorMatchCount,"
+ " selector_candidates: candidates,"
" };"
- " add(requested, 'requested');"
- " const id = attr(el, 'id'); if (id) add('#' + esc(id), 'id');"
- " const name = attr(el, 'name'); if (name) add(tag + '[name=\"' + name.replaceAll('\\\\', '\\\\\\\\').replaceAll('\"', '\\\"') + '\"]', 'name');"
- " const aria = attr(el, 'aria-label'); if (aria) add(tag + '[aria-label=\"' + aria.replaceAll('\\\\', '\\\\\\\\').replaceAll('\"', '\\\"') + '\"]', 'aria_label');"
- " const type = attr(el, 'type'); if (type) add(tag + '[type=\"' + type.replaceAll('\\\\', '\\\\\\\\').replaceAll('\"', '\\\"') + '\"]', 'type');"
- " const classes = Array.from(el.classList || []).filter(Boolean);"
- " if (classes.length) add(tag + classes.map((value) => '.' + esc(value)).join(''), 'class_list');"
- " return candidates;"
"})()"
)
diff --git a/skyvern/forge/sdk/copilot/context.py b/skyvern/forge/sdk/copilot/context.py
index 268fc5374..e2c28ad5e 100644
--- a/skyvern/forge/sdk/copilot/context.py
+++ b/skyvern/forge/sdk/copilot/context.py
@@ -8,7 +8,7 @@ import re
import uuid
from collections.abc import Mapping, Sequence
from dataclasses import dataclass, field
-from typing import TYPE_CHECKING, Any, Literal, get_args
+from typing import TYPE_CHECKING, Any, Literal, NamedTuple, get_args
import structlog
from pydantic import AliasChoices, BaseModel, ConfigDict, Field, field_validator
@@ -68,10 +68,14 @@ class NarrativeActivityEntry(TypedDict):
displayLabel: NotRequired[str]
success: NotRequired[bool]
id: str
+ # Server clock read for the event this entry describes, shared with the SSE
+ # update so a rehydrated row renders the same elapsed the live row did.
+ timestamp: NotRequired[str]
class NarrativeBlock(TypedDict):
label: str
+ workflowRunBlockId: NotRequired[str]
blockType: str
state: str
lastSeenIteration: int
@@ -83,6 +87,11 @@ class NarrativeBlock(TypedDict):
outcomeRole: NotRequired[RunOutcomeRole]
+class BlockRunIdentity(NamedTuple):
+ workflow_run_block_id: str
+ iteration: int
+
+
class NarrativeConnectedAccountChoice(TypedDict):
connection_id: str
name: str
@@ -223,6 +232,7 @@ class CodeAuthoringRepairContext(BaseModel):
page_result_summaries: list[str] = Field(default_factory=list)
page_action_summaries: list[str] = Field(default_factory=list)
page_challenge_summaries: list[str] = Field(default_factory=list)
+ page_obstruction_summaries: list[str] = Field(default_factory=list)
required_block_structure: str = ""
spine_stage_count: int | None = None
spine_split_blockers: list[str] = Field(default_factory=list)
@@ -859,6 +869,9 @@ class CopilotContext(AgentContext):
block_state_map: dict[str, str] = field(default_factory=dict)
block_started_at_map: dict[str, str] = field(default_factory=dict)
block_ended_at_map: dict[str, str] = field(default_factory=dict)
+ # Keyed by label, so a label that ran more than once in a turn keeps only its
+ # last run's identity.
+ block_run_identity_map: dict[str, BlockRunIdentity] = field(default_factory=dict)
turn_started_at: str | None = None
turn_ended_at: str | None = None
diff --git a/skyvern/forge/sdk/copilot/diagnosis_repair_contract.py b/skyvern/forge/sdk/copilot/diagnosis_repair_contract.py
index 0b631404b..98a750f6c 100644
--- a/skyvern/forge/sdk/copilot/diagnosis_repair_contract.py
+++ b/skyvern/forge/sdk/copilot/diagnosis_repair_contract.py
@@ -334,6 +334,7 @@ def _repair_context_root_cause_identity(
payload["page_result_summaries"] = _safe_identity_list(repair_context.page_result_summaries)
payload["page_action_summaries"] = _safe_identity_list(repair_context.page_action_summaries)
payload["page_challenge_summaries"] = _safe_identity_list(repair_context.page_challenge_summaries)
+ payload["page_obstruction_summaries"] = _safe_identity_list(repair_context.page_obstruction_summaries)
elif reason_code == "runtime_missing_output_dependency":
payload["missing_output_key"] = _safe_text(repair_context.missing_output_key, 120)
payload["available_output_keys"] = _safe_identity_list(repair_context.available_output_keys)
diff --git a/skyvern/forge/sdk/copilot/mcp_adapter.py b/skyvern/forge/sdk/copilot/mcp_adapter.py
index ddae6687a..05f92a0b4 100644
--- a/skyvern/forge/sdk/copilot/mcp_adapter.py
+++ b/skyvern/forge/sdk/copilot/mcp_adapter.py
@@ -55,6 +55,7 @@ from skyvern.forge.sdk.copilot.runtime import (
from skyvern.forge.sdk.copilot.screenshot_utils import enqueue_screenshot_from_result
from skyvern.forge.sdk.copilot.secret_scrub import scrub_secrets_from_structure
from skyvern.forge.sdk.copilot.turn_origin import TurnOrigin
+from skyvern.utils.contained_effects import contained_effect
from skyvern.webeye.browser_state import BrowserState
if TYPE_CHECKING:
@@ -115,6 +116,9 @@ class SchemaOverlay:
"""Schema overlay for MCP tools — hides params, renames args, injects forced values."""
description: str | None = None
+ # Appended to the tool's own description instead of replacing it, for a fact the copilot
+ # owns (a policy-dependent restriction) on a tool whose documentation it does not own.
+ description_suffix: str | None = None
hide_params: frozenset[str] = frozenset()
required_overrides: list[str] | None = None
arg_transforms: dict[str, str] = field(default_factory=dict)
@@ -321,32 +325,106 @@ def _scrub_tool_exception(ctx: AgentContext, tool_name: str, exception: BaseExce
return _scrub_tool_result(ctx, {"ok": False, "error": error})
-def _elapsed_ms(started: float) -> int:
- return int((time.monotonic() - started) * 1000)
+_MCPCallPhase = Literal["session_prepare", "context_enter", "dispatch", "evidence_drain", "context_exit"]
+# The segments charged to the wall clock. ``evidence_drain`` names where a call died but is never
+# charged here, so the residual stays the remainder of what the record actually reports.
+_MCP_CALL_SEGMENTS: tuple[_MCPCallPhase, ...] = ("session_prepare", "context_enter", "dispatch", "context_exit")
+
+
+class _PhaseClock:
+ """Segments one MCP call's wall clock. Per-segment flooring keeps the residual non-negative."""
+
+ def __init__(self) -> None:
+ self._started = time.monotonic()
+ self._mark = self._started
+ self._bucket: _MCPCallPhase | None = None
+ self._wall: int | None = None
+ self.current: _MCPCallPhase | None = None
+ self.elapsed: dict[_MCPCallPhase, int] = {}
+ self.drain_ms: int | None = None
+
+ def _charge(self, now: float) -> None:
+ if self._bucket is not None:
+ self.elapsed[self._bucket] = self.elapsed.get(self._bucket, 0) + int((now - self._mark) * 1000)
+ self._mark = now
+
+ def enter(self, phase: _MCPCallPhase) -> None:
+ self._charge(time.monotonic())
+ self._bucket = phase
+ self.current = phase
+
+ def unwind(self) -> None:
+ """Charge the teardown to ``context_exit`` while ``current`` keeps naming the segment that failed."""
+ self._charge(time.monotonic())
+ self._bucket = "context_exit"
+
+ def close(self) -> int:
+ if self._wall is None:
+ now = time.monotonic()
+ self._charge(now)
+ self._bucket = None
+ self._wall = int((now - self._started) * 1000)
+ return self._wall
+
+ def record_drain(self, started: float, *, failed: bool) -> None:
+ """Settling the page runs after the wall is frozen: the caller waits for it, but it is not part of the call."""
+ self.drain_ms = int((time.monotonic() - started) * 1000)
+ if failed:
+ self.current = "evidence_drain"
+
+ def settle(self) -> None:
+ """The call answered, so no segment holds a failure and ``timing_phase`` would misname a returned error."""
+ self.current = None
+
+
+def _server_mark(raw_mcp: dict[str, Any], name: str) -> int | None:
+ timing = raw_mcp.get("timing_ms")
+ value = timing.get(name) if isinstance(timing, dict) else None
+ return value if isinstance(value, int) and not isinstance(value, bool) else None
def _log_mcp_timing(
ctx: CopilotContext,
tool_name: str,
mcp_tool_name: str,
- wall_clock_ms: int,
+ phases: _PhaseClock,
raw_mcp: dict[str, Any],
call_path: Literal["model", "internal"],
call_status: Literal["ok", "timeout", "error", "session_error", "cancelled", "not_connected"] = "ok",
) -> None:
- timing = raw_mcp.get("timing_ms")
- total = timing.get("total") if isinstance(timing, dict) else None
- reported = total if isinstance(total, int) and not isinstance(total, bool) else None
- LOG.info(
- "MCP tool timing",
- tool_name=tool_name,
- mcp_tool_name=mcp_tool_name,
- wall_clock_ms=wall_clock_ms,
- server_timing_ms=reported,
- call_path=call_path,
- call_status=call_status,
- **_copilot_log_fields(ctx),
- )
+ with contained_effect("emit MCP tool timing", tool_name=tool_name, call_status=call_status):
+ reported = _server_mark(raw_mcp, "total")
+ attach_ms = _server_mark(raw_mcp, "attach")
+ # The tool's total excludes the browser attach it did before opening its timer, so the span the
+ # server actually held the call is the two together.
+ server_span_ms = None if reported is None else reported + (attach_ms or 0)
+ wall_clock_ms = phases.close()
+ spent = {phase: phases.elapsed.get(phase, 0) for phase in _MCP_CALL_SEGMENTS}
+ dispatch_ms = spent["dispatch"]
+ # The server measures on its own clock, so a span outside the dispatch segment cannot be
+ # subtracted from it without inventing a component.
+ server_fits = server_span_ms is not None and 0 <= server_span_ms <= dispatch_ms
+ untimed_ms = dispatch_ms - server_span_ms if server_fits and server_span_ms is not None else None
+ LOG.info(
+ "MCP tool timing",
+ tool_name=tool_name,
+ mcp_tool_name=mcp_tool_name,
+ wall_clock_ms=wall_clock_ms,
+ server_timing_ms=server_span_ms,
+ server_attach_ms=attach_ms,
+ call_path=call_path,
+ call_status=call_status,
+ phase_session_prepare_ms=spent["session_prepare"],
+ phase_context_enter_ms=spent["context_enter"],
+ phase_dispatch_ms=dispatch_ms,
+ phase_context_exit_ms=spent["context_exit"],
+ post_call_evidence_drain_ms=phases.drain_ms,
+ phase_residual_ms=wall_clock_ms - sum(spent.values()),
+ timing_phase=phases.current if call_status != "ok" else None,
+ phase_dispatch_untimed_ms=untimed_ms,
+ timing_server_overrun=None if server_span_ms is None else not server_fits,
+ **_copilot_log_fields(ctx),
+ )
def _browser_session_loss_result(
@@ -478,35 +556,36 @@ def _emit_continuity_event(
replacement_session_id: str | None,
disposition: Literal["detected", "reestablished", "failed"],
) -> None:
- workflow_run_id = (
- ctx.sdk_action_workflow_run_ids_by_browser_session.get((ctx.organization_id, lost_session_id))
- or ctx.last_run_blocks_workflow_run_id
- )
- fields: dict[str, Any] = {
- "error_code": _SESSION_EXPIRED_ERROR_CODE,
- "session_id": lost_session_id,
- "replacement_session_id": replacement_session_id,
- "workflow_run_id": workflow_run_id,
- "tool_name": tool_name,
- "call_path": call_path,
- "continuity_source": "direct_mcp",
- "continuity_disposition": disposition,
- **_copilot_log_fields(cast("CopilotContext", ctx)),
- }
- if disposition != "detected":
- fields["reestablish_budget_seconds"] = _SESSION_REESTABLISH_TIMEOUT_SECONDS
- log = LOG.info if disposition == "reestablished" else LOG.warning
- try:
- log("copilot_browser_session_continuity_loss", **fields)
- except Exception:
+ # The payload is built inside the guard too: this emit sits ahead of the recovery
+ # call, so a failure anywhere in it -- not just in the sink -- would leave
+ # ensure_browser_session uncalled and the disposition unrecorded.
+ with contained_effect("emit copilot session continuity event", session_id=lost_session_id):
+ workflow_run_id = (
+ ctx.sdk_action_workflow_run_ids_by_browser_session.get((ctx.organization_id, lost_session_id))
+ or ctx.last_run_blocks_workflow_run_id
+ )
+ fields: dict[str, Any] = {
+ "error_code": _SESSION_EXPIRED_ERROR_CODE,
+ "session_id": lost_session_id,
+ "replacement_session_id": replacement_session_id,
+ "workflow_run_id": workflow_run_id,
+ "tool_name": tool_name,
+ "call_path": call_path,
+ "continuity_source": "direct_mcp",
+ "continuity_disposition": disposition,
+ **_copilot_log_fields(cast("CopilotContext", ctx)),
+ }
+ if disposition != "detected":
+ fields["reestablish_budget_seconds"] = _SESSION_REESTABLISH_TIMEOUT_SECONDS
+ log = LOG.info if disposition == "reestablished" else LOG.warning
try:
+ log("copilot_browser_session_continuity_loss", **fields)
+ except Exception:
_FALLBACK_LOGGER.warning(
"copilot_browser_session_continuity_loss session_id=%s disposition=%s",
lost_session_id,
disposition,
)
- except Exception:
- pass
def _apply_continuity_outcome(
@@ -554,7 +633,7 @@ async def _prepare_browser_session_for_dispatch(
prior_session_id = ctx.browser_session_id
if not prior_session_id:
- return await ensure_browser_session(ctx, require_verified_session=True), None
+ return await ensure_browser_session(ctx), None
async with _browser_session_continuity_lock(ctx.organization_id, prior_session_id):
recorded = await _get_continuity_outcome(ctx.organization_id, prior_session_id)
@@ -562,10 +641,9 @@ async def _prepare_browser_session_for_dispatch(
_apply_continuity_outcome(ctx, recorded, tool_name=tool_name, call_path=call_path)
return None, _browser_session_loss_result({}, disposition=recorded.disposition)
- error = await ensure_browser_session(ctx, require_verified_session=True)
- if error is not None and ctx.browser_session_id == prior_session_id:
- # A bounded probe that could not determine liveness is not evidence of loss.
- return error, None
+ # No preflight verdict here: the attach below is the oracle, and an indeterminate probe
+ # is not evidence of loss.
+ error = await ensure_browser_session(ctx)
if (
getattr(ctx, "turn_origin", TurnOrigin.interactive) == TurnOrigin.runtime_self_heal
or ctx.browser_session_id == prior_session_id
@@ -895,6 +973,8 @@ class SkyvernOverlayMCPServer(MCPServer):
schema = _apply_schema_overlay(tool.inputSchema, overlay)
schema = _requested_output_path_choices(schema, requested_output_path_choices)
description = overlay.description or tool.description or ""
+ if overlay.description_suffix:
+ description = f"{description} {overlay.description_suffix}".strip()
result.append(
MCPTool(
@@ -956,11 +1036,12 @@ class SkyvernOverlayMCPServer(MCPServer):
record_tool_step_result_for_ctx(copilot_ctx, tool_name, arguments, hook_result)
return _copilot_to_call_tool_result(hook_result)
- started = time.monotonic()
+ phases = _PhaseClock()
mcp_name = self._alias_map.get(tool_name, tool_name)
mcp_args = _transform_args(arguments, overlay)
if overlay.requires_browser:
+ phases.enter("session_prepare")
try:
err, continuity_result = await _prepare_browser_session_for_dispatch(
copilot_ctx,
@@ -969,18 +1050,18 @@ class SkyvernOverlayMCPServer(MCPServer):
observed_generation=observed_continuity_generation,
)
except asyncio.CancelledError:
- _log_mcp_timing(copilot_ctx, tool_name, mcp_name, _elapsed_ms(started), {}, "model", "cancelled")
+ _log_mcp_timing(copilot_ctx, tool_name, mcp_name, phases, {}, "model", "cancelled")
raise
except Exception:
- _log_mcp_timing(copilot_ctx, tool_name, mcp_name, _elapsed_ms(started), {}, "model", "session_error")
+ _log_mcp_timing(copilot_ctx, tool_name, mcp_name, phases, {}, "model", "session_error")
raise
if err:
- _log_mcp_timing(copilot_ctx, tool_name, mcp_name, _elapsed_ms(started), {}, "model", "session_error")
+ _log_mcp_timing(copilot_ctx, tool_name, mcp_name, phases, {}, "model", "session_error")
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)
if continuity_result is not None:
- _log_mcp_timing(copilot_ctx, tool_name, mcp_name, _elapsed_ms(started), {}, "model", "session_error")
+ _log_mcp_timing(copilot_ctx, tool_name, mcp_name, phases, {}, "model", "session_error")
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)
@@ -992,19 +1073,27 @@ class SkyvernOverlayMCPServer(MCPServer):
# one. The ceiling bounds every await under the call — a page evaluate, but also a stale
# session handle whose CDP request never answers, which held a turn for 307s (SKY-13226).
if overlay.requires_browser:
+ phases.enter("context_enter")
async with mcp_browser_context(copilot_ctx):
- raw_result = await asyncio.wait_for(
- self._client.call_tool(mcp_name, mcp_args, raise_on_error=False),
- timeout=overlay.timeout,
- )
+ phases.enter("dispatch")
+ try:
+ raw_result = await asyncio.wait_for(
+ self._client.call_tool(mcp_name, mcp_args, raise_on_error=False),
+ timeout=overlay.timeout,
+ )
+ except BaseException:
+ phases.unwind()
+ raise
+ phases.enter("context_exit")
else:
+ phases.enter("dispatch")
raw_result = await asyncio.wait_for(
self._client.call_tool(mcp_name, mcp_args, raise_on_error=False),
timeout=overlay.timeout,
)
except TimeoutError:
LOG.warning("MCP tool call timed out", tool=tool_name, ceiling_seconds=overlay.timeout)
- _log_mcp_timing(copilot_ctx, tool_name, mcp_name, _elapsed_ms(started), {}, "model", "timeout")
+ _log_mcp_timing(copilot_ctx, tool_name, mcp_name, phases, {}, "model", "timeout")
# The call is cancelled where it stands, so a tool that changes the page may already have
# changed it. Reporting a plain failure invites a retry that acts on the page twice.
err = {
@@ -1018,7 +1107,7 @@ class SkyvernOverlayMCPServer(MCPServer):
record_tool_step_result_for_ctx(copilot_ctx, tool_name, arguments, err)
return _copilot_to_call_tool_result(err)
except CopilotBrowserSessionUnavailable as exc:
- _log_mcp_timing(copilot_ctx, tool_name, mcp_name, _elapsed_ms(started), {}, "model", "session_error")
+ _log_mcp_timing(copilot_ctx, tool_name, mcp_name, phases, {}, "model", "session_error")
disposition = await _handle_browser_session_loss(
copilot_ctx,
tool_name=tool_name,
@@ -1032,15 +1121,14 @@ class SkyvernOverlayMCPServer(MCPServer):
record_tool_step_result_for_ctx(copilot_ctx, tool_name, arguments, err)
return _copilot_to_call_tool_result(err)
except asyncio.CancelledError:
- _log_mcp_timing(copilot_ctx, tool_name, mcp_name, _elapsed_ms(started), {}, "model", "cancelled")
+ _log_mcp_timing(copilot_ctx, tool_name, mcp_name, phases, {}, "model", "cancelled")
raise
except Exception as exc:
LOG.warning("MCP tool call failed", tool=tool_name)
- _log_mcp_timing(copilot_ctx, tool_name, mcp_name, _elapsed_ms(started), {}, "model", "error")
+ _log_mcp_timing(copilot_ctx, tool_name, mcp_name, phases, {}, "model", "error")
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)
- wall_clock_ms = _elapsed_ms(started)
# Copy fastmcp's structured_content so mutations below stay local to
# this call — the client may reuse or cache the response object.
@@ -1053,7 +1141,8 @@ class SkyvernOverlayMCPServer(MCPServer):
else:
raw_mcp["error"] = raw_mcp.get("error") or "Unknown MCP error"
failed = raw_result.is_error or raw_mcp.get("ok", True) is not True
- _log_mcp_timing(copilot_ctx, tool_name, mcp_name, wall_clock_ms, raw_mcp, "model", "error" if failed else "ok")
+ phases.settle()
+ _log_mcp_timing(copilot_ctx, tool_name, mcp_name, phases, raw_mcp, "model", "error" if failed else "ok")
# Scrub before the post hook so evidence the hooks record from raw_mcp
# (flow evidence, scout observations) is scrubbed too.
raw_mcp = _scrub_tool_result(copilot_ctx, raw_mcp)
@@ -1122,13 +1211,14 @@ class SkyvernOverlayMCPServer(MCPServer):
extracted error string rather than silently defaulting to
``ok=True``.
"""
- started = time.monotonic()
+ phases = _PhaseClock()
copilot_name = self._reverse_alias.get(mcp_tool_name, mcp_tool_name)
ctx = self._context_provider()
observed_continuity_generation = getattr(ctx, "browser_session_continuity_generation", 0)
if not self._client:
- _log_mcp_timing(ctx, copilot_name, mcp_tool_name, _elapsed_ms(started), {}, "internal", "not_connected")
+ _log_mcp_timing(ctx, copilot_name, mcp_tool_name, phases, {}, "internal", "not_connected")
return _scrub_tool_result(ctx, {"ok": False, "error": "MCP client not connected"})
+ phases.enter("session_prepare")
try:
err, continuity_result = await _prepare_browser_session_for_dispatch(
ctx,
@@ -1137,31 +1227,45 @@ class SkyvernOverlayMCPServer(MCPServer):
observed_generation=observed_continuity_generation,
)
except asyncio.CancelledError:
- _log_mcp_timing(ctx, copilot_name, mcp_tool_name, _elapsed_ms(started), {}, "internal", "cancelled")
+ _log_mcp_timing(ctx, copilot_name, mcp_tool_name, phases, {}, "internal", "cancelled")
raise
except Exception:
- _log_mcp_timing(ctx, copilot_name, mcp_tool_name, _elapsed_ms(started), {}, "internal", "session_error")
+ _log_mcp_timing(ctx, copilot_name, mcp_tool_name, phases, {}, "internal", "session_error")
raise
if err:
- _log_mcp_timing(ctx, copilot_name, mcp_tool_name, _elapsed_ms(started), {}, "internal", "session_error")
+ _log_mcp_timing(ctx, copilot_name, mcp_tool_name, phases, {}, "internal", "session_error")
return _scrub_tool_result(ctx, err)
if continuity_result is not None:
- _log_mcp_timing(ctx, copilot_name, mcp_tool_name, _elapsed_ms(started), {}, "internal", "session_error")
+ _log_mcp_timing(ctx, copilot_name, mcp_tool_name, phases, {}, "internal", "session_error")
return _scrub_tool_result(ctx, continuity_result)
merged_args = {**mcp_args, "session_id": ctx.browser_session_id}
call_browser_session_id = ctx.browser_session_id
try:
+ phases.enter("context_enter")
async with mcp_browser_context(ctx):
- raw = await self._client.call_tool(mcp_tool_name, merged_args, raise_on_error=False)
- wall_clock_ms = _elapsed_ms(started)
+ phases.enter("dispatch")
+ try:
+ raw = await self._client.call_tool(mcp_tool_name, merged_args, raise_on_error=False)
+ except BaseException:
+ phases.unwind()
+ raise
+ phases.enter("context_exit")
+ # The evidence drain runs outside the dispatch span this record covers.
+ phases.close()
if self._evidence_candidate_origin is not None:
- await asyncio.sleep(0)
- await self._drain_evidence_candidate_response_tasks()
+ drain_started = time.monotonic()
+ try:
+ await asyncio.sleep(0)
+ await self._drain_evidence_candidate_response_tasks()
+ except BaseException:
+ phases.record_drain(drain_started, failed=True)
+ raise
+ phases.record_drain(drain_started, failed=False)
except asyncio.CancelledError:
- _log_mcp_timing(ctx, copilot_name, mcp_tool_name, _elapsed_ms(started), {}, "internal", "cancelled")
+ _log_mcp_timing(ctx, copilot_name, mcp_tool_name, phases, {}, "internal", "cancelled")
raise
except CopilotBrowserSessionUnavailable as exc:
- _log_mcp_timing(ctx, copilot_name, mcp_tool_name, _elapsed_ms(started), {}, "internal", "session_error")
+ _log_mcp_timing(ctx, copilot_name, mcp_tool_name, phases, {}, "internal", "session_error")
disposition = await _handle_browser_session_loss(
ctx,
tool_name=copilot_name,
@@ -1171,7 +1275,7 @@ class SkyvernOverlayMCPServer(MCPServer):
return _scrub_tool_result(ctx, _browser_session_loss_result({}, disposition=disposition))
except Exception as exc:
LOG.warning("Internal MCP tool call failed", tool=mcp_tool_name)
- _log_mcp_timing(ctx, copilot_name, mcp_tool_name, _elapsed_ms(started), {}, "internal", "error")
+ _log_mcp_timing(ctx, copilot_name, mcp_tool_name, phases, {}, "internal", "error")
return _scrub_tool_exception(ctx, mcp_tool_name, exc)
raw_mcp = dict(raw.structured_content or {})
if raw.is_error:
@@ -1182,9 +1286,8 @@ class SkyvernOverlayMCPServer(MCPServer):
else:
raw_mcp["error"] = raw_mcp.get("error") or "Unknown MCP error"
failed = raw.is_error or raw_mcp.get("ok", True) is not True
- _log_mcp_timing(
- ctx, copilot_name, mcp_tool_name, wall_clock_ms, raw_mcp, "internal", "error" if failed else "ok"
- )
+ phases.settle()
+ _log_mcp_timing(ctx, copilot_name, mcp_tool_name, phases, raw_mcp, "internal", "error" if failed else "ok")
scrubbed = _scrub_tool_result(ctx, raw_mcp)
result = mcp_to_copilot(scrubbed) if scrubbed else {}
if (
diff --git a/skyvern/forge/sdk/copilot/narration.py b/skyvern/forge/sdk/copilot/narration.py
index 7bd885054..e5f5193c6 100644
--- a/skyvern/forge/sdk/copilot/narration.py
+++ b/skyvern/forge/sdk/copilot/narration.py
@@ -27,6 +27,7 @@ from urllib.parse import urlparse
import structlog
+from skyvern.forge.sdk.copilot.context import BlockRunIdentity
from skyvern.forge.sdk.copilot.llm_config import get_fast_copilot_handler, resolve_fast_copilot_handler
from skyvern.forge.sdk.copilot.output_utils import sanitize_block_label_for_display
from skyvern.forge.sdk.schemas.workflow_copilot import (
@@ -143,7 +144,7 @@ def tool_activity_display_label(tool_name: str, tool_input: dict[str, Any] | Non
def build_tool_call_activity(
- tool_name: str, iteration: int, tool_call_id: str, display_label: str | None = None
+ tool_name: str, iteration: int, tool_call_id: str, *, timestamp: datetime, display_label: str | None = None
) -> NarrativeActivityEntry | None:
if tool_name in ACTIVITY_TOOL_DENYLIST:
return None
@@ -155,6 +156,7 @@ def build_tool_call_activity(
"toolName": tool_name,
"displayLabel": display_label,
"id": f"tc-{tool_call_id}",
+ "timestamp": timestamp.isoformat(),
}
@@ -164,6 +166,8 @@ def build_tool_result_activity(
success: bool,
iteration: int,
tool_call_id: str,
+ *,
+ timestamp: datetime,
display_label: str | None = None,
) -> NarrativeActivityEntry | None:
if tool_name in ACTIVITY_TOOL_DENYLIST:
@@ -177,6 +181,7 @@ def build_tool_result_activity(
"displayLabel": display_label,
"success": success,
"id": f"tr-{tool_call_id}",
+ "timestamp": timestamp.isoformat(),
}
@@ -186,6 +191,7 @@ def build_narration_activity(narration: str, iteration: int, timestamp: datetime
"text": narration,
"iteration": iteration,
"id": f"n-{iteration}-{timestamp.isoformat()}",
+ "timestamp": timestamp.isoformat(),
}
@@ -920,6 +926,7 @@ async def narrator_poll_tick(
block_state_map: dict[str, str] | None = None,
block_started_at_map: dict[str, str] | None = None,
block_ended_at_map: dict[str, str] | None = None,
+ block_run_identity_map: dict[str, BlockRunIdentity] | None = None,
workflow_run_id: str | None = None,
) -> NarratorPollTickResult:
"""Per-tick narrator bookkeeping; returns updated (prior_block_ts, last_block_fetch_monotonic).
@@ -977,6 +984,11 @@ async def narrator_poll_tick(
event_ts_iso = event_ts.isoformat()
if block_state_map is not None:
block_state_map[event.block_label] = event.status
+ if block_run_identity_map is not None:
+ block_run_identity_map[event.block_label] = BlockRunIdentity(
+ workflow_run_block_id=event.block_id,
+ iteration=state.current_iteration,
+ )
if event.status == "running":
state.running_block_label = event.block_label
elif event.status in _TERMINAL_BLOCK_STATUSES and state.running_block_label == event.block_label:
diff --git a/skyvern/forge/sdk/copilot/runtime.py b/skyvern/forge/sdk/copilot/runtime.py
index 3e1df45d2..09d863d19 100644
--- a/skyvern/forge/sdk/copilot/runtime.py
+++ b/skyvern/forge/sdk/copilot/runtime.py
@@ -100,6 +100,12 @@ class BrowserProbeOutcome(StrEnum):
could_not_determine = "could_not_determine"
+@dataclass(frozen=True)
+class BrowserProbeFault:
+ error_type: str
+ timed_out: bool
+
+
def _browser_context_attachability(browser_context: object | None) -> BrowserProbeOutcome:
if browser_context is None:
return BrowserProbeOutcome.positively_unreachable
@@ -751,7 +757,9 @@ async def mcp_browser_context(ctx: AgentContext) -> AsyncIterator[None]:
if retiring:
retire_browser_session_id(ctx, browser_session_id)
raise CopilotBrowserSessionUnavailable(browser_session_id)
- raise RuntimeError("No browser context for copilot session")
+ # Distinct wording on purpose: _is_unrecoverable_browser_session_error reads this text,
+ # and an undetermined signal must not count toward aborting the turn as session loss.
+ raise RuntimeError("Browser liveness for this copilot session could not be determined")
override_token = set_api_key_override(ctx.api_key)
try:
@@ -805,7 +813,9 @@ async def mcp_browser_context(ctx: AgentContext) -> AsyncIterator[None]:
reset_api_key_override(override_token)
-async def _probe_browser_session(ctx: AgentContext, session_id: str) -> BrowserProbeOutcome:
+async def _probe_browser_session(
+ ctx: AgentContext, session_id: str
+) -> tuple[BrowserProbeOutcome, BrowserProbeFault | None]:
"""Classify by what completed, never by exception type. Reaching `positively_unreachable`
needs both a lookup that returned and a health signal that answered; either failing to
complete is undetermined, since neither is evidence about the browser."""
@@ -816,25 +826,78 @@ async def _probe_browser_session(ctx: AgentContext, session_id: str) -> BrowserP
organization_id=ctx.organization_id,
)
if state is None:
- return BrowserProbeOutcome.positively_unreachable
+ return BrowserProbeOutcome.positively_unreachable, None
attachability = _browser_context_attachability(state.browser_context)
except Exception as exc:
+ error_type = type(exc).__name__
LOG.warning(
"Browser state probe failed; liveness undetermined",
session_id=session_id,
organization_id=ctx.organization_id,
- error_type=type(exc).__name__,
+ error_type=error_type,
+ exc_info=True,
+ )
+ return BrowserProbeOutcome.could_not_determine, BrowserProbeFault(
+ error_type=error_type,
+ timed_out=isinstance(exc, TimeoutError),
+ )
+ return attachability, None
+
+
+def _unverified_browser_session_facts(fault: BrowserProbeFault | None) -> dict[str, Any]:
+ if fault is None:
+ cause = "the browser's connectivity signal never answered"
+ elif fault.timed_out:
+ cause = f"the liveness probe did not answer within {_BROWSER_PROBE_WAIT_SECONDS}s ({fault.error_type})"
+ else:
+ cause = f"the liveness probe raised {fault.error_type}"
+ return {
+ "ok": False,
+ "error": (
+ f"The browser session could not be verified: {cause}. "
+ "An indeterminate probe is not evidence the browser is dead."
+ ),
+ "probe_error_type": fault.error_type if fault is not None else None,
+ "probe_timed_out": fault is not None and fault.timed_out,
+ }
+
+
+async def _try_attach_verify_browser_session(
+ ctx: AgentContext, session_id: str
+) -> tuple[bool, BrowserProbeOutcome | None, BrowserProbeFault | None]:
+ """Complete the determination the probe could not, bounded at the probe's own deadline: this
+ re-enters the same lookup that just failed to answer."""
+ try:
+ async with asyncio.timeout(_BROWSER_PROBE_WAIT_SECONDS):
+ state = await resolve_browser_state_for_context(ctx, session_id=session_id)
+ if state is None:
+ return False, BrowserProbeOutcome.positively_unreachable, None
+ attachability = _browser_context_attachability(state.browser_context)
+ if attachability == BrowserProbeOutcome.attachable:
+ return True, None, None
+ return False, attachability, None
+ except Exception as exc:
+ error_type = type(exc).__name__
+ LOG.warning(
+ "Browser session escalation failed; liveness still undetermined",
+ session_id=session_id,
+ organization_id=ctx.organization_id,
+ error_type=error_type,
exc_info=True,
)
- return BrowserProbeOutcome.could_not_determine
- return attachability
+ return (
+ False,
+ BrowserProbeOutcome.could_not_determine,
+ BrowserProbeFault(error_type=error_type, timed_out=isinstance(exc, TimeoutError)),
+ )
async def ensure_browser_session(ctx: AgentContext, *, require_verified_session: bool = False) -> dict[str, Any] | None:
"""Create a browser session if needed. Returns None on success, error dict on failure.
Callers that hand the id onward without ever attaching cannot discover a dead session, so they
- pass require_verified_session=True to get an infrastructure error instead of an unverified id.
+ pass require_verified_session=True to have the determination completed here: the session is
+ attached, replaced, or reported unverified with the facts that prevented an answer.
Exception: the self-heal path raises HealAdoptionFailed instead of returning an
error dict, so a failed adoption aborts the turn rather than degrading to a normal
@@ -876,15 +939,19 @@ async def ensure_browser_session(ctx: AgentContext, *, require_verified_session:
if ctx.browser_session_id:
probed_session_id = ctx.browser_session_id
- outcome = await _probe_browser_session(ctx, probed_session_id)
+ outcome, fault = await _probe_browser_session(ctx, probed_session_id)
if outcome == BrowserProbeOutcome.attachable:
return None
if outcome == BrowserProbeOutcome.could_not_determine:
- # Not evidence against the session, so it survives for callers that will attach and
- # find out. A caller that never attaches gets the fault surfaced instead.
+ # A caller that never attaches gets the determination completed once here; anything
+ # short of a completed resolve leaves the session unjudged, so its id survives.
if not require_verified_session:
return None
- return {"ok": False, "error": "Could not verify the browser session; please retry"}
+ attached, attach_outcome, attach_fault = await _try_attach_verify_browser_session(ctx, probed_session_id)
+ if attached:
+ return None
+ if attach_outcome != BrowserProbeOutcome.positively_unreachable:
+ return _unverified_browser_session_facts(attach_fault or fault)
LOG.warning(
"Supplied browser_session_id is no longer attachable; auto-creating",
session_id=probed_session_id,
diff --git a/skyvern/forge/sdk/copilot/runtime_authoring_repair.py b/skyvern/forge/sdk/copilot/runtime_authoring_repair.py
index f59fd0acc..be13b1082 100644
--- a/skyvern/forge/sdk/copilot/runtime_authoring_repair.py
+++ b/skyvern/forge/sdk/copilot/runtime_authoring_repair.py
@@ -27,6 +27,11 @@ _MISSING_OUTPUT_DEPENDENCY_REASON_CODE = "runtime_missing_output_dependency"
_RUNTIME_SUMMARY_MAX_CHARS = 120
_RUNTIME_SUMMARY_MAX_ITEMS = 5
_INSPECT_PAGE_SOURCE_TOOL = "inspect_page_for_composition"
+_OBSTRUCTION_KEYS = ("kind", "selector", "text", "visual_location")
+_OBSTRUCTION_CONTROL_KEYS = ("text", "selector")
+_OBSTRUCTION_FIELD_MAX_CHARS = 160
+OBSTRUCTION_SUMMARY_MAX_CHARS = 1200
+_NO_DISMISS_CONTROL_SUMMARY = "obstruction present, no dismiss control found in page evidence"
_KEY_ERROR_RE = re.compile(r"KeyError(?:\s*:|\()\s*['\"]([^'\"]+)['\"]")
@@ -124,16 +129,21 @@ def _safe_runtime_page_url(value: Any) -> str | None:
return _bounded_runtime_text(safe_url, 160) or None
-def _runtime_summary_entry(entry: Any, keys: tuple[str, ...]) -> str:
+def _runtime_summary_entry(
+ entry: Any,
+ keys: tuple[str, ...],
+ field_max_chars: int = 60,
+ summary_max_chars: int = _RUNTIME_SUMMARY_MAX_CHARS,
+) -> str:
if not isinstance(entry, dict):
return _bounded_runtime_text(entry)
parts = [
- _bounded_runtime_text(entry.get(key), 60)
+ _bounded_runtime_text(entry.get(key), field_max_chars)
if not isinstance(entry.get(key), bool)
else ("disabled" if entry.get(key) is True else "enabled")
for key in keys
]
- return _bounded_runtime_text(" ".join(part for part in parts if part))
+ return _bounded_runtime_text(" ".join(part for part in parts if part), summary_max_chars)
def _runtime_summary_list(value: Any, keys: tuple[str, ...]) -> list[str]:
@@ -187,6 +197,73 @@ def _runtime_result_summaries(value: Any) -> list[str]:
return summaries[:_RUNTIME_SUMMARY_MAX_ITEMS]
+def _obstruction_entries(evidence: dict[str, Any]) -> list[dict[str, Any]]:
+ page_obstructions = evidence.get("page_obstructions")
+ if isinstance(page_obstructions, list):
+ entries = [entry for entry in page_obstructions if isinstance(entry, dict)]
+ if entries:
+ return entries
+ modal_overlays = evidence.get("modal_overlays")
+ if not isinstance(modal_overlays, list):
+ return []
+ return [
+ {"selector": overlay.get("selector"), "visible_controls": overlay.get("dismiss_controls")}
+ for overlay in modal_overlays
+ if isinstance(overlay, dict)
+ ]
+
+
+def _has_page_obstruction(evidence: dict[str, Any]) -> bool:
+ return bool(_obstruction_entries(evidence))
+
+
+def repair_page_evidence_is_admissible(evidence: dict[str, Any]) -> bool:
+ """A packet whose only structured content is an obstruction carries no bounded page schema, yet
+ it is the entire repair signal for a click the overlay intercepted."""
+ return has_bounded_page_schema(evidence) or _has_page_obstruction(evidence)
+
+
+def _joined_obstruction_summary(obstruction: str, control: str) -> str:
+ """The control's selector is the repair-critical tail, so the obstruction prefix absorbs the
+ whole shortfall instead of letting the shared cap clip the selector off the end."""
+ if not obstruction:
+ return control[:OBSTRUCTION_SUMMARY_MAX_CHARS]
+ budget = OBSTRUCTION_SUMMARY_MAX_CHARS - len(control) - 1
+ if budget < 0:
+ return f"{obstruction} {control}"[:OBSTRUCTION_SUMMARY_MAX_CHARS]
+ return f"{obstruction[:budget]} {control}".strip()
+
+
+def _runtime_obstruction_summaries(evidence: Any) -> list[str]:
+ if not isinstance(evidence, dict):
+ return []
+ summaries: list[str] = []
+ for entry in _obstruction_entries(evidence)[:_RUNTIME_SUMMARY_MAX_ITEMS]:
+ obstruction = _runtime_summary_entry(
+ entry, _OBSTRUCTION_KEYS, _OBSTRUCTION_FIELD_MAX_CHARS, OBSTRUCTION_SUMMARY_MAX_CHARS
+ )
+ visible_controls = entry.get("visible_controls")
+ controls = (
+ [control for control in visible_controls if isinstance(control, dict)]
+ if isinstance(visible_controls, list)
+ else []
+ )
+ control_summaries = [
+ summary
+ for summary in (
+ _runtime_summary_entry(
+ control, _OBSTRUCTION_CONTROL_KEYS, _OBSTRUCTION_FIELD_MAX_CHARS, OBSTRUCTION_SUMMARY_MAX_CHARS
+ )
+ for control in controls
+ )
+ if summary
+ ]
+ summaries.append(
+ _joined_obstruction_summary(obstruction, "; ".join(control_summaries) or _NO_DISMISS_CONTROL_SUMMARY)
+ )
+ return summaries
+
+
def post_run_inspection_cleanly_matches(evidence: Any, run_id: Any) -> bool:
return (
isinstance(evidence, dict)
@@ -195,7 +272,7 @@ def post_run_inspection_cleanly_matches(evidence: Any, run_id: Any) -> bool:
and isinstance(run_id, str)
and bool(run_id)
and evidence.get("workflow_run_id") == run_id
- and has_bounded_page_schema(evidence)
+ and repair_page_evidence_is_admissible(evidence)
)
@@ -375,7 +452,7 @@ def _matching_bounded_post_run_inspection(
if not isinstance(run_id, str) or run_id != pending.workflow_run_id:
clear_runtime_authoring_repair_context(copilot_ctx)
return None
- if not has_bounded_page_schema(evidence):
+ if not repair_page_evidence_is_admissible(evidence):
clear_runtime_authoring_repair_context(copilot_ctx)
return None
if _post_run_terminal_page_evidence(evidence):
@@ -408,6 +485,7 @@ def finalize_runtime_authoring_repair_context_from_page_observation(
page_challenge_summaries = _runtime_summary_list(
evidence.get("challenge_controls"), ("text", "selector", "disabled")
)
+ page_obstruction_summaries = _runtime_obstruction_summaries(evidence)
finalized = pending.model_copy(
update={
"current_origin": _origin_from_runtime_url(current_url),
@@ -415,12 +493,17 @@ def finalize_runtime_authoring_repair_context_from_page_observation(
"current_title": _bounded_runtime_text(page_title, 160) or None,
"page_evidence_source": _bounded_runtime_text(evidence.get("source_tool"), 80) or None,
"observed_after_workflow_run": bool(
- page_form_summaries or page_result_summaries or page_action_summaries or page_challenge_summaries
+ page_form_summaries
+ or page_result_summaries
+ or page_action_summaries
+ or page_challenge_summaries
+ or page_obstruction_summaries
),
"page_form_summaries": page_form_summaries,
"page_result_summaries": page_result_summaries,
"page_action_summaries": page_action_summaries,
"page_challenge_summaries": page_challenge_summaries,
+ "page_obstruction_summaries": page_obstruction_summaries,
}
)
copilot_ctx.last_code_authoring_repair_context = finalized
@@ -456,5 +539,6 @@ def inject_runtime_authoring_repair_context(copilot_ctx: Any, result: dict[str,
page_form_summary_count=len(repair_context.page_form_summaries),
page_result_summary_count=len(repair_context.page_result_summaries),
page_action_summary_count=len(repair_context.page_action_summaries),
+ page_obstruction_summary_count=len(repair_context.page_obstruction_summaries),
)
data["authoring_repair_context"] = repair_context.model_dump(mode="json")
diff --git a/skyvern/forge/sdk/copilot/streaming_adapter.py b/skyvern/forge/sdk/copilot/streaming_adapter.py
index 98d515e7e..b08775996 100644
--- a/skyvern/forge/sdk/copilot/streaming_adapter.py
+++ b/skyvern/forge/sdk/copilot/streaming_adapter.py
@@ -348,8 +348,11 @@ async def stream_to_sse(
ctx.in_flight_stream_tool_call = InFlightStreamToolCall(
call_id=call_id, tool_name=tool_name, iteration=iteration, display_label=display_label
)
+ tool_call_ts = datetime.now(timezone.utc)
narrator_state.record_activity(
- build_tool_call_activity(tool_name, iteration, call_id, display_label=display_label)
+ build_tool_call_activity(
+ tool_name, iteration, call_id, timestamp=tool_call_ts, display_label=display_label
+ )
)
if not client_gone:
@@ -361,6 +364,7 @@ async def stream_to_sse(
tool_input=_sanitize_input(tool_input),
iteration=iteration,
tool_call_id=call_id,
+ timestamp=tool_call_ts,
)
)
@@ -401,9 +405,16 @@ async def stream_to_sse(
parsed, tool_name=tool_name, blocker_signal=blocker_signals, success=success
)
result_label = call_id_to_label.get(call_id) or tool_activity_display_label(tool_name)
+ tool_result_ts = datetime.now(timezone.utc)
narrator_state.record_activity(
build_tool_result_activity(
- tool_name, summary, success, iteration, call_id, display_label=result_label
+ tool_name,
+ summary,
+ success,
+ iteration,
+ call_id,
+ timestamp=tool_result_ts,
+ display_label=result_label,
)
)
@@ -419,6 +430,7 @@ async def stream_to_sse(
tool_call_id=call_id,
detail=detail,
workflow_run_id=_tool_result_workflow_run_id(tool_name, parsed),
+ timestamp=tool_result_ts,
)
)
@@ -543,11 +555,18 @@ async def flush_goal_satisfied_tool_result(stream: EventSourceStream, ctx: Copil
summary = format_tool_result_for_user(pending.tool_name, parsed, blocker_signal=blocker_signals)
success = user_facing_success(parsed, blocker_signal=blocker_signals)
display_label = pending.display_label or tool_activity_display_label(pending.tool_name)
+ flush_ts = datetime.now(timezone.utc)
narrator_state = ctx.narrator_state
if narrator_state is not None:
narrator_state.record_activity(
build_tool_result_activity(
- pending.tool_name, summary, success, pending.iteration, pending.call_id, display_label=display_label
+ pending.tool_name,
+ summary,
+ success,
+ pending.iteration,
+ pending.call_id,
+ timestamp=flush_ts,
+ display_label=display_label,
)
)
if await stream.is_disconnected():
@@ -565,6 +584,7 @@ async def flush_goal_satisfied_tool_result(stream: EventSourceStream, ctx: Copil
parsed, tool_name=pending.tool_name, blocker_signal=blocker_signals, success=success
),
workflow_run_id=_tool_result_workflow_run_id(pending.tool_name, parsed),
+ timestamp=flush_ts,
)
)
diff --git a/skyvern/forge/sdk/copilot/tools/__init__.py b/skyvern/forge/sdk/copilot/tools/__init__.py
index 2dcadf606..0f9b747ee 100644
--- a/skyvern/forge/sdk/copilot/tools/__init__.py
+++ b/skyvern/forge/sdk/copilot/tools/__init__.py
@@ -187,8 +187,7 @@ from .run_execution import (
from .run_execution import _watchdog_error_message as _watchdog_error_message
from .scouting import _MAX_SCOUTED_INTERACTIONS as _MAX_SCOUTED_INTERACTIONS
from .scouting import _capture_accessible_role_name as _capture_accessible_role_name
-from .scouting import _capture_scout_ambiguity as _capture_scout_ambiguity
-from .scouting import _capture_scout_role_name as _capture_scout_role_name
+from .scouting import _capture_scout_pre_action as _capture_scout_pre_action
from .scouting import _capture_scout_source_url as _capture_scout_source_url
from .scouting import _clear_pending_browser_interaction_observation as _clear_pending_browser_interaction_observation
from .scouting import (
@@ -842,6 +841,10 @@ async def update_and_run_blocks_tool(
parameters: dict[str, Any] | None = None,
) -> Any:
"""Update the workflow YAML and immediately run the specified blocks in one step.
+ This persists the workflow and remotely executes the selected frontier, waiting for it to
+ finish, so it is materially higher latency than a bounded page read. It is the surface for
+ testing durable behaviour, and for reaching a state that only execution can establish --
+ authentication, a credential or OTP step, or state an upstream block creates.
Use this instead of calling update_workflow and run_blocks_and_collect_debug separately.
The workflow must validate successfully before blocks are run.
@@ -1097,11 +1100,18 @@ async def inspect_page_for_composition_tool(
) -> str:
"""Inspect a known page before composing form/search workflow blocks.
+ This is a bounded read of known or current page state: it is the surface for uncertainty about
+ controls, selectors, visible state or layout, where no workflow execution is required.
Use this after the entrypoint URL is known and before authoring blocks that
fill fields, submit searches, filter results, or expand result rows. It
can also inspect the current browser page after a run by passing
target_url="current_page"; use that after partial/budgeted runs so you do
- not replay a search that already advanced the page.
+ not replay a search that already advanced the page. Passing any other
+ `target_url` navigates the live browser there and reports the reached
+ `current_url`, so a further `navigate_browser` to that same URL is redundant. The packet
+ describes the page only as it is at that moment: a control that appears solely after an
+ interaction -- a Delete control after an Add click, a cart after add-to-cart, the secure area
+ after login -- is absent from it until that interaction has happened.
Returns observed page evidence: current URL, title, navigation targets, form
fields with labels and selectors, submit/search controls, result containers,
diff --git a/skyvern/forge/sdk/copilot/tools/composition_capture.py b/skyvern/forge/sdk/copilot/tools/composition_capture.py
index e7d3eb740..086523775 100644
--- a/skyvern/forge/sdk/copilot/tools/composition_capture.py
+++ b/skyvern/forge/sdk/copilot/tools/composition_capture.py
@@ -27,6 +27,7 @@ from skyvern.forge.sdk.copilot.loop_detection import record_tool_step_result_for
from skyvern.forge.sdk.copilot.runtime_authoring_repair import (
finalize_runtime_authoring_repair_context_from_page_observation,
post_run_inspection_cleanly_matches,
+ repair_page_evidence_is_admissible,
)
from skyvern.forge.sdk.copilot.tracing_setup import copilot_span
@@ -584,7 +585,7 @@ def _preserves_existing_post_run_page_evidence(
*,
run_id: str,
) -> bool:
- if stamped.get("observed_after_workflow_run") is True and has_bounded_page_schema(stamped):
+ if stamped.get("observed_after_workflow_run") is True and repair_page_evidence_is_admissible(stamped):
return False
return post_run_inspection_cleanly_matches(copilot_ctx.composition_page_evidence, run_id)
diff --git a/skyvern/forge/sdk/copilot/tools/credential_fill.py b/skyvern/forge/sdk/copilot/tools/credential_fill.py
index 2c8982653..5c6fc75a0 100644
--- a/skyvern/forge/sdk/copilot/tools/credential_fill.py
+++ b/skyvern/forge/sdk/copilot/tools/credential_fill.py
@@ -972,7 +972,7 @@ async def _fill_credential_field_impl_serial(
if submitted:
data["submit_url"] = safe_page_origin(observed_url) or ""
if page_evidence is not None:
- _attach_scout_page_summary(result, page_evidence)
+ _attach_scout_page_summary(copilot_ctx, result, page_evidence)
else:
form_submits = await _capture_enclosing_form_submits(copilot_ctx, selector)
if form_submits:
diff --git a/skyvern/forge/sdk/copilot/tools/mcp_hooks.py b/skyvern/forge/sdk/copilot/tools/mcp_hooks.py
index 0fdda9fcf..f8190e8ac 100644
--- a/skyvern/forge/sdk/copilot/tools/mcp_hooks.py
+++ b/skyvern/forge/sdk/copilot/tools/mcp_hooks.py
@@ -15,6 +15,7 @@ from skyvern.forge.sdk.copilot.composition_browser_expressions import scout_cont
from skyvern.forge.sdk.copilot.config import (
BlockAuthoringPolicy,
download_scout_act_required_for_policy,
+ normalize_block_authoring_policy,
)
from skyvern.forge.sdk.copilot.context import CopilotContext
from skyvern.forge.sdk.copilot.credential_resolution import is_resolved_page_url, load_credentials
@@ -43,6 +44,8 @@ from ._shared import (
)
from .banned_blocks import (
_CODE_ONLY_TARGET_EVIDENCE_KEYS,
+ _COPILOT_BANNED_BLOCK_TYPES,
+ _COPILOT_CODE_ONLY_BROWSER_BANNED_BLOCK_TYPES,
_code_only_browser_schema_guidance,
_code_only_browser_unavailable_summary,
_copilot_banned_block_alternatives,
@@ -63,15 +66,15 @@ from .scouting import (
_attach_scout_observation_step,
_attach_scout_page_summary,
_capture_post_interaction_screenshot,
- _capture_scout_ambiguity,
- _capture_scout_role_name,
- _capture_scout_selector_candidates,
+ _capture_scout_pre_action,
_capture_scout_source_url,
_clear_pending_browser_interaction_observation,
+ _clear_pending_scout_selector_facts,
_consume_scout_source_url,
_mark_pending_browser_interaction_observation,
_maybe_attach_observed_download_target,
_maybe_attach_observed_render_target,
+ _page_evidence_names_obstruction,
_prenav_ambiguity_for_selector,
_prenav_role_name_for_selector,
_record_scout_trajectory_fact,
@@ -409,24 +412,17 @@ async def _click_pre_hook(
) -> dict[str, Any] | None:
# Cleared up front so an early return below (deterministic result or no selector)
# cannot leave a prior click's stash for this click's post-hook to consume.
- ctx.pending_scout_role_name = None
- ctx.pending_scout_role_name_match_count = None
ctx.pending_scout_click_selector = None
- ctx.pending_scout_ambiguous = None
- ctx.pending_scout_selector_match_count = None
- ctx.pending_scout_selector_candidates = None
ctx.pending_scout_download_snapshot = None
ctx.pending_scout_download = False
ctx.pending_scout_popup = None
ctx.pending_scout_popup_content_type = None
await _capture_scout_source_url(ctx)
selector = params.get("selector", "")
+ await _capture_scout_pre_action(ctx, selector if isinstance(selector, str) else None)
if not selector:
return None
ctx.pending_scout_click_selector = selector if isinstance(selector, str) else None
- await _capture_scout_role_name(ctx, selector)
- await _capture_scout_selector_candidates(ctx, selector)
- await _capture_scout_ambiguity(ctx, selector)
if _copilot_block_authoring_policy(ctx) == BlockAuthoringPolicy.CODE_ONLY_BROWSER:
ctx.pending_scout_download_snapshot = await _scout_session_download_names(ctx)
await _arm_scout_download_listener(ctx)
@@ -439,10 +435,7 @@ async def _type_text_pre_hook(
ctx: AgentContext,
) -> dict[str, Any] | None:
await _capture_scout_source_url(ctx)
- ctx.pending_scout_role_name = None
- ctx.pending_scout_role_name_match_count = None
- ctx.pending_scout_selector_match_count = None
- ctx.pending_scout_selector_candidates = None
+ _clear_pending_scout_selector_facts(ctx)
ctx.pending_scout_input_value = None
text = params.get("text")
selector = str(params.get("selector") or "")
@@ -461,9 +454,7 @@ async def _type_text_pre_hook(
}
if isinstance(text, str) and text:
ctx.pending_scout_input_value = text
- await _capture_scout_role_name(ctx, selector)
- await _capture_scout_selector_candidates(ctx, selector)
- await _capture_scout_ambiguity(ctx, selector)
+ await _capture_scout_pre_action(ctx, selector)
return None
@@ -471,16 +462,8 @@ async def _select_option_pre_hook(
params: dict[str, Any],
ctx: AgentContext,
) -> dict[str, Any] | None:
- ctx.pending_scout_ambiguous = None
- ctx.pending_scout_reanchor = None
- ctx.pending_scout_role_name = None
- ctx.pending_scout_role_name_match_count = None
- ctx.pending_scout_selector_match_count = None
- ctx.pending_scout_selector_candidates = None
await _capture_scout_source_url(ctx)
- await _capture_scout_role_name(ctx, params.get("selector", ""))
- await _capture_scout_selector_candidates(ctx, params.get("selector", ""))
- await _capture_scout_ambiguity(ctx, params.get("selector", ""))
+ await _capture_scout_pre_action(ctx, params.get("selector", ""))
return None
@@ -489,16 +472,7 @@ async def _press_key_pre_hook(
ctx: AgentContext,
) -> dict[str, Any] | None:
await _capture_scout_source_url(ctx)
- ctx.pending_scout_role_name = None
- ctx.pending_scout_role_name_match_count = None
- ctx.pending_scout_ambiguous = None
- ctx.pending_scout_reanchor = None
- ctx.pending_scout_selector_match_count = None
- ctx.pending_scout_selector_candidates = None
- if params.get("selector"):
- await _capture_scout_role_name(ctx, params.get("selector"))
- await _capture_scout_selector_candidates(ctx, params.get("selector"))
- await _capture_scout_ambiguity(ctx, params.get("selector"))
+ await _capture_scout_pre_action(ctx, params.get("selector"))
return None
@@ -644,6 +618,7 @@ async def _click_post_hook(
) -> dict[str, Any]:
ctx.last_scout_act_observe_outcome = None
ctx.last_scout_act_observe_packet = None
+ page_evidence: dict[str, Any] | None = None
_clear_pending_browser_interaction_observation(ctx)
source_url = _consume_scout_source_url(ctx)
pending_role_name = ctx.pending_scout_role_name
@@ -723,7 +698,7 @@ async def _click_post_hook(
await _maybe_attach_observed_download_target(ctx, result, selector=selector, url=url)
await _maybe_attach_observed_render_target(ctx, result, selector=selector, url=url)
if page_evidence is not None:
- _attach_scout_page_summary(result, page_evidence)
+ _attach_scout_page_summary(ctx, result, page_evidence)
elif ctx.last_scout_act_observe_outcome == "unchanged":
result["data"]["page_observation"] = {
"status": "unchanged",
@@ -731,9 +706,9 @@ async def _click_post_hook(
"The page observation did not change after the click; no post-click page evidence was attached."
),
}
- # Fresh page evidence already described the change, so the round-trip buys little. Accepted
- # cost: a blocker only a frame can show goes unseen until the next action fails and captures.
- if ctx.last_scout_act_observe_outcome != "attached":
+ # The round-trip is skipped only when the evidence positively names the obstruction a frame
+ # would have shown; evidence that merely parsed is not a substitute for looking at the page.
+ if ctx.last_scout_act_observe_outcome != "attached" or not _page_evidence_names_obstruction(page_evidence):
await _capture_post_interaction_screenshot(ctx)
return result
@@ -1017,7 +992,7 @@ async def _type_text_post_hook(
result["observation_step"] = observation_step
result["data"]["observation_step"] = observation_step
if page_evidence is not None:
- _attach_scout_page_summary(result, page_evidence)
+ _attach_scout_page_summary(ctx, result, page_evidence)
return result
@@ -1349,7 +1324,7 @@ async def _select_option_post_hook(
result["observation_step"] = observation_step
result["data"]["observation_step"] = observation_step
if page_evidence is not None:
- _attach_scout_page_summary(result, page_evidence)
+ _attach_scout_page_summary(ctx, result, page_evidence)
return result
@@ -1432,7 +1407,7 @@ async def _press_key_post_hook(
result["observation_step"] = observation_step
result["data"]["observation_step"] = observation_step
if page_evidence is not None:
- _attach_scout_page_summary(result, page_evidence)
+ _attach_scout_page_summary(ctx, result, page_evidence)
return result
@@ -1454,17 +1429,19 @@ def get_skyvern_mcp_alias_map() -> dict[str, str]:
_EVALUATE_BASE_DESCRIPTION = (
- "Execute JavaScript in the browser and return the result. "
- "Use this to inspect DOM state, read values, or run arbitrary JS."
+ "Execute JavaScript in the browser and return the result. Use it to inspect DOM state and read "
+ "values. JavaScript run here can also change the page, but only click, type_text, select_option "
+ "and press_key record a scouted interaction, so a change made through this tool leaves nothing to "
+ "author from -- act with those tools and read with this one."
)
# Scout-ACT framing: a download (or row-expand / post-login) affordance exposes its terminal
# target only once its page is reached. The model reaches that page with navigate/click and
-# observes it here — evaluate cannot click — so the model can author the terminal download step.
+# observes it here -- evaluate records no interaction -- so the model can author the download step.
_EVALUATE_SCOUT_ACT_DESCRIPTION = (
_EVALUATE_BASE_DESCRIPTION
+ " Some affordances (a download, a row-expand, a post-login area) only expose their target "
- "once the page holding them is reached. Use this tool to OBSERVE that page — it cannot click; "
- "reach the page with the navigate/click tools first. For a download, observe the page that "
+ "once the page holding them is reached. Use this tool to OBSERVE that page; reach it with the "
+ "navigate/click tools first. For a download, observe the page that "
"exposes the download control and capture a stable selector, then author the terminal download "
"step from the code-block schema contract."
)
@@ -1478,11 +1455,25 @@ def _evaluate_overlay_description(
return _EVALUATE_BASE_DESCRIPTION
+def _block_schema_banned_types_note(
+ block_authoring_policy: BlockAuthoringPolicy | str | None = BlockAuthoringPolicy.STANDARD,
+) -> str:
+ """Name the rejected types from the same constant the schema pre-hook rejects on. The set is
+ policy-dependent, which a static prompt line cannot track."""
+ 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
+ )
+ return f"Unavailable under the active policy and rejected on request: {', '.join(sorted(banned))}."
+
+
def _build_skyvern_mcp_overlays(
block_authoring_policy: BlockAuthoringPolicy | str | None = BlockAuthoringPolicy.STANDARD,
) -> dict[str, SchemaOverlay]:
return {
"get_block_schema": SchemaOverlay(
+ description_suffix=_block_schema_banned_types_note(block_authoring_policy),
pre_hook=_get_block_schema_pre_hook,
post_hook=_get_block_schema_post_hook,
),
diff --git a/skyvern/forge/sdk/copilot/tools/run_execution.py b/skyvern/forge/sdk/copilot/tools/run_execution.py
index f3cff86af..91edd4ef9 100644
--- a/skyvern/forge/sdk/copilot/tools/run_execution.py
+++ b/skyvern/forge/sdk/copilot/tools/run_execution.py
@@ -101,6 +101,7 @@ from skyvern.forge.sdk.copilot.runtime_authoring_repair import (
inject_runtime_authoring_repair_context,
post_run_inspection_cleanly_matches,
record_pending_runtime_authoring_repair_context,
+ repair_page_evidence_is_admissible,
same_run_typed_challenge_kind,
)
from skyvern.forge.sdk.copilot.tracing_setup import copilot_span
@@ -1463,7 +1464,7 @@ async def _capture_and_store_post_run_page(
evidence, observed_session_id, _ = await _read_run_session_page_evidence(
ctx, run_session_id=run_session_id, current_url=current_url
)
- if evidence is not None and has_bounded_page_schema(evidence):
+ if evidence is not None and repair_page_evidence_is_admissible(evidence):
store_post_run_page_evidence(
ctx,
evidence,
@@ -2191,6 +2192,7 @@ async def _run_blocks_and_collect_debug(
block_state_map=ctx.block_state_map,
block_started_at_map=ctx.block_started_at_map,
block_ended_at_map=ctx.block_ended_at_map,
+ block_run_identity_map=ctx.block_run_identity_map,
workflow_run_id=workflow_run.workflow_run_id,
)
prior_block_ts = tick_result.prior_block_ts
diff --git a/skyvern/forge/sdk/copilot/tools/scouting.py b/skyvern/forge/sdk/copilot/tools/scouting.py
index da510908a..34cc4a314 100644
--- a/skyvern/forge/sdk/copilot/tools/scouting.py
+++ b/skyvern/forge/sdk/copilot/tools/scouting.py
@@ -33,6 +33,9 @@ from skyvern.forge.sdk.copilot.composition_browser_expressions import (
from skyvern.forge.sdk.copilot.composition_browser_expressions import (
scout_accessible_role_name_expression as _scout_accessible_role_name_expression,
)
+from skyvern.forge.sdk.copilot.composition_browser_expressions import (
+ scout_pre_action_expression as _scout_pre_action_expression,
+)
from skyvern.forge.sdk.copilot.composition_browser_expressions import (
selector_candidates_expression as _selector_candidates_expression,
)
@@ -311,46 +314,6 @@ async def _role_name_match_count(
return value
-async def _capture_scout_role_name(ctx: AgentContext, selector: str | None) -> None:
- """Stash (selector, role, accessible_name) before an in-flight click that may navigate.
-
- A navigating click leaves only the landing page, so the post-action read returns the wrong
- element; this captures the source-page anchor so a bare-selector navigating click still carries a
- role/name into the trajectory."""
- ctx.pending_scout_role_name = None
- ctx.pending_scout_role_name_match_count = None
- selector = _selector_text(selector)
- if not selector:
- return
- parsed = _role_name_from_selector(selector)
- source = "selector"
- if parsed is not None:
- role, name = parsed
- else:
- source = "page_read"
- captured = await _capture_accessible_role_name(
- ctx, selector, timeout_seconds=_PRE_NAVIGATION_ROLE_NAME_TIMEOUT_SECONDS
- )
- if captured is None:
- # A read that never answered and one that answered namelessly leave the same empty
- # trajectory, and only the first is a timeout worth widening.
- LOG.info("copilot_scout_role_name_unavailable", reason="page_read_failed", source=source)
- return
- role, name = captured
- if not role or not name:
- LOG.info(
- "copilot_scout_role_name_unavailable",
- reason="empty_role" if not role else "empty_name",
- source=source,
- role_present=bool(role),
- )
- return
- ctx.pending_scout_role_name = (selector, role, name)
- count = await _role_name_match_count(ctx, role, name)
- if count is not None:
- ctx.pending_scout_role_name_match_count = (selector, role, name, count)
-
-
def _prenav_role_name_for_selector(pending: tuple[str, str, str] | None, selector: str) -> tuple[str, str]:
"""Return the pre-navigation (role, accessible_name) only when the recorded selector matches the
stashed one, so a navigating click's anchor is never applied to a different element."""
@@ -362,59 +325,112 @@ def _prenav_role_name_for_selector(pending: tuple[str, str, str] | None, selecto
return role, name
-async def _capture_scout_ambiguity(ctx: AgentContext, selector: str | None) -> None:
- """Stash source-page selector ambiguity and, when unique, a role/name re-anchor.
+def _prenav_ambiguity_for_selector(pending: tuple[str, bool] | None, selector: str) -> bool:
+ """Return the stashed ambiguity verdict only when the recorded selector matches the probed one, so a
+ navigating click's verdict is never applied to a different element."""
+ if pending is None:
+ return False
+ stashed_selector, ambiguous = pending
+ if stashed_selector != _selector_text(selector):
+ return False
+ return ambiguous
- The ambiguity fact never replaces the observed role/name packet. The re-anchor is an additional
- fact about uniqueness, not authority to discard a non-unique accessible identity.
- """
+
+def _clear_pending_scout_selector_facts(ctx: AgentContext) -> None:
+ ctx.pending_scout_role_name = None
+ ctx.pending_scout_role_name_match_count = None
+ ctx.pending_scout_selector_candidates = None
ctx.pending_scout_ambiguous = None
ctx.pending_scout_reanchor = None
ctx.pending_scout_selector_match_count = None
- selector = _selector_text(selector)
- if not selector:
- return
- count = await _selector_live_match_count(ctx, selector)
- if count is None:
- return
- ctx.pending_scout_selector_match_count = (selector, count)
- if count <= 1:
- return
- ctx.pending_scout_ambiguous = (selector, True)
- pending_role_name = getattr(ctx, "pending_scout_role_name", None)
- if isinstance(pending_role_name, tuple) and len(pending_role_name) == 3 and pending_role_name[0] == selector:
- role, name = pending_role_name[1:]
+
+
+def _non_negative_count(value: Any) -> int | None:
+ """A live cardinality, or None for the expression's "could not evaluate" sentinel."""
+ if isinstance(value, bool) or not isinstance(value, int) or value < 0:
+ return None
+ return value
+
+
+def _apply_scout_pre_action_packet(ctx: AgentContext, selector: str, packet: dict[str, Any], *, source: str) -> None:
+ role, name = "", ""
+ role_name = packet.get("role_name")
+ if isinstance(role_name, dict):
+ role = str(role_name.get("role") or "").strip()
+ name = str(role_name.get("accessible_name") or "").strip()
+ if role and name:
+ ctx.pending_scout_role_name = (selector, role, name)
else:
- captured = await _capture_accessible_role_name(
- ctx, selector, timeout_seconds=_PRE_NAVIGATION_ROLE_NAME_TIMEOUT_SECONDS
+ LOG.info(
+ "copilot_scout_role_name_unavailable",
+ reason="empty_role" if not role else "empty_name",
+ source=source,
+ role_present=bool(role),
)
- if captured is None:
- return
- role, name = captured
- if not role or not name:
+
+ role_count = _non_negative_count(packet.get("role_name_match_count"))
+ if role and name and role_count is not None:
+ ctx.pending_scout_role_name_match_count = (selector, role, name, role_count)
+
+ candidates: list[ScoutedSelectorCandidate] = []
+ for raw in packet.get("selector_candidates") or []:
+ if not isinstance(raw, dict):
+ continue
+ candidate_selector = _selector_text(raw.get("selector"))
+ candidate_source = _selector_text(raw.get("source"))
+ if not candidate_selector or not candidate_source:
+ continue
+ candidate: ScoutedSelectorCandidate = {"selector": candidate_selector, "source": candidate_source}
+ if candidate not in candidates:
+ candidates.append(candidate)
+ if candidates:
+ ctx.pending_scout_selector_candidates = candidates
+
+ selector_count = _non_negative_count(packet.get("selector_match_count"))
+ if selector_count is None:
return
- pending_role_count = getattr(ctx, "pending_scout_role_name_match_count", None)
- if (
- isinstance(pending_role_count, tuple)
- and len(pending_role_count) == 4
- and pending_role_count[:3] == (selector, role, name)
- ):
- role_count = pending_role_count[3]
- else:
- role_count = await _role_name_match_count(ctx, role, name)
- if role_count == 1:
+ ctx.pending_scout_selector_match_count = (selector, selector_count)
+ if selector_count <= 1:
+ return
+ ctx.pending_scout_ambiguous = (selector, True)
+ if role and name and role_count == 1:
ctx.pending_scout_reanchor = (selector, role, name)
-def _prenav_ambiguity_for_selector(pending: tuple[str, bool] | None, selector: str) -> bool:
- """Return the stashed ambiguity verdict only when the recorded selector matches the probed one, so a
- navigating click's verdict is never applied to a different element."""
- if pending is None:
- return False
- stashed_selector, ambiguous = pending
- if stashed_selector != _selector_text(selector):
- return False
- return ambiguous
+async def _capture_scout_pre_action(ctx: AgentContext, selector: str | None) -> None:
+ """Stash every pre-action source-page fact from one bounded page read.
+
+ The read runs inline before the action dispatches, so a failure leaves the facts it could not
+ reach unset and the action proceeds; the caller's TIER 1 role/name parse is passed in because a
+ role-engine selector is not valid CSS and could not be counted from the page alone."""
+ _clear_pending_scout_selector_facts(ctx)
+ selector = _selector_text(selector)
+ if not selector:
+ return
+ parsed = _role_name_from_selector(selector)
+ source = "selector" if parsed is not None else "page_read"
+ parsed_role, parsed_name = parsed if parsed is not None else ("", "")
+ server = ctx.discovery_mcp_server
+ result = None
+ if server is not None:
+ try:
+ result = await asyncio.wait_for(
+ server.call_internal_tool(
+ "skyvern_evaluate",
+ {"expression": _scout_pre_action_expression(selector, parsed_role, parsed_name)},
+ ),
+ timeout=_PRE_NAVIGATION_ROLE_NAME_TIMEOUT_SECONDS,
+ )
+ except Exception:
+ result = None
+ packet = (result.get("data") or {}).get("result") if isinstance(result, dict) and result.get("ok") else None
+ if not isinstance(packet, dict):
+ LOG.info("copilot_scout_role_name_unavailable", reason="page_read_failed", source=source)
+ if parsed is None:
+ return
+ # The parse needed no page, so an unreachable page must not cost the identity it already gave.
+ packet = {"role_name": {"role": parsed_role, "accessible_name": parsed_name}}
+ _apply_scout_pre_action_packet(ctx, selector, packet, source=source)
async def _resolve_scout_role_name(
@@ -1158,6 +1174,7 @@ _PAGE_SUMMARY_MAX_SUBMITS = 4
_PAGE_SUMMARY_MAX_NAV_TEXTS = 8
_PAGE_SUMMARY_MAX_DISMISS_TEXTS = 4
_PAGE_SUMMARY_MAX_DISCLOSURE_CONTROLS = 4
+_PAGE_SUMMARY_SELECTOR_CAP = 120
def _summary_text(value: Any) -> str:
@@ -1172,14 +1189,25 @@ def _summary_field_name(field: dict[str, Any]) -> str:
return ""
+def _summary_selector(control: dict[str, Any]) -> str:
+ """Carry a selector whole or not at all, never shortened: a truncated selector can still parse
+ and match a different element, which is worse for authoring than carrying no selector."""
+ raw = control.get("selector")
+ selector = raw.strip() if isinstance(raw, str) else ""
+ return selector if selector and len(selector) <= _PAGE_SUMMARY_SELECTOR_CAP else ""
+
+
def _summary_disclosure_control(control: dict[str, Any]) -> dict[str, Any] | None:
if not isinstance(control.get("expanded"), bool):
return None
summary: dict[str, Any] = {"expanded": control["expanded"]}
- for key in ("text", "selector", "controls"):
+ for key in ("text", "controls"):
value = _summary_text(control.get(key))
if value:
summary[key] = value
+ disclosure_selector = _summary_selector(control)
+ if disclosure_selector:
+ summary["selector"] = disclosure_selector
if "controls" in summary and isinstance(control.get("controlled_region_visible"), bool):
summary["controlled_region_visible"] = control["controlled_region_visible"]
if control.get("disabled") is True:
@@ -1189,6 +1217,19 @@ def _summary_disclosure_control(control: dict[str, Any]) -> dict[str, Any] | Non
return summary
+def _summary_entry(text: str, control: dict[str, Any]) -> dict[str, str]:
+ """A summary control carrying the selector the evidence observed for it, when there was one.
+
+ The selector is kept whole or dropped, never shortened: a truncated selector can still parse
+ and match a different element, which is worse for authoring than carrying no selector at all.
+ """
+ entry = {"text": text}
+ selector = _summary_selector(control)
+ if selector:
+ entry["selector"] = selector
+ return entry
+
+
def _build_scout_page_summary(evidence: dict[str, Any]) -> dict[str, Any]:
forms_summary: list[dict[str, Any]] = []
for form in evidence.get("forms") or []:
@@ -1200,12 +1241,16 @@ def _build_scout_page_summary(evidence: dict[str, Any]) -> dict[str, Any]:
{
"field_count": len(fields),
"fields": [
- name for name in (_summary_field_name(field) for field in fields[:_PAGE_SUMMARY_MAX_FIELDS]) if name
+ _summary_entry(name, field)
+ for field, name in (
+ (field, _summary_field_name(field)) for field in fields[:_PAGE_SUMMARY_MAX_FIELDS]
+ )
+ if name
],
"submit_controls": [
- text
- for text in (
- _summary_text(control.get("text") or control.get("value"))
+ _summary_entry(text, control)
+ for control, text in (
+ (control, _summary_text(control.get("text") or control.get("value")))
for control in submits[:_PAGE_SUMMARY_MAX_SUBMITS]
)
if text
@@ -1213,18 +1258,18 @@ def _build_scout_page_summary(evidence: dict[str, Any]) -> dict[str, Any]:
}
)
nav_targets = [target for target in evidence.get("navigation_targets") or [] if isinstance(target, dict)]
- dismiss_texts: list[str] = []
+ dismiss_entries: list[dict[str, str]] = []
for overlay in evidence.get("modal_overlays") or []:
if not isinstance(overlay, dict):
continue
for control in overlay.get("dismiss_controls") or []:
- if len(dismiss_texts) >= _PAGE_SUMMARY_MAX_DISMISS_TEXTS:
+ if len(dismiss_entries) >= _PAGE_SUMMARY_MAX_DISMISS_TEXTS:
break
if not isinstance(control, dict):
continue
text = _summary_text(control.get("text") or control.get("aria_label") or control.get("title"))
if text:
- dismiss_texts.append(text)
+ dismiss_entries.append(_summary_entry(text, control))
challenge_state = evidence.get("challenge_state")
challenge_detected = bool(evidence.get("challenge_controls")) or (
isinstance(challenge_state, dict) and challenge_state.get("detected") is True
@@ -1258,69 +1303,144 @@ def _build_scout_page_summary(evidence: dict[str, Any]) -> dict[str, Any]:
"navigation_target_count": len(nav_targets),
"navigation_targets_truncated": evidence.get("navigation_targets_truncated") is True,
"navigation_targets": [
- text
- for text in (_summary_text(target.get("text")) for target in nav_targets[:_PAGE_SUMMARY_MAX_NAV_TEXTS])
+ _summary_entry(text, target)
+ for target, text in (
+ (target, _summary_text(target.get("text"))) for target in nav_targets[:_PAGE_SUMMARY_MAX_NAV_TEXTS]
+ )
if text
],
"result_container_count": len(evidence.get("result_containers") or []),
"disclosure_controls": disclosure_controls,
"challenge_detected": challenge_detected,
- "modal_dismiss_controls": dismiss_texts,
+ "modal_dismiss_controls": dismiss_entries,
}
-def _shed_scout_page_summary_section(summary: dict[str, Any]) -> bool:
- """Drop one summary section, in fixed priority order; False when nothing is left to shed."""
+def _drop_scout_page_summary_selectors(summary: dict[str, Any]) -> bool:
+ """Collapse every control entry to the bare text it carries, and report whether anything changed."""
+ dropped = False
+ groups: list[Any] = [summary.get("navigation_targets"), summary.get("modal_dismiss_controls")]
+ for form in summary.get("forms") or []:
+ if isinstance(form, dict):
+ groups.extend([form.get("fields"), form.get("submit_controls")])
+ for entries in groups:
+ if not isinstance(entries, list):
+ continue
+ collapsed = [str(entry.get("text") or "") if isinstance(entry, dict) else entry for entry in entries]
+ if collapsed != entries:
+ entries[:] = collapsed
+ dropped = True
+ return dropped
+
+
+def _shed_scout_page_summary_section(summary: dict[str, Any]) -> str | None:
+ """Drop one summary section, in fixed priority order; None when nothing is left to shed. Selectors
+ go first so the enrichment can never cost a control the summary carried without it."""
+ if _drop_scout_page_summary_selectors(summary):
+ return "control_selectors"
if summary.get("navigation_targets"):
summary["navigation_targets"] = []
- return True
+ return "navigation_targets"
forms = [form for form in summary.get("forms") or [] if isinstance(form, dict)]
for form in forms[1:]:
if form.get("fields"):
form["fields"] = []
- return True
+ return "later_form_fields"
if summary.get("modal_dismiss_controls"):
summary["modal_dismiss_controls"] = []
- return True
+ return "modal_dismiss_controls"
for form in forms[1:]:
if form.get("submit_controls"):
form["submit_controls"] = []
- return True
+ return "later_form_submit_controls"
if forms and forms[0].get("fields"):
fields = forms[0]["fields"]
forms[0]["fields"] = fields[: len(fields) // 2] if len(fields) > 2 else []
- return True
+ return "first_form_fields"
if forms and forms[0].get("submit_controls"):
forms[0]["submit_controls"] = []
- return True
+ return "first_form_submit_controls"
if len(forms) > 1:
summary["forms"] = forms[:1]
- return True
+ return "later_forms"
if summary.get("disclosure_controls"):
summary["disclosure_controls"] = []
- return True
- return False
+ return "disclosure_controls"
+ return None
+
+
+def _redact_summary_node(ctx: AgentContext, node: Any) -> Any:
+ """Redact the summary's string leaves rather than the whole structure.
+
+ The scrubber rewrites dict keys and integers too, which erases the `text` key the shed ladder
+ reads and turns counts into strings. A selector the scrubber rewrote is dropped rather than
+ kept: a partially rewritten selector still parses and can match a different element.
+ """
+ if isinstance(node, dict):
+ redacted_dict: dict[str, Any] = {}
+ for key, value in node.items():
+ redacted_value = _redact_summary_node(ctx, value)
+ if key == "selector" and isinstance(value, str) and redacted_value != value:
+ continue
+ redacted_dict[key] = redacted_value
+ return redacted_dict
+ if isinstance(node, list):
+ return [_redact_summary_node(ctx, item) for item in node]
+ if isinstance(node, str):
+ redacted_leaf = _redact_codeblock_value(ctx, node)
+ return redacted_leaf if isinstance(redacted_leaf, str) else ""
+ return node
-def _attach_scout_page_summary(result: dict[str, Any], page_evidence: dict[str, Any]) -> None:
+def _attach_scout_page_summary(ctx: AgentContext, result: dict[str, Any], page_evidence: dict[str, Any]) -> None:
"""Attach a compact page summary at result["data"]["page"], keeping the whole
serialized result under the scout result budget by shedding sections —
- never by slicing the serialized JSON."""
+ never by slicing the serialized JSON.
+
+ The summary carries selectors, which can embed a workflow parameter's value, so it takes the same
+ redaction the interaction identity does. That scrubber knows workflow-parameter values only, and
+ those are populated on self-heal turns -- it is not a general secret filter.
+ """
data = result.get("data")
if not isinstance(data, dict):
return
try:
- summary = _build_scout_page_summary(page_evidence)
+ summary = _redact_summary_node(ctx, _build_scout_page_summary(page_evidence))
+ if not isinstance(summary, dict):
+ return
data["page"] = summary
+ shed: list[str] = []
while len(json.dumps(result)) > _SCOUT_RESULT_CHAR_CAP:
- if not _shed_scout_page_summary_section(summary):
- data.pop("page", None)
+ section = _shed_scout_page_summary_section(summary)
+ if section is None:
+ # A summary that vanished with no trace reads as a page with nothing on it, so the
+ # names of everything dropped stay behind even when the summary itself cannot.
+ data["page"] = {"shed": [*shed, "page_summary"]}
return
+ shed.append(section)
+ summary["shed"] = shed
except Exception:
data.pop("page", None)
LOG.warning("copilot_scout_act_observe_summary_failed")
+def _page_evidence_names_obstruction(page_evidence: dict[str, Any] | None) -> bool:
+ """True only when the evidence positively names a blocker a frame would have shown.
+
+ A computed-style obstruction candidate does not count: it fires on ordinary textless overlays
+ and would suppress the frame on exactly the pages a frame is needed for.
+ """
+ if not isinstance(page_evidence, dict):
+ return False
+ overlays = [overlay for overlay in page_evidence.get("modal_overlays") or [] if isinstance(overlay, dict)]
+ if any(overlay.get("dismiss_controls") for overlay in overlays):
+ return True
+ if page_evidence.get("challenge_controls"):
+ return True
+ challenge_state = page_evidence.get("challenge_state")
+ return isinstance(challenge_state, dict) and challenge_state.get("detected") is True
+
+
def _page_evidence_has_password_control(page_evidence: dict[str, Any]) -> bool:
forms = page_evidence.get("forms")
if not isinstance(forms, list):
@@ -1558,7 +1678,7 @@ async def _attach_evaluate_page_facts(ctx: AgentContext, result: dict[str, Any],
_record_scout_page_observation(ctx, page_evidence)
if has_bounded_page_schema(page_evidence):
_append_flow_evidence(ctx, page_evidence, reached_via="current_page")
- _attach_scout_page_summary(result, page_evidence)
+ _attach_scout_page_summary(ctx, result, page_evidence)
def _mark_post_run_page_observed(
diff --git a/skyvern/forge/sdk/core/skyvern_context.py b/skyvern/forge/sdk/core/skyvern_context.py
index 6742ecaa8..56ece7816 100644
--- a/skyvern/forge/sdk/core/skyvern_context.py
+++ b/skyvern/forge/sdk/core/skyvern_context.py
@@ -281,6 +281,21 @@ class SkyvernContext:
# When this reaches the threshold, further captcha solve attempts are short-circuited.
consecutive_captcha_timeouts: int = 0
+ # Circuit breaker: repeated successful captcha solves for one identity (the solve-budget
+ # key below). Bounds a solve-succeeds-repeatedly-but-run-never-advances loop that the
+ # timeout counter cannot see. Independent from consecutive_captcha_timeouts above.
+ consecutive_captcha_solves: int = 0
+ # Solve-budget key (task id + exact page url + concrete solver identity) of the last
+ # reliably-successful solve; a solve with a matching key spends one unit of the budget.
+ # None means no such solve has run yet. Opaque comparison string only; never log it.
+ last_captcha_solve_key: str | None = None
+ # Fast-fail latch (task id + exact page url) set when the solve budget above trips, so a retry
+ # of the captcha action short-circuits at the entry point before invoking a solver instead of
+ # paying another vendor call to re-raise the same failure. Coarser than last_captcha_solve_key
+ # (no solver identity — a pre-entry check can't know it without running the detector); a url
+ # change re-opens it. None means not latched. Opaque comparison string only; never log it.
+ captcha_solve_latch_key: str | None = None
+
# Browser dialogs captured since the last agent prompt build, surfaced into the
# next extract-action prompt so the LLM can react to validation rejections.
recent_dialog_messages: list[DialogEntry] = field(default_factory=list)
diff --git a/skyvern/forge/sdk/db/agent_db_test.py b/skyvern/forge/sdk/db/agent_db_test.py
index ad561a010..0b09853d1 100644
--- a/skyvern/forge/sdk/db/agent_db_test.py
+++ b/skyvern/forge/sdk/db/agent_db_test.py
@@ -32,11 +32,13 @@ async def test_create_organization(agent_db: AgentDB) -> None:
assert organization is not None
assert organization.organization_name == org_name
assert organization.domain == domain
+ assert organization.slug == "test-organization"
retrieved_org = await agent_db.organizations.get_organization(organization.organization_id)
assert retrieved_org is not None
assert retrieved_org.organization_name == org_name
assert retrieved_org.domain == domain
+ assert retrieved_org.slug == "test-organization"
retrieved_by_domain = await agent_db.organizations.get_organization_by_domain(domain=domain)
assert retrieved_by_domain is not None
@@ -60,6 +62,32 @@ async def test_create_organization_with_explicit_id(agent_db: AgentDB) -> None:
assert retrieved_org.domain == "explicit.test"
+async def test_create_organization_retries_derived_slug_collision(agent_db: AgentDB) -> None:
+ first = await agent_db.organizations.create_organization("Shared Name")
+ second = await agent_db.organizations.create_organization("Shared Name")
+
+ assert first.slug == "shared-name"
+ assert second.slug == "shared-name-2"
+
+
+async def test_set_organization_slug_if_missing_preserves_existing_slug(agent_db: AgentDB) -> None:
+ organization = await agent_db.organizations.create_organization("Shared Name", derive_slug=False)
+
+ winner = await agent_db.organizations.set_organization_slug_if_missing(
+ organization_id=organization.organization_id,
+ slug="first-slug",
+ )
+ loser = await agent_db.organizations.set_organization_slug_if_missing(
+ organization_id=organization.organization_id,
+ slug="stale-slug",
+ )
+
+ assert winner.slug == "first-slug"
+ assert loser.slug == "first-slug"
+
+
@pytest.mark.asyncio
async def test_get_organization_not_found(agent_db: AgentDB) -> None:
retrieved_org = await agent_db.organizations.get_organization("non_existent_id")
diff --git a/skyvern/forge/sdk/db/base_alchemy_db.py b/skyvern/forge/sdk/db/base_alchemy_db.py
index 83cdf939e..3dfbd52c4 100644
--- a/skyvern/forge/sdk/db/base_alchemy_db.py
+++ b/skyvern/forge/sdk/db/base_alchemy_db.py
@@ -90,6 +90,13 @@ class _SessionFactory:
def __getattr__(self, name: str) -> Any:
return getattr(self._sessionmaker, name)
+ def current(self) -> AsyncSession | None:
+ entry = self._session_ctx.get()
+ current_task = asyncio.current_task()
+ if entry is None or current_task is None or entry.task is not current_task:
+ return None
+ return entry.session
+
@asynccontextmanager
async def bind_connection(self, connection: AsyncConnection) -> AsyncIterator[AsyncSession]:
session = self._sessionmaker(bind=connection, join_transaction_mode="rollback_only")
diff --git a/skyvern/forge/sdk/db/enums.py b/skyvern/forge/sdk/db/enums.py
index 5badaa2ef..2a19426c0 100644
--- a/skyvern/forge/sdk/db/enums.py
+++ b/skyvern/forge/sdk/db/enums.py
@@ -16,6 +16,7 @@ class TaskType(StrEnum):
general = "general"
validation = "validation"
action = "action"
+ synthetic_sdk_action = "synthetic_sdk_action"
class BrowserSeedSource(StrEnum):
diff --git a/skyvern/forge/sdk/db/models.py b/skyvern/forge/sdk/db/models.py
index 6391c1c03..dae990c5b 100644
--- a/skyvern/forge/sdk/db/models.py
+++ b/skyvern/forge/sdk/db/models.py
@@ -187,9 +187,19 @@ class StepModel(Base):
class OrganizationModel(Base):
__tablename__ = "organizations"
+ __table_args__ = (
+ Index(
+ "uq_organizations_slug",
+ "slug",
+ unique=True,
+ postgresql_where=text("slug IS NOT NULL"),
+ sqlite_where=text("slug IS NOT NULL"),
+ ),
+ )
organization_id = Column(String, primary_key=True, default=generate_org_id)
organization_name = Column(String, nullable=False)
+ slug = Column(String, nullable=True)
webhook_callback_url = Column(UnicodeText)
max_steps_per_run = Column(Integer, nullable=True)
max_steps_per_workflow_run = Column(Integer, nullable=True)
diff --git a/skyvern/forge/sdk/db/repositories/organizations.py b/skyvern/forge/sdk/db/repositories/organizations.py
index b476ae21b..ab593ddcd 100644
--- a/skyvern/forge/sdk/db/repositories/organizations.py
+++ b/skyvern/forge/sdk/db/repositories/organizations.py
@@ -5,12 +5,14 @@ from datetime import datetime, timedelta, timezone
from typing import Literal, overload
from sqlalchemy import delete, select, update
+from sqlalchemy.exc import IntegrityError
from skyvern.forge.sdk.db._error_handling import db_operation
from skyvern.forge.sdk.db.base_alchemy_db import read_retry
from skyvern.forge.sdk.db.base_repository import BaseRepository
from skyvern.forge.sdk.db.enums import OrganizationAuthTokenType
from skyvern.forge.sdk.db.exceptions import NotFoundError
+from skyvern.forge.sdk.db.id import generate_org_id
from skyvern.forge.sdk.db.models import (
OrganizationAuthTokenModel,
OrganizationModel,
@@ -33,6 +35,12 @@ from skyvern.forge.sdk.schemas.organizations import (
)
from skyvern.forge.sdk.schemas.tasks import TaskStatus
from skyvern.forge.sdk.workflow.models.workflow import WorkflowRunStatus
+from skyvern.utils.organization_slug import (
+ OrganizationSlugCollisionError,
+ derive_org_slug,
+ is_org_slug_unique_violation,
+ iter_org_slug_candidates,
+)
class OrganizationsRepository(BaseRepository):
@@ -131,27 +139,74 @@ class OrganizationsRepository(BaseRepository):
max_retries_per_step: int | None = None,
domain: str | None = None,
organization_id: str | None = None,
+ slug: str | None = None,
+ derive_slug: bool = True,
) -> Organization:
+ resolved_organization_id = organization_id or generate_org_id()
+ if slug is None and derive_slug:
+ base_slug = derive_org_slug(organization_name, resolved_organization_id)
+ slug_candidates: Sequence[str | None] = tuple(iter_org_slug_candidates(base_slug, resolved_organization_id))
+ else:
+ slug_candidates = (slug,)
+
+ last_collision: IntegrityError | None = None
async with self.Session() as session:
- org = OrganizationModel(
- organization_id=organization_id,
- organization_name=organization_name,
- webhook_callback_url=webhook_callback_url,
- max_steps_per_run=max_steps_per_run,
- max_retries_per_step=max_retries_per_step,
- domain=domain,
+ for slug_candidate in slug_candidates:
+ organization = OrganizationModel(
+ organization_id=resolved_organization_id,
+ organization_name=organization_name,
+ webhook_callback_url=webhook_callback_url,
+ slug=slug_candidate,
+ max_steps_per_run=max_steps_per_run,
+ max_retries_per_step=max_retries_per_step,
+ domain=domain,
+ )
+ session.add(organization)
+ try:
+ await session.commit()
+ except IntegrityError as exc:
+ await session.rollback()
+ if slug is not None or not derive_slug or not is_org_slug_unique_violation(exc):
+ raise
+ last_collision = exc
+ continue
+ await session.refresh(organization)
+ return convert_to_organization(organization)
+
+ raise OrganizationSlugCollisionError(
+ f"Could not assign a unique slug to organization {resolved_organization_id}"
+ ) from last_collision
+
+ @db_operation("set_organization_slug_if_missing", expected_errors=(IntegrityError,))
+ async def set_organization_slug_if_missing(self, organization_id: str, slug: str) -> Organization:
+ """Atomically fill a missing slug and return the stored winner."""
+ async with self.Session() as session:
+ organization = await session.scalar(
+ update(OrganizationModel)
+ .where(
+ OrganizationModel.organization_id == organization_id,
+ OrganizationModel.slug.is_(None),
+ )
+ .values(slug=slug, modified_at=datetime.now(timezone.utc))
+ .returning(OrganizationModel)
)
- session.add(org)
+ if organization is None:
+ organization = await session.scalar(
+ select(OrganizationModel).where(OrganizationModel.organization_id == organization_id)
+ )
+ if organization is None:
+ raise NotFoundError
await session.commit()
- await session.refresh(org)
-
- return convert_to_organization(org)
+ await session.refresh(organization)
+ return convert_to_organization(organization)
@db_operation("update_organization")
async def update_organization(
self,
organization_id: str,
organization_name: str | None = None,
+ slug: str | None = None,
+ update_slug: bool = False,
webhook_callback_url: str | None = None,
max_steps_per_run: int | None = None,
max_steps_per_workflow_run: int | None = None,
@@ -172,6 +227,8 @@ class OrganizationsRepository(BaseRepository):
raise NotFoundError
if organization_name:
organization.organization_name = organization_name
+ if update_slug:
+ organization.slug = slug
# ``is not None`` (not truthy): "" clears the webhook, 0 disables retries.
if webhook_callback_url is not None:
organization.webhook_callback_url = webhook_callback_url
diff --git a/skyvern/forge/sdk/db/repositories/workflows.py b/skyvern/forge/sdk/db/repositories/workflows.py
index adc0daeea..5eb85c135 100644
--- a/skyvern/forge/sdk/db/repositories/workflows.py
+++ b/skyvern/forge/sdk/db/repositories/workflows.py
@@ -456,7 +456,9 @@ class WorkflowsRepository(BaseRepository):
get_workflow_query = get_workflow_query.filter_by(version=version)
if ignore_version:
get_workflow_query = get_workflow_query.filter(WorkflowModel.version != ignore_version)
- get_workflow_query = get_workflow_query.order_by(WorkflowModel.version.desc())
+ # Result.first() does not emit LIMIT, so without this the query fetches and discards every
+ # version row for the wpid — cost grows with each edit the workflow has ever received.
+ get_workflow_query = get_workflow_query.order_by(WorkflowModel.version.desc()).limit(1)
async with self.Session() as session:
if workflow := (await session.scalars(get_workflow_query)).first():
is_template = (
diff --git a/skyvern/forge/sdk/db/utils.py b/skyvern/forge/sdk/db/utils.py
index fc93bde84..6f83718ad 100644
--- a/skyvern/forge/sdk/db/utils.py
+++ b/skyvern/forge/sdk/db/utils.py
@@ -450,6 +450,7 @@ def convert_to_organization(org_model: OrganizationModel) -> Organization:
return Organization(
organization_id=org_model.organization_id,
organization_name=org_model.organization_name,
+ slug=org_model.slug,
webhook_callback_url=org_model.webhook_callback_url,
max_steps_per_run=org_model.max_steps_per_run,
max_steps_per_workflow_run=org_model.max_steps_per_workflow_run,
diff --git a/skyvern/forge/sdk/forge_log.py b/skyvern/forge/sdk/forge_log.py
index 3060e73e5..daa3cb247 100644
--- a/skyvern/forge/sdk/forge_log.py
+++ b/skyvern/forge/sdk/forge_log.py
@@ -1,6 +1,7 @@
import logging
import random
import sys
+import threading
from contextlib import contextmanager
from contextvars import ContextVar
from decimal import Decimal
@@ -883,6 +884,112 @@ def _categorize_exception(exc_type: type, exc_name: str) -> str:
return "ERROR"
+_INTERPRETER_TRACEBACK_HOOK_MARKER = "_skyvern_interpreter_traceback_hook"
+_UNRAISABLE_OBJECT_REPR_CHARS = 512
+_INTERPRETER_HOOK_REENTRY = threading.local()
+
+
+def _log_interpreter_traceback(
+ msg: str,
+ exc_info: tuple[type[BaseException] | None, BaseException | None, TracebackType | None],
+ **fields: Any,
+) -> bool:
+ """Emit one structured record for a traceback the interpreter would print to stderr.
+
+ Returns False when the caller must fall back to the hook it replaced.
+ """
+ exc_type, exc_value, exc_traceback = exc_info
+ if exc_type is None or exc_value is None:
+ return False
+ # These hooks fire from arbitrary garbage-collection points, so emitting can itself trigger a
+ # collection whose finalizer raises another unraisable. Without this guard that recurses until
+ # the stack is exhausted.
+ if getattr(_INTERPRETER_HOOK_REENTRY, "active", False):
+ return False
+ _INTERPRETER_HOOK_REENTRY.active = True
+ try:
+ logging.getLogger("skyvern.interpreter").error(
+ msg,
+ exc_info=(exc_type, exc_value, exc_traceback),
+ extra={key: value for key, value in fields.items() if value is not None},
+ )
+ except Exception:
+ return False
+ finally:
+ _INTERPRETER_HOOK_REENTRY.active = False
+ return True
+
+
+def _unraisable_object_repr(obj: Any) -> str | None:
+ # CPython folds the object's repr into err_msg instead of setting `object` in some finalizer
+ # paths, so None here is normal and the field is dropped rather than rendered as "None".
+ if obj is None:
+ return None
+ try:
+ return str(_truncate_log_value(repr(obj), _UNRAISABLE_OBJECT_REPR_CHARS))
+ except BaseException:
+ return "<unrepresentable>"
+
+
+def _install_interpreter_traceback_hooks() -> None:
+ """Route the tracebacks the interpreter writes straight to stderr through the logging stack.
+
+ ``sys.excepthook``, ``threading.excepthook`` and ``sys.unraisablehook`` bypass ``logging``
+ entirely and print a multi-line traceback to stderr. A line-oriented collector bills each
+ frame as its own event, so one exception lands as ~30 unstitched events carrying none of the
+ ``error_type``/``exception_hash`` fields ``add_error_processor`` derives — which is what
+ ``exception_hash`` grouping and any error-rate threshold on the service are read against.
+ """
+ previous_excepthook = sys.excepthook
+ if not getattr(previous_excepthook, _INTERPRETER_TRACEBACK_HOOK_MARKER, False):
+
+ def excepthook(
+ exc_type: type[BaseException],
+ exc_value: BaseException,
+ exc_traceback: TracebackType | None,
+ ) -> None:
+ if issubclass(exc_type, (KeyboardInterrupt, SystemExit)) or not _log_interpreter_traceback(
+ "Uncaught exception", (exc_type, exc_value, exc_traceback)
+ ):
+ previous_excepthook(exc_type, exc_value, exc_traceback)
+
+ setattr(excepthook, _INTERPRETER_TRACEBACK_HOOK_MARKER, True)
+ sys.excepthook = excepthook
+
+ previous_threading_excepthook = threading.excepthook
+ if not getattr(previous_threading_excepthook, _INTERPRETER_TRACEBACK_HOOK_MARKER, False):
+ # Typed Any like codeblock_runner's unraisable hook: neither hook argument has a type
+ # CPython exposes at runtime, and these annotations are evaluated at import time.
+ def threading_excepthook(args: Any) -> None:
+ # threading's default hook drops SystemExit silently; keep that.
+ if args.exc_type is SystemExit or not _log_interpreter_traceback(
+ "Uncaught exception in thread",
+ (args.exc_type, args.exc_value, args.exc_traceback),
+ thread_name=args.thread.name if args.thread is not None else None,
+ ):
+ previous_threading_excepthook(args)
+
+ setattr(threading_excepthook, _INTERPRETER_TRACEBACK_HOOK_MARKER, True)
+ threading.excepthook = threading_excepthook
+
+ previous_unraisable_hook = sys.unraisablehook
+ if not getattr(previous_unraisable_hook, _INTERPRETER_TRACEBACK_HOOK_MARKER, False):
+
+ def unraisablehook(unraisable: Any) -> None:
+ # The default renders the object into the message; keeping it in its own field leaves
+ # `msg` low-cardinality enough to group on.
+ if not _log_interpreter_traceback(
+ "Exception ignored in interpreter callback",
+ (unraisable.exc_type, unraisable.exc_value, unraisable.exc_traceback),
+ unraisable_err_msg=unraisable.err_msg,
+ unraisable_object=_unraisable_object_repr(unraisable.object),
+ ):
+ previous_unraisable_hook(unraisable)
+
+ setattr(unraisablehook, _INTERPRETER_TRACEBACK_HOOK_MARKER, True)
+ sys.unraisablehook = unraisablehook
+
+
def setup_logger() -> None:
"""
Setup the logger with the specified format
@@ -1032,3 +1139,6 @@ def setup_logger() -> None:
asyncio_logger = logging.getLogger("asyncio")
asyncio_logger.filters = [f for f in asyncio_logger.filters if not isinstance(f, _DriverPipeNoiseFilter)]
asyncio_logger.addFilter(_DriverPipeNoiseFilter())
+
+ # Last, so the handler these hooks log through is already installed.
+ _install_interpreter_traceback_hooks()
diff --git a/skyvern/forge/sdk/routes/agent_protocol.py b/skyvern/forge/sdk/routes/agent_protocol.py
index 73f4db033..32b16645b 100644
--- a/skyvern/forge/sdk/routes/agent_protocol.py
+++ b/skyvern/forge/sdk/routes/agent_protocol.py
@@ -213,6 +213,7 @@ from skyvern.services import (
workflow_service,
)
from skyvern.services.pdf_import_service import pdf_import_service
+from skyvern.utils.organization_slug import is_org_slug_unique_violation
from skyvern.utils.url_validators import validate_webhook_url
from skyvern.utils.yaml_loader import format_yaml_error, safe_load_no_dates
from skyvern.webeye.actions.actions import Action
@@ -5458,6 +5459,12 @@ async def update_organization(
org_update: OrganizationUpdate,
current_org: Organization = Depends(org_auth_service.get_current_org),
) -> Organization:
+ if "slug" in org_update.model_fields_set and org_update.slug is None:
+ raise HTTPException(
+ status_code=http_status.HTTP_400_BAD_REQUEST,
+ detail="Organization slug cannot be cleared.",
+ )
+
if org_update.webhook_callback_url and org_update.webhook_callback_url != current_org.webhook_callback_url:
org_update.webhook_callback_url = validate_webhook_url(org_update.webhook_callback_url)
@@ -5520,20 +5527,30 @@ async def update_organization(
detail=f"{field_name} must reference a valid custom LLM for this organization",
)
- updated = await app.DATABASE.organizations.update_organization(
- current_org.organization_id,
- max_steps_per_run=org_update.max_steps_per_run,
- max_steps_per_workflow_run=org_update.max_steps_per_workflow_run,
- clear_max_steps_per_workflow_run=org_update.clear_max_steps_per_workflow_run,
- max_retries_per_step=org_update.max_retries_per_step,
- webhook_callback_url=org_update.webhook_callback_url,
- artifact_url_expiry_seconds=org_update.artifact_url_expiry_seconds,
- clear_artifact_url_expiry_seconds=org_update.clear_artifact_url_expiry_seconds,
- default_llm_key=org_update.default_llm_key,
- clear_default_llm_key=org_update.clear_default_llm_key,
- default_secondary_llm_key=org_update.default_secondary_llm_key,
- clear_default_secondary_llm_key=org_update.clear_default_secondary_llm_key,
- )
+ try:
+ updated = await app.DATABASE.organizations.update_organization(
+ current_org.organization_id,
+ slug=org_update.slug,
+ update_slug="slug" in org_update.model_fields_set,
+ max_steps_per_run=org_update.max_steps_per_run,
+ max_steps_per_workflow_run=org_update.max_steps_per_workflow_run,
+ clear_max_steps_per_workflow_run=org_update.clear_max_steps_per_workflow_run,
+ max_retries_per_step=org_update.max_retries_per_step,
+ webhook_callback_url=org_update.webhook_callback_url,
+ artifact_url_expiry_seconds=org_update.artifact_url_expiry_seconds,
+ clear_artifact_url_expiry_seconds=org_update.clear_artifact_url_expiry_seconds,
+ default_llm_key=org_update.default_llm_key,
+ clear_default_llm_key=org_update.clear_default_llm_key,
+ default_secondary_llm_key=org_update.default_secondary_llm_key,
+ clear_default_secondary_llm_key=org_update.clear_default_secondary_llm_key,
+ )
+ except IntegrityError as exc:
+ if "slug" not in org_update.model_fields_set or not is_org_slug_unique_violation(exc):
+ raise
+ raise HTTPException(
+ status_code=http_status.HTTP_409_CONFLICT,
+ detail="Organization slug is already in use.",
+ ) from exc
org_auth_service.invalidate_cached_org(current_org.organization_id)
return updated
diff --git a/skyvern/forge/sdk/routes/sdk.py b/skyvern/forge/sdk/routes/sdk.py
index aece662f5..ef5b054f4 100644
--- a/skyvern/forge/sdk/routes/sdk.py
+++ b/skyvern/forge/sdk/routes/sdk.py
@@ -5,12 +5,12 @@ from fastapi import Depends, HTTPException, status
from skyvern.core.script_generations.real_skyvern_page_ai import RealSkyvernPageAi
from skyvern.core.script_generations.script_skyvern_page import ScriptSkyvernPage
-from skyvern.exceptions import ScrapingFailed, SkyvernActionFailed
+from skyvern.exceptions import ScrapingFailed, ScreenshotTargetClosed, SkyvernActionFailed, SkyvernHTTPException
from skyvern.forge import app
from skyvern.forge.sdk.api.files import validate_download_url
from skyvern.forge.sdk.core import skyvern_context
from skyvern.forge.sdk.core.skyvern_context import SkyvernContext
-from skyvern.forge.sdk.db.enums import WorkflowRunTriggerType
+from skyvern.forge.sdk.db.enums import TaskType, WorkflowRunTriggerType
from skyvern.forge.sdk.routes.routers import base_router
from skyvern.forge.sdk.schemas.organizations import Organization
from skyvern.forge.sdk.schemas.sdk_actions import (
@@ -95,6 +95,7 @@ async def run_sdk_action(
status_code=status.HTTP_404_NOT_FOUND,
detail=f"Workflow {workflow_run.workflow_id} not found",
)
+ task_type = TaskType.general
else:
workflow = await app.WORKFLOW_SERVICE.create_empty_workflow(
organization,
@@ -112,9 +113,7 @@ async def run_sdk_action(
version=None,
trigger_type=WorkflowRunTriggerType.api,
)
- workflow_run = await app.WORKFLOW_SERVICE.mark_workflow_run_as_completed(
- workflow_run_id=workflow_run.workflow_run_id,
- )
+ task_type = TaskType.synthetic_sdk_action
task = await app.DATABASE.tasks.create_task(
organization_id=organization_id,
@@ -126,8 +125,14 @@ async def run_sdk_action(
workflow_run_id=workflow_run.workflow_run_id,
browser_session_id=browser_session_id,
browser_address=browser_address,
+ task_type=task_type,
)
+ if created_workflow_run:
+ workflow_run = await app.WORKFLOW_SERVICE.mark_workflow_run_as_completed(
+ workflow_run_id=workflow_run.workflow_run_id,
+ )
+
step = await app.DATABASE.tasks.create_step(
task.task_id,
order=0,
@@ -283,6 +288,37 @@ async def run_sdk_action(
error=e.reason,
)
raise HTTPException(status_code=status.HTTP_422_UNPROCESSABLE_CONTENT, detail=e.reason)
+ except ScreenshotTargetClosed as e:
+ await app.DATABASE.tasks.update_task(
+ task_id=task.task_id,
+ organization_id=organization_id,
+ status=TaskStatus.failed,
+ failure_reason=str(e),
+ )
+ LOG.warning(
+ "SDK action failed because the browser target was closed",
+ action_type=action.type,
+ browser_session_id=browser_session_id,
+ error=str(e),
+ )
+ raise HTTPException(
+ status_code=status.HTTP_422_UNPROCESSABLE_CONTENT,
+ detail="The browser page, context or browser was closed before the action could complete.",
+ )
+ except SkyvernHTTPException as e:
+ await app.DATABASE.tasks.update_task(
+ task_id=task.task_id,
+ organization_id=organization_id,
+ status=TaskStatus.failed,
+ failure_reason=str(e),
+ )
+ LOG.warning(
+ "SDK action failed with a typed HTTP error",
+ action_type=action.type,
+ status_code=e.status_code,
+ error=str(e),
+ )
+ raise
except Exception as e:
await app.DATABASE.tasks.update_task(
task_id=task.task_id,
diff --git a/skyvern/forge/sdk/routes/streaming/screencast.py b/skyvern/forge/sdk/routes/streaming/screencast.py
index 669044e41..aa4ab6ba9 100644
--- a/skyvern/forge/sdk/routes/streaming/screencast.py
+++ b/skyvern/forge/sdk/routes/streaming/screencast.py
@@ -22,6 +22,12 @@ LOG = structlog.get_logger()
DEFAULT_WIDTH = 1280
DEFAULT_HEIGHT = 720
ACTIVE_PAGE_POLL_INTERVAL = 0.5
+# A page-less context is bimodal in production: an ordinary tab swap or navigation clears within a
+# few seconds, while a viewer whose session has lost every tab stays empty for minutes and never
+# recovers. Hold the fast cadence past the transient band, then back off so a wedged viewer costs a
+# poll every 30s instead of two a second.
+ACTIVE_PAGE_DEGRADED_AFTER = 4.0
+ACTIVE_PAGE_MAX_POLL_INTERVAL = 30.0
LATENCY_BUCKETS_SECONDS: tuple[float, ...] = (
0.001,
0.002,
@@ -177,6 +183,18 @@ async def start_screencast_loop(
) -> None:
id_key = f"{entity_type}_id"
metric_attributes = {"entity_type": entity_type}
+ # The ids are locals here but never reach structlog: the streaming handlers run without a
+ # skyvern_context, so add_log_context has nothing to inject. Bind them explicitly, under the
+ # id_key alias too, so the entry/recovery pair is searchable per session rather than anonymous.
+ degraded_context: dict[str, str] = {
+ "entity_id": entity_id,
+ "entity_type": entity_type,
+ id_key: entity_id,
+ }
+ if organization_id:
+ degraded_context["organization_id"] = organization_id
+ if workflow_run_id:
+ degraded_context["workflow_run_id"] = workflow_run_id
cdp_session: CDPSession | None = None
attached_page: object | None = None
frame_queue: asyncio.Queue[tuple[str, float]] = asyncio.Queue(maxsize=2)
@@ -230,24 +248,18 @@ async def start_screencast_loop(
break
async def _on_frame(session: CDPSession, params: dict, received_at: float) -> None:
+ # Acked before the session check because Chrome withholds further frames until the last one
+ # is acked: a frame that lands while a swap is in flight is not displayed, but dropping it
+ # unacked would stall the session it came from.
+ asyncio.create_task(_ack_frame(session, params.get("sessionId", 0)))
if session is not cdp_session:
return
- data = params.get("data", "")
- session_id = params.get("sessionId", 0)
metadata = params.get("metadata", {})
if metadata:
_update_viewport_from_metadata(metadata)
- asyncio.create_task(_ack_frame(session, session_id))
- _queue_frame(data, received_at)
+ _queue_frame(params.get("data", ""), received_at)
- async def _stop_current_screencast() -> None:
- nonlocal cdp_session, attached_page
- if cdp_session is None:
- attached_page = None
- return
- session = cdp_session
- cdp_session = None
- attached_page = None
+ async def _discard_session(session: CDPSession) -> None:
try:
await session.send("Page.stopScreencast", {})
except Exception:
@@ -257,6 +269,15 @@ async def start_screencast_loop(
except Exception:
pass
+ async def _stop_current_screencast() -> None:
+ nonlocal cdp_session, attached_page
+ session = cdp_session
+ cdp_session = None
+ attached_page = None
+ if session is None:
+ return
+ await _discard_session(session)
+
async def _prime_current_frame(session: CDPSession, page: object) -> None:
try:
result = await session.send(
@@ -283,10 +304,9 @@ async def start_screencast_loop(
if page is attached_page and cdp_session is not None:
return
- await _stop_current_screencast()
- _drain_frame_queue()
+ # The replacement is built and confirmed before anything tears down what the viewer is
+ # watching, so a page that cannot be attached leaves the running stream alone.
next_session = await page.context.new_cdp_session(page) # type: ignore[attr-defined]
- cdp_session = next_session
next_session.on(
"Page.screencastFrame",
lambda params: asyncio.create_task(_on_frame(next_session, params, time.monotonic())),
@@ -302,9 +322,17 @@ async def start_screencast_loop(
},
)
except (asyncio.CancelledError, Exception):
- await _stop_current_screencast()
+ await _discard_session(next_session)
raise
+ # Adopting and draining without an await in between is what keeps the swap clean: frames the
+ # replacement already emitted are still queued (and acked) afterwards, while frames from the
+ # page being left behind are rejected by _on_frame instead of surviving the drain.
+ previous_session = cdp_session
+ cdp_session = next_session
attached_page = page
+ _drain_frame_queue()
+ if previous_session is not None:
+ await _discard_session(previous_session)
await _prime_current_frame(next_session, page)
LOG.info(
"CDP screencast started",
@@ -357,8 +385,17 @@ async def start_screencast_loop(
)
async def _active_page_monitor_loop() -> None:
+ interval = ACTIVE_PAGE_POLL_INTERVAL
+ degraded_since: float | None = None
+ reported = False
+
while True:
- await asyncio.sleep(ACTIVE_PAGE_POLL_INTERVAL)
+ await asyncio.sleep(interval)
+ # Degraded means the screencast is not following the current working page: there is
+ # none, or there is one that will not attach while the viewer keeps seeing the page it
+ # was already on. Both back off, since retrying an unattachable page at 2 Hz is the
+ # same pathology as polling for one that does not exist.
+ following = False
try:
page = await _resolve_working_page(
browser_state,
@@ -370,6 +407,7 @@ async def start_screencast_loop(
)
if page is not None and page is not attached_page:
await _attach_to_page(page)
+ following = page is not None
except Exception:
LOG.debug(
"Could not refresh CDP screencast active page",
@@ -378,6 +416,35 @@ async def start_screencast_loop(
exc_info=True,
)
+ now = time.monotonic()
+ if following:
+ if reported and degraded_since is not None:
+ LOG.info(
+ "Live view is following the active page again",
+ **degraded_context,
+ degraded_for_seconds=round(now - degraded_since, 1),
+ )
+ interval = ACTIVE_PAGE_POLL_INTERVAL
+ degraded_since = None
+ reported = False
+ continue
+
+ if degraded_since is None:
+ degraded_since = now
+ degraded_for = now - degraded_since
+ if degraded_for < ACTIVE_PAGE_DEGRADED_AFTER:
+ continue
+
+ interval = min(interval * 2, ACTIVE_PAGE_MAX_POLL_INTERVAL)
+ if not reported:
+ reported = True
+ LOG.warning(
+ "Live view cannot follow the active page; backing off",
+ **degraded_context,
+ degraded_for_seconds=round(degraded_for, 1),
+ max_poll_interval_seconds=ACTIVE_PAGE_MAX_POLL_INTERVAL,
+ )
+
try:
page = await _resolve_working_page(browser_state, entity_id, entity_type, workflow_run_id, organization_id)
if page is None:
diff --git a/skyvern/forge/sdk/schemas/organizations.py b/skyvern/forge/sdk/schemas/organizations.py
index d0a69139d..65e332f4b 100644
--- a/skyvern/forge/sdk/schemas/organizations.py
+++ b/skyvern/forge/sdk/schemas/organizations.py
@@ -1,8 +1,9 @@
from datetime import datetime
-from pydantic import BaseModel, ConfigDict, EmailStr, Field
+from pydantic import BaseModel, ConfigDict, EmailStr, Field, field_validator
from skyvern.forge.sdk.db.enums import OrganizationAuthTokenType
+from skyvern.utils.organization_slug import is_valid_org_slug
class Organization(BaseModel):
@@ -10,6 +11,7 @@ class Organization(BaseModel):
organization_id: str
organization_name: str
+ slug: str | None = None
webhook_callback_url: str | None = None
max_steps_per_run: int | None = None
max_steps_per_workflow_run: int | None = None
@@ -185,6 +187,10 @@ class GetOrganizationAPIKeysResponse(BaseModel):
class OrganizationUpdate(BaseModel):
+ slug: str | None = Field(
+ default=None,
+ description="Set a stable organization slug. Omit this field to keep the current slug. Explicit null is rejected.",
+ )
max_steps_per_run: int | None = Field(default=None, ge=1)
max_steps_per_workflow_run: int | None = Field(default=None, ge=1)
clear_max_steps_per_workflow_run: bool = Field(
@@ -245,3 +251,10 @@ class OrganizationUpdate(BaseModel):
"exclusive with a non-null value in ``default_secondary_llm_key`` (the clear flag wins)."
),
)
+
+ @field_validator("slug")
+ @classmethod
+ def validate_slug(cls, value: str | None) -> str | None:
+ if value is not None and not is_valid_org_slug(value):
+ raise ValueError("slug must match ^[a-z0-9-]{1,20}$")
+ return value
diff --git a/skyvern/forge/sdk/schemas/tasks.py b/skyvern/forge/sdk/schemas/tasks.py
index d656a8a6e..bb356a642 100644
--- a/skyvern/forge/sdk/schemas/tasks.py
+++ b/skyvern/forge/sdk/schemas/tasks.py
@@ -2,7 +2,7 @@ from __future__ import annotations
from datetime import datetime
from enum import StrEnum
-from typing import Any
+from typing import Any, Literal
from fastapi import status
from pydantic import BaseModel, Field, field_serializer, field_validator, model_validator
@@ -147,6 +147,12 @@ class TaskBase(BaseModel):
class TaskRequest(TaskBase):
+ task_type: Literal[TaskType.general, TaskType.validation, TaskType.action] | None = Field(
+ default=TaskType.general,
+ description="The type of the task",
+ examples=[TaskType.general, TaskType.validation, TaskType.action],
+ )
+
url: str = Field(
...,
description="Starting URL for the task.",
diff --git a/skyvern/forge/sdk/schemas/workflow_copilot.py b/skyvern/forge/sdk/schemas/workflow_copilot.py
index 3ad6dd826..34e0082f9 100644
--- a/skyvern/forge/sdk/schemas/workflow_copilot.py
+++ b/skyvern/forge/sdk/schemas/workflow_copilot.py
@@ -327,6 +327,10 @@ class WorkflowCopilotToolCallUpdate(BaseModel):
tool_input: dict = Field(default_factory=dict, description="Sanitized tool input (no secrets)")
iteration: int = Field(..., description="Agent loop iteration number")
tool_call_id: str = Field(..., description="Unique ID for this tool invocation")
+ timestamp: datetime | None = Field(
+ None,
+ description="Server timestamp for this event; the same clock read is persisted on the matching activity entry.",
+ )
class WorkflowCopilotToolResultUpdate(BaseModel):
@@ -357,6 +361,10 @@ class WorkflowCopilotToolResultUpdate(BaseModel):
"passed or failed; None for non-run tools."
),
)
+ timestamp: datetime | None = Field(
+ None,
+ description="Server timestamp for this event; the same clock read is persisted on the matching activity entry.",
+ )
class WorkflowCopilotCondensingUpdate(BaseModel):
diff --git a/skyvern/forge/sdk/services/org_auth_service.py b/skyvern/forge/sdk/services/org_auth_service.py
index 3bf01e07b..8e5c13963 100644
--- a/skyvern/forge/sdk/services/org_auth_service.py
+++ b/skyvern/forge/sdk/services/org_auth_service.py
@@ -14,6 +14,7 @@ from pydantic import ValidationError
from skyvern.config import settings
from skyvern.forge import app
+from skyvern.forge.request_logging import set_request_organization
from skyvern.forge.sdk.core import skyvern_context
from skyvern.forge.sdk.db.agent_db import AgentDB
from skyvern.forge.sdk.models import TokenPayload
@@ -185,11 +186,11 @@ async def get_current_org(
def apply_request_org_context(organization: Organization) -> None:
- """Populate skyvern_context + OTEL span with the resolved organization.
+ """Populate skyvern_context, the api.raw_request record, and the OTEL span with the org.
- Shared by get_current_org and get_current_caller_context so the cached
- helper paths (which short-circuit the per-helper context-setting on cache
- hits) still leave a consistent request-scoped context for downstream routes.
+ Every request-scoped auth path funnels through here so a cache hit — which
+ short-circuits the per-helper context-setting — still leaves a consistent
+ request-scoped identity for downstream routes and for request logging.
"""
try:
ctx = skyvern_context.current()
@@ -198,6 +199,8 @@ def apply_request_org_context(organization: Organization) -> None:
ctx.organization_name = organization.organization_name
except Exception:
pass
+ # The request-logging middleware sits outside skyvern_context, so it needs its own stamp.
+ set_request_organization(organization.organization_id, organization.organization_name)
if not settings.OTEL_ENABLED:
return
try:
@@ -296,13 +299,20 @@ async def get_current_org_with_api_token(
async def get_current_org_with_authentication(
authorization: Annotated[str | None, Header()] = None,
+ x_posthog_attribution: Annotated[
+ str | None,
+ Header(alias=POSTHOG_ATTRIBUTION_HEADER, include_in_schema=False),
+ ] = None,
) -> Organization:
if not authorization:
raise HTTPException(
status_code=status.HTTP_403_FORBIDDEN,
detail="Invalid credentials",
)
- return await authenticate_helper(authorization)
+ return await authenticate_helper(
+ authorization,
+ attribution_header=x_posthog_attribution,
+ )
def _extract_bearer_token(authorization: str) -> str | None:
@@ -342,12 +352,7 @@ async def authenticate_helper(
detail="Invalid credentials",
)
- # set organization_id in skyvern context and log context
- context = skyvern_context.current()
- if context:
- context.organization_id = organization.organization_id
- context.organization_name = organization.organization_name
-
+ apply_request_org_context(organization)
return organization
@@ -589,12 +594,6 @@ async def _get_current_org_cached(x_api_key: str, db: AgentDB) -> Organization:
invalidation_generation = _current_org_cache_invalidation_generation
validation = await resolve_org_from_api_key(x_api_key, db)
- # set organization_id in skyvern context and log context
- context = skyvern_context.current()
- if context:
- context.organization_id = validation.organization.organization_id
- context.organization_name = validation.organization.organization_name
-
if invalidation_generation == _current_org_cache_invalidation_generation:
_current_org_cache[cache_key] = validation.organization
return validation.organization
@@ -613,12 +612,11 @@ async def get_current_org_cached(x_api_key: str, db: AgentDB) -> Organization:
db,
token_types=(OrganizationAuthTokenType.ui_session,),
)
- context = skyvern_context.current()
- if context:
- context.organization_id = validation.organization.organization_id
- context.organization_name = validation.organization.organization_name
- return validation.organization
- return await _get_current_org_cached(x_api_key, db)
+ organization = validation.organization
+ else:
+ organization = await _get_current_org_cached(x_api_key, db)
+ apply_request_org_context(organization)
+ return organization
def invalidate_cached_org(organization_id: str) -> None:
diff --git a/skyvern/forge/sdk/workflow/context_manager.py b/skyvern/forge/sdk/workflow/context_manager.py
index f73e40e61..0b30df198 100644
--- a/skyvern/forge/sdk/workflow/context_manager.py
+++ b/skyvern/forge/sdk/workflow/context_manager.py
@@ -1550,7 +1550,7 @@ class WorkflowRunContext:
self, parameter: OutputParameter, value: dict[str, Any] | list | str | None
) -> None:
if parameter.key in self.values:
- LOG.warning(f"Output parameter {parameter.output_parameter_id} already has a registered value, overwriting")
+ LOG.debug(f"Output parameter {parameter.output_parameter_id} already has a registered value, overwriting")
self.values[parameter.key] = value
self.register_block_reference_variable_from_output_parameter(parameter, value)
@@ -1580,7 +1580,7 @@ class WorkflowRunContext:
merged = {**current_value, **block_reference_value}
block_reference_value = merged
else:
- LOG.warning(f"Parameter {block_label} already has a value in workflow run context, overwriting")
+ LOG.debug(f"Parameter {block_label} already has a value in workflow run context, overwriting")
self.values[block_label] = block_reference_value
self.workflow_run_outputs[block_label] = block_reference_value
@@ -1711,6 +1711,15 @@ class WorkflowRunContext:
def totp_secret_value_key(self, totp_secret_id: str) -> str:
return f"{totp_secret_id}_value"
+ def is_registered_credential_parameter_key(self, key: str) -> bool:
+ """Whether ``key`` was registered as one of the credential parameter types.
+
+ Ordinary workflow/run inputs can share the dict-with-``totp`` shape but are not
+ credentials; only a registered credential parameter owns a credential-backed TOTP
+ secret. Callers use this to keep arbitrary run inputs out of credential-only paths.
+ """
+ return isinstance(self.parameters.get(key), _CREDENTIAL_PARAMETER_TYPES)
+
def find_credential_parameter_key_for_secret(self, secret_id: str) -> str | None:
for parameter_key, value in self.values.items():
if not isinstance(value, dict):
diff --git a/skyvern/forge/sdk/workflow/exceptions.py b/skyvern/forge/sdk/workflow/exceptions.py
index 20364a810..123fa15ea 100644
--- a/skyvern/forge/sdk/workflow/exceptions.py
+++ b/skyvern/forge/sdk/workflow/exceptions.py
@@ -192,9 +192,13 @@ class InvalidCodeBlockStep(WorkflowDefinitionValidationException):
)
-class InvalidWaitBlockTime(SkyvernException):
- def __init__(self, max_sec: int) -> None:
- super().__init__(f"Invalid wait time for wait block, it should be a number between 0 and {max_sec}.")
+class InvalidWaitBlockTime(WorkflowDefinitionValidationException):
+ def __init__(self, block_label: str, wait_sec: int, max_sec: int) -> None:
+ super().__init__(
+ f"Invalid wait time {wait_sec} for wait block '{block_label}'. "
+ f"It must be a whole number of seconds between 1 and {max_sec}.",
+ status_code=status.HTTP_422_UNPROCESSABLE_CONTENT,
+ )
class FailedToFormatJinjaStyleParameter(SkyvernException):
diff --git a/skyvern/forge/sdk/workflow/models/block.py b/skyvern/forge/sdk/workflow/models/block.py
index 1167d35f4..45f3fc508 100644
--- a/skyvern/forge/sdk/workflow/models/block.py
+++ b/skyvern/forge/sdk/workflow/models/block.py
@@ -48,7 +48,6 @@ from jinja2.sandbox import SandboxedEnvironment
from jsonschema import Draft202012Validator
from jsonschema.exceptions import ValidationError
from opentelemetry import trace as otel_trace
-from playwright.async_api import Error as PlaywrightError
from playwright.async_api import Page
from pydantic import BaseModel, Field, PrivateAttr, model_validator
from sqlalchemy.exc import InterfaceError, OperationalError
@@ -254,6 +253,7 @@ from skyvern.utils.url_validators import (
from skyvern.webeye.actions.action_types import ActionType
from skyvern.webeye.actions.actions import Action, ActionStatus
from skyvern.webeye.browser_artifacts import DownloadBinding
+from skyvern.webeye.browser_driver_errors import is_driver_error
from skyvern.webeye.browser_factory import rebind_download_dir
from skyvern.webeye.browser_object_predicates import is_page_like
from skyvern.webeye.browser_state import BrowserState, get_browser_state_diagnostic
@@ -925,7 +925,7 @@ class Block(BaseModel, abc.ABC):
if isinstance(current_value, dict):
block_reference_data.update(current_value)
else:
- LOG.warning(
+ LOG.debug(
f"Parameter {self.label} has a registered reference value, going to overwrite it by block metadata"
)
@@ -1178,7 +1178,7 @@ class Block(BaseModel, abc.ABC):
# create a screenshot
browser_state = app.BROWSER_MANAGER.get_for_workflow_run(workflow_run_id)
if not browser_state:
- LOG.warning(
+ LOG.info(
"No browser state found when creating workflow_run_block",
workflow_run_id=workflow_run_id,
workflow_run_block_id=workflow_run_block_id,
@@ -5549,7 +5549,7 @@ async def wrapper({default_args}):
return True
if engine_selection is not None:
return engine_selection.is_engine_error(exception) is True
- return isinstance(exception, PlaywrightError) # locator/timeout/navigation errors subclass this
+ return is_driver_error(exception) # locator/timeout/navigation errors subclass the driver's base
async def _finalize_recovery_block(
self,
diff --git a/skyvern/forge/sdk/workflow/workflow_definition_converter.py b/skyvern/forge/sdk/workflow/workflow_definition_converter.py
index 14ed99af3..97ffe575d 100644
--- a/skyvern/forge/sdk/workflow/workflow_definition_converter.py
+++ b/skyvern/forge/sdk/workflow/workflow_definition_converter.py
@@ -881,7 +881,11 @@ def block_yaml_to_block(
elif block_yaml.block_type == BlockType.WAIT:
if block_yaml.wait_sec <= 0 or block_yaml.wait_sec > settings.WORKFLOW_WAIT_BLOCK_MAX_SEC:
- raise InvalidWaitBlockTime(settings.WORKFLOW_WAIT_BLOCK_MAX_SEC)
+ raise InvalidWaitBlockTime(
+ block_yaml.label,
+ block_yaml.wait_sec,
+ settings.WORKFLOW_WAIT_BLOCK_MAX_SEC,
+ )
return WaitBlock(
**base_kwargs,
diff --git a/skyvern/forge/taskv3/engine.py b/skyvern/forge/taskv3/engine.py
index ff87f1a01..d7b7743f8 100644
--- a/skyvern/forge/taskv3/engine.py
+++ b/skyvern/forge/taskv3/engine.py
@@ -29,7 +29,14 @@ import structlog
from skyvern.config import settings
from skyvern.forge.sdk.api.llm.exceptions import LLMProviderErrorRetryableTask
-from skyvern.forge.taskv3.loop import LoopOutcome, ToolSpec, make_finish_tool, run_agent_tool_loop
+from skyvern.forge.taskv3.loop import (
+ DEFAULT_MAX_SETTLE_DEFERRALS,
+ ActivityRecency,
+ LoopOutcome,
+ ToolSpec,
+ make_finish_tool,
+ run_agent_tool_loop,
+)
from skyvern.forge.taskv3.tools import PageProvider, build_browser_tools
LOG = structlog.get_logger()
@@ -163,6 +170,7 @@ async def run_task_v3_agent_loop(
resolve_typed_text: Callable[[str], Any] | None = None,
page_free: bool = False,
page_fingerprint: Callable[[], Awaitable[str | None]] | None = None,
+ max_settle_deferrals: int = DEFAULT_MAX_SETTLE_DEFERRALS,
) -> LoopOutcome:
"""Run one Task V3 task to completion against `page`, returning the loop outcome.
@@ -171,7 +179,8 @@ async def run_task_v3_agent_loop(
and wall-clock budgets bound cost beyond the turn/tool-call caps. When a
`page_fingerprint` sampler is provided, a finish(completed) on an unsettled page IS forced back
for a bounded re-verification turn; without one, pre-finish re-verification is prompt guidance
- only."""
+ only. `max_settle_deferrals=0` disables that completed-side re-verification while leaving the
+ failure-evidence gate, which shares the sampler, intact."""
# 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 = (
@@ -188,10 +197,13 @@ async def run_task_v3_agent_loop(
# The fingerprint sampler is caller-built (browser semantics — e.g. peeking without page
# recovery — live with the dispatcher); the finish gate owns the settle wait, bounded by this
# run's deadline and cancellation so probing cannot overrun either. Page-free runs never probe.
+ activity = ActivityRecency()
finish_tool = make_finish_tool(
page_fingerprint=None if page_free else page_fingerprint,
+ max_settle_deferrals=max_settle_deferrals,
should_cancel=should_cancel,
deadline_at=time.monotonic() + deadline_seconds if deadline_seconds is not None else None,
+ activity=activity,
)
tools = browser_tools + (extra_tools or []) + [finish_tool]
base_system_prompt = PAGE_FREE_SYSTEM_PROMPT if page_free else SYSTEM_PROMPT
@@ -212,6 +224,7 @@ async def run_task_v3_agent_loop(
deadline_seconds=deadline_seconds,
retryable_call_exceptions=(LLMProviderErrorRetryableTask,),
max_call_retries=DEFAULT_MAX_CALL_RETRIES,
+ activity=activity,
)
LOG.info(
"taskv3 engine loop finished",
diff --git a/skyvern/forge/taskv3/loop.py b/skyvern/forge/taskv3/loop.py
index a7221dea7..00068927e 100644
--- a/skyvern/forge/taskv3/loop.py
+++ b/skyvern/forge/taskv3/loop.py
@@ -172,6 +172,67 @@ ACTION_LOOP_TERMINATE_AFTER = 6
# Facetable sibling of PERCEPTION_STALL_REASON_PREFIX; same dashboard contract.
ACTION_LOOP_REASON_PREFIX = "action_loop:"
+# Failure-evidence gate: a finish(failed) issued shortly after a submit-class action or a
+# solve_captcha attempt is held for ONE evidence turn, because submissions and captcha protocols
+# complete asynchronously — the sampled false-negative verdicts fired 2-7s after the model's last
+# look while the page went on to show the submission confirmation. Trigger tools are the ones whose
+# page effects can land after their tool result; the window is in loop turns so intervening
+# perception does NOT disarm it (the state can flip after the last observe while a protocol is in
+# flight). The true verdict-to-flip latency is unmeasured in the sampled replays: the quiescence
+# wait exits on the first stable fingerprint pair (so honest gated failures pay ~one sample), the
+# cap only bounds a still-mutating page, and the effective evidence window is dominated by the
+# deferral round-trip itself (one LLM turn + the observe).
+# Completed-side settle deferrals. 0 disables that gate while leaving the failure-evidence gate
+# (which shares the fingerprint sampler) intact.
+DEFAULT_MAX_SETTLE_DEFERRALS = 2
+FAILURE_EVIDENCE_WINDOW_TURNS = 5
+FAILURE_EVIDENCE_SETTLE_MAX_SECONDS = 8.0
+# A deferral needs room for its corrected cycle; without it the gate would convert an honest
+# failure verdict into budget_exhausted (a budget cap landing mid-deferral). The worst-case cycle
+# is wait + observe + re-finish — the deferral message invites an optional brief wait — so both
+# the turn and tool-call reservations are 3, the latter read from a per-call refreshed counter.
+# The deadline headroom must additionally fund the settle cap plus the cycle's LLM round trips.
+FAILURE_EVIDENCE_MIN_DEADLINE_HEADROOM_SECONDS = 60.0
+FAILURE_EVIDENCE_MIN_TOOL_CALLS = 3
+FAILURE_EVIDENCE_MIN_TURNS = 3
+
+
+def _arms_failure_evidence(tool_name: str, args: dict[str, Any], ok: bool) -> bool:
+ """solve_captcha arms on ANY dispatch — its "not solved" error is exactly the verdict the async
+ protocol can contradict. Other actions arm only when they reached the page AND in their
+ submit-shaped form: any click, an Enter press, or a type that pressed Enter."""
+ if tool_name == "solve_captcha":
+ return True
+ if not ok:
+ return False
+ if tool_name == "click":
+ # Deliberately broad: the loop has no submit-classification for click targets, and
+ # narrowing by label/selector text is the marker-parsing this design avoids.
+ return True
+ if tool_name == "press_key":
+ return str(args.get("key", "")).strip().lower() in ("enter", "return", "numpadenter")
+ if tool_name == "type":
+ return bool(args.get("press_enter"))
+ return False
+
+
+@dataclass
+class ActivityRecency:
+ """Written by the tool loop each turn/action, read by the finish tool's failure-evidence gate."""
+
+ turn: int = 0
+ turns_remaining: int | None = None
+ tool_calls_remaining: int | None = None
+ tokens_remaining: int | None = None
+ last_turn_tokens: int = 0
+ last_trigger_turn: int | None = None
+ # True while any perception tool's identical-snapshot streak is one short of the stall
+ # terminator: a deferral-forced observe must never be the snapshot that trips it.
+ perception_stall_imminent: bool = False
+
+ def armed(self, window: int = FAILURE_EVIDENCE_WINDOW_TURNS) -> bool:
+ return self.last_trigger_turn is not None and (self.turn - self.last_trigger_turn) <= window
+
def _unblocker_options(available_tools: set[str]) -> list[str]:
options = []
@@ -226,10 +287,13 @@ def _append_skipped_tool_results(
def make_finish_tool(
page_fingerprint: Callable[[], Awaitable[str | None]] | None = None,
- max_settle_deferrals: int = 2,
+ max_settle_deferrals: int = DEFAULT_MAX_SETTLE_DEFERRALS,
should_cancel: Callable[[], Awaitable[bool]] | None = None,
deadline_at: float | None = None,
settle_wait_seconds: float = 0.7,
+ activity: ActivityRecency | None = None,
+ max_failure_deferrals: int = 1,
+ failure_settle_max_seconds: float = FAILURE_EVIDENCE_SETTLE_MAX_SECONDS,
) -> ToolSpec:
"""`page_fingerprint` samples an opaque fingerprint of the page's rendered content (None when no
page is available). A finish(completed) is deferred (bounded by `max_settle_deferrals`, then
@@ -237,8 +301,40 @@ def make_finish_tool(
the settled state instead of a mid-render shell — delayed loads otherwise produce stochastic
false completions. A sampling error is unknown, not settled: it defers. The wait between samples
is capped at `deadline_at` (time.monotonic clock) and abandoned once `should_cancel` reports
- True, so probing cannot outlive the loop's own bounds."""
+ True, so probing cannot outlive the loop's own bounds.
+
+ The symmetric failure side: when `activity` reports recent submit-class/captcha activity, a
+ finish(failed) is held for ONE evidence turn (`max_failure_deferrals`, per run like the
+ completed-side cap, not per verdict attempt) — a quiescence wait
+ bounded by `failure_settle_max_seconds`, then a deferral asking the model to re-observe —
+ because async submissions and captcha protocols otherwise produce false-negative verdicts.
+ terminated is never gated on either side."""
deferrals = 0
+ failure_deferrals = 0
+
+ async def _quiesced() -> bool:
+ """Bounded wait for the page to stop mutating before the failure verdict's evidence turn.
+ Returns False when there is no page to observe (a deferral would burn a turn for nothing)."""
+ assert page_fingerprint is not None # gated by the caller's None check
+ prev = await page_fingerprint()
+ if prev is None:
+ return False
+ cap_at = time.monotonic() + failure_settle_max_seconds
+ while True:
+ wait = min(settle_wait_seconds, cap_at - time.monotonic())
+ if deadline_at is not None:
+ wait = min(wait, deadline_at - time.monotonic())
+ if wait <= 0:
+ return True
+ await asyncio.sleep(wait)
+ if should_cancel is not None and await should_cancel():
+ return True # defer: the loop's cancellation check ends the run before another turn
+ current = await page_fingerprint()
+ if current is None:
+ return False
+ if current == prev:
+ return True
+ prev = current
async def _settled() -> bool:
assert page_fingerprint is not None # gated by the caller's None check
@@ -255,7 +351,7 @@ def make_finish_tool(
return first == await page_fingerprint()
async def handler(args: dict[str, Any]) -> ToolResult:
- nonlocal deferrals
+ nonlocal deferrals, failure_deferrals
status = args.get("status")
if status not in ("completed", "failed", "terminated"):
return ToolResult.error(
@@ -276,6 +372,53 @@ def make_finish_tool(
"present in the loaded content (not a loading indicator or empty container), "
"then finish again."
)
+ if (
+ status == "failed"
+ and activity is not None
+ and page_fingerprint is not None
+ and failure_deferrals < max_failure_deferrals
+ and activity.armed()
+ # The corrected cycle needs budget for its worst case (wait + observe + re-finish);
+ # without headroom on every budget axis a deferral would convert an honest failure
+ # into budget_exhausted (or, for a stall-streak one short of the terminator, into a
+ # generic stall termination that replaces the model's accurate reason).
+ and (activity.turns_remaining is None or activity.turns_remaining >= FAILURE_EVIDENCE_MIN_TURNS)
+ and (
+ activity.tool_calls_remaining is None
+ or activity.tool_calls_remaining >= FAILURE_EVIDENCE_MIN_TOOL_CALLS
+ )
+ # The token margin is deliberately approximate: sized off the triggering turn, while
+ # the deferral turns carry a slightly larger transcript.
+ and (
+ activity.tokens_remaining is None
+ or activity.tokens_remaining >= FAILURE_EVIDENCE_MIN_TURNS * max(activity.last_turn_tokens, 1)
+ )
+ and not activity.perception_stall_imminent
+ and (
+ deadline_at is None or deadline_at - time.monotonic() >= FAILURE_EVIDENCE_MIN_DEADLINE_HEADROOM_SECONDS
+ )
+ ):
+ should_defer = True
+ try:
+ # False only when there is no page to observe; cancellation mid-wait still defers
+ # (the loop's own cancel check ends the run first).
+ should_defer = await _quiesced()
+ except Exception:
+ pass # unknown page state still defers: the model's re-observe is the evidence step
+ if should_defer:
+ failure_deferrals += 1
+ LOG.info("taskv3 finish failure deferred for evidence", turn=activity.turn)
+ return ToolResult.error(
+ "failure verdict held for one evidence check: it follows recent page actions or "
+ "a captcha attempt whose effects can land after your last look — submissions and "
+ "captcha protocols often complete asynchronously, so the page may no longer show "
+ "the state this verdict was based on. Re-observe the page once (waiting briefly "
+ "first if it may still be processing): only a positive confirmation of the goal "
+ "(e.g. a submission confirmation banner) justifies finishing with "
+ "status=completed; if it still shows the blocked or failed state, or shows no "
+ "positive confirmation at all, finish with status=failed again and the verdict "
+ "will stand."
+ )
return ToolResult.ok(
content="Task attempt ended. No further actions are permitted.",
data={
@@ -367,6 +510,7 @@ async def run_agent_tool_loop(
stall_terminate_after: int | None = PERCEPTION_STALL_TERMINATE_AFTER,
action_nudge_after: int | None = ACTION_LOOP_NUDGE_AFTER,
action_terminate_after: int | None = ACTION_LOOP_TERMINATE_AFTER,
+ activity: ActivityRecency | None = None,
) -> LoopOutcome:
tool_by_name = {tool.name: tool for tool in tools}
openai_tools = [tool.to_openai_tool() for tool in tools]
@@ -448,6 +592,10 @@ async def run_agent_tool_loop(
outcome = LoopOutcome("budget_exhausted", f"max_tool_calls ({max_tool_calls}) reached")
break
turns += 1
+ if activity is not None:
+ activity.turn = turns
+ activity.turns_remaining = max_turns - turns
+ activity.tool_calls_remaining = max_tool_calls - total_tool_calls
# Elide superseded perception results before re-sending the transcript, so a perception-heavy
# run can't balloon the context to the token backstop (the pre-compaction runaway mode).
@@ -504,6 +652,9 @@ async def run_agent_tool_loop(
if not turn_tokens:
turn_tokens = (_get(usage, "prompt_tokens") or 0) + (_get(usage, "completion_tokens") or 0)
total_tokens += int(turn_tokens or 0)
+ if activity is not None:
+ activity.last_turn_tokens = int(turn_tokens or 0)
+ activity.tokens_remaining = None if max_tokens is None else max_tokens - total_tokens
text = _extract_text(response)
tool_calls = _extract_tool_calls(response)
@@ -547,6 +698,10 @@ async def run_agent_tool_loop(
_append_skipped_tool_results(messages, tool_calls[idx:], "action-step budget reached")
break
total_tool_calls += 1
+ if activity is not None:
+ # Refreshed per call, not per turn: a batched action+finish turn must not defer on
+ # a stale turn-start snapshot (the conversion the headroom guard exists to prevent).
+ activity.tool_calls_remaining = max_tool_calls - total_tool_calls
tool_started_at = time.monotonic()
if spec is None:
result = ToolResult.error(f"unknown_tool: {tool_name}")
@@ -606,6 +761,10 @@ async def run_agent_tool_loop(
prev = stall_counts.get(tool_name)
identical_count = prev[1] + 1 if prev is not None and prev[0] == result.content else 1
stall_counts[tool_name] = (result.content, identical_count)
+ if activity is not None and stall_terminate_after is not None:
+ activity.perception_stall_imminent = any(
+ count >= stall_terminate_after - 1 for _, count in stall_counts.values()
+ )
if stall_terminate_after is not None and identical_count >= stall_terminate_after:
LOG.info(
"taskv3 loop perception stalled", tool=tool_name, identical_count=identical_count, turn=turns
@@ -660,6 +819,8 @@ async def run_agent_tool_loop(
round_actions.append((tool_name, args, result.status == "ok"))
if spec.billable and result.status == "ok":
billable_actions.append(tool_name)
+ if activity is not None and _arms_failure_evidence(tool_name, args, result.status == "ok"):
+ activity.last_trigger_turn = turns
if spec is not None and spec.terminal and result.status == "ok":
data = result.data or {}
diff --git a/skyvern/forge/taskv3/tools.py b/skyvern/forge/taskv3/tools.py
index cb9995ef7..e67d1551f 100644
--- a/skyvern/forge/taskv3/tools.py
+++ b/skyvern/forge/taskv3/tools.py
@@ -351,24 +351,58 @@ _OBSERVE_JS = (
// Monotonic across observe() calls (persisted on window), and never reassigned on an element that
// already has one, so a data-tv3 marker always denotes the same element. Resetting the counter per
// call let a selector remembered from an earlier observe silently resolve to a different node.
- if (typeof window.__tv3_next !== 'number') window.__tv3_next = 0;
+ if (!Number.isInteger(window.__tv3_next) || window.__tv3_next < 0 || window.__tv3_next > 1e9) window.__tv3_next = 0;
let i = 0;
+ let dropped = 0;
let lastGroup = '';
for (const el of els) {
+ // A form exposes its named controls as its own properties, so <input name="tagName"> makes
+ // el.tagName that input. Every read below can therefore be a clobbered non-function, and the
+ // loop is inside page.evaluate: one throw costs the whole element list, not one element.
+ try {
const r = el.getBoundingClientRect();
if (r.width === 0 || r.height === 0) continue;
let selector = null;
- const uniq = (s) => { try { return document.querySelectorAll(s).length === 1; } catch (e) { return false; } };
- if (el.id) { const s = '#' + CSS.escape(el.id); if (uniq(s)) selector = s; }
- if (!selector && el.getAttribute('data-testid')) { const s = '[data-testid="' + el.getAttribute('data-testid') + '"]'; if (uniq(s)) selector = s; }
- if (!selector && el.name) { const s = el.tagName.toLowerCase() + '[name="' + el.name + '"]'; if (uniq(s)) selector = s; }
+ // Unique is not enough -- it must be THIS element. A page can pre-seed a marker or exploit
+ // U+0000 folding to U+FFFD so a selector matches exactly one node that is a different one.
+ const resolves = (s) => { try { return document.querySelectorAll(s).length === 1 && document.querySelector(s) === el; } catch (e) { return false; } };
+ // Values here are page-controlled: an unescaped `"` closes the selector and turns it into a
+ // selector list aimed at an element of the page's choosing, which still resolves uniquely.
+ // String() because form named getters make el.id/el.name return an ELEMENT, not a string.
+ const attr = (name, value) => '[' + name + '="' + String(value).replace(/\\/g, '\\\\').replace(/"/g, '\\"') + '"]';
+ // The model copies these selectors back verbatim, and an escape sequence does not survive that:
+ // `#\31 abc` addresses a different codepoint the moment its terminating space is dropped. The
+ // escape being a no-op is exactly the condition for the id needing no escaping. The trim check
+ // is separate: Playwright trims the selector string, so `#email<NBSP>` -- which CSS.escape leaves
+ // alone, being above U+007F -- reaches the page as `#email` and silently selects a different
+ // element. Only the tail can be trimmed away; a leading one sits behind the `#` and survives.
+ if (el.id) {
+ const raw = String(el.id);
+ const esc = window.CSS && CSS.escape ? CSS.escape(raw) : null;
+ const s = esc === raw && raw === raw.trimEnd() ? '#' + esc : attr('id', raw);
+ if (resolves(s)) selector = s;
+ }
+ if (!selector && el.getAttribute('data-testid')) { const s = attr('data-testid', el.getAttribute('data-testid')); if (resolves(s)) selector = s; }
+ if (!selector && el.name) { const s = el.tagName.toLowerCase() + attr('name', el.name); if (resolves(s)) selector = s; }
if (!selector) {
let m = el.getAttribute('data-tv3');
// Reuse a marker only if it still uniquely resolves; otherwise mint a fresh monotonic one.
// Keeps a marker stable across observe() calls without trusting a foreign, duplicated, or
// syntactically-broken data-tv3 value that a remembered selector could resolve to the wrong node.
- if (!m || !uniq('[data-tv3="' + m + '"]')) { m = 't' + (window.__tv3_next++); el.setAttribute('data-tv3', m); }
- selector = '[data-tv3="' + m + '"]';
+ if (!m || !resolves(attr('data-tv3', m))) {
+ // Skip values the page already carries, or a pre-seeded data-tv3 collides with a freshly
+ // minted one and two elements share a selector. Bounded, and the suffix varies per attempt:
+ // a frozen or saturated counter makes ++ a no-op, and an unbounded search would wedge the
+ // renderer for the rest of the run. An element we cannot name uniquely is left unlisted.
+ m = null;
+ for (let n = 0; n < 64 && m === null; n++) {
+ const candidate = 't' + (window.__tv3_next++) + (n ? '-' + n : '');
+ if (!document.querySelector(attr('data-tv3', candidate))) m = candidate;
+ }
+ if (m === null) { dropped++; continue; }
+ el.setAttribute('data-tv3', m);
+ }
+ selector = attr('data-tv3', m);
}
let label = (el.getAttribute('aria-label') || el.getAttribute('placeholder') || '').trim();
if (!label && el.labels && el.labels[0]) label = (el.labels[0].innerText || '').trim();
@@ -397,6 +431,7 @@ _OBSERVE_JS = (
if (pressed === 'true' || pressed === 'false') rec.pressed = pressed === 'true';
out.push(rec);
if (++i > 250) break;
+ } catch (e) { dropped++; continue; }
}
// Page-text digest: outcome states (submission confirmations, rejection banners, validation
// summaries) live in non-interactive nodes the element list can never carry. Sources are
@@ -458,7 +493,7 @@ _OBSERVE_JS = (
iframeInfo.entries.push({ host: u.host.slice(0, 80), title: ttl, captcha: sig.test(src + ' ' + ttl) });
}
} catch (e) { iframeInfo.total = 0; iframeInfo.entries.length = 0; }
- return JSON.stringify({ url: location.href, title: document.title, text: texts, iframes: iframeInfo, elements: out });
+ return JSON.stringify({ url: location.href, title: document.title, text: texts, iframes: iframeInfo, dropped: dropped, elements: out });
}
"""
)
@@ -557,6 +592,11 @@ def build_browser_tools(
+ "; ".join(parts)
+ overflow
)
+ dropped = data.get("dropped") or 0
+ if dropped:
+ # Without this an element list emptied by unreadable elements is indistinguishable from
+ # a page that genuinely has no controls.
+ lines.append(f"note: {dropped} element(s) could not be described and are not listed below")
for e in elements:
extra = ""
if e.get("value"):
diff --git a/skyvern/services/otp_service.py b/skyvern/services/otp_service.py
index ede8a2ebc..b42476bbc 100644
--- a/skyvern/services/otp_service.py
+++ b/skyvern/services/otp_service.py
@@ -464,6 +464,8 @@ def try_generate_totp_for_credential(
credential_key: str,
workflow_run_id: str,
) -> OTPValue | None:
+ if not workflow_run_context.is_registered_credential_parameter_key(credential_key):
+ return None
value = workflow_run_context.values.get(credential_key)
if not isinstance(value, dict):
return None
@@ -521,13 +523,17 @@ def has_credential_totp_candidate(workflow_run_id: str | None) -> bool:
current_context = skyvern_context.current()
active_credential_key = current_context.active_credential_parameter_key if current_context else None
if active_credential_key:
+ if not workflow_run_context.is_registered_credential_parameter_key(active_credential_key):
+ return False
value = workflow_run_context.values.get(active_credential_key)
return isinstance(value, dict) and isinstance(value.get("totp"), str)
candidate_keys = [
key
for key, value in workflow_run_context.values.items()
- if isinstance(value, dict) and isinstance(value.get("totp"), str)
+ if isinstance(value, dict)
+ and isinstance(value.get("totp"), str)
+ and workflow_run_context.is_registered_credential_parameter_key(key)
]
return len(candidate_keys) == 1
@@ -555,7 +561,9 @@ def try_generate_totp_from_credential(workflow_run_id: str | None) -> OTPValue |
candidate_keys = [
key
for key, value in workflow_run_context.values.items()
- if isinstance(value, dict) and isinstance(value.get("totp"), str)
+ if isinstance(value, dict)
+ and isinstance(value.get("totp"), str)
+ and workflow_run_context.is_registered_credential_parameter_key(key)
]
if len(candidate_keys) != 1:
if len(candidate_keys) > 1:
diff --git a/skyvern/services/script_service.py b/skyvern/services/script_service.py
index ce5402ba3..9826d74e0 100644
--- a/skyvern/services/script_service.py
+++ b/skyvern/services/script_service.py
@@ -570,7 +570,7 @@ async def _take_workflow_run_block_screenshot(
"""
browser_state = app.BROWSER_MANAGER.get_for_workflow_run(workflow_run_id)
if not browser_state:
- LOG.warning("No browser state found when creating workflow_run_block", workflow_run_id=workflow_run_id)
+ LOG.info("No browser state found when creating workflow_run_block", workflow_run_id=workflow_run_id)
else:
screenshot = await browser_state.take_fullpage_screenshot()
if screenshot:
@@ -3274,7 +3274,7 @@ def _render_template_with_label(template: str, label: str | None = None) -> str:
if isinstance(current_value, dict):
block_reference_data.update(current_value)
else:
- LOG.warning(
+ LOG.debug(
f"Script service: Parameter {label} has a registered reference value, going to overwrite it by block metadata"
)
diff --git a/skyvern/utils/contained_effects.py b/skyvern/utils/contained_effects.py
new file mode 100644
index 000000000..86835a985
--- /dev/null
+++ b/skyvern/utils/contained_effects.py
@@ -0,0 +1,46 @@
+"""Containment for recording side effects that must not reach the caller's outcome.
+
+Observation and bookkeeping -- log emits, span attributes, Temporal search-attribute
+writes -- routinely sit on a critical path: inside a ``finally``, in a finalizer, or
+after the terminal write that already decided the run. A failure there should cost the
+record, never the work.
+
+A plain ``try``/``except`` is not containment when the handler re-enters the sink that
+just failed, so the report path below is itself suppressed. ``BaseException`` is
+deliberately not caught: cancellation and interpreter shutdown must still propagate.
+"""
+
+from __future__ import annotations
+
+import contextlib
+from collections.abc import Iterator
+from contextlib import contextmanager
+from typing import Any
+
+import structlog
+
+LOG = structlog.get_logger()
+
+
+@contextmanager
+def contained_effect(effect: str, /, **context: Any) -> Iterator[None]:
+ """Run a recording side effect so that its failure cannot change what the caller does.
+
+ ``effect`` names what was being recorded, and ``context`` adds identifying fields to
+ the report. Build the payload inside the block too -- a sink that cannot fail is of
+ no help when the arguments to it can.
+ """
+ try:
+ yield
+ except Exception as exc:
+ _report_contained_failure(effect, exc, context)
+
+
+def _report_contained_failure(effect: str, exc: Exception, context: dict[str, Any]) -> None:
+ fields: dict[str, Any] = dict(context)
+ fields["effect"] = effect
+ fields["error_type"] = type(exc).__name__
+ # The sink being protected may be this same logger, so the report cannot be allowed
+ # to re-raise what the guard just swallowed.
+ with contextlib.suppress(Exception):
+ LOG.warning("Contained side effect failed", **fields)
diff --git a/skyvern/utils/organization_slug.py b/skyvern/utils/organization_slug.py
new file mode 100644
index 000000000..46131be3c
--- /dev/null
+++ b/skyvern/utils/organization_slug.py
@@ -0,0 +1,137 @@
+from __future__ import annotations
+
+import re
+from collections.abc import Iterator
+from typing import TYPE_CHECKING
+
+from sqlalchemy.exc import IntegrityError
+
+if TYPE_CHECKING:
+ from skyvern.forge.sdk.schemas.organizations import Organization
+
+ORG_SLUG_MAX_LENGTH = 20
+ORG_SLUG_MAX_SUFFIX_ATTEMPTS = 5
+ORG_SLUG_UNIQUE_CONSTRAINT = "uq_organizations_slug"
+_ORG_SLUG_SQLITE_UNIQUE_ERROR = "UNIQUE constraint failed: organizations.slug"
+ORG_SLUG_PATTERN = re.compile(r"^[a-z0-9-]{1,20}$")
+_INVALID_CHARACTER_PATTERN = re.compile(r"[^a-z0-9-]")
+_CONSECUTIVE_HYPHEN_PATTERN = re.compile(r"-+")
+
+
+def is_valid_org_slug(value: str) -> bool:
+ return ORG_SLUG_PATTERN.fullmatch(value) is not None
+
+
+def _normalize_slug_source(value: str) -> str:
+ normalized = _INVALID_CHARACTER_PATTERN.sub("-", value.casefold())
+ return _CONSECUTIVE_HYPHEN_PATTERN.sub("-", normalized).strip("-")
+
+
+def sanitize_org_slug(value: str, organization_id: str) -> str:
+ """Return an address-safe slug, using the organization ID when the value is empty."""
+ slug = _normalize_slug_source(value)[:ORG_SLUG_MAX_LENGTH]
+ if slug:
+ return slug
+
+ organization_id_tail = _normalize_slug_source(organization_id)[-ORG_SLUG_MAX_LENGTH:]
+ if not organization_id_tail:
+ raise ValueError("organization_id must contain at least one ASCII letter or digit")
+ return organization_id_tail[-ORG_SLUG_MAX_LENGTH:]
+
+
+def build_org_id_tail_slug(organization_id: str) -> str:
+ return sanitize_org_slug("", organization_id)
+
+
+def is_org_slug_unique_violation(error: IntegrityError) -> bool:
+ """Return whether an integrity error identifies the organization slug constraint."""
+ diagnostic = getattr(error.orig, "diag", None)
+ constraint_name = getattr(diagnostic, "constraint_name", None)
+ if constraint_name is not None:
+ return constraint_name == ORG_SLUG_UNIQUE_CONSTRAINT
+ original_error = str(error.orig)
+ return (
+ ORG_SLUG_UNIQUE_CONSTRAINT in original_error
+ or ORG_SLUG_UNIQUE_CONSTRAINT in str(error)
+ or _ORG_SLUG_SQLITE_UNIQUE_ERROR in original_error
+ )
+
+
+def derive_org_slug(organization_name: str, organization_id: str) -> str:
+ return sanitize_org_slug(organization_name, organization_id)
+
+
+def build_org_slug_candidate(base_slug: str, collision_number: int) -> str:
+ """Build the base slug, then ``-2``, ``-3``, and later collision candidates."""
+ if not is_valid_org_slug(base_slug):
+ raise ValueError("base_slug must match ^[a-z0-9-]{1,20}$")
+ if collision_number < 1:
+ raise ValueError("collision_number must be at least 1")
+ if collision_number == 1:
+ return base_slug
+
+ suffix = f"-{collision_number}"
+ prefix_length = ORG_SLUG_MAX_LENGTH - len(suffix)
+ if prefix_length < 1:
+ raise ValueError("collision_number is too large to fit in an organization slug")
+ prefix = base_slug[:prefix_length].rstrip("-")
+ if not prefix:
+ prefix = base_slug[:prefix_length]
+ return f"{prefix}{suffix}"
+
+
+def iter_org_slug_candidates(base_slug: str, organization_id: str) -> Iterator[str]:
+ """Yield the bounded base ladder, followed by the organization ID tail."""
+ organization_id_tail = build_org_id_tail_slug(organization_id)
+ seen: set[str] = set()
+ if base_slug:
+ for collision_number in range(1, ORG_SLUG_MAX_SUFFIX_ATTEMPTS + 2):
+ candidate = build_org_slug_candidate(base_slug, collision_number)
+ if candidate not in seen:
+ seen.add(candidate)
+ yield candidate
+ if organization_id_tail not in seen:
+ yield organization_id_tail
+
+
+class OrganizationSlugCollisionError(RuntimeError):
+ pass
+
+
+async def persist_org_slug(organization: Organization, base_slug: str) -> str:
+ """Persist a slug with bounded retries without replacing a concurrent winner."""
+ from skyvern.forge import app
+
+ last_collision: IntegrityError | None = None
+ for candidate in iter_org_slug_candidates(base_slug, organization.organization_id):
+ try:
+ if organization.slug is None:
+ stored_organization = await app.DATABASE.organizations.set_organization_slug_if_missing(
+ organization_id=organization.organization_id,
+ slug=candidate,
+ )
+ else:
+ stored_organization = await app.DATABASE.organizations.update_organization(
+ organization.organization_id,
+ slug=candidate,
+ update_slug=True,
+ )
+ except IntegrityError as exc:
+ if not is_org_slug_unique_violation(exc):
+ raise
+ last_collision = exc
+ continue
+ if stored_organization.slug is None:
+ raise RuntimeError("organization slug persistence returned no slug")
+ return stored_organization.slug
+
+ raise OrganizationSlugCollisionError(
+ f"Could not assign a unique slug to organization {organization.organization_id}"
+ ) from last_collision
+
+
+async def get_or_derive_org_slug(organization: Organization) -> str:
+ if organization.slug:
+ return organization.slug
+ base_slug = derive_org_slug(organization.organization_name, organization.organization_id)
+ return await persist_org_slug(organization, base_slug)
diff --git a/skyvern/utils/prompt_engine.py b/skyvern/utils/prompt_engine.py
index fa28d56a4..f7b1afbbb 100644
--- a/skyvern/utils/prompt_engine.py
+++ b/skyvern/utils/prompt_engine.py
@@ -1,3 +1,4 @@
+from collections.abc import Callable
from typing import Any
import structlog
@@ -54,6 +55,9 @@ class MaxStepsReasonResponse(BaseModel):
PROMPT_HARD_CEILING_TOKENS = 180_000
+_CEILING_SAFETY_MARGIN_TOKENS = 2_000
+_MIN_USEFUL_ELEMENT_TOKENS = 20_000
+_MAX_ELEMENT_TRIM_ROUNDS = 3
CEILING_FALLBACK_KEYS_BY_TEMPLATE: dict[str, list[str]] = {
"extract-information": [
@@ -167,6 +171,10 @@ def load_prompt_with_elements_tracked(
max_tokens=DEFAULT_MAX_TOKENS,
)
+ def _mirror_trimmed_elements(trimmed: str) -> None:
+ if element_tree_builder.last_used_element_tree_html is not None:
+ element_tree_builder.last_used_element_tree_html = trimmed
+
final_prompt, final_kwargs, final_token_count = _enforce_prompt_ceiling_counted(
prompt,
prompt_engine=prompt_engine,
@@ -174,6 +182,7 @@ def load_prompt_with_elements_tracked(
kwargs=kwargs,
elements=elements,
precomputed_token_count=current_prompt_token_count,
+ on_elements_trimmed=_mirror_trimmed_elements,
)
# SKY-9718: stash the locally-counted prompt size on SkyvernContext so the downstream
@@ -214,6 +223,50 @@ def load_prompt_with_elements(
return prompt
+def _truncate_elements_at_tag_boundary(elements: str, keep_chars: int) -> str:
+ if keep_chars >= len(elements):
+ return elements
+ # Cut on a tag boundary so the tail isn't a half-written tag or attribute.
+ last_tag_end = elements.rfind(">", 0, keep_chars)
+ return elements[: last_tag_end + 1] if last_tag_end != -1 else elements[:keep_chars]
+
+
+def _trim_elements_to_fit(
+ prompt: str,
+ *,
+ prompt_engine: PromptEngine,
+ template_name: str,
+ kwargs: dict[str, Any],
+ elements: str,
+ token_count: int,
+ min_useful_element_tokens: int,
+) -> tuple[str, str, int]:
+ """Trim the rendered element tree until the prompt fits under the hard ceiling.
+
+ Returns the (possibly unchanged) prompt, elements, and token count. The tree is left
+ alone when the non-element inputs are what blow the budget — trimming it then costs
+ page context without getting the prompt under the ceiling.
+ """
+ target_tokens = PROMPT_HARD_CEILING_TOKENS - _CEILING_SAFETY_MARGIN_TOKENS
+ trimmed = elements
+ for _ in range(_MAX_ELEMENT_TRIM_ROUNDS):
+ element_tokens = count_tokens(trimmed)
+ if element_tokens == 0:
+ break
+ element_budget = target_tokens - (token_count - element_tokens)
+ if element_budget < min_useful_element_tokens:
+ break
+ keep_chars = int(element_budget * (len(trimmed) / element_tokens))
+ if keep_chars >= len(trimmed):
+ break
+ trimmed = _truncate_elements_at_tag_boundary(trimmed, keep_chars)
+ prompt = prompt_engine.load_prompt(template_name, elements=trimmed, **kwargs)
+ token_count = count_tokens(prompt)
+ if token_count <= PROMPT_HARD_CEILING_TOKENS:
+ break
+ return prompt, trimmed, token_count
+
+
def _enforce_prompt_ceiling_counted(
prompt: str,
*,
@@ -222,6 +275,7 @@ def _enforce_prompt_ceiling_counted(
kwargs: dict[str, Any],
elements: Any | None = None,
precomputed_token_count: int | None = None,
+ on_elements_trimmed: Callable[[str], None] | None = None,
) -> tuple[str, dict[str, Any], int]:
"""Count-aware core of the hard-ceiling enforcement, returning the final prompt's token count.
@@ -233,6 +287,47 @@ def _enforce_prompt_ceiling_counted(
final_token_count = precomputed_token_count if precomputed_token_count is not None else count_tokens(prompt)
if final_token_count <= PROMPT_HARD_CEILING_TOKENS:
return prompt, working_kwargs, final_token_count
+
+ original_elements: str | None = elements if isinstance(elements, str) else None
+ # Mirrors the `elements` parameter so the pass-through to load_prompt is unchanged for
+ # callers that render without one; only a non-empty rendered tree is ever trimmed.
+ working_elements: Any | None = elements
+
+ def _fitted() -> tuple[str, dict[str, Any], int]:
+ if (
+ original_elements is not None
+ and isinstance(working_elements, str)
+ and working_elements != original_elements
+ ):
+ LOG.warning(
+ "Prompt exceeded hard ceiling; trimmed the element tree to fit",
+ template_name=template_name,
+ elements_char_count_before=len(original_elements),
+ elements_char_count_after=len(working_elements),
+ final_token_count=final_token_count,
+ hard_ceiling=PROMPT_HARD_CEILING_TOKENS,
+ )
+ if on_elements_trimmed is not None:
+ on_elements_trimmed(working_elements)
+ return prompt, working_kwargs, final_token_count
+
+ # The element tree is usually what blows the ceiling, and no combination of fallback
+ # drops can rescue a prompt whose tree alone is over budget. Trim it first so those
+ # drops aren't spent for nothing; `_MIN_USEFUL_ELEMENT_TOKENS` keeps this from gutting
+ # the page when a large non-element input is the real cause.
+ if isinstance(working_elements, str) and working_elements:
+ prompt, working_elements, final_token_count = _trim_elements_to_fit(
+ prompt,
+ prompt_engine=prompt_engine,
+ template_name=template_name,
+ kwargs=working_kwargs,
+ elements=working_elements,
+ token_count=final_token_count,
+ min_useful_element_tokens=_MIN_USEFUL_ELEMENT_TOKENS,
+ )
+ if final_token_count <= PROMPT_HARD_CEILING_TOKENS:
+ return _fitted()
+
fallback_keys = CEILING_FALLBACK_KEYS_BY_TEMPLATE.get(template_name, [])
drops_applied = 0
for drop_key in fallback_keys:
@@ -247,13 +342,29 @@ def _enforce_prompt_ceiling_counted(
)
working_kwargs[drop_key] = None
drops_applied += 1
- if elements is None:
+ if working_elements is None:
prompt = prompt_engine.load_prompt(template_name, **working_kwargs)
else:
- prompt = prompt_engine.load_prompt(template_name, elements=elements, **working_kwargs)
+ prompt = prompt_engine.load_prompt(template_name, elements=working_elements, **working_kwargs)
final_token_count = count_tokens(prompt)
if final_token_count <= PROMPT_HARD_CEILING_TOKENS:
- return prompt, working_kwargs, final_token_count
+ return _fitted()
+
+ # Last resort: the drops freed whatever they could, so trim the tree as far as it takes.
+ # A degraded view of the page still lets the step run; raising ends the run outright.
+ if isinstance(working_elements, str) and working_elements:
+ prompt, working_elements, final_token_count = _trim_elements_to_fit(
+ prompt,
+ prompt_engine=prompt_engine,
+ template_name=template_name,
+ kwargs=working_kwargs,
+ elements=working_elements,
+ token_count=final_token_count,
+ min_useful_element_tokens=0,
+ )
+ if final_token_count <= PROMPT_HARD_CEILING_TOKENS:
+ return _fitted()
+
LOG.error(
"Prompt still exceeds hard ceiling",
template_name=template_name,
@@ -261,7 +372,8 @@ def _enforce_prompt_ceiling_counted(
hard_ceiling=PROMPT_HARD_CEILING_TOKENS,
fallback_keys_configured=len(fallback_keys),
drops_applied=drops_applied,
- elements_char_count=len(elements) if elements else None,
+ elements_char_count=len(original_elements) if original_elements else None,
+ elements_char_count_after_trim=len(working_elements) if working_elements else None,
)
raise SkyvernContextWindowExceededError(prompt_name=template_name)
diff --git a/skyvern/webeye/actions/handler.py b/skyvern/webeye/actions/handler.py
index f20bf3d87..810772f3b 100644
--- a/skyvern/webeye/actions/handler.py
+++ b/skyvern/webeye/actions/handler.py
@@ -21,7 +21,7 @@ from cachetools import TTLCache
from fuzzysearch import find_near_matches
from opentelemetry import trace as otel_trace
from playwright._impl._errors import Error as PlaywrightError
-from playwright.async_api import Download, FileChooser, Frame, Locator, Page, Request, Response, TimeoutError
+from playwright.async_api import Download, FileChooser, Frame, Locator, Page, Request, Response
from pydantic import BaseModel, field_validator
from skyvern.config import settings
@@ -78,6 +78,7 @@ from skyvern.exceptions import (
PhoneNumberInputBrowserInteractionFailed,
PhoneNumberInputBrowserValidityMismatch,
PhoneNumberInputMismatch,
+ ScreenshotTargetClosed,
SecretInputMismatch,
SkyvernException,
SkyvernHTTPException,
@@ -135,6 +136,7 @@ from skyvern.forge.sdk.settings_manager import SettingsManager
from skyvern.forge.sdk.trace import apply_context_attrs, traced, traced_span
from skyvern.services import service_utils
from skyvern.services.action_service import get_action_history
+from skyvern.utils.contained_effects import contained_effect
from skyvern.utils.lean_html import apply_lean_to_tree
from skyvern.utils.prompt_engine import (
CheckDateFormatResponse,
@@ -164,6 +166,7 @@ from skyvern.webeye.actions.actions import (
)
from skyvern.webeye.actions.responses import ActionAbort, ActionFailure, ActionResult, ActionSuccess
from skyvern.webeye.browser_artifacts import DownloadBinding
+from skyvern.webeye.browser_driver_errors import is_driver_error, is_driver_timeout_error
from skyvern.webeye.browser_engine import UNSET_SELECTION, BrowserEngineSelection, resolve_engine_selection_for_task
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
@@ -260,19 +263,19 @@ _COLLAPSE_XP_ASSIGNMENT_MEMO: TTLCache[str, bool] = TTLCache(maxsize=100_000, tt
def _is_selected_engine_timeout(exc: BaseException, engine_selection: BrowserEngineSelection | None) -> bool:
- """A driver-native timeout under THIS run's selected engine; the stock Playwright ``TimeoutError``
- identity when no engine is pinned (unchanged default)."""
+ """A driver-native timeout under THIS run's selected engine; any installed Playwright-family
+ driver's timeout identity when no engine is pinned."""
if engine_selection is not None:
return engine_selection.is_engine_timeout_error(exc)
- return isinstance(exc, TimeoutError)
+ return is_driver_timeout_error(exc)
def _is_selected_engine_error(exc: BaseException, engine_selection: BrowserEngineSelection | None) -> bool:
- """A driver-native error under THIS run's selected engine; the stock Playwright ``Error`` identity
- when no engine is pinned (unchanged default)."""
+ """A driver-native error under THIS run's selected engine; any installed Playwright-family
+ driver's error identity when no engine is pinned."""
if engine_selection is not None:
return engine_selection.is_engine_error(exc)
- return isinstance(exc, PlaywrightError)
+ return is_driver_error(exc)
class _CollapseGateResult(NamedTuple):
@@ -4564,6 +4567,13 @@ class ActionHandler:
else:
LOG.exception("Unhandled exception in action handler", action=action)
actions_result.append(ActionFailure(e))
+ except ScreenshotTargetClosed as e:
+ LOG.warning(
+ "Browser target closed while handling action",
+ action=action,
+ exception_message=str(e),
+ )
+ actions_result.append(ActionFailure(e))
except Exception as e:
LOG.exception("Unhandled exception in action handler", action=action)
actions_result.append(ActionFailure(e))
@@ -6092,25 +6102,23 @@ def _emit_tel_input_outcome(
return
try:
- final_result = results[-1] if results else None
- if isinstance(final_result, ActionSuccess):
- terminal_result = ActionStatus.completed.value
- elif isinstance(final_result, ActionAbort):
- terminal_result = ActionStatus.skipped.value
- else:
- terminal_result = ActionStatus.failed.value
- if exception_type is None and final_result is not None:
- exception_type = final_result.exception_type
- LOG.info(
- "tel_input_outcome",
- sampling=False,
- **outcome.model_dump(mode="json"),
- terminal_result=terminal_result,
- exception_type=exception_type,
- )
- except Exception as exc:
- with contextlib.suppress(Exception):
- LOG.warning("Failed to emit tel input outcome", error_type=type(exc).__name__)
+ with contained_effect("emit tel input outcome"):
+ final_result = results[-1] if results else None
+ if isinstance(final_result, ActionSuccess):
+ terminal_result = ActionStatus.completed.value
+ elif isinstance(final_result, ActionAbort):
+ terminal_result = ActionStatus.skipped.value
+ else:
+ terminal_result = ActionStatus.failed.value
+ if exception_type is None and final_result is not None:
+ exception_type = final_result.exception_type
+ LOG.info(
+ "tel_input_outcome",
+ sampling=False,
+ **outcome.model_dump(mode="json"),
+ terminal_result=terminal_result,
+ exception_type=exception_type,
+ )
finally:
action.tel_input_outcome = None
@@ -8040,6 +8048,14 @@ async def handle_complete_action(
verification_result = await app.agent.complete_verify(
page, scraped_page, task, step, verification_trigger="complete_action_forced"
)
+ except ScreenshotTargetClosed as e:
+ _span.set_attribute("verification_path", "needs_llm_error")
+ LOG.warning(
+ "Browser target closed while verifying the complete action",
+ workflow_run_id=task.workflow_run_id,
+ exception_message=str(e),
+ )
+ return [ActionFailure(exception=e)]
except Exception as e:
_span.set_attribute("verification_path", "needs_llm_error")
LOG.exception(
diff --git a/skyvern/webeye/browser_driver_errors.py b/skyvern/webeye/browser_driver_errors.py
new file mode 100644
index 000000000..6da0c4d09
--- /dev/null
+++ b/skyvern/webeye/browser_driver_errors.py
@@ -0,0 +1,46 @@
+"""Driver-native error identities for callers with no pinned ``BrowserEngineSelection``."""
+
+from __future__ import annotations
+
+import importlib
+
+from playwright.async_api import Error as _ImportedDriverError
+from playwright.async_api import TimeoutError as _ImportedDriverTimeoutError
+
+# Two Playwright-family driver packages can be live in one process: scripts/patch_browser.sh repoints
+# this file's driver import to the fork across the browser image but deliberately skips
+# cloud/persistent_browsers, so a persistent session's pages raise the un-rewritten package's error
+# classes. Package names are spelled as bare strings, and the import prefix is never written
+# literally anywhere in this file, because that rewrite matches the literal prefix and would repoint
+# the scan along with the import.
+_DRIVER_PACKAGES = ("playwright", "patchright")
+
+
+def _load_driver_error_types() -> tuple[tuple[type[BaseException], ...], tuple[type[BaseException], ...]]:
+ # Seeded from the static import so the result is never empty and always carries whichever package
+ # the build repointed this file at; the scan only ever adds the other one.
+ error_types: list[type[BaseException]] = [_ImportedDriverError]
+ timeout_types: list[type[BaseException]] = [_ImportedDriverTimeoutError]
+ for package in _DRIVER_PACKAGES:
+ try:
+ api = importlib.import_module(f"{package}.async_api")
+ driver_error, driver_timeout_error = api.Error, api.TimeoutError
+ except (ImportError, AttributeError):
+ continue
+ if driver_error not in error_types:
+ error_types.append(driver_error)
+ if driver_timeout_error not in timeout_types:
+ timeout_types.append(driver_timeout_error)
+ return tuple(error_types), tuple(timeout_types)
+
+
+DRIVER_ERROR_TYPES, DRIVER_TIMEOUT_ERROR_TYPES = _load_driver_error_types()
+
+
+def is_driver_error(exc: BaseException) -> bool:
+ """Whether ``exc`` is a driver-family error from any Playwright-family package installed here."""
+ return isinstance(exc, DRIVER_ERROR_TYPES)
+
+
+def is_driver_timeout_error(exc: BaseException) -> bool:
+ return isinstance(exc, DRIVER_TIMEOUT_ERROR_TYPES)
diff --git a/skyvern/webeye/real_browser_state.py b/skyvern/webeye/real_browser_state.py
index cab058719..b718c27e1 100644
--- a/skyvern/webeye/real_browser_state.py
+++ b/skyvern/webeye/real_browser_state.py
@@ -105,6 +105,7 @@ class RealBrowserState(BrowserState):
self._remote_driver_detached = False
self._browser_state_diagnostic: BrowserStateDiagnostic | None = None
self._ever_connected = browser_context is not None
+ self._close_requested = False
self._disconnect_listener_context: BrowserContext | None = None
self._disconnect_listener_browser: Browser | None = None
if browser_context is not None:
@@ -285,6 +286,7 @@ class RealBrowserState(BrowserState):
self.browser_cleanup = browser_cleanup
self._browser_state_diagnostic = None
self._ever_connected = True
+ self._close_requested = False
self._register_disconnect_listeners(browser_context)
# Strikes describe the browser that earned them; a replacement starts even.
skyvern_context.record_browser_success()
@@ -582,13 +584,17 @@ class RealBrowserState(BrowserState):
event=event,
observation_source=observation_source,
)
- LOG.warning(
+ # A disconnect observed after close() was requested is the teardown we asked for; only an
+ # unrequested one is worth a warning.
+ log = LOG.info if self._close_requested else LOG.warning
+ log(
"Browser state disconnected",
browser_session_id=browser_session_id,
disconnect_reason=reason,
disconnect_event=event,
disconnect_observed_at=disconnect_observed_at.isoformat(),
disconnect_observation_source=observation_source,
+ close_requested=self._close_requested,
)
def get_browser_state_diagnostic(self) -> BrowserStateDiagnostic | None:
@@ -825,6 +831,9 @@ class RealBrowserState(BrowserState):
"download interceptor disable",
)
if close_browser_on_completion:
+ # Only a teardown that closes the context is a requested disconnect; the keep-alive path
+ # leaves the browser to a later owner, whose disconnects are still unrequested.
+ self._close_requested = True
recording_finalized = await self._run_bounded_detachable(
self._teardown_context(),
BROWSER_CLOSE_TIMEOUT,
diff --git a/skyvern/webeye/skycdp/facade/page.py b/skyvern/webeye/skycdp/facade/page.py
index 3f3e005f7..b842d4f1f 100644
--- a/skyvern/webeye/skycdp/facade/page.py
+++ b/skyvern/webeye/skycdp/facade/page.py
@@ -592,14 +592,11 @@ class Page:
return self._network.take_document_response()
async def reload(self, *, timeout: float | None = None, wait_until: str = "load") -> None:
- # Page.reload keeps the URL, so wait_for_load_state cannot be trusted here: its readyState poll
- # reads the pre-reload document -- still the frame's registered execution context and already
- # "complete" -- and returns before the new document exists (the load-count-1->1 parity gap).
- # The new document's execution context is only registered as the reload commits, so wait for
- # the load event that fires *after* this reload's own main-frame commit; that load, unlike the
- # poll, cannot be satisfied until the re-created document is in place.
+ # Page.reload keeps the URL, so readyState polling can observe the pre-reload document. Wait for
+ # this reload's own main-frame commit and its following load event instead.
seconds = seconds_from_ms(timeout, DEFAULT_NAVIGATION_TIMEOUT_MS)
loop = asyncio.get_running_loop()
+ deadline = loop.time() + seconds
committed: asyncio.Future[None] = loop.create_future()
loaded: asyncio.Future[None] = loop.create_future()
@@ -614,9 +611,12 @@ class Page:
self.on("framenavigated", on_navigated)
self._session.on("Page.loadEventFired", on_loaded)
try:
- await self._session.send("Page.reload", {})
- with suppress(asyncio.TimeoutError):
- await asyncio.wait_for(loaded, seconds)
+ await self._session.send("Page.reload", {}, timeout=seconds)
+ remaining = max(0.0, deadline - loop.time())
+ try:
+ await asyncio.wait_for(loaded, timeout=remaining)
+ except asyncio.TimeoutError as exc:
+ raise CdpTimeoutError("reload did not commit and load a new main-frame document") from exc
finally:
self.remove_listener("framenavigated", on_navigated)
self._session.off("Page.loadEventFired", on_loaded)
diff --git a/skyvern/webeye/utils/dom.py b/skyvern/webeye/utils/dom.py
index d243d16c8..917c402e9 100644
--- a/skyvern/webeye/utils/dom.py
+++ b/skyvern/webeye/utils/dom.py
@@ -10,15 +10,11 @@ from urllib.parse import urljoin, urlparse
import structlog
from playwright.async_api import (
ElementHandle,
-)
-from playwright.async_api import Error as PlaywrightError
-from playwright.async_api import (
FloatRect,
Frame,
FrameLocator,
Locator,
Page,
- TimeoutError,
)
from skyvern.config import settings
@@ -41,6 +37,7 @@ from skyvern.experimentation.wait_utils import get_or_create_wait_config, get_wa
from skyvern.forge.sdk.event.factory import EventStrategyFactory
from skyvern.utils.url_validators import validate_fetch_url
from skyvern.webeye.actions import handler_utils
+from skyvern.webeye.browser_driver_errors import is_driver_error, is_driver_timeout_error
from skyvern.webeye.browser_engine import BrowserEngineSelection
from skyvern.webeye.dom_inspection import (
read_locator_tag_name,
@@ -74,17 +71,17 @@ def is_element_detached_error(exc: BaseException) -> bool:
def is_engine_error(exc: BaseException, engine_selection: BrowserEngineSelection | None = None) -> bool:
"""Whether ``exc`` is a driver-family error from THIS run's engine. Routes through the per-run
- selection when one is pinned so a non-Playwright engine's natives are recognised; falls back to the
- stock Playwright identity when no engine is pinned (callers built outside the per-run engine seam),
- preserving exact stock behavior. A foreign engine's native error is rejected either way."""
- return engine_selection.is_engine_error(exc) if engine_selection is not None else isinstance(exc, PlaywrightError)
+ selection when one is pinned so a non-Playwright engine's natives are recognised; falls back to
+ every installed Playwright-family driver's identity when no engine is pinned (callers built outside
+ the per-run engine seam). A foreign engine's native error is rejected either way."""
+ return engine_selection.is_engine_error(exc) if engine_selection is not None else is_driver_error(exc)
def is_engine_timeout_error(exc: BaseException, engine_selection: BrowserEngineSelection | None = None) -> bool:
- """Whether ``exc`` is THIS run's engine timeout. Same selection-vs-stock routing as
- ``is_engine_error``; the stock fallback keeps the historical ``TimeoutError`` identity."""
+ """Whether ``exc`` is THIS run's engine timeout. Same selection-vs-driver routing as
+ ``is_engine_error``."""
return (
- engine_selection.is_engine_timeout_error(exc) if engine_selection is not None else isinstance(exc, TimeoutError)
+ engine_selection.is_engine_timeout_error(exc) if engine_selection is not None else is_driver_timeout_error(exc)
)
@@ -1392,11 +1389,29 @@ class SkyvernElement:
element_x = rect["x"] if rect["x"] > 0 else None
element_y = rect["y"] if rect["y"] > 0 else None
+ # Center the element on the live viewport, not the settings default: the viewport
+ # can be smaller (a dynamic override), and centering on 1920x1080 would scroll the
+ # element off the actual surface. get_frame() is a Page | Frame — a Frame exposes its
+ # owning Page via .page while a Page owns viewport_size directly, so resolve to
+ # whichever carries the viewport. Only a concrete dict with positive integer
+ # width/height is used; otherwise fall back to settings.
+ frame_or_page = self.get_frame()
+ viewport_owner = frame_or_page.page if hasattr(frame_or_page, "page") else frame_or_page
+ frame_viewport = getattr(viewport_owner, "viewport_size", None)
+ viewport_width = settings.BROWSER_WIDTH
+ viewport_height = settings.BROWSER_HEIGHT
+ if isinstance(frame_viewport, dict):
+ fv_width = frame_viewport.get("width")
+ fv_height = frame_viewport.get("height")
+ if isinstance(fv_width, int) and isinstance(fv_height, int) and fv_width > 0 and fv_height > 0:
+ viewport_width = fv_width
+ viewport_height = fv_height
+
if element_y is not None:
- target_y = max(int(element_y - (settings.BROWSER_HEIGHT / 2)), 0)
+ target_y = max(int(element_y - (viewport_height / 2)), 0)
if element_x is not None:
- target_x = max(int(element_x - (settings.BROWSER_WIDTH / 2)), 0)
+ target_x = max(int(element_x - (viewport_width / 2)), 0)
skyvern_frame = await SkyvernFrame.create_instance(self.get_frame())
if target_x is not None and target_y is not None:
diff --git a/skyvern/webeye/utils/page.py b/skyvern/webeye/utils/page.py
index 820e55a01..a439b18c5 100644
--- a/skyvern/webeye/utils/page.py
+++ b/skyvern/webeye/utils/page.py
@@ -16,7 +16,6 @@ import structlog
from opentelemetry import trace as otel_trace
from PIL import Image
from playwright._impl._errors import Error as PlaywrightError
-from playwright._impl._errors import TimeoutError
from playwright.async_api import ElementHandle, Frame, Locator, Page
from skyvern.constants import PAGE_CONTENT_TIMEOUT, SKYVERN_DIR
@@ -25,6 +24,7 @@ from skyvern.forge.sdk.browser_action_preflight import policy_observation_enable
from skyvern.forge.sdk.core import skyvern_context
from skyvern.forge.sdk.settings_manager import SettingsManager
from skyvern.forge.sdk.trace import apply_context_attrs, traced, traced_span
+from skyvern.webeye.browser_driver_errors import is_driver_error, is_driver_timeout_error
from skyvern.webeye.browser_engine import BrowserEngineSelection
from skyvern.webeye.browser_errors import BrowserTargetClosedError
from skyvern.webeye.browser_health import BrowserOperation
@@ -242,15 +242,16 @@ _NAVIGATION_SETTLE_TIMEOUT_MS = 3000
def _is_engine_error(exc: BaseException, engine_selection: BrowserEngineSelection | None) -> bool:
- """Whether ``exc`` belongs to THIS run's selected browser-engine error family. Falls back to the
- stock-Playwright identity when no engine is pinned, so an unmigrated caller keeps exact stock
- behavior; a foreign engine's error (or an unrelated exception) is rejected and left to propagate."""
- return engine_selection.is_engine_error(exc) if engine_selection is not None else isinstance(exc, PlaywrightError)
+ """Whether ``exc`` belongs to THIS run's selected browser-engine error family. Falls back to every
+ installed Playwright-family driver's identity when no engine is pinned, because an unpinned caller
+ can hold a page from either driver package the image installs; a foreign engine's error (or an
+ unrelated exception) is rejected and left to propagate."""
+ return engine_selection.is_engine_error(exc) if engine_selection is not None else is_driver_error(exc)
def is_engine_timeout(exc: BaseException, engine_selection: BrowserEngineSelection | None) -> bool:
return (
- engine_selection.is_engine_timeout_error(exc) if engine_selection is not None else isinstance(exc, TimeoutError)
+ engine_selection.is_engine_timeout_error(exc) if engine_selection is not None else is_driver_timeout_error(exc)
)
@@ -1547,6 +1548,11 @@ class SkyvernFrame:
_close_screenshot_stitch_resources(images, merged_img, buffer)
if len(images) > 1:
gc.collect()
+ except ScreenshotTargetClosed:
+ # The fallback below captures the same page, so a closed target can only fail there too.
+ x = None
+ y = None
+ raise
except Exception:
LOG.warning(
"Failed to take full page screenshot, fallback to use playwright full page screenshot",
diff --git a/tests/conftest.py b/tests/conftest.py
index e69de29bb..6aa01484e 100644
--- a/tests/conftest.py
+++ b/tests/conftest.py
@@ -0,0 +1,60 @@
+"""Fixtures shared by every suite."""
+
+import inspect
+from collections.abc import Callable
+from typing import Any
+
+import pytest
+
+
+class ForcedSinkFailure(RuntimeError):
+ """Stands in for a real sink error when a test forces a side effect to fail."""
+
+
+def failing_sink(monkeypatch: pytest.MonkeyPatch) -> Callable[..., None]:
+ """Replace a recording sink with one that raises, to assert the caller's decision survives.
+
+ A contained side effect and an uncontained one have byte-identical happy paths, which
+ is why review and CI both miss escapes. Making the sink raise is what tells them
+ apart::
+
+ failing_sink(workflow_module.workflow, "upsert_search_attributes")
+
+ Pass ``when`` to break only some calls, for the common shape where one sink serves
+ both the happy path and a finalizer and only the finalizer's call runs under the
+ conditions that break it. It receives the call's arguments; calls it rejects no-op.
+
+ The replacement matches the original's sync/async kind, and patching a name that does
+ not exist is an error rather than a silently passing test.
+ """
+
+ def install(
+ target: object,
+ attribute: str,
+ *,
+ exc: BaseException | None = None,
+ when: Callable[..., bool] | None = None,
+ ) -> None:
+ is_async = inspect.iscoroutinefunction(getattr(target, attribute))
+ failure = exc if exc is not None else ForcedSinkFailure(f"{attribute} was forced to fail")
+
+ def should_fail(args: tuple[Any, ...], kwargs: dict[str, Any]) -> bool:
+ return when is None or when(*args, **kwargs)
+
+ if is_async:
+
+ async def async_sink(*args: Any, **kwargs: Any) -> None:
+ if should_fail(args, kwargs):
+ raise failure
+
+ monkeypatch.setattr(target, attribute, async_sink)
+ return
+
+ def sync_sink(*args: Any, **kwargs: Any) -> None:
+ if should_fail(args, kwargs):
+ raise failure
+
+ monkeypatch.setattr(target, attribute, sync_sink)
+
+ return install
diff --git a/tests/unit/browser_extension/test_broker_client.py b/tests/unit/browser_extension/test_broker_client.py
index 62e194dea..15942f95b 100644
--- a/tests/unit/browser_extension/test_broker_client.py
+++ b/tests/unit/browser_extension/test_broker_client.py
@@ -712,6 +712,30 @@ def test_first_spawn_leaves_extension_credentials_for_daemon_child(
)
+def test_spawn_rejects_ready_response_for_a_different_port(
+ monkeypatch: pytest.MonkeyPatch,
+ tmp_path: Path,
+) -> None:
+ monkeypatch.setenv("HOME", str(tmp_path / "home"))
+ paths = ensure_run_directory(19778, base_dir=tmp_path / "run")
+ process = MagicMock()
+ monkeypatch.setattr(broker_client_module, "_broker_is_reachable", lambda _paths: False)
+ monkeypatch.setattr(broker_client_module.subprocess, "Popen", MagicMock(return_value=process))
+ monkeypatch.setattr(
+ broker_client_module,
+ "read_readiness",
+ MagicMock(return_value={"status": "READY", "port": 19779}),
+ )
+ terminate = MagicMock()
+ monkeypatch.setattr(broker_client_module, "_terminate_spawned_process", terminate)
+
+ with pytest.raises(BrowserExtensionBrokerError, match="readiness response is invalid") as error_info:
+ broker_client_module._ensure_broker_process(19778, paths)
+
+ assert error_info.value.code == "INVALID_READINESS"
+ terminate.assert_called_once_with(process)
+
+
def test_client_only_surfaces_daemon_auto_enable_failure(
monkeypatch: pytest.MonkeyPatch,
tmp_path: Path,
diff --git a/tests/unit/browser_extension/test_broker_state.py b/tests/unit/browser_extension/test_broker_state.py
index 1aa5d44d2..81aa9ae59 100644
--- a/tests/unit/browser_extension/test_broker_state.py
+++ b/tests/unit/browser_extension/test_broker_state.py
@@ -317,6 +317,35 @@ def test_readiness_success_error_and_timeout() -> None:
os.close(write_fd)
+ "payload",
+ [
+ b"\n",
+ b"not-json\n",
+ b'{"status":"READY"}\n',
+ b'{"status":"READY","port":0}\n',
+ b'{"status":"ERROR"}\n',
+ b'{"status":"ERROR","code":""}\n',
+ ],
+)
+def test_readiness_rejects_malformed_probe_payloads(payload: bytes) -> None:
+ read_fd, write_fd = os.pipe()
+ try:
+ os.write(write_fd, payload)
+ os.close(write_fd)
+ write_fd = -1
+
+ with pytest.raises(BrowserExtensionBrokerError) as error_info:
+ read_readiness(read_fd, timeout=0.1)
+
+ assert error_info.value.code == "INVALID_READINESS"
+ assert error_info.value.message == "Broker readiness response is invalid"
+ finally:
+ os.close(read_fd)
+ if write_fd >= 0:
+ os.close(write_fd)
+
+
def test_startup_log_is_bounded_while_child_is_writing(tmp_path: Path) -> None:
paths = ensure_run_directory(19777, base_dir=tmp_path / "run")
write_fd, drain_thread = prepare_startup_log(paths)
diff --git a/tests/unit/browser_extension/test_cdp_adapter.py b/tests/unit/browser_extension/test_cdp_adapter.py
index ea066019f..68bd17084 100644
--- a/tests/unit/browser_extension/test_cdp_adapter.py
+++ b/tests/unit/browser_extension/test_cdp_adapter.py
@@ -1,15 +1,20 @@
from __future__ import annotations
import asyncio
+import json
from collections.abc import AsyncIterator
-from unittest.mock import patch
+from unittest.mock import AsyncMock, patch
import pytest
import pytest_asyncio
from aiohttp import ClientSession, ClientWebSocketResponse
from skyvern.browser_extension.cdp_adapter import ExtensionCdpAdapter
-from skyvern.browser_extension.errors import ExtensionRequestError
+from skyvern.browser_extension.errors import (
+ BrowserExtensionBrokerError,
+ BrowserExtensionNotConnectedError,
+ ExtensionRequestError,
+)
from skyvern.browser_extension.target_registry import VirtualTargetRegistry
@@ -18,7 +23,7 @@ class StubRelay:
self.scoped_tabs = scoped_tabs or []
self.calls: list[tuple[str, dict]] = []
self.next_tab_id = 100
- self.fail_next: ExtensionRequestError | None = None
+ self.fail_next: BrowserExtensionBrokerError | ExtensionRequestError | None = None
self.fail_attach_tab_ids: set[int] = set()
self.block_attach_tab_id: int | None = None
self.attach_started = asyncio.Event()
@@ -28,7 +33,13 @@ class StubRelay:
self.release_detach = asyncio.Event()
self.main_frame_ids: dict[int, str] = {}
self.block_send_keys: set[tuple[str | None, str]] = set()
- self.fail_send_keys: dict[tuple[str | None, str], ExtensionRequestError] = {}
+ self.fail_send_keys: dict[
+ tuple[str | None, str],
+ BrowserExtensionBrokerError
+ | BrowserExtensionNotConnectedError
+ | ExtensionRequestError
+ | asyncio.CancelledError,
+ ] = {}
self.send_started: dict[tuple[str | None, str], asyncio.Event] = {}
self.release_send: dict[tuple[str | None, str], asyncio.Event] = {}
self.released_tabs: list[int] = []
@@ -42,7 +53,7 @@ class StubRelay:
if op == "debugger.attach":
tab_id = args["tabId"]
if tab_id in self.fail_attach_tab_ids:
- raise ExtensionRequestError("CDP_ERROR", "attach failed")
+ raise ExtensionRequestError("ATTACH_FAILED", "attach failed")
if tab_id == self.block_attach_tab_id:
self.attach_started.set()
await self.release_attach.wait()
@@ -257,6 +268,60 @@ async def test_auto_attach_existing_and_later_scoped_tabs() -> None:
assert popup["params"]["targetInfo"]["openerId"] == "tab-7"
+async def test_coded_attach_failed_already_attached_error_propagates_without_unsharing_tab() -> None:
+ tab = {"tabId": 11, "url": "https://shared.example", "title": "Shared"}
+ relay = StubRelay([tab])
+ relay.fail_next = ExtensionRequestError("ATTACH_FAILED", "Another debugger is already attached")
+ adapter = ExtensionCdpAdapter(VirtualTargetRegistry(), relay)
+ adapter._send = AsyncMock()
+
+ await adapter._handle_client_text(
+ None, # type: ignore[arg-type]
+ json.dumps({"id": 1, "method": "Target.setAutoAttach", "params": {"autoAttach": True}}),
+ )
+
+ adapter._send.assert_awaited_once_with(
+ None,
+ {"id": 1, "error": {"code": -32000, "message": "ATTACH_FAILED: Another debugger is already attached"}},
+ )
+ assert relay.scoped_tabs == [tab]
+ assert not any(op == "debugger.detach" for op, _ in relay.calls)
+ assert not any(op == "debugger.send" for op, _ in relay.calls)
+
+
+async def test_adopted_group_tab_uses_same_attach_flow_as_session_created_tab() -> None:
+ relay = StubRelay()
+ registry = VirtualTargetRegistry()
+ adapter = ExtensionCdpAdapter(registry, relay)
+ adapter._auto_attach = True
+ emit_attached = AsyncMock()
+ adapter._emit_attached = emit_attached
+ try:
+ await adapter.handle_extension_event(
+ "tabs.created",
+ {"tabId": 50, "url": "https://created.example", "title": "Created"},
+ )
+ await asyncio.gather(*list(adapter._background_tasks))
+ await adapter.handle_extension_event(
+ "scope.tabAdded",
+ {"tabId": 51, "url": "https://adopted.example", "title": "Adopted"},
+ )
+ await asyncio.gather(*list(adapter._background_tasks))
+ finally:
+ await adapter.stop()
+
+ assert [call for call in relay.calls if call[0] == "debugger.attach"] == [
+ ("debugger.attach", {"tabId": 50}),
+ ("debugger.attach", {"tabId": 51}),
+ ]
+ assert [call.args[:2] for call in emit_attached.await_args_list] == [
+ (50, "tab-50"),
+ (51, "tab-51"),
+ ]
+
+
@pytest.mark.asyncio
async def test_root_target_discovery_waits_for_auto_attach_while_session_commands_continue() -> None:
scoped_tabs = [
@@ -273,7 +338,6 @@ async def test_root_target_discovery_waits_for_auto_attach_while_session_command
try:
async with ClientSession() as client, client.ws_connect(adapter.cdp_ws_url) as ws:
await ws.send_json({"id": 1, "method": "Target.setAutoAttach", "params": {"autoAttach": True}})
- assert await receive_response(ws, 1) == {"id": 1, "result": {}}
await asyncio.wait_for(relay.attach_started.wait(), 1)
attached_session_id = registry.root_session_id(41)
@@ -296,6 +360,7 @@ async def test_root_target_discovery_waits_for_auto_attach_while_session_command
}
relay.release_attach.set()
+ assert await receive_response(ws, 1) == {"id": 1, "result": {}}
targets = await receive_response(ws, 2)
finally:
relay.release_attach.set()
@@ -305,7 +370,257 @@ async def test_root_target_discovery_waits_for_auto_attach_while_session_command
@pytest.mark.asyncio
-async def test_auto_attach_post_reply_failure_skips_failed_tab_without_second_response() -> None:
+async def test_auto_attach_failure_reaches_client_instead_of_acknowledging_success() -> None:
+ relay = StubRelay([{"tabId": 30, "url": "https://bad.example", "title": "Bad"}])
+ relay.fail_attach_tab_ids.add(30)
+ registry = VirtualTargetRegistry()
+ adapter = ExtensionCdpAdapter(registry, relay)
+ adapter._send = AsyncMock()
+
+ await adapter._handle_client_text(
+ None, # type: ignore[arg-type]
+ json.dumps({"id": 1, "method": "Target.setAutoAttach", "params": {"autoAttach": True}}),
+ )
+
+ adapter._send.assert_awaited_once_with(
+ None,
+ {"id": 1, "error": {"code": -32000, "message": "ATTACH_FAILED: attach failed"}},
+ )
+
+
+async def test_repeated_auto_attach_failure_restores_enabled_state_for_later_scoped_tabs() -> None:
+ relay = StubRelay([{"tabId": 30, "url": "https://good.example", "title": "Good"}])
+ registry = VirtualTargetRegistry()
+ adapter = ExtensionCdpAdapter(registry, relay)
+ await adapter.start()
+ try:
+ async with ClientSession() as client, client.ws_connect(adapter.cdp_ws_url) as ws:
+ await ws.send_json({"id": 1, "method": "Target.setAutoAttach", "params": {"autoAttach": True}})
+ assert await receive_response(ws, 1) == {"id": 1, "result": {}}
+ await receive_event(ws, "Target.attachedToTarget")
+
+ relay.scoped_tabs.append({"tabId": 31, "url": "https://bad.example", "title": "Bad"})
+ relay.fail_attach_tab_ids.add(31)
+ await ws.send_json({"id": 2, "method": "Target.setAutoAttach", "params": {"autoAttach": True}})
+ assert await receive_response(ws, 2) == {
+ "id": 2,
+ "error": {"code": -32000, "message": "ATTACH_FAILED: attach failed"},
+ }
+ assert adapter._auto_attach is True
+
+ relay.fail_attach_tab_ids.remove(31)
+ await adapter.handle_extension_event(
+ "scope.tabAdded", {"tabId": 32, "url": "https://later.example", "title": "Later"}
+ )
+ later = await receive_event(ws, "Target.attachedToTarget")
+ finally:
+ await adapter.stop()
+
+ assert later["params"]["targetInfo"]["targetId"] == "tab-32"
+
+
+async def test_empty_scope_auto_attach_broker_failure_reaches_client() -> None:
+ relay = StubRelay()
+ relay.fail_next = BrowserExtensionBrokerError("BROKER_UNAVAILABLE", "broker unavailable")
+ adapter = ExtensionCdpAdapter(VirtualTargetRegistry(), relay)
+ adapter._send = AsyncMock()
+
+ await adapter._handle_client_text(
+ None, # type: ignore[arg-type]
+ json.dumps({"id": 1, "method": "Target.setAutoAttach", "params": {"autoAttach": True}}),
+ )
+
+ adapter._send.assert_awaited_once_with(
+ None,
+ {"id": 1, "error": {"code": -32000, "message": "BROKER_UNAVAILABLE: broker unavailable"}},
+ )
+ assert adapter._auto_attach is False
+
+
+async def test_auto_attach_replies_before_a_concurrent_scope_event() -> None:
+ relay = StubRelay()
+ relay.block_attach_tab_id = 100
+ registry = VirtualTargetRegistry()
+ adapter = ExtensionCdpAdapter(registry, relay)
+ original_request = relay.request
+ order: list[str] = []
+
+ async def request_with_scope_event(op: str, args: dict, timeout: float = 30.0) -> dict:
+ result = await original_request(op, args, timeout)
+ if op == "tabs.create":
+ await adapter.handle_extension_event(
+ "scope.tabAdded",
+ {"tabId": result["tabId"], "url": args["url"], "title": ""},
+ )
+ asyncio.get_running_loop().call_soon(relay.release_attach.set)
+ return result
+
+ relay.request = request_with_scope_event
+ adapter._reply = AsyncMock(side_effect=lambda *_args: order.append("reply"))
+ adapter._emit_attached = AsyncMock(side_effect=lambda *_args: order.append("attached"))
+
+ await adapter._handle_root_command(None, 1, "Target.setAutoAttach", {"autoAttach": True}) # type: ignore[arg-type]
+ await asyncio.gather(*list(adapter._background_tasks))
+
+ assert order == ["reply", "attached"]
+ assert [call for call in relay.calls if call[0] == "debugger.attach"] == [
+ ("debugger.attach", {"tabId": 100}),
+ ]
+
+
+async def test_frame_discovery_timeout_does_not_register_a_phantom_attached_page() -> None:
+ relay = StubRelay([{"tabId": 32, "url": "https://frame.example", "title": "Frame"}])
+ relay.fail_send_keys[(None, "Page.getFrameTree")] = ExtensionRequestError(
+ "COMMAND_TIMEOUT", "frame discovery timed out"
+ )
+ registry = VirtualTargetRegistry()
+ adapter = ExtensionCdpAdapter(registry, relay)
+ generation = adapter._begin_tab_scope(32)
+
+ with pytest.raises(ExtensionRequestError, match="frame discovery timed out"):
+ await adapter._ensure_attached(relay.scoped_tabs[0], generation=generation)
+
+ assert 32 not in adapter._attached_tabs
+ with pytest.raises(KeyError):
+ registry.target_id_for_tab(32)
+ assert ("debugger.detach", {"tabId": 32}) in relay.calls
+
+
+async def test_frame_discovery_not_connected_discards_attachment_and_restores_auto_attach() -> None:
+ relay = StubRelay([{"tabId": 32, "url": "https://frame.example", "title": "Frame"}])
+ relay.fail_send_keys[(None, "Page.getFrameTree")] = BrowserExtensionNotConnectedError()
+ registry = VirtualTargetRegistry()
+ adapter = ExtensionCdpAdapter(registry, relay)
+
+ with pytest.raises(BrowserExtensionNotConnectedError):
+ await adapter._set_auto_attach(None, 1, {"autoAttach": True}, None) # type: ignore[arg-type]
+
+ assert adapter._auto_attach is False
+ assert 32 not in adapter._attached_tabs
+ with pytest.raises(KeyError):
+ registry.target_id_for_tab(32)
+ assert ("debugger.detach", {"tabId": 32}) in relay.calls
+
+
+async def test_frame_discovery_cancellation_discards_attachment_and_restores_auto_attach() -> None:
+ relay = StubRelay([{"tabId": 32, "url": "https://frame.example", "title": "Frame"}])
+ relay.fail_send_keys[(None, "Page.getFrameTree")] = asyncio.CancelledError()
+ registry = VirtualTargetRegistry()
+ adapter = ExtensionCdpAdapter(registry, relay)
+
+ with pytest.raises(asyncio.CancelledError):
+ await adapter._set_auto_attach(None, 1, {"autoAttach": True}, None) # type: ignore[arg-type]
+
+ assert adapter._auto_attach is False
+ assert 32 not in adapter._attached_tabs
+ with pytest.raises(KeyError):
+ registry.target_id_for_tab(32)
+ assert ("debugger.detach", {"tabId": 32}) in relay.calls
+
+
+async def test_frame_discovery_broker_failure_discards_attachment_and_restores_auto_attach() -> None:
+ relay = StubRelay([{"tabId": 32, "url": "https://frame.example", "title": "Frame"}])
+ relay.fail_send_keys[(None, "Page.getFrameTree")] = BrowserExtensionBrokerError(
+ "EXTENSION_RESET_IN_PROGRESS", "extension reset in progress"
+ )
+ registry = VirtualTargetRegistry()
+ adapter = ExtensionCdpAdapter(registry, relay)
+ adapter._send = AsyncMock()
+
+ await adapter._handle_client_text(
+ None, # type: ignore[arg-type]
+ json.dumps({"id": 1, "method": "Target.setAutoAttach", "params": {"autoAttach": True}}),
+ )
+
+ adapter._send.assert_awaited_once_with(
+ None,
+ {
+ "id": 1,
+ "error": {
+ "code": -32000,
+ "message": "EXTENSION_RESET_IN_PROGRESS: extension reset in progress",
+ },
+ },
+ )
+ assert adapter._auto_attach is False
+ assert 32 not in adapter._attached_tabs
+ with pytest.raises(KeyError):
+ registry.target_id_for_tab(32)
+ assert ("debugger.detach", {"tabId": 32}) in relay.calls
+
+
+async def test_scope_revoked_during_frame_discovery_discards_the_attachment() -> None:
+ relay = StubRelay([{"tabId": 33, "url": "https://racy.example", "title": "Racy"}])
+ frame_key = (None, "Page.getFrameTree")
+ relay.block_send_keys.add(frame_key)
+ registry = VirtualTargetRegistry()
+ adapter = ExtensionCdpAdapter(registry, relay)
+ generation = adapter._begin_tab_scope(33)
+
+ attaching = asyncio.create_task(adapter._ensure_attached(relay.scoped_tabs[0], generation=generation))
+ await relay.send_started.setdefault(frame_key, asyncio.Event()).wait()
+ adapter._revoke_tab_scope(33)
+ relay.release_send.setdefault(frame_key, asyncio.Event()).set()
+
+ assert await attaching is None
+ assert 33 not in adapter._attached_tabs
+ assert ("debugger.detach", {"tabId": 33}) in relay.calls
+
+
+async def test_auto_attach_scope_revocation_cancellation_rolls_back_prior_tabs() -> None:
+ relay = StubRelay(
+ [
+ {"tabId": 33, "url": "https://first.example", "title": "First"},
+ {"tabId": 34, "url": "https://revoked.example", "title": "Revoked"},
+ ]
+ )
+ relay.block_detach_tab_id = 34
+ registry = VirtualTargetRegistry()
+ adapter = ExtensionCdpAdapter(registry, relay)
+ original_request = relay.request
+ revoked_detach_finished = asyncio.Event()
+
+ async def request_with_scope_revocation(op: str, args: dict, timeout: float = 30.0) -> dict:
+ result = await original_request(op, args, timeout)
+ if op == "debugger.send" and args["tabId"] == 34 and args["method"] == "Page.getFrameTree":
+ adapter._revoke_tab_scope(34)
+ if op == "debugger.detach" and args["tabId"] == 34:
+ revoked_detach_finished.set()
+ return result
+
+ relay.request = request_with_scope_revocation
+ attaching = asyncio.create_task(
+ adapter._set_auto_attach(None, 1, {"autoAttach": True}, None) # type: ignore[arg-type]
+ )
+ await relay.detach_started.wait()
+
+ attaching.cancel()
+ with pytest.raises(asyncio.CancelledError):
+ await attaching
+
+ relay.release_detach.set()
+ await asyncio.wait_for(revoked_detach_finished.wait(), timeout=1)
+
+ assert adapter._auto_attach is False
+ assert adapter._attached_tabs == set()
+ assert ("debugger.detach", {"tabId": 33}) in relay.calls
+ with pytest.raises(KeyError):
+ registry.target_id_for_tab(33)
+ with pytest.raises(KeyError):
+ registry.target_id_for_tab(34)
+
+
+async def test_auto_attach_transactional_failure_restores_state_without_second_response() -> None:
relay = StubRelay(
[
{"tabId": 30, "url": "https://bad.example", "title": "Bad"},
@@ -320,19 +635,15 @@ async def test_auto_attach_post_reply_failure_skips_failed_tab_without_second_re
async with ClientSession() as client, client.ws_connect(adapter.cdp_ws_url) as ws:
await ws.send_json({"id": 1, "method": "Target.setAutoAttach", "params": {"autoAttach": True}})
- assert await receive_response(ws, 1) == {"id": 1, "result": {}}
- attached = await receive_event(ws, "Target.attachedToTarget")
- assert attached["params"]["targetInfo"]["targetId"] == "tab-31"
+ assert await receive_response(ws, 1) == {
+ "id": 1,
+ "error": {"code": -32000, "message": "ATTACH_FAILED: attach failed"},
+ }
with pytest.raises(TimeoutError):
await ws.receive_json(timeout=0.05)
- await ws.send_json({"id": 2, "method": "Browser.close", "params": {}})
- assert await receive_response(ws, 2) == {"id": 2, "result": {}}
- await ws.receive(timeout=1)
finally:
await adapter.stop()
- assert set(relay.released_tabs) == {30, 31}
-
@pytest.mark.asyncio
async def test_tab_removal_tombstones_in_flight_background_attach() -> None:
diff --git a/tests/unit/browser_extension/test_extension_bridge_hardening.py b/tests/unit/browser_extension/test_extension_bridge_hardening.py
new file mode 100644
index 000000000..ff2814deb
--- /dev/null
+++ b/tests/unit/browser_extension/test_extension_bridge_hardening.py
@@ -0,0 +1,529 @@
+from __future__ import annotations
+
+import json
+import shutil
+import subprocess
+from pathlib import Path
+
+import pytest
+
+
+def test_extension_request_isolation_timeouts_and_mv3_reconnect_contract() -> None:
+ node = shutil.which("node")
+ if node is None:
+ pytest.skip("node is required for the extension bridge contract test")
+
+ extension_dir = Path(__file__).parents[3] / "skyvern" / "browser_extension" / "extension"
+ bridge_uri = (extension_dir / "bridge_connection.js").as_uri()
+ debugger_uri = (extension_dir / "debugger_router.js").as_uri()
+ protocol_uri = (extension_dir / "protocol.js").as_uri()
+ script = f"""
+const alarmListeners = [];
+const alarmCreates = [];
+globalThis.chrome = {{
+ alarms: {{
+ onAlarm: {{ addListener(listener) {{ alarmListeners.push(listener); }} }},
+ async create(name, options) {{ alarmCreates.push({{ name, options }}); }},
+ }},
+ storage: {{
+ local: {{
+ async get(defaults) {{ return {{ ...defaults, enabled: false, pairingToken: "token" }}; }},
+ async set() {{}},
+ }},
+ }},
+ debugger: {{
+ onEvent: {{ addListener() {{}} }},
+ onDetach: {{ addListener() {{}} }},
+ async getTargets() {{ return []; }},
+ }},
+}};
+globalThis.WebSocket = {{ OPEN: 1, CONNECTING: 0, CLOSING: 2 }};
+
+const {{ BridgeConnection, nextReconnectDelay }} = await import({json.dumps(bridge_uri)});
+const {{ DebuggerRouter }} = await import({json.dumps(debugger_uri)});
+const {{ BRIDGE_ALARM_NAME, ERROR_CODES }} = await import({json.dumps(protocol_uri)});
+
+const waitUntil = async (predicate, timeoutMs = 250) => {{
+ const deadline = Date.now() + timeoutMs;
+ while (!predicate()) {{
+ if (Date.now() >= deadline) throw new Error("condition timed out");
+ await new Promise((resolve) => setTimeout(resolve, 1));
+ }}
+}};
+
+// A page command that never settles must not hold the global inbound-message chain.
+let releaseWedged;
+const frames = [];
+const bridge = new BridgeConnection({{
+ onRequest: async (op) => {{
+ if (op === "debugger.send") {{
+ return new Promise((resolve) => {{ releaseWedged = resolve; }});
+ }}
+ return {{ tabs: [] }};
+ }},
+ onAuthenticated: async () => undefined,
+ onReset: async () => ({{ executed: true, ok: true, failedTabCount: 0 }}),
+ onStateChange: () => undefined,
+ requestTimeoutMs: 5,
+}});
+bridge.authenticated = true;
+const socket = {{ readyState: 1, send: (raw) => frames.push(JSON.parse(raw)) }};
+bridge.socket = socket;
+bridge.connectionGeneration = 7;
+bridge.enqueueIncomingMessage(
+ JSON.stringify({{ v: 2, type: "request", id: "stuck", op: "debugger.send", args: {{}} }}),
+ 7,
+ socket,
+);
+bridge.enqueueIncomingMessage(
+ JSON.stringify({{ v: 2, type: "request", id: "list", op: "tabs.list", args: {{}} }}),
+ 7,
+ socket,
+);
+await waitUntil(() => frames.some((frame) => frame.id === "list"));
+if (frames.find((frame) => frame.id === "list")?.ok !== true) {{
+ throw new Error("independent request did not complete successfully");
+}}
+if (frames.some((frame) => frame.id === "stuck")) {{
+ throw new Error("wedged request unexpectedly completed");
+}}
+await waitUntil(() => frames.some((frame) => frame.id === "stuck"));
+const timeoutFrame = frames.find((frame) => frame.id === "stuck");
+if (timeoutFrame?.ok !== false || timeoutFrame?.error?.code !== ERROR_CODES.COMMAND_TIMEOUT) {{
+ throw new Error(`request timeout was not structured: ${{JSON.stringify(timeoutFrame)}}`);
+}}
+releaseWedged({{}});
+await new Promise((resolve) => setTimeout(resolve, 5));
+if (frames.filter((frame) => frame.id === "stuck").length !== 1) {{
+ throw new Error("settling a timed-out operation sent a duplicate response");
+}}
+
+// MV3 eviction recovery must have a persistent 30-second alarm plus bounded backoff.
+await bridge.initialize();
+const alarm = alarmCreates.find((entry) => entry.name === BRIDGE_ALARM_NAME);
+if (alarm?.options?.periodInMinutes !== 0.5) {{
+ throw new Error(`unexpected reconnect alarm period: ${{alarm?.options?.periodInMinutes}}`);
+}}
+const backoff = [1_000];
+for (let index = 0; index < 7; index += 1) backoff.push(nextReconnectDelay(backoff.at(-1)));
+if (JSON.stringify(backoff) !== JSON.stringify([1_000, 2_000, 4_000, 8_000, 16_000, 30_000, 30_000, 30_000])) {{
+ throw new Error(`unexpected reconnect backoff: ${{JSON.stringify(backoff)}}`);
+}}
+let alarmKicks = 0;
+bridge.kick = async () => {{ alarmKicks += 1; }};
+alarmListeners.forEach((listener) => listener({{ name: BRIDGE_ALARM_NAME }}));
+await waitUntil(() => alarmKicks === 1);
+
+const tabScope = {{
+ async runTabOperation(_tabId, operation) {{
+ return operation({{ isCurrent: () => true, assertCurrent() {{}} }});
+ }},
+ async assertControllableLocked() {{}},
+ async assertScoped() {{}},
+ isScoped() {{ return true; }},
+ async handleDebuggerDetachLocked() {{}},
+}};
+const events = [];
+const router = new DebuggerRouter({{
+ tabScope,
+ sendEvent: (event, params) => events.push({{ event, params }}),
+ onAttachedChange: () => undefined,
+ attachTimeoutMs: 5,
+ commandTimeoutMs: 5,
+ recoveryTimeoutMs: 5,
+}});
+
+// Attach has a bounded, explicit failure state. A different adopted tab can still attach.
+chrome.debugger.attach = ({{ tabId }}) =>
+ tabId === 11
+ ? new Promise(() => undefined)
+ : tabId === 13
+ ? Promise.reject(new Error("another debugger owns this tab"))
+ : Promise.resolve();
+let attachError;
+try {{
+ await router.attach({{ tabId: 11 }});
+}} catch (error) {{
+ attachError = error;
+}}
+if (attachError?.code !== ERROR_CODES.ATTACH_FAILED || !attachError.message.includes("timed out")) {{
+ throw new Error(`attach failure was not structured: ${{attachError?.code}} ${{attachError?.message}}`);
+}}
+if (router.attachStates.get(11)?.status !== "orphaned_attach") {{
+ throw new Error("attach state machine did not quarantine the unresolved attempt");
+}}
+let rejectedAttachError;
+try {{
+ await router.attach({{ tabId: 13 }});
+}} catch (error) {{
+ rejectedAttachError = error;
+}}
+if (
+ rejectedAttachError?.code !== ERROR_CODES.ATTACH_FAILED ||
+ !rejectedAttachError.message.includes("another debugger owns this tab")
+) {{
+ throw new Error(`rejected attach was not structured: ${{rejectedAttachError?.code}}`);
+}}
+await router.attach({{ tabId: 12 }});
+if (!router.attachedTabs.has(12) || router.attachStates.get(12)?.status !== "attached") {{
+ throw new Error("a healthy adopted tab did not complete the normal attach flow");
+}}
+
+// A wedged CDP command returns COMMAND_TIMEOUT, attempts detach recovery, and does not block another tab.
+router.attachedTabs.add(21);
+router.attachStates.set(21, {{ status: "attached" }});
+router.attachedTabs.add(22);
+router.attachStates.set(22, {{ status: "attached" }});
+const detached = [];
+chrome.debugger.detach = async ({{ tabId }}) => {{ detached.push(tabId); }};
+chrome.debugger.sendCommand = ({{ tabId }}, method) =>
+ tabId === 21 ? new Promise(() => undefined) : Promise.resolve({{ method }});
+let commandError;
+try {{
+ await router.send({{ tabId: 21, method: "Runtime.evaluate", params: {{ expression: "while(true){{}}" }} }});
+}} catch (error) {{
+ commandError = error;
+}}
+if (commandError?.code !== ERROR_CODES.COMMAND_TIMEOUT) {{
+ throw new Error(`command timeout was not structured: ${{commandError?.code}}`);
+}}
+if (!detached.includes(21) || router.attachedTabs.has(21)) {{
+ throw new Error("timed-out command did not execute bounded detach recovery");
+}}
+const healthy = await router.send({{ tabId: 22, method: "Runtime.evaluate", params: {{ expression: "2+2" }} }});
+if (healthy.result.method !== "Runtime.evaluate") {{
+ throw new Error("healthy tab command was blocked by a wedged tab");
+}}
+"""
+
+ 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:
+ pytest.skip("node is required for the extension bridge lifecycle test")
+
+ extension_dir = Path(__file__).parents[3] / "skyvern" / "browser_extension" / "extension"
+ bridge_uri = (extension_dir / "bridge_connection.js").as_uri()
+ debugger_uri = (extension_dir / "debugger_router.js").as_uri()
+ protocol_uri = (extension_dir / "protocol.js").as_uri()
+ tab_scope_uri = (extension_dir / "tab_scope.js").as_uri()
+ script = f"""
+const listeners = {{ created: [], removed: [], updated: [], debuggerEvent: [], debuggerDetach: [] }};
+const tabs = new Map();
+const sessionState = {{}};
+const debuggerAttached = new Set();
+let createTab;
+globalThis.chrome = {{
+ alarms: {{ onAlarm: {{ addListener() {{}} }} }},
+ tabs: {{
+ onCreated: {{ addListener(listener) {{ listeners.created.push(listener); }} }},
+ onRemoved: {{ addListener(listener) {{ listeners.removed.push(listener); }} }},
+ onUpdated: {{ addListener(listener) {{ listeners.updated.push(listener); }} }},
+ create() {{ return new Promise((resolve) => {{ createTab = resolve; }}); }},
+ async get(tabId) {{
+ const tab = tabs.get(tabId);
+ if (!tab) throw new Error("missing tab");
+ return {{ ...tab }};
+ }},
+ async group({{ tabIds }}) {{
+ const tab = tabs.get(tabIds[0]);
+ if (tab) tab.groupId = 700;
+ return 700;
+ }},
+ async ungroup(tabIds) {{
+ for (const tabId of tabIds) {{
+ const tab = tabs.get(tabId);
+ if (tab) tab.groupId = -1;
+ }}
+ }},
+ async remove(tabId) {{ tabs.delete(tabId); }},
+ async update(tabId, values) {{ Object.assign(tabs.get(tabId), values); }},
+ }},
+ tabGroups: {{
+ async query() {{ return []; }},
+ async get(groupId) {{ return {{ id: groupId, title: "Skyvern Controlled" }}; }},
+ async update() {{}},
+ }},
+ windows: {{ async update() {{}} }},
+ storage: {{
+ session: {{
+ async get(defaults) {{ return {{ ...defaults, ...sessionState }}; }},
+ async set(values) {{ Object.assign(sessionState, values); }},
+ async remove(keys) {{ for (const key of keys) delete sessionState[key]; }},
+ }},
+ }},
+ debugger: {{
+ onEvent: {{ addListener(listener) {{ listeners.debuggerEvent.push(listener); }} }},
+ onDetach: {{ addListener(listener) {{ listeners.debuggerDetach.push(listener); }} }},
+ async getTargets() {{
+ return [...debuggerAttached].map((tabId) => ({{ tabId, attached: true }}));
+ }},
+ }},
+}};
+globalThis.WebSocket = {{ OPEN: 1, CONNECTING: 0, CLOSING: 2 }};
+
+const {{ BridgeConnection }} = await import({json.dumps(bridge_uri)});
+const {{ DebuggerRouter }} = await import({json.dumps(debugger_uri)});
+const {{ ERROR_CODES }} = await import({json.dumps(protocol_uri)});
+const {{ TabScope }} = await import({json.dumps(tab_scope_uri)});
+
+const delay = (milliseconds) => new Promise((resolve) => setTimeout(resolve, milliseconds));
+const waitUntil = async (predicate, timeoutMs = 250) => {{
+ const deadline = Date.now() + timeoutMs;
+ while (!predicate()) {{
+ if (Date.now() >= deadline) throw new Error("condition timed out");
+ await delay(1);
+ }}
+}};
+const settleWithin = (promise, timeoutMs = 100) => Promise.race([
+ promise,
+ delay(timeoutMs).then(() => {{ throw new Error("promise did not settle"); }}),
+]);
+
+const scope = new TabScope({{ sendEvent: () => undefined, operationTimeoutMs: 20 }});
+await scope.initialize();
+const originalRemove = chrome.tabs.remove;
+let releaseRemove;
+chrome.tabs.remove = (tabId) => {{
+ if (tabId === 13) {{
+ return new Promise((resolve) => {{
+ releaseRemove = () => {{
+ tabs.delete(tabId);
+ resolve();
+ }};
+ }});
+ }}
+ return originalRemove(tabId);
+}};
+
+// Reset must invalidate an in-flight create before ACK and the late Chrome result
+// must never scope a tab into the new epoch.
+const createOutcome = scope.create({{ url: "https://old-client.example" }}).then(
+ () => null,
+ (error) => error,
+);
+await waitUntil(() => typeof createTab === "function");
+await settleWithin(scope.prepareForReset());
+await scope.reset();
+scope.finishReset();
+tabs.set(10, {{ id: 10, windowId: 1, groupId: -1, url: "https://old-client.example" }});
+createTab(tabs.get(10));
+const createError = await settleWithin(createOutcome);
+if (createError?.code !== ERROR_CODES.COMMAND_TIMEOUT || scope.scopedTabIds.has(10)) {{
+ throw new Error(`late create crossed reset: ${{createError?.code}} scoped=${{scope.scopedTabIds.has(10)}}`);
+}}
+
+// 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" }});
+scope.scopedTabIds.add(13);
+const removeOutcome = scope.remove({{ tabId: 13 }}).then(
+ () => null,
+ (error) => error,
+);
+await waitUntil(() => typeof releaseRemove === "function");
+await settleWithin(scope.prepareForReset());
+await scope.reset();
+scope.finishReset();
+if (!scope.quarantinedTabIds.has(13)) {{
+ throw new Error("removal was not quarantined before reset");
+}}
+const shareOutcome = scope.shareTab(13).then(
+ () => null,
+ (error) => error,
+);
+const shareError = await settleWithin(shareOutcome);
+if (
+ shareError?.code !== ERROR_CODES.COMMAND_TIMEOUT ||
+ scope.scopedTabIds.has(13)
+) {{
+ throw new Error(`removal crossed reset: ${{shareError?.code}} scoped=${{scope.scopedTabIds.has(13)}}`);
+}}
+releaseRemove();
+await settleWithin(removeOutcome);
+await waitUntil(() => !scope.quarantinedTabIds.has(13));
+
+// A permanently unresolved scoped operation must not strand resetFinished.
+const wedgedOutcome = scope.runTabOperation(99, () => new Promise(() => undefined)).then(
+ () => null,
+ (error) => error,
+);
+await waitUntil(() => scope.activeOperationCount === 1);
+await settleWithin(scope.prepareForReset());
+await scope.reset();
+scope.finishReset();
+const wedgedError = await settleWithin(wedgedOutcome);
+if (wedgedError?.code !== ERROR_CODES.COMMAND_TIMEOUT) {{
+ throw new Error(`wedged operation was not cancelled by reset: ${{wedgedError?.code}}`);
+}}
+
+for (const tabId of [11, 12, 21]) {{
+ tabs.set(tabId, {{ id: tabId, windowId: 1, groupId: -1, url: "https://example.test" }});
+ scope.scopedTabIds.add(tabId);
+}}
+const router = new DebuggerRouter({{
+ tabScope: scope,
+ sendEvent: () => undefined,
+ onAttachedChange: () => undefined,
+ attachTimeoutMs: 5,
+ commandTimeoutMs: 5,
+ recoveryTimeoutMs: 5,
+ operationDeadlineMarginMs: 1,
+}});
+
+// Queued callers share the failed attach state. A late successful attach is
+// quarantined and detached before a later caller can retry.
+let resolveLateAttach;
+let attachCalls = 0;
+chrome.debugger.attach = ({{ tabId }}) => {{
+ attachCalls += 1;
+ if (tabId !== 11) {{
+ debuggerAttached.add(tabId);
+ return Promise.resolve();
+ }}
+ return new Promise((resolve) => {{
+ resolveLateAttach = () => {{ debuggerAttached.add(tabId); resolve(); }};
+ }});
+}};
+const firstAttach = router.attach({{ tabId: 11 }}).then(() => null, (error) => error);
+await waitUntil(() => router.attachStates.get(11)?.status === "attaching");
+const queuedAttach = router.attach({{ tabId: 11 }}).then(() => null, (error) => error);
+const firstAttachError = await settleWithin(firstAttach);
+const queuedAttachError = await settleWithin(queuedAttach);
+if (
+ firstAttachError?.code !== ERROR_CODES.ATTACH_FAILED ||
+ queuedAttachError?.code !== ERROR_CODES.ATTACH_FAILED ||
+ attachCalls !== 1
+) {{
+ throw new Error(`attach retry storm: calls=${{attachCalls}} first=${{firstAttachError?.code}} queued=${{queuedAttachError?.code}}`);
+}}
+const detachEvents = [];
+chrome.debugger.detach = async ({{ tabId }}) => {{
+ detachEvents.push(tabId);
+ debuggerAttached.delete(tabId);
+}};
+resolveLateAttach();
+await waitUntil(() => detachEvents.includes(11) && !router.attachStates.has(11));
+if (debuggerAttached.has(11) || router.attachedTabs.has(11)) {{
+ throw new Error("late attach left a zombie debugger session");
+}}
+
+// A detach callback that arrives after the timeout must reconcile local state.
+await router.attach({{ tabId: 12 }});
+let resolveLateDetach;
+chrome.debugger.detach = ({{ tabId }}) => new Promise((resolve) => {{
+ resolveLateDetach = () => {{ debuggerAttached.delete(tabId); resolve(); }};
+}});
+const detachError = await settleWithin(
+ router.detach({{ tabId: 12 }}).then(() => null, (error) => error),
+);
+if (detachError?.code !== ERROR_CODES.DEBUGGER_DETACHED) {{
+ throw new Error(`late detach did not return DEBUGGER_DETACHED: ${{detachError?.code}}`);
+}}
+resolveLateDetach();
+await waitUntil(() => !router.attachedTabs.has(12) && !router.attachStates.has(12));
+
+router.attachStates.set(77, {{ status: "failed", reason: "old failure" }});
+await router.reset();
+if (router.attachStates.has(77)) {{
+ throw new Error("reset retained a failed attach state");
+}}
+
+// The command, timeout recovery, and response all stay inside the genuine
+// per-tab queue. A queued same-tab operation cannot delay recovery past the
+// bridge's outer response deadline.
+scope.scopedTabIds.add(21);
+router.attachedTabs.add(21);
+router.attachStates.set(21, {{ status: "attached" }});
+debuggerAttached.add(21);
+const order = [];
+chrome.debugger.sendCommand = () => {{
+ order.push("command-start");
+ return new Promise(() => undefined);
+}};
+let resolveRecoveryDetach;
+chrome.debugger.detach = ({{ tabId }}) => {{
+ order.push("detach-start");
+ return new Promise((resolve) => {{
+ resolveRecoveryDetach = () => {{
+ debuggerAttached.delete(tabId);
+ order.push("detach-late-done");
+ resolve();
+ }};
+ }});
+}};
+const frames = [];
+const bridge = new BridgeConnection({{
+ onRequest: (op, args) => op === "debugger.send" ? router.send(args) : Promise.resolve({{}}),
+ onAuthenticated: async () => undefined,
+ onReset: async () => ({{ executed: true, ok: true, failedTabCount: 0 }}),
+ onStateChange: () => undefined,
+ requestTimeoutMs: 40,
+}});
+bridge.authenticated = true;
+const socket = {{ readyState: WebSocket.OPEN, send: (raw) => {{ order.push("response"); frames.push(JSON.parse(raw)); }} }};
+bridge.socket = socket;
+bridge.connectionGeneration = 3;
+let releasePriorOperation;
+const priorOperation = scope.runTabOperation(21, () => {{
+ order.push("prior-start");
+ return new Promise((resolve) => {{ releasePriorOperation = resolve; }});
+}});
+await waitUntil(() => order.includes("prior-start"));
+bridge.enqueueIncomingMessage(
+ JSON.stringify({{
+ v: 2,
+ type: "request",
+ id: "ordered-timeout",
+ op: "debugger.send",
+ args: {{ tabId: 21, method: "Page.navigate", params: {{ url: "https://example.test" }} }},
+ }}),
+ 3,
+ socket,
+);
+await delay(2);
+releasePriorOperation();
+await priorOperation;
+await waitUntil(() => order.includes("command-start"));
+const queuedOperation = scope.runTabOperation(21, () => {{
+ order.push("queued-start");
+ return new Promise(() => undefined);
+}}).catch(() => undefined);
+await waitUntil(() => frames.length === 1);
+const frame = frames[0];
+if (frame.ok !== false || frame.error?.code !== ERROR_CODES.COMMAND_TIMEOUT) {{
+ throw new Error(`unexpected bridge timeout frame: ${{JSON.stringify(frame)}}`);
+}}
+await waitUntil(() => order.includes("queued-start"));
+if (
+ router.attachStates.get(21)?.status !== "quarantined" ||
+ router.attachedTabs.has(21) ||
+ !(order.indexOf("detach-start") < order.indexOf("queued-start") &&
+ order.indexOf("detach-start") < order.indexOf("response"))
+) {{
+ throw new Error(`recovery escaped the tab queue or outer deadline: ${{JSON.stringify(order)}}`);
+}}
+resolveRecoveryDetach();
+await settleWithin(queuedOperation);
+await waitUntil(() => !router.attachedTabs.has(21) && !router.attachStates.has(21));
+"""
+
+ result = subprocess.run(
+ [node, "--input-type=module", "--eval", script],
+ capture_output=True,
+ text=True,
+ check=False,
+ timeout=10,
+ )
+
+ assert result.returncode == 0, result.stderr
diff --git a/tests/unit/browser_extension/test_mcp_glue.py b/tests/unit/browser_extension/test_mcp_glue.py
index 63a4eea65..69a01cc6d 100644
--- a/tests/unit/browser_extension/test_mcp_glue.py
+++ b/tests/unit/browser_extension/test_mcp_glue.py
@@ -16,7 +16,7 @@ import pytest
import typer
from typer.testing import CliRunner
-from skyvern.browser_extension.errors import BrowserExtensionError
+from skyvern.browser_extension.errors import BrowserExtensionBrokerError, BrowserExtensionError
from skyvern.browser_extension.runtime import BrowserExtensionRuntime
from skyvern.cli import run_commands
from skyvern.cli.commands import browser as browser_commands
@@ -205,6 +205,44 @@ async def test_broker_session_opens_one_step_pairing_inline(
assert runtime.wait_for_extension.await_args_list == [call(8.0), call(remaining_wait)]
+ ("broker_error", "hint_fragment", "excluded_fragment"),
+ [
+ (
+ BrowserExtensionBrokerError("INVALID_READINESS", "Broker readiness response is invalid"),
+ "startup.log",
+ "SKYVERN_BROWSER_EXTENSION_PORT",
+ ),
+ (
+ BrowserExtensionBrokerError("PORT_IN_USE", "Browser-extension port is already in use"),
+ "SKYVERN_BROWSER_EXTENSION_PORT",
+ "startup.log",
+ ),
+ ],
+)
+async def test_broker_startup_failures_have_distinct_actionable_hints(
+ monkeypatch: pytest.MonkeyPatch,
+ broker_error: BrowserExtensionBrokerError,
+ hint_fragment: str,
+ excluded_fragment: str,
+) -> None:
+ monkeypatch.setenv("BROWSER_TYPE", "extension-connect")
+ monkeypatch.delenv("SKYVERN_BROWSER_EXTENSION_BROKER", raising=False)
+ monkeypatch.setattr(
+ mcp_session.BrowserExtensionRuntime,
+ "get_or_start",
+ AsyncMock(side_effect=broker_error),
+ )
+
+ result = await mcp_session.skyvern_browser_session_create()
+
+ assert result["ok"] is False
+ assert broker_error.code in result["error"]["message"]
+ assert hint_fragment in result["error"]["hint"]
+ assert excluded_fragment not in result["error"]["hint"]
+
+
@pytest.mark.asyncio
async def test_session_create_extension_connected_returns_safe_success_payload(
monkeypatch: pytest.MonkeyPatch,
diff --git a/tests/unit/browser_extension/test_protocol.py b/tests/unit/browser_extension/test_protocol.py
index 59b6e497d..710ff8496 100644
--- a/tests/unit/browser_extension/test_protocol.py
+++ b/tests/unit/browser_extension/test_protocol.py
@@ -99,9 +99,11 @@ def test_protocol_allowlists_match_contract() -> None:
"TAB_NOT_FOUND",
"TAB_NOT_SCOPED",
"RESTRICTED_URL",
+ "ATTACH_FAILED",
"DEBUGGER_DETACHED",
"CDP_METHOD_NOT_ALLOWED",
"CDP_ERROR",
+ "COMMAND_TIMEOUT",
"INTERNAL",
}
)
@@ -270,13 +272,18 @@ const router = new DebuggerRouter({{
onAttachedChange: () => undefined,
}});
router.attachedTabs.add(7);
+router.attachStates.set(7, {{ status: "attached" }});
const failed = await router.reset();
-if (failed.failedTabCount !== 1 || !router.attachedTabs.has(7)) {{
- throw new Error("live debugger attachment was certified as detached");
+if (
+ failed.failedTabCount !== 1 ||
+ router.attachedTabs.has(7) ||
+ router.attachStates.get(7)?.status !== "quarantined"
+) {{
+ throw new Error("live debugger attachment was not quarantined after detach failure");
}}
targets = [];
const benign = await router.reset();
-if (benign.failedTabCount !== 0 || router.attachedTabs.has(7)) {{
+if (benign.failedTabCount !== 0 || router.attachedTabs.has(7) || router.attachStates.has(7)) {{
throw new Error("already-detached or missing target was not accepted");
}}
let detachCleanupCount = 0;
diff --git a/tests/unit/conftest.py b/tests/unit/conftest.py
index 9c150b1eb..46a084daf 100644
--- a/tests/unit/conftest.py
+++ b/tests/unit/conftest.py
@@ -141,6 +141,18 @@ def reset_collapse_xp_assignment_memo():
_clear()
[email protected](autouse=True)
+def restore_interpreter_traceback_hooks() -> Iterator[None]:
+ """setup_logger() replaces the three interpreter hooks process-wide.
+
+ Left installed they outlive the test that configured logging and shadow pytest's own
+ unraisable/thread-exception plugins, which install their hooks per test.
+ """
+ hooks = (sys.excepthook, threading.excepthook, sys.unraisablehook)
+ yield
+ sys.excepthook, threading.excepthook, sys.unraisablehook = hooks
+
+
@pytest.fixture(autouse=True)
def reset_mcp_stateless_http_mode():
"""Keep MCP transport mode from leaking between independently collected test files."""
diff --git a/tests/unit/data/click_overlay_named_dismiss.html b/tests/unit/data/click_overlay_named_dismiss.html
new file mode 100644
index 000000000..cba8f6969
--- /dev/null
+++ b/tests/unit/data/click_overlay_named_dismiss.html
@@ -0,0 +1,10 @@
+<html><body>
+ <main><button id="btn-open-statements">Continue to statements</button></main>
+ <div class="overlay" id="terms-overlay">
+ <form class="modal" id="terms-modal" role="dialog" aria-modal="true">
+ <h2>Terms and Privacy</h2>
+ <label><input type="checkbox" id="accept-terms" name="accept_terms" /><span>I agree.</span></label>
+ <button type="submit" id="btn-continue">Continue</button>
+ </form>
+ </div>
+</body></html>
diff --git a/tests/unit/embedded/test_sqlite_server_mode.py b/tests/unit/embedded/test_sqlite_server_mode.py
index 0d11b23d3..92ffa537a 100644
--- a/tests/unit/embedded/test_sqlite_server_mode.py
+++ b/tests/unit/embedded/test_sqlite_server_mode.py
@@ -164,6 +164,30 @@ async def test_sqlite_bootstrap_from_empty_db(sqlite_bootstrap_db, patched_env_w
assert org.organization_name == "Skyvern-local"
+async def test_sqlite_bootstrap_upgrades_legacy_organization_table(
+ sqlite_bootstrap_db,
+ patched_env_writes,
+) -> None:
+ """Bootstrap adds the slug column and partial unique index to an existing SQLite database."""
+ from skyvern.forge.api_app import _bootstrap_sqlite
+ from skyvern.forge.sdk.db.models import Base
+
+ async with sqlite_bootstrap_db.engine.begin() as conn:
+ await conn.run_sync(Base.metadata.create_all)
+ await conn.exec_driver_sql("DROP INDEX IF EXISTS uq_organizations_slug")
+ await conn.exec_driver_sql("ALTER TABLE organizations DROP COLUMN slug")
+
+ await _bootstrap_sqlite()
+
+ async with sqlite_bootstrap_db.engine.begin() as conn:
+ columns = {row[1] for row in (await conn.exec_driver_sql("PRAGMA table_info(organizations)")).all()}
+ indexes = {row[1] for row in (await conn.exec_driver_sql("PRAGMA index_list(organizations)")).all()}
+
+ assert "slug" in columns
+ assert "uq_organizations_slug" in indexes
+
+
@pytest.mark.asyncio
async def test_sqlite_bootstrap_syncs_existing_env_api_key(
monkeypatch: pytest.MonkeyPatch,
diff --git a/tests/unit/forge/sdk/db/test_tasks_repository.py b/tests/unit/forge/sdk/db/test_tasks_repository.py
index 05d8e2182..567d80786 100644
--- a/tests/unit/forge/sdk/db/test_tasks_repository.py
+++ b/tests/unit/forge/sdk/db/test_tasks_repository.py
@@ -1,5 +1,7 @@
import pytest
+from skyvern.forge.sdk.db.enums import TaskType
+
@pytest.mark.asyncio
async def test_total_unique_step_order_count_deduplicates_retries_in_sqlite(agent_db) -> None:
@@ -41,3 +43,26 @@ async def test_total_unique_step_order_count_deduplicates_retries_in_sqlite(agen
)
== 2
)
+
+
+async def test_internal_synthetic_sdk_task_round_trips_through_repository(agent_db) -> None:
+ organization = await agent_db.organizations.create_organization(
+ organization_name="Test organization",
+ organization_id="o_test_synthetic_sdk_task",
+ )
+ task = await agent_db.tasks.create_task(
+ url="https://example.com",
+ title="Synthetic SDK action",
+ navigation_goal="Click the button",
+ data_extraction_goal=None,
+ navigation_payload=None,
+ organization_id=organization.organization_id,
+ task_type=TaskType.synthetic_sdk_action,
+ )
+
+ assert task.task_type == TaskType.synthetic_sdk_action
+
+ persisted = await agent_db.tasks.get_task(task.task_id, organization.organization_id)
+ assert persisted is not None
+ assert persisted.task_type == TaskType.synthetic_sdk_action
diff --git a/tests/unit/forge/sdk/db/test_workflows_repository_search.py b/tests/unit/forge/sdk/db/test_workflows_repository_search.py
index 9ced624b1..5dacb1589 100644
--- a/tests/unit/forge/sdk/db/test_workflows_repository_search.py
+++ b/tests/unit/forge/sdk/db/test_workflows_repository_search.py
@@ -1,4 +1,6 @@
-"""Regression tests for SKY-8795: workflow list search must match workflow_permanent_id.
+"""Regression tests for the shape of workflows-repository queries.
+
+SKY-8795: workflow list search must match workflow_permanent_id.
The /workflows page sends `search_key` to the backend. Before the fix, the search
only matched `workflows.title`, `folders.title`, and parameter metadata — typing a
@@ -11,7 +13,9 @@ from typing import Any
from unittest.mock import AsyncMock, MagicMock
import pytest
+from sqlalchemy import event
+from skyvern.forge.sdk.db.agent_db import AgentDB
from skyvern.forge.sdk.db.repositories.workflows import WorkflowsRepository
@@ -58,3 +62,44 @@ async def test_get_workflows_by_organization_id_search_key_matches_workflow_perm
# that pasting a wpid_* into the workflows page search box finds the workflow.
assert "workflows.workflow_permanent_id" in compiled_where
assert "wpid_510867674757598984" in compiled_where
+
+
+async def test_get_workflow_by_permanent_id_bounds_the_latest_version_lookup(agent_db: AgentDB, db_engine: Any) -> None:
+ """The latest-version lookup must emit LIMIT.
+
+ Result.first() returns the newest row whether or not the statement is bounded, so a
+ correctness assertion cannot catch this: unbounded, the query fetches and discards every
+ version row for the wpid, and each discarded row carries a full workflow_definition.
+ """
+ org = await agent_db.organizations.create_organization(
+ organization_name="Version Growth Org",
+ domain="version-growth.test",
+ )
+ wpid = "wpid_version_growth"
+ for version in range(1, 6):
+ await agent_db.workflows.create_workflow(
+ title=f"v{version}",
+ workflow_definition={"parameters": [], "blocks": []},
+ organization_id=org.organization_id,
+ workflow_permanent_id=wpid,
+ version=version,
+ )
+
+ statements: list[str] = []
+
+ @event.listens_for(db_engine.sync_engine, "after_cursor_execute")
+ def _capture(conn: Any, cursor: Any, statement: str, parameters: Any, context: Any, executemany: bool) -> None:
+ statements.append(statement)
+
+ workflow = await agent_db.workflows.get_workflow_by_permanent_id(
+ workflow_permanent_id=wpid,
+ organization_id=org.organization_id,
+ )
+
+ assert workflow is not None
+ assert workflow.version == 5
+
+ version_lookups = [s for s in statements if "ORDER BY workflows.version DESC" in s]
+ assert version_lookups, "expected the latest-version lookup to be issued"
+ assert all("LIMIT" in s.upper() for s in version_lookups)
diff --git a/tests/unit/test_agent_otp_routing.py b/tests/unit/test_agent_otp_routing.py
index b537f17a8..8234f527d 100644
--- a/tests/unit/test_agent_otp_routing.py
+++ b/tests/unit/test_agent_otp_routing.py
@@ -1,4 +1,19 @@
-"""Regression tests for Agent OTP routing."""
+"""Regression tests for Agent OTP source routing.
+
+Covers the post-first-plan skip seam: after the first planning pass produces a plan,
+``handle_potential_OTP_actions`` may skip the polling verification re-plan only when the retained
+first-pass actions are an existing multi-field consecutive single-digit sequence AND the runtime
+already holds the ``totp_codes[f"{task_id}_secret"]`` stash the per-digit execution path types. This
+is the sole runtime-consumable shape on this v1 two-pass seam. A ``get_verification_code`` action
+must re-plan (it is not runtime-materialized on this path); a literal digit string must re-plan; a
+fabricated placeholder must re-plan; a raw or wrapped provider marker input
+(``BW_TOTP``/``OP_TOTP``/``AZ_TOTP``) must re-plan; an ordinary action dict carrying a ``totp`` key
+must re-plan; a multi-field sequence without the runtime stash must re-plan; payload OTP must still
+win; and magic-link framing must survive into the first prompt. The new gate never selects or reads
+a credential candidate — the agent no longer imports ``has_credential_totp_candidate``. Also covers
+that handle_potential_verification_code delegates to resolve_otp_value without a pre-resolver DB
+roundtrip.
+"""
from __future__ import annotations
@@ -7,12 +22,23 @@ from unittest.mock import AsyncMock, MagicMock
import pytest
-from skyvern.forge.agent import ForgeAgent, PromptBuildResult, _model_is_abandoning_verification
+from skyvern.forge.agent import (
+ ForgeAgent,
+ PromptBuildResult,
+ _model_is_abandoning_verification,
+)
from skyvern.forge.sdk.core import skyvern_context
from skyvern.forge.sdk.core.skyvern_context import SkyvernContext
from skyvern.forge.sdk.schemas.totp_codes import OTPType
+from skyvern.forge.sdk.services.bitwarden import BitwardenConstants
+from skyvern.forge.sdk.workflow.context_manager import WorkflowRunContext
+from skyvern.forge.sdk.workflow.models.parameter import CredentialParameter
+from skyvern.schemas.run_enums import RunEngine
+from skyvern.services import otp_service
from skyvern.services.otp_service import OTPValue
+_VALID_TOTP_SEED = "JBSWY3DPEHPK3PXP"
+
def _make_task(
*,
@@ -35,38 +61,522 @@ def _make_task(
)
-async def test_handle_potential_verification_code_uses_resolver_without_db_lookup(
+class _FakeWorkflowRunContext:
+ def __init__(self, values: dict[str, dict[str, str]], secrets: dict[str, str]) -> None:
+ self.values = values
+ self.secrets = secrets
+
+ def totp_secret_value_key(self, totp_secret_id: str) -> str:
+ return f"{totp_secret_id}_value"
+
+ def get_original_secret_value_or_none(self, key: str) -> str | None:
+ return self.secrets.get(key)
+
+
+def _patch_workflow_context(monkeypatch: pytest.MonkeyPatch, fake: _FakeWorkflowRunContext) -> None:
+ monkeypatch.setattr(
+ otp_service,
+ "app",
+ SimpleNamespace(
+ WORKFLOW_CONTEXT_MANAGER=SimpleNamespace(
+ get_workflow_run_context=lambda _wr_id: fake,
+ has_workflow_run_context=lambda _wr_id: True,
+ ),
+ ),
+ )
+
+
+def _usable_credential_context() -> _FakeWorkflowRunContext:
+ return _FakeWorkflowRunContext(
+ values={"credentials": {"username": "u", "password": "p", "totp": "tot"}},
+ secrets={"tot_value": _VALID_TOTP_SEED},
+ )
+
+
+def _real_credential_context(
+ *, seed: str = "otpauth://totp/Test?secret=" + _VALID_TOTP_SEED, placeholder: str = "cred_totp"
+) -> WorkflowRunContext:
+ context = WorkflowRunContext("title", "wid", "wpid", "wr_test", None)
+ context.parameters["credentials"] = CredentialParameter.model_construct()
+ context.values["credentials"] = {"username": "u", "password": "p", "totp": placeholder}
+ context.secrets[placeholder] = BitwardenConstants.TOTP
+ context.secrets[f"{placeholder}_value"] = seed
+ return context
+
+
+def _otp_json_response(actions: list, **overrides: object) -> dict:
+ """First-plan LLM response on a verification page. Defaults request the verification-code
+ branch (place=True, should_enter=True) so the skip predicate is what decides re-plan-vs-skip."""
+ return {
+ "place_to_enter_verification_code": True,
+ "should_enter_verification_code": True,
+ "should_verify_by_magic_link": False,
+ "actions": actions,
+ **overrides,
+ }
+
+
+async def _run_otp_actions(
monkeypatch: pytest.MonkeyPatch,
-) -> None:
- task = _make_task(navigation_payload={"otp_code": "654321"})
+ task: SimpleNamespace,
+ json_response: dict,
+) -> tuple[AsyncMock, MagicMock, tuple]:
+ """Drive the real handle_potential_OTP_actions post-plan seam. Returns (hpvc mock, parse mock,
+ result). hpvc awaited ⇒ the polling verification re-plan fired; not awaited ⇒ the first plan was
+ kept and ``result`` is what the seam returned."""
step = MagicMock()
+ step.step_id = "stp_test"
+ step.order = 0
scraped_page = MagicMock()
browser_state = MagicMock()
+
+ hpvc = AsyncMock(return_value={"actions": [{"action_type": "INPUT_TEXT", "text": "999999"}]})
+ monkeypatch.setattr(ForgeAgent, "handle_potential_verification_code", hpvc)
+ parse_mock = MagicMock(return_value=[object()])
+ monkeypatch.setattr("skyvern.forge.agent.parse_actions", parse_mock)
+ monkeypatch.setattr("skyvern.forge.agent.stamp_parsed_actions", MagicMock())
+
+ agent = ForgeAgent.__new__(ForgeAgent)
+ result = await agent.handle_potential_OTP_actions(task, step, scraped_page, browser_state, json_response)
+ return hpvc, parse_mock, result
+
+
+_FABRICATED_PLACEHOLDER_INPUT = [{"action_type": "INPUT_TEXT", "id": "AAAA", "text": "placeholder_FAKE_totp"}]
+_PROVIDER_MARKER_INPUT = [{"action_type": "INPUT_TEXT", "id": "AAAA", "text": "OP_TOTP"}]
+_GET_VERIFICATION_CODE = [{"action_type": "get_verification_code", "reasoning": "fetch code"}]
+_MULTI_FIELD = [{"action_type": "INPUT_TEXT", "id": f"F{i}", "text": str(i)} for i in range(1, 7)]
+_SAME_FORM_MULTI_FIELD = [
+ *[{"action_type": "INPUT_TEXT", "id": f"F{i}", "text": str(i)} for i in range(1, 7)],
+ {"action_type": "CLICK", "id": "BBBB", "reasoning": "submit the code"},
+]
+_LEADING_ACTION_MULTI_FIELD = [
+ {"action_type": "CLICK", "id": "BBBB", "reasoning": "focus the code field"},
+ *[{"action_type": "INPUT_TEXT", "id": f"F{i}", "text": str(i)} for i in range(1, 7)],
+]
+_SAME_FORM_GET_VERIFICATION_CODE = [
+ {"action_type": "CLICK", "id": "BBBB", "reasoning": "focus the code field"},
+ {"action_type": "get_verification_code", "reasoning": "fetch code"},
+]
+_WRAPPED_PROVIDER_MARKER_INPUT = [{"action_type": "INPUT_TEXT", "id": "AAAA", "text": "prefix_OP_TOTP_suffix"}]
+_LITERAL_INPUT = [{"action_type": "INPUT_TEXT", "id": "AAAA", "text": "123456"}]
+_ORDINARY_DICT_TOTP = [{"action_type": "INPUT_TEXT", "id": "AAAA", "text": "hello", "totp": "placeholder_CGft_totp"}]
+
+
[email protected]("active_key", ["credentials", None])
+async def test_single_field_registered_credential_placeholder_skips_and_preserves_click(
+ monkeypatch: pytest.MonkeyPatch, active_key: str | None
+) -> None:
+ context = _real_credential_context()
+ manager = SimpleNamespace(
+ has_workflow_run_context=lambda _id: True,
+ get_workflow_run_context=lambda _id: context,
+ )
+ monkeypatch.setattr(otp_service.app, "WORKFLOW_CONTEXT_MANAGER", manager)
+ monkeypatch.setattr("skyvern.forge.agent.app.WORKFLOW_CONTEXT_MANAGER", manager)
+ task = _make_task()
+ actions = [{"action_type": "INPUT_TEXT", "id": "AAAA", "text": "cred_totp"}, {"action_type": "CLICK", "id": "BBBB"}]
+ response = _otp_json_response(actions)
+ with skyvern_context.scoped(SkyvernContext(task_id=task.task_id, active_credential_parameter_key=active_key)):
+ hpvc, _parse, result = await _run_otp_actions(monkeypatch, task, response)
+ hpvc.assert_not_awaited()
+ assert result[0] is response and result[0]["actions"] is actions and result[1] == []
+
+
+ "case",
+ [
+ ("literal", [{"action_type": "INPUT_TEXT", "text": "123456"}], "credentials"),
+ ("raw_marker", [{"action_type": "INPUT_TEXT", "text": "BW_TOTP"}], "credentials"),
+ ("wrapped_marker", [{"action_type": "INPUT_TEXT", "text": "x_BW_TOTP_x"}], "credentials"),
+ ("fabricated", [{"action_type": "INPUT_TEXT", "text": "placeholder_FAKE_totp"}], "credentials"),
+ ("wrapped_registered", [{"action_type": "INPUT_TEXT", "text": "x_cred_totp"}], "credentials"),
+ ("password", [{"action_type": "INPUT_TEXT", "text": "password_totp"}], "credentials"),
+ ("foreign", [{"action_type": "INPUT_TEXT", "text": "other_totp"}], "credentials"),
+ ("missing_seed", [{"action_type": "INPUT_TEXT", "text": "cred_totp"}], "credentials"),
+ ("unparseable", [{"action_type": "INPUT_TEXT", "text": "cred_totp"}], "credentials"),
+ (
+ "leading_click",
+ [{"action_type": "CLICK"}, {"action_type": "INPUT_TEXT", "text": "cred_totp"}],
+ "credentials",
+ ),
+ (
+ "two_inputs",
+ [{"action_type": "INPUT_TEXT", "text": "cred_totp"}, {"action_type": "INPUT_TEXT", "text": "x"}],
+ "credentials",
+ ),
+ ],
+)
+async def test_single_field_negative_matrix_replans(monkeypatch: pytest.MonkeyPatch, case: tuple) -> None:
+ name, actions, active = case
+ context = _real_credential_context(seed="bad" if name == "unparseable" else _VALID_TOTP_SEED)
+ if name == "missing_seed":
+ context.secrets.pop("cred_totp_value")
+ if name == "foreign":
+ context.values["other"] = {"totp": "other_totp"}
+ context.parameters["other"] = CredentialParameter.model_construct()
+ context.secrets["other_totp"] = BitwardenConstants.TOTP
+ context.secrets["other_totp_value"] = "otpauth://totp/Other?secret=" + _VALID_TOTP_SEED
+ if name == "password":
+ context.secrets["password_totp"] = "password-secret"
+ context.values["credentials"]["password"] = "password_totp"
+ manager = SimpleNamespace(has_workflow_run_context=lambda _id: True, get_workflow_run_context=lambda _id: context)
+ monkeypatch.setattr(otp_service.app, "WORKFLOW_CONTEXT_MANAGER", manager)
+ monkeypatch.setattr("skyvern.forge.agent.app.WORKFLOW_CONTEXT_MANAGER", manager)
+ task = _make_task()
+ with skyvern_context.scoped(SkyvernContext(task_id=task.task_id, active_credential_parameter_key=active)):
+ hpvc, _parse, _result = await _run_otp_actions(monkeypatch, task, _otp_json_response(actions))
+ hpvc.assert_awaited_once()
+
+
+ "first_actions",
+ [
+ pytest.param(_PROVIDER_MARKER_INPUT, id="provider_marker_replans"),
+ pytest.param(_GET_VERIFICATION_CODE, id="get_verification_code_replans"),
+ pytest.param(_SAME_FORM_GET_VERIFICATION_CODE, id="same_form_click_plus_get_verification_code_replans"),
+ pytest.param(_LITERAL_INPUT, id="literal_digits_replans"),
+ pytest.param(_FABRICATED_PLACEHOLDER_INPUT, id="fabricated_placeholder_replans"),
+ pytest.param(_ORDINARY_DICT_TOTP, id="ordinary_dict_totp_key_replans"),
+ pytest.param(_WRAPPED_PROVIDER_MARKER_INPUT, id="wrapped_provider_marker_replans"),
+ ],
+)
+async def test_non_multi_field_shapes_always_replan(
+ monkeypatch: pytest.MonkeyPatch,
+ first_actions: list,
+) -> None:
+ """The sole runtime-consumable shape on this v1 two-pass seam is an existing multi-field
+ single-digit sequence backed by the runtime secret stash. Every other first-pass shape must keep
+ the polling re-plan — even with a usable credential registered and a runtime stash present, so a
+ predicate that keyed on secret presence would wrongly skip.
+
+ A ``get_verification_code`` action (and a same-form click preceding it) is not runtime-materialized
+ on this path and must re-plan; a literal digit string, a fabricated placeholder, an ordinary action
+ dict carrying a ``totp`` key, and a raw or wrapped provider marker input must all re-plan.
+ """
+ _patch_workflow_context(monkeypatch, _usable_credential_context())
+ task = _make_task()
+
+ ctx = SkyvernContext(
+ task_id=task.task_id,
+ active_credential_parameter_key="credentials",
+ totp_codes={f"{task.task_id}_secret": _VALID_TOTP_SEED},
+ )
+ skyvern_context.set(ctx)
+ try:
+ hpvc, _parse_mock, _result = await _run_otp_actions(monkeypatch, task, _otp_json_response(first_actions))
+ finally:
+ skyvern_context.reset()
+
+ hpvc.assert_awaited_once()
+
+
+ "actions_override",
+ [
+ pytest.param({}, id="actions_missing"),
+ pytest.param({"actions": None}, id="actions_none"),
+ pytest.param({"actions": "123456"}, id="actions_string"),
+ pytest.param({"actions": {"action_type": "INPUT_TEXT"}}, id="actions_dict"),
+ ],
+)
+async def test_missing_or_malformed_actions_fail_open_to_replan(
+ monkeypatch: pytest.MonkeyPatch,
+ actions_override: dict,
+) -> None:
+ """A first plan whose ``actions`` is absent or not a list must not blow up the skip gate: the
+ optimization inspects the plan only when ``actions`` is a real list, otherwise it falls open to
+ the polling verification re-plan (which rebuilds the payload). Even with the runtime secret stash
+ present, a non-list payload cannot be a consumable multi-field shape."""
+ _patch_workflow_context(monkeypatch, _usable_credential_context())
+ task = _make_task()
json_response = {
"place_to_enter_verification_code": True,
"should_enter_verification_code": True,
+ "should_verify_by_magic_link": False,
+ **actions_override,
}
- resolver = AsyncMock(return_value=None)
- db_get = AsyncMock()
- monkeypatch.setattr("skyvern.forge.agent.resolve_otp_value", resolver)
- monkeypatch.setattr("skyvern.forge.agent.app.DATABASE.workflow_runs.get_workflow_run", db_get)
+ ctx = SkyvernContext(
+ task_id=task.task_id,
+ active_credential_parameter_key="credentials",
+ totp_codes={f"{task.task_id}_secret": _VALID_TOTP_SEED},
+ )
+ skyvern_context.set(ctx)
+ try:
+ hpvc, _parse_mock, _result = await _run_otp_actions(monkeypatch, task, json_response)
+ finally:
+ skyvern_context.reset()
+
+ hpvc.assert_awaited_once()
+
+
+def test_agent_no_longer_imports_credential_candidate_selector() -> None:
+ """The new gate never selects or reads a credential candidate; the agent module must not carry the
+ ``has_credential_totp_candidate`` import that the earlier gate depended on."""
+ import skyvern.forge.agent as agent_module
+
+ assert not hasattr(agent_module, "has_credential_totp_candidate")
+
+
+async def test_same_form_multi_field_preserves_exact_first_plan(monkeypatch: pytest.MonkeyPatch) -> None:
+ """A same-form ``[six consecutive single-digit INPUT_TEXT, CLICK submit]`` plan backed by the
+ runtime secret stash is runtime-consumable: the single-digit run begins at action-list index 0, so
+ the per-digit execution path materializes it, and the model-requested trailing submit click is
+ preserved. The seam keeps the first plan and returns the exact original action list untouched, with
+ no re-plan."""
+ _patch_workflow_context(monkeypatch, _usable_credential_context())
+ task = _make_task()
+ json_response = _otp_json_response(_SAME_FORM_MULTI_FIELD)
+ original_actions = json_response["actions"]
+
+ ctx = SkyvernContext(
+ task_id=task.task_id,
+ active_credential_parameter_key="credentials",
+ totp_codes={f"{task.task_id}_secret": _VALID_TOTP_SEED},
+ )
+ skyvern_context.set(ctx)
+ try:
+ hpvc, _parse_mock, result = await _run_otp_actions(monkeypatch, task, json_response)
+ finally:
+ skyvern_context.reset()
+
+ hpvc.assert_not_awaited()
+ returned_json, returned_actions = result
+ assert returned_json is json_response
+ assert returned_json["actions"] is original_actions
+ assert returned_json["actions"] == _SAME_FORM_MULTI_FIELD
+ assert returned_actions == []
+
+
+async def test_leading_action_before_multi_field_replans(monkeypatch: pytest.MonkeyPatch) -> None:
+ """A ``[CLICK, six consecutive single-digit INPUT_TEXT]`` plan is NOT runtime-consumable even with
+ the runtime secret stash present: the leading action pushes the first digit to absolute
+ ``action_index == 1``, so ``_handle_multi_field_totp_sequence`` never seeds the cache (it generates
+ only at index 0) and every digit fails with a cache miss. The skip must fail open to the polling
+ verification re-plan. RED on the prior shape check that matched a single-digit run at any offset."""
+ _patch_workflow_context(monkeypatch, _usable_credential_context())
+ task = _make_task()
+
+ ctx = SkyvernContext(
+ task_id=task.task_id,
+ active_credential_parameter_key="credentials",
+ totp_codes={f"{task.task_id}_secret": _VALID_TOTP_SEED},
+ )
+ skyvern_context.set(ctx)
+ try:
+ hpvc, _parse_mock, _result = await _run_otp_actions(
+ monkeypatch, task, _otp_json_response(_LEADING_ACTION_MULTI_FIELD)
+ )
+ finally:
+ skyvern_context.reset()
+
+ hpvc.assert_awaited_once()
+
+async def test_multi_field_skips_only_with_runtime_secret_stash(monkeypatch: pytest.MonkeyPatch) -> None:
+ """A multi-field single-digit plan is only runtime-consumable when the runtime already holds the
+ code the per-digit execution path types — the ``totp_codes[f"{task_id}_secret"]`` stash the
+ existing multi-field preparation reads. With the stash present the skip fires."""
+ _patch_workflow_context(monkeypatch, _usable_credential_context())
+ task = _make_task()
+
+ ctx = SkyvernContext(
+ task_id=task.task_id,
+ active_credential_parameter_key="credentials",
+ totp_codes={f"{task.task_id}_secret": _VALID_TOTP_SEED},
+ )
+ skyvern_context.set(ctx)
+ try:
+ hpvc, _parse_mock, _result = await _run_otp_actions(monkeypatch, task, _otp_json_response(_MULTI_FIELD))
+ finally:
+ skyvern_context.reset()
+
+ hpvc.assert_not_awaited()
+
+
+async def test_multi_field_replans_without_runtime_secret_stash(monkeypatch: pytest.MonkeyPatch) -> None:
+ """Same credential candidate and same multi-field single-digit plan, but no runtime stash: the
+ per-digit execution path cannot materialize the code, so the polling verification re-plan must
+ still fire. RED on the shape-only predicate that skipped on digit count alone."""
+ _patch_workflow_context(monkeypatch, _usable_credential_context())
+ task = _make_task()
+
+ ctx = SkyvernContext(task_id=task.task_id, active_credential_parameter_key="credentials")
+ skyvern_context.set(ctx)
+ try:
+ hpvc, _parse_mock, _result = await _run_otp_actions(monkeypatch, task, _otp_json_response(_MULTI_FIELD))
+ finally:
+ skyvern_context.reset()
+
+ hpvc.assert_awaited_once()
+
+
+async def test_post_plan_skip_blocked_by_payload_otp(monkeypatch: pytest.MonkeyPatch) -> None:
+ """Payload OTP is highest precedence and resolved independently, so the multi-field skip must
+ never run ahead of it: even a multi-field plan backed by the runtime secret stash (which would
+ otherwise skip) must fall through to the re-plan when the navigation payload carries an OTP."""
+ _patch_workflow_context(monkeypatch, _usable_credential_context())
+ task = _make_task(navigation_payload={"otp_code": "654321"})
+
+ ctx = SkyvernContext(
+ task_id=task.task_id,
+ active_credential_parameter_key="credentials",
+ totp_codes={f"{task.task_id}_secret": _VALID_TOTP_SEED},
+ )
+ skyvern_context.set(ctx)
+ try:
+ hpvc, _parse_mock, _result = await _run_otp_actions(monkeypatch, task, _otp_json_response(_MULTI_FIELD))
+ finally:
+ skyvern_context.reset()
+
+ hpvc.assert_awaited_once()
+
+
+async def test_single_field_credential_shortcut_does_not_override_payload_otp(monkeypatch: pytest.MonkeyPatch) -> None:
+ _patch_workflow_context(monkeypatch, _usable_credential_context())
+ task = _make_task(navigation_payload={"otp_code": "654321"})
+ hpvc, _parse, _result = await _run_otp_actions(
+ monkeypatch, task, _otp_json_response([{"action_type": "INPUT_TEXT", "text": "cred_totp"}])
+ )
+ hpvc.assert_awaited_once()
+
+
+async def test_single_field_credential_shortcut_does_not_override_magic_link(monkeypatch: pytest.MonkeyPatch) -> None:
+ _patch_workflow_context(monkeypatch, _usable_credential_context())
+ task = _make_task()
+ step, page, browser = MagicMock(), MagicMock(), MagicMock()
+ magic = AsyncMock(return_value=["magic"])
+ monkeypatch.setattr(ForgeAgent, "handle_potential_magic_link", magic)
agent = ForgeAgent.__new__(ForgeAgent)
- await agent.handle_potential_verification_code(task, step, scraped_page, browser_state, json_response)
+ response = _otp_json_response(
+ [{"action_type": "INPUT_TEXT", "text": "cred_totp"}],
+ should_verify_by_magic_link=True,
+ should_enter_verification_code=False,
+ place_to_enter_verification_code=False,
+ )
+ actions = await agent.handle_potential_OTP_actions(task, step, page, browser, response)
+ magic.assert_awaited_once()
+ assert actions[1] == ["magic"]
- resolver.assert_awaited_once_with(task, expected_otp_type=OTPType.TOTP)
- db_get.assert_not_awaited()
+
+async def test_single_field_routing_is_planning_only(monkeypatch: pytest.MonkeyPatch) -> None:
+ context = _real_credential_context()
+ manager = SimpleNamespace(has_workflow_run_context=lambda _id: True, get_workflow_run_context=lambda _id: context)
+ monkeypatch.setattr(otp_service.app, "WORKFLOW_CONTEXT_MANAGER", manager)
+ monkeypatch.setattr("skyvern.forge.agent.app.WORKFLOW_CONTEXT_MANAGER", manager)
+ monkeypatch.setattr(
+ "skyvern.forge.sdk.services.credentials.generate_totp_code", MagicMock(side_effect=AssertionError)
+ )
+ task = _make_task()
+ hpvc, _parse, result = await _run_otp_actions(
+ monkeypatch,
+ task,
+ _otp_json_response([{"action_type": "INPUT_TEXT", "text": "cred_totp"}, {"action_type": "CLICK"}]),
+ )
+ hpvc.assert_not_awaited()
+ assert result[1] == []
+
+
+async def test_post_plan_polling_only_replans(monkeypatch: pytest.MonkeyPatch) -> None:
+ """Ordinary run-context (no runtime secret stash) keeps the two-pass verification re-plan for a
+ multi-field single-digit plan; the new gate never selects a credential candidate to override it."""
+ _patch_workflow_context(
+ monkeypatch,
+ _FakeWorkflowRunContext(values={"credentials": {"username": "u", "password": "p"}}, secrets={}),
+ )
+ task = _make_task()
+
+ with skyvern_context.scoped(SkyvernContext(task_id=task.task_id, active_credential_parameter_key=None)):
+ hpvc, _parse_mock, _result = await _run_otp_actions(monkeypatch, task, _otp_json_response(_MULTI_FIELD))
+
+ hpvc.assert_awaited_once()
+
+
+async def test_missing_workflow_run_context_falls_through_to_replan(monkeypatch: pytest.MonkeyPatch) -> None:
+ """The optional credential optimization must not run before the established re-plan when the
+ task is detached from a workflow run."""
+ task = _make_task()
+ task.workflow_run_id = None
+ ctx = SkyvernContext(task_id=task.task_id, active_credential_parameter_key=None)
+ with skyvern_context.scoped(ctx):
+ hpvc, _parse_mock, _result = await _run_otp_actions(monkeypatch, task, _otp_json_response(_LITERAL_INPUT))
+ hpvc.assert_awaited_once()
@pytest.mark.asyncio
-async def test_handle_potential_verification_code_skips_polling_when_credential_returns_first(
+async def test_first_pass_preserves_magic_link_framing_with_usable_credential(
monkeypatch: pytest.MonkeyPatch,
) -> None:
- """SKY-9178 regression: when both webhook URL and credential TOTP are configured,
- the resolver yields the credential code first and webhook polling is never invoked."""
+ """Magic-link framing must survive into the first extract-action prompt even when a usable
+ credential TOTP and polling are both configured. The first-pass verification_code_check must be
+ the base ``bool(totp_verification_url or totp_identifier)`` — not suppressed by credential
+ usability — otherwise the model is never asked about magic-link and the branch is stripped
+ (extract-action.j2). RED on head: the pre-plan gate returns False for a usable credential.
+ """
+ _patch_workflow_context(monkeypatch, _usable_credential_context())
task = _make_task()
+
+ step = MagicMock()
+ step.step_id = "stp_test"
+ step.order = 0
+ step.retry_index = 0
+ browser_state = MagicMock()
+ scraped_page = MagicMock()
+ scraped_page.elements = []
+
+ captured: dict[str, object] = {}
+
+ async def fake_build(
+ self_agent: object,
+ _task: object,
+ _step: object,
+ _browser_state: object,
+ _scraped_page: object,
+ *,
+ verification_code_check: bool,
+ expire_verification_code: bool,
+ ) -> PromptBuildResult:
+ captured["verification_code_check"] = verification_code_check
+ return PromptBuildResult(prompt="p", use_caching=False, prompt_name="n", without_page_information=False)
+
+ monkeypatch.setattr(ForgeAgent, "_build_extract_action_prompt", fake_build)
+
+ agent = ForgeAgent.__new__(ForgeAgent)
+ ctx = SkyvernContext(
+ task_id=task.task_id,
+ active_credential_parameter_key="credentials",
+ next_step_pre_scraped_data={"step_id": step.step_id, "scraped_page": scraped_page, "timestamp": None},
+ )
+ skyvern_context.set(ctx)
+ try:
+ await agent.build_and_record_step_prompt(
+ task, step, browser_state, RunEngine.skyvern_v1, persist_artifacts=False
+ )
+ finally:
+ skyvern_context.reset()
+
+ assert captured["verification_code_check"] is True
+
+
+async def test_handle_potential_verification_code_uses_resolver_without_db_lookup(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ task = _make_task(navigation_payload={"otp_code": "654321"})
step = MagicMock()
scraped_page = MagicMock()
browser_state = MagicMock()
@@ -75,45 +585,16 @@ async def test_handle_potential_verification_code_skips_polling_when_credential_
"should_enter_verification_code": True,
}
- credential_code = OTPValue(value="123456", type=OTPType.TOTP)
- resolver = AsyncMock(return_value=credential_code)
- poll = AsyncMock()
+ resolver = AsyncMock(return_value=None)
db_get = AsyncMock()
monkeypatch.setattr("skyvern.forge.agent.resolve_otp_value", resolver)
- monkeypatch.setattr("skyvern.forge.agent.poll_otp_value", poll)
monkeypatch.setattr("skyvern.forge.agent.app.DATABASE.workflow_runs.get_workflow_run", db_get)
- rebuilt = AsyncMock(
- return_value=PromptBuildResult(
- prompt="prompt",
- use_caching=False,
- prompt_name="prompt_name",
- without_page_information=False,
- )
- )
- monkeypatch.setattr(ForgeAgent, "_build_extract_action_prompt", rebuilt)
- monkeypatch.setattr("skyvern.forge.agent.service_utils.is_cua_task", AsyncMock(return_value=False))
-
- rescrape = AsyncMock(return_value={"actions": []})
- monkeypatch.setattr(
- "skyvern.forge.agent.LLMAPIHandlerFactory.get_override_llm_api_handler",
- lambda *args, **kwargs: rescrape,
- )
-
agent = ForgeAgent.__new__(ForgeAgent)
- agent.async_operation_pool = MagicMock()
-
- skyvern_context.set(SkyvernContext(task_id=task.task_id))
- try:
- result = await agent.handle_potential_verification_code(task, step, scraped_page, browser_state, json_response)
- finally:
- skyvern_context.reset()
+ await agent.handle_potential_verification_code(task, step, scraped_page, browser_state, json_response)
resolver.assert_awaited_once_with(task, expected_otp_type=OTPType.TOTP)
- poll.assert_not_awaited()
db_get.assert_not_awaited()
- rescrape.assert_awaited_once()
- assert result == {"actions": []}
@pytest.mark.asyncio
diff --git a/tests/unit/test_agent_task_v3.py b/tests/unit/test_agent_task_v3.py
index 5a9504abf..fabd2d326 100644
--- a/tests/unit/test_agent_task_v3.py
+++ b/tests/unit/test_agent_task_v3.py
@@ -633,13 +633,13 @@ async def test_resolve_v3_llm_key_uses_posthog_override(monkeypatch: pytest.Monk
async def test_resolve_v3_llm_key_sends_wpid_flag_property(monkeypatch: pytest.MonkeyPatch) -> None:
# wpid-scoped PostHog conditions need workflow_permanent_id in properties; non-workflow
# tasks send the "not_workflow" sentinel (same convention as the workflow-block-engine flag).
- reader = AsyncMock(return_value="OPENAI_GPT5_6_LUNA_HIGH")
+ reader = AsyncMock(return_value="FLAG_KEY")
monkeypatch.setattr("skyvern.forge.agent.app.EXPERIMENTATION_PROVIDER.get_value_cached", reader)
monkeypatch.setattr(agent_module.LLMConfigRegistry, "is_registered", lambda _k: True)
monkeypatch.setattr(agent_module, "is_custom_llm_key", lambda _k: False)
resolved = await agent_module._resolve_task_v3_llm_key(_v3_task(workflow_permanent_id="wpid_123"))
- assert resolved == "OPENAI_GPT5_6_LUNA_HIGH"
+ assert resolved == "FLAG_KEY"
assert reader.call_args.kwargs["properties"] == {
"organization_id": "o_test",
"workflow_permanent_id": "wpid_123",
@@ -1982,18 +1982,60 @@ async def test_execute_task_v3_failed_run_carries_failure_category(
async def test_execute_task_v3_settle_completion_fenced_to_block_tasks(
monkeypatch: pytest.MonkeyPatch,
) -> None:
+ # Both populations get a fingerprint sampler: the failure-evidence gate needs one to run at all
+ # (SKY-14598). Only the completed-side settle deferral stays fenced to block tasks, and it is
+ # fenced by its own deferral budget rather than by starving the shared sampler.
outcome = LoopOutcome(status="completed", reason="done", billable_actions=[])
block = _make_block(NavigationBlock, navigation_goal="Open the panel")
_step, _task, loop_mock, _post = await _run_execute_task_v3(
monkeypatch, outcome, task_block=block, data_extraction_goal=None, extracted_information_schema=None
)
- fingerprint = loop_mock.await_args.kwargs["page_fingerprint"]
- assert fingerprint is not None
+ assert loop_mock.await_args.kwargs["page_fingerprint"] is not None
+ assert loop_mock.await_args.kwargs["max_settle_deferrals"] > 0
_step, _task, bare_loop_mock, _post = await _run_execute_task_v3(
monkeypatch, outcome, data_extraction_goal=None, extracted_information_schema=None
)
- assert bare_loop_mock.await_args.kwargs["page_fingerprint"] is None
+ assert bare_loop_mock.await_args.kwargs["page_fingerprint"] is not None
+ assert bare_loop_mock.await_args.kwargs["max_settle_deferrals"] == 0
+
+
+async def test_execute_task_v3_bare_task_fingerprint_samples_the_pinned_page(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ # A bare task pins one page for the run, so its fingerprint must sample THAT page. Going through
+ # browser_state.get_working_page() would return the newest tab after any popup — sampling a page
+ # the model never acted on — and would repoint the working page as a side effect, which is a
+ # behaviour change to the live bare-task arm rather than the scoped one this gate intends.
+ outcome = LoopOutcome(status="completed", reason="done", billable_actions=[])
+ pinned = MagicMock()
+ pinned.is_closed = MagicMock(return_value=False)
+ pinned.evaluate = AsyncMock(return_value="pinned-hash:100:10")
+ popup = MagicMock()
+ popup.is_closed = MagicMock(return_value=False)
+ popup.evaluate = AsyncMock(return_value="popup-hash:1:1")
+
+ _step, _task, loop_mock, _post = await _run_execute_task_v3(
+ monkeypatch,
+ outcome,
+ must_get_working_page_side_effect=[pinned],
+ get_working_page_side_effect=[popup, popup, popup],
+ data_extraction_goal=None,
+ extracted_information_schema=None,
+ )
+ fingerprint = loop_mock.await_args.kwargs["page_fingerprint"]
+ before = loop_mock.browser_state.get_working_page.await_count
+ assert await fingerprint() == "pinned-hash:100:10"
+ # The sampler probed the pinned page and never the popup, and did not consult (or repoint) the
+ # browser's working page to do it. Counting the delta rather than asserting never-awaited: the
+ # post-loop completion-veto gate legitimately calls get_working_page once, before this point.
+ popup.evaluate.assert_not_awaited()
+ assert loop_mock.browser_state.get_working_page.await_count == before
+
+ # A closed pinned page yields None rather than silently falling back to another tab.
+ pinned.is_closed = MagicMock(return_value=True)
+ assert await fingerprint() is None
@pytest.mark.asyncio
diff --git a/tests/unit/test_code_block_captcha.py b/tests/unit/test_code_block_captcha.py
index fea2c7b81..282a45e2f 100644
--- a/tests/unit/test_code_block_captcha.py
+++ b/tests/unit/test_code_block_captcha.py
@@ -4,6 +4,7 @@ import asyncio
from unittest.mock import AsyncMock
import pytest
+from playwright.async_api import Error as PlaywrightError
from skyvern.forge import app
from skyvern.forge.agent_functions import AgentFunction
@@ -444,9 +445,7 @@ async def test_real_sandbox_solve_captcha_rejects_inconclusive_token_baseline(
token_values=["opaque-token"],
frames=[FakeFrame(url="https://www.google.com/recaptcha/api2/anchor", anchor=anchor)],
)
- page.recaptcha_token.input_value = AsyncMock(
- side_effect=[block_module.PlaywrightError("probe failed"), "opaque-token"]
- )
+ page.recaptcha_token.input_value = AsyncMock(side_effect=[PlaywrightError("probe failed"), "opaque-token"])
block = CodeBlock.model_construct(code="await solve_captcha(page)", label="captcha_anchor_unknown_baseline")
await block.generate_async_user_function(block.code, page)()
diff --git a/tests/unit/test_code_block_sandbox.py b/tests/unit/test_code_block_sandbox.py
index 7c1e50390..e41ba1255 100644
--- a/tests/unit/test_code_block_sandbox.py
+++ b/tests/unit/test_code_block_sandbox.py
@@ -25,6 +25,7 @@ from skyvern.forge.sdk.workflow.models.block import (
CodeBlock,
)
from skyvern.forge.sdk.workflow.models.parameter import (
+ CredentialParameter,
OutputParameter,
ParameterType,
WorkflowParameter,
@@ -1164,6 +1165,20 @@ _WORKFLOW_RUN_ID = "wr_otp_test"
_ORG_ID = "o_otp_test"
+def _register_credential_parameter(wrc, key: str = _CREDENTIAL_KEY) -> None:
+ """Register a real CredentialParameter under ``key``, mirroring production so
+ is_registered_credential_parameter_key gates the credential-only TOTP paths."""
+ now = datetime.now(timezone.utc)
+ wrc.parameters[key] = CredentialParameter(
+ key=key,
+ credential_parameter_id=f"cp_{key}",
+ workflow_id="w",
+ credential_id="vault:item",
+ created_at=now,
+ modified_at=now,
+ )
+
+
def _build_wrc_with_totp_seed(seed: str = _RFC_TOTP_SEED):
"""Build a real WorkflowRunContext carrying a TOTP-bearing credential.
@@ -1189,6 +1204,7 @@ def _build_wrc_with_totp_seed(seed: str = _RFC_TOTP_SEED):
wrc.secrets[totp_secret_id] = BitwardenConstants.TOTP
wrc.secrets[wrc.totp_secret_value_key(totp_secret_id)] = seed
wrc.values[_CREDENTIAL_KEY] = {"context": "placeholder note", "totp": totp_secret_id}
+ _register_credential_parameter(wrc)
return wrc
@@ -1208,6 +1224,7 @@ def _build_wrc_with_identifier(identifier: str = "[email protected]"):
)
wrc.values[_CREDENTIAL_KEY] = {"context": "placeholder note"}
wrc.credential_totp_identifiers[_CREDENTIAL_KEY] = identifier
+ _register_credential_parameter(wrc)
return wrc
diff --git a/tests/unit/test_config.py b/tests/unit/test_config.py
index c889e1e36..49047c010 100644
--- a/tests/unit/test_config.py
+++ b/tests/unit/test_config.py
@@ -86,3 +86,30 @@ def test_explicit_code_block_mode_ignores_legacy_setting_with_warning(
assert "CODE_BLOCK_MODE=disabled" in caplog.text
assert "deprecated" in caplog.text
assert "ignored" in caplog.text
+
+
+ ("raw_value", "expected"),
+ [
+ ("256", 256),
+ # The gt=0 bound would otherwise make "turn shedding off" unreachable from an env file,
+ # and a boot-time ValidationError takes the API down rather than uncapping it.
+ ("", None),
+ ("0", None),
+ ("none", None),
+ ("null", None),
+ ],
+)
+def test_api_limit_concurrency_env_values(
+ monkeypatch: pytest.MonkeyPatch, raw_value: str, expected: int | None
+) -> None:
+ monkeypatch.setenv("API_LIMIT_CONCURRENCY", raw_value)
+
+ assert Settings(_env_file=None).API_LIMIT_CONCURRENCY == expected
+
+
+def test_api_limit_concurrency_rejects_negative(monkeypatch: pytest.MonkeyPatch) -> None:
+ monkeypatch.setenv("API_LIMIT_CONCURRENCY", "-1")
+
+ with pytest.raises(ValueError):
+ Settings(_env_file=None)
diff --git a/tests/unit/test_contained_effects.py b/tests/unit/test_contained_effects.py
new file mode 100644
index 000000000..33835ef9f
--- /dev/null
+++ b/tests/unit/test_contained_effects.py
@@ -0,0 +1,53 @@
+import asyncio
+from types import SimpleNamespace
+
+import pytest
+
+from skyvern.utils import contained_effects
+from skyvern.utils.contained_effects import contained_effect
+
+
+def _decide_with_effect(effect: object) -> str:
+ """A caller that records something after it has already decided its outcome."""
+ decision = "completed"
+ with contained_effect("record the decision", run_id="r_1"):
+ effect()
+ return decision
+
+
+def test_a_failing_effect_does_not_reach_the_caller() -> None:
+ def effect() -> None:
+ raise RuntimeError("sink is down")
+
+ assert _decide_with_effect(effect) == "completed"
+
+
+def test_a_failing_report_path_does_not_reach_the_caller(monkeypatch: pytest.MonkeyPatch) -> None:
+ """The mechanism that defeats the obvious fix: the handler re-enters the sink that failed.
+
+ A try/except around an emit is not containment when the except body logs through the
+ same logger that just threw, so the report path has to be able to fail silently."""
+ reports: list[str] = []
+
+ def broken_warning(_event: str, **_fields: object) -> None:
+ reports.append("attempted")
+ raise RuntimeError("the logger itself is down")
+
+ monkeypatch.setattr(contained_effects, "LOG", SimpleNamespace(warning=broken_warning))
+
+ def effect() -> None:
+ raise RuntimeError("sink is down")
+
+ assert _decide_with_effect(effect) == "completed"
+ assert reports == ["attempted"]
+
+
+def test_cancellation_still_propagates() -> None:
+ """Containment covers failure, not teardown: swallowing cancellation would hang the caller."""
+
+ async def cancelled_effect() -> None:
+ with contained_effect("record something"):
+ raise asyncio.CancelledError()
+
+ with pytest.raises(asyncio.CancelledError):
+ asyncio.run(cancelled_effect())
diff --git a/tests/unit/test_copilot_agent_helpers.py b/tests/unit/test_copilot_agent_helpers.py
index 1a2ff404e..9a9213885 100644
--- a/tests/unit/test_copilot_agent_helpers.py
+++ b/tests/unit/test_copilot_agent_helpers.py
@@ -5,6 +5,7 @@ from __future__ import annotations
import asyncio
import json
from datetime import datetime, timezone
+from pathlib import Path
from types import SimpleNamespace
from typing import Any
from unittest.mock import AsyncMock, MagicMock
@@ -5423,3 +5424,59 @@ class TestRecordedBuildTestOutcomeSourceBinding:
assert "code matches" in prompt
assert "POST-RUN PAGE-PATH CONTRACT UNBOUND" not in prompt
assert "inspect_page_for_composition" not in prompt
+
+
+def _resolved_description(overlay: object) -> str:
+ """Mirror mcp_adapter resolution: the suffix appends to the description, never replaces it."""
+ base = getattr(overlay, "description", None) or ""
+ suffix = getattr(overlay, "description_suffix", None) or ""
+ return f"{base} {suffix}".strip()
+
+
+class TestToolFactOwnership:
+ """A fact deleted from the static prompt must still reach the model through the tool
+ description the usage guide is generated from, or the deletion removed the only copy."""
+
+ @staticmethod
+ def _tool_usage_guide() -> str:
+ from skyvern.forge.sdk.copilot.tools import NATIVE_TOOLS, _build_skyvern_mcp_overlays
+
+ overlays = _build_skyvern_mcp_overlays(BlockAuthoringPolicy.CODE_ONLY_BROWSER)
+ tool_info = [(tool.name, tool.description or "") for tool in NATIVE_TOOLS]
+ tool_info.extend((name, _resolved_description(overlay)) for name, overlay in overlays.items())
+ return agent_module._build_tool_usage_guide(tool_info)
+
+ @staticmethod
+ def _prompt_text() -> str:
+ return (
+ Path(agent_module.__file__).resolve().parents[2] / "prompts" / "skyvern" / "workflow-copilot-agent.j2"
+ ).read_text()
+
+ @pytest.mark.parametrize(
+ ("tool", "fact"),
+ [
+ ("click", "instant and"),
+ ("scroll", "below the fold"),
+ ("select_option", "For free-text inputs"),
+ ("press_key", "Escape"),
+ ("console_messages", "read-only"),
+ ("inspect_page_for_composition", "navigates the live browser there"),
+ ("get_block_schema", "task_v2"),
+ ("evaluate", "record a scouted interaction"),
+ ("inspect_page_for_composition", "bounded read of known or current page state"),
+ ("update_and_run_blocks", "higher latency than a bounded page read"),
+ ],
+ )
+ def test_migrated_fact_reaches_the_model_through_its_owning_tool(self, tool: str, fact: str) -> None:
+ guide = self._tool_usage_guide()
+
+ assert f"**{tool}**" in guide
+ assert fact in guide
+
+ def test_prompt_carries_no_tool_call_ration_or_duplicated_tool_docs(self) -> None:
+ prompt = self._prompt_text()
+
+ assert "more than twice in a row" not in prompt
+ for duplicated in ("- CSS SELECTORS:", "- SCROLL:", "- SELECT_OPTION:", "- PRESS_KEY:", "- CONSOLE_MESSAGES:"):
+ assert duplicated not in prompt
+ assert "Use evaluate for reading/inspection" not in prompt
diff --git a/tests/unit/test_copilot_diagnosis_repair_contract.py b/tests/unit/test_copilot_diagnosis_repair_contract.py
index de6088b2c..d812d6ddb 100644
--- a/tests/unit/test_copilot_diagnosis_repair_contract.py
+++ b/tests/unit/test_copilot_diagnosis_repair_contract.py
@@ -3,6 +3,7 @@ from __future__ import annotations
import hashlib
import json
from collections.abc import Callable
+from pathlib import Path
from types import SimpleNamespace
from typing import Any
from unittest.mock import MagicMock
@@ -10,6 +11,7 @@ from unittest.mock import MagicMock
import pytest
from structlog.testing import capture_logs
+from skyvern.forge.sdk.copilot.agent import _code_authoring_repair_context_prompt
from skyvern.forge.sdk.copilot.blocker_signal import CopilotToolBlockerSignal
from skyvern.forge.sdk.copilot.build_test_outcome import recorded_outcome_from_run_blocks_result
from skyvern.forge.sdk.copilot.challenge_evidence import (
@@ -18,8 +20,10 @@ from skyvern.forge.sdk.copilot.challenge_evidence import (
ChallengeKind,
composition_challenge_carrier,
)
+from skyvern.forge.sdk.copilot.completion_output_grounding import page_evidence_prose_text
from skyvern.forge.sdk.copilot.completion_verification import CompletionVerificationResult, CriterionVerdict
from skyvern.forge.sdk.copilot.composition_evidence import (
+ has_bounded_page_schema,
merge_visual_composition_evidence,
parse_composition_html,
)
@@ -43,6 +47,7 @@ from skyvern.forge.sdk.copilot.run_outcome import (
RecordedRunOutcome,
)
from skyvern.forge.sdk.copilot.runtime_authoring_repair import (
+ OBSTRUCTION_SUMMARY_MAX_CHARS,
finalize_runtime_authoring_repair_context_from_page_observation,
inject_runtime_authoring_repair_context,
post_run_inspection_cleanly_matches,
@@ -3312,3 +3317,350 @@ def test_vision_challenge_without_a_blocked_submit_claim_still_terminalizes_over
assert carrier is ChallengeEvidenceSource.VISION
assert signal is not None
assert signal.internal_reason_code == TERMINAL_CHALLENGE_BLOCKER_REASON_CODE
+
+
+_NAMED_CONTROL_OVERLAY_HTML = (Path(__file__).parent / "data" / "click_overlay_named_dismiss.html").read_text()
+
+_LONG_OVERLAY_SELECTOR_ID = "overlay-" + "notice-gate-region-" * 5
+
+_LONG_SELECTOR_OVERLAY_HTML = f"""
+<html><body>
+ <main><button id="btn-open-statements">Continue to statements</button></main>
+ <div class="overlay" id="{_LONG_OVERLAY_SELECTOR_ID}">
+ <div class="modal" id="inner-modal" role="dialog" aria-modal="true">
+ <h2>Notice</h2>
+ <button id="btn-one">Accept</button>
+ <button id="btn-two">Decline</button>
+ <button id="btn-three">Manage</button>
+ <button id="btn-four">Close</button>
+ </div>
+ </div>
+</body></html>
+"""
+
+
+def _overlay_repair_ctx(evidence: dict[str, Any]) -> CopilotContext:
+ ctx = _ctx()
+ ctx.block_authoring_policy = BlockAuthoringPolicy.CODE_ONLY_BROWSER
+ ctx.composition_page_evidence = {
+ **evidence,
+ "source_tool": "inspect_page_for_composition",
+ "observed_after_workflow_run": True,
+ "workflow_run_id": "wr_overlay",
+ }
+ ctx.pending_code_authoring_runtime_repair_context = CodeAuthoringRepairContext(
+ block_label="click_continue_and_extract_success",
+ reason_code="runtime_block_failure",
+ runtime_failure_reason="TimeoutError: Locator.wait_for: Timeout 10000ms exceeded.",
+ workflow_run_id="wr_overlay",
+ )
+ return ctx
+
+
+def _overlay_page_evidence(html: str) -> dict[str, Any]:
+ return parse_composition_html(html, inspected_url="http://localhost/x", current_url="http://localhost/x")
+
+
+def _obstruction_only_page_evidence() -> dict[str, Any]:
+ return {
+ "page_obstructions": [
+ {
+ "kind": "other",
+ "source": "vision_summary",
+ "visual_location": "Full-page overlay covering the page and its button.",
+ "visible_controls": [],
+ "underlying_page_blocked": True,
+ }
+ ],
+ "modal_overlays": [],
+ "forms": [],
+ "navigation_targets": [],
+ "result_containers": [],
+ "challenge_controls": [],
+ }
+
+
+def test_an_overlay_seen_later_in_the_run_replaces_the_earlier_clean_capture() -> None:
+ ctx = _ctx()
+ ctx.last_run_blocks_workflow_run_id = "wr_failed"
+ ctx.last_test_ok = False
+
+ clean, _ = store_post_run_page_evidence(
+ ctx,
+ _bounded_failure_page_evidence(),
+ run_id="wr_failed",
+ current_url="https://example.test/app/results",
+ source_browser_session_id=None,
+ run_browser_session_id=None,
+ )
+ ctx.composition_page_evidence = clean
+
+ overlay, _ = store_post_run_page_evidence(
+ ctx,
+ {"source_tool": "inspect_page_for_composition", **_obstruction_only_page_evidence()},
+ run_id="wr_failed",
+ current_url="https://example.test/app/results",
+ source_browser_session_id=None,
+ run_browser_session_id=None,
+ )
+
+ assert overlay.get("page_obstructions"), "the overlay the run actually hit must not be discarded"
+ assert ctx.composition_page_evidence.get("page_obstructions")
+
+
+def test_obstruction_without_dismiss_controls_still_finalizes_a_repair_context() -> None:
+ ctx = _overlay_repair_ctx(_obstruction_only_page_evidence())
+ assert has_bounded_page_schema(ctx.composition_page_evidence) is False
+
+ repair_context = finalize_runtime_authoring_repair_context_from_page_observation(ctx)
+
+ assert repair_context is not None
+ assert repair_context.observed_after_workflow_run is True
+ assert repair_context.page_form_summaries == []
+ assert repair_context.page_obstruction_summaries == [
+ "other Full-page overlay covering the page and its button. "
+ "obstruction present, no dismiss control found in page evidence"
+ ]
+ rendered_line = (
+ "page_obstructions: other Full-page overlay covering the page and its button. "
+ "obstruction present, no dismiss control found in page evidence"
+ )
+ assert rendered_line in _code_authoring_repair_context_prompt(ctx).splitlines()
+ assert "obstruction present, no dismiss control found" in rendered_line
+
+
+def test_overlay_dismiss_controls_reach_the_repair_prompt_beside_the_runtime_failure() -> None:
+ ctx = _overlay_repair_ctx(_overlay_page_evidence(_NAMED_CONTROL_OVERLAY_HTML))
+
+ repair_context = finalize_runtime_authoring_repair_context_from_page_observation(ctx)
+
+ assert repair_context is not None
+ summaries = repair_context.page_obstruction_summaries
+ assert [summary.split()[1] for summary in summaries] == ["#terms-overlay", "#terms-modal"]
+ for summary in summaries:
+ assert "#accept-terms" in summary
+ assert "Continue #btn-continue" in summary
+ prompt_lines = _code_authoring_repair_context_prompt(ctx).splitlines()
+ assert "runtime_failure_reason: TimeoutError: Locator.wait_for: Timeout 10000ms exceeded." in prompt_lines
+ assert "observed_after_workflow_run: true" in prompt_lines
+ obstruction_line = next(line for line in prompt_lines if line.startswith("page_obstructions:"))
+ assert "#terms-overlay" in obstruction_line
+ assert "#btn-continue" in obstruction_line
+
+ ctx.last_code_authoring_repair_context = repair_context.model_copy(update={"selector": "#btn-continue"})
+ selector_prompt_lines = _code_authoring_repair_context_prompt(ctx).splitlines()
+ assert "selector: #btn-continue" in selector_prompt_lines
+ assert obstruction_line in selector_prompt_lines
+
+
+def test_overlay_selectors_longer_than_a_summary_field_reach_the_prompt_whole() -> None:
+ ctx = _overlay_repair_ctx(_overlay_page_evidence(_LONG_SELECTOR_OVERLAY_HTML))
+ long_selector = f"#{_LONG_OVERLAY_SELECTOR_ID}"
+ assert len(long_selector) > 100
+
+ repair_context = finalize_runtime_authoring_repair_context_from_page_observation(ctx)
+
+ assert repair_context is not None
+ summary = repair_context.page_obstruction_summaries[0]
+ assert summary.startswith(f"modal_overlay {long_selector} ")
+ assert summary.endswith("#btn-four")
+ assert f"page_obstructions: modal_overlay {long_selector} " in _code_authoring_repair_context_prompt(ctx)
+
+
+def test_every_obstruction_keeps_dismiss_controls_when_controls_outnumber_the_summary_budget() -> None:
+ ctx = _overlay_repair_ctx(_overlay_page_evidence(_LONG_SELECTOR_OVERLAY_HTML))
+ long_selector = f"#{_LONG_OVERLAY_SELECTOR_ID}"
+
+ repair_context = finalize_runtime_authoring_repair_context_from_page_observation(ctx)
+
+ assert repair_context is not None
+ per_obstruction = {
+ selector: [summary for summary in repair_context.page_obstruction_summaries if selector in summary]
+ for selector in (long_selector, "#inner-modal")
+ }
+ assert [len(summaries) for summaries in per_obstruction.values()] == [1, 1]
+ assert [
+ selector
+ for selector in ("#btn-one", "#btn-two", "#btn-three", "#btn-four")
+ if selector in per_obstruction["#inner-modal"][0]
+ ] == ["#btn-one", "#btn-two", "#btn-three", "#btn-four"]
+
+
+def test_dismiss_controls_are_reported_without_an_action_or_a_preference() -> None:
+ ctx = _overlay_repair_ctx(_overlay_page_evidence(_NAMED_CONTROL_OVERLAY_HTML))
+ evidence_before = json.dumps(ctx.composition_page_evidence, sort_keys=True)
+ pending_before = ctx.pending_code_authoring_runtime_repair_context
+
+ repair_context = finalize_runtime_authoring_repair_context_from_page_observation(ctx)
+
+ assert repair_context is not None
+ for summary, obstruction in zip(
+ repair_context.page_obstruction_summaries, ctx.composition_page_evidence["page_obstructions"]
+ ):
+ source_control_order = [control.get("selector") for control in obstruction["visible_controls"]]
+ assert sorted(source_control_order, key=summary.index) == source_control_order
+ assert json.dumps(ctx.composition_page_evidence, sort_keys=True) == evidence_before
+ assert pending_before is not None
+ before = pending_before.model_dump()
+ assert {key for key, value in repair_context.model_dump().items() if before[key] != value} <= {
+ "current_origin",
+ "current_url",
+ "current_title",
+ "page_evidence_source",
+ "observed_after_workflow_run",
+ "page_form_summaries",
+ "page_result_summaries",
+ "page_action_summaries",
+ "page_challenge_summaries",
+ "page_obstruction_summaries",
+ }
+
+
+def test_modal_overlay_dismiss_controls_are_read_only_without_page_obstructions() -> None:
+ ctx = _overlay_repair_ctx(
+ {
+ "page_obstructions": [],
+ "modal_overlays": [
+ {
+ "selector": "#gate-modal",
+ "dismiss_controls": [{"text": "Accept All", "selector": "button.accept"}],
+ }
+ ],
+ "forms": [],
+ "navigation_targets": [],
+ "result_containers": [],
+ "challenge_controls": [],
+ }
+ )
+
+ repair_context = finalize_runtime_authoring_repair_context_from_page_observation(ctx)
+
+ assert repair_context is not None
+ assert repair_context.page_obstruction_summaries == ["#gate-modal Accept All button.accept"]
+
+
+def test_page_free_of_obstructions_renders_no_obstruction_line() -> None:
+ ctx = _overlay_repair_ctx(
+ {
+ "page_obstructions": [],
+ "modal_overlays": [],
+ "forms": [{"fields": [], "submit_controls": [{"text": "Continue", "selector": "#btn-continue"}]}],
+ "navigation_targets": [],
+ "result_containers": [],
+ "challenge_controls": [],
+ }
+ )
+
+ repair_context = finalize_runtime_authoring_repair_context_from_page_observation(ctx)
+
+ assert repair_context is not None
+ assert repair_context.page_obstruction_summaries == []
+ assert "page_obstructions:" not in _code_authoring_repair_context_prompt(ctx)
+
+
+def test_page_obstruction_summaries_separate_runtime_repair_root_cause_signatures() -> None:
+ def signature(summaries: list[str]) -> str | None:
+ repair_context = CodeAuthoringRepairContext(
+ block_label="click_continue_and_extract_success",
+ reason_code="runtime_block_failure",
+ observed_after_workflow_run=True,
+ page_obstruction_summaries=summaries,
+ )
+ contract = build_diagnosis_repair_contract(
+ source_tool="update_and_run_blocks",
+ result=_authoring_repair_result(repair_context),
+ ctx=_ctx(),
+ )
+ return contract.to_trace_data()["root_cause_signature"]
+
+ named_control_signature = signature(["#terms-overlay Continue #btn-continue"])
+ textless_signature = signature(
+ ["other Full-page overlay obstruction present, no dismiss control found in page evidence"]
+ )
+
+ assert named_control_signature is not None
+ assert named_control_signature != textless_signature
+
+
+async def test_obstruction_only_packet_survives_the_automatic_post_run_capture(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ ctx = _ctx()
+ packet = _obstruction_only_page_evidence()
+
+ async def _read(
+ _ctx_arg: CopilotContext, *, run_session_id: str, current_url: str
+ ) -> tuple[dict[str, Any], str, None]:
+ return packet, run_session_id, None
+
+ monkeypatch.setattr(run_execution_module, "_read_run_session_page_evidence", _read)
+
+ await run_execution_module._capture_and_store_post_run_page(
+ ctx, run_session_id="pbs_run", run_id="wr_overlay", current_url="https://example.test/statements"
+ )
+
+ stored = ctx.composition_page_evidence
+ assert stored is not None
+ assert has_bounded_page_schema(stored) is False
+ assert stored["observed_after_workflow_run"] is True
+ assert stored["workflow_run_id"] == "wr_overlay"
+ assert stored["page_obstructions"] == packet["page_obstructions"]
+
+
+def test_dispatched_terminal_capture_admits_an_obstruction_only_packet() -> None:
+ packet = _obstruction_only_page_evidence()
+
+ assert has_bounded_page_schema(packet) is False
+ assert page_evidence_prose_text(packet).strip() != ""
+ assert run_execution_module._dispatched_terminal_page_evidence_is_usable(packet) is True
+
+
+def test_same_run_matcher_keeps_a_stored_obstruction_only_packet() -> None:
+ stored = {
+ **_obstruction_only_page_evidence(),
+ "source_tool": "inspect_page_for_composition",
+ "observed_after_workflow_run": True,
+ "workflow_run_id": "wr_overlay",
+ }
+
+ assert has_bounded_page_schema(stored) is False
+ assert post_run_inspection_cleanly_matches(stored, "wr_overlay") is True
+ assert post_run_inspection_cleanly_matches(stored, "wr_other") is False
+
+
+def test_a_long_control_text_never_costs_the_prompt_the_dismiss_selector() -> None:
+ control_selector = "#" + "dismiss-the-full-page-notice-" * 5
+ ctx = _overlay_repair_ctx(
+ {
+ "page_obstructions": [
+ {
+ "kind": "modal_overlay",
+ "selector": "#" + "notice-gate-region-" * 8,
+ "visual_location": "Full-viewport notice covering the statements card. " * 4,
+ "visible_controls": [
+ {"text": "Accept and continue past this notice. " * 6, "selector": control_selector}
+ ],
+ }
+ ],
+ "modal_overlays": [],
+ "forms": [],
+ "navigation_targets": [],
+ "result_containers": [],
+ "challenge_controls": [],
+ }
+ )
+
+ repair_context = finalize_runtime_authoring_repair_context_from_page_observation(ctx)
+
+ assert repair_context is not None
+ summary = repair_context.page_obstruction_summaries[0]
+ assert len(summary) <= OBSTRUCTION_SUMMARY_MAX_CHARS
+ assert summary.endswith(control_selector)
+ obstruction_lines = [
+ line
+ for line in _code_authoring_repair_context_prompt(ctx).splitlines()
+ if line.startswith("page_obstructions:")
+ ]
+ assert obstruction_lines
+ assert control_selector in obstruction_lines[0]
diff --git a/tests/unit/test_copilot_hooks.py b/tests/unit/test_copilot_hooks.py
index facab44c5..aad7e2d0f 100644
--- a/tests/unit/test_copilot_hooks.py
+++ b/tests/unit/test_copilot_hooks.py
@@ -22,18 +22,27 @@ from skyvern.forge.sdk.copilot.hooks import CopilotRunHooks
from skyvern.forge.sdk.copilot.output_utils import MCP_RESULT_PROVENANCE_KEY, MCP_RESULT_PROVENANCE_VALUE
from skyvern.forge.sdk.copilot.runtime import AgentContext
from skyvern.forge.sdk.copilot.tools import (
- _capture_scout_ambiguity,
+ _capture_scout_pre_action,
_click_post_hook,
_click_pre_hook,
_prenav_ambiguity_for_selector,
_verify_scout_type_landed,
+ mcp_hooks,
)
+from skyvern.forge.sdk.copilot.tools import scouting as scouting_module
from skyvern.forge.sdk.copilot.tools.credential_fill import _fill_observed_effects
from skyvern.forge.sdk.copilot.tools.mcp_hooks import (
ScoutReadbackOutcome,
_scout_readback_outcome,
_scout_type_landing_failure,
)
+from skyvern.forge.sdk.copilot.tools.scouting import (
+ _PAGE_SUMMARY_SELECTOR_CAP,
+ _build_scout_page_summary,
+ _page_evidence_names_obstruction,
+ _summary_disclosure_control,
+ _summary_entry,
+)
from tests.unit.copilot_test_helpers import make_copilot_ctx
READBACK_OUTCOME_CASES = yaml.safe_load((Path(__file__).parent / "credential_readback_outcome_cases.yaml").read_text())[
@@ -528,7 +537,6 @@ class TestMCPFailedStepLoopDetection:
return FakeRawResult()
async def fake_ensure_browser_session(ctx: Any, *, require_verified_session: bool = False) -> None:
- assert require_verified_session is True
ctx.browser_session_id = "pbs_copilot"
return None
@@ -1119,6 +1127,39 @@ class TestBrowserInteractionObservationHooks:
assert ctx.pending_browser_interaction_observation is None
+_ACTED_SELECTOR = "button[data-action='order']"
+
+
+def _no_redaction_ctx() -> SimpleNamespace:
+ """These cases assert summary shape; the redactor is a no-op without codeblock parameters."""
+ return SimpleNamespace(codeblock_redaction_parameters={})
+
+
+# Post-action browser calls each interaction issues, production-shaped (vision on). Only `click`
+# is in _ACT_OBSERVE_TOOLS, so only it takes the structured packet and its retained fallback frame;
+# The type_text path takes no frame but is the heaviest at four calls: two reads that verify the
+# text landed plus two evaluates. A new probe on any path fails this.
+_INTERACTION_HOOK_PAIRS = (
+ ("_click_pre_hook", {}, "_click_post_hook", {}, {"skyvern_evaluate": 1, "skyvern_screenshot": 1}),
+ (
+ "_type_text_pre_hook",
+ {"text": "socks"},
+ "_type_text_post_hook",
+ {"text_length": 5},
+ {"skyvern_evaluate": 2, "skyvern_get_value": 2},
+ ),
+ ("_select_option_pre_hook", {"value": "price_asc"}, "_select_option_post_hook", {"value": "price_asc"}, {}),
+ ("_press_key_pre_hook", {"key": "Enter"}, "_press_key_post_hook", {"key": "Enter"}, {}),
+)
+
+_INTERACTION_PRE_HOOKS = (
+ ("_click_pre_hook", {}),
+ ("_type_text_pre_hook", {"text": "socks"}),
+ ("_select_option_pre_hook", {"value": "price_asc"}),
+ ("_press_key_pre_hook", {"key": "Enter"}),
+)
+
+
class TestScoutedInteractionCapture:
"""A scouted interaction with a concrete selector is captured and surfaced to
code-only authoring; intent-only and failed-readback actions are not."""
@@ -1357,8 +1398,6 @@ class TestScoutedInteractionCapture:
@pytest.mark.asyncio
async def test_navigate_post_hook_records_the_ordered_effect_fact(self, monkeypatch: pytest.MonkeyPatch) -> None:
- from skyvern.forge.sdk.copilot.tools import mcp_hooks
-
ctx = self._ctx(source_url="https://example.com/two-factor")
monkeypatch.setattr(mcp_hooks, "_bind_login_credential_for_observed_url", AsyncMock())
monkeypatch.setattr(mcp_hooks, "_capture_post_interaction_screenshot", AsyncMock())
@@ -1377,8 +1416,6 @@ class TestScoutedInteractionCapture:
async def test_navigate_post_hook_next_step_claims_no_attached_screenshot(
self, monkeypatch: pytest.MonkeyPatch
) -> None:
- from skyvern.forge.sdk.copilot.tools import mcp_hooks
-
ctx = self._ctx(source_url="https://example.com/login")
monkeypatch.setattr(mcp_hooks, "_bind_login_credential_for_observed_url", AsyncMock())
monkeypatch.setattr(mcp_hooks, "_capture_post_interaction_screenshot", AsyncMock(return_value=False))
@@ -1396,8 +1433,6 @@ class TestScoutedInteractionCapture:
async def test_navigate_post_hook_claims_only_the_screenshot_it_staged(
self, monkeypatch: pytest.MonkeyPatch
) -> None:
- from skyvern.forge.sdk.copilot.tools import mcp_hooks
-
ctx = self._ctx(source_url="https://example.com/login")
monkeypatch.setattr(mcp_hooks, "_bind_login_credential_for_observed_url", AsyncMock())
monkeypatch.setattr(mcp_hooks, "_capture_post_interaction_screenshot", AsyncMock(return_value=True))
@@ -1412,8 +1447,6 @@ class TestScoutedInteractionCapture:
@pytest.mark.asyncio
async def test_failed_navigate_stages_a_frame(self, monkeypatch: pytest.MonkeyPatch) -> None:
- from skyvern.forge.sdk.copilot.tools import mcp_hooks
-
capture = AsyncMock(return_value=True)
monkeypatch.setattr(mcp_hooks, "_capture_post_interaction_screenshot", capture)
@@ -1424,17 +1457,18 @@ class TestScoutedInteractionCapture:
assert "next_step" not in result
@pytest.mark.asyncio
- async def test_click_that_attached_page_evidence_stages_no_frame(self, monkeypatch: pytest.MonkeyPatch) -> None:
- from skyvern.forge.sdk.copilot.tools import mcp_hooks
-
+ async def _click_with_attached_evidence(
+ self, monkeypatch: pytest.MonkeyPatch, evidence: dict[str, Any]
+ ) -> AsyncMock:
capture = AsyncMock(return_value=True)
monkeypatch.setattr(mcp_hooks, "_capture_post_interaction_screenshot", capture)
async def attach_observation(ctx: SimpleNamespace, **kwargs: Any) -> tuple[int | None, dict[str, Any] | None]:
ctx.last_scout_act_observe_outcome = "attached"
- return None, None
+ return None, evidence
monkeypatch.setattr(mcp_hooks, "_register_scout_interaction_observation", attach_observation)
+ monkeypatch.setattr(mcp_hooks, "_attach_scout_page_summary", lambda ctx, result, page_evidence: None)
ctx = self._ctx(source_url="https://example.com/product")
await mcp_hooks._click_post_hook(
@@ -1442,13 +1476,34 @@ class TestScoutedInteractionCapture:
{"browser_context": {"url": "https://example.com/cart", "title": "Cart"}},
ctx,
)
+ return capture
+ @pytest.mark.asyncio
+ async def test_click_whose_evidence_names_a_modal_stages_no_frame(self, monkeypatch: pytest.MonkeyPatch) -> None:
+ evidence = {
+ "page_title": "Cart",
+ "modal_overlays": [{"selector": "#promo", "dismiss_controls": [{"text": "No thanks"}]}],
+ "challenge_state": {"detected": False},
+ }
+ capture = await self._click_with_attached_evidence(monkeypatch, evidence)
capture.assert_not_awaited()
@pytest.mark.asyncio
- async def test_failed_click_stages_a_frame(self, monkeypatch: pytest.MonkeyPatch) -> None:
- from skyvern.forge.sdk.copilot.tools import mcp_hooks
+ async def test_click_whose_evidence_names_no_obstruction_still_stages_a_frame(
+ self, monkeypatch: pytest.MonkeyPatch
+ ) -> None:
+ evidence = {
+ "page_title": "Cart",
+ "modal_overlays": [],
+ "challenge_controls": [],
+ "challenge_state": {"detected": False},
+ "visual_obstruction_candidates": [{"selector": ".sticky", "reason": "fixed_overlay"}],
+ }
+ capture = await self._click_with_attached_evidence(monkeypatch, evidence)
+ capture.assert_awaited_once()
+ @pytest.mark.asyncio
+ async def test_failed_click_stages_a_frame(self, monkeypatch: pytest.MonkeyPatch) -> None:
capture = AsyncMock(return_value=True)
monkeypatch.setattr(mcp_hooks, "_capture_post_interaction_screenshot", capture)
@@ -1764,12 +1819,8 @@ class TestScoutedInteractionCapture:
async def test_click_pre_hook_stashes_role_name_from_bare_css_via_browser_read(
self, monkeypatch: pytest.MonkeyPatch
) -> None:
- # Bare CSS selector cannot be parsed, so the stash comes from the TIER-2 pre-navigation read.
- async def _fake_read(_ctx: object, _selector: str, *, timeout_seconds: float) -> tuple[str, str]:
- return "link", "Download"
-
- monkeypatch.setattr("skyvern.forge.sdk.copilot.tools.scouting._capture_accessible_role_name", _fake_read)
- ctx = self._ctx()
+ # Bare CSS selector cannot be parsed, so the role/name comes from the page read.
+ ctx = self._ctx_with_scripted_reads(selector_count=1, role_name=("link", "Download"), match_count=1)
ctx.pending_scout_source_url = None
await _click_pre_hook({"selector": "a"}, ctx)
assert ctx.pending_scout_role_name == ("a", "link", "Download")
@@ -1858,25 +1909,13 @@ class TestScoutedInteractionCapture:
from skyvern.forge.sdk.copilot.tools import _press_key_post_hook
from skyvern.forge.sdk.copilot.tools.mcp_hooks import _press_key_pre_hook
- ctx = self._ctx(source_url="https://example.com/form")
- ctx.discovery_mcp_server = SimpleNamespace(
- call_internal_tool=AsyncMock(
- side_effect=[
- {"ok": True, "data": {"result": {"role": "textbox", "accessible_name": "Search"}}},
- {"ok": True, "data": {"result": 2}},
- {
- "ok": True,
- "data": {
- "result": [
- {"selector": "#q", "source": "id"},
- {"selector": 'input[name="q"]', "source": "name"},
- ]
- },
- },
- {"ok": True, "data": {"result": 2}},
- ]
- )
+ ctx = self._ctx_with_scripted_reads(
+ selector_count=2,
+ role_name=("textbox", "Search"),
+ match_count=2,
+ candidates=[{"selector": "#q", "source": "id"}, {"selector": 'input[name="q"]', "source": "name"}],
)
+ ctx.pending_scout_source_url = "https://example.com/form"
assert await _press_key_pre_hook({"selector": "#q", "key": "Enter"}, ctx) is None
await _press_key_post_hook(
@@ -1963,22 +2002,18 @@ class TestScoutedInteractionCapture:
assert result["data"]["observation_step"] == entry["step"]
def _ctx_with_count(self, count: int) -> SimpleNamespace:
- server = SimpleNamespace()
- server.call_internal_tool = AsyncMock(return_value={"ok": True, "data": {"result": count}})
- ctx = self._ctx(source_url="https://example.com/portal")
- ctx.discovery_mcp_server = server
- return ctx
+ return self._ctx_with_scripted_reads(selector_count=count, role_name=("", ""), match_count=-1)
@pytest.mark.asyncio
async def test_capture_scout_ambiguity_marks_multi_match_selector(self) -> None:
ctx = self._ctx_with_count(3)
- await _capture_scout_ambiguity(ctx, "button[data-action='orderDocuments']")
+ await _capture_scout_pre_action(ctx, "button[data-action='orderDocuments']")
assert ctx.pending_scout_ambiguous == ("button[data-action='orderDocuments']", True)
@pytest.mark.asyncio
async def test_capture_scout_ambiguity_does_not_mark_unique_selector(self) -> None:
ctx = self._ctx_with_count(1)
- await _capture_scout_ambiguity(ctx, "#unique")
+ await _capture_scout_pre_action(ctx, "#unique")
assert ctx.pending_scout_ambiguous is None
def test_live_scout_packet_has_no_dynamic_row_classifier(self) -> None:
@@ -1999,16 +2034,27 @@ class TestScoutedInteractionCapture:
assert ctx.scouted_interactions[-1].get("ambiguous") is True
def _ctx_with_scripted_reads(
- self, *, selector_count: int, role_name: tuple[str, str], match_count: int
+ self,
+ *,
+ selector_count: int,
+ role_name: tuple[str, str],
+ match_count: int,
+ candidates: list[dict[str, str]] | None = None,
) -> SimpleNamespace:
+ role, name = role_name
+
async def call(_tool: str, args: dict[str, Any]) -> dict[str, Any]:
- expression = args["expression"]
- if "accessible_name:" in expression:
- role, name = role_name
- return {"ok": True, "data": {"result": {"role": role, "accessible_name": name}}}
- if "targetRole" in expression:
- return {"ok": True, "data": {"result": match_count}}
- return {"ok": True, "data": {"result": selector_count}}
+ return {
+ "ok": True,
+ "data": {
+ "result": {
+ "role_name": {"role": role, "accessible_name": name} if (role or name) else None,
+ "role_name_match_count": match_count,
+ "selector_match_count": selector_count,
+ "selector_candidates": candidates or [],
+ }
+ },
+ }
server = SimpleNamespace()
server.call_internal_tool = AsyncMock(side_effect=call)
@@ -2021,7 +2067,7 @@ class TestScoutedInteractionCapture:
ctx = self._ctx_with_scripted_reads(
selector_count=2, role_name=("button", "I AM A BUSINESS CUSTOMER"), match_count=1
)
- await _capture_scout_ambiguity(ctx, "button[data-action='businessToggle']")
+ await _capture_scout_pre_action(ctx, "button[data-action='businessToggle']")
assert ctx.pending_scout_ambiguous == ("button[data-action='businessToggle']", True)
assert ctx.pending_scout_reanchor == (
"button[data-action='businessToggle']",
@@ -2032,14 +2078,14 @@ class TestScoutedInteractionCapture:
@pytest.mark.asyncio
async def test_capture_scout_ambiguity_withholds_name_degenerate_reanchor(self) -> None:
ctx = self._ctx_with_scripted_reads(selector_count=2, role_name=("button", "Toggle"), match_count=2)
- await _capture_scout_ambiguity(ctx, "button[data-action='businessToggle']")
+ await _capture_scout_pre_action(ctx, "button[data-action='businessToggle']")
assert ctx.pending_scout_ambiguous == ("button[data-action='businessToggle']", True)
assert ctx.pending_scout_reanchor is None
@pytest.mark.asyncio
async def test_capture_scout_ambiguity_withholds_nameless_reanchor(self) -> None:
ctx = self._ctx_with_scripted_reads(selector_count=2, role_name=("button", ""), match_count=1)
- await _capture_scout_ambiguity(ctx, "button[data-action='businessToggle']")
+ await _capture_scout_pre_action(ctx, "button[data-action='businessToggle']")
assert ctx.pending_scout_ambiguous == ("button[data-action='businessToggle']", True)
assert ctx.pending_scout_reanchor is None
@@ -2237,6 +2283,339 @@ class TestScoutedInteractionCapture:
assert ctx.scouted_interactions[0]["tool_name"] == "press_key"
assert ctx.scouted_interactions[0]["key"] == "Enter"
+ @pytest.mark.parametrize(("hook_name", "extra_params"), _INTERACTION_PRE_HOOKS)
+ @pytest.mark.parametrize("policy", [None, BlockAuthoringPolicy.CODE_ONLY_BROWSER])
+ @pytest.mark.asyncio
+ async def test_interaction_pre_hook_issues_one_internal_packet(
+ self,
+ hook_name: str,
+ extra_params: dict[str, Any],
+ policy: BlockAuthoringPolicy | None,
+ monkeypatch: pytest.MonkeyPatch,
+ ) -> None:
+ monkeypatch.setattr(mcp_hooks, "_scout_session_download_names", AsyncMock(return_value=frozenset()))
+ ctx = self._ctx_with_scripted_reads(selector_count=2, role_name=("button", "Order"), match_count=1)
+ ctx.block_authoring_policy = policy
+
+ assert await getattr(mcp_hooks, hook_name)({"selector": _ACTED_SELECTOR, **extra_params}, ctx) is None
+
+ assert ctx.discovery_mcp_server.call_internal_tool.await_count == 1
+
+ def _ctx_with_post_action_capture(
+ self, *, hollow: bool = False, unsettled_challenge: bool = False
+ ) -> SimpleNamespace:
+ """Context whose discovery server answers the fused pre-action read and the
+ post-action structured capture. ``hollow`` returns a packet with no controls,
+ which is the only state that earns the bounded recapture."""
+ page: dict[str, Any] = {"page_title": "Results", "forms": [], "navigation_targets": []}
+ if not hollow:
+ page = {
+ "page_title": "Results",
+ "forms": [
+ {
+ "fields": [{"name": "npi", "label": "NPI number", "type": "text", "selector": "#npi"}],
+ "submit_controls": [{"text": "Search", "type": "submit", "selector": "#go"}],
+ }
+ ],
+ "navigation_targets": [{"text": "Details", "href": "https://example.com/d", "selector": "a.d"}],
+ "result_containers": [{"tag": "table", "id": "results", "selector": "#results"}],
+ }
+ if unsettled_challenge:
+ # Keyword says challenge, no rendered carrier resolves it — the second recapture trigger.
+ page = {**page, "anti_bot_indicators": ["captcha"], "challenge_controls": []}
+
+ async def call(_tool: str, args: dict[str, Any]) -> dict[str, Any]:
+ if "REQUESTED_TARGETS" in str(args.get("expression", "")):
+ return {"ok": True, "data": {"result": page}}
+ return {
+ "ok": True,
+ "data": {
+ "result": {
+ "role_name": {"role": "button", "accessible_name": "Order"},
+ "role_name_match_count": 1,
+ "selector_match_count": 1,
+ "selector_candidates": [],
+ }
+ },
+ }
+
+ server = SimpleNamespace()
+ server.call_internal_tool = AsyncMock(side_effect=call)
+ ctx = self._ctx(source_url="https://example.com/portal")
+ ctx.discovery_mcp_server = server
+ ctx.pre_run_gated_output_warning_fingerprint = ()
+ ctx.last_code_authoring_repair_context = None
+ ctx.supports_vision = True
+ return ctx
+
+ @staticmethod
+ def _census(ctx: SimpleNamespace) -> dict[str, int]:
+ census: dict[str, int] = {}
+ for await_call in ctx.discovery_mcp_server.call_internal_tool.await_args_list:
+ census[await_call.args[0]] = census.get(await_call.args[0], 0) + 1
+ return census
+
+ @pytest.mark.parametrize(
+ ("pre_hook", "pre_args", "post_hook", "post_data", "expected_census"), _INTERACTION_HOOK_PAIRS
+ )
+ @pytest.mark.asyncio
+ async def test_every_interaction_post_hook_census(
+ self,
+ pre_hook: str,
+ pre_args: dict[str, Any],
+ post_hook: str,
+ post_data: dict[str, Any],
+ expected_census: dict[str, int],
+ monkeypatch: pytest.MonkeyPatch,
+ ) -> None:
+ """Production-shaped: vision on, so the retained fallback frame is counted."""
+ monkeypatch.setattr(mcp_hooks, "_scout_session_download_names", AsyncMock(return_value=frozenset()))
+ ctx = self._ctx_with_post_action_capture()
+ assert await getattr(mcp_hooks, pre_hook)({"selector": _ACTED_SELECTOR, **pre_args}, ctx) is None
+ ctx.discovery_mcp_server.call_internal_tool.reset_mock()
+
+ await getattr(mcp_hooks, post_hook)(
+ {"ok": True, "data": {"selector": _ACTED_SELECTOR, **post_data}},
+ {"browser_context": {"url": "https://example.com/next", "title": "Next"}},
+ ctx,
+ )
+
+ assert self._census(ctx) == expected_census
+
+ @pytest.mark.parametrize("policy", [None, BlockAuthoringPolicy.CODE_ONLY_BROWSER])
+ @pytest.mark.parametrize("landing_url", ["https://example.com/portal", "https://example.com/next"])
+ @pytest.mark.asyncio
+ async def test_click_post_hook_issues_one_structured_packet_plus_the_frame(
+ self,
+ policy: BlockAuthoringPolicy | None,
+ landing_url: str,
+ monkeypatch: pytest.MonkeyPatch,
+ ) -> None:
+ """Vision is on, as it is in production, so the fallback frame is counted here."""
+ monkeypatch.setattr(mcp_hooks, "_scout_session_download_names", AsyncMock(return_value=frozenset()))
+ ctx = self._ctx_with_post_action_capture()
+ ctx.block_authoring_policy = policy
+ assert await mcp_hooks._click_pre_hook({"selector": _ACTED_SELECTOR}, ctx) is None
+ ctx.discovery_mcp_server.call_internal_tool.reset_mock()
+
+ await mcp_hooks._click_post_hook(
+ {"ok": True, "data": {"selector": _ACTED_SELECTOR}},
+ {"browser_context": {"url": landing_url, "title": "Next"}},
+ ctx,
+ )
+
+ assert self._census(ctx) == {"skyvern_evaluate": 1, "skyvern_screenshot": 1}
+
+ @pytest.mark.asyncio
+ async def test_click_post_hook_recaptures_once_when_the_first_packet_is_hollow(
+ self, monkeypatch: pytest.MonkeyPatch
+ ) -> None:
+ """Hollow is one of three recapture triggers; unsettled challenge evidence and an
+ unchanged-after-interaction page are the others."""
+ monkeypatch.setattr(mcp_hooks, "_scout_session_download_names", AsyncMock(return_value=frozenset()))
+ ctx = self._ctx_with_post_action_capture(hollow=True)
+ assert await mcp_hooks._click_pre_hook({"selector": _ACTED_SELECTOR}, ctx) is None
+ ctx.discovery_mcp_server.call_internal_tool.reset_mock()
+
+ await mcp_hooks._click_post_hook(
+ {"ok": True, "data": {"selector": _ACTED_SELECTOR}},
+ {"browser_context": {"url": "https://example.com/next", "title": "Next"}},
+ ctx,
+ )
+
+ assert self._census(ctx) == {"skyvern_evaluate": 2, "skyvern_screenshot": 1}
+ assert ctx.last_scout_act_observe_recapture_attempted is True
+
+ @pytest.mark.asyncio
+ async def test_click_post_hook_recaptures_once_when_challenge_evidence_is_unsettled(
+ self, monkeypatch: pytest.MonkeyPatch
+ ) -> None:
+ monkeypatch.setattr(mcp_hooks, "_scout_session_download_names", AsyncMock(return_value=frozenset()))
+ ctx = self._ctx_with_post_action_capture(unsettled_challenge=True)
+ assert await mcp_hooks._click_pre_hook({"selector": _ACTED_SELECTOR}, ctx) is None
+ ctx.discovery_mcp_server.call_internal_tool.reset_mock()
+
+ await mcp_hooks._click_post_hook(
+ {"ok": True, "data": {"selector": _ACTED_SELECTOR}},
+ {"browser_context": {"url": "https://example.com/next", "title": "Next"}},
+ ctx,
+ )
+
+ # Two packets, no frame: the settled packet names the challenge, which is the one case the
+ # ticket allows the fallback frame to be dropped.
+ assert self._census(ctx) == {"skyvern_evaluate": 2}
+ assert ctx.last_scout_act_observe_recapture_attempted is True
+
+ def test_page_summary_drops_an_oversized_selector_instead_of_truncating_it(self) -> None:
+ long_selector = "div.wrapper > " + " > ".join(f"section.level-{n}" for n in range(12))
+ assert len(long_selector) > _PAGE_SUMMARY_SELECTOR_CAP
+
+ entry = _summary_entry("Close", {"selector": long_selector})
+
+ assert entry == {"text": "Close"}
+ assert _summary_entry("Close", {"selector": "#close"}) == {"text": "Close", "selector": "#close"}
+
+ # the disclosure summary carries selectors too and holds the same invariant
+ oversized = {"expanded": True, "text": "Show options", "selector": long_selector}
+ assert "selector" not in _summary_disclosure_control(oversized)
+ sized = {"expanded": True, "text": "Show options", "selector": "#opts"}
+ assert _summary_disclosure_control(sized)["selector"] == "#opts"
+
+ @pytest.mark.parametrize(("hook_name", "extra_params"), _INTERACTION_PRE_HOOKS)
+ @pytest.mark.asyncio
+ async def test_interaction_pre_hooks_reach_the_same_stash(
+ self, hook_name: str, extra_params: dict[str, Any], monkeypatch: pytest.MonkeyPatch
+ ) -> None:
+ monkeypatch.setattr(mcp_hooks, "_scout_session_download_names", AsyncMock(return_value=frozenset()))
+ candidates = [{"selector": "#order-docs", "source": "id"}]
+ ctx = self._ctx_with_scripted_reads(
+ selector_count=2, role_name=("button", "Order"), match_count=1, candidates=candidates
+ )
+
+ assert await getattr(mcp_hooks, hook_name)({"selector": _ACTED_SELECTOR, **extra_params}, ctx) is None
+
+ assert ctx.pending_scout_role_name == (_ACTED_SELECTOR, "button", "Order")
+ assert ctx.pending_scout_role_name_match_count == (_ACTED_SELECTOR, "button", "Order", 1)
+ assert ctx.pending_scout_selector_candidates == candidates
+ assert ctx.pending_scout_selector_match_count == (_ACTED_SELECTOR, 2)
+ assert ctx.pending_scout_ambiguous == (_ACTED_SELECTOR, True)
+ assert ctx.pending_scout_reanchor == (_ACTED_SELECTOR, "button", "Order")
+
+ @pytest.mark.parametrize(("hook_name", "extra_params"), _INTERACTION_PRE_HOOKS)
+ @pytest.mark.asyncio
+ async def test_interaction_pre_hook_without_a_selector_clears_the_prior_stash(
+ self, hook_name: str, extra_params: dict[str, Any], monkeypatch: pytest.MonkeyPatch
+ ) -> None:
+ monkeypatch.setattr(mcp_hooks, "_scout_session_download_names", AsyncMock(return_value=frozenset()))
+ ctx = self._ctx_with_scripted_reads(selector_count=2, role_name=("button", "Order"), match_count=1)
+ ctx.pending_scout_role_name = ("#stale", "button", "Stale")
+ ctx.pending_scout_selector_match_count = ("#stale", 1)
+
+ assert await getattr(mcp_hooks, hook_name)(dict(extra_params), ctx) is None
+
+ assert ctx.pending_scout_role_name is None
+ assert ctx.pending_scout_selector_match_count is None
+ assert ctx.discovery_mcp_server.call_internal_tool.await_count == 0
+
+ @pytest.mark.asyncio
+ async def test_pre_action_packet_keeps_every_candidate_and_the_ambiguity_flag(self) -> None:
+ candidates = [
+ {"selector": "button[data-action='order']", "source": "requested"},
+ {"selector": "#order-docs", "source": "id"},
+ {"selector": "button.order", "source": "class_list"},
+ ]
+ ctx = self._ctx_with_scripted_reads(
+ selector_count=3, role_name=("button", "Order documents"), match_count=3, candidates=candidates
+ )
+ await _capture_scout_pre_action(ctx, "button[data-action='order']")
+
+ assert ctx.pending_scout_selector_candidates == candidates
+ assert ctx.pending_scout_ambiguous == ("button[data-action='order']", True)
+ assert ctx.pending_scout_selector_match_count == ("button[data-action='order']", 3)
+ assert ctx.pending_scout_reanchor is None
+
+ @pytest.mark.asyncio
+ async def test_pre_action_packet_leaves_unknown_cardinality_unset(self) -> None:
+ ctx = self._ctx_with_scripted_reads(selector_count=-1, role_name=("", ""), match_count=-1)
+ await _capture_scout_pre_action(ctx, "input[[bad")
+
+ assert ctx.pending_scout_selector_match_count is None
+ assert ctx.pending_scout_role_name_match_count is None
+ assert ctx.pending_scout_ambiguous is None
+
+
+class TestScoutPageSummary:
+ @staticmethod
+ def _evidence(field_count: int) -> dict[str, Any]:
+ return {
+ "page_title": "Checkout",
+ "forms": [
+ {
+ "fields": [
+ {"label": f"Field {index} with a fairly long visible label", "selector": f"#field-{index}"}
+ for index in range(field_count)
+ ],
+ "submit_controls": [{"text": "Place order", "selector": "#place-order"}],
+ }
+ ],
+ "navigation_targets": [
+ {"text": f"Section {index} of the site navigation", "selector": f"a.nav-{index}"} for index in range(8)
+ ],
+ "modal_overlays": [{"dismiss_controls": [{"text": "No thanks", "selector": "#promo-close"}]}],
+ "challenge_state": {"detected": False},
+ }
+
+ def test_summary_carries_the_selector_for_each_control(self) -> None:
+ summary = _build_scout_page_summary(self._evidence(2))
+
+ assert summary["forms"][0]["fields"][0]["selector"] == "#field-0"
+ assert summary["forms"][0]["submit_controls"][0] == {"text": "Place order", "selector": "#place-order"}
+ assert summary["navigation_targets"][0]["selector"] == "a.nav-0"
+ assert summary["modal_dismiss_controls"][0]["selector"] == "#promo-close"
+
+ def test_summary_names_every_section_it_sheds(self) -> None:
+ result: dict[str, Any] = {"ok": True, "data": {"filler": "x" * (scouting_module._SCOUT_RESULT_CHAR_CAP - 800)}}
+ scouting_module._attach_scout_page_summary(_no_redaction_ctx(), result, self._evidence(8))
+
+ page = result["data"]["page"]
+ assert page["shed"][:2] == ["control_selectors", "navigation_targets"]
+ assert page["navigation_targets"] == []
+ assert "page_summary" not in page["shed"]
+
+ def test_selectors_are_shed_before_any_control_the_baseline_carried(self) -> None:
+ evidence = self._evidence(8)
+ result: dict[str, Any] = {"ok": True, "data": {"filler": "x" * 900}}
+ scouting_module._attach_scout_page_summary(_no_redaction_ctx(), result, evidence)
+
+ page = result["data"]["page"]
+ assert page["shed"] == ["control_selectors"]
+ assert page["navigation_targets"] == [target["text"] for target in evidence["navigation_targets"]]
+ assert page["forms"][0]["fields"] == [field["label"] for field in evidence["forms"][0]["fields"]]
+
+ def test_a_summary_too_large_to_shed_still_leaves_its_shed_record(self) -> None:
+ result: dict[str, Any] = {"ok": True, "data": {"filler": "x" * scouting_module._SCOUT_RESULT_CHAR_CAP}}
+ scouting_module._attach_scout_page_summary(_no_redaction_ctx(), result, self._evidence(8))
+
+ page = result["data"]["page"]
+ assert set(page) == {"shed"}
+ assert page["shed"][0] == "control_selectors"
+ assert page["shed"][-1] == "page_summary"
+
+ def test_summary_carries_no_filled_field_value(self) -> None:
+ secret = "hunter2-not-a-real-secret"
+ summary = _build_scout_page_summary(
+ {
+ "page_title": "Sign in",
+ "forms": [
+ {
+ "fields": [
+ {"label": "Password", "type": "password", "value": secret, "selector": "#pw"},
+ {"label": "Username", "value": "operator", "selector": "#user"},
+ ],
+ "submit_controls": [{"text": "Sign in", "selector": "#signin"}],
+ }
+ ],
+ }
+ )
+
+ assert secret not in json.dumps(summary)
+ assert summary["forms"][0]["fields"][0] == {"text": "Password", "selector": "#pw"}
+
+ def test_obstruction_predicate_ignores_visual_candidates(self) -> None:
+ assert not _page_evidence_names_obstruction(
+ {
+ "modal_overlays": [],
+ "challenge_controls": [],
+ "challenge_state": {"detected": False},
+ "visual_obstruction_candidates": [{"selector": ".sticky"}],
+ }
+ )
+ assert not _page_evidence_names_obstruction({"modal_overlays": [{"selector": "#promo"}]})
+ assert _page_evidence_names_obstruction(
+ {"modal_overlays": [{"selector": "#promo", "dismiss_controls": [{"text": "Close", "selector": ".x"}]}]}
+ )
+ assert _page_evidence_names_obstruction({"challenge_state": {"detected": True}})
+
class TestAssembleEnforcementMessages:
@staticmethod
diff --git a/tests/unit/test_copilot_mcp_adapter.py b/tests/unit/test_copilot_mcp_adapter.py
index b0da8d7dc..70ec4b06b 100644
--- a/tests/unit/test_copilot_mcp_adapter.py
+++ b/tests/unit/test_copilot_mcp_adapter.py
@@ -1,6 +1,6 @@
import asyncio
import json
-from collections.abc import AsyncIterator, Iterator
+from collections.abc import AsyncIterator, Callable, Iterator
from contextlib import asynccontextmanager
from types import SimpleNamespace
from typing import Any
@@ -73,8 +73,33 @@ _PAYLOAD_KEYS_THAT_WOULD_LEAK = {"args", "merged_args", "arguments", "mcp_args",
_BROWSER_BOOT_SECONDS = 2.0
_MCP_CALL_SECONDS = 3.0
_AFTER_CALL_SECONDS = 5.0
+_AFTER_CALL_MS = 5000
_WALL_MS = 5000
_SESSION_ONLY_MS = 2000
+_MCP_CALL_MS = 3000
+_CONTEXT_ENTER_SECONDS = 4.0
+_CONTEXT_EXIT_SECONDS = 1.0
+_CONTEXT_ENTER_MS = 4000
+_CONTEXT_EXIT_MS = 1000
+_GAP_WALL_MS = 10000
+_AN_HOUR_SECONDS = 3600.0
+_AN_HOUR_MS = 3_600_000
+_PHASE_KEYS = (
+ "phase_session_prepare_ms",
+ "phase_context_enter_ms",
+ "phase_dispatch_ms",
+ "phase_context_exit_ms",
+ "phase_residual_ms",
+)
+
+
+def _assert_every_millisecond_is_attributed(record: dict[str, Any]) -> None:
+ """The residual is the remainder, so its bound is what proves the segments were charged correctly.
+
+ Summing the segments and the residual is an identity that holds for any values whatsoever.
+ """
+ assert sum(record[key] for key in _PHASE_KEYS) == record["wall_clock_ms"]
+ assert 0 <= record["phase_residual_ms"] < len(mcp_adapter._MCP_CALL_SEGMENTS)
class _SharedLocalCache(LocalCache):
@@ -111,6 +136,28 @@ def _stub_browser_session(monkeypatch: pytest.MonkeyPatch, _fake_clock: list[flo
yield
+def _install_timed_context(monkeypatch: pytest.MonkeyPatch, clock: list[float]) -> None:
+ @asynccontextmanager
+ async def _scope(_ctx: AgentContext) -> AsyncIterator[None]:
+ clock[0] += _CONTEXT_ENTER_SECONDS
+ try:
+ yield
+ finally:
+ clock[0] += _CONTEXT_EXIT_SECONDS
+
+ monkeypatch.setattr(mcp_adapter, "mcp_browser_context", _scope)
+
+
+def _browser_server(on_call: Callable[[], None]) -> SkyvernOverlayMCPServer:
+ return _make_server(
+ make_copilot_ctx(browser_session_id="pbs_1"),
+ {"ok": True},
+ SchemaOverlay(requires_browser=True),
+ alias_map=get_skyvern_mcp_alias_map(),
+ on_call=on_call,
+ )
+
+
def _timing_records(captured: list[dict[str, Any]]) -> list[dict[str, Any]]:
return [record for record in captured if record.get("event") == _TIMING_EVENT]
@@ -135,12 +182,13 @@ def _server_whose_call_takes_time(
clock: list[float],
alias_map: dict[str, str] | None = None,
is_error: bool = False,
+ browser_session_id: str | None = "pbs_1",
) -> SkyvernOverlayMCPServer:
def _advance() -> None:
clock[0] += _MCP_CALL_SECONDS
return _make_server(
- make_copilot_ctx(browser_session_id="pbs_1"),
+ make_copilot_ctx(browser_session_id=browser_session_id),
payload,
overlay,
alias_map=alias_map,
@@ -199,11 +247,27 @@ class TestMCPToolTiming:
records = _timing_records(captured)
assert len(records) == 1
assert records[0]["server_timing_ms"] is None
+ assert records[0]["server_attach_ms"] is None
assert records[0]["tool_name"] == "skyvern_evaluate"
assert records[0]["mcp_tool_name"] == "skyvern_evaluate"
assert records[0]["call_path"] == "internal"
assert records[0]["wall_clock_ms"] == _WALL_MS
+ @pytest.mark.asyncio
+ async def test_the_browser_attach_is_named_and_folded_back_into_the_server_span_once(
+ self, _fake_clock: list[float]
+ ) -> None:
+ payload = {"ok": True, "data": {"x": 1}, "timing_ms": {"attach": 300, "total": 515}}
+ server = _server_whose_call_takes_time(payload, SchemaOverlay(), _fake_clock)
+
+ with capture_logs() as captured:
+ await server.call_internal_tool("skyvern_evaluate", {"expression": "scan()"})
+
+ record = _timing_records(captured)[0]
+ assert record["server_attach_ms"] == 300
+ assert record["server_timing_ms"] == 815
+ assert record["phase_dispatch_untimed_ms"] == _MCP_CALL_MS - 815
+
@pytest.mark.asyncio
async def test_model_facing_call_logs_both_names_and_excludes_the_post_hook(self, _fake_clock: list[float]) -> None:
payload = {"ok": True, "data": {"result": 1}, "timing_ms": {"sdk": 812, "total": 815}}
@@ -242,6 +306,7 @@ class TestMCPToolTiming:
assert len(records) == 1
assert records[0]["call_status"] == "timeout"
assert records[0]["server_timing_ms"] is None
+ assert records[0]["timing_server_overrun"] is None
assert records[0]["wall_clock_ms"] == _WALL_MS
@pytest.mark.asyncio
@@ -291,6 +356,10 @@ class TestMCPToolTiming:
assert records[0]["call_path"] == call_path
assert records[0]["wall_clock_ms"] == _SESSION_ONLY_MS
assert records[0]["server_timing_ms"] is None
+ assert records[0]["timing_phase"] == "session_prepare"
+ assert records[0]["phase_session_prepare_ms"] == _SESSION_ONLY_MS
+ assert records[0]["phase_dispatch_ms"] == 0
+ assert records[0]["phase_residual_ms"] >= 0
@pytest.mark.asyncio
@pytest.mark.parametrize("call_path", ["model", "internal"])
@@ -302,7 +371,9 @@ class TestMCPToolTiming:
return {"ok": False, "error": "no browser session"}
monkeypatch.setattr(mcp_adapter, "ensure_browser_session", _session_error)
- server = _server_whose_call_takes_time({"ok": True}, SchemaOverlay(requires_browser=True), _fake_clock)
+ server = _server_whose_call_takes_time(
+ {"ok": True}, SchemaOverlay(requires_browser=True), _fake_clock, browser_session_id=None
+ )
with capture_logs() as captured:
result = await _call(server, call_path)
@@ -370,6 +441,258 @@ class TestMCPToolTiming:
assert records[0]["call_path"] == "internal"
assert records[0]["server_timing_ms"] is None
+ @pytest.mark.asyncio
+ @pytest.mark.parametrize("call_path", ["model", "internal"])
+ async def test_a_call_whose_wall_clock_dwarfs_the_server_total_names_where_the_time_went(
+ self, call_path: str, monkeypatch: pytest.MonkeyPatch, _fake_clock: list[float]
+ ) -> None:
+ _install_timed_context(monkeypatch, _fake_clock)
+ payload = {"ok": True, "data": {"x": 1}, "timing_ms": {"total": 815}}
+ server = _server_whose_call_takes_time(
+ payload, SchemaOverlay(requires_browser=True), _fake_clock, alias_map=get_skyvern_mcp_alias_map()
+ )
+
+ with capture_logs() as captured:
+ await _call(server, call_path)
+
+ record = _timing_records(captured)[0]
+ assert record["wall_clock_ms"] == _GAP_WALL_MS
+ assert record["server_timing_ms"] == 815
+ assert record["phase_session_prepare_ms"] == _SESSION_ONLY_MS
+ assert record["phase_context_enter_ms"] == _CONTEXT_ENTER_MS
+ assert record["phase_dispatch_ms"] == _MCP_CALL_MS
+ assert record["phase_context_exit_ms"] == _CONTEXT_EXIT_MS
+ assert record["phase_residual_ms"] == 0
+ assert record["timing_phase"] is None
+ _assert_every_millisecond_is_attributed(record)
+ assert record["phase_dispatch_untimed_ms"] == _MCP_CALL_MS - 815
+ assert record["timing_server_overrun"] is False
+ outside_the_server = sum(record[key] for key in _PHASE_KEYS if key != "phase_dispatch_ms")
+ assert outside_the_server + record["phase_dispatch_untimed_ms"] == _GAP_WALL_MS - 815
+
+ @pytest.mark.asyncio
+ @pytest.mark.parametrize("call_path", ["model", "internal"])
+ async def test_a_tool_that_answered_with_an_error_names_no_segment_as_the_one_it_died_in(
+ self, call_path: str, monkeypatch: pytest.MonkeyPatch, _fake_clock: list[float]
+ ) -> None:
+ _install_timed_context(monkeypatch, _fake_clock)
+ payload = {"ok": False, "error": "the page said no", "timing_ms": {"total": 815}}
+ server = _server_whose_call_takes_time(
+ payload, SchemaOverlay(requires_browser=True), _fake_clock, alias_map=get_skyvern_mcp_alias_map()
+ )
+
+ with capture_logs() as captured:
+ await _call(server, call_path)
+
+ record = _timing_records(captured)[0]
+ assert record["call_status"] == "error"
+ assert record["timing_phase"] is None
+ assert record["post_call_evidence_drain_ms"] is None
+ _assert_every_millisecond_is_attributed(record)
+
+ @pytest.mark.asyncio
+ @pytest.mark.parametrize("requires_browser", [False, True], ids=["no_browser", "browser"])
+ async def test_a_call_far_longer_than_any_plausible_ceiling_runs_to_completion(
+ self, requires_browser: bool, monkeypatch: pytest.MonkeyPatch, _fake_clock: list[float]
+ ) -> None:
+ overlay = SchemaOverlay(requires_browser=requires_browser)
+ assert overlay.timeout is None
+ if requires_browser:
+ _install_timed_context(monkeypatch, _fake_clock)
+
+ dispatches = []
+
+ def _advance_an_hour() -> None:
+ dispatches.append(_fake_clock[0])
+ _fake_clock[0] += _AN_HOUR_SECONDS
+
+ server = _make_server(
+ make_copilot_ctx(browser_session_id="pbs_1"),
+ {"ok": True, "data": {"x": 1}},
+ overlay,
+ on_call=_advance_an_hour,
+ )
+
+ with capture_logs() as captured:
+ result = await server.call_tool("evaluate", {"expression": "scan()"})
+
+ assert isinstance(result, CallToolResult)
+ assert result.isError is not True
+ assert len(dispatches) == 1
+ assert json.loads(result.content[0].text)["data"] == {"x": 1}
+ record = _timing_records(captured)[0]
+ assert record["call_status"] == "ok"
+ assert record["phase_dispatch_ms"] == _AN_HOUR_MS
+ around_the_dispatch = _SESSION_ONLY_MS + _CONTEXT_ENTER_MS + _CONTEXT_EXIT_MS if requires_browser else 0
+ assert record["wall_clock_ms"] == _AN_HOUR_MS + around_the_dispatch
+ assert record["phase_residual_ms"] == 0
+
+ @pytest.mark.asyncio
+ @pytest.mark.parametrize("call_path", ["model", "internal"])
+ @pytest.mark.parametrize("cancel_at", ["context_enter", "dispatch", "context_exit"])
+ async def test_a_cancelled_call_names_the_segment_that_was_in_flight(
+ self, cancel_at: str, call_path: str, monkeypatch: pytest.MonkeyPatch, _fake_clock: list[float]
+ ) -> None:
+ @asynccontextmanager
+ async def _scope(_ctx: AgentContext) -> AsyncIterator[None]:
+ _fake_clock[0] += _CONTEXT_ENTER_SECONDS
+ if cancel_at == "context_enter":
+ raise asyncio.CancelledError
+ try:
+ yield
+ finally:
+ _fake_clock[0] += _CONTEXT_EXIT_SECONDS
+ if cancel_at == "context_exit":
+ raise asyncio.CancelledError
+
+ monkeypatch.setattr(mcp_adapter, "mcp_browser_context", _scope)
+
+ def _advance() -> None:
+ _fake_clock[0] += _MCP_CALL_SECONDS
+ if cancel_at == "dispatch":
+ raise asyncio.CancelledError
+
+ server = _browser_server(_advance)
+
+ with capture_logs() as captured:
+ with pytest.raises(asyncio.CancelledError):
+ await _call(server, call_path)
+
+ record = _timing_records(captured)[0]
+ assert record["call_status"] == "cancelled"
+ assert record["call_path"] == call_path
+ assert record["timing_phase"] == cancel_at
+ assert record["server_timing_ms"] is None
+ assert record["phase_residual_ms"] >= 0
+ _assert_every_millisecond_is_attributed(record)
+ if cancel_at == "context_enter":
+ assert record["phase_dispatch_ms"] == 0
+ assert record["phase_context_exit_ms"] == 0
+ else:
+ assert record["phase_dispatch_ms"] == _MCP_CALL_MS
+ assert record["phase_context_exit_ms"] == _CONTEXT_EXIT_MS
+
+ @pytest.mark.asyncio
+ async def test_a_server_total_larger_than_the_dispatch_segment_is_not_subtracted(
+ self, monkeypatch: pytest.MonkeyPatch, _fake_clock: list[float]
+ ) -> None:
+ _install_timed_context(monkeypatch, _fake_clock)
+ payload = {"ok": True, "data": {"x": 1}, "timing_ms": {"total": _MCP_CALL_MS + 1}}
+ server = _server_whose_call_takes_time(
+ payload, SchemaOverlay(requires_browser=True), _fake_clock, alias_map=get_skyvern_mcp_alias_map()
+ )
+
+ with capture_logs() as captured:
+ await server.call_tool("evaluate", {"expression": "scan()"})
+
+ record = _timing_records(captured)[0]
+ assert record["phase_dispatch_untimed_ms"] is None
+ assert record["timing_server_overrun"] is True
+ _assert_every_millisecond_is_attributed(record)
+
+ @pytest.mark.asyncio
+ @pytest.mark.parametrize(
+ ("failure", "call_status"),
+ [
+ (asyncio.CancelledError(), "cancelled"),
+ (CopilotBrowserSessionUnavailable("pbs_1"), "session_error"),
+ (RuntimeError("drain exploded"), "error"),
+ ],
+ ids=["cancelled", "session_error", "error"],
+ )
+ async def test_an_evidence_drain_that_fails_still_reports_the_budget_it_spent(
+ self,
+ failure: BaseException,
+ call_status: str,
+ monkeypatch: pytest.MonkeyPatch,
+ _fake_clock: list[float],
+ ) -> None:
+ payload = {"ok": True, "data": {"x": 1}, "timing_ms": {"total": 815}}
+ server = _server_whose_call_takes_time(payload, SchemaOverlay(), _fake_clock)
+ server._evidence_candidate_origin = "https://public.test"
+ server._context_provider().browser_session_replacements = {"pbs_1": "pbs_replacement"}
+
+ async def _failing_drain() -> None:
+ _fake_clock[0] += _AFTER_CALL_SECONDS
+ raise failure
+
+ monkeypatch.setattr(server, "_drain_evidence_candidate_response_tasks", _failing_drain)
+
+ with capture_logs() as captured:
+ if isinstance(failure, asyncio.CancelledError):
+ with pytest.raises(asyncio.CancelledError):
+ await server.call_internal_tool("skyvern_evaluate", {"expression": "scan()"})
+ else:
+ await server.call_internal_tool("skyvern_evaluate", {"expression": "scan()"})
+
+ record = _timing_records(captured)[0]
+ assert record["call_status"] == call_status
+ assert record["wall_clock_ms"] == _WALL_MS
+ assert record["post_call_evidence_drain_ms"] == _AFTER_CALL_MS
+ assert record["phase_residual_ms"] == 0
+ assert record["timing_phase"] == "evidence_drain"
+ _assert_every_millisecond_is_attributed(record)
+
+ @pytest.mark.asyncio
+ async def test_an_evidence_drain_that_succeeds_reports_what_the_caller_waited_for_it(
+ self, monkeypatch: pytest.MonkeyPatch, _fake_clock: list[float]
+ ) -> None:
+ payload = {"ok": True, "data": {"x": 1}, "timing_ms": {"total": 815}}
+ server = _server_whose_call_takes_time(payload, SchemaOverlay(), _fake_clock)
+ server._evidence_candidate_origin = "https://public.test"
+
+ async def _slow_drain() -> None:
+ _fake_clock[0] += _AFTER_CALL_SECONDS
+
+ monkeypatch.setattr(server, "_drain_evidence_candidate_response_tasks", _slow_drain)
+
+ with capture_logs() as captured:
+ await server.call_internal_tool("skyvern_evaluate", {"expression": "scan()"})
+
+ record = _timing_records(captured)[0]
+ assert record["call_status"] == "ok"
+ assert record["post_call_evidence_drain_ms"] == _AFTER_CALL_MS
+ assert record["wall_clock_ms"] == _WALL_MS
+ _assert_every_millisecond_is_attributed(record)
+
+ @pytest.mark.asyncio
+ async def test_a_timing_sink_that_fails_costs_the_record_and_not_the_tool_result(
+ self, monkeypatch: pytest.MonkeyPatch, _fake_clock: list[float]
+ ) -> None:
+ payload = {"ok": True, "data": {"x": 1}, "timing_ms": {"total": 815}}
+ server = _server_whose_call_takes_time(payload, SchemaOverlay(), _fake_clock)
+ real_info = mcp_adapter.LOG.info
+
+ def _sink_down(event: str, **fields: Any) -> Any:
+ if event == "MCP tool timing":
+ raise RuntimeError("structlog sink unavailable")
+ return real_info(event, **fields)
+
+ monkeypatch.setattr(mcp_adapter.LOG, "info", _sink_down)
+
+ result = await server.call_internal_tool("skyvern_evaluate", {"expression": "scan()"})
+
+ assert result.get("data") == {"x": 1}
+
+ @pytest.mark.asyncio
+ async def test_a_tool_that_needs_no_browser_spends_its_whole_wall_clock_dispatching(
+ self, _fake_clock: list[float]
+ ) -> None:
+ payload = {"ok": True, "data": {"x": 1}, "timing_ms": {"total": 815}}
+ server = _server_whose_call_takes_time(payload, SchemaOverlay(), _fake_clock)
+
+ with capture_logs() as captured:
+ await server.call_tool("evaluate", {"expression": "scan()"})
+
+ record = _timing_records(captured)[0]
+ assert record["wall_clock_ms"] == _MCP_CALL_MS
+ assert record["phase_dispatch_ms"] == _MCP_CALL_MS
+ assert record["phase_session_prepare_ms"] == 0
+ assert record["phase_context_enter_ms"] == 0
+ assert record["phase_context_exit_ms"] == 0
+ assert record["phase_residual_ms"] == 0
+ assert record["timing_phase"] is None
+
class TestBrowserSessionContinuity:
@pytest.fixture(autouse=True)
@@ -647,22 +970,28 @@ class TestBrowserSessionContinuity:
@pytest.mark.asyncio
@pytest.mark.parametrize("call_path", ["model", "internal"])
- async def test_pre_dispatch_probe_uncertainty_does_not_claim_session_loss(
+ async def test_pre_dispatch_probe_uncertainty_dispatches_instead_of_claiming_loss(
self, call_path: str, monkeypatch: pytest.MonkeyPatch
) -> None:
ctx = make_copilot_ctx(browser_session_id="pbs_lost")
- async def _undetermined(_ctx: AgentContext, **_kwargs: Any) -> dict[str, Any]:
+ async def _undetermined(_ctx: AgentContext, *, require_verified_session: bool = False) -> Any:
await asyncio.sleep(0)
- return {"ok": False, "error": "Could not verify the browser session; please retry"}
+ # Only a caller that demands verification is handed a verdict; everyone else is
+ # allowed through to attach and find out.
+ return {"ok": False, "error": "unverified"} if require_verified_session else None
+
+ @asynccontextmanager
+ async def _attached(_ctx: AgentContext) -> AsyncIterator[None]:
+ yield
monkeypatch.setattr(mcp_adapter, "ensure_browser_session", _undetermined)
+ monkeypatch.setattr(mcp_adapter, "mcp_browser_context", _attached)
server = _make_server(ctx, {"ok": True}, SchemaOverlay(requires_browser=True))
with capture_logs() as logs:
- result = await _call(server, call_path)
+ await _call(server, call_path)
- assert "Could not verify the browser session" in _surfaced_error(result, call_path)
assert ctx.blocker_signal is None
assert ctx.browser_session_id == "pbs_lost"
assert ctx.browser_session_replacements == {}
@@ -670,7 +999,7 @@ class TestBrowserSessionContinuity:
assert continuity == []
timing = _timing_records(logs)
assert len(timing) == 1
- assert timing[0]["call_status"] == "session_error"
+ assert timing[0]["call_status"] == "ok"
@pytest.mark.asyncio
async def test_reestablish_budget_expiry_terminalizes_session_loss(self, monkeypatch: pytest.MonkeyPatch) -> None:
diff --git a/tests/unit/test_copilot_narration.py b/tests/unit/test_copilot_narration.py
index e49599401..f2b4fcb59 100644
--- a/tests/unit/test_copilot_narration.py
+++ b/tests/unit/test_copilot_narration.py
@@ -35,6 +35,8 @@ from skyvern.forge.sdk.copilot.narration import (
snapshot_ctx,
)
+_ACTIVITY_TS = datetime(2026, 1, 1, tzinfo=timezone.utc)
+
def _ctx(
update_workflow_called: bool = False,
@@ -484,6 +486,25 @@ async def test_schedule_narration_emits_on_happy_path(monkeypatch: pytest.Monkey
assert state.last_emitted_at is not None
+async def test_narration_entry_shares_the_clock_read_of_its_sse_update(monkeypatch: pytest.MonkeyPatch) -> None:
+ async def _handler(prompt: str, prompt_name: str, **kwargs: object) -> str:
+ return "Revising the workflow draft."
+
+ await _install_handler(monkeypatch, _handler)
+
+ state = NarratorState()
+ state.record_transition(TransitionKind.WORKFLOW_UPDATED)
+ stream = _FakeStream()
+
+ schedule_narration(state, stream, iteration=3) # type: ignore[arg-type]
+ assert state.in_flight_task is not None
+ await state.in_flight_task
+
+ entry = state.design_activity[0]
+ assert entry["timestamp"] == stream.sent[0].timestamp.isoformat()
+
+
@pytest.mark.asyncio
async def test_schedule_narration_keeps_clock_frozen_on_failure(monkeypatch: pytest.MonkeyPatch) -> None:
"""A failed narration must not advance ``last_emitted_at``. Advancing would
@@ -883,6 +904,38 @@ async def test_poll_tick_block_ts_change_triggers_fetch_and_records_transition()
pass
+async def test_poll_tick_records_block_run_identity_alongside_started_at() -> None:
+ state = NarratorState(current_iteration=4)
+ stream = _StubStream()
+ started_at: dict[str, str] = {}
+ identities: dict[str, narration.BlockRunIdentity] = {}
+
+ async def fetch() -> list[_StubBlock]:
+ return [_StubBlock("b7", "running")]
+
+ await narrator_poll_tick(
+ state,
+ current_block_ts=_ts(2.0),
+ prior_block_ts=_ts(1.0),
+ last_block_fetch_monotonic=0.0,
+ seen_block_states={},
+ fetch_block_statuses=fetch,
+ stream=stream, # type: ignore[arg-type]
+ block_started_at_map=started_at,
+ block_run_identity_map=identities,
+ )
+
+ assert "label_b7" in started_at
+ assert identities["label_b7"] == narration.BlockRunIdentity(workflow_run_block_id="b7", iteration=4)
+ if state.in_flight_task is not None:
+ state.in_flight_task.cancel()
+ try:
+ await state.in_flight_task
+ except (asyncio.CancelledError, Exception):
+ pass
+
+
@pytest.mark.asyncio
async def test_poll_tick_block_unchanged_does_not_fetch_or_record() -> None:
state = NarratorState(last_attempted_at=time.monotonic())
@@ -1343,7 +1396,9 @@ async def test_poll_tick_block_ended_at_overwritten_by_latest_terminal_and_clear
def _armed_state(iteration: int) -> NarratorState:
state = NarratorState()
state.record_transition(TransitionKind.NEW_TOOL_CLUSTER)
- state.record_activity(narration.build_tool_call_activity("edit_block", iteration, f"c{iteration}"))
+ state.record_activity(
+ narration.build_tool_call_activity("edit_block", iteration, f"c{iteration}", timestamp=_ACTIVITY_TS)
+ )
return state
@@ -1361,7 +1416,7 @@ def test_should_emit_true_for_a_clean_iteration_alongside_an_armed_one() -> None
def test_should_emit_true_when_the_iterations_only_tool_is_denylisted() -> None:
state = NarratorState()
state.record_transition(TransitionKind.NEW_TOOL_CLUSTER)
- state.record_activity(narration.build_tool_call_activity("get_run_results", 0, "c0"))
+ state.record_activity(narration.build_tool_call_activity("get_run_results", 0, "c0", timestamp=_ACTIVITY_TS))
assert state.iterations_with_tool_activity == set()
assert should_emit(state, now=100.0, iteration=0) is True
@@ -1369,7 +1424,9 @@ def test_should_emit_true_when_the_iterations_only_tool_is_denylisted() -> None:
def test_tool_result_alone_arms_the_iteration() -> None:
state = NarratorState()
state.record_transition(TransitionKind.NEW_TOOL_CLUSTER)
- state.record_activity(narration.build_tool_result_activity("edit_block", "done", True, 5, "c5"))
+ state.record_activity(
+ narration.build_tool_result_activity("edit_block", "done", True, 5, "c5", timestamp=_ACTIVITY_TS)
+ )
assert should_emit(state, now=100.0, iteration=5) is False
@@ -1398,7 +1455,7 @@ async def test_narration_dropped_when_the_iteration_arms_while_the_narrator_is_i
schedule_narration(state, stream, iteration=4) # type: ignore[arg-type]
assert state.in_flight_task is not None
- state.record_activity(narration.build_tool_call_activity("edit_block", 4, "c4"))
+ state.record_activity(narration.build_tool_call_activity("edit_block", 4, "c4", timestamp=_ACTIVITY_TS))
released.set()
await state.in_flight_task
@@ -1414,7 +1471,7 @@ async def test_narration_emits_for_a_clean_iteration(monkeypatch: pytest.MonkeyP
await _install_handler(monkeypatch, _handler)
state = NarratorState()
- state.record_activity(narration.build_tool_call_activity("edit_block", 4, "c4"))
+ state.record_activity(narration.build_tool_call_activity("edit_block", 4, "c4", timestamp=_ACTIVITY_TS))
state.record_transition(TransitionKind.NEW_TOOL_CLUSTER)
stream = _FakeStream()
@@ -1439,7 +1496,7 @@ def test_suppressed_iteration_consumes_its_transition_instead_of_banking_it() ->
# streaming_adapter sets current_iteration before recording the transition.
state.current_iteration = 3
state.record_transition(TransitionKind.WORKFLOW_UPDATED)
- state.record_activity(narration.build_tool_call_activity("update_workflow", 3, "c3"))
+ state.record_activity(narration.build_tool_call_activity("update_workflow", 3, "c3", timestamp=_ACTIVITY_TS))
schedule_narration(state, stream, 3)
@@ -1447,7 +1504,7 @@ def test_suppressed_iteration_consumes_its_transition_instead_of_banking_it() ->
assert state.in_flight_task is None
# A later unarmed iteration must not inherit the earlier transition.
- state.record_activity(narration.build_tool_call_activity("get_browser_screenshot", 7, "c7"))
+ state.record_activity(narration.build_tool_call_activity("get_browser_screenshot", 7, "c7", timestamp=_ACTIVITY_TS))
assert should_emit(state, 300.0, 7) is False
@@ -1458,12 +1515,97 @@ def test_suppression_keeps_a_transition_banked_by_an_earlier_clean_iteration() -
# Iteration 5's only tool is denylisted, so nothing typed describes it.
state.current_iteration = 5
state.record_transition(TransitionKind.TOOL_STARTED)
- state.record_activity(narration.build_tool_call_activity("get_browser_screenshot", 5, "c5"))
+ state.record_activity(narration.build_tool_call_activity("get_browser_screenshot", 5, "c5", timestamp=_ACTIVITY_TS))
# Iteration 6 carries a typed row and is suppressed; it must not consume
# iteration 5's transition.
state.current_iteration = 6
- state.record_activity(narration.build_tool_call_activity("click", 6, "c6"))
+ state.record_activity(narration.build_tool_call_activity("click", 6, "c6", timestamp=_ACTIVITY_TS))
schedule_narration(state, stream, 6)
assert state.pending_transition is TransitionKind.TOOL_STARTED
+
+
+def test_workflow_edit_reset_clears_the_block_run_identity_map() -> None:
+ from skyvern.forge.sdk.copilot.blocker_signal import clear_active_run_evidence_on_workflow_edit
+
+ ctx = SimpleNamespace(
+ last_run_blocks_workflow_run_id="wr_1",
+ last_successful_run_blocks_workflow_run_id=None,
+ last_run_blocks_browser_session_id=None,
+ recorded_persisted_block_run_workflow_run_id=None,
+ last_run_blocks_block_ids=["b1"],
+ last_run_blocks_block_labels=["log_in"],
+ last_run_outcome=None,
+ last_run_outcome_block_labels=["log_in"],
+ last_test_anti_bot=None,
+ completion_verification_result=None,
+ outcome_verification_trace_snapshot={"a": 1},
+ pre_run_page_reference=None,
+ registered_artifact_evidence=None,
+ post_run_page_observation_tool=None,
+ post_run_page_observation_url=None,
+ post_run_page_observation_workflow_run_id=None,
+ post_run_page_observation_after_failed_test=False,
+ post_run_page_observation_generation=0,
+ post_run_current_page_inspection_workflow_run_id=None,
+ block_state_map={"log_in": "failed"},
+ block_started_at_map={"log_in": "2026-01-01T00:00:00+00:00"},
+ block_ended_at_map={"log_in": "2026-01-01T00:00:05+00:00"},
+ block_run_identity_map={"log_in": narration.BlockRunIdentity("wrb_A", 3)},
+ )
+
+ clear_active_run_evidence_on_workflow_edit(ctx)
+
+ # A re-authored block must not persist the detached run's identity: the next
+ # payload would otherwise attribute it to the run the edit just replaced.
+ assert ctx.block_run_identity_map == {}
+ assert ctx.block_state_map == {}
+
+
+async def test_poll_tick_keeps_the_last_run_identity_for_a_repeated_label() -> None:
+ # A repair loop reruns one label under a new workflow_run_block_id; the map
+ # must end on the run that actually produced the block the payload persists.
+ state = NarratorState(current_iteration=2)
+ stream = _StubStream()
+ identities: dict[str, narration.BlockRunIdentity] = {}
+ seen: dict[str, str] = {}
+ blocks = [_StubBlock("wrb_first", "running", label="log_in")]
+
+ async def fetch() -> list[_StubBlock]:
+ return blocks
+
+ await narrator_poll_tick(
+ state,
+ current_block_ts=_ts(2.0),
+ prior_block_ts=_ts(1.0),
+ last_block_fetch_monotonic=0.0,
+ seen_block_states=seen,
+ fetch_block_statuses=fetch,
+ stream=stream, # type: ignore[arg-type]
+ block_run_identity_map=identities,
+ )
+ assert identities["log_in"].workflow_run_block_id == "wrb_first"
+
+ state.current_iteration = 5
+ blocks[:] = [_StubBlock("wrb_second", "running", label="log_in")]
+ await narrator_poll_tick(
+ state,
+ current_block_ts=_ts(4.0),
+ prior_block_ts=_ts(3.0),
+ last_block_fetch_monotonic=0.0,
+ seen_block_states=seen,
+ fetch_block_statuses=fetch,
+ stream=stream, # type: ignore[arg-type]
+ block_run_identity_map=identities,
+ )
+
+ assert identities["log_in"] == narration.BlockRunIdentity(workflow_run_block_id="wrb_second", iteration=5)
+
+ if state.in_flight_task is not None:
+ state.in_flight_task.cancel()
+ try:
+ await state.in_flight_task
+ except (asyncio.CancelledError, Exception):
+ pass
diff --git a/tests/unit/test_copilot_narrative_activity.py b/tests/unit/test_copilot_narrative_activity.py
index e8ed565e3..dd6054789 100644
--- a/tests/unit/test_copilot_narrative_activity.py
+++ b/tests/unit/test_copilot_narrative_activity.py
@@ -4,7 +4,7 @@ from datetime import datetime, timezone
from types import SimpleNamespace
from skyvern.forge.sdk.copilot.agent import _build_narrative_payload
-from skyvern.forge.sdk.copilot.context import CopilotContext
+from skyvern.forge.sdk.copilot.context import BlockRunIdentity, CopilotContext
from skyvern.forge.sdk.copilot.narration import (
MAX_BLOCK_ACTIVITY_ENTRIES,
MAX_DESIGN_ACTIVITY_ENTRIES,
@@ -19,6 +19,8 @@ from skyvern.forge.sdk.copilot.review_gate import workflow_block_fingerprints
_SURGICAL_EDIT_TOOLS = ("edit_block", "delete_block")
+_TS = datetime(2026, 1, 1, tzinfo=timezone.utc)
+
_CREDENTIAL_PAYLOAD: dict[str, object] = {
"count": 4,
"credentials": [
@@ -61,7 +63,7 @@ def _staged(*labels: str) -> SimpleNamespace:
def test_tool_call_activity_shape_and_denylist() -> None:
- entry = build_tool_call_activity("update_workflow", 3, "abc")
+ entry = build_tool_call_activity("update_workflow", 3, "abc", timestamp=_TS)
assert entry == {
"kind": "tool_call",
"text": "Updating workflow…",
@@ -69,13 +71,14 @@ def test_tool_call_activity_shape_and_denylist() -> None:
"toolName": "update_workflow",
"displayLabel": "Updating workflow",
"id": "tc-abc",
+ "timestamp": _TS.isoformat(),
}
assert "success" not in entry
- assert build_tool_call_activity("get_run_results", 0, "x") is None
+ assert build_tool_call_activity("get_run_results", 0, "x", timestamp=_TS) is None
def test_tool_result_activity_shape_falls_back_to_tool_name_and_denylist() -> None:
- entry = build_tool_result_activity("update_workflow", "Updated 2 blocks", True, 4, "abc")
+ entry = build_tool_result_activity("update_workflow", "Updated 2 blocks", True, 4, "abc", timestamp=_TS)
assert entry == {
"kind": "tool_result",
"text": "Updated 2 blocks",
@@ -84,10 +87,13 @@ def test_tool_result_activity_shape_falls_back_to_tool_name_and_denylist() -> No
"displayLabel": "Updating workflow",
"success": True,
"id": "tr-abc",
+ "timestamp": _TS.isoformat(),
}
- assert build_tool_result_activity("update_workflow", "", False, 4, "abc")["text"] == "Updating workflow"
- assert build_tool_result_activity("get_browser_screenshot", "s", True, 0, "x") is None
- assert build_tool_result_activity("get_run_results", "s", True, 0, "x") is None
+ assert (
+ build_tool_result_activity("update_workflow", "", False, 4, "abc", timestamp=_TS)["text"] == "Updating workflow"
+ )
+ assert build_tool_result_activity("get_browser_screenshot", "s", True, 0, "x", timestamp=_TS) is None
+ assert build_tool_result_activity("get_run_results", "s", True, 0, "x", timestamp=_TS) is None
def test_narration_activity_shape() -> None:
@@ -97,6 +103,7 @@ def test_narration_activity_shape() -> None:
"text": "Doing the thing",
"iteration": 5,
"id": "n-5-2026-01-01T00:00:00+00:00",
+ "timestamp": "2026-01-01T00:00:00+00:00",
}
assert "toolName" not in entry
@@ -112,7 +119,7 @@ def test_emitted_progress_texts_is_a_fresh_per_state_set() -> None:
def test_record_activity_routes_to_design_when_no_block_running() -> None:
state = NarratorState()
- state.record_activity(build_tool_call_activity("update_workflow", 0, "c1"))
+ state.record_activity(build_tool_call_activity("update_workflow", 0, "c1", timestamp=_TS))
assert [e["id"] for e in state.design_activity] == ["tc-c1"]
assert state.block_activity == {}
@@ -120,7 +127,9 @@ def test_record_activity_routes_to_design_when_no_block_running() -> None:
def test_record_activity_routes_to_running_block() -> None:
state = NarratorState()
state.running_block_label = "step_1"
- state.record_activity(build_tool_result_activity("run_blocks_and_collect_debug", "ran", True, 1, "c2"))
+ state.record_activity(
+ build_tool_result_activity("run_blocks_and_collect_debug", "ran", True, 1, "c2", timestamp=_TS)
+ )
assert [e["id"] for e in state.block_activity["step_1"]] == ["tr-c2"]
assert state.design_activity == []
@@ -128,8 +137,8 @@ def test_record_activity_routes_to_running_block() -> None:
def test_record_activity_drops_denylisted_entries() -> None:
state = NarratorState()
state.running_block_label = "step_1"
- state.record_activity(build_tool_call_activity("get_run_results", 0, "c1"))
- state.record_activity(build_tool_call_activity("update_workflow", 1, "c2"))
+ state.record_activity(build_tool_call_activity("get_run_results", 0, "c1", timestamp=_TS))
+ state.record_activity(build_tool_call_activity("update_workflow", 1, "c2", timestamp=_TS))
assert [e["id"] for e in state.block_activity["step_1"]] == ["tc-c2"]
@@ -137,7 +146,7 @@ def test_record_activity_caps_keep_most_recent() -> None:
state = NarratorState()
state.running_block_label = "b"
for i in range(MAX_BLOCK_ACTIVITY_ENTRIES + 10):
- state.record_activity(build_tool_call_activity("t", i, f"c{i}"))
+ state.record_activity(build_tool_call_activity("t", i, f"c{i}", timestamp=_TS))
bucket = state.block_activity["b"]
assert len(bucket) == MAX_BLOCK_ACTIVITY_ENTRIES
assert bucket[0]["iteration"] == 10
@@ -155,11 +164,13 @@ def test_record_activity_pins_run_tool_result_to_its_call_bucket() -> None:
# running_block_label; its result must rejoin the call's bucket so the FE
# folds the pair instead of stranding the call row "calling…".
state = NarratorState()
- state.record_activity(build_tool_call_activity("update_and_run_blocks", 0, "c1"))
+ state.record_activity(build_tool_call_activity("update_and_run_blocks", 0, "c1", timestamp=_TS))
assert [e["id"] for e in state.design_activity] == ["tc-c1"]
state.running_block_label = "step_1"
- state.record_activity(build_tool_result_activity("update_and_run_blocks", "Workflow updated", True, 1, "c1"))
+ state.record_activity(
+ build_tool_result_activity("update_and_run_blocks", "Workflow updated", True, 1, "c1", timestamp=_TS)
+ )
assert [e["id"] for e in state.design_activity] == ["tc-c1", "tr-c1"]
assert state.block_activity == {}
@@ -168,11 +179,11 @@ def test_record_activity_pins_run_tool_result_to_its_call_bucket() -> None:
def test_record_activity_non_run_tool_result_routes_live_not_pinned() -> None:
# The pin is scoped to run tools; other tools keep live running_block_label routing.
state = NarratorState()
- state.record_activity(build_tool_call_activity("evaluate", 0, "c9"))
+ state.record_activity(build_tool_call_activity("evaluate", 0, "c9", timestamp=_TS))
assert [e["id"] for e in state.design_activity] == ["tc-c9"]
state.running_block_label = "step_2"
- state.record_activity(build_tool_result_activity("evaluate", "Inspecting page", True, 1, "c9"))
+ state.record_activity(build_tool_result_activity("evaluate", "Inspecting page", True, 1, "c9", timestamp=_TS))
assert [e["id"] for e in state.block_activity["step_2"]] == ["tr-c9"]
assert [e["id"] for e in state.design_activity] == ["tc-c9"]
@@ -196,14 +207,22 @@ def test_build_narrative_payload_serializes_block_and_design_activity() -> None:
build_narration_activity("Planning the build", 0, datetime(2026, 1, 1, tzinfo=timezone.utc))
]
state.block_activity = {
- "step_1": [build_tool_result_activity("run_blocks_and_collect_debug", "ran step_1", True, 1, "c1")]
+ "step_1": [
+ build_tool_result_activity("run_blocks_and_collect_debug", "ran step_1", True, 1, "c1", timestamp=_TS)
+ ]
}
ctx.narrator_state = state
payload = _build_narrative_payload(ctx, terminal="response", terminal_message="done", narrative_summary="summary")
assert payload["designActivity"] == [
- {"kind": "narration", "text": "Planning the build", "iteration": 0, "id": "n-0-2026-01-01T00:00:00+00:00"}
+ {
+ "kind": "narration",
+ "text": "Planning the build",
+ "iteration": 0,
+ "id": "n-0-2026-01-01T00:00:00+00:00",
+ "timestamp": "2026-01-01T00:00:00+00:00",
+ }
]
blocks_by_label = {b["label"]: b for b in payload["blocks"]}
assert blocks_by_label["step_1"]["activity"] == [
@@ -215,11 +234,28 @@ def test_build_narrative_payload_serializes_block_and_design_activity() -> None:
"displayLabel": "Testing workflow",
"success": True,
"id": "tr-c1",
+ "timestamp": _TS.isoformat(),
}
]
assert blocks_by_label["step_2"]["activity"] == []
+def test_build_narrative_payload_persists_block_run_identity() -> None:
+ ctx = _ctx()
+ ctx.staged_workflow = _staged("step_1", "drafted_only") # type: ignore[assignment]
+ ctx.has_staged_proposal = True
+ ctx.block_state_map = {"step_1": "completed"}
+ ctx.block_run_identity_map = {"step_1": BlockRunIdentity(workflow_run_block_id="wrb_1", iteration=6)}
+
+ payload = _build_narrative_payload(ctx, terminal="response", terminal_message=None, narrative_summary=None)
+
+ blocks_by_label = {b["label"]: b for b in payload["blocks"]}
+ assert blocks_by_label["step_1"]["workflowRunBlockId"] == "wrb_1"
+ assert blocks_by_label["step_1"]["lastSeenIteration"] == 6
+ assert "workflowRunBlockId" not in blocks_by_label["drafted_only"]
+ assert blocks_by_label["drafted_only"]["lastSeenIteration"] == 0
+
+
def test_build_narrative_payload_empty_when_no_narrator_state() -> None:
ctx = _ctx()
ctx.staged_workflow = _staged("step_1") # type: ignore[assignment]
@@ -352,9 +388,13 @@ def test_surgical_edit_tools_never_render_the_working_fallback() -> None:
}
for index, tool_name in enumerate(_SURGICAL_EDIT_TOOLS):
display_label = labels[tool_name]
- state.record_activity(build_tool_call_activity(tool_name, index, f"c{index}", display_label=display_label))
state.record_activity(
- build_tool_result_activity(tool_name, "", True, index, f"c{index}", display_label=display_label)
+ build_tool_call_activity(tool_name, index, f"c{index}", display_label=display_label, timestamp=_TS)
+ )
+ state.record_activity(
+ build_tool_result_activity(
+ tool_name, "", True, index, f"c{index}", display_label=display_label, timestamp=_TS
+ )
)
rows = state.design_activity
@@ -367,9 +407,9 @@ def test_surgical_edit_tools_never_render_the_working_fallback() -> None:
def _credential_rows(state: NarratorState, parsed: dict[str, object], index: int) -> None:
summary = format_tool_result_for_user("list_credentials", parsed) # type: ignore[arg-type]
- state.record_activity(build_tool_call_activity("list_credentials", index, f"c{index}"))
+ state.record_activity(build_tool_call_activity("list_credentials", index, f"c{index}", timestamp=_TS))
state.record_activity(
- build_tool_result_activity("list_credentials", summary, bool(parsed["ok"]), index, f"c{index}")
+ build_tool_result_activity("list_credentials", summary, bool(parsed["ok"]), index, f"c{index}", timestamp=_TS)
)
@@ -403,8 +443,10 @@ def test_no_connection_use_line_is_rendered_from_credential_enumeration() -> Non
def test_explicit_display_label_overrides_the_static_name_map() -> None:
- call = build_tool_call_activity("edit_block", 2, "c7", display_label='Editing block "Log in"')
- result = build_tool_result_activity("edit_block", "", True, 2, "c7", display_label='Editing block "Log in"')
+ call = build_tool_call_activity("edit_block", 2, "c7", display_label='Editing block "Log in"', timestamp=_TS)
+ result = build_tool_result_activity(
+ "edit_block", "", True, 2, "c7", display_label='Editing block "Log in"', timestamp=_TS
+ )
assert call["displayLabel"] == result["displayLabel"] == 'Editing block "Log in"'
assert call["text"] == 'Editing block "Log in"…'
assert result["text"] == 'Editing block "Log in"'
@@ -434,8 +476,12 @@ def test_credential_fill_row_names_the_action_without_leaking_material() -> None
assert label == "Entering saved credentials"
state = NarratorState()
- state.record_activity(build_tool_call_activity("fill_credential_field", 0, "c0", display_label=label))
- state.record_activity(build_tool_result_activity("fill_credential_field", "", True, 0, "c0", display_label=label))
+ state.record_activity(
+ build_tool_call_activity("fill_credential_field", 0, "c0", display_label=label, timestamp=_TS)
+ )
+ state.record_activity(
+ build_tool_result_activity("fill_credential_field", "", True, 0, "c0", display_label=label, timestamp=_TS)
+ )
rows = state.design_activity
assert len(rows) == 2
diff --git a/tests/unit/test_copilot_runtime.py b/tests/unit/test_copilot_runtime.py
index b3dc8970d..f5e33f0ed 100644
--- a/tests/unit/test_copilot_runtime.py
+++ b/tests/unit/test_copilot_runtime.py
@@ -10,15 +10,22 @@ alongside the tools and enforcement helpers they exercise end-to-end.
from __future__ import annotations
import asyncio
+import inspect
+from dataclasses import fields
from types import SimpleNamespace
from typing import Any
from unittest.mock import AsyncMock, MagicMock
import pytest
from sqlalchemy.exc import TimeoutError as SQLATimeoutError
+from structlog.testing import capture_logs
-from skyvern.forge.sdk.copilot import runtime
+from skyvern.forge.sdk.cache.local import LocalCache
+from skyvern.forge.sdk.copilot import mcp_adapter, runtime
+from skyvern.forge.sdk.copilot.mcp_adapter import SchemaOverlay
from skyvern.forge.sdk.copilot.runtime import AgentContext, ensure_browser_session, mcp_browser_context, mcp_to_copilot
+from skyvern.forge.sdk.copilot.unrecoverable_tool_error import _is_unrecoverable_browser_session_error
+from tests.unit.test_copilot_secret_scrub import _make_server
class _FakeBrowser:
@@ -407,10 +414,11 @@ async def test_probe_classifies_failed_lookup_as_undetermined(monkeypatch: pytes
ctx = _make_ctx()
ctx.browser_session_id = "bs_live"
- outcome = await runtime._probe_browser_session(ctx, "bs_live")
+ outcome, fault = await runtime._probe_browser_session(ctx, "bs_live")
assert outcome == runtime.BrowserProbeOutcome.could_not_determine
assert outcome != runtime.BrowserProbeOutcome.positively_unreachable
+ assert fault == runtime.BrowserProbeFault(error_type="TimeoutError", timed_out=False)
health_check.assert_not_called()
@@ -426,14 +434,17 @@ async def test_probe_deadline_is_uncertainty_not_session_loss(monkeypatch: pytes
mock_app.DATABASE.browser_sessions.get_persistent_browser_session = MagicMock(return_value=None)
mock_app.PERSISTENT_SESSIONS_MANAGER = mock_manager
monkeypatch.setattr(runtime, "app", mock_app)
- monkeypatch.setattr(runtime, "_BROWSER_PROBE_WAIT_SECONDS", 0.01)
+ monkeypatch.setattr(runtime, "_BROWSER_PROBE_WAIT_SECONDS", 0.25)
ctx = _make_ctx()
ctx.browser_session_id = "bs_slow_but_unknown"
result = await ensure_browser_session(ctx, require_verified_session=True)
- assert result == {"ok": False, "error": "Could not verify the browser session; please retry"}
+ assert result is not None
+ assert result["probe_timed_out"] is True
+ assert result["probe_error_type"] == "TimeoutError"
+ assert "not evidence the browser is dead" in result["error"]
assert ctx.browser_session_id == "bs_slow_but_unknown"
mock_manager.create_session.assert_not_awaited()
@@ -590,10 +601,11 @@ async def test_probe_treats_failed_health_signal_as_undetermined(monkeypatch: py
ctx = _make_ctx()
ctx.browser_session_id = "bs_live"
- outcome = await runtime._probe_browser_session(ctx, "bs_live")
+ outcome, fault = await runtime._probe_browser_session(ctx, "bs_live")
assert outcome == runtime.BrowserProbeOutcome.could_not_determine
assert outcome != runtime.BrowserProbeOutcome.positively_unreachable
+ assert fault is None
@pytest.mark.asyncio
@@ -612,7 +624,7 @@ async def test_attach_keeps_session_when_health_signal_is_unavailable(
ctx = _make_ctx()
ctx.browser_session_id = "bs_live"
- with pytest.raises(RuntimeError, match="No browser context") as exc_info:
+ with pytest.raises(RuntimeError, match="could not be determined") as exc_info:
async with mcp_browser_context(ctx):
pass
@@ -620,6 +632,35 @@ async def test_attach_keeps_session_when_health_signal_is_unavailable(
assert not isinstance(exc_info.value, runtime.CopilotBrowserSessionUnavailable)
+async def test_an_undetermined_attach_is_not_read_as_session_loss(monkeypatch: pytest.MonkeyPatch) -> None:
+ mock_manager = MagicMock()
+ mock_app = MagicMock()
+ mock_app.PERSISTENT_SESSIONS_MANAGER = mock_manager
+ monkeypatch.setattr(runtime, "app", mock_app)
+
+ undetermined_state = MagicMock()
+ undetermined_state.browser_context = _UnreachableSignalContext()
+ mock_manager.get_browser_state = AsyncMock(return_value=undetermined_state)
+ ctx = _make_ctx()
+ ctx.browser_session_id = "bs_live"
+ with pytest.raises(RuntimeError) as undetermined:
+ async with mcp_browser_context(ctx):
+ pass
+
+ mock_manager.get_browser_state = AsyncMock(return_value=None)
+ ctx.browser_session_id = "bs_gone"
+ with pytest.raises(runtime.CopilotBrowserSessionUnavailable) as retired:
+ async with mcp_browser_context(ctx):
+ pass
+
+ def _tool_output(exc: BaseException) -> dict[str, Any]:
+ return {"ok": False, "error": f"evaluate failed: {exc}"}
+
+ assert not _is_unrecoverable_browser_session_error("evaluate", _tool_output(undetermined.value))
+ assert _is_unrecoverable_browser_session_error("evaluate", _tool_output(retired.value))
+
+
@pytest.mark.asyncio
async def test_ensure_does_not_retire_a_session_replaced_during_the_probe(
monkeypatch: pytest.MonkeyPatch,
@@ -715,3 +756,410 @@ async def test_create_closes_its_session_when_a_sibling_installed_one_first(
assert ctx.browser_session_id == "bs_sibling"
mock_manager.close_session.assert_awaited_once()
assert mock_manager.close_session.await_args.args[1] == "bs_loser"
+
+
+_SLOW_LOOKUP = object()
+
+
+def _deadline_fault() -> TimeoutError:
+ """What asyncio.timeout raises, without the wall-clock wait. The scripted lookup assigns steps
+ by call count, so a real deadline that fires before its call is entered shifts every later step."""
+ return TimeoutError("probe deadline")
+
+
+_TIMING_EVENT = "MCP tool timing"
+
+
+def _attachable_state() -> MagicMock:
+ state = MagicMock()
+ state.browser_context = _FakeBrowserContext()
+ return state
+
+
+def _dead_state() -> MagicMock:
+ state = MagicMock()
+ state.browser_context = _FakeBrowserContext(connected=False)
+ return state
+
+
+def _undetermined_state() -> MagicMock:
+ state = MagicMock()
+ state.browser_context = _UnreachableSignalContext()
+ return state
+
+
+class _SharedSessionLookup:
+ """The probe and the attach read the same session-manager lookup, so a fault meant to hit only
+ the probe has to be scoped to its call."""
+
+ def __init__(self, *script: Any) -> None:
+ self._script = list(script)
+ self.calls = 0
+
+ async def __call__(self, **_kwargs: Any) -> Any:
+ self.calls += 1
+ step = self._script[self.calls - 1] if self.calls <= len(self._script) else _attachable_state()
+ if step is _SLOW_LOOKUP:
+ await asyncio.Event().wait()
+ if isinstance(step, Exception):
+ raise step
+ return step
+
+
+def _install_dispatch_stack(
+ monkeypatch: pytest.MonkeyPatch,
+ lookup: _SharedSessionLookup,
+ *,
+ created_session_id: str = "bs_created",
+) -> MagicMock:
+ created = MagicMock()
+ created.persistent_browser_session_id = created_session_id
+
+ mock_manager = MagicMock()
+ mock_manager.get_browser_state = lookup
+ mock_manager.create_session = AsyncMock(return_value=created)
+ mock_app = MagicMock()
+ mock_app.DATABASE.browser_sessions.get_persistent_browser_session = MagicMock(return_value=None)
+ mock_app.PERSISTENT_SESSIONS_MANAGER = mock_manager
+ monkeypatch.setattr(runtime, "app", mock_app)
+ monkeypatch.setattr(runtime, "_BROWSER_PROBE_WAIT_SECONDS", 0.25)
+ monkeypatch.setattr(runtime, "get_skyvern", lambda: MagicMock())
+ monkeypatch.setattr(runtime, "SkyvernBrowser", lambda *_a, **_kw: MagicMock(workflow_run_id=None))
+ monkeypatch.setattr(runtime, "get_active_api_key", lambda: "sk-test-key")
+ monkeypatch.setattr(runtime, "set_api_key_override", lambda _key: object())
+ monkeypatch.setattr(runtime, "reset_api_key_override", lambda _token: None)
+ monkeypatch.setattr(runtime, "register_copilot_session", MagicMock())
+ monkeypatch.setattr(runtime, "unregister_copilot_session", MagicMock())
+
+ async def _close(_organization_id: str, _session_id: str) -> None:
+ return None
+
+ monkeypatch.setattr(runtime, "close_browser_session_quietly", _close)
+ monkeypatch.setattr(mcp_adapter, "close_browser_session_quietly", _close)
+ monkeypatch.setattr(mcp_adapter.app, "CACHE", LocalCache())
+ monkeypatch.setattr(runtime, "_BROWSER_BOOT_POLL_INTERVAL_SECONDS", 0.0)
+ mcp_adapter._LOCAL_CONTINUITY_OUTCOMES.clear()
+ mcp_adapter._LOCAL_CONTINUITY_ROOTS.clear()
+ return mock_manager
+
+
+async def _dispatch_browser_tool(ctx: AgentContext) -> tuple[Any, list[dict[str, Any]]]:
+ server = _make_server(
+ ctx,
+ {"ok": True, "data": {"result": 7}, "timing_ms": {"total": 1234}},
+ SchemaOverlay(requires_browser=True),
+ )
+ with capture_logs() as captured:
+ result = await server.call_tool("evaluate", {"expression": "scan()"})
+ return result, [record for record in captured if record.get("event") == _TIMING_EVENT]
+
+
+def _count_session_loss_handling(monkeypatch: pytest.MonkeyPatch) -> list[str]:
+ handled: list[str] = []
+ original = mcp_adapter._handle_browser_session_loss
+
+ async def _counted(ctx: AgentContext, **kwargs: Any) -> Any:
+ handled.append(str(kwargs["lost_session_id"]))
+ return await original(ctx, **kwargs)
+
+ monkeypatch.setattr(mcp_adapter, "_handle_browser_session_loss", _counted)
+ return handled
+
+
+def _count_stored_continuity_outcomes(monkeypatch: pytest.MonkeyPatch) -> list[tuple[str, str]]:
+ stored: list[tuple[str, str]] = []
+ original = mcp_adapter._store_continuity_outcome
+
+ async def _counted(organization_id: str, outcome: mcp_adapter._BrowserSessionContinuityOutcome) -> None:
+ stored.append((outcome.lost_session_id, outcome.disposition))
+ await original(organization_id, outcome)
+
+ monkeypatch.setattr(mcp_adapter, "_store_continuity_outcome", _counted)
+ return stored
+
+
+class TestIndeterminateProbeDispatch:
+ @pytest.mark.parametrize(
+ ("first_lookup", "arm"),
+ [
+ pytest.param(_deadline_fault(), "slow", id="probe_deadline"),
+ pytest.param(SQLATimeoutError("pool exhausted"), "exception", id="probe_exception"),
+ pytest.param(None, "nofault", id="connectivity_signal_never_answered"),
+ ],
+ )
+ @pytest.mark.asyncio
+ async def test_an_indeterminate_probe_still_reaches_the_browser(
+ self, monkeypatch: pytest.MonkeyPatch, first_lookup: Any, arm: str
+ ) -> None:
+ lookup = _SharedSessionLookup(_undetermined_state() if arm == "nofault" else first_lookup)
+ _install_dispatch_stack(monkeypatch, lookup)
+
+ ctx = _make_ctx()
+ ctx.browser_session_id = "bs_live"
+
+ result, timing = await _dispatch_browser_tool(ctx)
+
+ assert "please retry" not in result.content[0].text
+ assert '"result": 7' in result.content[0].text
+ assert ctx.browser_session_id == "bs_live"
+ assert [record["call_status"] for record in timing] == ["ok"]
+ assert timing[0]["server_timing_ms"] == 1234
+
+ @pytest.mark.asyncio
+ async def test_the_same_indeterminate_fault_is_handled_the_same_way_every_time(
+ self, monkeypatch: pytest.MonkeyPatch
+ ) -> None:
+ lookup = _SharedSessionLookup(
+ SQLATimeoutError("pool exhausted"),
+ _attachable_state(),
+ SQLATimeoutError("pool exhausted"),
+ )
+ _install_dispatch_stack(monkeypatch, lookup)
+
+ ctx = _make_ctx()
+ ctx.browser_session_id = "bs_live"
+
+ first_result, first_timing = await _dispatch_browser_tool(ctx)
+ second_result, second_timing = await _dispatch_browser_tool(ctx)
+
+ assert first_result.content[0].text == second_result.content[0].text
+ assert [record["call_status"] for record in first_timing] == [record["call_status"] for record in second_timing]
+ assert ctx.browser_session_id == "bs_live"
+
+ @pytest.mark.asyncio
+ async def test_a_dead_session_is_replaced_once_without_the_loss_handler(
+ self, monkeypatch: pytest.MonkeyPatch
+ ) -> None:
+ manager = _install_dispatch_stack(monkeypatch, _SharedSessionLookup(_dead_state()))
+ handled = _count_session_loss_handling(monkeypatch)
+ stored = _count_stored_continuity_outcomes(monkeypatch)
+
+ ctx = _make_ctx()
+ ctx.browser_session_id = "bs_stale"
+
+ result, _ = await _dispatch_browser_tool(ctx)
+
+ manager.create_session.assert_awaited_once()
+ assert handled == []
+ assert stored == [("bs_stale", "reestablished")]
+ assert ctx.browser_session_id == "bs_created"
+ assert "browser session was lost" in result.content[0].text
+
+ @pytest.mark.asyncio
+ async def test_a_session_that_dies_between_probe_and_attach_is_handled_once(
+ self, monkeypatch: pytest.MonkeyPatch
+ ) -> None:
+ _install_dispatch_stack(monkeypatch, _SharedSessionLookup(_attachable_state(), _dead_state()))
+ handled = _count_session_loss_handling(monkeypatch)
+
+ ctx = _make_ctx()
+ ctx.browser_session_id = "bs_dies_at_attach"
+
+ result, _ = await _dispatch_browser_tool(ctx)
+
+ assert handled == ["bs_dies_at_attach"]
+ assert "browser session was lost" in result.content[0].text
+
+ @pytest.mark.asyncio
+ async def test_no_session_held_never_probes_and_creates_one(self, monkeypatch: pytest.MonkeyPatch) -> None:
+ _install_dispatch_stack(monkeypatch, _SharedSessionLookup())
+
+ probed: list[str] = []
+ original_probe = runtime._probe_browser_session
+
+ async def _counted_probe(ctx: AgentContext, session_id: str) -> Any:
+ probed.append(session_id)
+ return await original_probe(ctx, session_id)
+
+ monkeypatch.setattr(runtime, "_probe_browser_session", _counted_probe)
+
+ ctx = _make_ctx()
+ ctx.browser_session_id = None
+
+ error, continuity = await mcp_adapter._prepare_browser_session_for_dispatch(
+ ctx, tool_name="evaluate", call_path="model", observed_generation=0
+ )
+
+ assert probed == []
+ assert (error, continuity) == (None, None)
+ assert ctx.browser_session_id == "bs_created"
+
+ def test_the_indeterminate_path_carries_no_attempt_state(self) -> None:
+ forbidden = ("attempt", "count", "ceiling", "budget", "classifier", "cache", "memo")
+ source = "".join(
+ inspect.getsource(fn)
+ for fn in (
+ runtime._probe_browser_session,
+ runtime._unverified_browser_session_facts,
+ runtime._try_attach_verify_browser_session,
+ runtime.ensure_browser_session,
+ mcp_adapter._prepare_browser_session_for_dispatch,
+ )
+ )
+
+ assert [token for token in forbidden if token in source] == []
+ assert [field.name for field in fields(runtime.BrowserProbeFault)] == ["error_type", "timed_out"]
+
+
+class TestUnverifiedSessionFacts:
+ @pytest.mark.parametrize(
+ ("fault", "expected_error_type", "expected_timed_out", "expected_cause"),
+ [
+ pytest.param(
+ runtime.BrowserProbeFault(error_type="TimeoutError", timed_out=True),
+ "TimeoutError",
+ True,
+ "did not answer within",
+ id="timeout",
+ ),
+ pytest.param(
+ runtime.BrowserProbeFault(error_type="OperationalError", timed_out=False),
+ "OperationalError",
+ False,
+ "raised OperationalError",
+ id="exception",
+ ),
+ pytest.param(None, None, False, "connectivity signal never answered", id="no_fault"),
+ ],
+ )
+ def test_the_caller_that_never_attaches_gets_the_probe_s_own_facts(
+ self,
+ fault: runtime.BrowserProbeFault | None,
+ expected_error_type: str | None,
+ expected_timed_out: bool,
+ expected_cause: str,
+ ) -> None:
+ facts = runtime._unverified_browser_session_facts(fault)
+
+ assert facts["ok"] is False
+ assert facts["probe_error_type"] == expected_error_type
+ assert facts["probe_timed_out"] is expected_timed_out
+ assert expected_cause in facts["error"]
+ assert "An indeterminate probe is not evidence the browser is dead." in facts["error"]
+
+
+def _count_escalations(monkeypatch: pytest.MonkeyPatch) -> list[str]:
+ escalated: list[str] = []
+ original = runtime._try_attach_verify_browser_session
+
+ async def _counted(ctx: AgentContext, session_id: str) -> Any:
+ escalated.append(session_id)
+ return await original(ctx, session_id)
+
+ monkeypatch.setattr(runtime, "_try_attach_verify_browser_session", _counted)
+ return escalated
+
+
+class TestVerifiedCallerEscalation:
+ """The caller that hands the id to an out-of-process run and never attaches itself."""
+
+ @pytest.mark.parametrize(
+ "probe_step",
+ [
+ pytest.param(_deadline_fault(), id="probe_deadline"),
+ pytest.param(ConnectionError("session manager pool exhausted"), id="probe_exception"),
+ pytest.param(_undetermined_state(), id="connectivity_signal_never_answered"),
+ ],
+ )
+ @pytest.mark.asyncio
+ async def test_an_indeterminate_probe_is_settled_by_one_escalation(
+ self, monkeypatch: pytest.MonkeyPatch, probe_step: Any
+ ) -> None:
+ manager = _install_dispatch_stack(monkeypatch, _SharedSessionLookup(probe_step, _attachable_state()))
+ escalated = _count_escalations(monkeypatch)
+
+ ctx = _make_ctx()
+ ctx.browser_session_id = "bs_live"
+
+ assert await ensure_browser_session(ctx, require_verified_session=True) is None
+ assert ctx.browser_session_id == "bs_live"
+ assert escalated == ["bs_live"]
+ manager.create_session.assert_not_awaited()
+
+ @pytest.mark.parametrize(
+ ("probe_step", "escalation_step", "expected_error_type", "expected_timed_out"),
+ [
+ pytest.param(
+ _deadline_fault(), ConnectionError("still down"), "ConnectionError", False, id="probe_deadline"
+ ),
+ pytest.param(
+ ConnectionError("pool exhausted"), _deadline_fault(), "TimeoutError", True, id="probe_exception"
+ ),
+ ],
+ )
+ @pytest.mark.asyncio
+ async def test_the_facts_name_the_fault_that_decided_the_outcome(
+ self,
+ monkeypatch: pytest.MonkeyPatch,
+ probe_step: Any,
+ escalation_step: Any,
+ expected_error_type: str,
+ expected_timed_out: bool,
+ ) -> None:
+ manager = _install_dispatch_stack(monkeypatch, _SharedSessionLookup(probe_step, escalation_step))
+
+ ctx = _make_ctx()
+ ctx.browser_session_id = "bs_live"
+
+ result = await ensure_browser_session(ctx, require_verified_session=True)
+
+ assert result is not None
+ assert result["probe_error_type"] == expected_error_type
+ assert result["probe_timed_out"] is expected_timed_out
+ assert "An indeterminate probe is not evidence the browser is dead." in result["error"]
+ assert "please retry" not in result["error"]
+ assert ctx.browser_session_id == "bs_live"
+ manager.create_session.assert_not_awaited()
+
+ @pytest.mark.asyncio
+ async def test_an_escalation_that_never_answers_returns_facts_rather_than_hanging(
+ self, monkeypatch: pytest.MonkeyPatch
+ ) -> None:
+ _install_dispatch_stack(monkeypatch, _SharedSessionLookup(ConnectionError("pool exhausted"), _SLOW_LOOKUP))
+
+ ctx = _make_ctx()
+ ctx.browser_session_id = "bs_live"
+
+ result = await ensure_browser_session(ctx, require_verified_session=True)
+
+ assert result is not None and result["ok"] is False
+ assert result["probe_timed_out"] is True
+ assert ctx.browser_session_id == "bs_live"
+
+ @pytest.mark.asyncio
+ async def test_a_session_the_escalation_proves_gone_is_replaced_exactly_once(
+ self, monkeypatch: pytest.MonkeyPatch
+ ) -> None:
+ manager = _install_dispatch_stack(monkeypatch, _SharedSessionLookup(ConnectionError("pool exhausted"), None))
+ escalated = _count_escalations(monkeypatch)
+
+ ctx = _make_ctx()
+ ctx.browser_session_id = "bs_gone"
+
+ assert await ensure_browser_session(ctx, require_verified_session=True) is None
+ assert ctx.browser_session_id == "bs_created"
+ assert escalated == ["bs_gone"]
+ manager.create_session.assert_awaited_once()
+
+ @pytest.mark.asyncio
+ async def test_the_same_session_gets_the_same_answer_every_time(self, monkeypatch: pytest.MonkeyPatch) -> None:
+ _install_dispatch_stack(
+ monkeypatch,
+ _SharedSessionLookup(
+ ConnectionError("pool exhausted"),
+ ConnectionError("still down"),
+ ConnectionError("pool exhausted"),
+ ConnectionError("still down"),
+ ),
+ )
+ escalated = _count_escalations(monkeypatch)
+
+ ctx = _make_ctx()
+ ctx.browser_session_id = "bs_live"
+
+ first = await ensure_browser_session(ctx, require_verified_session=True)
+ second = await ensure_browser_session(ctx, require_verified_session=True)
+
+ assert first == second
+ assert escalated == ["bs_live", "bs_live"]
+ assert ctx.browser_session_id == "bs_live"
diff --git a/tests/unit/test_copilot_scout_act_observe.py b/tests/unit/test_copilot_scout_act_observe.py
index 781a50851..c53fe06b0 100644
--- a/tests/unit/test_copilot_scout_act_observe.py
+++ b/tests/unit/test_copilot_scout_act_observe.py
@@ -396,6 +396,15 @@ class TestActObserveSuccess:
assert has_bounded_page_schema(evidence)
assert evidence["forms"][0]["fields"][0]["label"] == "NPI number"
+ @pytest.mark.asyncio
+ async def test_click_issues_one_post_action_packet_and_no_recapture(self) -> None:
+ ctx = _ctx(server=_server_returning(_bounded_extractor_payload()))
+
+ await _run_click(ctx)
+
+ assert ctx.discovery_mcp_server.call_internal_tool.await_count == 1
+ assert ctx.last_scout_act_observe_recapture_attempted is False
+
@pytest.mark.asyncio
async def test_pending_marker_cleared_and_result_carries_summary(self) -> None:
ctx = _ctx(server=_server_returning(_bounded_extractor_payload()))
@@ -410,15 +419,18 @@ class TestActObserveSuccess:
assert page["forms"] == [
{
"field_count": 2,
- "fields": ["NPI number", "State"],
- "submit_controls": ["Search"],
+ "fields": [
+ {"text": "NPI number", "selector": "#npi"},
+ {"text": "State", "selector": "#state"},
+ ],
+ "submit_controls": [{"text": "Search", "selector": "#go"}],
}
]
assert page["navigation_target_count"] == 1
- assert page["navigation_targets"] == ["Provider details"]
+ assert [target["text"] for target in page["navigation_targets"]] == ["Provider details"]
assert page["result_container_count"] == 1
assert page["challenge_detected"] is False
- assert page["modal_dismiss_controls"] == ["Accept"]
+ assert [control["text"] for control in page["modal_dismiss_controls"]] == ["Accept"]
assert len(json.dumps(result)) <= _SCOUT_RESULT_CHAR_CAP
@pytest.mark.asyncio
@@ -593,7 +605,9 @@ class TestActObserveSuccess:
assert any(control.get("selector") == "button.primary" for control in parsed_controls)
model_facing_result: dict[str, Any] = {"ok": True, "data": {}}
- scouting_module._attach_scout_page_summary(model_facing_result, parsed)
+ scouting_module._attach_scout_page_summary(
+ SimpleNamespace(codeblock_redaction_parameters={}), model_facing_result, parsed
+ )
assert model_facing_result["data"]["page"]["disclosure_controls"] == [
{
@@ -769,6 +783,9 @@ class TestActObserveDegrade:
assert ctx.flow_evidence[0]["had_bounded_schema"] is True
assert ctx.flow_evidence[0]["evidence"]["forms"][0]["fields"][0]["label"] == "NPI number"
assert not hasattr(ctx, "latest_recorded_build_test_outcome")
+ assert ctx.discovery_mcp_server.call_internal_tool.await_count == 2
+ assert ctx.last_scout_act_observe_recapture_attempted is True
+ assert ctx.last_scout_act_observe_recapture_result == "attached"
@pytest.mark.asyncio
async def test_persistent_post_interaction_hollow_records_build_test_outcome(self) -> None:
diff --git a/tests/unit/test_copilot_streaming_adapter.py b/tests/unit/test_copilot_streaming_adapter.py
index 4a5156965..1fcd4f86f 100644
--- a/tests/unit/test_copilot_streaming_adapter.py
+++ b/tests/unit/test_copilot_streaming_adapter.py
@@ -189,6 +189,71 @@ def _new_ctx() -> SimpleNamespace:
)
+async def test_tool_activity_entries_share_the_clock_read_of_their_sse_update() -> None:
+ result = MagicMock()
+ result.stream_events = lambda: _stream_events_from(
+ _tool_called_event("c1", "update_workflow"),
+ _tool_output_event("c1"),
+ )
+ result.cancel = MagicMock()
+
+ sent: list[Any] = []
+
+ async def _send(payload: Any) -> bool:
+ sent.append(payload)
+ return True
+
+ stream = MagicMock()
+ stream.is_disconnected = AsyncMock(return_value=False)
+ stream.send = _send
+ ctx = _new_ctx()
+
+ await stream_to_sse(result, stream, ctx)
+
+ live_by_id = {
+ f"tc-{p.tool_call_id}" if p.type == WorkflowCopilotStreamMessageType.TOOL_CALL else f"tr-{p.tool_call_id}": p
+ for p in sent
+ if p.type in (WorkflowCopilotStreamMessageType.TOOL_CALL, WorkflowCopilotStreamMessageType.TOOL_RESULT)
+ }
+ entries = ctx.narrator_state.design_activity
+ assert {e["id"] for e in entries} == {"tc-c1", "tr-c1"}
+ for entry in entries:
+ assert entry["timestamp"] == live_by_id[entry["id"]].timestamp.isoformat()
+
+
+async def test_goal_satisfied_flush_entry_shares_the_clock_read_of_its_sse_update() -> None:
+ sent: list[Any] = []
+
+ async def _send(payload: Any) -> bool:
+ sent.append(payload)
+ return True
+
+ stream = MagicMock()
+ stream.is_disconnected = AsyncMock(return_value=False)
+ stream.send = _send
+
+ narrator_state = NarratorState()
+ ctx = SimpleNamespace(
+ narrator_state=narrator_state,
+ in_flight_stream_tool_call=InFlightStreamToolCall(
+ call_id="c9", tool_name="update_workflow", iteration=2, display_label=None
+ ),
+ goal_satisfied_tool_name="update_workflow",
+ goal_satisfied_tool_output={"ok": True, "data": {"block_count": 1}},
+ last_artifact_health_blocker_reason=None,
+ completion_verification_result=None,
+ )
+
+ await flush_goal_satisfied_tool_result(stream, ctx) # type: ignore[arg-type]
+
+ entry = narrator_state.design_activity[0]
+ live = next(p for p in sent if p.type == WorkflowCopilotStreamMessageType.TOOL_RESULT)
+ assert entry["id"] == "tr-c9"
+ assert entry["timestamp"] == live.timestamp.isoformat()
+
+
@pytest.mark.asyncio
async def test_stream_to_sse_keeps_running_after_client_disconnect() -> None:
"""SKY-8986 regression: a dropped SSE client must NOT cancel the agent run.
@@ -931,6 +996,7 @@ class TestCodeRepairProgressStreaming:
narration_entries = [e for e in ctx.narrator_state.design_activity if e["kind"] == "narration"]
assert len(narration_entries) == 1
assert narration_entries[0]["text"] == _PROGRESS_TEXT
+ assert narration_entries[0]["timestamp"] == narrations[0].timestamp.isoformat()
assert all(e["kind"] != "tool_result" for e in ctx.narrator_state.design_activity)
# De-duplicated rejects still advance the narrator iteration (read by the run-outcome frame).
assert ctx.narrator_state.current_iteration == 2
diff --git a/tests/unit/test_copilot_typed_value_policy.py b/tests/unit/test_copilot_typed_value_policy.py
index fbc991547..9b799d994 100644
--- a/tests/unit/test_copilot_typed_value_policy.py
+++ b/tests/unit/test_copilot_typed_value_policy.py
@@ -15,6 +15,7 @@ async def test_type_text_uses_exact_registered_secret_fact_and_stashes_ordinary_
browser_session_id=None,
pending_scout_source_url=None,
pending_scout_input_value=None,
+ discovery_mcp_server=None,
block_authoring_policy=BlockAuthoringPolicy.CODE_ONLY_BROWSER,
secret_scrub_values=["known-vault-value"],
)
@@ -40,6 +41,7 @@ async def test_type_text_pre_hook_does_not_infer_secret_status_from_text_selecto
browser_session_id=None,
pending_scout_source_url=None,
pending_scout_input_value=None,
+ discovery_mcp_server=None,
block_authoring_policy=BlockAuthoringPolicy.CODE_ONLY_BROWSER,
workflow_persisted=True,
last_full_workflow_test_ok=True,
diff --git a/tests/unit/test_extract_actions_ceiling.py b/tests/unit/test_extract_actions_ceiling.py
index 050f8a883..402bf66c9 100644
--- a/tests/unit/test_extract_actions_ceiling.py
+++ b/tests/unit/test_extract_actions_ceiling.py
@@ -72,6 +72,52 @@ def test_enforce_ceiling_raises_when_unfixable() -> None:
)
+def test_extract_action_trims_element_tree_that_alone_exceeds_ceiling() -> None:
+ """SKY-14634: a page whose element tree alone blows the ceiling must still render.
+
+ Dropping every fallback key cannot rescue such a prompt, so before this the step died
+ with SkyvernContextWindowExceededError even though no provider had rejected anything.
+ """
+ from skyvern.forge.prompts import prompt_engine as engine_module
+ from skyvern.utils.prompt_engine import PROMPT_HARD_CEILING_TOKENS, load_prompt_with_elements
+ from skyvern.utils.token_counter import count_tokens
+
+ oversized_tree = "".join(f'<div id="{i}">lorem ipsum dolor sit amet</div>' for i in range(30_000))
+ assert count_tokens(oversized_tree) > PROMPT_HARD_CEILING_TOKENS
+
+ builder = _make_element_tree_builder()
+ builder.build_element_tree = MagicMock(return_value=oversized_tree)
+
+ rendered = load_prompt_with_elements(
+ element_tree_builder=builder,
+ prompt_engine=engine_module,
+ template_name="extract-action",
+ navigation_goal="Log in to the site",
+ navigation_payload_str='{"username": "UNIQUE_USER_DETAIL"}',
+ starting_url="https://example.test",
+ current_url="https://example.test",
+ data_extraction_goal=None,
+ action_history="UNIQUE_ACTION_HISTORY",
+ error_code_mapping_str=None,
+ local_datetime="2026-04-14T12:00:00",
+ verification_code_check=False,
+ complete_criterion=None,
+ terminate_criterion=None,
+ show_close_page_action=False,
+ open_tabs_context=None,
+ )
+
+ assert count_tokens(rendered) <= PROMPT_HARD_CEILING_TOKENS
+ # The tree is the bulk, so it is what gets trimmed — the fallback drops are not spent
+ # discarding the user's details and action history for a prompt they cannot rescue.
+ assert "UNIQUE_ACTION_HISTORY" in rendered
+ assert "UNIQUE_USER_DETAIL" in rendered
+ # The extraction cache hashes last_used_element_tree_html, so it has to track the
+ # trimmed tree the LLM actually saw rather than the full one.
+ assert builder.last_used_element_tree_html in rendered
+ assert len(builder.last_used_element_tree_html) < len(oversized_tree)
+
+
def test_extract_action_small_prompt_passes_through() -> None:
from skyvern.forge.prompts import prompt_engine as engine_module
from skyvern.utils.prompt_engine import PROMPT_HARD_CEILING_TOKENS, load_prompt_with_elements
diff --git a/tests/unit/test_forge_log_foreign_tracebacks.py b/tests/unit/test_forge_log_foreign_tracebacks.py
index 81341b6be..e1daf1d58 100644
--- a/tests/unit/test_forge_log_foreign_tracebacks.py
+++ b/tests/unit/test_forge_log_foreign_tracebacks.py
@@ -1,8 +1,12 @@
from __future__ import annotations
+import contextlib
+import gc
import io
import json
import logging
+import sys
+import threading
from collections.abc import Iterator
from decimal import Decimal
@@ -63,6 +67,83 @@ def test_foreign_stdlib_exception_renders_single_structured_line(json_stream: io
assert record["exception_hash"]
+class _FinalizerRaises:
+ """A __del__ that raises is routed to sys.unraisablehook, which prints straight to stderr."""
+
+ def __del__(self) -> None:
+ _raise_through_wrapper()
+
+
+def test_unraisable_traceback_becomes_one_structured_event(json_stream: io.StringIO) -> None:
+ """CPython's default hook prints one stderr line per frame, so a line-oriented collector bills
+ a single exception as ~30 error events, none of them carrying exception_hash to group on."""
+ # pytest's own unraisable/thread-exception plugins save and restore these hooks, so re-assert
+ # them from inside the test body rather than relying on the fixture's setup-phase install.
+ forge_log._install_interpreter_traceback_hooks()
+
+ doomed = _FinalizerRaises()
+ del doomed
+ gc.collect()
+
+ lines = json_stream.getvalue().strip().splitlines()
+ assert len(lines) == 1
+ record = json.loads(lines[0])
+
+ assert record["msg"].startswith("Exception ignored in interpreter callback")
+ assert record["error_type"] == "builtins.ValueError"
+ assert record["exception_hash"]
+ assert "ValueError: kaboom from an activity" in record["exception"]
+ assert "async_wrapper" in record["exception"]
+ # The finalized object is what the default hook puts on its first line. CPython moved its repr
+ # from `object` into `err_msg` between 3.11 and 3.14, so assert only that it survives somewhere.
+ assert "_FinalizerRaises" in f"{record.get('unraisable_err_msg', '')}{record.get('unraisable_object', '')}"
+
+
+def test_uncaught_thread_exception_becomes_one_structured_event(json_stream: io.StringIO) -> None:
+ forge_log._install_interpreter_traceback_hooks()
+
+ thread = threading.Thread(target=_raise_through_wrapper, name="background-poller")
+ thread.start()
+ thread.join()
+
+ lines = json_stream.getvalue().strip().splitlines()
+ assert len(lines) == 1
+ record = json.loads(lines[0])
+
+ assert record["thread_name"] == "background-poller"
+ assert record["error_type"] == "builtins.ValueError"
+ assert record["exception_hash"]
+ assert "async_wrapper" in record["exception"]
+
+
+def test_uncaught_main_thread_exception_becomes_one_structured_event(json_stream: io.StringIO) -> None:
+ try:
+ _raise_through_wrapper()
+ except ValueError:
+ sys.excepthook(*sys.exc_info())
+
+ lines = json_stream.getvalue().strip().splitlines()
+ assert len(lines) == 1
+ record = json.loads(lines[0])
+
+ assert record["error_type"] == "builtins.ValueError"
+ assert record["exception_hash"]
+
+
+def test_keyboard_interrupt_keeps_default_stderr_behaviour(json_stream: io.StringIO) -> None:
+ """Ctrl-C is a one-line traceback nobody groups on; turning it into an ERROR event would
+ make every interactive shutdown look like a failure."""
+ stderr = io.StringIO()
+ try:
+ raise KeyboardInterrupt
+ except KeyboardInterrupt:
+ with contextlib.redirect_stderr(stderr):
+ sys.excepthook(*sys.exc_info())
+
+ assert json_stream.getvalue() == ""
+ assert "KeyboardInterrupt" in stderr.getvalue()
+
+
def test_oversized_structured_payload_is_bounded_to_one_log_record(json_stream: io.StringIO) -> None:
structlog.get_logger("oversized-test").error(
"oversized_payload", payload="x" * 100_000, status="failed", error="payload rejected"
diff --git a/tests/unit/test_forge_log_uvicorn_levels.py b/tests/unit/test_forge_log_uvicorn_levels.py
index 87c5c320d..f5bdcd155 100644
--- a/tests/unit/test_forge_log_uvicorn_levels.py
+++ b/tests/unit/test_forge_log_uvicorn_levels.py
@@ -131,6 +131,15 @@ def test_uvicorn_run_configuration(module_path: str) -> None:
assert isinstance(loop_kwarg.value, ast.Constant) and loop_kwarg.value.value == "asyncio", (
f"{module_path} must select loop='asyncio' until MagicStack/uvloop#740 is released"
)
+ keep_alive_kwarg = next((kw for kw in node.keywords if kw.arg == "timeout_keep_alive"), None)
+ assert keep_alive_kwarg is not None, (
+ f"{module_path} must pass timeout_keep_alive= to uvicorn.run(); uvicorn's 5s default "
+ "sits below any load balancer idle timeout, which is AWS's documented 502 condition."
+ )
+ assert (
+ isinstance(keep_alive_kwarg.value, ast.Attribute)
+ and keep_alive_kwarg.value.attr == "UVICORN_TIMEOUT_KEEP_ALIVE"
+ ), f"{module_path} must source timeout_keep_alive from settings.UVICORN_TIMEOUT_KEEP_ALIVE"
for kw in node.keywords:
assert kw.arg != "log_level", (
f"{module_path} must not pass log_level= to uvicorn.run(); it triggers "
diff --git a/tests/unit/test_generate_cua_actions_visual_continuation.py b/tests/unit/test_generate_cua_actions_visual_continuation.py
index 08d0e3545..85c1f7099 100644
--- a/tests/unit/test_generate_cua_actions_visual_continuation.py
+++ b/tests/unit/test_generate_cua_actions_visual_continuation.py
@@ -64,7 +64,7 @@ async def _invoke_no_call_continuation(
step = make_step(now, task, step_id="cua-step", status=StepStatus.created, order=0, output=None)
previous_response = SimpleNamespace(id="resp_prev", output=[])
- scraped_page = SimpleNamespace(screenshots=[SCREENSHOT_BYTES])
+ scraped_page = SimpleNamespace(screenshots=[SCREENSHOT_BYTES], window_dimension=None)
create_mock = AsyncMock(return_value=SimpleNamespace(id="resp_new", output=[], usage=_fake_usage()))
monkeypatch.setattr(
@@ -115,6 +115,64 @@ async def test_no_computer_call_continuation_includes_answer_and_screenshot(
assert expected_data_url in image_urls
+async def _capture_cua_tools(
+ monkeypatch: pytest.MonkeyPatch, window_dimension: dict[str, int] | None
+) -> list[dict[str, Any]]:
+ """Drive _generate_cua_actions once and return the `tools` the OpenAI Responses call declared."""
+ agent = ForgeAgent()
+ now = datetime.now(UTC)
+ organization = make_organization(now)
+ task = make_task(now, organization)
+ step = make_step(now, task, step_id="cua-step", status=StepStatus.created, order=0, output=None)
+
+ computer_call = SimpleNamespace(
+ type="computer_call",
+ call_id="call_dim",
+ action=SimpleNamespace(type="scroll"),
+ pending_safety_checks=[],
+ )
+ previous_response = SimpleNamespace(id="resp_prev", output=[computer_call])
+ scraped_page = SimpleNamespace(screenshots=[SCREENSHOT_BYTES], window_dimension=window_dimension)
+
+ create_mock = AsyncMock(return_value=SimpleNamespace(id="resp_new", output=[], usage=_fake_usage()))
+ monkeypatch.setattr(
+ agent_module.app,
+ "OPENAI_CLIENT",
+ SimpleNamespace(responses=SimpleNamespace(create=create_mock)),
+ raising=False,
+ )
+ monkeypatch.setattr(
+ agent_module.app,
+ "DATABASE",
+ SimpleNamespace(tasks=SimpleNamespace(update_step=AsyncMock())),
+ raising=False,
+ )
+ monkeypatch.setattr(agent_module, "parse_cua_actions", AsyncMock(return_value=[]))
+
+ await agent._generate_cua_actions(
+ task=task, step=step, scraped_page=scraped_page, previous_response=previous_response
+ )
+ return create_mock.await_args.kwargs["tools"]
+
+
+async def test_cua_tool_declares_live_viewport_dimensions(monkeypatch: pytest.MonkeyPatch) -> None:
+ """The computer tool's display size must be the live page viewport, so returned coordinates
+ map into the real (possibly-shrunk) page rather than a hardcoded 1920x1080."""
+ tools = await _capture_cua_tools(monkeypatch, {"width": 1440, "height": 810})
+
+ assert tools[0]["display_width"] == 1440
+ assert tools[0]["display_height"] == 810
+
+
+async def test_cua_tool_falls_back_to_settings_without_a_live_viewport(monkeypatch: pytest.MonkeyPatch) -> None:
+ tools = await _capture_cua_tools(monkeypatch, None)
+
+ assert tools[0]["display_width"] == agent_module.settings.BROWSER_WIDTH
+ assert tools[0]["display_height"] == agent_module.settings.BROWSER_HEIGHT
+
+
@pytest.mark.asyncio
async def test_truthy_answer_appends_execute_directive(monkeypatch: pytest.MonkeyPatch) -> None:
create_mock = await _invoke_no_call_continuation(monkeypatch)
@@ -152,7 +210,7 @@ async def test_computer_call_output_continuation_shape_unchanged(monkeypatch: py
pending_safety_checks=[],
)
previous_response = SimpleNamespace(id="resp_prev", output=[computer_call])
- scraped_page = SimpleNamespace(screenshots=[SCREENSHOT_BYTES])
+ scraped_page = SimpleNamespace(screenshots=[SCREENSHOT_BYTES], window_dimension=None)
create_mock = AsyncMock(return_value=SimpleNamespace(id="resp_new", output=[], usage=_fake_usage()))
monkeypatch.setattr(
diff --git a/tests/unit/test_loop_block_output_scoping.py b/tests/unit/test_loop_block_output_scoping.py
index 154aa19f9..265763658 100644
--- a/tests/unit/test_loop_block_output_scoping.py
+++ b/tests/unit/test_loop_block_output_scoping.py
@@ -470,3 +470,22 @@ def test_traced_decorator_owns_execute_safe_not_the_invalidation_helper() -> Non
# wrapper sets __wrapped__ via functools.wraps.
assert Block.execute_safe.__wrapped__.__qualname__ == "Block.execute_safe"
assert not hasattr(Block._invalidate_stale_output_on_failure, "__wrapped__")
+
+
+async def test_loop_iteration_reregistration_is_not_a_warning(monkeypatch: pytest.MonkeyPatch) -> None:
+ # Re-registering a block's output on the next loop iteration is the designed path (every
+ # iteration overwrites the last), so it must not compete with real warnings in the log stream.
+ from skyvern.forge.sdk.workflow import context_manager as context_manager_module
+
+ log = MagicMock()
+ monkeypatch.setattr(context_manager_module, "LOG", log)
+ ctx = _make_ctx()
+ param = _make_output_parameter("extract_details_output")
+
+ await ctx.register_output_parameter_value_post_execution(param, {"quote": "iteration-1"})
+ await ctx.register_output_parameter_value_post_execution(param, {"quote": "iteration-2"})
+
+ assert ctx.values["extract_details_output"] == {"quote": "iteration-2"}
+ log.warning.assert_not_called()
+ assert log.debug.call_count >= 1
diff --git a/tests/unit/test_mcp_browser_tools.py b/tests/unit/test_mcp_browser_tools.py
index 17bc8fed7..f20950906 100644
--- a/tests/unit/test_mcp_browser_tools.py
+++ b/tests/unit/test_mcp_browser_tools.py
@@ -10,7 +10,9 @@ from unittest.mock import AsyncMock, MagicMock, Mock, call
import pytest
-from skyvern.cli.core import browser_ops, session_manager
+from skyvern.cli.core import browser_ops
+from skyvern.cli.core import result as result_mod
+from skyvern.cli.core import session_manager
from skyvern.cli.core.browser_ops import (
CustomSelectClassifyError,
CustomSelectMatchError,
@@ -1415,6 +1417,21 @@ async def test_skyvern_type_ai_error_uses_exception_type_for_empty_message(
assert result["error"]["details"] == {"exception_type": "SilentFailure"}
+async def test_select_option_reports_the_browser_attach_when_the_custom_path_falls_back(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ _action_page(monkeypatch, select_option=AsyncMock(return_value="us"))
+ result_mod._pending_attach.set(700)
+ try:
+ result = await mcp_browser.skyvern_select_option(selector="#country", value="us")
+ finally:
+ result_mod._pending_attach.set(None)
+
+ assert result["ok"] is True
+ assert result["timing_ms"].get("attach") == 700
+
+
@pytest.mark.asyncio
async def test_skyvern_select_option_selector_is_resilient_by_default(monkeypatch: pytest.MonkeyPatch) -> None:
select = AsyncMock(return_value="us")
diff --git a/tests/unit/test_mcp_session_lifecycle.py b/tests/unit/test_mcp_session_lifecycle.py
index b710b0978..50634fd4c 100644
--- a/tests/unit/test_mcp_session_lifecycle.py
+++ b/tests/unit/test_mcp_session_lifecycle.py
@@ -1,11 +1,14 @@
from __future__ import annotations
+import asyncio
+from collections.abc import Iterator
from types import SimpleNamespace
from typing import cast
from unittest.mock import AsyncMock, MagicMock
import httpx
import pytest
+from fastmcp.server.middleware import MiddlewareContext
from skyvern.cli.core import client as client_mod
from skyvern.cli.core import result as result_mod
@@ -13,6 +16,7 @@ from skyvern.cli.core import session_manager, session_ops
from skyvern.cli.core.result import BrowserContext
from skyvern.cli.core.session_ops import SessionCloseResult, coerce_proxy_location
from skyvern.cli.mcp_tools import session as mcp_session
+from skyvern.cli.mcp_tools.telemetry import MCPTelemetryMiddleware
from skyvern.client.types.extensions import Extensions
from skyvern.constants import SKYVERN_MCP_USER_AGENT
from skyvern.schemas.runs import GeoTarget, ProxyLocation
@@ -1704,3 +1708,114 @@ async def test_session_create_persists_active_api_key_hash_in_session_state(
)
assert current.api_key_hash == session_manager._api_key_hash("sk_key_create")
assert current.api_key_hash != "sk_key_create"
+
+
+def _attach_clock(monkeypatch: pytest.MonkeyPatch) -> Iterator[list[float]]:
+ now = [100.0]
+ monkeypatch.setattr(result_mod, "time", SimpleNamespace(perf_counter=lambda: now[0]))
+ result_mod._pending_attach.set(None)
+ yield now
+ result_mod._pending_attach.set(None)
+
+
+def _reusable_cloud_session(monkeypatch: pytest.MonkeyPatch, clock: list[float], attach_seconds: float) -> None:
+ session_manager.set_current_session(
+ session_manager.SessionState(
+ browser=MagicMock(),
+ context=BrowserContext(mode="cloud_session", session_id="pbs_123"),
+ api_key_hash=session_manager._api_key_hash(client_mod.get_active_api_key()),
+ )
+ )
+
+ def _get_skyvern() -> MagicMock:
+ clock[0] += attach_seconds
+ return MagicMock()
+
+ monkeypatch.setattr(session_manager, "get_skyvern", _get_skyvern)
+
+
+async def test_browser_attaches_are_named_on_the_tool_that_opens_its_timer_after_them(
+ monkeypatch: pytest.MonkeyPatch, _attach_clock: list[float]
+) -> None:
+ _reusable_cloud_session(monkeypatch, _attach_clock, 1.5)
+
+ await session_manager.resolve_browser(session_id="pbs_123")
+ await session_manager.resolve_browser(session_id="pbs_123")
+ with result_mod.Timer() as timer:
+ _attach_clock[0] += 0.5
+
+ assert timer.timing_ms == {"attach": 3000, "total": 500}
+
+
+async def test_an_attach_resolved_in_a_child_task_is_not_charged_to_the_parents_timer(
+ monkeypatch: pytest.MonkeyPatch, _attach_clock: list[float]
+) -> None:
+ _reusable_cloud_session(monkeypatch, _attach_clock, 1.5)
+
+ await asyncio.create_task(session_manager.resolve_browser(session_id="pbs_123"))
+ with result_mod.Timer() as timer:
+ _attach_clock[0] += 0.5
+
+ assert timer.timing_ms == {"total": 500}
+
+
+async def test_an_attach_whose_tool_never_opened_a_timer_is_dropped_before_the_next_tool_runs(
+ monkeypatch: pytest.MonkeyPatch, _attach_clock: list[float]
+) -> None:
+ _reusable_cloud_session(monkeypatch, _attach_clock, 1.5)
+ marks: dict[str, int] = {}
+
+ async def _next_tool(_context: MiddlewareContext[object]) -> object:
+ with result_mod.Timer() as timer:
+ _attach_clock[0] += 0.5
+ marks.update(timer.timing_ms)
+ return MagicMock(content=[], structured_content=None)
+
+ await session_manager.resolve_browser(session_id="pbs_123")
+ _attach_clock[0] += 0.01
+ await MCPTelemetryMiddleware().on_call_tool(
+ MiddlewareContext(message=SimpleNamespace(name="skyvern_click"), fastmcp_context=None),
+ _next_tool,
+ )
+
+ assert marks == {"total": 500}
+
+
+def test_a_tool_that_attached_no_browser_reports_only_the_time_it_spent(_attach_clock: list[float]) -> None:
+ with result_mod.Timer() as timer:
+ _attach_clock[0] += 0.5
+
+ assert timer.timing_ms == {"total": 500}
+
+
+async def test_an_attach_inside_a_timer_is_not_charged_again_to_the_next_tool(
+ monkeypatch: pytest.MonkeyPatch, _attach_clock: list[float]
+) -> None:
+ _reusable_cloud_session(monkeypatch, _attach_clock, 1.5)
+
+ with result_mod.Timer() as inside:
+ await session_manager.resolve_browser(session_id="pbs_123")
+ with result_mod.Timer() as next_tool:
+ _attach_clock[0] += 0.5
+
+ assert inside.timing_ms == {"total": 1500}
+ assert next_tool.timing_ms == {"total": 500}
+
+
+async def test_an_attach_is_charged_however_long_the_tool_takes_to_open_its_timer(
+ monkeypatch: pytest.MonkeyPatch, _attach_clock: list[float]
+) -> None:
+ _reusable_cloud_session(monkeypatch, _attach_clock, 1.5)
+
+ await session_manager.resolve_browser(session_id="pbs_123")
+ _attach_clock[0] += 0.2
+ with result_mod.Timer() as timer:
+ _attach_clock[0] += 0.5
+
+ assert timer.timing_ms == {"attach": 1500, "total": 500}
diff --git a/tests/unit/test_multi_field_totp.py b/tests/unit/test_multi_field_totp.py
index 396424644..84a8325b0 100644
--- a/tests/unit/test_multi_field_totp.py
+++ b/tests/unit/test_multi_field_totp.py
@@ -687,3 +687,79 @@ class TestGetTotpDigitBasic:
digit_index=idx,
)
assert result == expected, f"Expected digit {expected} at index {idx}, got {result}"
+
+
+class TestMultiFieldTotpAbsoluteIndexExecution:
+ """Execution-path coverage for the multi-field TOTP absolute action-index contract.
+
+ ``ForgeAgent._is_multi_field_totp_sequence`` decides, per INPUT_TEXT action, whether the runtime
+ stamps ``totp_timing_info`` with the action's ABSOLUTE index in the whole batch, and
+ ``_handle_multi_field_totp_sequence`` only seeds the TOTP cache when that index is 0. These tests
+ prove the accepted ``[digits..., CLICK submit]`` plan reaches execution with digit indexes 0..N-1
+ and the handler generates/caches/reuses, while a leading action is not treated as a sequence."""
+
+ @staticmethod
+ def _digit(text: str) -> SimpleNamespace:
+ return SimpleNamespace(action_type=ActionType.INPUT_TEXT, text=text)
+
+ @staticmethod
+ def _click() -> SimpleNamespace:
+ return SimpleNamespace(action_type=ActionType.CLICK, text=None)
+
+ def _stamped_digit_indexes(self, actions: list) -> list[int]:
+ """Replicate the agent execution loop: stamp INPUT_TEXT actions with their absolute index only
+ when the batch is a multi-field TOTP sequence."""
+ from skyvern.forge.agent import ForgeAgent
+
+ agent = ForgeAgent.__new__(ForgeAgent)
+ if not agent._is_multi_field_totp_sequence(actions):
+ return []
+ return [action_idx for action_idx, action in enumerate(actions) if action.action_type == ActionType.INPUT_TEXT]
+
+ def test_digits_then_submit_click_reaches_execution_at_indexes_0_to_n(self) -> None:
+ actions = [self._digit(str(d)) for d in range(1, 7)] + [self._click()]
+ assert self._stamped_digit_indexes(actions) == [0, 1, 2, 3, 4, 5]
+
+ def test_leading_action_is_not_a_multi_field_sequence(self) -> None:
+ actions = [self._click()] + [self._digit(str(d)) for d in range(1, 7)]
+ assert self._stamped_digit_indexes(actions) == []
+
+ @pytest.mark.asyncio
+ async def test_stamped_indexes_drive_generate_then_reuse(self) -> None:
+ """The 0..N-1 indexes the accepted plan produces let the handler generate+cache at the first
+ digit and reuse the cache for a later digit without regenerating. Asserts cache is populated
+ (not its plaintext value) so no code/secret is exposed."""
+ actions = [self._digit(str(d)) for d in range(1, 7)] + [self._click()]
+ indexes = self._stamped_digit_indexes(actions)
+ assert indexes[0] == 0 and indexes[-1] == len(indexes) - 1
+
+ context = SimpleNamespace(totp_codes={})
+ fake_totp = _FakeTotp()
+ task = SimpleNamespace(task_id="task_exec")
+ cache_key = f"{task.task_id}_totp_cache"
+
+ with (
+ patch("skyvern.webeye.actions.handler.skyvern_context.ensure_context", return_value=context),
+ patch("skyvern.webeye.actions.handler.parse_totp_config", return_value=fake_totp),
+ patch("skyvern.webeye.actions.handler.time.time", return_value=44),
+ ):
+ first = await _handle_multi_field_totp_sequence(
+ {"action_index": indexes[0], "totp_secret": "otpauth://totp/example?secret=abc"},
+ task,
+ )
+ assert first is None
+ assert context.totp_codes.get(cache_key)
+ generated_at_first = list(fake_totp.at_values)
+
+ with (
+ patch("skyvern.webeye.actions.handler.skyvern_context.ensure_context", return_value=context),
+ patch("skyvern.webeye.actions.handler.parse_totp_config", return_value=fake_totp),
+ patch("skyvern.webeye.actions.handler.time.time", return_value=44),
+ patch("skyvern.webeye.actions.handler._totp_window_sleep", new_callable=AsyncMock),
+ ):
+ later = await _handle_multi_field_totp_sequence(
+ {"action_index": indexes[-1], "totp_secret": "otpauth://totp/example?secret=abc"},
+ task,
+ )
+ assert later is None
+ assert fake_totp.at_values == generated_at_first
diff --git a/tests/unit/test_org_auth_service.py b/tests/unit/test_org_auth_service.py
index d894d7dfb..2630b9a5a 100644
--- a/tests/unit/test_org_auth_service.py
+++ b/tests/unit/test_org_auth_service.py
@@ -6,7 +6,7 @@ from types import SimpleNamespace
import jwt
import pytest
-from fastapi import FastAPI, HTTPException
+from fastapi import Depends, FastAPI, HTTPException
from fastapi.testclient import TestClient
from freezegun import freeze_time
@@ -947,6 +947,57 @@ async def test_get_current_org_forwards_optional_attribution_header_to_authentic
assert calls == [("clerk-token", "encoded-attribution")]
+def test_get_current_org_with_authentication_forwards_optional_attribution_header(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ organization = _make_org("org-attribution-authentication")
+ calls: list[tuple[str, str | None]] = []
+
+ async def authentication_callback(
+ token: str,
+ attribution_header: str | None = None,
+ ) -> Organization:
+ calls.append((token, attribution_header))
+ return organization
+
+ monkeypatch.setattr(
+ org_auth_service,
+ "app",
+ SimpleNamespace(authentication_function=authentication_callback),
+ )
+
+ fastapi_app = FastAPI()
+
+ @fastapi_app.get("/organization")
+ async def get_organization(
+ current_organization: Organization = Depends(org_auth_service.get_current_org_with_authentication),
+ ) -> Organization:
+ return current_organization
+
+ parameters = fastapi_app.openapi()["paths"]["/organization"]["get"]["parameters"]
+ assert all(parameter["name"] != org_auth_service.POSTHOG_ATTRIBUTION_HEADER for parameter in parameters)
+
+ with TestClient(fastapi_app) as client:
+ attributed_response = client.get(
+ "/organization",
+ headers={
+ "Authorization": "Bearer clerk-token",
+ org_auth_service.POSTHOG_ATTRIBUTION_HEADER: "encoded-attribution",
+ },
+ )
+ un_attributed_response = client.get(
+ "/organization",
+ headers={"Authorization": "Bearer clerk-token"},
+ )
+
+ assert attributed_response.status_code == 200
+ assert un_attributed_response.status_code == 200
+ assert calls == [
+ ("clerk-token", "encoded-attribution"),
+ ("clerk-token", None),
+ ]
+
+
@pytest.mark.asyncio
async def test_authenticate_helper_requires_attribution_aware_callback(
monkeypatch: pytest.MonkeyPatch,
diff --git a/tests/unit/test_organization_slug.py b/tests/unit/test_organization_slug.py
new file mode 100644
index 000000000..afb38aa0b
--- /dev/null
+++ b/tests/unit/test_organization_slug.py
@@ -0,0 +1,289 @@
+from __future__ import annotations
+
+from types import SimpleNamespace
+from unittest.mock import AsyncMock, MagicMock
+
+import pytest
+from fastapi import HTTPException
+from pydantic import ValidationError
+from sqlalchemy.exc import IntegrityError
+
+from skyvern.forge.sdk.schemas.organizations import OrganizationUpdate
+from skyvern.utils.organization_slug import (
+ build_org_slug_candidate,
+ derive_org_slug,
+ get_or_derive_org_slug,
+ iter_org_slug_candidates,
+)
+
+
+def _integrity_error(constraint_name: str) -> IntegrityError:
+ return IntegrityError(
+ "UPDATE organizations",
+ {},
+ Exception(f'duplicate key value violates unique constraint "{constraint_name}"'),
+ )
+
+
+ ("organization_name", "organization_id", "expected"),
+ [
+ ("Acme CORP", "o_unused", "acme-corp"),
+ ("Straße Labs", "o_unused", "strasse-labs"),
+ ("___Acme!!! -- Corp___", "o_unused", "acme-corp"),
+ ("Acme.Inc", "o_unused", "acme-inc"),
+ ("AcmeInc", "o_unused", "acmeinc"),
+ ("Acme💥Inc", "o_unused", "acme-inc"),
+ ("abcdefghijklmnopqrstuvwxyz", "o_unused", "abcdefghijklmnopqrst"),
+ ("!!!", "o_1234567890ABCDEFGHIJKL", "34567890abcdefghijkl"),
+ ],
+)
+def test_derive_org_slug_rules(organization_name: str, organization_id: str, expected: str) -> None:
+ assert derive_org_slug(organization_name, organization_id) == expected
+
+
+def test_invalid_character_mapping_keeps_acme_dot_inc_distinct_from_acme_inc() -> None:
+ assert derive_org_slug("Acme.Inc", "o_unused") == "acme-inc"
+ assert derive_org_slug("AcmeInc", "o_unused") == "acmeinc"
+
+
+def test_collision_candidates_preserve_max_length_and_include_org_id_tail() -> None:
+ base_slug = "abcdefghijklmnopqrst"
+ organization_id = "o_1234567890abcdef"
+
+ assert build_org_slug_candidate(base_slug, 1) == base_slug
+ assert build_org_slug_candidate(base_slug, 2) == "abcdefghijklmnopqr-2"
+ assert list(iter_org_slug_candidates(base_slug, organization_id)) == [
+ base_slug,
+ "abcdefghijklmnopqr-2",
+ "abcdefghijklmnopqr-3",
+ "abcdefghijklmnopqr-4",
+ "abcdefghijklmnopqr-5",
+ "abcdefghijklmnopqr-6",
+ "o-1234567890abcdef",
+ ]
+ assert list(iter_org_slug_candidates("", organization_id)) == ["o-1234567890abcdef"]
+ assert list(iter_org_slug_candidates("o-123", "o_123")) == [
+ "o-123",
+ "o-123-2",
+ "o-123-3",
+ "o-123-4",
+ "o-123-5",
+ "o-123-6",
+ ]
+ assert list(iter_org_slug_candidates("o", "o_2")) == [
+ "o",
+ "o-2",
+ "o-3",
+ "o-4",
+ "o-5",
+ "o-6",
+ ]
+
+
+async def test_get_or_derive_org_slug_retries_slug_unique_collision(monkeypatch: pytest.MonkeyPatch) -> None:
+ from skyvern.forge import app
+
+ organization = SimpleNamespace(
+ organization_id="o_123",
+ organization_name="Acme",
+ slug=None,
+ )
+ set_slug_if_missing = AsyncMock(
+ side_effect=[
+ _integrity_error("uq_organizations_slug"),
+ SimpleNamespace(slug="acme-2"),
+ ]
+ )
+ monkeypatch.setattr(
+ app,
+ "DATABASE",
+ SimpleNamespace(organizations=SimpleNamespace(set_organization_slug_if_missing=set_slug_if_missing)),
+ )
+
+ assert await get_or_derive_org_slug(organization) == "acme-2"
+ assert set_slug_if_missing.await_args_list[0].kwargs == {
+ "organization_id": "o_123",
+ "slug": "acme",
+ }
+ assert set_slug_if_missing.await_args_list[1].kwargs == {
+ "organization_id": "o_123",
+ "slug": "acme-2",
+ }
+
+
+async def test_get_or_derive_org_slug_uses_org_id_tail_after_five_suffix_collisions(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ from skyvern.forge import app
+
+ organization = SimpleNamespace(
+ organization_id="o_1234567890abcdef",
+ organization_name="Acme",
+ slug=None,
+ )
+ set_slug_if_missing = AsyncMock(
+ side_effect=[
+ *[_integrity_error("uq_organizations_slug") for _ in range(6)],
+ SimpleNamespace(slug="o-1234567890abcdef"),
+ ]
+ )
+ monkeypatch.setattr(
+ app,
+ "DATABASE",
+ SimpleNamespace(organizations=SimpleNamespace(set_organization_slug_if_missing=set_slug_if_missing)),
+ )
+
+ assert await get_or_derive_org_slug(organization) == "o-1234567890abcdef"
+ assert [call.kwargs["slug"] for call in set_slug_if_missing.await_args_list] == [
+ "acme",
+ "acme-2",
+ "acme-3",
+ "acme-4",
+ "acme-5",
+ "acme-6",
+ "o-1234567890abcdef",
+ ]
+
+
+async def test_get_or_derive_org_slug_preserves_concurrent_winner(monkeypatch: pytest.MonkeyPatch) -> None:
+ from skyvern.forge import app
+
+ organization = SimpleNamespace(
+ organization_id="o_123",
+ organization_name="Acme",
+ slug=None,
+ )
+ set_slug_if_missing = AsyncMock(return_value=SimpleNamespace(slug="newer-clerk-slug"))
+ monkeypatch.setattr(
+ app,
+ "DATABASE",
+ SimpleNamespace(organizations=SimpleNamespace(set_organization_slug_if_missing=set_slug_if_missing)),
+ )
+
+ assert await get_or_derive_org_slug(organization) == "newer-clerk-slug"
+ set_slug_if_missing.assert_awaited_once_with(organization_id="o_123", slug="acme")
+
+
+async def test_get_or_derive_org_slug_does_not_retry_other_integrity_errors(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ from skyvern.forge import app
+
+ organization = SimpleNamespace(
+ organization_id="o_123",
+ organization_name="Acme",
+ slug=None,
+ )
+ error = _integrity_error("uq_organizations_domain")
+ set_slug_if_missing = AsyncMock(side_effect=error)
+ monkeypatch.setattr(
+ app,
+ "DATABASE",
+ SimpleNamespace(organizations=SimpleNamespace(set_organization_slug_if_missing=set_slug_if_missing)),
+ )
+
+ with pytest.raises(IntegrityError) as exc_info:
+ await get_or_derive_org_slug(organization)
+
+ assert exc_info.value is error
+ set_slug_if_missing.assert_awaited_once()
+
+
[email protected]("slug", ["a", "acme-2", "abcdefghijklmnopqrst", None])
+def test_organization_update_accepts_valid_slug(slug: str | None) -> None:
+ update = OrganizationUpdate(slug=slug)
+
+ assert update.slug == slug
+ assert "slug" in update.model_fields_set
+
+
+ "slug",
+ ["", "Acme", "acme_org", "acme.org", "acme org", "abcdefghijklmnopqrstu"],
+)
+def test_organization_update_rejects_invalid_slug(slug: str) -> None:
+ with pytest.raises(ValidationError, match="slug must match"):
+ OrganizationUpdate(slug=slug)
+
+
+ "error",
+ [
+ _integrity_error("uq_organizations_slug"),
+ IntegrityError("UPDATE organizations", {}, Exception("UNIQUE constraint failed: organizations.slug")),
+ ],
+ ids=["postgresql", "sqlite"],
+)
+async def test_update_organization_returns_conflict_for_duplicate_slug(
+ monkeypatch: pytest.MonkeyPatch,
+ error: IntegrityError,
+) -> None:
+ from skyvern.forge.sdk.routes import agent_protocol
+
+ update_organization = AsyncMock(side_effect=error)
+ monkeypatch.setattr(
+ agent_protocol.app,
+ "DATABASE",
+ SimpleNamespace(organizations=SimpleNamespace(update_organization=update_organization)),
+ )
+
+ with pytest.raises(HTTPException) as exc_info:
+ await agent_protocol.update_organization(
+ OrganizationUpdate(slug="taken"),
+ current_org=SimpleNamespace(organization_id="o_123", webhook_callback_url=None),
+ )
+
+ assert exc_info.value.status_code == 409
+ assert exc_info.value.detail == "Organization slug is already in use."
+
+
+async def test_update_organization_reraises_unrelated_integrity_error(monkeypatch: pytest.MonkeyPatch) -> None:
+ from skyvern.forge.sdk.routes import agent_protocol
+
+ error = _integrity_error("uq_organizations_domain")
+ update_organization = AsyncMock(side_effect=error)
+ monkeypatch.setattr(
+ agent_protocol.app,
+ "DATABASE",
+ SimpleNamespace(organizations=SimpleNamespace(update_organization=update_organization)),
+ )
+
+ with pytest.raises(IntegrityError) as exc_info:
+ await agent_protocol.update_organization(
+ OrganizationUpdate(slug="available"),
+ current_org=SimpleNamespace(organization_id="o_123", webhook_callback_url=None),
+ )
+
+ assert exc_info.value is error
+
+
+async def test_update_organization_rejects_explicit_slug_clear(monkeypatch: pytest.MonkeyPatch) -> None:
+ from skyvern.forge.sdk.routes import agent_protocol
+
+ update_organization = AsyncMock()
+ invalidate_cached_org = MagicMock()
+ monkeypatch.setattr(
+ agent_protocol.app,
+ "DATABASE",
+ SimpleNamespace(organizations=SimpleNamespace(update_organization=update_organization)),
+ )
+ monkeypatch.setattr(agent_protocol.org_auth_service, "invalidate_cached_org", invalidate_cached_org)
+
+ with pytest.raises(HTTPException) as exc_info:
+ await agent_protocol.update_organization(
+ OrganizationUpdate(slug=None),
+ current_org=SimpleNamespace(organization_id="o_123", webhook_callback_url=None),
+ )
+
+ assert exc_info.value.status_code == 400
+ assert exc_info.value.detail == "Organization slug cannot be cleared."
+ update_organization.assert_not_awaited()
+ invalidate_cached_org.assert_not_called()
diff --git a/tests/unit/test_otp_service.py b/tests/unit/test_otp_service.py
index 9a688b028..6f441ab63 100644
--- a/tests/unit/test_otp_service.py
+++ b/tests/unit/test_otp_service.py
@@ -2,7 +2,7 @@
from __future__ import annotations
-from datetime import datetime, timedelta
+from datetime import datetime, timedelta, timezone
from types import SimpleNamespace
from unittest.mock import AsyncMock, MagicMock, patch
@@ -14,6 +14,12 @@ from skyvern.exceptions import FailedToGetTOTPVerificationCode, NoTOTPVerificati
from skyvern.forge.sdk.core import skyvern_context
from skyvern.forge.sdk.core.skyvern_context import SkyvernContext
from skyvern.forge.sdk.schemas.totp_codes import OTPType
+from skyvern.forge.sdk.workflow.context_manager import _CREDENTIAL_PARAMETER_TYPES
+from skyvern.forge.sdk.workflow.models.parameter import (
+ CredentialParameter,
+ WorkflowParameter,
+ WorkflowParameterType,
+)
from skyvern.services import otp_service
from skyvern.services.otp_service import (
OTPValue,
@@ -178,6 +184,49 @@ class TestResolveOtpValuePlaceholderFallthrough:
credential.assert_called_once_with("wr_test")
poll.assert_not_called()
+ @pytest.mark.asyncio
+ async def test_ordinary_input_dict_falls_through_to_polling(self, monkeypatch: pytest.MonkeyPatch) -> None:
+ """An ordinary run input dict with a placeholder `totp` is not a credential.
+
+ With the real credential lookup running against a realistic registration shape,
+ the ordinary dict must fall through to polling (awaited once) rather than being
+ resolved as a credential-backed TOTP and short-circuiting resolution.
+ """
+ monkeypatch.setattr(pyotp.TOTP, "now", lambda _self: "111111")
+ fake_context = _FakeWorkflowRunContext(
+ values={"user_input": {"totp": "tot_x"}},
+ secrets={"tot_x_value": _VALID_TOTP_SEED},
+ parameters={"user_input": _ordinary_workflow_parameter("user_input")},
+ )
+ fake_app = SimpleNamespace(
+ WORKFLOW_CONTEXT_MANAGER=SimpleNamespace(
+ get_workflow_run_context=lambda _wr_id: fake_context,
+ has_workflow_run_context=lambda _wr_id: True,
+ ),
+ DATABASE=SimpleNamespace(
+ workflow_runs=SimpleNamespace(get_workflow_run=AsyncMock(return_value=None)),
+ ),
+ )
+ monkeypatch.setattr(otp_service, "app", fake_app)
+
+ task = SimpleNamespace(
+ task_id="tsk_test",
+ workflow_run_id="wr_test",
+ organization_id="o_test",
+ totp_verification_url="https://example.com/webhook",
+ totp_identifier=None,
+ navigation_payload={},
+ )
+ polled = OTPValue(value="424242", type=OTPType.TOTP)
+ poll = AsyncMock(return_value=polled)
+ monkeypatch.setattr(otp_service, "poll_otp_value", poll)
+
+ with skyvern_context.scoped(_scoped_context(active=None)):
+ result = await resolve_otp_value(task)
+
+ assert result is polled
+ poll.assert_awaited_once()
+
def _mock_org_token() -> MagicMock:
token = MagicMock()
@@ -1553,12 +1602,54 @@ class TestPollOtpValueRetry:
assert raw not in str(polling.values())
+def _credential_parameter(key: str) -> CredentialParameter:
+ now = datetime.now(timezone.utc)
+ return CredentialParameter(
+ key=key,
+ credential_parameter_id=f"cp_{key}",
+ workflow_id="wf_test",
+ credential_id=f"cred_{key}",
+ created_at=now,
+ modified_at=now,
+ )
+
+
+def _ordinary_workflow_parameter(key: str) -> WorkflowParameter:
+ now = datetime.now(timezone.utc)
+ return WorkflowParameter(
+ key=key,
+ workflow_parameter_type=WorkflowParameterType.JSON,
+ workflow_parameter_id=f"wp_{key}",
+ workflow_id="wf_test",
+ created_at=now,
+ modified_at=now,
+ )
+
+
class _FakeWorkflowRunContext:
- """Minimal stub mirroring WorkflowRunContext shape for try_generate_totp_from_credential."""
+ """Stub mirroring WorkflowRunContext shape (values/secrets/parameters) for TOTP lookup.
+
+ ``parameters`` maps each key to a real Parameter model so
+ ``is_registered_credential_parameter_key`` exercises the same
+ ``_CREDENTIAL_PARAMETER_TYPES`` isinstance check as production. When omitted,
+ every values key is registered as a real credential parameter (the shape the
+ original credential-selection tests assume).
+ """
- def __init__(self, values: dict[str, dict[str, str]], secrets: dict[str, str]) -> None:
+ def __init__(
+ self,
+ values: dict[str, dict[str, str]],
+ secrets: dict[str, str],
+ parameters: dict[str, object] | None = None,
+ ) -> None:
self.values = values
self.secrets = secrets
+ if parameters is None:
+ parameters = {key: _credential_parameter(key) for key in values}
+ self.parameters = parameters
+
+ def is_registered_credential_parameter_key(self, key: str) -> bool:
+ return isinstance(self.parameters.get(key), _CREDENTIAL_PARAMETER_TYPES)
def totp_secret_value_key(self, totp_secret_id: str) -> str:
return f"{totp_secret_id}_value"
@@ -1677,6 +1768,58 @@ class TestTryGenerateTotpFromCredential:
assert result is not None
assert result.value == "131313"
+ def test_ordinary_input_dict_with_placeholder_totp_is_not_a_candidate(
+ self, monkeypatch: pytest.MonkeyPatch
+ ) -> None:
+ """An ordinary run input dict with a placeholder-shaped `totp` is not a credential.
+
+ Before the registration boundary it was the sole fallback candidate and its
+ `totp` value was resolved and generated, letting an ordinary input masquerade as
+ a credential-backed TOTP instead of falling through to polling.
+ """
+ fake = _FakeWorkflowRunContext(
+ values={"user_input": {"totp": "tot_x"}},
+ secrets={"tot_x_value": _VALID_TOTP_SEED},
+ parameters={"user_input": _ordinary_workflow_parameter("user_input")},
+ )
+ self._patch_workflow_context(monkeypatch, fake)
+ monkeypatch.setattr(pyotp.TOTP, "now", lambda _self: "111111")
+
+ with skyvern_context.scoped(_scoped_context(active=None)):
+ result = try_generate_totp_from_credential("wr_test")
+
+ assert result is None
+
+ def test_active_key_not_registered_credential_returns_none(self, monkeypatch: pytest.MonkeyPatch) -> None:
+ """A stale/arbitrary active key pointing at an ordinary dict cannot bypass the boundary."""
+ fake = _FakeWorkflowRunContext(
+ values={"user_input": {"totp": "tot_x"}},
+ secrets={"tot_x_value": _VALID_TOTP_SEED},
+ parameters={"user_input": _ordinary_workflow_parameter("user_input")},
+ )
+ self._patch_workflow_context(monkeypatch, fake)
+
+ with skyvern_context.scoped(_scoped_context(active="user_input")):
+ result = try_generate_totp_from_credential("wr_test")
+
+ assert result is None
+
+ def test_registered_credential_parameter_generates_code(self, monkeypatch: pytest.MonkeyPatch) -> None:
+ """A registered credential parameter with a TOTP secret still generates normally."""
+ fake = _FakeWorkflowRunContext(
+ values={"credentials": {"username": "u", "totp": "tot_b"}},
+ secrets={"tot_b_value": _VALID_TOTP_SEED},
+ parameters={"credentials": _credential_parameter("credentials")},
+ )
+ self._patch_workflow_context(monkeypatch, fake)
+ monkeypatch.setattr(pyotp.TOTP, "now", lambda _self: "246810")
+
+ with skyvern_context.scoped(_scoped_context(active=None)):
+ result = try_generate_totp_from_credential("wr_test")
+
+ assert result is not None
+ assert result.value == "246810"
+
def test_workflow_run_id_none_returns_none(self) -> None:
assert try_generate_totp_from_credential(None) is None
diff --git a/tests/unit/test_request_logging.py b/tests/unit/test_request_logging.py
index 46ec5ba13..2330bd7ae 100644
--- a/tests/unit/test_request_logging.py
+++ b/tests/unit/test_request_logging.py
@@ -27,9 +27,11 @@ from skyvern.forge.request_logging import (
_client_ip_from_headers,
_is_loggable_content_type,
_sanitize_body,
+ _sanitize_headers,
_sanitize_response_body,
log_raw_request_exception,
log_raw_request_middleware,
+ set_request_organization,
)
# ---------------------------------------------------------------------------
@@ -377,6 +379,15 @@ def _make_request(method: str = "GET", path: str = "/api/v1/test") -> MagicMock:
return request
+def test_sanitize_headers_removes_posthog_attribution_but_keeps_ordinary_header() -> None:
+ assert _sanitize_headers(
+ {
+ "X-PostHog-Attribution": "encoded-attribution",
+ "X-Request-ID": "request-id",
+ }
+ ) == {"X-Request-ID": "request-id"}
+
+
class TestSanitizeResponseBody:
def test_sensitive_endpoint_fully_redacted(self) -> None:
request = _make_request("POST", "/api/v1/credentials")
@@ -592,6 +603,14 @@ def _make_app(unhandled_exception_status: int = 500) -> FastAPI:
async def protected() -> dict:
raise HTTPException(status_code=403, detail="Invalid credentials")
+ @app.get("/payment-required")
+ async def payment_required() -> dict:
+ raise HTTPException(status_code=402, detail="Payment Required")
+
+ @app.post("/post-only")
+ async def post_only() -> dict:
+ return {"ok": True}
+
@app.get("/v1/credentials/totp")
async def get_totp() -> dict:
return {"code": "123456", "content": "Your code is 123456"}
@@ -687,6 +706,69 @@ class TestMiddlewareLogVolume:
assert log_mock.error.call_args.args[0] == "api.raw_request"
assert log_mock.error.call_args.kwargs["status_code"] == response.status_code
+ def test_authenticated_request_is_attributed_to_its_organization(
+ self, log_mock: MagicMock, monkeypatch: pytest.MonkeyPatch
+ ) -> None:
+ """Per-org error-rate monitors need customer identity on every api.raw_request row.
+
+ Auth resolves inside api_app's own BaseHTTPMiddleware layers, whose child tasks do not
+ propagate rebound ContextVars back up to the logging middleware that emits the row.
+ """
+ monkeypatch.setattr(api_app, "LOG", MagicMock())
+ app = api_app.create_api_app()
+
+ @app.post("/_test_request_logging_authed")
+ async def authed() -> dict:
+ set_request_organization("o_385835488455492960", "Acme Corp")
+ return {"ok": True}
+
+ response = TestClient(app).post("/_test_request_logging_authed")
+
+ assert response.status_code == 200
+ logged = log_mock.info.call_args.kwargs
+ assert logged["organization_id"] == "o_385835488455492960"
+ assert logged["organization_name"] == "Acme Corp"
+
+ def test_unhandled_exception_is_attributed_to_its_organization(
+ self, log_mock: MagicMock, monkeypatch: pytest.MonkeyPatch
+ ) -> None:
+ monkeypatch.setattr(api_app, "LOG", MagicMock())
+ app = api_app.create_api_app()
+
+ @app.post("/_test_request_logging_authed_boom")
+ async def boom() -> None:
+ set_request_organization("o_385835488455492960", "Acme Corp")
+ raise ValueError("kaboom")
+
+ response = TestClient(app, raise_server_exceptions=False).post("/_test_request_logging_authed_boom")
+
+ assert response.status_code == 500
+ assert log_mock.error.call_args.kwargs["organization_id"] == "o_385835488455492960"
+
+ def test_organization_does_not_leak_into_a_later_unauthenticated_request(
+ self, log_mock: MagicMock, monkeypatch: pytest.MonkeyPatch
+ ) -> None:
+ monkeypatch.setattr(api_app, "LOG", MagicMock())
+ app = api_app.create_api_app()
+
+ @app.post("/_test_request_logging_authed")
+ async def authed() -> dict:
+ set_request_organization("o_385835488455492960", "Acme Corp")
+ return {"ok": True}
+
+ @app.post("/_test_request_logging_anonymous")
+ async def anonymous() -> dict:
+ return {"ok": True}
+
+ client = TestClient(app)
+ client.post("/_test_request_logging_authed")
+ response = client.post("/_test_request_logging_anonymous")
+
+ assert response.status_code == 200
+ logged = log_mock.info.call_args.kwargs
+ assert "organization_id" not in logged
+ assert "organization_name" not in logged
+
def test_action_log_request_and_response_bodies_are_fully_redacted(self, log_mock: MagicMock) -> None:
client = TestClient(_make_app())
secret = "sk-test-action-log-secret"
@@ -745,13 +827,6 @@ class TestMiddlewareLogVolume:
assert response.status_code == 200
log_mock.info.assert_called_once()
- def test_failed_get_is_logged_as_warning(self, log_mock: MagicMock) -> None:
- client = TestClient(_make_app())
- response = client.get("/missing")
- assert response.status_code == 404
- log_mock.warning.assert_called_once()
- assert log_mock.warning.call_args.args[0] == "api.raw_request"
-
def test_403_get_keeps_datadog_monitor_contract(self, log_mock: MagicMock) -> None:
"""The 403-spike monitors query api.raw_request status:warn @status_code:403."""
client = TestClient(_make_app())
@@ -887,3 +962,31 @@ class TestClientDisconnectDuringBodyRead:
assert response is sentinel
request.body.assert_not_awaited()
+
+
+class TestRawRequestLogLevel:
+ """Only 4xx rows that call for action share the warn tier; 404/405 are routine and log at info."""
+
+ @pytest.mark.parametrize(("path", "status_code"), [("/missing", 404), ("/post-only", 405)])
+ def test_not_found_and_method_not_allowed_log_at_info(
+ self, log_mock: MagicMock, path: str, status_code: int
+ ) -> None:
+ response = TestClient(_make_app()).get(path)
+
+ assert response.status_code == status_code
+ log_mock.info.assert_called_once()
+ assert log_mock.info.call_args.args[0] == "api.raw_request"
+ assert log_mock.info.call_args.kwargs["status_code"] == status_code
+ log_mock.warning.assert_not_called()
+
+ @pytest.mark.parametrize(("path", "status_code"), [("/payment-required", 402), ("/protected", 403)])
+ def test_actionable_client_errors_still_log_at_warning(
+ self, log_mock: MagicMock, path: str, status_code: int
+ ) -> None:
+ response = TestClient(_make_app()).get(path)
+
+ assert response.status_code == status_code
+ log_mock.warning.assert_called_once()
+ assert log_mock.warning.call_args.args[0] == "api.raw_request"
+ assert log_mock.warning.call_args.kwargs["status_code"] == status_code
+ log_mock.info.assert_not_called()
diff --git a/tests/unit/test_run_sdk_action_failures.py b/tests/unit/test_run_sdk_action_failures.py
index 53b38683e..bd40cbd97 100644
--- a/tests/unit/test_run_sdk_action_failures.py
+++ b/tests/unit/test_run_sdk_action_failures.py
@@ -7,7 +7,8 @@ from unittest.mock import AsyncMock, MagicMock, patch
import pytest
from fastapi import HTTPException
-from skyvern.exceptions import ScrapingFailed, SkyvernActionFailed
+from skyvern.exceptions import ScrapingFailed, ScreenshotTargetClosed, SkyvernActionFailed
+from skyvern.forge.sdk.db.enums import TaskType
from skyvern.forge.sdk.routes.sdk import _sdk_action_context_refcounts, run_sdk_action
from tests.unit.conftest import LEGACY_DOWNLOAD_ESCAPE_CASES
@@ -55,26 +56,124 @@ def mock_app() -> Any:
@pytest.mark.asyncio
-async def test_auto_generated_run_is_completed_through_workflow_service(
+async def test_auto_generated_run_commits_marker_before_completion(
mock_request: Any, mock_organization: Any, mock_app: Any
) -> None:
mock_request.workflow_run_id = None
workflow = MagicMock(workflow_id="w_test", workflow_permanent_id="wpid_test", title="t")
workflow_run = MagicMock(workflow_run_id="wr_test", workflow_id="w_test")
+ task = mock_app.DATABASE.tasks.create_task.return_value
+ step = mock_app.DATABASE.tasks.create_step.return_value
+ events: list[str] = []
+
mock_app.WORKFLOW_SERVICE.create_empty_workflow = AsyncMock(return_value=workflow)
mock_app.WORKFLOW_SERVICE.setup_workflow_run = AsyncMock(return_value=workflow_run)
- mock_app.WORKFLOW_SERVICE.mark_workflow_run_as_completed = AsyncMock(return_value=workflow_run)
- mock_app.DATABASE.workflow_runs.update_workflow_run = AsyncMock(return_value=workflow_run)
- mock_app.DATABASE.tasks.create_task = AsyncMock(side_effect=RuntimeError("stop after completion"))
- with patch("skyvern.forge.sdk.routes.sdk.app", mock_app):
- with pytest.raises(RuntimeError, match="stop after completion"):
+ mock_app.DATABASE.workflow_runs.update_workflow_run = AsyncMock()
+
+ async def create_task(**_: Any) -> Any:
+ events.append("task")
+ return task
+
+ async def mark_workflow_run_as_completed(**_: Any) -> Any:
+ events.append("complete")
+ return workflow_run
+
+ async def create_step(*_: Any, **__: Any) -> Any:
+ events.append("step")
+ return step
+
+ async def create_workflow_run_block(**_: Any) -> None:
+ events.append("block")
+
+ mock_app.DATABASE.tasks.create_task = AsyncMock(side_effect=create_task)
+ mock_app.WORKFLOW_SERVICE.mark_workflow_run_as_completed = AsyncMock(side_effect=mark_workflow_run_as_completed)
+ mock_app.DATABASE.tasks.create_step = AsyncMock(side_effect=create_step)
+ mock_app.DATABASE.observer.create_workflow_run_block = AsyncMock(side_effect=create_workflow_run_block)
+
+ with (
+ patch("skyvern.forge.sdk.routes.sdk.app", mock_app),
+ patch("skyvern.forge.sdk.routes.sdk.skyvern_context") as mock_ctx,
+ patch(
+ "skyvern.core.script_generations.script_skyvern_page.ScriptSkyvernPage.create_scraped_page",
+ new_callable=AsyncMock,
+ side_effect=RuntimeError("stop after setup"),
+ ),
+ ):
+ mock_ctx.ensure_context.return_value = MagicMock(request_id="req_test", tz_info=None, prompt=None)
+ with pytest.raises(RuntimeError, match="stop after setup"):
await run_sdk_action(mock_request, organization=mock_organization)
+ assert events[:4] == ["task", "complete", "step", "block"]
+ assert mock_app.DATABASE.tasks.create_task.await_args.kwargs["task_type"] == TaskType.synthetic_sdk_action
mock_app.WORKFLOW_SERVICE.mark_workflow_run_as_completed.assert_awaited_once_with(workflow_run_id="wr_test")
mock_app.DATABASE.workflow_runs.update_workflow_run.assert_not_awaited()
+async def test_caller_provided_run_keeps_general_task_type(
+ mock_request: Any, mock_organization: Any, mock_app: Any
+) -> None:
+ mock_app.WORKFLOW_SERVICE.mark_workflow_run_as_completed = AsyncMock()
+
+ with (
+ patch("skyvern.forge.sdk.routes.sdk.app", mock_app),
+ patch("skyvern.forge.sdk.routes.sdk.skyvern_context") as mock_ctx,
+ patch(
+ "skyvern.core.script_generations.script_skyvern_page.ScriptSkyvernPage.create_scraped_page",
+ new_callable=AsyncMock,
+ side_effect=RuntimeError("stop inside action"),
+ ),
+ ):
+ mock_ctx.ensure_context.return_value = MagicMock(request_id="req_test", tz_info=None, prompt=None)
+ with pytest.raises(RuntimeError, match="stop inside action"):
+ await run_sdk_action(mock_request, organization=mock_organization)
+
+ assert mock_app.DATABASE.tasks.create_task.await_args.kwargs["task_type"] == TaskType.general
+ mock_app.WORKFLOW_SERVICE.mark_workflow_run_as_completed.assert_not_awaited()
+
+
+async def test_minted_sdk_action_uses_inline_dispatch_without_generic_executor(
+ mock_request: Any, mock_organization: Any, mock_app: Any
+) -> None:
+ mock_request.workflow_run_id = None
+ workflow = MagicMock(workflow_id="w_test", workflow_permanent_id="wpid_test", title="t")
+ workflow_run = MagicMock(workflow_run_id="wr_test", workflow_id="w_test")
+ mock_app.WORKFLOW_SERVICE.create_empty_workflow = AsyncMock(return_value=workflow)
+ mock_app.WORKFLOW_SERVICE.setup_workflow_run = AsyncMock(return_value=workflow_run)
+ mock_app.WORKFLOW_SERVICE.mark_workflow_run_as_completed = AsyncMock(return_value=workflow_run)
+ mock_app.WORKFLOW_SERVICE.create_workflow_from_prompt = AsyncMock()
+ scraped_page = MagicMock(_browser_state=MagicMock(must_get_working_page=AsyncMock(return_value=MagicMock())))
+ page_ai = MagicMock(ai_click=AsyncMock(return_value={"clicked": True}))
+ generic_executor = MagicMock()
+ generic_executor.execute_task = AsyncMock()
+ generic_executor.execute_workflow = AsyncMock()
+
+ with (
+ patch("skyvern.forge.sdk.routes.sdk.app", mock_app),
+ patch("skyvern.forge.sdk.routes.sdk.skyvern_context") as mock_ctx,
+ patch(
+ "skyvern.core.script_generations.script_skyvern_page.ScriptSkyvernPage.create_scraped_page",
+ new_callable=AsyncMock,
+ return_value=scraped_page,
+ ),
+ patch("skyvern.forge.sdk.routes.sdk.RealSkyvernPageAi", return_value=page_ai),
+ patch(
+ "skyvern.forge.sdk.executor.factory.AsyncExecutorFactory.get_executor",
+ return_value=generic_executor,
+ ) as get_executor,
+ ):
+ mock_ctx.ensure_context.return_value = MagicMock(request_id="req_test", tz_info=None, prompt=None)
+ response = await run_sdk_action(mock_request, organization=mock_organization)
+
+ assert response.result == {"clicked": True}
+ get_executor.assert_not_called()
+ generic_executor.execute_task.assert_not_awaited()
+ generic_executor.execute_workflow.assert_not_awaited()
+ mock_app.WORKFLOW_SERVICE.create_workflow_from_prompt.assert_not_awaited()
+
+
@pytest.mark.asyncio
async def test_handler_returns_422_when_action_raises_skyvern_action_failed(
mock_request: Any, mock_organization: Any, mock_app: Any
@@ -117,6 +216,29 @@ async def test_handler_returns_400_when_action_raises_scraping_failed(
assert exc_info.value.status_code == 400
+async def test_handler_returns_422_when_browser_target_closed(
+ mock_request: Any, mock_organization: Any, mock_app: Any
+) -> None:
+ with (
+ patch("skyvern.forge.sdk.routes.sdk.app", mock_app),
+ patch("skyvern.forge.sdk.routes.sdk.skyvern_context") as mock_ctx,
+ patch(
+ "skyvern.core.script_generations.script_skyvern_page.ScriptSkyvernPage.create_scraped_page",
+ new_callable=AsyncMock,
+ side_effect=ScreenshotTargetClosed(
+ error_message="Page.screenshot: Target page, context or browser has been closed"
+ ),
+ ),
+ ):
+ mock_ctx.ensure_context.return_value = MagicMock(request_id="req_test", tz_info=None, prompt=None)
+ with pytest.raises(HTTPException) as exc_info:
+ await run_sdk_action(mock_request, organization=mock_organization)
+
+ assert exc_info.value.status_code == 422
+ mock_app.DATABASE.tasks.update_task.assert_awaited()
+
+
@pytest.mark.asyncio
async def test_handler_propagates_unknown_exception(mock_request: Any, mock_organization: Any, mock_app: Any) -> None:
with (
diff --git a/tests/unit/test_screenshot_target_closed_callers.py b/tests/unit/test_screenshot_target_closed_callers.py
index 5dabc98e6..a58d0f021 100644
--- a/tests/unit/test_screenshot_target_closed_callers.py
+++ b/tests/unit/test_screenshot_target_closed_callers.py
@@ -6,20 +6,26 @@ helper classifies it and logs info, but each caller frame decided severity indep
suppressing one frame just moved the ERROR-with-traceback — and the auto-filed Error Tracking
issue — up to the next one. ``agent_step`` now passes it through as an expected terminal failure
alongside ``ScrapingFailed`` / ``MissingBrowserStatePage``, and ``execute_step`` fails the task
-cleanly at warning. These tests pin every frame, with controls so unrelated failures still ERROR.
+cleanly at warning. Task teardown, the action handler, complete-action verification and the SDK
+route (``test_run_sdk_action_failures.py``) were the frames left over from that first pass. These
+tests pin every frame, with controls so unrelated failures still ERROR.
"""
from __future__ import annotations
import inspect
+from collections.abc import AsyncIterator
+from contextlib import asynccontextmanager
from datetime import UTC, datetime
-from unittest.mock import AsyncMock, MagicMock
+from typing import Any
+from unittest.mock import AsyncMock, MagicMock, patch
import pytest
from playwright._impl._errors import TargetClosedError
import skyvern.forge.agent as agent_mod
import skyvern.services.task_v2_service as task_v2_mod
+import skyvern.webeye.actions.handler as handler_mod
import skyvern.webeye.scraper.scraper as scraper_mod
from skyvern.exceptions import FailedToTakeScreenshot, ScreenshotTargetClosed
from skyvern.forge.agent import ForgeAgent
@@ -27,10 +33,16 @@ from skyvern.forge.sdk.core import skyvern_context
from skyvern.forge.sdk.core.skyvern_context import SkyvernContext
from skyvern.forge.sdk.models import StepStatus
from skyvern.schemas.runs import RunEngine
+from skyvern.webeye.actions.actions import ActionType, ClickAction, CompleteAction
from tests.unit.helpers import make_browser_state, make_organization, make_step, make_task
from tests.unit.test_agent_step_characterization import make_agent_step_rig
+@asynccontextmanager
+async def _noop_async_context(*args: Any, **kwargs: Any) -> AsyncIterator[None]:
+ yield
+
+
def _agent_rig(
monkeypatch: pytest.MonkeyPatch, screenshot_error: Exception, html_error: Exception | None = None
) -> tuple[MagicMock, dict]:
@@ -227,6 +239,144 @@ class TestAgentStepPassThrough:
log.exception.assert_called()
+class TestCleanUpTaskTargetClosed:
+ """The final screenshot is best-effort teardown, taken while the browser is being torn down.
+ The narrow handler only named Playwright's ``TargetClosedError``, but the screenshot helper
+ stopped letting that through -- it classifies and re-raises ``ScreenshotTargetClosed``.
+ """
+
+ def _rig(self, monkeypatch: pytest.MonkeyPatch, screenshot_error: Exception) -> tuple[MagicMock, dict]:
+ now = datetime.now(UTC)
+ organization = make_organization(now)
+ task = make_task(now, organization, workflow_run_id="wr-cleanup")
+ step = make_step(now, task, step_id="step-cleanup", status=StepStatus.completed, order=0, output=None)
+
+ browser_state, _, page = make_browser_state()
+ browser_state.get_working_page = AsyncMock(return_value=page)
+ browser_state.take_fullpage_screenshot = AsyncMock(side_effect=screenshot_error)
+
+ app_mock = MagicMock()
+ app_mock.DATABASE.tasks.get_task = AsyncMock(return_value=task)
+ app_mock.BROWSER_MANAGER.get_for_task = MagicMock(return_value=browser_state)
+ app_mock.ARTIFACT_MANAGER.create_artifact = AsyncMock()
+ monkeypatch.setattr(agent_mod, "app", app_mock)
+ monkeypatch.setattr(agent_mod.analytics, "capture", MagicMock())
+ monkeypatch.setattr(agent_mod, "settle_browser_downloads_for_context", _noop_async_context)
+
+ log = MagicMock()
+ monkeypatch.setattr(agent_mod, "LOG", log)
+ skyvern_context.set(SkyvernContext(task_id=task.task_id, organization_id=task.organization_id))
+
+ return log, {"task": task, "last_step": step}
+
+ @pytest.mark.asyncio
+ async def test_closed_target_is_logged_without_error(self, monkeypatch: pytest.MonkeyPatch) -> None:
+ log, kwargs = self._rig(monkeypatch, ScreenshotTargetClosed(error_message="Page is closed"))
+
+ await ForgeAgent().clean_up_task(**kwargs)
+
+ log.exception.assert_not_called()
+ assert any("page is closed" in str(call.args[0]).lower() for call in log.warning.call_args_list), (
+ f"closed target was not warned about: {log.warning.call_args_list}"
+ )
+
+ @pytest.mark.asyncio
+ async def test_other_screenshot_failures_still_log_exception(self, monkeypatch: pytest.MonkeyPatch) -> None:
+ log, kwargs = self._rig(monkeypatch, FailedToTakeScreenshot(error_message="Target crashed"))
+
+ await ForgeAgent().clean_up_task(**kwargs)
+
+ assert any(
+ "Failed to take screenshot before sending task response" in str(call.args[0])
+ for call in log.exception.call_args_list
+ )
+
+
+class TestHandleActionTargetClosed:
+ async def _run(self, monkeypatch: pytest.MonkeyPatch, error: Exception) -> tuple[MagicMock, list]:
+ now = datetime.now(UTC)
+ task = make_task(now, make_organization(now))
+ step = make_step(now, task, step_id="step-action", status=StepStatus.running, order=0, output=None)
+
+ async def failing_handler(*args: object, **kwargs: object) -> None:
+ raise error
+
+ app_mock = MagicMock()
+ app_mock.AGENT_FUNCTION.wait_for_challenge_solver = AsyncMock()
+ log = MagicMock()
+ monkeypatch.setattr(handler_mod, "app", app_mock)
+ monkeypatch.setattr(handler_mod, "LOG", log)
+
+ with (
+ patch.dict(handler_mod.ActionHandler._handled_action_types, {ActionType.CLICK: failing_handler}),
+ patch.dict(handler_mod.ActionHandler._setup_action_types, {}, clear=True),
+ patch.dict(handler_mod.ActionHandler._teardown_action_types, {}, clear=True),
+ ):
+ results = await handler_mod.ActionHandler._handle_action(
+ scraped_page=MagicMock(id_to_element_dict={"el": {"id": "el"}}),
+ task=task,
+ step=step,
+ page=MagicMock(),
+ action=ClickAction(element_id="el"),
+ )
+ return log, results
+
+ @pytest.mark.asyncio
+ async def test_closed_target_fails_the_action_without_error(self, monkeypatch: pytest.MonkeyPatch) -> None:
+ log, results = await self._run(monkeypatch, ScreenshotTargetClosed(error_message="Page is closed"))
+
+ assert len(results) == 1 and results[0].success is False
+ assert results[0].exception_type == "ScreenshotTargetClosed"
+ log.exception.assert_not_called()
+ log.warning.assert_called_once()
+
+ @pytest.mark.asyncio
+ async def test_other_failures_still_log_exception(self, monkeypatch: pytest.MonkeyPatch) -> None:
+ log, results = await self._run(monkeypatch, RuntimeError("boom"))
+
+ assert len(results) == 1 and results[0].success is False
+ assert any(
+ "Unhandled exception in action handler" in str(call.args[0]) for call in log.exception.call_args_list
+ )
+
+
+class TestCompleteActionVerificationTargetClosed:
+ async def _run(self, monkeypatch: pytest.MonkeyPatch, error: Exception) -> tuple[MagicMock, list]:
+ now = datetime.now(UTC)
+ task = make_task(now, make_organization(now))
+ step = make_step(now, task, step_id="step-complete", status=StepStatus.running, order=0, output=None)
+
+ app_mock = MagicMock()
+ app_mock.agent.complete_verify = AsyncMock(side_effect=error)
+ log = MagicMock()
+ monkeypatch.setattr(handler_mod, "app", app_mock)
+ monkeypatch.setattr(handler_mod, "LOG", log)
+
+ results = await handler_mod.handle_complete_action(
+ CompleteAction(),
+ MagicMock(),
+ MagicMock(),
+ task,
+ step,
+ )
+ return log, results
+
+ @pytest.mark.asyncio
+ async def test_closed_target_fails_verification_without_error(self, monkeypatch: pytest.MonkeyPatch) -> None:
+ log, results = await self._run(monkeypatch, ScreenshotTargetClosed(error_message="Page is closed"))
+
+ assert len(results) == 1 and results[0].success is False
+ log.exception.assert_not_called()
+ log.warning.assert_called_once()
+
+ @pytest.mark.asyncio
+ async def test_other_failures_still_log_exception(self, monkeypatch: pytest.MonkeyPatch) -> None:
+ log, results = await self._run(monkeypatch, RuntimeError("boom"))
+
+ assert len(results) == 1 and results[0].success is False
+ assert any("Failed to verify the complete action" in str(call.args[0]) for call in log.exception.call_args_list)
+
+
class TestTaskV2IterationTargetClosed:
"""Structural guard: ``run_task_v2_helper`` needs a full workflow-run rig to drive, so this pins
the clause ordering instead — the closed-target handler must precede the generic ``LOG.exception``.
diff --git a/tests/unit/test_script_service_fallback_engine.py b/tests/unit/test_script_service_fallback_engine.py
index 7b46cc35d..5c74698b6 100644
--- a/tests/unit/test_script_service_fallback_engine.py
+++ b/tests/unit/test_script_service_fallback_engine.py
@@ -190,3 +190,22 @@ def test_resolver_finds_loop_nested_block_engine() -> None:
workflow = _make_workflow([loop])
assert script_service._resolve_original_block_engine("inner_block", workflow) == RunEngine.skyvern_v3
assert script_service._resolve_original_block_engine("missing", workflow) is None
+
+
+async def test_block_screenshot_without_browser_state_is_not_a_warning(monkeypatch: pytest.MonkeyPatch) -> None:
+ # A block that runs before a browser exists, or never needs one, has no screenshot to take;
+ # skipping it is routine and must not compete with real warnings.
+ from skyvern.services import script_service as script_service_module
+
+ log = MagicMock()
+ monkeypatch.setattr(script_service_module, "LOG", log)
+ monkeypatch.setattr(
+ "skyvern.services.script_service.app.BROWSER_MANAGER.get_for_workflow_run", lambda *_a, **_k: None
+ )
+
+ await script_service_module._take_workflow_run_block_screenshot("wr_test", "o_test", MagicMock())
+
+ log.warning.assert_not_called()
+ log.info.assert_called_once()
+ assert log.info.call_args.args[0] == "No browser state found when creating workflow_run_block"
diff --git a/tests/unit/test_skycdp_reload.py b/tests/unit/test_skycdp_reload.py
new file mode 100644
index 000000000..e03ff5d93
--- /dev/null
+++ b/tests/unit/test_skycdp_reload.py
@@ -0,0 +1,75 @@
+from __future__ import annotations
+
+import asyncio
+from collections.abc import Callable
+
+import pytest
+
+from skyvern.webeye.skycdp.errors import CdpTimeoutError
+from skyvern.webeye.skycdp.facade.page import Page
+
+
+class _ReloadSession:
+ def __init__(self) -> None:
+ self.detached = False
+ self.reload_sent = asyncio.Event()
+ self.handlers: dict[str, list[Callable[[dict], None]]] = {}
+
+ async def send(self, method: str, params: dict | None = None, *, timeout: float | None = None) -> dict:
+ if method == "Page.reload":
+ assert timeout is not None and timeout > 0
+ self.reload_sent.set()
+ return {}
+
+ def on(self, event: str, handler: Callable[[dict], None]) -> None:
+ self.handlers.setdefault(event, []).append(handler)
+
+ def off(self, event: str, handler: Callable[[dict], None]) -> None:
+ self.handlers[event].remove(handler)
+
+ def emit(self, event: str, params: dict) -> None:
+ for handler in list(self.handlers.get(event, [])):
+ handler(params)
+
+
+async def test_reload_waits_for_a_new_main_frame_commit_and_load_event() -> None:
+ session = _ReloadSession()
+ page = Page(object(), session) # type: ignore[arg-type]
+ page._main_frame_id = "main"
+ page._bind_session_events(session)
+
+ reloading = asyncio.create_task(page.reload(timeout=5_000, wait_until="domcontentloaded"))
+ await session.reload_sent.wait()
+
+ assert not reloading.done()
+ session.emit("Page.frameNavigated", {"frame": {"id": "subframe", "url": "https://frame.example"}})
+ assert not reloading.done()
+ session.emit("Page.loadEventFired", {})
+ assert not reloading.done()
+
+ session.emit("Page.frameNavigated", {"frame": {"id": "main", "url": "https://example.test"}})
+ assert not reloading.done()
+ session.emit("Page.loadEventFired", {})
+ await reloading
+
+ assert not page._listeners.get("framenavigated")
+ assert session.handlers["Page.loadEventFired"] == []
+
+
+async def test_reload_times_out_when_load_event_never_arrives() -> None:
+ session = _ReloadSession()
+ page = Page(object(), session) # type: ignore[arg-type]
+ page._main_frame_id = "main"
+ page._bind_session_events(session)
+
+ reloading = asyncio.create_task(page.reload(timeout=50, wait_until="load"))
+ await session.reload_sent.wait()
+ session.emit("Page.frameNavigated", {"frame": {"id": "main", "url": "https://example.test"}})
+
+ with pytest.raises(CdpTimeoutError, match="reload did not commit and load a new main-frame document"):
+ await reloading
+
+ assert not page._listeners.get("framenavigated")
+ assert session.handlers["Page.loadEventFired"] == []
diff --git a/tests/unit/test_task_request_validation.py b/tests/unit/test_task_request_validation.py
index a3344c5da..3f6ba162a 100644
--- a/tests/unit/test_task_request_validation.py
+++ b/tests/unit/test_task_request_validation.py
@@ -82,6 +82,26 @@ def test_legacy_task_request_validates_browser_address_at_parse_time() -> None:
assert request.browser_address == "wss://browser.example.test/devtools/browser/id"
+def test_public_task_request_rejects_internal_synthetic_task_type() -> None:
+ import pydantic
+
+ from skyvern.forge.sdk.db.enums import TaskType
+ from skyvern.forge.sdk.schemas.tasks import TaskRequest
+
+ with pytest.raises(pydantic.ValidationError, match="task_type"):
+ TaskRequest(url="https://task.example.test", task_type=TaskType.synthetic_sdk_action)
+
+ task_type_schema = TaskRequest.model_json_schema()["properties"]["task_type"]
+ schema_values = set(task_type_schema.get("enum", []))
+ schema_values.update(value for branch in task_type_schema.get("anyOf", []) for value in branch.get("enum", []))
+ assert schema_values == {
+ TaskType.general.value,
+ TaskType.validation.value,
+ TaskType.action.value,
+ }
+ assert TaskType.synthetic_sdk_action.value not in schema_values
+
+
def test_legacy_workflow_request_validates_browser_address_at_parse_time() -> None:
import pydantic
diff --git a/tests/unit/test_taskv3_auth_tools.py b/tests/unit/test_taskv3_auth_tools.py
index f62fc9cdb..9da7dcc1a 100644
--- a/tests/unit/test_taskv3_auth_tools.py
+++ b/tests/unit/test_taskv3_auth_tools.py
@@ -2,6 +2,7 @@
from __future__ import annotations
+from datetime import datetime, timezone
from types import SimpleNamespace
from typing import Any
from unittest.mock import AsyncMock, MagicMock
@@ -13,6 +14,7 @@ from skyvern.forge.sdk.core.skyvern_context import SkyvernContext
from skyvern.forge.sdk.schemas.totp_codes import OTPType
from skyvern.forge.sdk.workflow import context_manager as cm
from skyvern.forge.sdk.workflow.context_manager import WorkflowContextManager, WorkflowRunContext
+from skyvern.forge.sdk.workflow.models.parameter import CredentialParameter
from skyvern.forge.taskv3 import auth_tools
from skyvern.services import otp_service
from skyvern.services.otp_service import OTPValue
@@ -183,6 +185,18 @@ def test_get_secret_values_for_run_standalone_task_uses_global_artifact_redactio
skyvern_context.reset()
+def _credential_parameter(key: str) -> CredentialParameter:
+ now = datetime.now(timezone.utc)
+ return CredentialParameter(
+ key=key,
+ credential_parameter_id=f"cp_{key}",
+ workflow_id="w_test",
+ credential_id=f"cred_{key}",
+ created_at=now,
+ modified_at=now,
+ )
+
+
def _workflow_run_context_with_totp_credentials() -> WorkflowRunContext:
workflow_run_context = WorkflowRunContext(
workflow_title="t",
@@ -195,6 +209,8 @@ def _workflow_run_context_with_totp_credentials() -> WorkflowRunContext:
workflow_run_context.values["cred_2"] = {"totp": "totp_id_2"}
workflow_run_context.secrets["totp_id_1_value"] = "SEED_ONE"
workflow_run_context.secrets["totp_id_2_value"] = "SEED_TWO"
+ workflow_run_context.parameters["cred_1"] = _credential_parameter("cred_1")
+ workflow_run_context.parameters["cred_2"] = _credential_parameter("cred_2")
return workflow_run_context
diff --git a/tests/unit/test_taskv3_engine.py b/tests/unit/test_taskv3_engine.py
index d604345b9..0701cfdaf 100644
--- a/tests/unit/test_taskv3_engine.py
+++ b/tests/unit/test_taskv3_engine.py
@@ -21,6 +21,7 @@ from skyvern.forge.taskv3.engine import (
run_task_v3_agent_loop,
taskv3_runaway_backstops,
)
+from skyvern.forge.taskv3.loop import ToolResult, ToolSpec
from skyvern.forge.taskv3.tools import PAGE_UNAVAILABLE_ERROR
from tests.unit.test_taskv3_loop import _ScriptedCaller
from tests.unit.test_taskv3_tools import _FakePage, _fixed_page_provider
@@ -345,3 +346,44 @@ async def test_engine_requests_tool_choice_when_enabled(monkeypatch: pytest.Monk
)
assert captured["call_kwargs"] == {"step": step}
+
+
+async def test_engine_wires_failure_evidence_gate() -> None:
+ # End-to-end wiring: the engine's own ActivityRecency reaches both the loop (which records the
+ # solve_captcha attempt) and the finish tool (which holds the failure verdict for one evidence
+ # turn). Without either half the first finish(failed) would be accepted immediately.
+ async def solve_captcha_handler(args: Any) -> ToolResult:
+ return ToolResult.error("a captcha challenge is present but could not be solved this attempt")
+
+ captcha_tool = ToolSpec(
+ name="solve_captcha",
+ description="solve_captcha",
+ parameters={"type": "object", "properties": {}},
+ handler=solve_captcha_handler,
+ recordable=True,
+ )
+
+ async def page_fingerprint() -> str | None:
+ return "fp"
+
+ async def provider() -> Any:
+ return object()
+
+ script = [
+ [("solve_captcha", {})],
+ [("finish", {"status": "failed", "reason": "could_not_pass_captcha"})],
+ [("finish", {"status": "failed", "reason": "still blocked, re-verified"})],
+ ]
+ caller = _ScriptedCaller(script)
+ outcome = await run_task_v3_agent_loop(
+ page_provider=provider,
+ llm_caller=caller,
+ goal="apply",
+ page_fingerprint=page_fingerprint,
+ extra_tools=[captcha_tool],
+ max_action_steps=4,
+ max_turns=8,
+ )
+ assert outcome.status == "failed"
+ assert outcome.reason == "still blocked, re-verified"
diff --git a/tests/unit/test_taskv3_loop.py b/tests/unit/test_taskv3_loop.py
index 155e77fd1..e87db94b6 100644
--- a/tests/unit/test_taskv3_loop.py
+++ b/tests/unit/test_taskv3_loop.py
@@ -20,6 +20,7 @@ from skyvern.exceptions import SkyvernContextWindowExceededError
from skyvern.forge.sdk.api.llm.exceptions import LLMProviderErrorRetryableTask
from skyvern.forge.taskv3.loop import (
NO_TOOL_CALL_NUDGE,
+ ActivityRecency,
ToolHandler,
ToolResult,
ToolSpec,
@@ -1466,3 +1467,608 @@ async def test_navigate_resets_action_counters() -> None:
outcome, _ = await _run(script, tools, max_turns=200, max_tool_calls=500)
assert outcome.status == "completed"
assert len(clicks) == 10
+
+
+def _captcha_tool(results: list[str]) -> ToolSpec:
+ """solve_captcha fake: recordable, non-billable, returns each result as a tool ERROR (the
+ tri-state's not-solved arm) — the arm the false-negative verdicts followed in production."""
+ calls = {"n": 0}
+
+ async def handler(args: dict[str, Any]) -> ToolResult:
+ content = results[min(calls["n"], len(results) - 1)]
+ calls["n"] += 1
+ return ToolResult.error(content)
+
+ return ToolSpec(
+ name="solve_captcha",
+ description="solve_captcha",
+ parameters={"type": "object", "properties": {}},
+ handler=handler,
+ recordable=True,
+ )
+
+
+def _fingerprint_seq(samples: list[str | None]):
+ """Fingerprint fake returning each sample in order, repeating the last forever."""
+ calls = {"n": 0}
+
+ async def fingerprint() -> str | None:
+ sample = samples[min(calls["n"], len(samples) - 1)]
+ calls["n"] += 1
+ return sample
+
+ return fingerprint, calls
+
+
+async def test_finish_failed_after_captcha_defers_for_evidence_then_corrected_verdict() -> None:
+ # The production false-negative shape: solve_captcha reports not-solved, the model immediately
+ # calls finish(failed) — but the captcha protocol completes asynchronously and the submission
+ # lands. The verdict must be held for one evidence turn; the fresh observe shows the
+ # confirmation banner and the corrected verdict is completed.
+ activity = ActivityRecency()
+ fingerprint, fp_calls = _fingerprint_seq(["mid-flight", "submitted", "submitted"])
+ tools = [
+ _captcha_tool(["a captcha challenge is present but could not be solved this attempt"]),
+ _perception_tool("observe", "url=x text: 'Application submitted!'"),
+ make_finish_tool(page_fingerprint=fingerprint, activity=activity, settle_wait_seconds=0.01),
+ ]
+ script = [
+ [("solve_captcha", {})],
+ [("finish", {"status": "failed", "reason": "could_not_pass_captcha"})],
+ [("observe", {})],
+ [("finish", {"status": "completed", "reason": "the page shows the application was submitted"})],
+ ]
+ outcome, _ = await _run(script, tools, activity=activity)
+ assert outcome.status == "completed"
+ assert outcome.reason == "the page shows the application was submitted"
+ deferrals = [
+ m
+ for m in outcome.messages
+ if m.get("role") == "tool" and "held for one evidence check" in str(m.get("content"))
+ ]
+ assert len(deferrals) == 1
+ # The quiescence wait must actually compare sample pairs: mid-flight vs submitted (mutating),
+ # then submitted twice (stable exit) = 3 samples; the corrected finish(completed)'s own settle
+ # probe adds 2 more.
+ assert fp_calls["n"] == 5
+
+
+async def test_failure_gate_still_fires_when_completed_side_settle_is_disabled() -> None:
+ # The bare-task configuration (SKY-14598): the sampler is supplied so the failure-evidence gate
+ # can run, while max_settle_deferrals=0 keeps the completed-side settle probe off. Disabling one
+ # gate must not disable the other — they share only the sampler.
+ activity = ActivityRecency()
+ fingerprint, _ = _fingerprint_seq(["mid-flight", "submitted", "submitted"])
+ tools = [
+ _captcha_tool(["a captcha challenge is present but could not be solved this attempt"]),
+ _perception_tool("observe", "url=x text: 'Application submitted!'"),
+ make_finish_tool(
+ page_fingerprint=fingerprint,
+ max_settle_deferrals=0,
+ activity=activity,
+ settle_wait_seconds=0.01,
+ ),
+ ]
+ script = [
+ [("solve_captcha", {})],
+ [("finish", {"status": "failed", "reason": "could_not_pass_captcha"})],
+ [("observe", {})],
+ [("finish", {"status": "completed", "reason": "the page shows the application was submitted"})],
+ ]
+ outcome, _ = await _run(script, tools, activity=activity)
+ assert outcome.status == "completed"
+ deferrals = [
+ m
+ for m in outcome.messages
+ if m.get("role") == "tool" and "held for one evidence check" in str(m.get("content"))
+ ]
+ assert len(deferrals) == 1
+
+
+async def test_completed_verdict_never_probes_when_settle_is_disabled() -> None:
+ # The other half of the same scoping claim: with max_settle_deferrals=0 a completed verdict is
+ # accepted as-is and the page is never probed for it. Asserting the sampler is untouched (not
+ # merely that no deferral message appeared) is what makes "the completed path is unchanged for
+ # bare tasks" checkable rather than asserted.
+ activity = ActivityRecency()
+ fingerprint, fp_calls = _fingerprint_seq(["mid-flight", "settled", "settled"])
+ tools = [
+ _recording_tool("click", []),
+ make_finish_tool(
+ page_fingerprint=fingerprint,
+ max_settle_deferrals=0,
+ activity=activity,
+ settle_wait_seconds=0.01,
+ ),
+ ]
+ script = [
+ [("click", {"selector": "#submit"})],
+ [("finish", {"status": "completed", "reason": "done"})],
+ ]
+ outcome, _ = await _run(script, tools, activity=activity)
+ assert outcome.status == "completed"
+ assert outcome.reason == "done"
+ assert fp_calls["n"] == 0
+
+
+async def test_finish_failed_after_submit_click_defers_once_then_stands() -> None:
+ # An honest blocked failure after a submit attempt (e.g. a persistent anti-spam banner) costs
+ # exactly one evidence observe: the re-observe shows the same blocked state, the re-issued
+ # failure is accepted unchanged.
+ activity = ActivityRecency()
+ fingerprint, _ = _fingerprint_seq(["fp"])
+ clicks: list[tuple[str, dict[str, Any]]] = []
+ tools = [
+ _billable_tool("click", clicks),
+ _perception_tool("observe", _REJECTION_OBSERVE),
+ make_finish_tool(page_fingerprint=fingerprint, activity=activity, settle_wait_seconds=0.0),
+ ]
+ script = [
+ [("click", {"selector": "#btn-submit"})],
+ [("finish", {"status": "failed", "reason": "submission rejected"})],
+ [("observe", {})],
+ [("finish", {"status": "failed", "reason": "submission still rejected after re-observe"})],
+ ]
+ outcome, _ = await _run(script, tools, activity=activity)
+ assert outcome.status == "failed"
+ assert outcome.reason == "submission still rejected after re-observe"
+ deferrals = [
+ m
+ for m in outcome.messages
+ if m.get("role") == "tool" and "held for one evidence check" in str(m.get("content"))
+ ]
+ assert len(deferrals) == 1
+
+
+async def test_dead_posting_real_trace_shape_gains_at_most_one_observe() -> None:
+ # Conservative dead-posting variant: the replayed dead-posting traces contain no trigger
+ # actions at all (zero cost, pinned by the no-recent-trigger test); this pins the worst case
+ # where a probing click lands in-window — the gate fires and the accepted cost is exactly one
+ # deferral cycle, never more, and the verdict stands.
+ activity = ActivityRecency()
+ fingerprint, _ = _fingerprint_seq(["dead-page"])
+ clicks: list[tuple[str, dict[str, Any]]] = []
+ tools = [
+ _perception_tool("get_html", "<h1>Page not found</h1>"),
+ _perception_tool("observe", ["url=x text: 'The page you requested was not found'"] * 4),
+ _billable_tool("click", clicks),
+ make_finish_tool(page_fingerprint=fingerprint, activity=activity, settle_wait_seconds=0.0),
+ ]
+ script = [
+ [("get_html", {})],
+ [("observe", {})],
+ [("click", {"selector": "#try-anyway"})],
+ [("observe", {})],
+ [("finish", {"status": "failed", "reason": "posting no longer exists"})],
+ [("observe", {})],
+ [("finish", {"status": "failed", "reason": "posting no longer exists (re-verified)"})],
+ ]
+ outcome, _ = await _run(script, tools, activity=activity)
+ assert outcome.status == "failed"
+ assert outcome.reason == "posting no longer exists (re-verified)"
+ deferrals = [
+ m
+ for m in outcome.messages
+ if m.get("role") == "tool" and "held for one evidence check" in str(m.get("content"))
+ ]
+ assert len(deferrals) == 1
+
+
+async def test_finish_failed_without_recent_trigger_is_not_gated() -> None:
+ # A failure with no recent submit-class or captcha activity (missing input data, dead page
+ # never interacted with) needs no page evidence: accepted immediately, page never sampled.
+ activity = ActivityRecency()
+ fingerprint, fp_calls = _fingerprint_seq(["fp"])
+ tools = [
+ _perception_tool("observe", "url=x text: 'Job not found'"),
+ make_finish_tool(page_fingerprint=fingerprint, activity=activity, settle_wait_seconds=0.0),
+ ]
+ script = [
+ [("observe", {})],
+ [("finish", {"status": "failed", "reason": "the posting does not exist"})],
+ ]
+ outcome, _ = await _run(script, tools, activity=activity)
+ assert outcome.status == "failed"
+ assert outcome.turns == 2
+ assert fp_calls["n"] == 0
+
+
+async def test_recency_window_boundary_arms_at_five_turns_and_expires_at_six() -> None:
+ # Trigger activity expires exactly at the window edge: a click 6 turns back is not gated; the
+ # same click 5 turns back still is. Pins FAILURE_EVIDENCE_WINDOW_TURNS in both directions.
+ contents = [f"url=x step={i}" for i in range(10)]
+
+ activity = ActivityRecency()
+ fingerprint, fp_calls = _fingerprint_seq(["fp"])
+ clicks: list[tuple[str, dict[str, Any]]] = []
+ tools = [
+ _billable_tool("click", clicks),
+ _perception_tool("observe", contents),
+ make_finish_tool(page_fingerprint=fingerprint, activity=activity, settle_wait_seconds=0.0),
+ ]
+ script = (
+ [[("click", {"selector": "#expand"})]]
+ + [[("observe", {})] for _ in range(5)]
+ + [[("finish", {"status": "failed", "reason": "blocked"})]]
+ )
+ outcome, _ = await _run(script, tools, activity=activity)
+ assert outcome.status == "failed"
+ assert fp_calls["n"] == 0
+
+ activity = ActivityRecency()
+ fingerprint, fp_calls = _fingerprint_seq(["fp"])
+ tools = [
+ _billable_tool("click", clicks),
+ _perception_tool("observe", contents),
+ make_finish_tool(page_fingerprint=fingerprint, activity=activity, settle_wait_seconds=0.0),
+ ]
+ script = (
+ [[("click", {"selector": "#expand"})]]
+ + [[("observe", {})] for _ in range(4)]
+ + [
+ [("finish", {"status": "failed", "reason": "blocked"})],
+ [("observe", {})],
+ [("finish", {"status": "failed", "reason": "blocked (re-verified)"})],
+ ]
+ )
+ outcome, _ = await _run(script, tools, activity=activity)
+ assert outcome.status == "failed"
+ assert outcome.reason == "blocked (re-verified)"
+ assert fp_calls["n"] > 0
+
+
+async def test_errored_click_does_not_arm_the_evidence_gate() -> None:
+ # A click that never dispatched cannot have an async tail; only successful clicks (or any
+ # solve_captcha attempt) arm the gate.
+ activity = ActivityRecency()
+ fingerprint, fp_calls = _fingerprint_seq(["fp"])
+ sink: list[tuple[str, dict[str, Any]]] = []
+ click = _recording_tool("click", sink, raises=True)
+ click.billable = True
+ tools = [click, make_finish_tool(page_fingerprint=fingerprint, activity=activity, settle_wait_seconds=0.0)]
+ script = [
+ [("click", {"selector": "#submit"})],
+ [("finish", {"status": "failed", "reason": "could not interact with the page"})],
+ ]
+ outcome, _ = await _run(script, tools, activity=activity)
+ assert outcome.status == "failed"
+ assert fp_calls["n"] == 0
+
+
+async def test_finish_failed_gate_skipped_when_no_page() -> None:
+ # No page to observe (fingerprint samples None): a deferral would burn a turn on an observe
+ # that cannot succeed, so the verdict is accepted as-is.
+ activity = ActivityRecency()
+ fingerprint, _ = _fingerprint_seq([None])
+ clicks: list[tuple[str, dict[str, Any]]] = []
+ tools = [
+ _billable_tool("click", clicks),
+ make_finish_tool(page_fingerprint=fingerprint, activity=activity, settle_wait_seconds=0.0),
+ ]
+ script = [
+ [("click", {"selector": "#submit"})],
+ [("finish", {"status": "failed", "reason": "page lost"})],
+ ]
+ outcome, _ = await _run(script, tools, activity=activity)
+ assert outcome.status == "failed"
+ assert outcome.reason == "page lost"
+
+
+async def test_finish_failed_gate_respects_remaining_turn_budget() -> None:
+ # The corrected-verdict turn needs two turns (observe + re-finish). With no turn budget left
+ # the gate must accept the honest verdict rather than convert it into budget_exhausted.
+ activity = ActivityRecency()
+ fingerprint, fp_calls = _fingerprint_seq(["fp"])
+ clicks: list[tuple[str, dict[str, Any]]] = []
+ tools = [
+ _billable_tool("click", clicks),
+ make_finish_tool(page_fingerprint=fingerprint, activity=activity, settle_wait_seconds=0.0),
+ ]
+ script = [
+ [("click", {"selector": "#submit"})],
+ [("finish", {"status": "failed", "reason": "blocked at the buzzer"})],
+ ]
+ outcome, _ = await _run(script, tools, activity=activity, max_turns=2)
+ assert outcome.status == "failed"
+ assert outcome.reason == "blocked at the buzzer"
+ assert fp_calls["n"] == 0
+
+
+async def test_failure_settle_wait_is_bounded_on_a_never_quiet_page() -> None:
+ # A page that never stops mutating cannot pin the settle wait: the quiescence loop gives up at
+ # its cap and the deferral proceeds, still bounded to one evidence turn overall.
+ activity = ActivityRecency()
+ counter = iter(range(1000))
+
+ async def never_quiet() -> str | None:
+ return f"fp-{next(counter)}"
+
+ clicks: list[tuple[str, dict[str, Any]]] = []
+ tools = [
+ _billable_tool("click", clicks),
+ _perception_tool("observe", _REJECTION_OBSERVE),
+ make_finish_tool(
+ page_fingerprint=never_quiet,
+ activity=activity,
+ settle_wait_seconds=0.01,
+ failure_settle_max_seconds=0.05,
+ ),
+ ]
+ script = [
+ [("click", {"selector": "#submit"})],
+ [("finish", {"status": "failed", "reason": "rejected"})],
+ [("observe", {})],
+ [("finish", {"status": "failed", "reason": "rejected (re-verified)"})],
+ ]
+ started = time.monotonic()
+ outcome, _ = await _run(script, tools, activity=activity)
+ assert outcome.status == "failed"
+ assert outcome.reason == "rejected (re-verified)"
+ assert time.monotonic() - started < 5.0
+
+
+async def test_finish_terminated_after_click_is_never_gated() -> None:
+ # terminate_criterion verdicts stay cheap: terminated never consults the page, even with
+ # trigger activity in the window.
+ activity = ActivityRecency()
+ fingerprint, fp_calls = _fingerprint_seq(["fp"])
+ clicks: list[tuple[str, dict[str, Any]]] = []
+ tools = [
+ _billable_tool("click", clicks),
+ make_finish_tool(page_fingerprint=fingerprint, activity=activity, settle_wait_seconds=0.0),
+ ]
+ script = [
+ [("click", {"selector": "#submit"})],
+ [("finish", {"status": "terminated", "reason": "terminate criterion met"})],
+ ]
+ outcome, _ = await _run(script, tools, activity=activity)
+ assert outcome.status == "terminated"
+ assert fp_calls["n"] == 0
+
+
+async def test_failure_gate_off_without_activity_tracker() -> None:
+ # Fenced like the completed-side probe: without an activity tracker (bare callers) the failure
+ # path keeps its pre-gate behavior — first finish(failed) accepted, page never sampled.
+ fingerprint, fp_calls = _fingerprint_seq(["fp"])
+ clicks: list[tuple[str, dict[str, Any]]] = []
+ tools = [
+ _billable_tool("click", clicks),
+ make_finish_tool(page_fingerprint=fingerprint, settle_wait_seconds=0.0),
+ ]
+ script = [
+ [("click", {"selector": "#submit"})],
+ [("finish", {"status": "failed", "reason": "blocked"})],
+ ]
+ outcome, _ = await _run(script, tools)
+ assert outcome.status == "failed"
+ assert fp_calls["n"] == 0
+
+
+async def test_failure_gate_skips_when_deadline_headroom_is_short() -> None:
+ # A deferral issued near the run deadline cannot complete its observe + re-finish cycle: the
+ # loop would convert the honest verdict into budget_exhausted. With thin deadline headroom the
+ # gate accepts the verdict as-is.
+ activity = ActivityRecency()
+ fingerprint, fp_calls = _fingerprint_seq(["fp"])
+ clicks: list[tuple[str, dict[str, Any]]] = []
+ tools = [
+ _billable_tool("click", clicks),
+ make_finish_tool(
+ page_fingerprint=fingerprint,
+ activity=activity,
+ settle_wait_seconds=0.0,
+ deadline_at=time.monotonic() + 5.0,
+ ),
+ ]
+ script = [
+ [("click", {"selector": "#submit"})],
+ [("finish", {"status": "failed", "reason": "blocked near the deadline"})],
+ ]
+ outcome, _ = await _run(script, tools, activity=activity)
+ assert outcome.status == "failed"
+ assert outcome.reason == "blocked near the deadline"
+ assert fp_calls["n"] == 0
+
+
+async def test_failure_gate_skips_when_tool_call_budget_is_short() -> None:
+ # Same conversion risk on the tool-call cap: the deferral cycle needs the finish + observe +
+ # re-finish calls, so with fewer remaining the verdict is accepted as-is.
+ activity = ActivityRecency()
+ fingerprint, fp_calls = _fingerprint_seq(["fp"])
+ clicks: list[tuple[str, dict[str, Any]]] = []
+ tools = [
+ _billable_tool("click", clicks),
+ make_finish_tool(page_fingerprint=fingerprint, activity=activity, settle_wait_seconds=0.0),
+ ]
+ script = [
+ [("click", {"selector": "#submit"})],
+ [("finish", {"status": "failed", "reason": "blocked with two calls left"})],
+ ]
+ outcome, _ = await _run(script, tools, activity=activity, max_tool_calls=3)
+ assert outcome.status == "failed"
+ assert outcome.reason == "blocked with two calls left"
+ assert fp_calls["n"] == 0
+
+
+async def test_failure_gate_never_trips_the_perception_stall_terminator() -> None:
+ # A deferral-forced observe must never be the identical snapshot that trips the stall
+ # terminator — that would replace the model's accurate failure reason with a generic stall
+ # termination. With the streak one short of the terminator the gate accepts the verdict.
+ activity = ActivityRecency()
+ fingerprint, fp_calls = _fingerprint_seq(["fp"])
+ clicks: list[tuple[str, dict[str, Any]]] = []
+ tools = [
+ _billable_tool("click", clicks),
+ _perception_tool("observe", "url=x frozen behind a gate"),
+ make_finish_tool(page_fingerprint=fingerprint, activity=activity, settle_wait_seconds=0.0),
+ ]
+ script = [
+ [("observe", {})],
+ [("observe", {})],
+ [("click", {"selector": "#submit"})],
+ [("finish", {"status": "failed", "reason": "page is frozen behind a gate"})],
+ ]
+ outcome, _ = await _run(script, tools, activity=activity, stall_terminate_after=3, stall_nudge_after=2)
+ assert outcome.status == "failed"
+ assert outcome.reason == "page is frozen behind a gate"
+ assert fp_calls["n"] == 0
+
+
+async def test_failure_gate_reads_tool_call_budget_per_call_not_per_turn() -> None:
+ # A batched action+finish turn consumes calls after the turn-start snapshot; the gate must read
+ # the refreshed counter or its deferral converts the honest verdict into budget_exhausted.
+ activity = ActivityRecency()
+ fingerprint, fp_calls = _fingerprint_seq(["fp"])
+ clicks: list[tuple[str, dict[str, Any]]] = []
+ tools = [
+ _billable_tool("click", clicks),
+ make_finish_tool(page_fingerprint=fingerprint, activity=activity, settle_wait_seconds=0.0),
+ ]
+ script = [
+ [("click", {"selector": "#a"}), ("click", {"selector": "#b"})],
+ [("click", {"selector": "#submit"}), ("finish", {"status": "failed", "reason": "blocked at the call cap"})],
+ ]
+ outcome, _ = await _run(script, tools, activity=activity, max_tool_calls=5)
+ assert outcome.status == "failed"
+ assert outcome.reason == "blocked at the call cap"
+ assert fp_calls["n"] == 0
+
+
+async def test_failure_gate_skips_when_token_budget_is_short() -> None:
+ # Near the token ceiling the deferral cycle cannot fund its two extra turns; the verdict is
+ # accepted rather than converted into budget_exhausted (max_tokens).
+ activity = ActivityRecency()
+ fingerprint, fp_calls = _fingerprint_seq(["fp"])
+ clicks: list[tuple[str, dict[str, Any]]] = []
+ tools = [
+ _billable_tool("click", clicks),
+ make_finish_tool(page_fingerprint=fingerprint, activity=activity, settle_wait_seconds=0.0),
+ ]
+ script = [
+ [("click", {"selector": "#submit"})],
+ [("finish", {"status": "failed", "reason": "blocked near the token ceiling"})],
+ ]
+ outcome, _ = await _run(script, tools, activity=activity, max_tokens=35)
+ assert outcome.status == "failed"
+ assert outcome.reason == "blocked near the token ceiling"
+ assert fp_calls["n"] == 0
+
+
+async def test_enter_typed_submission_arms_the_evidence_gate_but_plain_typing_does_not() -> None:
+ # An Enter-typed submission (press_enter=true) carries the same async tail as a click; a
+ # plain field fill does not and must stay ungated.
+ activity = ActivityRecency()
+ fingerprint, _ = _fingerprint_seq(["fp"])
+ typed: list[tuple[str, dict[str, Any]]] = []
+ tools = [
+ _billable_tool("type", typed),
+ _perception_tool("observe", _REJECTION_OBSERVE),
+ make_finish_tool(page_fingerprint=fingerprint, activity=activity, settle_wait_seconds=0.0),
+ ]
+ script = [
+ [("type", {"selector": "#q", "text": "answer", "press_enter": True})],
+ [("finish", {"status": "failed", "reason": "rejected"})],
+ [("observe", {})],
+ [("finish", {"status": "failed", "reason": "rejected (re-verified)"})],
+ ]
+ outcome, _ = await _run(script, tools, activity=activity)
+ assert outcome.status == "failed"
+ assert outcome.reason == "rejected (re-verified)"
+
+ activity = ActivityRecency()
+ fingerprint, fp_calls = _fingerprint_seq(["fp"])
+ tools = [
+ _billable_tool("type", typed),
+ make_finish_tool(page_fingerprint=fingerprint, activity=activity, settle_wait_seconds=0.0),
+ ]
+ script = [
+ [("type", {"selector": "#q", "text": "answer"})],
+ [("finish", {"status": "failed", "reason": "missing required data"})],
+ ]
+ outcome, _ = await _run(script, tools, activity=activity)
+ assert outcome.status == "failed"
+ assert fp_calls["n"] == 0
+
+
+async def test_press_key_enter_arms_the_gate_but_escape_does_not() -> None:
+ # Only submit-shaped key presses carry an async submission tail; Escape/Tab/arrows are
+ # navigation and must not buy an evidence check.
+ activity = ActivityRecency()
+ fingerprint, _ = _fingerprint_seq(["fp"])
+ presses: list[tuple[str, dict[str, Any]]] = []
+ tools = [
+ _billable_tool("press_key", presses),
+ _perception_tool("observe", _REJECTION_OBSERVE),
+ make_finish_tool(page_fingerprint=fingerprint, activity=activity, settle_wait_seconds=0.0),
+ ]
+ script = [
+ [("press_key", {"key": "Enter"})],
+ [("finish", {"status": "failed", "reason": "rejected"})],
+ [("observe", {})],
+ [("finish", {"status": "failed", "reason": "rejected (re-verified)"})],
+ ]
+ outcome, _ = await _run(script, tools, activity=activity)
+ assert outcome.status == "failed"
+ assert outcome.reason == "rejected (re-verified)"
+
+ activity = ActivityRecency()
+ fingerprint, fp_calls = _fingerprint_seq(["fp"])
+ tools = [
+ _billable_tool("press_key", presses),
+ make_finish_tool(page_fingerprint=fingerprint, activity=activity, settle_wait_seconds=0.0),
+ ]
+ script = [
+ [("press_key", {"key": "Escape"})],
+ [("finish", {"status": "failed", "reason": "modal would not close"})],
+ ]
+ outcome, _ = await _run(script, tools, activity=activity)
+ assert outcome.status == "failed"
+ assert fp_calls["n"] == 0
+
+
+async def test_deferral_cycle_with_wait_fits_the_reserved_budget() -> None:
+ # The deferral message invites an optional wait before the evidence observe, so the reserved
+ # cycle is wait + observe + re-finish: a deferral granted at the reservation edge must let all
+ # three calls run instead of converting the verdict into budget_exhausted at the cap.
+ activity = ActivityRecency()
+ fingerprint, _ = _fingerprint_seq(["fp"])
+ clicks: list[tuple[str, dict[str, Any]]] = []
+ waits: list[tuple[str, dict[str, Any]]] = []
+ tools = [
+ _billable_tool("click", clicks),
+ _recording_tool("wait", waits),
+ _perception_tool("observe", _REJECTION_OBSERVE),
+ make_finish_tool(page_fingerprint=fingerprint, activity=activity, settle_wait_seconds=0.0),
+ ]
+ script = [
+ [("click", {"selector": "#submit"})],
+ [("finish", {"status": "failed", "reason": "rejected"})],
+ [("wait", {"seconds": 3})],
+ [("observe", {})],
+ [("finish", {"status": "failed", "reason": "rejected (re-verified after wait)"})],
+ ]
+ outcome, _ = await _run(script, tools, activity=activity, max_tool_calls=5)
+ assert outcome.status == "failed"
+ assert outcome.reason == "rejected (re-verified after wait)"
+ assert len(waits) == 1
diff --git a/tests/unit/test_taskv3_tools.py b/tests/unit/test_taskv3_tools.py
index 6a815bf1b..7a1ff9163 100644
--- a/tests/unit/test_taskv3_tools.py
+++ b/tests/unit/test_taskv3_tools.py
@@ -6,7 +6,9 @@ operations (no task-ecosystem) with the right args, without a live browser.
from __future__ import annotations
+import asyncio
import contextlib
+import html
import json
from collections.abc import AsyncIterator
from pathlib import Path
@@ -936,6 +938,205 @@ async def test_observe_reports_aria_pressed_state() -> None:
assert by_sel["#toggle-no"].get("pressed") is True
+# (id, the selector observe must mint for it). Expected selectors are written out rather than
+# recomputed, so the test pins a format instead of mirroring the implementation's own escaping.
+# "-" is minted today as `#\\-`, which document.querySelectorAll accepts (so the in-page uniqueness
+# guard admits it) but Playwright's parser rejects, breaking every consume site.
+_ID_MATRIX_ESCAPED = [
+ ("1abc", '[id="1abc"]'),
+ ("9f2b1e7a-1c3d-4e5f-8a9b-0c1d2e3f4a5b", '[id="9f2b1e7a-1c3d-4e5f-8a9b-0c1d2e3f4a5b"]'),
+ ("42", '[id="42"]'),
+ ("-1abc", '[id="-1abc"]'),
+ ("-", '[id="-"]'),
+ ("a.b", '[id="a.b"]'),
+ ("a:b", '[id="a:b"]'),
+ ("form:panel:input", '[id="form:panel:input"]'),
+ ("a b", '[id="a b"]'),
+ ("a[0]", '[id="a[0]"]'),
+ ('a"b', '[id="a\\"b"]'),
+ ("a\\b", '[id="a\\\\b"]'),
+ # Playwright trims the selector string, and CSS.escape leaves everything above U+007F alone, so
+ # `#email<NBSP>` arrives as `#email` -- which selects the plain `email` element further down.
+ ("email\u00a0", '[id="email\u00a0"]'),
+ ("\u00a0", '[id="\u00a0"]'),
+ ("trailing ", '[id="trailing "]'), # escaped by CSS.escape already; pins that branch, not the trim
+]
+# Ids that keep `#id`. Non-ASCII is not by itself a reason to change form -- accented and CJK ids
+# select fine -- so only whitespace at the ends disqualifies an id, and an interior one is harmless.
+_ID_MATRIX_PLAIN = [
+ ("email", "#email"),
+ ("first-name", "#first-name"),
+ ("_field1", "#_field1"),
+ ("--custom", "#--custom"),
+ ("caf\u00e9", "#caf\u00e9"),
+ ("\u767b\u5f55", "#\u767b\u5f55"),
+ ("a\u00a0b", "#a\u00a0b"),
+ ("\u00a0email", "#\u00a0email"), # behind the `#`, so nothing trims it and the form still works
+]
+_ID_MATRIX = _ID_MATRIX_ESCAPED + _ID_MATRIX_PLAIN
+
+
+def _id_matrix_html() -> str:
+ rows = "".join(
+ f'<input type="text" id="{html.escape(v, quote=True)}" data-probe="{i}">' for i, (v, _) in enumerate(_ID_MATRIX)
+ )
+ return f"<!doctype html><html><body>{rows}</body></html>"
+
+
+@_skip_no_browser
+async def test_observe_mints_selectors_that_resolve_for_every_id_shape() -> None:
+ # Minted selectors are copied by the model into its own tool calls, so a selector that only
+ # looks well-formed is worthless: each one has to select its own element through the same query
+ # paths the tools use. A `#id` selector carrying an escape (`#\31 abc`) does not survive that
+ # trip -- drop the space terminating the hex escape and it addresses a different codepoint.
+ async with _content_page(_id_matrix_html()) as page:
+ by_probe = {e["i"]: e["selector"] for e in (await _observe_data(page))["elements"]}
+ assert len(by_probe) == len(_ID_MATRIX)
+ for i, (elem_id, _) in enumerate(_ID_MATRIX):
+ selector = by_probe[i]
+ if selector.startswith("#"):
+ assert "\\" not in selector, (elem_id, selector)
+ handle = await page.query_selector(selector)
+ assert handle is not None, (elem_id, selector)
+ assert await handle.get_attribute("data-probe") == str(i), (elem_id, selector)
+ # click/fill/press go through Playwright's own selector engine, not querySelector.
+ assert await page.locator(selector).count() == 1, (elem_id, selector)
+
+
+@_skip_no_browser
+async def test_observe_keeps_plain_id_selectors_unchanged() -> None:
+ # Negative control: ids that need no escaping keep the `#id` form byte for byte. Changing the
+ # selector format for ids that already work would be a far wider blast radius than the bug.
+ async with _content_page(_id_matrix_html()) as page:
+ by_probe = {e["i"]: e["selector"] for e in (await _observe_data(page))["elements"]}
+ for i, (elem_id, expected) in enumerate(_ID_MATRIX):
+ assert by_probe[i] == expected, (elem_id, by_probe[i])
+
+
+@_skip_no_browser
+async def test_observe_falls_back_to_a_marker_for_ids_holding_a_raw_line_break() -> None:
+ # A raw line break cannot appear in a CSS string, so these ids get no id selector and take the
+ # marker path. That is the intended trade, not an accident: the `#a\a b` form they used to get
+ # carries the same escape terminator this whole change exists to keep out of the transcript.
+ html_doc = (
+ '<!doctype html><html><body><input type="text" data-probe="0"><input type="text" data-probe="1"></body></html>'
+ )
+ async with _content_page(html_doc) as page:
+ await page.evaluate(
+ "() => document.querySelectorAll('input').forEach((el, i) => { el.id = 'a' + (i ? '\\r' : '\\n') + 'b'; })"
+ )
+ for element in (await _observe_data(page))["elements"]:
+ assert element["selector"].startswith("[data-tv3="), element
+ assert await page.locator(element["selector"]).count() == 1, element
+
+
+# A form exposes its named controls as its own properties, so <input name="X"> inside a form makes
+# form.X that input rather than whatever it normally is. Every one of these is read while building
+# an element record, and the read happens inside page.evaluate.
+_CLOBBERABLE = ["id", "name", "tagName", "getAttribute", "getBoundingClientRect", "innerText", "closest"]
+
+
+@_skip_no_browser
[email protected]("clobbered", _CLOBBERABLE)
+async def test_observe_survives_a_form_that_clobbers_a_property_it_reads(clobbered: str) -> None:
+ # One such element used to throw out of page.evaluate and take the whole element list with it,
+ # so the agent lost perception entirely -- and on static markup it never got it back.
+ html_doc = (
+ "<!doctype html><html><body>"
+ f'<form role="button" id="real"><input name="{clobbered}" data-probe="0"><span>x</span></form>'
+ '<input id="other" data-probe="1">'
+ "</body></html>"
+ )
+ async with _content_page(html_doc) as page:
+ elements = (await _observe_data(page))["elements"]
+ assert any(e["selector"] == "#other" for e in elements), elements
+ for element in elements:
+ assert await page.locator(element["selector"]).count() == 1, element
+
+
+@_skip_no_browser
+async def test_observe_markers_are_not_collided_by_a_marker_the_page_already_carries() -> None:
+ # Uniqueness alone let a page pre-seed the marker the counter was about to mint, giving two
+ # elements the same selector. Playwright's page-level click takes the first match, so the agent
+ # would act on the wrong control with nothing to indicate it.
+ html_doc = (
+ "<!doctype html><html><body>"
+ '<div role="button" data-tv3="t0" data-probe="0">A</div>'
+ '<div role="button" data-probe="1">B</div>'
+ "</body></html>"
+ )
+ async with _content_page(html_doc) as page:
+ elements = (await _observe_data(page))["elements"]
+ selectors = [e["selector"] for e in elements]
+ assert len(set(selectors)) == len(selectors), selectors
+ for element in elements:
+ handle = await page.query_selector(element["selector"])
+ assert await handle.get_attribute("data-probe") == str(element["i"]), element
+
+
+# Each stops `window.__tv3_next++` from making progress while still looking like a plain integer.
+_FROZEN_COUNTERS = [
+ "window.__tv3_next = 1e21",
+ "window.__tv3_next = 9007199254740992",
+ "Object.defineProperty(window, '__tv3_next', {value: 0, writable: false})",
+]
+
+
+@_skip_no_browser
[email protected]("tamper", _FROZEN_COUNTERS)
+async def test_observe_still_mints_distinct_markers_when_the_counter_cannot_advance(tamper: str) -> None:
+ # Searching for a free marker used to loop until it found one, so a counter that cannot advance
+ # spun the renderer's main thread forever -- not just failing this observe but killing the page
+ # for the rest of the run, since nothing else on it can run again either.
+ async with _content_page(
+ '<!doctype html><html><body><div role="button">A</div><div role="button">B</div></body></html>'
+ ) as page:
+ await page.evaluate(f"() => {{ {tamper}; }}")
+ selectors = [e["selector"] for e in (await asyncio.wait_for(_observe_data(page), timeout=10))["elements"]]
+ assert len(selectors) == 2, selectors
+ assert len(set(selectors)) == 2, selectors
+
+
+@_skip_no_browser
+async def test_observe_still_sees_elements_when_the_page_removes_css_escape() -> None:
+ # CSS.escape is page-removable and sits on the path of every element carrying an id, so losing
+ # it emptied the whole element list -- and an empty list reads as "this page has no controls"
+ # rather than as a failure. It costs the `#id` shorthand now, not the elements.
+ async with _content_page('<!doctype html><html><body><input id="9start"><input id="a b"></body></html>') as page:
+ await page.evaluate("() => { window.CSS = null; }")
+ data = await _observe_data(page)
+ assert [e["selector"] for e in data["elements"]] == ['[id="9start"]', '[id="a b"]']
+ assert not data.get("dropped")
+
+
+@_skip_no_browser
+async def test_observe_selectors_cannot_be_aimed_at_another_element_by_page_markup() -> None:
+ # An unescaped quote in a page-controlled attribute closes the selector and continues it as a
+ # selector list, which still matches exactly one element -- so the uniqueness guard passes and
+ # the agent is handed a selector for the element the page chose.
+ breakout = 'x"] , [id="victim'
+ html_doc = (
+ "<!doctype html><html><body>"
+ f'<input data-testid="{html.escape(breakout, quote=True)}" data-probe="0">'
+ f'<textarea name="{html.escape(breakout, quote=True)}" data-probe="1"></textarea>'
+ '<input id="victim" data-probe="2">'
+ "</body></html>"
+ )
+ async with _content_page(html_doc) as page:
+ for element in (await _observe_data(page))["elements"]:
+ handle = await page.query_selector(element["selector"])
+ assert handle is not None, element
+ assert await handle.get_attribute("data-probe") == str(element["i"]), element
+
+
@pytest.mark.asyncio
async def test_observe_renders_text_digest_and_pressed_state() -> None:
class _DigestPage(_FakePage):
diff --git a/tests/unit/test_wait_block_invalid_time.py b/tests/unit/test_wait_block_invalid_time.py
new file mode 100644
index 000000000..388449dce
--- /dev/null
+++ b/tests/unit/test_wait_block_invalid_time.py
@@ -0,0 +1,148 @@
+"""Regression tests for ``InvalidWaitBlockTime`` (SKY-14616).
+
+An out-of-range wait block is client input, but the exception subclassed plain
+``SkyvernException``, so both HTTP entry paths reported it as a 5xx. These assert the status
+code rather than that something raised: ``pytest.raises(InvalidWaitBlockTime)`` alone passes
+against the unfixed code, because which class is raised is the entire defect.
+"""
+
+from __future__ import annotations
+
+import datetime as dt
+import importlib
+from typing import Any
+
+import pytest
+from fastapi import FastAPI, Request
+from fastapi.responses import JSONResponse
+from fastapi.testclient import TestClient
+
+from skyvern.config import settings
+from skyvern.exceptions import SkyvernHTTPException
+from skyvern.forge import app as forge_app
+from skyvern.forge.sdk.routes.routers import base_router
+from skyvern.forge.sdk.schemas.organizations import Organization
+from skyvern.forge.sdk.services import org_auth_service
+from skyvern.forge.sdk.workflow.exceptions import (
+ InvalidWaitBlockTime,
+ WorkflowDefinitionValidationException,
+)
+from skyvern.forge.sdk.workflow.models.block import WaitBlock
+from skyvern.forge.sdk.workflow.workflow_definition_converter import convert_workflow_definition
+from skyvern.schemas.workflows import WaitBlockYAML, WorkflowDefinitionYAML
+
+ORG_ID = "o_test"
+BLOCK_LABEL = "let_page_settle"
+
+# The copilot route validates the string as a bare WorkflowDefinitionYAML, not a create request.
+WAIT_BLOCK_YAML = """
+parameters: []
+blocks:
+ - block_type: wait
+ label: let_page_settle
+ wait_sec: 0
+"""
+
+
+def _definition(wait_sec: int) -> WorkflowDefinitionYAML:
+ return WorkflowDefinitionYAML(
+ parameters=[],
+ blocks=[WaitBlockYAML(label=BLOCK_LABEL, wait_sec=wait_sec)],
+ )
+
+
+def _make_org() -> Organization:
+ now = dt.datetime.now(dt.timezone.utc)
+ return Organization(
+ organization_id=ORG_ID,
+ organization_name="Test Org",
+ created_at=now,
+ modified_at=now,
+ )
+
+
[email protected]("wait_sec", [0, -1, settings.WORKFLOW_WAIT_BLOCK_MAX_SEC + 1])
+def test_out_of_range_wait_is_a_422_validation_error(wait_sec: int) -> None:
+ with pytest.raises(InvalidWaitBlockTime) as excinfo:
+ convert_workflow_definition(_definition(wait_sec), workflow_id="wf_test")
+
+ exc = excinfo.value
+ # The class is the whole defect: the create route keys its 422 branch off this base, and the
+ # copilot route keys its 400 branch off BaseWorkflowHTTPException, which this now inherits.
+ assert isinstance(exc, WorkflowDefinitionValidationException)
+ assert exc.status_code == 422
+
+ message = str(exc.message)
+ assert BLOCK_LABEL in message
+ # Anchored to the preceding word: a bare `str(wait_sec) in message` passes vacuously for 0,
+ # which also appears inside "1800".
+ assert f"wait time {wait_sec}" in message
+ assert f"between 1 and {settings.WORKFLOW_WAIT_BLOCK_MAX_SEC}" in message
+
+
[email protected]("wait_sec", [1, settings.WORKFLOW_WAIT_BLOCK_MAX_SEC])
+def test_in_range_wait_still_converts(wait_sec: int) -> None:
+ converted = convert_workflow_definition(_definition(wait_sec), workflow_id="wf_test")
+
+ block = converted.blocks[0]
+ assert isinstance(block, WaitBlock)
+ assert block.wait_sec == wait_sec
+
+
+class _ConvertOnlyWorkflowService:
+ """Stands in for the DB round trips the create route makes before conversion, so the real
+ converter still raises and the assertion stays on the route's own dispatch."""
+
+ async def create_workflow_from_request(self, *, organization: Any, request: Any, **kwargs: Any) -> Any:
+ convert_workflow_definition(request.workflow_definition, workflow_id="wf_test")
+ raise AssertionError("conversion was expected to reject the wait block")
+
+
[email protected](scope="module")
+def client() -> TestClient:
+ importlib.import_module("skyvern.forge.sdk.routes.agent_protocol")
+ importlib.import_module("skyvern.forge.sdk.routes.workflow_copilot")
+
+ app = FastAPI()
+ app.include_router(base_router, prefix="/v1")
+
+ # Mirror api_app.py, so a SkyvernHTTPException renders as its own status code. Without this
+ # the pre-fix FailedToCreateWorkflow would surface as an unhandled error rather than its 500.
+ @app.exception_handler(SkyvernHTTPException)
+ async def _handle_skyvern_http_exception(request: Request, exc: SkyvernHTTPException) -> JSONResponse:
+ return JSONResponse(status_code=exc.status_code, content={"detail": exc.message})
+
+ app.dependency_overrides[org_auth_service.get_current_org] = _make_org
+ app.dependency_overrides[org_auth_service.get_current_user_id_or_none] = lambda: None
+
+ return TestClient(app)
+
+
+def test_create_workflow_route_returns_422(client: TestClient, monkeypatch: pytest.MonkeyPatch) -> None:
+ monkeypatch.setattr(forge_app, "WORKFLOW_SERVICE", _ConvertOnlyWorkflowService())
+
+ resp = client.post(
+ "/v1/workflows",
+ json={
+ "json_definition": {
+ "title": "Wait block regression",
+ "workflow_definition": {
+ "parameters": [],
+ "blocks": [{"block_type": "wait", "label": BLOCK_LABEL, "wait_sec": 0}],
+ },
+ }
+ },
+ )
+
+ assert resp.status_code == 422, resp.text
+ assert BLOCK_LABEL in resp.json()["detail"]
+
+
+def test_copilot_convert_yaml_route_returns_400(client: TestClient) -> None:
+ resp = client.post(
+ "/v1/workflow/copilot/convert-yaml-to-blocks",
+ json={"workflow_definition_yaml": WAIT_BLOCK_YAML, "workflow_id": "wf_test"},
+ )
+
+ assert resp.status_code == 400, resp.text
+ assert BLOCK_LABEL in resp.json()["detail"]
diff --git a/tests/unit/webeye/test_screenshot_load_state_nonfatal.py b/tests/unit/webeye/test_screenshot_load_state_nonfatal.py
index 43312e5d9..a08e53f97 100644
--- a/tests/unit/webeye/test_screenshot_load_state_nonfatal.py
+++ b/tests/unit/webeye/test_screenshot_load_state_nonfatal.py
@@ -2,6 +2,8 @@
from __future__ import annotations
+import sys
+import types
from unittest.mock import AsyncMock, MagicMock
import pytest
@@ -11,6 +13,7 @@ from playwright._impl._errors import TimeoutError as PlaywrightTimeoutError
from playwright.async_api import Page
from skyvern.exceptions import FailedToTakeScreenshot, ScreenshotTargetClosed
+from skyvern.webeye import browser_driver_errors
from skyvern.webeye.browser_engine import BrowserEngineSelection
from skyvern.webeye.browser_errors import BrowserAutomationError, BrowserTargetClosedError
from skyvern.webeye.utils import page as page_module
@@ -256,3 +259,108 @@ class TestScreenshotTargetClosedClassification:
await _current_viewpoint_screenshot_helper(page)
assert type(exc_info.value) is FailedToTakeScreenshot
+
+
+def second_driver_package(monkeypatch: pytest.MonkeyPatch) -> tuple[type[Exception], type[Exception]]:
+ """Model the browser image's two live Playwright-family driver packages: a persistent session's
+ pages are driven by the package this module's imports were NOT rewritten to, so they raise error
+ classes with a different identity."""
+
+ class _ForkError(Exception):
+ pass
+
+ class _ForkTimeout(_ForkError):
+ pass
+
+ api = types.ModuleType("patchright.async_api")
+ api.Error = _ForkError # type: ignore[attr-defined]
+ api.TimeoutError = _ForkTimeout # type: ignore[attr-defined]
+ package = types.ModuleType("patchright")
+ package.async_api = api # type: ignore[attr-defined]
+ monkeypatch.setitem(sys.modules, "patchright", package)
+ monkeypatch.setitem(sys.modules, "patchright.async_api", api)
+
+ error_types, timeout_types = browser_driver_errors._load_driver_error_types()
+ monkeypatch.setattr(browser_driver_errors, "DRIVER_ERROR_TYPES", error_types)
+ monkeypatch.setattr(browser_driver_errors, "DRIVER_TIMEOUT_ERROR_TYPES", timeout_types)
+ return _ForkError, _ForkTimeout
+
+
+class TestSecondDriverPackageClassification:
+ @pytest.mark.asyncio
+ async def test_timeout_uses_timeout_arm(
+ self, second_driver_package: tuple[type[Exception], type[Exception]]
+ ) -> None:
+ _, fork_timeout = second_driver_package
+ page = _make_page(b"image-bytes")
+ error = fork_timeout("Page.screenshot: Timeout 30000ms exceeded")
+ page.screenshot = AsyncMock(side_effect=error)
+ log = MagicMock()
+
+ with pytest.raises(FailedToTakeScreenshot) as exc_info:
+ with pytest.MonkeyPatch.context() as monkeypatch:
+ monkeypatch.setattr(page_module, "LOG", log)
+ await _current_viewpoint_screenshot_helper(page)
+
+ assert exc_info.value.__cause__ is error
+ log.warning.assert_called_once()
+ log.error.assert_not_called()
+
+ @pytest.mark.asyncio
+ async def test_target_close_uses_target_closed_arm(
+ self, second_driver_package: tuple[type[Exception], type[Exception]]
+ ) -> None:
+ fork_error, _ = second_driver_package
+ page = _make_page(b"image-bytes")
+ error = fork_error("Page.screenshot: Target page, context or browser has been closed")
+ page.screenshot = AsyncMock(side_effect=error)
+ log = MagicMock()
+
+ with pytest.raises(ScreenshotTargetClosed) as exc_info:
+ with pytest.MonkeyPatch.context() as monkeypatch:
+ monkeypatch.setattr(page_module, "LOG", log)
+ await _current_viewpoint_screenshot_helper(page)
+
+ assert exc_info.value.__cause__ is error
+ log.info.assert_called_once()
+ log.error.assert_not_called()
+
+
+class TestScrollingScreenshotClosedTargetFallback:
+ """``take_scrolling_screenshot`` falls back to a whole-page Playwright capture when the scrolling
+ merge fails. That fallback screenshots the same page, so a closed target can only fail again --
+ once with a WARNING traceback here, once more from the fallback's own classification.
+ """
+
+ def _rig(self, monkeypatch: pytest.MonkeyPatch, error: Exception) -> tuple[MagicMock, AsyncMock, MagicMock]:
+ page = _make_page(b"image-bytes")
+ monkeypatch.setattr(page_module, "_scrolling_screenshots_helper", AsyncMock(side_effect=error))
+ fallback = AsyncMock(return_value=b"fallback-bytes")
+ monkeypatch.setattr(page_module, "_current_viewpoint_screenshot_helper", fallback)
+ frame = MagicMock()
+ frame.get_scroll_x_y = AsyncMock(return_value=(0, 120))
+ frame.safe_scroll_to_x_y = AsyncMock()
+ monkeypatch.setattr(page_module.SkyvernFrame, "create_instance", AsyncMock(return_value=frame))
+ return page, fallback, frame
+
+ @pytest.mark.asyncio
+ async def test_closed_target_skips_the_doomed_fallback(self, monkeypatch: pytest.MonkeyPatch) -> None:
+ error = ScreenshotTargetClosed(error_message="Page is closed")
+ page, fallback, frame = self._rig(monkeypatch, error)
+
+ with pytest.raises(ScreenshotTargetClosed) as exc_info:
+ await page_module.SkyvernFrame.take_scrolling_screenshot(page, scrolling_number=2)
+
+ assert exc_info.value is error
+ fallback.assert_not_awaited()
+ frame.safe_scroll_to_x_y.assert_not_awaited()
+
+ @pytest.mark.asyncio
+ async def test_other_failures_still_fall_back(self, monkeypatch: pytest.MonkeyPatch) -> None:
+ page, fallback, frame = self._rig(monkeypatch, RuntimeError("merge failed"))
+
+ result = await page_module.SkyvernFrame.take_scrolling_screenshot(page, scrolling_number=2)
+
+ assert result == b"fallback-bytes"
+ fallback.assert_awaited_once()
diff --git a/tests/unit/workflow/test_block_browser_state_recovery.py b/tests/unit/workflow/test_block_browser_state_recovery.py
index 615e8670c..0796f0522 100644
--- a/tests/unit/workflow/test_block_browser_state_recovery.py
+++ b/tests/unit/workflow/test_block_browser_state_recovery.py
@@ -439,3 +439,57 @@ async def test_reconnect_stops_fresh_driver_when_state_rebuild_fails(monkeypatch
# A failed rebuild must stop both drivers so it never orphans the freshly started one.
fresh_pw.stop.assert_awaited_once()
stale_pw.stop.assert_awaited_once()
+
+
+async def test_requested_close_logs_disconnect_at_info_not_warning(monkeypatch: pytest.MonkeyPatch) -> None:
+ # The end-of-run teardown closes the context on purpose; observing that close is diagnostic
+ # context, not a warning. A close nobody requested still warns.
+ from skyvern.webeye import real_browser_state as real_browser_state_module
+
+ log = MagicMock()
+ monkeypatch.setattr(real_browser_state_module, "LOG", log)
+ monkeypatch.setattr(real_browser_state_module, "disable_download_interceptor_for_context", AsyncMock())
+
+ async def _skip_phase(coro, timeout, description): # type: ignore[no-untyped-def]
+ coro.close()
+ return True
+
+ context = MagicMock(browser=MagicMock())
+ state = RealBrowserState(pw=MagicMock(), browser_context=context)
+ monkeypatch.setattr(state, "_run_bounded_detachable", _skip_phase)
+ monkeypatch.setattr(state, "_run_browser_cleanup_bounded", AsyncMock())
+ monkeypatch.setattr(state, "_stop_driver_bounded", AsyncMock())
+
+ await state.close()
+ state._on_browser_context_closed(context)
+
+ log.warning.assert_not_called()
+ assert [c for c in log.info.call_args_list if c.args[0] == "Browser state disconnected"]
+ assert state.get_browser_state_diagnostic() is not None
+
+ unrequested = RealBrowserState(pw=MagicMock(), browser_context=MagicMock(browser=MagicMock()))
+ unrequested._on_browser_context_closed(unrequested.browser_context)
+
+ log.warning.assert_called_once()
+ assert log.warning.call_args.args[0] == "Browser state disconnected"
+
+
+async def test_keep_alive_close_does_not_downgrade_a_later_disconnect(monkeypatch: pytest.MonkeyPatch) -> None:
+ # close(close_browser_on_completion=False) keeps the browser for reuse, so a disconnect that
+ # follows it is nobody's request and must still warn.
+ from skyvern.webeye import real_browser_state as real_browser_state_module
+
+ log = MagicMock()
+ monkeypatch.setattr(real_browser_state_module, "LOG", log)
+
+ context = MagicMock(browser=MagicMock())
+ state = RealBrowserState(pw=MagicMock(), browser_context=context)
+ monkeypatch.setattr(state, "_stop_driver_bounded", AsyncMock())
+
+ await state.close(close_browser_on_completion=False, release_driver=False)
+ state._on_browser_context_closed(context)
+
+ log.warning.assert_called_once()
+ assert log.warning.call_args.args[0] == "Browser state disconnected"
diff --git a/tests/unit_tests/test_streaming_screencast.py b/tests/unit_tests/test_streaming_screencast.py
index a641d15b8..430fd9e15 100644
--- a/tests/unit_tests/test_streaming_screencast.py
+++ b/tests/unit_tests/test_streaming_screencast.py
@@ -1,8 +1,10 @@
from __future__ import annotations
import asyncio
+import contextlib
+from collections.abc import Callable
from types import SimpleNamespace
-from unittest.mock import AsyncMock, Mock
+from unittest.mock import ANY, AsyncMock, Mock
import pytest
@@ -219,6 +221,7 @@ class _FakeCdpSession:
def __init__(self) -> None:
self.handlers: dict[str, object] = {}
self.sent: list[tuple[str, dict]] = []
+ self.detached = False
def on(self, event: str, handler: object) -> None:
self.handlers[event] = handler
@@ -230,7 +233,10 @@ class _FakeCdpSession:
return {}
async def detach(self) -> None:
- return None
+ self.detached = True
+
+ def methods_sent(self) -> list[str]:
+ return [method for method, _ in self.sent]
class _FakePage:
@@ -240,6 +246,14 @@ class _FakePage:
self.viewport_size = {"width": 800, "height": 600}
+async def _wait_for(predicate: Callable[[], bool]) -> bool:
+ for _ in range(500):
+ if predicate():
+ return True
+ await asyncio.sleep(0.01)
+ return False
+
+
@pytest.mark.asyncio
async def test_forwarded_frame_is_acked_and_records_forward_latency(monkeypatch: pytest.MonkeyPatch) -> None:
session = _FakeCdpSession()
@@ -339,3 +353,311 @@ async def test_evicted_frame_records_queue_dwell(monkeypatch: pytest.MonkeyPatch
await asyncio.wait_for(loop_task, timeout=5)
assert [payload["screenshot"] for payload in sent] == ["primed", "frame-2", "frame-3"]
+
+
+async def test_a_page_that_cannot_be_attached_does_not_kill_the_running_stream(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ current_session = _FakeCdpSession()
+ current_page = _FakePage(current_session)
+ next_session = _FakeCdpSession()
+ next_page = _FakePage(next_session)
+ attach_fails = True
+
+ async def _new_cdp_session(_page: object) -> _FakeCdpSession:
+ if attach_fails:
+ raise RuntimeError("Target closed")
+ return next_session
+
+ next_page.context.new_cdp_session = AsyncMock(side_effect=_new_cdp_session)
+ monkeypatch.setattr(screencast, "ACTIVE_PAGE_POLL_INTERVAL", 0.01)
+ # Cap the backoff too: a slow runner could otherwise spend long enough failing to attach
+ # that the poll interval grows past this test's own wait budget.
+ monkeypatch.setattr(screencast, "ACTIVE_PAGE_MAX_POLL_INTERVAL", 0.05)
+
+ pages = iter([current_page])
+
+ async def _resolve_working_page(*_args: object, **_kwargs: object) -> object:
+ return next(pages, next_page)
+
+ monkeypatch.setattr(screencast, "_resolve_working_page", _resolve_working_page)
+
+ sent: list[dict] = []
+
+ async def _send_json(payload: dict) -> None:
+ sent.append(payload)
+ if payload["screenshot"] == "frame-from-next-page":
+ raise RuntimeError("client gone")
+
+ websocket = SimpleNamespace(send_json=_send_json)
+
+ async def _never_finalized() -> bool:
+ return False
+
+ loop_task = asyncio.create_task(
+ screencast.start_screencast_loop(websocket, object(), "pbs_1", "browser_session", _never_finalized)
+ )
+ assert await _wait_for(lambda: bool(next_page.context.new_cdp_session.await_count))
+
+ assert current_session.detached is False
+ assert "Page.stopScreencast" not in current_session.methods_sent()
+ current_session.handlers["Page.screencastFrame"](
+ {"data": "frame-from-current-page", "sessionId": 7, "metadata": {}}
+ )
+ assert await _wait_for(lambda: any(payload["screenshot"] == "frame-from-current-page" for payload in sent))
+
+ attach_fails = False
+ assert await _wait_for(lambda: "Page.startScreencast" in next_session.methods_sent())
+ assert await _wait_for(lambda: current_session.detached)
+ next_session.handlers["Page.screencastFrame"]({"data": "frame-from-next-page", "sessionId": 9, "metadata": {}})
+ await asyncio.wait_for(loop_task, timeout=5)
+
+ assert [payload["screenshot"] for payload in sent] == [
+ "primed",
+ "frame-from-current-page",
+ "primed",
+ "frame-from-next-page",
+ ]
+
+
+class _FramesDuringStartSession(_FakeCdpSession):
+ """Emits a frame before Page.startScreencast returns, i.e. before the loop can adopt it."""
+
+ async def send(self, method: str, params: dict | None = None) -> dict:
+ result = await super().send(method, params)
+ if method == "Page.startScreencast":
+ self.handlers["Page.screencastFrame"]({"data": "mid-swap", "sessionId": 11, "metadata": {}})
+ await asyncio.sleep(0)
+ return result
+
+
+async def test_a_frame_that_lands_mid_swap_is_still_acked(monkeypatch: pytest.MonkeyPatch) -> None:
+ session = _FramesDuringStartSession()
+ page = _FakePage(session)
+ monkeypatch.setattr(screencast, "_resolve_working_page", AsyncMock(return_value=page))
+
+ sent: list[dict] = []
+
+ async def _send_json(payload: dict) -> None:
+ sent.append(payload)
+ raise RuntimeError("client gone")
+
+ async def _never_finalized() -> bool:
+ return False
+
+ await asyncio.wait_for(
+ screencast.start_screencast_loop(
+ SimpleNamespace(send_json=_send_json), object(), "pbs_1", "browser_session", _never_finalized
+ ),
+ timeout=5,
+ )
+
+ # Chrome stops producing frames for a session whose frames go unacked, so the ack has to happen
+ # even though the frame arrived too early to be forwarded.
+ assert ("Page.screencastFrameAck", {"sessionId": 11}) in session.sent
+ assert [payload["screenshot"] for payload in sent] == ["primed"]
+
+
+_REAL_SLEEP = asyncio.sleep
+
+
+class _VirtualClock:
+ """Instant sleeps over a virtual monotonic clock, recorded per calling task.
+
+ Grouping by task keeps the completion poller's one sleep out of the page monitor's sequence.
+ """
+
+ def __init__(self, stop_after: int) -> None:
+ self.by_task: dict[int, list[float]] = {}
+ self.now = 0.0
+ self._stop_after = stop_after
+ self.parked = asyncio.Event()
+
+ def monotonic(self) -> float:
+ return self.now
+
+ async def sleep(self, delay: float) -> None:
+ recorded = self.by_task.setdefault(id(asyncio.current_task()), [])
+ recorded.append(delay)
+ self.now += delay
+ if len(recorded) >= self._stop_after:
+ self.parked.set()
+ await asyncio.Event().wait()
+ await _REAL_SLEEP(0)
+
+ @property
+ def poll_delays(self) -> list[float]:
+ return max(self.by_task.values(), key=len, default=[])
+
+
+def _scripted_pages(*script: object):
+ """Resolve pages in order, then hold the final entry forever."""
+ remaining = list(script)
+
+ async def _resolve(*args: object, **kwargs: object) -> object:
+ return remaining.pop(0) if len(remaining) > 1 else remaining[0]
+
+ return _resolve
+
+
+async def _drive_page_monitor(
+ monkeypatch: pytest.MonkeyPatch,
+ clock: _VirtualClock,
+ *script: object,
+ entity_id: str = "pbs_1",
+ entity_type: str = "browser_session",
+ **loop_kwargs: object,
+) -> asyncio.Task:
+ monkeypatch.setattr(screencast, "_resolve_working_page", _scripted_pages(*script))
+ monkeypatch.setattr(screencast.asyncio, "sleep", clock.sleep)
+ monkeypatch.setattr(screencast, "time", SimpleNamespace(monotonic=clock.monotonic))
+
+ async def _never_finalized() -> bool:
+ await asyncio.Event().wait()
+ return False
+
+ task = asyncio.create_task(
+ screencast.start_screencast_loop(
+ SimpleNamespace(send_json=AsyncMock()),
+ object(),
+ entity_id,
+ entity_type,
+ _never_finalized,
+ **loop_kwargs,
+ )
+ )
+ await asyncio.wait_for(clock.parked.wait(), timeout=5)
+ return task
+
+
+async def _stop(task: asyncio.Task) -> None:
+ # Cancelling start_screencast_loop mid-wait leaves its child tasks running, so drain them too.
+ task.cancel()
+ for pending in asyncio.all_tasks() - {asyncio.current_task()}:
+ pending.cancel()
+ with contextlib.suppress(BaseException):
+ await pending
+
+
+def _messages(calls: list, message: str) -> list:
+ return [call for call in calls if call.args and call.args[0] == message]
+
+
+async def test_page_poll_holds_the_fast_cadence_then_backs_off_and_clamps(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ """Ordinary page-less gaps clear in a few seconds, so the fast cadence is held past them; only a
+ wedged viewer reaches the backoff, and it must stop doubling at the ceiling rather than growing."""
+ clock = _VirtualClock(stop_after=16)
+ task = await _drive_page_monitor(monkeypatch, clock, _FakePage(_FakeCdpSession()), None)
+
+ try:
+ assert clock.poll_delays == [0.5] * 9 + [1.0, 2.0, 4.0, 8.0, 16.0, 30.0, 30.0]
+ finally:
+ await _stop(task)
+
+
+async def test_degraded_entry_is_reported_exactly_once(monkeypatch: pytest.MonkeyPatch) -> None:
+ """The whole point of the bound: one wedged viewer used to log on every poll."""
+ log = Mock()
+ monkeypatch.setattr(screencast, "LOG", log)
+ clock = _VirtualClock(stop_after=60)
+ task = await _drive_page_monitor(
+ monkeypatch,
+ clock,
+ _FakePage(_FakeCdpSession()),
+ None,
+ entity_id="pbs_1",
+ entity_type="browser_session",
+ organization_id="o_1",
+ )
+
+ try:
+ entries = _messages(log.warning.call_args_list, "Live view cannot follow the active page; backing off")
+ assert len(clock.poll_delays) == 60
+ assert len(entries) == 1
+ assert entries[0].kwargs["browser_session_id"] == "pbs_1"
+ assert entries[0].kwargs["entity_id"] == "pbs_1"
+ assert entries[0].kwargs["entity_type"] == "browser_session"
+ assert entries[0].kwargs["organization_id"] == "o_1"
+ assert entries[0].kwargs["degraded_for_seconds"] == 4.0
+ finally:
+ await _stop(task)
+
+
+async def test_a_page_appearing_mid_backoff_recovers_and_reports_the_degraded_duration(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ log = Mock()
+ monkeypatch.setattr(screencast, "LOG", log)
+ clock = _VirtualClock(stop_after=15)
+ recovered = _FakePage(_FakeCdpSession())
+ task = await _drive_page_monitor(
+ monkeypatch,
+ clock,
+ _FakePage(_FakeCdpSession()),
+ *([None] * 12),
+ recovered,
+ )
+
+ try:
+ recoveries = _messages(log.info.call_args_list, "Live view is following the active page again")
+ assert len(recoveries) == 1
+ # Empty from t=0.5 until the page came back at t=19.5, across the 0.5->8.0 backoff.
+ assert recoveries[0].kwargs["degraded_for_seconds"] == 19.0
+ assert recoveries[0].kwargs["browser_session_id"] == "pbs_1"
+ # The screencast re-attached to the page that came back, and the fast cadence resumed.
+ assert ("Page.startScreencast", ANY) in recovered.context.new_cdp_session.return_value.sent
+ assert clock.poll_delays[13:] == [0.5, 0.5]
+ finally:
+ await _stop(task)
+
+
+async def test_the_page_monitor_survives_a_long_degraded_stretch(monkeypatch: pytest.MonkeyPatch) -> None:
+ """Backing off is not giving up: the viewer stays connected so a page that returns is followed."""
+ clock = _VirtualClock(stop_after=200)
+ task = await _drive_page_monitor(monkeypatch, clock, _FakePage(_FakeCdpSession()), None)
+
+ try:
+ assert not task.done()
+ assert len(clock.poll_delays) == 200
+ assert set(clock.poll_delays[20:]) == {30.0}
+ finally:
+ await _stop(task)
+
+
+class _UnattachablePage:
+ """Resolves fine, but every attempt to open a CDP session on it fails."""
+
+ def __init__(self) -> None:
+ self.context = SimpleNamespace(new_cdp_session=AsyncMock(side_effect=RuntimeError("cdp session refused")))
+ self.url = "https://example.test/"
+ self.viewport_size = {"width": 800, "height": 600}
+
+
+async def test_a_page_that_never_attaches_backs_off_like_a_missing_one(monkeypatch: pytest.MonkeyPatch) -> None:
+ """A page the viewer cannot attach to is as dead as no page: without this the loop would sit at
+ 2 Hz forever on a failing attach, which is the pathology the backoff exists to stop."""
+ log = Mock()
+ monkeypatch.setattr(screencast, "LOG", log)
+ clock = _VirtualClock(stop_after=12)
+ task = await _drive_page_monitor(
+ monkeypatch,
+ clock,
+ _FakePage(_FakeCdpSession()),
+ _UnattachablePage(),
+ )
+
+ try:
+ assert clock.poll_delays == [0.5] * 9 + [1.0, 2.0, 4.0]
+ entries = _messages(log.warning.call_args_list, "Live view cannot follow the active page; backing off")
+ assert len(entries) == 1
+ finally:
+ await _stop(task)