Automate browser based workflows with AI
Python aiapiautomationbrowserbrowser-automationcomputergptllmplaywrightpowerautomatepuppeteerpythonrpaseleniumvisionworkflow
Make skyvern.com agent-readable: OAuth discovery, markdown negotiation, rate-limit headers, MCP manifest (#8283)
Cindy Li9cc1138657c6
diff --git a/docs/api-reference/openapi.json b/docs/api-reference/openapi.jsonindex 6bc92e5ca..9582729e9 100644--- a/docs/api-reference/openapi.json+++ b/docs/api-reference/openapi.json@@ -3005,7 +3005,8 @@"tags": ["agent"],- "summary": "Get Runs V2",+ "summary": "List runs",+ "description": "List the organization's task and agent runs, newest first, filterable by status, run type, agent, and a free-text search term. Returns a paginated array of run summaries.","operationId": "get_runs_v2_v1_runs_get","parameters": [{@@ -3197,7 +3198,8 @@"tags": ["Files"],- "summary": "Upload File",+ "summary": "Upload a file",+ "description": "Upload a file to Skyvern storage so runs can reference it as an input. Returns the file id, its storage URI, a presigned download URL, and the expiry implied by the requested retention period.","operationId": "upload_file_v1_upload_file_post","parameters": [{@@ -5810,6 +5812,7 @@"Schedules"],"summary": "List all schedules for the organization",+ "description": "List every schedule in the organization, across all agents, filterable by active/paused status and a search term matched against agent title or schedule name. Returns a paginated list plus the total count.","operationId": "schedules_list_all","parameters": [{@@ -6851,6 +6854,7 @@"Agents"],"summary": "Get an agent by id",+ "description": "Fetch a single agent definition by its permanent id, optionally pinned to a specific version. Returns the agent's blocks, parameters, and metadata.","operationId": "get_workflow_v1_workflows__workflow_permanent_id__get","parameters": [{@@ -7080,6 +7084,7 @@"Schedules"],"summary": "Create a schedule for an agent",+ "description": "Create a cron schedule that runs the given agent automatically with a fixed set of parameters. Returns the stored schedule and its next upcoming run times.","operationId": "schedules_create","parameters": [{@@ -7148,6 +7153,7 @@"Schedules"],"summary": "List schedules for an agent",+ "description": "List all schedules attached to a single agent. Returns the schedules in creation order.","operationId": "schedules_list","parameters": [{@@ -7208,6 +7214,7 @@"Schedules"],"summary": "Get an agent schedule by id",+ "description": "Fetch one schedule belonging to an agent. Returns the schedule's cron expression, timezone, parameters, enabled state, and next upcoming run times.","operationId": "schedules_get","parameters": [{@@ -7275,6 +7282,7 @@"Schedules"],"summary": "Update an agent schedule",+ "description": "Replace a schedule's cron expression, timezone, run parameters, and enabled state. Returns the updated schedule and its next upcoming run times.","operationId": "schedules_update","parameters": [{@@ -7352,6 +7360,7 @@"Schedules"],"summary": "Delete an agent schedule",+ "description": "Permanently delete a schedule so it never triggers again. Returns an acknowledgement flag.","operationId": "schedules_delete","parameters": [{@@ -7421,6 +7430,7 @@"Schedules"],"summary": "Enable an agent schedule",+ "description": "Resume a paused schedule so it starts triggering runs again. Returns the updated schedule.","operationId": "schedules_enable","parameters": [{@@ -7490,6 +7500,7 @@"Schedules"],"summary": "Disable an agent schedule",+ "description": "Pause a schedule so it stops triggering runs, without deleting it. Returns the updated schedule.","operationId": "schedules_disable","parameters": [{diff --git a/docs/cloud/account-settings/api-keys.mdx b/docs/cloud/account-settings/api-keys.mdxindex 9fa63b6e3..929490765 100644--- a/docs/cloud/account-settings/api-keys.mdx+++ b/docs/cloud/account-settings/api-keys.mdx@@ -55,6 +55,13 @@ Store the key in an environment variable (`SKYVERN_API_KEY`) rather than hardcod>Full endpoint documentation with interactive playground</Card>+ <Card+ title="Authentication & Permissions"+ icon="shield-check"+ href="/cloud/account-settings/authentication-and-permissions"+ >+ What an API key can reach, OAuth scopes, and how to isolate access+ </Card><Cardtitle="Billing & Usage"icon="receipt"diff --git a/docs/cloud/account-settings/api-versioning-and-deprecation.mdx b/docs/cloud/account-settings/api-versioning-and-deprecation.mdxnew file mode 100644index 000000000..077e3a63e--- /dev/null+++ b/docs/cloud/account-settings/api-versioning-and-deprecation.mdx@@ -0,0 +1,18 @@+---+title: API Versioning & Deprecation+subtitle: How the API is versioned and how changes reach you+description: Skyvern's API versioning scheme (URL path /v1/), what counts as a backward-compatible change, and the deprecation policy - 6 months minimum notice, Deprecation and Sunset response headers, and changelog announcements.+slug: cloud/account-settings/api-versioning-and-deprecation+keywords:+ - API versioning+ - deprecation policy+ - sunset+ - breaking changes+ - backward compatibility+ - v1+ - changelog+---++import ApiVersioningContent from "/snippets/api-versioning-content.mdx";++<ApiVersioningContent />diff --git a/docs/cloud/account-settings/authentication-and-permissions.mdx b/docs/cloud/account-settings/authentication-and-permissions.mdxnew file mode 100644index 000000000..5d9f6350e--- /dev/null+++ b/docs/cloud/account-settings/authentication-and-permissions.mdx@@ -0,0 +1,22 @@+---+title: Authentication & Permissions+subtitle: What your API key and OAuth tokens can access+description: How Skyvern scopes access - organization-scoped API keys sent as x-api-key, OAuth 2.0 browser sign-in and its supported scopes, the hosted MCP server, and how to isolate access between environments and teams.+slug: cloud/account-settings/authentication-and-permissions+keywords:+ - authentication+ - authorization+ - permissions+ - scopes+ - API key+ - x-api-key+ - OAuth 2.0+ - bearer token+ - MCP+ - organization+ - access control+---++import ApiPermissionsContent from "/snippets/api-permissions-content.mdx";++<ApiPermissionsContent />diff --git a/docs/developers/api/authentication-and-permissions.mdx b/docs/developers/api/authentication-and-permissions.mdxnew file mode 100644index 000000000..191a670d3--- /dev/null+++ b/docs/developers/api/authentication-and-permissions.mdx@@ -0,0 +1,23 @@+---+title: Authentication & Permissions+subtitle: API keys, OAuth 2.0 scopes, and how access is scoped+description: How Skyvern API access is scoped - organization-scoped API keys sent as x-api-key, OAuth 2.0 with browser sign-in and its supported scopes, the hosted MCP server, and what each credential can reach.+slug: developers/api/authentication-and-permissions+keywords:+ - authentication+ - authorization+ - permissions+ - scopes+ - API key+ - x-api-key+ - OAuth 2.0+ - bearer token+ - PKCE+ - MCP+ - organization+ - least privilege+---++import ApiPermissionsContent from "/snippets/api-permissions-content.mdx";++<ApiPermissionsContent />diff --git a/docs/developers/api/versioning-and-deprecation.mdx b/docs/developers/api/versioning-and-deprecation.mdxnew file mode 100644index 000000000..6c67f6d3c--- /dev/null+++ b/docs/developers/api/versioning-and-deprecation.mdx@@ -0,0 +1,22 @@+---+title: Versioning & Deprecation+subtitle: How the REST API is versioned and how changes are announced+description: Skyvern's REST API versioning scheme (URL path /v1/), what counts as a backward-compatible change, and the deprecation policy - 6 months minimum notice, Deprecation and Sunset response headers per RFC 9745 and RFC 8594, and changelog announcements.+slug: developers/api/versioning-and-deprecation+keywords:+ - API versioning+ - deprecation policy+ - sunset+ - Deprecation header+ - Sunset header+ - RFC 8594+ - RFC 9745+ - breaking changes+ - backward compatibility+ - v1+ - changelog+---++import ApiVersioningContent from "/snippets/api-versioning-content.mdx";++<ApiVersioningContent />diff --git a/docs/docs.json b/docs/docs.jsonindex da984f269..88440e956 100644--- a/docs/docs.json+++ b/docs/docs.json@@ -124,6 +124,8 @@"group": "Account & Settings","pages": ["cloud/account-settings/api-keys",+ "cloud/account-settings/authentication-and-permissions",+ "cloud/account-settings/api-versioning-and-deprecation","cloud/account-settings/billing-usage","cloud/account-settings/organization-settings","cloud/account-settings/profile-settings"@@ -195,6 +197,13 @@"developers/going-to-production/reliability-tips"]},+ {+ "group": "API Access",+ "pages": [+ "developers/api/authentication-and-permissions",+ "developers/api/versioning-and-deprecation"+ ]+ },{"group": "Debugging","pages": [diff --git a/docs/llms.txt b/docs/llms.txtindex 31997ac89..6a285583e 100644--- a/docs/llms.txt+++ b/docs/llms.txt@@ -49,6 +49,11 @@- [Error Handling](https://skyvern.com/docs/developers/going-to-production/error-handling.md): Detect, classify, and recover from task failures; retry strategies, cancel runs, and webhook error payloads- [Reliability Tips](https://skyvern.com/docs/developers/going-to-production/reliability-tips.md): Write robust prompts, handle edge cases, and build resilient automations that work across website changes+## API Access++- [Authentication & Permissions](https://skyvern.com/docs/developers/api/authentication-and-permissions.md): How API access is scoped; organization-scoped API keys sent as x-api-key, OAuth 2.0 browser sign-in and its supported scopes, the hosted MCP server at https://api.skyvern.com/mcp, and what each credential can reach+- [Versioning & Deprecation](https://skyvern.com/docs/developers/api/versioning-and-deprecation.md): REST API versioning scheme (URL path /v1/), what counts as a backward-compatible change, and the deprecation policy; 6 months minimum notice, Deprecation and Sunset response headers per RFC 9745 and RFC 8594, and changelog announcements+## Debugging- [Using Artifacts](https://skyvern.com/docs/developers/debugging/using-artifacts.md): Access recordings, screenshots, action logs, and network data for every rundiff --git a/docs/snippets/api-permissions-content.mdx b/docs/snippets/api-permissions-content.mdxnew file mode 100644index 000000000..e410b661e--- /dev/null+++ b/docs/snippets/api-permissions-content.mdx@@ -0,0 +1,128 @@+Every Skyvern credential is scoped to **one organization**. There are two ways to authenticate, and both resolve to the same thing: full API access on behalf of that organization.++| Method | Credential | How you send it | Best for |+| --- | --- | --- | --- |+| API key | Long-lived organization key | `x-api-key` header | Servers, CI, SDKs, scripts |+| OAuth 2.0 | Access token from browser sign-in, refreshable | `Authorization: Bearer` header | MCP clients and AI assistants, apps acting for a signed-in user |++## API keys++An API key is an organization-scoped bearer credential. Send it in the `x-api-key` header:++```bash+curl -X POST "https://api.skyvern.com/v1/run/tasks" \+ -H "x-api-key: YOUR_API_KEY" \+ -H "Content-Type: application/json" \+ -d '{ "url": "https://example.com", "prompt": "Extract the pricing table" }'+```++Find and copy your key from **Settings** in the Cloud dashboard, or at [app.skyvern.com/settings](https://app.skyvern.com/settings).++### What an API key can do++The key identifies the organization it belongs to. Authorization is at that granularity and no finer:++- It can call **every** documented endpoint that the organization can reach — create and cancel runs, read run history and artifacts, create and delete workflows, manage browser sessions and profiles, and read and write stored credentials.+- Usage and cost are metered to that organization.+- It carries no expiry of its own; it is valid until revoked.++<Warning>+There are no read-only keys, per-endpoint keys, or per-resource keys today. Any API key grants full organization-level authority, so treat one like a root password: store it in a secrets manager, never commit it, and never ship it to a browser or mobile client.+</Warning>++### Isolating access++Because scoping is per organization, the organization is the isolation boundary. To separate access:++- Use **separate organizations** for separate blast radii — production versus staging, or one per customer or per team.+- Rotate keys from **Settings** when someone with access leaves or a key may have leaked. Revoking a key immediately invalidates every client using it, including OAuth tokens issued against it.+- Put outbound results behind [webhooks](/developers/going-to-production/webhooks) with signature verification rather than handing a key to a third party so it can poll.+++## OAuth 2.0++Skyvern Cloud is an OAuth 2.0 authorization server, backed by Clerk. It exists so MCP clients and AI assistants can authenticate a human with a browser sign-in instead of asking them to paste a static key into a config file.++Discovery metadata is public:++```bash+curl https://api.skyvern.com/.well-known/oauth-authorization-server+curl https://api.skyvern.com/.well-known/oauth-protected-resource+```++| Property | Value |+| --- | --- |+| Issuer | `https://clerk.skyvern.com` |+| Authorization endpoint | `https://api.skyvern.com/oauth/authorize` |+| Token endpoint | `https://api.skyvern.com/oauth/token` |+| Revocation endpoint | `https://clerk.skyvern.com/oauth/token/revoke` |+| Dynamic client registration | `https://clerk.skyvern.com/oauth/register` |+| Grant types | `authorization_code`, `refresh_token` |+| Response types | `code` |+| PKCE | `S256` required |+| Protected resource | `https://api.skyvern.com/mcp` |+| Bearer methods | `header` |++Clients that support MCP OAuth discovery — Claude Code, Claude Desktop, Cursor, Codex CLI, ChatGPT — need no client ID or client secret in their config; they register dynamically and open a browser for sign-in. See the [MCP server setup guide](/developers/getting-started/mcp) for per-client commands.++### Supported scopes++The authorization server advertises these `scopes_supported`:++| Scope | Meaning |+| --- | --- |+| `openid` | OpenID Connect sign-in; issue an ID token |+| `profile` | Basic profile claims (name) |+| `email` | Email address claim |+| `public_metadata` | Public user metadata claims |+| `private_metadata` | Private user metadata claims |+| `offline_access` | Issue a refresh token so the client can stay connected |+| `user:org:read` | Read the signed-in user's organization membership |++The protected-resource metadata for the MCP server narrows the advertised set to `profile` and `email`.++<Warning>+These are **identity scopes, not API permission scopes.** They describe which claims about the signed-in user the token carries. They do not restrict which Skyvern endpoints or tools the token can reach.+</Warning>++Once the authorization code is exchanged, the resulting access token authorizes as the organization the signed-in user belongs to, with the same organization-wide authority as an API key. Requesting fewer scopes does not produce a more restricted token. Access tokens expire and are refreshable with `offline_access`; a refresh token is single-use and rotated on every exchange, and replaying an old one revokes the whole token family. Revoking the organization's API key also invalidates tokens issued against it.++## MCP server++The hosted Model Context Protocol server is at **`https://api.skyvern.com/mcp`**. It accepts either credential:++- OAuth: `Authorization: Bearer <access_token>`+- API key: `x-api-key: YOUR_API_KEY`++You can narrow the **tool list** a client sees, either with a scoped URL or a header:++```bash+# Scoped URL+https://api.skyvern.com/mcp/x/operate++# Or the default URL plus a header+X-Skyvern-Scope: operate+```++Valid values are `operate`, `build`, `browser`, `lean`, and `all`. Omitting the scope is identical to `all`.++<Note>+Tool scopes are a **usability filter, not an authorization boundary.** They change which tools the server advertises, so a smaller scope means a smaller, sharper tool list for the model — but the request still authenticates with the same organization-wide credential. Do not rely on a narrow scope to prevent a client from taking an action.+</Note>++## Summary of the scoping model++- **Organization** is the only authorization boundary. Every credential is bound to exactly one, and grants full access within it.+- **API keys** are org-scoped bearer credentials with no sub-scopes, sent as `x-api-key`.+- **OAuth scopes** control identity claims about the signed-in user, not API reach.+- **MCP tool scopes** control the advertised tool catalog, not permissions.+- To limit what a credential can touch, create a separate organization.++<CardGroup cols={2}>+ <Card title="API Key" icon="key" href="/cloud/account-settings/api-keys">+ Find, copy, and rotate your key in the Cloud dashboard+ </Card>+ <Card title="MCP Server" icon="plug" href="/developers/getting-started/mcp">+ Per-client OAuth and API-key setup for the hosted MCP server+ </Card>+</CardGroup>diff --git a/docs/snippets/api-versioning-content.mdx b/docs/snippets/api-versioning-content.mdxnew file mode 100644index 000000000..b19ab4010--- /dev/null+++ b/docs/snippets/api-versioning-content.mdx@@ -0,0 +1,95 @@+Skyvern's REST API is versioned in the URL path. The current and only supported version is **v1**, served from `https://api.skyvern.com/v1/`.++```bash+curl -X POST "https://api.skyvern.com/v1/run/tasks" \+ -H "x-api-key: YOUR_API_KEY" \+ -H "Content-Type: application/json" \+ -d '{ "url": "https://example.com", "prompt": "Extract the pricing table" }'+```++## How versioning works++The major version appears once, as the first path segment. It never appears in a header, query parameter, or `Accept` media type.++| Change type | How it ships |+| --- | --- |+| Backward-compatible change | Released into `v1` with no new version and no client action required |+| Breaking change | Released under a new path prefix (`/v2/`), with `v1` kept alive through the deprecation window below |++Skyvern does not use date-based or header-negotiated versions. If your client pins `https://api.skyvern.com/v1`, no deployment we make will change the shape of a response you already depend on.++## What counts as backward compatible++Treat the following as expected within `v1`, and make sure your client tolerates them:++- New endpoints and new HTTP methods on existing paths+- New optional request parameters and request body fields+- New fields in response bodies+- New values in existing enums (for example, a new run status or failure reason)+- New or reworded human-readable `detail` strings on error responses+- Changes to the ordering of JSON object keys or of items in an unordered collection++The practical rule: **ignore unknown fields rather than failing on them**, and treat an unrecognized enum value as "something newer than my client" instead of an error.++## What we will not do inside v1++These are breaking changes. They only ship in a new major version, never into `v1`:++- Removing or renaming an endpoint, a request field, or a response field+- Changing the type or format of an existing field+- Making an optional parameter required, or adding a new required parameter+- Removing a value from an enum+- Changing the HTTP status code or error code for an existing failure mode+- Changing the authentication a route requires++## Stability guarantees by surface++| Surface | Stability |+| --- | --- |+| `https://api.skyvern.com/v1/*` | Stable and covered by this policy. Described by the [OpenAPI specification](/api-reference/openapi.json) |+| `/api/v1/*`, `/api/v2/*` | Legacy compatibility paths. Excluded from the OpenAPI specification and from this policy. Do not build new integrations on them; use `/v1/` |+| Official SDKs (Python, TypeScript) | Semantic versioning, generated from the same OpenAPI specification. A major SDK bump can accompany an API major version |+| MCP server (`https://api.skyvern.com/mcp`) | Tool names and arguments follow the same compatibility rules as `v1` endpoints |+| Undocumented endpoints and fields | Anything absent from the OpenAPI specification and these docs is internal and may change without notice |++## Deprecation and sunset policy++When we do deprecate part of the API, this is what you can count on:++- **At least 6 months notice.** That is the minimum time between the deprecation announcement and the sunset date on which the endpoint stops serving traffic. Removing an entire major version gets at least 12 months.+- **A changelog announcement** on the [Skyvern changelog](/changelog), naming the affected endpoints, the replacement, and the sunset date.+- **Machine-readable response headers** on every response from a deprecated endpoint, following [RFC 9745](https://www.rfc-editor.org/rfc/rfc9745.html) (`Deprecation`) and [RFC 8594](https://www.rfc-editor.org/rfc/rfc8594.html) (`Sunset`).+- **`deprecated: true` in the OpenAPI specification** for the affected operation, parameter, or schema field, so generated clients and API tooling surface the warning automatically.+- **No silent removals.** An endpoint that has not been announced, header-flagged, and given its full notice window will not be turned off.++A response from a deprecated endpoint looks like this:++```http+HTTP/1.1 200 OK+Deprecation: @1767225600+Sunset: Wed, 01 Jul 2026 00:00:00 GMT+Link: <https://skyvern.com/docs/changelog>; rel="deprecation"; type="text/html"+```++`Deprecation` carries the moment the endpoint became deprecated, `Sunset` the moment it stops responding, and the `Link` header points at the announcement explaining the migration.++<Note>+No `/v1` endpoint is deprecated today, so these headers are not present on any current response. The two deprecations in flight are field-level and documented in place: the `title` query parameter on `GET /v1/agents` (use `search_key`) and `publish_workflow` on task creation.+</Note>++## Building a client that survives changes++- Pin the version prefix (`/v1/`), not a specific SDK patch release.+- Parse responses leniently: ignore unknown fields, default unknown enum values to a safe branch.+- Log any response carrying a `Deprecation` or `Sunset` header, and alert on it — that header is the earliest programmatic signal you will get.+- Watch the [changelog](/changelog) for announcements, and diff the [OpenAPI specification](/api-reference/openapi.json) in CI if you generate your own client.++## Where changes are announced++| Channel | What it carries |+| --- | --- |+| [Changelog](/changelog) | Weekly entries: new features, improvements, fixes, and every deprecation announcement |+| [OpenAPI specification](/api-reference/openapi.json) | The authoritative machine-readable contract, including `deprecated` flags |+| `Deprecation` / `Sunset` headers | Per-request signal on any deprecated endpoint |++Questions about a migration: [[email protected]](mailto:[email protected]).diff --git a/skyvern-frontend/src/components/BrowserStream.tsx b/skyvern-frontend/src/components/BrowserStream.tsxindex a41b0d623..9e34a41ad 100644--- a/skyvern-frontend/src/components/BrowserStream.tsx+++ b/skyvern-frontend/src/components/BrowserStream.tsx@@ -21,18 +21,12 @@ import { toast } from "@/components/ui/use-toast";import { useCredentialGetter } from "@/hooks/useCredentialGetter";import { useRecordingElapsedSeconds } from "@/hooks/useRecordingElapsedSeconds";import { statusIsNotFinalized } from "@/routes/tasks/types";-import { buildOptimisticStep } from "@/routes/workflows/editor/recording/optimisticSteps";-import { useClientIdStore } from "@/store/useClientIdStore";import {useRecordingStore,countVisibleDraftSteps,- type ExfiltratedEventConsoleParams,- type MessageInExfiltratedEvent,- type RecordingInterpretationUpdate,} from "@/store/useRecordingStore";import { useSettingsStore } from "@/store/SettingsStore";-import { wssBaseUrl, newWssBaseUrl, getCredentialParam } from "@/util/env";-import { copyText } from "@/util/copyText";+import { wssBaseUrl, newWssBaseUrl } from "@/util/env";import { formatRecordingClock } from "@/util/recordingClock";import { installNoVncGestureCrashGuard } from "@/util/novncGestureCrashGuard";import { cn } from "@/util/utils";@@ -44,6 +38,8 @@ import {handleVncClipboardPasteShortcut,type HeldMetaSides,} from "@/components/browserStreamClipboard";+import { useRecordingMessageChannel } from "@/routes/streaming/useRecordingMessageChannel";+import { useWebSocketParams } from "@/routes/streaming/webSocketParams";import "./browser-stream.css";@@ -66,87 +62,6 @@ interface BrowserSession {completed_at?: string | null;}-interface CommandBeginExfiltration {- kind: "begin-exfiltration";- workflow_permanent_id?: string;- live_interpretation_enabled?: boolean;- // Declares that this client understands delta interpretation updates, so the- // backend may send changed_steps instead of full snapshots.- supports_interpretation_deltas?: boolean;- // Per-recording id: stable across reconnects, new per recording, so the- // backend reuses the session on reconnect but starts fresh on a new recording.- recording_attempt_id?: string;-}--interface CommandCedeControl {- kind: "cede-control";-}--interface CommandEndExfiltration {- kind: "end-exfiltration";-}--interface CommandTakeControl {- kind: "take-control";-}--interface CommandRecordingCapturePause {- kind: "recording-capture-pause";-}--interface CommandRecordingCaptureResume {- kind: "recording-capture-resume";-}--interface CommandRecordingRearmCapture {- kind: "recording-rearm-capture";-}--// a "Command" is an fire-n-forget out-message - it does not require a response-type Command =- | CommandBeginExfiltration- | CommandCedeControl- | CommandEndExfiltration- | CommandRecordingCapturePause- | CommandRecordingCaptureResume- | CommandRecordingRearmCapture- | CommandTakeControl;--const messageInKinds = [- "ask-for-clipboard",- "copied-text",- "exfiltrated-event",- "recording-interpretation-update",-] as const;--type MessageInKind = (typeof messageInKinds)[number];--interface MessageInAskForClipboard {- kind: "ask-for-clipboard";-}--interface MessageInCopiedText {- kind: "copied-text";- text: string;-}--interface MessageInRecordingInterpretationUpdate extends RecordingInterpretationUpdate {- kind: "recording-interpretation-update";-}--type MessageIn =- | MessageInCopiedText- | MessageInAskForClipboard- | MessageInExfiltratedEvent- | MessageInRecordingInterpretationUpdate;--interface MessageOutAskForClipboardResponse {- kind: "ask-for-clipboard-response";- text: string;-}--type MessageOut = MessageOutAskForClipboardResponse;-type Props = {browserSessionId?: string;exfiltrate?: boolean;@@ -329,7 +244,6 @@ function BrowserStream({const [hasBrowserSession, setHasBrowserSession] = useState(true); // be optimisticconst [isBrowserSessionStarted, setIsBrowserSessionStarted] = useState(false);const [userIsControlling, setUserIsControlling] = useState(false);- const [messageSocket, setMessageSocket] = useState<WebSocket | null>(null);const [vncDisconnectedTrigger, setVncDisconnectedTrigger] = useState(0);const [isVncConnected, setIsVncConnected] = useState<boolean>(false);const [isCanvasReady, setIsCanvasReady] = useState<boolean>(false);@@ -339,7 +253,6 @@ function BrowserStream({const [messagesDisconnectedTrigger, setMessagesDisconnectedTrigger] =useState(0);const prevMessageConnectedRef = useRef<boolean>(false);- const [isMessageConnected, setIsMessageConnected] = useState<boolean>(false);const [canvasContainer, setCanvasContainer] = useState<HTMLDivElement | null>(null,);@@ -358,14 +271,70 @@ function BrowserStream({const messageReconnectTimerRef = useRef<ReturnType<typeof setTimeout> | null>(null,);- const clientId = useClientIdStore((state) => state.clientId);const isRecording = useRecordingStore((state) => state.isRecording);+ const workflowPermanentId = useRecordingStore(+ (state) => state.workflowPermanentId,+ );const settingsStore = useSettingsStore();const credentialGetter = useCredentialGetter();+ const getWebSocketParams = useWebSocketParams();const isBrowserSessionAvailable =entity !== "browserSession" || hasBrowserSession;const isBrowserSessionBackendReady =entity !== "browserSession" || isBrowserSessionStarted;+ const getFrameDataUrl = useCallback(() => {+ const canvas = canvasContainer?.querySelector("canvas");+ return canvas?.toDataURL("image/jpeg", 0.5) ?? null;+ }, [canvasContainer]);+ const handleMessageConnectionChange = useCallback(+ (connected: boolean, event?: CloseEvent) => {+ if (connected) {+ setTerminalDiagnostic(null);+ return;+ }+ if (!event) {+ return;+ }+ const { code, reason } = event;+ setTerminalDiagnostic(+ (prev) =>+ prev ??+ (code === 1006+ ? {+ title: "The messages channel slipped away",+ detail: "The messages channel dropped before sending a frame.",+ hint: "Check that the API server is reachable from the UI.",+ }+ : {+ title: "The messages channel packed up and left",+ detail: `Messages channel closed with code ${code}${reason ? ` (${reason})` : ""}.`,+ }),+ );+ },+ [],+ );+ const legacyMessageSocketUrl =+ entity === "task" && runId+ ? `${wssBaseUrl}/stream/messages/task/${runId}`+ : entity === "workflow" && runId+ ? `${wssBaseUrl}/stream/messages/workflow_run/${runId}`+ : undefined;+ const { isMessageConnected, sendCommand } = useRecordingMessageChannel({+ browserSessionId: runId,+ enabled:+ showStream &&+ Boolean(canvasContainer) &&+ Boolean(runId) &&+ isBrowserSessionAvailable &&+ isBrowserSessionBackendReady,+ exfiltrate,+ workflowPermanentId,+ getFrameDataUrl,+ clipboard: "vnc",+ socketUrl: legacyMessageSocketUrl,+ reconnectTrigger: messagesDisconnectedTrigger,+ onConnectionChange: handleMessageConnectionChange,+ });useEffect(() => {onActivityRef.current = onActivity;@@ -376,7 +345,6 @@ function BrowserStream({setIsReady(false);setIsVncConnected(false);setIsCanvasReady(false);- setIsMessageConnected(false);setHasBrowserSession(true);setTerminalDiagnostic(null);messageReconnectAttemptsRef.current = 0;@@ -390,14 +358,6 @@ function BrowserStream({}}, [browserSessionId]);- const getWebSocketParams = useCallback(async () => {- const params = new URLSearchParams(- await getCredentialParam(credentialGetter),- );- params.set("client_id", clientId);- return params.toString();- }, [clientId, credentialGetter]);-// browser is readyuseEffect(() => {setIsReady(@@ -656,122 +616,12 @@ function BrowserStream({);}, [vncInteractive]);- useEffect(() => {- if (!showStream || !canvasContainer || !runId) {- return;- }-- let ws: WebSocket | null = null;- let cancelled = false;-- const connect = async () => {- const wsParams = await getWebSocketParams();-- const messageUrl =- entity === "browserSession"- ? `${newWssBaseUrl}/stream/messages/browser_session/${runId}?${wsParams}`- : entity === "task"- ? `${wssBaseUrl}/stream/messages/task/${runId}?${wsParams}`- : entity === "workflow"- ? `${wssBaseUrl}/stream/messages/workflow_run/${runId}?${wsParams}`- : null;-- if (!messageUrl) {- throw new Error("No message url");- }-- if (!isBrowserSessionAvailable || !isBrowserSessionBackendReady) {- setIsMessageConnected(false);- return;- }-- ws = new WebSocket(messageUrl);-- ws.onopen = () => {- setIsMessageConnected(true);- setMessageSocket(ws);- setTerminalDiagnostic(null);- };-- ws.onmessage = (event) => {- const data = event.data;-- try {- const message = JSON.parse(data);-- handleMessage(message, ws);-- // handle incoming messages if needed- } catch (e) {- console.error(- "Error parsing message from message channel:",- e,- event,- );- }- };-- ws.onclose = (event) => {- setIsMessageConnected(false);- setMessageSocket(null);- if (cancelled) return;- const { code, reason } = event;- setTerminalDiagnostic(- (prev) =>- prev ??- (code === 1006- ? {- title: "The messages channel slipped away",- detail:- "The messages channel dropped before sending a frame.",- hint: "Check that the API server is reachable from the UI.",- }- : {- title: "The messages channel packed up and left",- detail: `Messages channel closed with code ${code}${reason ? ` (${reason})` : ""}.`,- }),- );- };- };-- connect();-- return () => {- cancelled = true;- try {- ws && ws.close();- } catch (e) {- // pass- }- };- // NOTE: adding getWebSocketParams causes constant reconnects of message channel when,- // for instance, take-control or cede-control is clicked- // eslint-disable-next-line react-hooks/exhaustive-deps- }, [- browserSessionId,- canvasContainer,- messagesDisconnectedTrigger,- entity,- isBrowserSessionAvailable,- isBrowserSessionBackendReady,- runId,- showStream,- ]);-// effect to send a message when the user is controlling, vs not controllinguseEffect(() => {if (!isMessageConnected) {return;}- const sendCommand = (command: Command) => {- if (!messageSocket) {- return;- }-- messageSocket.send(JSON.stringify(command));- };-if (interactive || userIsControlling) {sendCommand({ kind: "take-control" });} else {@@ -830,74 +680,6 @@ function BrowserStream({}}, [task, workflow]);- const { workflowPermanentId, recordingAttemptId } = useRecordingStore(- useShallow((state) => ({- workflowPermanentId: state.workflowPermanentId,- recordingAttemptId: state.recordingAttemptId,- })),- );-- // effect for exfiltration- useEffect(() => {- const sendCommand = (command: Command) => {- if (!messageSocket) {- return;- }-- messageSocket.send(JSON.stringify(command));- };-- if (exfiltrate) {- // Including a workflow id turns on backend live interpretation: the- // server streams recording-interpretation-update draft step snapshots- // back over this same socket while the user records.- sendCommand({- kind: "begin-exfiltration",- workflow_permanent_id: workflowPermanentId ?? undefined,- live_interpretation_enabled: Boolean(workflowPermanentId),- // Client capability: the backend only emits per-step delta updates- // (changed_steps upserted by step_id) to clients that declare support;- // otherwise it falls back to full snapshots.- supports_interpretation_deltas: true,- // Stable across reconnects of this recording; a new recording mints a- // new id so the backend starts a fresh interpretation session.- recording_attempt_id: recordingAttemptId ?? undefined,- });- } else {- sendCommand({ kind: "end-exfiltration" });- }- }, [exfiltrate, messageSocket, workflowPermanentId, recordingAttemptId]);-- const manualCapturePaused = useRecordingStore(- (state) => state.manualCapturePaused,- );- const draftEditDepth = useRecordingStore((state) => state.draftEditDepth);- const capturePaused = manualCapturePaused || draftEditDepth > 0;- const previousCapturePausedRef = useRef(false);-- // Pause exfiltration + live interpretation while the operator edits drafts- // or explicitly pauses capture.- useEffect(() => {- if (!exfiltrate || !messageSocket) {- // Backend pause state is per exfiltration session, so start the next- // session's edge detection from "not paused". A recording that ended- // while paused would otherwise fire a spurious resume on the next start;- // and if capture IS paused on a mid-recording reconnect, this re-sends- // the pause to the new socket (idempotent) instead of assuming it.- previousCapturePausedRef.current = false;- return;- }-- const wasPaused = previousCapturePausedRef.current;- if (!wasPaused && capturePaused) {- messageSocket.send(JSON.stringify({ kind: "recording-capture-pause" }));- } else if (wasPaused && !capturePaused) {- messageSocket.send(JSON.stringify({ kind: "recording-capture-resume" }));- }-- previousCapturePausedRef.current = capturePaused;- }, [capturePaused, exfiltrate, messageSocket]);-useEffect(() => {if (!interactive) {setUserIsControlling(false);@@ -1013,282 +795,9 @@ function BrowserStream({return;}- const sendCommand = (command: Command) => {- if (!messageSocket) {- return;- }-- messageSocket.send(JSON.stringify(command));- };-sendCommand({ kind: "take-control" });setUserIsControlling(true);- }, [isRecording, isMessageConnected, messageSocket]);-- /**- * TODO(jdo): could use zod or smth similar- */- const getMessage = (data: unknown): MessageIn | undefined => {- if (!data) {- return;- }-- if (typeof data !== "object") {- return;- }-- if (!("kind" in data)) {- return;- }-- const k = data.kind;-- if (typeof k !== "string") {- return;- }-- if (!messageInKinds.includes(k as MessageInKind)) {- return;- }-- const kind = k as MessageInKind;-- switch (kind) {- case "ask-for-clipboard": {- return data as MessageInAskForClipboard;- }- case "copied-text": {- if ("text" in data && typeof data.text === "string") {- return {- kind: "copied-text",- text: data.text,- };- }- break;- }- case "exfiltrated-event": {- if (- "event_name" in data &&- typeof data.event_name === "string" &&- "params" in data &&- typeof data.params === "object" &&- data.params !== null &&- "source" in data &&- typeof data.source === "string"- ) {- const event = data as MessageInExfiltratedEvent;-- return {- kind: "exfiltrated-event",- event_name: event.event_name,- params: event.params,- source: event.source,- timestamp: event.timestamp,- } as MessageInExfiltratedEvent;- }- break;- }- case "recording-interpretation-update": {- // steps is optional: a delta update carries changed_steps instead. Only- // session_revision is required to accept the message.- if (- "session_revision" in data &&- typeof data.session_revision === "number"- ) {- const update = data as MessageInRecordingInterpretationUpdate;- return {- kind: "recording-interpretation-update",- interpretation_session_id:- typeof update.interpretation_session_id === "string"- ? update.interpretation_session_id- : "",- session_revision: update.session_revision,- steps: Array.isArray(update.steps) ? update.steps : [],- changed_steps: Array.isArray(update.changed_steps)- ? update.changed_steps- : [],- // Absent/true => full snapshot (legacy). Only false triggers delta merge.- is_snapshot:- typeof update.is_snapshot === "boolean"- ? update.is_snapshot- : true,- pending:- typeof update.pending === "boolean" ? update.pending : false,- finalized:- typeof update.finalized === "boolean" ? update.finalized : false,- };- }- break;- }- default: {- const _exhaustive: never = kind;- return _exhaustive;- }- }- };-- // Best-effort frame grab from the VNC canvas at the moment of a recorded- // click, so the live feed can show a zoomed shot at the action point.- const captureRecordingScreenshot = (- params: ExfiltratedEventConsoleParams,- ) => {- const schedule =- typeof requestIdleCallback === "function"- ? (fn: () => void) => requestIdleCallback(fn, { timeout: 750 })- : (fn: () => void) => window.setTimeout(fn, 0);-- schedule(() => {- try {- const canvas = canvasContainer?.querySelector("canvas");- if (!canvas) {- return;- }- useRecordingStore.getState().addScreenshot({- timestampMs: params.timestamp,- dataUrl: canvas.toDataURL("image/jpeg", 0.5),- xp: params.mousePosition.xp,- yp: params.mousePosition.yp,- });- } catch {- // toDataURL can throw on a tainted/headless canvas; shots are optional- }- });- };-- const handleMessage = (data: unknown, ws: WebSocket | null) => {- const message = getMessage(data);-- if (!message) {- console.warn("Unknown message received on message channel:", data);- return;- }-- const kind = message.kind;-- const respond = (message: MessageOut) => {- if (!ws) {- console.warn("Cannot send message, as message socket is null.");- console.warn(message);- return;- }-- ws.send(JSON.stringify(message));- };-- switch (kind) {- case "ask-for-clipboard": {- if (!navigator.clipboard) {- console.warn("Clipboard API not available.");- return;- }-- navigator.clipboard- .readText()- .then((text) => {- toast({- title: "Pasting Into Browser",- description:- "Pasting your current clipboard text into the browser.",- });-- const response: MessageOutAskForClipboardResponse = {- kind: "ask-for-clipboard-response",- text,- };-- respond(response);- })- .catch((err) => {- console.error("Failed to read clipboard contents: ", err);- });-- break;- }- case "copied-text": {- const text = message.text;-- copyText(text)- .then((success) => {- if (success) {- toast({- title: "Copied to Clipboard",- description: "The text has been copied to your clipboard.",- });- } else {- toast({- variant: "destructive",- title: "Failed to write to Clipboard",- description: "The text could not be copied to your clipboard.",- });- }- })- .catch((err) => {- console.error("Failed to write to clipboard:", err);-- toast({- variant: "destructive",- title: "Failed to write to Clipboard",- description: "The text could not be copied to your clipboard.",- });- });-- break;- }- case "exfiltrated-event": {- // Read store state fresh: this handler is attached once per socket- // and would otherwise see a stale isRecording.- const store = useRecordingStore.getState();- if (!store.isRecording && !store.finishRequested) {- break;- }- if (store.isCapturePaused()) {- break;- }- if (- store.isRecording &&- message.source === "console" &&- message.params.type === "click"- ) {- captureRecordingScreenshot(message.params);- }- if (- store.isRecording &&- !store.finishRequested &&- message.source === "cdp" &&- (message.event_name === "nav:frame_navigated" ||- message.event_name === "nav:navigated_within_document")- ) {- if (ws) {- ws.send(JSON.stringify({ kind: "recording-rearm-capture" }));- }- }- if (store.isRecording && !store.finishRequested) {- const optimistic = buildOptimisticStep(message);- if (optimistic) {- store.addOptimisticStep(optimistic);- }- }- store.add(message);- break;- }- case "recording-interpretation-update": {- useRecordingStore.getState().applyInterpretationUpdate({- interpretation_session_id: message.interpretation_session_id,- session_revision: message.session_revision,- steps: message.steps,- changed_steps: message.changed_steps,- is_snapshot: message.is_snapshot,- pending: message.pending,- finalized: message.finalized,- });- break;- }- default: {- const _exhaustive: never = kind;- return _exhaustive;- }- }- };+ }, [isRecording, isMessageConnected, sendCommand]);const streamDiagnostic: StreamDiagnostic =!showStream || !runIddiff --git a/skyvern-frontend/src/routes/browserSessions/BrowserSessionStream.test.tsx b/skyvern-frontend/src/routes/browserSessions/BrowserSessionStream.test.tsxindex c7c869431..bb565384a 100644--- a/skyvern-frontend/src/routes/browserSessions/BrowserSessionStream.test.tsx+++ b/skyvern-frontend/src/routes/browserSessions/BrowserSessionStream.test.tsx@@ -2,6 +2,7 @@ import { createHash, randomBytes } from "node:crypto";import { createServer, type Server } from "node:http";import { createConnection, type AddressInfo, type Socket } from "node:net";import type { Duplex } from "node:stream";+import { StrictMode } from "react";import { act, render, screen, waitFor } from "@testing-library/react";import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";@@ -21,6 +22,15 @@ const env = vi.hoisted(() => ({const cdpInputState = vi.hoisted(() => ({viewportWidth: 0,viewportHeight: 0,+ clipboardPasteEnabled: false,+ clipboardCopyEnabled: false,+ userIsControlling: false,+ inputReady: false,+ setUserIsControlling: undefined as ((value: boolean) => void) | undefined,+}));++const telemetry = vi.hoisted(() => ({+ captureRecordBrowser: vi.fn(),}));vi.mock("@/util/env", () => ({@@ -37,6 +47,10 @@ vi.mock("@/hooks/useCredentialGetter", () => {return { useCredentialGetter: () => credentialGetter };});+vi.mock("@/util/recordBrowserTelemetry", () => ({+ captureRecordBrowser: telemetry.captureRecordBrowser,+}));+vi.mock("@/routes/streaming/useCdpInput", async (importOriginal) => {const actual =await importOriginal<typeof import("@/routes/streaming/useCdpInput")>();@@ -46,7 +60,13 @@ vi.mock("@/routes/streaming/useCdpInput", async (importOriginal) => {const { viewportWidth, viewportHeight } = options;cdpInputState.viewportWidth = viewportWidth;cdpInputState.viewportHeight = viewportHeight;- return actual.useCdpInput(options);+ cdpInputState.clipboardPasteEnabled = Boolean(options.onClipboardPaste);+ cdpInputState.clipboardCopyEnabled = Boolean(options.onClipboardCopy);+ const result = actual.useCdpInput(options);+ cdpInputState.userIsControlling = result.userIsControlling;+ cdpInputState.inputReady = result.inputReady;+ cdpInputState.setUserIsControlling = result.setUserIsControlling;+ return result;},};});@@ -55,26 +75,43 @@ vi.mock("@/routes/streaming/InteractiveStreamView", () => ({InteractiveStreamView: ({streamImgSrc,currentUrl,+ showControlButtons,+ userIsControlling,}: {streamImgSrc: string;currentUrl?: string;+ showControlButtons: boolean;+ userIsControlling: boolean;}) => (- <div- data-frame={streamImgSrc}- data-url={currentUrl}- data-testid="stream-frame"- />+ <>+ <div+ data-frame={streamImgSrc}+ data-url={currentUrl}+ data-testid="stream-frame"+ />+ {showControlButtons && userIsControlling && (+ <button type="button">stop controlling</button>+ )}+ </>),}));class FakeStreamSocket {+ static readonly OPEN = 1;static instances: FakeStreamSocket[] = [];+ readonly readyState = FakeStreamSocket.OPEN;+ readonly send = vi.fn();close = vi.fn();+ readonly url: string;+ onopen: ((event: Event) => void) | null = null;+ onmessage: ((event: MessageEvent) => void) | null = null;+ onclose: ((event: CloseEvent) => void) | null = null;private listeners: Record<string, Array<(event: unknown) => void>> = {};- constructor() {+ constructor(url: string) {+ this.url = url;FakeStreamSocket.instances.push(this);}@@ -85,6 +122,13 @@ class FakeStreamSocket {removeEventListener() {}emit(type: string, event: unknown) {+ if (type === "open") {+ this.onopen?.(event as Event);+ } else if (type === "message") {+ this.onmessage?.(event as MessageEvent);+ } else if (type === "close") {+ this.onclose?.(event as CloseEvent);+ }for (const listener of this.listeners[type] ?? []) {listener(event);}@@ -250,6 +294,7 @@ describe("diagnosticForStatus", () => {describe("BrowserSessionStream terminal statuses", () => {beforeEach(() => {stubAnimationFrame();+ cdpInputState.setUserIsControlling = undefined;Object.defineProperty(window, "WebSocket", {configurable: true,value: FakeStreamSocket,@@ -287,6 +332,429 @@ describe("BrowserSessionStream terminal statuses", () => {expect(screen.getByText("Browser session complete")).toBeTruthy();});+ it("opens no recording message socket when exfiltrate is omitted", async () => {+ render(<BrowserSessionStream browserSessionId="pbs_test" />);++ await waitFor(() => expect(FakeStreamSocket.instances).toHaveLength(1));++ expect(FakeStreamSocket.instances[0]?.url).toContain(+ "/stream/browser_sessions/",+ );+ expect(+ FakeStreamSocket.instances.some((socket) =>+ socket.url.includes("/stream/messages/browser_session/"),+ ),+ ).toBe(false);+ expect(cdpInputState).toMatchObject({+ clipboardPasteEnabled: false,+ clipboardCopyEnabled: false,+ });+ });++ it("opens the recording message socket when exfiltrate is provided", async () => {+ render(+ <BrowserSessionStream browserSessionId="pbs_test" exfiltrate={false} />,+ );++ await waitFor(() => expect(FakeStreamSocket.instances).toHaveLength(2));++ expect(+ FakeStreamSocket.instances.some((socket) =>+ socket.url.includes("/stream/messages/browser_session/pbs_test"),+ ),+ ).toBe(true);+ expect(cdpInputState).toMatchObject({+ clipboardPasteEnabled: false,+ clipboardCopyEnabled: false,+ });+ });++ it("enables recording clipboard interception only while the message socket is connected", async () => {+ const view = render(+ <BrowserSessionStream browserSessionId="pbs_test" exfiltrate={true} />,+ );++ await waitFor(() => expect(FakeStreamSocket.instances).toHaveLength(2));+ const messageSocket = FakeStreamSocket.instances.find((socket) =>+ socket.url.includes("/stream/messages/browser_session/pbs_test"),+ );+ expect(messageSocket).toBeTruthy();+ expect(cdpInputState).toMatchObject({+ clipboardPasteEnabled: false,+ clipboardCopyEnabled: false,+ });++ act(() => messageSocket?.emit("open", new Event("open")));+ await waitFor(() =>+ expect(cdpInputState).toMatchObject({+ clipboardPasteEnabled: true,+ clipboardCopyEnabled: true,+ }),+ );++ act(() =>+ messageSocket?.emit("close", new CloseEvent("close", { code: 1006 })),+ );+ await waitFor(() =>+ expect(cdpInputState).toMatchObject({+ clipboardPasteEnabled: false,+ clipboardCopyEnabled: false,+ }),+ );+ view.unmount();+ });++ it("takes control for recording and only cedes a recording-owned grab", async () => {+ const view = render(+ <BrowserSessionStream+ browserSessionId="pbs_test"+ exfiltrate={false}+ interactive={true}+ />,+ );+ await waitFor(() => expect(FakeStreamSocket.instances).toHaveLength(3));+ const inputSocket = FakeStreamSocket.instances.find((socket) =>+ socket.url.includes("/stream/cdp_input/browser_session/pbs_test"),+ );+ expect(inputSocket).toBeTruthy();+ inputSocket?.send.mockClear();++ view.rerender(+ <BrowserSessionStream+ browserSessionId="pbs_test"+ exfiltrate={true}+ interactive={true}+ />,+ );+ await waitFor(() =>+ expect(inputSocket?.send).toHaveBeenCalledWith(+ JSON.stringify({ kind: "take-control" }),+ ),+ );++ view.rerender(+ <BrowserSessionStream+ browserSessionId="pbs_test"+ exfiltrate={false}+ interactive={true}+ />,+ );+ await waitFor(() =>+ expect(inputSocket?.send).toHaveBeenCalledWith(+ JSON.stringify({ kind: "cede-control" }),+ ),+ );++ act(() => cdpInputState.setUserIsControlling?.(true));+ await waitFor(() =>+ expect(inputSocket?.send).toHaveBeenCalledWith(+ JSON.stringify({ kind: "take-control" }),+ ),+ );+ inputSocket?.send.mockClear();++ view.rerender(+ <BrowserSessionStream+ browserSessionId="pbs_test"+ exfiltrate={true}+ interactive={true}+ />,+ );+ view.rerender(+ <BrowserSessionStream+ browserSessionId="pbs_test"+ exfiltrate={false}+ interactive={true}+ />,+ );+ expect(inputSocket?.send).not.toHaveBeenCalledWith(+ JSON.stringify({ kind: "cede-control" }),+ );+ view.unmount();+ });++ it("drops recording control on input close and retakes it when the reconnected input is ready", async () => {+ vi.useFakeTimers();+ const view = render(+ <BrowserSessionStream+ browserSessionId="pbs_test"+ exfiltrate={true}+ interactive={true}+ />,+ );+ try {+ await act(async () => Promise.resolve());+ const firstInputSocket = FakeStreamSocket.instances.find((socket) =>+ socket.url.includes("/stream/cdp_input/browser_session/pbs_test"),+ );+ expect(firstInputSocket).toBeTruthy();+ act(() => {+ firstInputSocket?.emit("message", {+ data: JSON.stringify({ kind: "ready" }),+ });+ });+ await act(async () => Promise.resolve());+ expect(cdpInputState.userIsControlling).toBe(true);++ act(() => {+ firstInputSocket?.emit(+ "close",+ new CloseEvent("close", { code: 4411 }),+ );+ });+ await act(async () => Promise.resolve());+ expect(cdpInputState).toMatchObject({+ inputReady: false,+ userIsControlling: false,+ });++ await act(async () => vi.advanceTimersByTimeAsync(2000));+ await act(async () => Promise.resolve());+ const inputSockets = FakeStreamSocket.instances.filter((socket) =>+ socket.url.includes("/stream/cdp_input/browser_session/pbs_test"),+ );+ expect(inputSockets).toHaveLength(2);+ const reconnectedInputSocket = inputSockets[1]!;+ reconnectedInputSocket.send.mockClear();+ act(() => reconnectedInputSocket.emit("open", new Event("open")));+ expect(cdpInputState.userIsControlling).toBe(false);+ expect(reconnectedInputSocket.send).not.toHaveBeenCalledWith(+ JSON.stringify({ kind: "take-control" }),+ );++ act(() => {+ reconnectedInputSocket.emit("message", {+ data: JSON.stringify({ kind: "ready" }),+ });+ });+ await act(async () => Promise.resolve());+ expect(cdpInputState.userIsControlling).toBe(true);+ expect(reconnectedInputSocket.send).toHaveBeenCalledWith(+ JSON.stringify({ kind: "take-control" }),+ );+ } finally {+ view.unmount();+ vi.useRealTimers();+ }+ });++ it("hides manual stop controlling while recording", async () => {+ const view = render(+ <BrowserSessionStream+ browserSessionId="pbs_test"+ exfiltrate={false}+ showControlButtons={true}+ />,+ );+ await waitFor(() => expect(FakeStreamSocket.instances).toHaveLength(3));+ const streamSocket = FakeStreamSocket.instances.find((socket) =>+ socket.url.includes("/stream/browser_sessions/pbs_test"),+ );+ act(() => {+ streamSocket?.emitStreamMessage({+ status: "running",+ screenshot: "frame",+ });+ });+ await waitFor(() =>+ expect(screen.getByTestId("stream-frame")).toBeTruthy(),+ );+ act(() => cdpInputState.setUserIsControlling?.(true));+ await waitFor(() =>+ expect(+ screen.getByRole("button", { name: "stop controlling" }),+ ).toBeTruthy(),+ );++ view.rerender(+ <BrowserSessionStream+ browserSessionId="pbs_test"+ exfiltrate={true}+ showControlButtons={true}+ />,+ );++ await waitFor(() =>+ expect(+ screen.queryByRole("button", { name: "stop controlling" }),+ ).toBeNull(),+ );+ view.unmount();+ });++ it("reconnects the recording channel after it disconnects during recording", async () => {+ vi.useFakeTimers();+ const view = render(+ <BrowserSessionStream browserSessionId="pbs_test" exfiltrate={true} />,+ );+ try {+ await act(async () => Promise.resolve());+ const firstMessageSocket = FakeStreamSocket.instances.find((socket) =>+ socket.url.includes("/stream/messages/browser_session/pbs_test"),+ );+ expect(firstMessageSocket).toBeTruthy();+ act(() => firstMessageSocket?.emit("open", new Event("open")));++ act(() =>+ firstMessageSocket?.emit(+ "close",+ new CloseEvent("close", { code: 1006 }),+ ),+ );+ await act(async () => vi.advanceTimersByTimeAsync(1000));+ await act(async () => Promise.resolve());++ const messageSockets = FakeStreamSocket.instances.filter((socket) =>+ socket.url.includes("/stream/messages/browser_session/pbs_test"),+ );+ expect(messageSockets).toHaveLength(2);+ const reconnectedSocket = messageSockets[1]!;+ act(() => reconnectedSocket.emit("open", new Event("open")));+ expect(+ reconnectedSocket.send.mock.calls.map((call) =>+ JSON.parse(String(call[0])),+ ),+ ).toContainEqual(expect.objectContaining({ kind: "begin-exfiltration" }));++ act(() =>+ reconnectedSocket.emit(+ "close",+ new CloseEvent("close", { code: 1006 }),+ ),+ );+ await act(async () => vi.advanceTimersByTimeAsync(1000));+ await act(async () => Promise.resolve());+ expect(+ FakeStreamSocket.instances.filter((socket) =>+ socket.url.includes("/stream/messages/browser_session/pbs_test"),+ ),+ ).toHaveLength(3);+ } finally {+ view.unmount();+ vi.useRealTimers();+ }+ });++ it("reconnects a channel stranded by stopping before its retry", async () => {+ vi.useFakeTimers();+ const view = render(+ <BrowserSessionStream browserSessionId="pbs_test" exfiltrate={true} />,+ );+ try {+ await act(async () => Promise.resolve());+ const firstMessageSocket = FakeStreamSocket.instances.find((socket) =>+ socket.url.includes("/stream/messages/browser_session/pbs_test"),+ );+ expect(firstMessageSocket).toBeTruthy();+ act(() => firstMessageSocket?.emit("open", new Event("open")));+ act(() =>+ firstMessageSocket?.emit(+ "close",+ new CloseEvent("close", { code: 1006 }),+ ),+ );++ view.rerender(+ <BrowserSessionStream browserSessionId="pbs_test" exfiltrate={false} />,+ );+ await act(async () => vi.advanceTimersByTimeAsync(1000));+ expect(+ FakeStreamSocket.instances.filter((socket) =>+ socket.url.includes("/stream/messages/browser_session/pbs_test"),+ ),+ ).toHaveLength(1);++ view.rerender(+ <BrowserSessionStream browserSessionId="pbs_test" exfiltrate={true} />,+ );+ await act(async () => vi.advanceTimersByTimeAsync(1000));+ await act(async () => Promise.resolve());+ const messageSockets = FakeStreamSocket.instances.filter((socket) =>+ socket.url.includes("/stream/messages/browser_session/pbs_test"),+ );+ expect(messageSockets).toHaveLength(2);+ act(() => messageSockets[1]!.emit("open", new Event("open")));+ expect(+ messageSockets[1]!.send.mock.calls.map((call) =>+ JSON.parse(String(call[0])),+ ),+ ).toContainEqual(expect.objectContaining({ kind: "begin-exfiltration" }));+ } finally {+ view.unmount();+ vi.useRealTimers();+ }+ });++ it("reports aggregate stream health once when recording ends", async () => {+ vi.useFakeTimers();+ const view = render(+ <StrictMode>+ <BrowserSessionStream browserSessionId="pbs_test" exfiltrate={true} />+ </StrictMode>,+ );+ try {+ await act(async () => Promise.resolve());+ const streamSocket = FakeStreamSocket.instances.find(+ (socket) =>+ socket.url.includes("/stream/browser_sessions/") &&+ !socket.close.mock.calls.length,+ );+ expect(streamSocket).toBeTruthy();++ act(() => {+ streamSocket?.emitStreamMessage({+ status: "running",+ screenshot: "frame-1",+ });+ streamSocket?.emitStreamMessage({+ status: "running",+ screenshot: "frame-2",+ });+ streamSocket?.emitStreamMessage({+ status: "running",+ screenshot: "frame-3",+ });+ });+ await act(async () => vi.advanceTimersByTimeAsync(30_000));++ act(() => {+ for (let frame = 0; frame < 6; frame += 1) {+ streamSocket?.emitStreamMessage({+ status: "running",+ screenshot: `frame-${frame + 4}`,+ });+ }+ });+ await act(async () => vi.advanceTimersByTimeAsync(30_000));++ expect(telemetry.captureRecordBrowser).not.toHaveBeenCalled();++ view.rerender(+ <StrictMode>+ <BrowserSessionStream+ browserSessionId="pbs_test"+ exfiltrate={false}+ />+ </StrictMode>,+ );+ await act(async () => vi.advanceTimersByTimeAsync(0));++ expect(telemetry.captureRecordBrowser).toHaveBeenCalledOnce();+ expect(telemetry.captureRecordBrowser).toHaveBeenCalledWith(+ "record_browser.cdp_stream_health",+ expect.objectContaining({+ sample_count: 2,+ }),+ );+ const properties = telemetry.captureRecordBrowser.mock.calls[0]?.[1];+ expect(properties?.fps_avg).toBeCloseTo(0.15);+ expect(properties?.fps_min).toBeCloseTo(0.1);+ } finally {+ view.unmount();+ vi.useRealTimers();+ }+ });+it("shows the terminal panel even if a terminal status arrives with a frame", async () => {render(<BrowserSessionStream browserSessionId="pbs_test" />);diff --git a/skyvern-frontend/src/routes/browserSessions/BrowserSessionStream.tsx b/skyvern-frontend/src/routes/browserSessions/BrowserSessionStream.tsxindex 5315b56b1..8c1b6abaf 100644--- a/skyvern-frontend/src/routes/browserSessions/BrowserSessionStream.tsx+++ b/skyvern-frontend/src/routes/browserSessions/BrowserSessionStream.tsx@@ -1,7 +1,8 @@-import { useEffect, useRef, useState } from "react";+import { useCallback, useEffect, useRef, useState } from "react";import { useCredentialGetter } from "@/hooks/useCredentialGetter";import { newWssBaseUrl, getCredentialParam } from "@/util/env";import { useCdpInput } from "@/routes/streaming/useCdpInput";+import { useRecordingMessageChannel } from "@/routes/streaming/useRecordingMessageChannel";import { InteractiveStreamView } from "@/routes/streaming/InteractiveStreamView";import {markCommit,@@ -31,6 +32,7 @@ import {streamReconnectDelayMs,} from "@/routes/streaming/streamLifecycle";import { useSettingsStore } from "@/store/SettingsStore";+import { captureRecordBrowser } from "@/util/recordBrowserTelemetry";type StreamMessage = {browser_session_id?: string;@@ -90,6 +92,8 @@ interface Props {enableUrlInput?: boolean;// Passing this hands the window frame to the caller (see InteractiveStreamView).onFrameWidthChange?: (width: number | null) => void;+ exfiltrate?: boolean;+ workflowPermanentId?: string | null;}function BrowserSessionStream({@@ -103,6 +107,8 @@ function BrowserSessionStream({forceCdp = false,enableUrlInput = false,onFrameWidthChange,+ exfiltrate,+ workflowPermanentId,}: Props) {const [streamImgSrc, setStreamImgSrc] = useState<string>("");const [streamImgToken, setStreamImgToken] = useState<number>(0);@@ -116,6 +122,15 @@ function BrowserSessionStream({const settingsStore = useSettingsStore();const socketRef = useRef<WebSocket | null>(null);+ const streamImgSrcRef = useRef("");+ const exfiltrateRef = useRef(!!exfiltrate);+ const recordingFrameCountRef = useRef(0);+ const recordingFpsSamplesRef = useRef<number[]>([]);+ const recordingHealthFlushTimerRef = useRef<number | null>(null);+ const recordingHealthEndedRef = useRef(false);+ const recordingOwnsControlRef = useRef(false);+ const previousControlExfiltrateRef = useRef(false);+ const previousInputReadyRef = useRef(false);const onActivityRef = useRef(onActivity);const hasFrameRef = useRef(false);const pendingFrameRef = useRef<{@@ -128,10 +143,92 @@ function BrowserSessionStream({const reconnectAttemptsRef = useRef(0);const streamFinishedRef = useRef(false);const reconnectTimerRef = useRef<ReturnType<typeof setTimeout> | null>(null);+ const recordingReconnectTimerRef = useRef<ReturnType<+ typeof setTimeout+ > | null>(null);+ const recordingChannelDisconnectedRef = useRef(false);+ const [recordingReconnectTrigger, setRecordingReconnectTrigger] = useState(0);// 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);+ exfiltrateRef.current = !!exfiltrate;++ const scheduleRecordingReconnect = useCallback(() => {+ if (recordingReconnectTimerRef.current) {+ return;+ }+ recordingReconnectTimerRef.current = setTimeout(() => {+ recordingReconnectTimerRef.current = null;+ if (exfiltrateRef.current) {+ setRecordingReconnectTrigger((trigger) => trigger + 1);+ }+ }, 1000);+ }, []);++ const handleRecordingConnectionChange = useCallback(+ (connected: boolean, event?: CloseEvent) => {+ if (connected) {+ recordingChannelDisconnectedRef.current = false;+ if (recordingReconnectTimerRef.current) {+ clearTimeout(recordingReconnectTimerRef.current);+ recordingReconnectTimerRef.current = null;+ }+ return;+ }+ if (!event) {+ return;+ }+ recordingChannelDisconnectedRef.current = true;+ if (exfiltrateRef.current) {+ scheduleRecordingReconnect();+ }+ },+ [scheduleRecordingReconnect],+ );++ useEffect(() => {+ return () => {+ if (recordingReconnectTimerRef.current) {+ clearTimeout(recordingReconnectTimerRef.current);+ }+ };+ }, []);++ const recordingChannelEnabled = exfiltrate !== undefined;+ const { isMessageConnected, sendCommand: sendRecordingCommand } =+ useRecordingMessageChannel({+ browserSessionId,+ enabled: recordingChannelEnabled,+ exfiltrate: !!exfiltrate,+ workflowPermanentId: workflowPermanentId ?? null,+ getFrameDataUrl: () =>+ streamImgSrcRef.current+ ? `data:image/${streamFormat};base64,${streamImgSrcRef.current}`+ : null,+ clipboard: "message",+ reconnectTrigger: recordingReconnectTrigger,+ onConnectionChange: handleRecordingConnectionChange,+ });++ useEffect(() => {+ if (+ exfiltrate &&+ !isMessageConnected &&+ recordingChannelDisconnectedRef.current+ ) {+ scheduleRecordingReconnect();+ }+ }, [exfiltrate, isMessageConnected, scheduleRecordingReconnect]);+ const onClipboardPaste = useCallback(+ (text: string) => {+ sendRecordingCommand({ kind: "clipboard-paste", text });+ },+ [sendRecordingCommand],+ );+ const onClipboardCopy = useCallback(() => {+ sendRecordingCommand({ kind: "clipboard-copy" });+ }, [sendRecordingCommand]);// The CDP input socket must be wired whenever the stream can be controlled,// whether by default interaction or via the take-control button.@@ -155,12 +252,90 @@ function BrowserSessionStream({interactive: controllable,viewportWidth,viewportHeight,+ onClipboardPaste:+ exfiltrate && isMessageConnected ? onClipboardPaste : undefined,+ onClipboardCopy:+ exfiltrate && isMessageConnected ? onClipboardCopy : undefined,});+ useEffect(() => {+ const recordingStarted =+ !!exfiltrate && !previousControlExfiltrateRef.current;+ const recordingEnded = !exfiltrate && previousControlExfiltrateRef.current;+ const inputBecameReady = inputReady && !previousInputReadyRef.current;++ if (recordingStarted) {+ recordingOwnsControlRef.current = !userIsControlling;+ setUserIsControlling(true);+ } else if (exfiltrate && inputBecameReady) {+ setUserIsControlling(true);+ } else if (recordingEnded) {+ if (recordingOwnsControlRef.current) {+ setUserIsControlling(false);+ }+ recordingOwnsControlRef.current = false;+ }++ previousControlExfiltrateRef.current = !!exfiltrate;+ previousInputReadyRef.current = inputReady;+ }, [exfiltrate, inputReady, setUserIsControlling, userIsControlling]);+useEffect(() => {onActivityRef.current = onActivity;}, [onActivity]);+ useEffect(() => {+ if (!exfiltrate) {+ recordingHealthEndedRef.current = true;+ return;+ }++ if (recordingHealthFlushTimerRef.current !== null) {+ if (!recordingHealthEndedRef.current) {+ window.clearTimeout(recordingHealthFlushTimerRef.current);+ }+ recordingHealthFlushTimerRef.current = null;+ }+ recordingHealthEndedRef.current = false;+ recordingFrameCountRef.current = 0;+ recordingFpsSamplesRef.current = [];+ let sampleStartedAtMs = Date.now();+ const recordSample = (ensureSample: boolean) => {+ const now = Date.now();+ const elapsedSeconds = (now - sampleStartedAtMs) / 1000;+ if (elapsedSeconds > 0) {+ recordingFpsSamplesRef.current.push(+ recordingFrameCountRef.current / elapsedSeconds,+ );+ } else if (ensureSample && recordingFpsSamplesRef.current.length === 0) {+ recordingFpsSamplesRef.current.push(0);+ }+ recordingFrameCountRef.current = 0;+ sampleStartedAtMs = now;+ };+ const interval = window.setInterval(() => recordSample(false), 30_000);++ return () => {+ window.clearInterval(interval);+ recordSample(true);+ const samples = [...recordingFpsSamplesRef.current];+ recordingFpsSamplesRef.current = [];+ const flushTimer = window.setTimeout(() => {+ captureRecordBrowser("record_browser.cdp_stream_health", {+ fps_avg:+ samples.reduce((total, sample) => total + sample, 0) /+ samples.length,+ fps_min: Math.min(...samples),+ sample_count: samples.length,+ });+ if (recordingHealthFlushTimerRef.current === flushTimer) {+ recordingHealthFlushTimerRef.current = null;+ }+ }, 0);+ recordingHealthFlushTimerRef.current = flushTimer;+ };+ }, [exfiltrate]);+useEffect(() => startDebugReport(), []);// Once control can't be offered (input socket torn down), forget any prior@@ -173,6 +348,7 @@ function BrowserSessionStream({useEffect(() => {let cancelled = false;+ streamImgSrcRef.current = "";setStreamImgSrc("");setStreamFormat("png");setViewportWidth(1280);@@ -260,6 +436,9 @@ function BrowserSessionStream({}};if (message.screenshot) {+ if (exfiltrateRef.current) {+ recordingFrameCountRef.current += 1;+ }hasFrameRef.current = true;reconnectAttemptsRef.current = 0;streamEndedDiagnosticRef.current = null;@@ -276,6 +455,7 @@ function BrowserSessionStream({if (!pending || !isCurrentSocket()) return;pendingFrameRef.current = null;lastCommittedTokenRef.current = pending.token;+ streamImgSrcRef.current = pending.screenshot;setStreamImgSrc(pending.screenshot);setStreamImgToken(pending.token);applyMetadata(pending.message);@@ -312,6 +492,7 @@ function BrowserSessionStream({// screenshot covering the status panel.clearPendingFrame();hasFrameRef.current = false;+ streamImgSrcRef.current = "";setStreamImgSrc("");// Only a terminal status forecloses reconnecting; a live session whose// screencast ended is exactly the case worth redialling.@@ -373,6 +554,7 @@ function BrowserSessionStream({reconnectAttemptsRef.current > STREAM_STALE_FRAME_AFTER_ATTEMPTS) {hasFrameRef.current = false;+ streamImgSrcRef.current = "";setStreamImgSrc("");}if (!hasFrameRef.current) {@@ -396,6 +578,7 @@ function BrowserSessionStream({// 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;+ streamImgSrcRef.current = "";setStreamImgSrc("");setDiagnostic(diagnosticForReconnectExhausted(BROWSER_SESSION_STREAM_SUBJECT),@@ -454,7 +637,7 @@ function BrowserSessionStream({setUserIsControlling={setUserIsControlling}inputReady={inputReady}containerRef={containerRef}- showControlButtons={showControlButtons}+ showControlButtons={showControlButtons && !exfiltrate}handlers={handlers}currentUrl={currentUrl}centered={centered}diff --git a/skyvern-frontend/src/routes/browserSessions/hooks/useProcessRecordingMutation.test.tsx b/skyvern-frontend/src/routes/browserSessions/hooks/useProcessRecordingMutation.test.tsxnew file mode 100644index 000000000..94b326350--- /dev/null+++ b/skyvern-frontend/src/routes/browserSessions/hooks/useProcessRecordingMutation.test.tsx@@ -0,0 +1,113 @@+// @vitest-environment jsdom++import type { ReactNode } from "react";+import { act, renderHook, waitFor } from "@testing-library/react";+import { QueryClient, QueryClientProvider } from "@tanstack/react-query";+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";++import { WorkflowPermanentIdContext } from "@/routes/workflows/WorkflowPermanentIdContext";+import {+ useRecordingStore,+ type OptimisticStep,+ type RecordingDraftStep,+} from "@/store/useRecordingStore";++import { useProcessRecordingMutation } from "./useProcessRecordingMutation";++const mocks = vi.hoisted(() => ({+ captureRecordBrowser: vi.fn(),+ markRecordBrowserProcessed: vi.fn(),+ post: vi.fn(),+}));++vi.mock("@/api/AxiosClient", () => ({+ getClient: vi.fn(async () => ({ post: mocks.post })),+}));++vi.mock("@/components/ui/use-toast", () => ({ toast: vi.fn() }));++vi.mock("@/hooks/useCredentialGetter", () => ({+ useCredentialGetter: () => vi.fn(async () => "test-token"),+}));++vi.mock("posthog-js/react", () => ({+ useFeatureFlagEnabled: () => false,+}));++vi.mock("@/util/recordBrowserTelemetry", () => ({+ captureRecordBrowser: mocks.captureRecordBrowser,+ markRecordBrowserProcessed: mocks.markRecordBrowserProcessed,+}));++function wrapper({ children }: { children: ReactNode }) {+ const queryClient = new QueryClient({+ defaultOptions: { mutations: { retry: false } },+ });+ return (+ <WorkflowPermanentIdContext.Provider value="wpid-1">+ <QueryClientProvider client={queryClient}>{children}</QueryClientProvider>+ </WorkflowPermanentIdContext.Provider>+ );+}++const draftStep: RecordingDraftStep = {+ step_id: "step-1",+ action_kind: "click",+ block_type: "action",+ label: "Click",+ status: "ready",+ editable_fields: [],+ parameters: [],+ parameter_keys: [],+};++const optimisticStep: OptimisticStep = {+ local_id: "optimistic-1",+ action_kind: "click",+ title: "Click",+ timestamp: 1,+};++describe("useProcessRecordingMutation telemetry", () => {+ beforeEach(() => {+ vi.useFakeTimers({ shouldAdvanceTime: true });+ vi.setSystemTime(1_000);+ vi.clearAllMocks();+ useRecordingStore.getState().reset();+ useRecordingStore.getState().setRecordingTransport("cdp");+ useRecordingStore.getState().setIsRecording(true);+ useRecordingStore.setState({ optimisticSteps: [optimisticStep] });+ mocks.captureRecordBrowser.mockClear();+ });++ afterEach(() => {+ vi.useRealTimers();+ useRecordingStore.getState().reset();+ });++ it("reports successful processing with the recording transport and counters", async () => {+ mocks.post.mockResolvedValue({ data: { blocks: [], parameters: [] } });+ vi.setSystemTime(3_500);+ useRecordingStore.getState().setIsRecording(false);+ const { result } = renderHook(+ () =>+ useProcessRecordingMutation({+ browserSessionId: "pbs-1",+ }),+ { wrapper },+ );++ act(() => result.current.mutate({ draftSteps: [draftStep] }));++ await waitFor(() => expect(result.current.isSuccess).toBe(true));+ expect(mocks.captureRecordBrowser).toHaveBeenCalledWith(+ "record_browser.finished",+ {+ transport: "cdp",+ duration_ms: 2_500,+ event_count: 0,+ optimistic_step_count: 1,+ },+ );+ });+});diff --git a/skyvern-frontend/src/routes/browserSessions/hooks/useProcessRecordingMutation.ts b/skyvern-frontend/src/routes/browserSessions/hooks/useProcessRecordingMutation.tsindex 7bae496aa..536f85fa4 100644--- a/skyvern-frontend/src/routes/browserSessions/hooks/useProcessRecordingMutation.ts+++ b/skyvern-frontend/src/routes/browserSessions/hooks/useProcessRecordingMutation.ts@@ -36,6 +36,12 @@ const useProcessRecordingMutation = ({const recordingStore = useRecordingStore();const workflowPermanentId = useWorkflowPermanentId();const mutationStartedAtRef = useRef<number | null>(null);+ const recordingStatsRef = useRef<{+ transport: "cdp" | "vnc";+ durationMs: number;+ eventCount: number;+ optimisticStepCount: number;+ } | null>(null);// Per-user opt-in preview; not enrolled reads as false (agent blocks).const codeFirst =useFeatureFlagEnabled(RECORD_BROWSER_CODE_FIRST_FLAG) ?? false;@@ -67,7 +73,14 @@ const useProcessRecordingMutation = ({mutationStartedAtRef.current = Date.now();- const eventCount = recordingStore.getEventCount();+ const currentRecording = useRecordingStore.getState();+ const eventCount = currentRecording.getEventCount();+ recordingStatsRef.current = {+ transport: currentRecording.recordingTransport,+ durationMs: Math.round(currentRecording.getSecondsRecording() * 1000),+ eventCount,+ optimisticStepCount: currentRecording.optimisticSteps.length,+ };const hasDraftSteps = (draftSteps?.length ?? 0) > 0;if (eventCount === 0 && !hasDraftSteps) {@@ -119,6 +132,22 @@ const useProcessRecordingMutation = ({markRecordBrowserProcessed(blocks?.length ?? 0);+ const completedRecording = recordingStatsRef.current;+ recordingStatsRef.current = null;+ const currentRecording = useRecordingStore.getState();+ captureRecordBrowser("record_browser.finished", {+ transport:+ completedRecording?.transport ?? currentRecording.recordingTransport,+ duration_ms:+ completedRecording?.durationMs ??+ Math.round(currentRecording.getSecondsRecording() * 1000),+ event_count:+ completedRecording?.eventCount ?? currentRecording.getEventCount(),+ optimistic_step_count:+ completedRecording?.optimisticStepCount ??+ currentRecording.optimisticSteps.length,+ });+captureRecordBrowser("record_browser.processed", {block_count: blocks?.length ?? 0,parameter_count: parameters?.length ?? 0,@@ -156,6 +185,7 @@ const useProcessRecordingMutation = ({? Date.now() - mutationStartedAtRef.current: 0;mutationStartedAtRef.current = null;+ recordingStatsRef.current = null;if (error instanceof Error && error.message === FAIL_QUIET_NO_EVENTS) {recordingStore.reset();diff --git a/skyvern-frontend/src/routes/streaming/useCdpInput.test.ts b/skyvern-frontend/src/routes/streaming/useCdpInput.test.tsindex d21c0c2db..236593271 100644--- a/skyvern-frontend/src/routes/streaming/useCdpInput.test.ts+++ b/skyvern-frontend/src/routes/streaming/useCdpInput.test.ts@@ -71,13 +71,19 @@ async function renderInputHook() {});}-async function renderControllingInputHook() {+async function renderControllingInputHook(+ clipboardCallbacks: {+ onClipboardPaste?: (text: string) => void;+ onClipboardCopy?: () => void;+ } = {},+) {const { result } = renderHook(() =>useCdpInput({inputWsUrl: "wss://input.test",interactive: true,viewportWidth: 1280,viewportHeight: 720,+ ...clipboardCallbacks,}),);@@ -91,14 +97,61 @@ async function renderControllingInputHook() {return result;}-function fakeKeyboardEvent(key: string, code: string): React.KeyboardEvent {+async function renderWheelInputHook() {+ const hook = renderHook(() =>+ useCdpInput({+ inputWsUrl: "wss://input.test",+ interactive: true,+ viewportWidth: 1280,+ viewportHeight: 720,+ }),+ );++ await act(async () => {+ await Promise.resolve();+ });++ const container = document.createElement("div");+ const image = document.createElement("img");+ vi.spyOn(image, "getBoundingClientRect").mockReturnValue({+ x: 0,+ y: 0,+ top: 0,+ right: 1280,+ bottom: 720,+ left: 0,+ width: 1280,+ height: 720,+ toJSON: () => ({}),+ });+ container.appendChild(image);+ Object.defineProperty(hook.result.current.containerRef, "current", {+ configurable: true,+ value: container,+ });++ act(() => {+ hook.result.current.setUserIsControlling(true);+ });+ latestSocketSend().mockClear();++ return { ...hook, container };+}++function fakeKeyboardEvent(+ key: string,+ code: string,+ modifiers: Partial<+ Pick<React.KeyboardEvent, "altKey" | "ctrlKey" | "metaKey" | "shiftKey">+ > = {},+): React.KeyboardEvent {return {key,code,- altKey: false,- ctrlKey: false,- metaKey: false,- shiftKey: false,+ altKey: modifiers.altKey ?? false,+ ctrlKey: modifiers.ctrlKey ?? false,+ metaKey: modifiers.metaKey ?? false,+ shiftKey: modifiers.shiftKey ?? false,preventDefault: vi.fn(),} as unknown as React.KeyboardEvent;}@@ -224,6 +277,93 @@ describe("useCdpInput reconnects", () => {});});+describe("useCdpInput wheel handling", () => {+ let animationFrameCallback: FrameRequestCallback | undefined;+ let nextAnimationFrameId: number;+ let requestAnimationFrame: ReturnType<typeof vi.fn>;+ let cancelAnimationFrame: ReturnType<typeof vi.fn>;++ beforeEach(() => {+ vi.clearAllMocks();+ MockWebSocket.instances = [];+ vi.stubGlobal("WebSocket", MockWebSocket);+ nextAnimationFrameId = 1;+ requestAnimationFrame = vi.fn((callback: FrameRequestCallback) => {+ animationFrameCallback = callback;+ return nextAnimationFrameId++;+ });+ vi.stubGlobal("requestAnimationFrame", requestAnimationFrame);+ cancelAnimationFrame = vi.fn();+ vi.stubGlobal("cancelAnimationFrame", cancelAnimationFrame);+ });++ afterEach(() => {+ vi.unstubAllGlobals();+ });++ it("coalesces wheel events within one animation frame", async () => {+ const { container } = await renderWheelInputHook();+ expect(requestAnimationFrame).not.toHaveBeenCalled();+ const first = new WheelEvent("wheel", {+ clientX: 100,+ clientY: 200,+ deltaX: 1.2,+ deltaY: 2.4,+ ctrlKey: true,+ cancelable: true,+ });+ const second = new WheelEvent("wheel", {+ clientX: 300,+ clientY: 400,+ deltaX: 2.4,+ deltaY: 3.2,+ shiftKey: true,+ cancelable: true,+ });++ container.dispatchEvent(first);+ container.dispatchEvent(second);++ expect(first.defaultPrevented).toBe(true);+ expect(second.defaultPrevented).toBe(true);+ expect(requestAnimationFrame).toHaveBeenCalledOnce();+ expect(latestSocketSend()).not.toHaveBeenCalled();++ act(() => {+ animationFrameCallback?.(16);+ });++ expect(latestSocketSend()).toHaveBeenCalledOnce();+ expect(latestSocketSend()).toHaveBeenCalledWith(+ JSON.stringify({+ type: "wheelEvent",+ x: 300,+ y: 400,+ deltaX: 4,+ deltaY: 6,+ modifiers: 8,+ }),+ );+ expect(requestAnimationFrame).toHaveBeenCalledOnce();+ });++ it("cancels a pending wheel animation frame on cleanup", async () => {+ const { container, unmount } = await renderWheelInputHook();+ container.dispatchEvent(+ new WheelEvent("wheel", {+ clientX: 100,+ clientY: 200,+ deltaY: 1,+ cancelable: true,+ }),+ );++ unmount();++ expect(cancelAnimationFrame).toHaveBeenCalledWith(1);+ });+});+describe("useCdpInput key handling", () => {beforeEach(() => {vi.useFakeTimers();@@ -352,6 +492,105 @@ describe("useCdpInput key handling", () => {}),);});++ it("sends Cmd+V through the recording message callback instead of CDP key events", async () => {+ const onClipboardPaste = vi.fn();+ Object.defineProperty(navigator, "clipboard", {+ configurable: true,+ value: { readText: vi.fn(async () => "clipboard text") },+ });+ const result = await renderControllingInputHook({ onClipboardPaste });+ const send = latestSocketSend();+ send.mockClear();+ const keyDown = fakeKeyboardEvent("v", "KeyV", { metaKey: true });+ const keyUp = fakeKeyboardEvent("v", "KeyV");++ await act(async () => {+ result.current.handlers.handleKeyDown(keyDown);+ await Promise.resolve();+ result.current.handlers.handleKeyUp(keyUp);+ });++ expect(onClipboardPaste).toHaveBeenCalledWith("clipboard text");+ expect(send).not.toHaveBeenCalled();+ expect(keyDown.preventDefault).toHaveBeenCalled();+ expect(keyUp.preventDefault).toHaveBeenCalled();+ });++ it("drops a clipboard read that resolves after recording callbacks are removed", async () => {+ let resolveClipboard: ((text: string) => void) | undefined;+ Object.defineProperty(navigator, "clipboard", {+ configurable: true,+ value: {+ readText: vi.fn(+ () =>+ new Promise<string>((resolve) => {+ resolveClipboard = resolve;+ }),+ ),+ },+ });+ const onClipboardPaste = vi.fn();+ const { result, rerender } = renderHook(+ ({ paste }: { paste?: (text: string) => void }) =>+ useCdpInput({+ inputWsUrl: "wss://input.test",+ interactive: true,+ viewportWidth: 1280,+ viewportHeight: 720,+ onClipboardPaste: paste,+ }),+ {+ initialProps: {+ paste: onClipboardPaste as ((text: string) => void) | undefined,+ },+ },+ );+ await act(async () => Promise.resolve());+ act(() => result.current.setUserIsControlling(true));++ act(() => {+ result.current.handlers.handleKeyDown(+ fakeKeyboardEvent("v", "KeyV", { metaKey: true }),+ );+ });+ rerender({ paste: undefined });+ await act(async () => {+ resolveClipboard?.("late clipboard text");+ await Promise.resolve();+ });++ expect(onClipboardPaste).not.toHaveBeenCalled();+ });++ it("forwards an ordinary key pair after intercepting a clipboard chord", async () => {+ Object.defineProperty(navigator, "clipboard", {+ configurable: true,+ value: { readText: vi.fn(async () => "clipboard text") },+ });+ const result = await renderControllingInputHook({+ onClipboardPaste: vi.fn(),+ });+ const send = latestSocketSend();+ send.mockClear();++ await act(async () => {+ result.current.handlers.handleKeyDown(+ fakeKeyboardEvent("v", "KeyV", { metaKey: true }),+ );+ await Promise.resolve();+ result.current.handlers.handleKeyUp(fakeKeyboardEvent("v", "KeyV"));+ });+ act(() => {+ result.current.handlers.handleKeyDown(fakeKeyboardEvent("v", "KeyV"));+ result.current.handlers.handleKeyUp(fakeKeyboardEvent("v", "KeyV"));+ });++ expect(send.mock.calls.map((call) => JSON.parse(String(call[0])))).toEqual([+ expect.objectContaining({ eventType: "keyDown", code: "KeyV" }),+ expect.objectContaining({ eventType: "keyUp", code: "KeyV" }),+ ]);+ });});describe("useCdpInput navigate", () => {diff --git a/skyvern-frontend/src/routes/streaming/useCdpInput.ts b/skyvern-frontend/src/routes/streaming/useCdpInput.tsindex dd8494494..1c764105e 100644--- a/skyvern-frontend/src/routes/streaming/useCdpInput.ts+++ b/skyvern-frontend/src/routes/streaming/useCdpInput.ts@@ -19,6 +19,8 @@ interface UseCdpInputOptions {interactive: boolean;viewportWidth: number;viewportHeight: number;+ onClipboardPaste?: (text: string) => void;+ onClipboardCopy?: () => void;}interface UseCdpInputReturn {@@ -56,6 +58,8 @@ export function useCdpInput({interactive,viewportWidth,viewportHeight,+ onClipboardPaste,+ onClipboardCopy,}: UseCdpInputOptions): UseCdpInputReturn {const [userIsControlling, setUserIsControlling] = useState(false);const [inputReady, setInputReady] = useState(false);@@ -73,6 +77,19 @@ export function useCdpInput({const inputReconnectAttemptsRef = useRef(0);const inputStoppedRef = useRef(false);const inputEventCountRef = useRef(0);+ const wheelAccumulatorRef = useRef<{+ deltaX: number;+ deltaY: number;+ x: number;+ y: number;+ modifiers: number;+ } | null>(null);+ const wheelAnimationFrameRef = useRef<number | null>(null);+ const interceptedClipboardKeysRef = useRef(new Set<string>());+ const onClipboardPasteRef = useRef(onClipboardPaste);+ const onClipboardCopyRef = useRef(onClipboardCopy);+ onClipboardPasteRef.current = onClipboardPaste;+ onClipboardCopyRef.current = onClipboardCopy;useEffect(() => {if (!interactive || !inputWsUrl) return;@@ -213,6 +230,29 @@ export function useCdpInput({const el = containerRef.current;if (!el) return;+ const flushWheelEvents = () => {+ wheelAnimationFrameRef.current = null;+ const event = wheelAccumulatorRef.current;+ wheelAccumulatorRef.current = null;+ const ws = inputSocketRef.current;+ if (+ event &&+ (event.deltaX !== 0 || event.deltaY !== 0) &&+ ws?.readyState === WebSocket.OPEN+ ) {+ ws.send(+ JSON.stringify({+ type: "wheelEvent",+ x: event.x,+ y: event.y,+ deltaX: Math.round(event.deltaX),+ deltaY: Math.round(event.deltaY),+ modifiers: event.modifiers,+ }),+ );+ }+ };+const handler = (e: WheelEvent) => {e.preventDefault();const ws = inputSocketRef.current;@@ -231,20 +271,29 @@ export function useCdpInput({);if (!coords) return;- ws.send(- JSON.stringify({- type: "wheelEvent",- x: coords.x,- y: coords.y,- deltaX: Math.round(e.deltaX),- deltaY: Math.round(e.deltaY),- modifiers: getModifiers(e),- }),- );+ const accumulated = wheelAccumulatorRef.current;+ wheelAccumulatorRef.current = {+ deltaX: (accumulated?.deltaX ?? 0) + e.deltaX,+ deltaY: (accumulated?.deltaY ?? 0) + e.deltaY,+ x: coords.x,+ y: coords.y,+ modifiers: getModifiers(e),+ };+ if (accumulated === null) {+ wheelAnimationFrameRef.current =+ requestAnimationFrame(flushWheelEvents);+ }};el.addEventListener("wheel", handler, { passive: false });- return () => el.removeEventListener("wheel", handler);+ return () => {+ el.removeEventListener("wheel", handler);+ if (wheelAnimationFrameRef.current !== null) {+ cancelAnimationFrame(wheelAnimationFrameRef.current);+ wheelAnimationFrameRef.current = null;+ }+ wheelAccumulatorRef.current = null;+ };}, [interactive, userIsControlling, viewportWidth, viewportHeight]);const sendInputEvent = useCallback((payload: Record<string, unknown>) => {@@ -346,6 +395,27 @@ export function useCdpInput({(e: React.KeyboardEvent) => {if (!interactive || !userIsControlling) return;e.preventDefault();+ const clipboardModifier = e.metaKey || e.ctrlKey;+ const key = e.key.toLowerCase();+ if (clipboardModifier && key === "v" && onClipboardPasteRef.current) {+ interceptedClipboardKeysRef.current.add(e.code);+ if (!navigator.clipboard) {+ console.warn("Clipboard API not available.");+ return;+ }+ navigator.clipboard+ .readText()+ .then((text) => onClipboardPasteRef.current?.(text))+ .catch((error) => {+ console.error("Failed to read clipboard contents:", error);+ });+ return;+ }+ if (clipboardModifier && key === "c" && onClipboardCopyRef.current) {+ interceptedClipboardKeysRef.current.add(e.code);+ onClipboardCopyRef.current();+ return;+ }const isPrintable = e.key.length === 1;const windowsVirtualKeyCode = virtualKeyCodeFor(e);const payload: Record<string, unknown> = {@@ -368,6 +438,9 @@ export function useCdpInput({(e: React.KeyboardEvent) => {if (!interactive || !userIsControlling) return;e.preventDefault();+ if (interceptedClipboardKeysRef.current.delete(e.code)) {+ return;+ }const windowsVirtualKeyCode = virtualKeyCodeFor(e);const payload: Record<string, unknown> = {type: "keyEvent",diff --git a/skyvern-frontend/src/routes/streaming/useRecordingMessageChannel.test.ts b/skyvern-frontend/src/routes/streaming/useRecordingMessageChannel.test.tsnew file mode 100644index 000000000..7120f4260--- /dev/null+++ b/skyvern-frontend/src/routes/streaming/useRecordingMessageChannel.test.ts@@ -0,0 +1,449 @@+import { act, renderHook } from "@testing-library/react";+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";++import {+ useRecordingStore,+ type MessageInExfiltratedConsoleEvent,+ type RecordingDraftStep,+} from "@/store/useRecordingStore";++import { useRecordingMessageChannel } from "./useRecordingMessageChannel";++const mocks = vi.hoisted(() => ({+ getWebSocketParams: vi.fn(async () => "client_id=client-test"),+}));++vi.mock("./webSocketParams", () => ({+ useWebSocketParams: () => mocks.getWebSocketParams,+}));++vi.mock("@/util/env", () => ({+ newWssBaseUrl: "wss://api.test",+}));++class MockWebSocket {+ static readonly OPEN = 1;+ static instances: MockWebSocket[] = [];++ readonly readyState = MockWebSocket.OPEN;+ readonly send = vi.fn();+ readonly close = vi.fn();+ onopen: ((event: Event) => void) | null = null;+ onmessage: ((event: MessageEvent) => void) | null = null;+ onclose: ((event: CloseEvent) => void) | null = null;++ constructor(readonly url: string) {+ MockWebSocket.instances.push(this);+ }++ emitOpen() {+ this.onopen?.(new Event("open"));+ }++ emitMessage(message: unknown) {+ this.onmessage?.(+ new MessageEvent("message", { data: JSON.stringify(message) }),+ );+ }++ emitClose(code = 1006) {+ this.onclose?.(new CloseEvent("close", { code }));+ }+}++const initialRecordingState = useRecordingStore.getState();++async function openSocket() {+ await act(async () => {+ await Promise.resolve();+ });+ const socket = MockWebSocket.instances[MockWebSocket.instances.length - 1];+ if (!socket) {+ throw new Error("No WebSocket was constructed");+ }+ act(() => socket.emitOpen());+ return socket;+}++function consoleClick(timestamp: number): MessageInExfiltratedConsoleEvent {+ return {+ kind: "exfiltrated-event",+ event_name: "user_interaction",+ source: "console",+ timestamp: timestamp / 1000,+ params: {+ type: "click",+ url: "https://example.test",+ timestamp,+ target: { tagName: "BUTTON", text: ["Submit"] },+ mousePosition: { xa: 640, ya: 360, xp: 0.5, yp: 0.5 },+ activeElement: { tagName: "BUTTON" },+ window: {+ width: 1280,+ height: 720,+ scrollX: 0,+ scrollY: 0,+ },+ },+ };+}++describe("useRecordingMessageChannel", () => {+ beforeEach(() => {+ vi.clearAllMocks();+ MockWebSocket.instances = [];+ vi.stubGlobal("WebSocket", MockWebSocket);+ useRecordingStore.setState(initialRecordingState, true);+ useRecordingStore.getState().reset();+ });++ afterEach(() => {+ vi.unstubAllGlobals();+ useRecordingStore.setState(initialRecordingState, true);+ });++ it("sends the complete begin-exfiltration payload on the rising edge", async () => {+ useRecordingStore.setState({+ isRecording: true,+ recordingAttemptId: "attempt-1",+ });+ const { rerender } = renderHook(+ ({ exfiltrate }) =>+ useRecordingMessageChannel({+ browserSessionId: "pbs-1",+ enabled: true,+ exfiltrate,+ workflowPermanentId: "workflow-1",+ clipboard: "none",+ }),+ { initialProps: { exfiltrate: false } },+ );+ const socket = await openSocket();+ socket.send.mockClear();++ rerender({ exfiltrate: true });++ expect(+ socket.send.mock.calls.map((call) => JSON.parse(String(call[0]))),+ ).toContainEqual({+ kind: "begin-exfiltration",+ workflow_permanent_id: "workflow-1",+ live_interpretation_enabled: true,+ supports_interpretation_deltas: true,+ recording_attempt_id: "attempt-1",+ });+ });++ it("sends end-exfiltration when discard and unmount happen together", async () => {+ useRecordingStore.setState({ isRecording: true });+ const { unmount } = renderHook(() =>+ useRecordingMessageChannel({+ browserSessionId: "pbs-1",+ enabled: true,+ exfiltrate: true,+ workflowPermanentId: null,+ clipboard: "none",+ }),+ );+ const socket = await openSocket();++ act(() => useRecordingStore.setState({ isRecording: false }));+ unmount();++ expect(+ socket.send.mock.calls.map((call) => JSON.parse(String(call[0]))),+ ).toEqual([+ expect.objectContaining({ kind: "begin-exfiltration" }),+ { kind: "end-exfiltration" },+ ]);+ });++ it("keeps a mid-recording reconnect resumable without sending end-exfiltration", async () => {+ useRecordingStore.setState({ isRecording: true });+ const { rerender } = renderHook(+ ({ reconnectTrigger }) =>+ useRecordingMessageChannel({+ browserSessionId: "pbs-1",+ enabled: true,+ exfiltrate: true,+ workflowPermanentId: null,+ clipboard: "none",+ reconnectTrigger,+ }),+ { initialProps: { reconnectTrigger: 0 } },+ );+ const firstSocket = await openSocket();++ rerender({ reconnectTrigger: 1 });+ const secondSocket = await openSocket();++ expect(+ firstSocket.send.mock.calls.map((call) => JSON.parse(String(call[0]))),+ ).not.toContainEqual({ kind: "end-exfiltration" });+ expect(+ secondSocket.send.mock.calls.map((call) => JSON.parse(String(call[0]))),+ ).toContainEqual(expect.objectContaining({ kind: "begin-exfiltration" }));+ });++ it("retries begin-exfiltration errors five times per recording", async () => {+ vi.useFakeTimers();+ try {+ useRecordingStore.setState({ isRecording: true });+ const { rerender } = renderHook(+ ({ exfiltrate }) =>+ useRecordingMessageChannel({+ browserSessionId: "pbs-1",+ enabled: true,+ exfiltrate,+ workflowPermanentId: null,+ clipboard: "none",+ }),+ { initialProps: { exfiltrate: true } },+ );+ const socket = await openSocket();++ for (let attempt = 0; attempt < 5; attempt += 1) {+ act(() =>+ socket.emitMessage({+ kind: "error",+ failed_kind: "begin-exfiltration",+ message: "Capture is not ready",+ }),+ );+ await act(async () => vi.advanceTimersByTimeAsync(2000));+ }++ const commands = socket.send.mock.calls.map((call) =>+ JSON.parse(String(call[0])),+ );+ expect(commands).toHaveLength(6);+ expect(commands).toEqual(+ commands.map(() =>+ expect.objectContaining({ kind: "begin-exfiltration" }),+ ),+ );++ act(() =>+ socket.emitMessage({+ kind: "error",+ failed_kind: "begin-exfiltration",+ message: "Capture is still not ready",+ }),+ );+ await act(async () => vi.advanceTimersByTimeAsync(2000));+ expect(socket.send).toHaveBeenCalledTimes(6);++ rerender({ exfiltrate: false });+ useRecordingStore.setState({ isRecording: true });+ rerender({ exfiltrate: true });+ socket.send.mockClear();+ act(() =>+ socket.emitMessage({+ kind: "error",+ failed_kind: "begin-exfiltration",+ message: "Capture is not ready for the next recording",+ }),+ );+ await act(async () => vi.advanceTimersByTimeAsync(2000));+ expect(+ socket.send.mock.calls.map((call) => JSON.parse(String(call[0]))),+ ).toContainEqual(expect.objectContaining({ kind: "begin-exfiltration" }));+ } finally {+ vi.useRealTimers();+ }+ });++ it("does not construct a socket after credential loading is cancelled", async () => {+ let resolveParams: ((params: string) => void) | undefined;+ mocks.getWebSocketParams.mockReturnValueOnce(+ new Promise<string>((resolve) => {+ resolveParams = resolve;+ }),+ );+ const { unmount } = renderHook(() =>+ useRecordingMessageChannel({+ browserSessionId: "pbs-1",+ enabled: true,+ exfiltrate: false,+ workflowPermanentId: null,+ clipboard: "none",+ }),+ );++ unmount();+ await act(async () => {+ resolveParams?.("client_id=late");+ await Promise.resolve();+ });++ expect(MockWebSocket.instances).toEqual([]);+ });++ it("reports disconnected when credential setup fails", async () => {+ const onConnectionChange = vi.fn();+ mocks.getWebSocketParams.mockRejectedValueOnce(+ new Error("credential lookup failed"),+ );++ renderHook(() =>+ useRecordingMessageChannel({+ browserSessionId: "pbs-1",+ enabled: true,+ exfiltrate: true,+ workflowPermanentId: null,+ clipboard: "none",+ onConnectionChange,+ }),+ );+ await act(async () => {+ await Promise.resolve();+ });++ expect(MockWebSocket.instances).toEqual([]);+ expect(onConnectionChange).toHaveBeenCalledWith(+ false,+ expect.objectContaining({ code: 1011 }),+ );+ });++ it("resets pause edges between exfiltration sessions", async () => {+ const { rerender } = renderHook(+ ({ exfiltrate }) =>+ useRecordingMessageChannel({+ browserSessionId: "pbs-1",+ enabled: true,+ exfiltrate,+ workflowPermanentId: null,+ clipboard: "none",+ }),+ { initialProps: { exfiltrate: true } },+ );+ const socket = await openSocket();++ act(() => useRecordingStore.setState({ manualCapturePaused: true }));+ expect(+ socket.send.mock.calls.map((call) => JSON.parse(String(call[0]))),+ ).toContainEqual({ kind: "recording-capture-pause" });++ rerender({ exfiltrate: false });+ socket.send.mockClear();+ rerender({ exfiltrate: true });++ expect(+ socket.send.mock.calls.map((call) => JSON.parse(String(call[0]))),+ ).toEqual(+ expect.arrayContaining([+ expect.objectContaining({ kind: "begin-exfiltration" }),+ { kind: "recording-capture-pause" },+ ]),+ );++ socket.send.mockClear();+ act(() => useRecordingStore.setState({ manualCapturePaused: false }));+ expect(+ socket.send.mock.calls.map((call) => JSON.parse(String(call[0]))),+ ).toContainEqual({ kind: "recording-capture-resume" });+ });++ it("rearms capture after an inbound CDP navigation event", async () => {+ useRecordingStore.setState({ isRecording: true });+ renderHook(() =>+ useRecordingMessageChannel({+ browserSessionId: "pbs-1",+ enabled: true,+ exfiltrate: true,+ workflowPermanentId: null,+ clipboard: "none",+ }),+ );+ const socket = await openSocket();+ socket.send.mockClear();+ const event = {+ kind: "exfiltrated-event",+ event_name: "nav:frame_navigated",+ source: "cdp",+ timestamp: 1,+ params: { targetInfo: { url: "https://example.test/next" } },+ };++ act(() => socket.emitMessage(event));++ expect(+ socket.send.mock.calls.map((call) => JSON.parse(String(call[0]))),+ ).toContainEqual({ kind: "recording-rearm-capture" });+ expect(useRecordingStore.getState().pendingEvents).toContainEqual(event);+ });++ it("stores the current frame for an inbound console click", async () => {+ const getFrameDataUrl = vi.fn(() => "data:image/jpeg;base64,frame");+ vi.stubGlobal("requestIdleCallback", (callback: IdleRequestCallback) => {+ callback({ didTimeout: false, timeRemaining: () => 50 });+ return 1;+ });+ useRecordingStore.setState({ isRecording: true });+ renderHook(() =>+ useRecordingMessageChannel({+ browserSessionId: "pbs-1",+ enabled: true,+ exfiltrate: true,+ workflowPermanentId: null,+ getFrameDataUrl,+ clipboard: "none",+ }),+ );+ const socket = await openSocket();++ act(() => socket.emitMessage(consoleClick(1_700_000_000_000)));++ expect(getFrameDataUrl).toHaveBeenCalled();+ expect(useRecordingStore.getState().screenshots).toContainEqual({+ timestampMs: 1_700_000_000_000,+ dataUrl: "data:image/jpeg;base64,frame",+ xp: 0.5,+ yp: 0.5,+ });+ });++ it("applies inbound interpretation updates to the recording store", async () => {+ useRecordingStore.setState({ isRecording: true });+ renderHook(() =>+ useRecordingMessageChannel({+ browserSessionId: "pbs-1",+ enabled: true,+ exfiltrate: true,+ workflowPermanentId: "workflow-1",+ clipboard: "none",+ }),+ );+ const socket = await openSocket();+ const step: RecordingDraftStep = {+ step_id: "step-1",+ action_kind: "click",+ block_type: "action",+ label: "Click submit",+ status: "ready",+ editable_fields: [],+ parameters: [],+ parameter_keys: [],+ };++ act(() =>+ socket.emitMessage({+ kind: "recording-interpretation-update",+ interpretation_session_id: "interpretation-1",+ session_revision: 1,+ steps: [step],+ pending: false,+ finalized: false,+ }),+ );++ expect(useRecordingStore.getState()).toMatchObject({+ interpretationSessionId: "interpretation-1",+ sessionRevision: 1,+ draftSteps: [step],+ interpretationPending: false,+ interpretationFinalized: false,+ });+ });+});diff --git a/skyvern-frontend/src/routes/streaming/useRecordingMessageChannel.ts b/skyvern-frontend/src/routes/streaming/useRecordingMessageChannel.tsnew file mode 100644index 000000000..8692b2b10--- /dev/null+++ b/skyvern-frontend/src/routes/streaming/useRecordingMessageChannel.ts@@ -0,0 +1,686 @@+import { useCallback, useEffect, useRef, useState } from "react";++import { toast } from "@/components/ui/use-toast";+import { buildOptimisticStep } from "@/routes/workflows/editor/recording/optimisticSteps";+import {+ useRecordingStore,+ type ExfiltratedEventConsoleParams,+ type MessageInExfiltratedEvent,+ type RecordingInterpretationUpdate,+} from "@/store/useRecordingStore";+import { copyText } from "@/util/copyText";+import { newWssBaseUrl } from "@/util/env";++import { useWebSocketParams } from "./webSocketParams";++export type RecordingClipboardMode = "vnc" | "message" | "none";++export interface UseRecordingMessageChannelOptions {+ browserSessionId: string | null;+ /** socket lifecycle gate: open the message WS while true */+ enabled: boolean;+ /** recording active: drives begin/end-exfiltration on edges */+ exfiltrate: boolean;+ workflowPermanentId: string | null;+ /** returns a data URL of the current frame for click screenshots, or null */+ getFrameDataUrl?: () => string | null;+ clipboard: RecordingClipboardMode;+ socketUrl?: string;+ reconnectTrigger?: number;+ onConnectionChange?: (connected: boolean, event?: CloseEvent) => void;+}++interface CommandBeginExfiltration {+ kind: "begin-exfiltration";+ workflow_permanent_id?: string;+ live_interpretation_enabled?: boolean;+ // Declares that this client understands delta interpretation updates, so the+ // backend may send changed_steps instead of full snapshots.+ supports_interpretation_deltas?: boolean;+ // Per-recording id: stable across reconnects, new per recording, so the+ // backend reuses the session on reconnect but starts fresh on a new recording.+ recording_attempt_id?: string;+}++interface CommandCedeControl {+ kind: "cede-control";+}++interface CommandEndExfiltration {+ kind: "end-exfiltration";+}++interface CommandTakeControl {+ kind: "take-control";+}++interface CommandRecordingCapturePause {+ kind: "recording-capture-pause";+}++interface CommandRecordingCaptureResume {+ kind: "recording-capture-resume";+}++interface CommandRecordingRearmCapture {+ kind: "recording-rearm-capture";+}++interface CommandAskForClipboardResponse {+ kind: "ask-for-clipboard-response";+ text: string;+}++interface CommandClipboardCopy {+ kind: "clipboard-copy";+}++interface CommandClipboardPaste {+ kind: "clipboard-paste";+ text: string;+}++// a "Command" is a fire-n-forget out-message - it does not require a response+export type Command =+ | CommandAskForClipboardResponse+ | CommandBeginExfiltration+ | CommandCedeControl+ | CommandClipboardCopy+ | CommandClipboardPaste+ | CommandEndExfiltration+ | CommandRecordingCapturePause+ | CommandRecordingCaptureResume+ | CommandRecordingRearmCapture+ | CommandTakeControl;++export interface UseRecordingMessageChannelResult {+ messageSocket: WebSocket | null;+ isMessageConnected: boolean;+ /** send a command over the message socket if open */+ sendCommand: (command: Command) => void;+}++const messageInKinds = [+ "ask-for-clipboard",+ "copied-text",+ "error",+ "exfiltrated-event",+ "recording-interpretation-update",+] as const;++type MessageInKind = (typeof messageInKinds)[number];++interface MessageInAskForClipboard {+ kind: "ask-for-clipboard";+}++interface MessageInCopiedText {+ kind: "copied-text";+ text: string;+}++interface MessageInError {+ kind: "error";+ failed_kind: string;+ message: string;+}++interface MessageInRecordingInterpretationUpdate extends RecordingInterpretationUpdate {+ kind: "recording-interpretation-update";+}++type MessageIn =+ | MessageInCopiedText+ | MessageInError+ | MessageInAskForClipboard+ | MessageInExfiltratedEvent+ | MessageInRecordingInterpretationUpdate;++function getMessage(data: unknown): MessageIn | undefined {+ if (!data) {+ return;+ }++ if (typeof data !== "object") {+ return;+ }++ if (!("kind" in data)) {+ return;+ }++ const k = data.kind;++ if (typeof k !== "string") {+ return;+ }++ if (!messageInKinds.includes(k as MessageInKind)) {+ return;+ }++ const kind = k as MessageInKind;++ switch (kind) {+ case "ask-for-clipboard": {+ return data as MessageInAskForClipboard;+ }+ case "copied-text": {+ if ("text" in data && typeof data.text === "string") {+ return {+ kind: "copied-text",+ text: data.text,+ };+ }+ break;+ }+ case "error": {+ if (+ "failed_kind" in data &&+ typeof data.failed_kind === "string" &&+ "message" in data &&+ typeof data.message === "string"+ ) {+ return {+ kind: "error",+ failed_kind: data.failed_kind,+ message: data.message,+ };+ }+ break;+ }+ case "exfiltrated-event": {+ if (+ "event_name" in data &&+ typeof data.event_name === "string" &&+ "params" in data &&+ typeof data.params === "object" &&+ data.params !== null &&+ "source" in data &&+ typeof data.source === "string"+ ) {+ const event = data as MessageInExfiltratedEvent;++ return {+ kind: "exfiltrated-event",+ event_name: event.event_name,+ params: event.params,+ source: event.source,+ timestamp: event.timestamp,+ } as MessageInExfiltratedEvent;+ }+ break;+ }+ case "recording-interpretation-update": {+ // steps is optional: a delta update carries changed_steps instead. Only+ // session_revision is required to accept the message.+ if (+ "session_revision" in data &&+ typeof data.session_revision === "number"+ ) {+ const update = data as MessageInRecordingInterpretationUpdate;+ return {+ kind: "recording-interpretation-update",+ interpretation_session_id:+ typeof update.interpretation_session_id === "string"+ ? update.interpretation_session_id+ : "",+ session_revision: update.session_revision,+ steps: Array.isArray(update.steps) ? update.steps : [],+ changed_steps: Array.isArray(update.changed_steps)+ ? update.changed_steps+ : [],+ // Absent/true => full snapshot (legacy). Only false triggers delta merge.+ is_snapshot:+ typeof update.is_snapshot === "boolean" ? update.is_snapshot : true,+ pending: typeof update.pending === "boolean" ? update.pending : false,+ finalized:+ typeof update.finalized === "boolean" ? update.finalized : false,+ };+ }+ break;+ }+ default: {+ const _exhaustive: never = kind;+ return _exhaustive;+ }+ }+}++function captureRecordingScreenshot(+ params: ExfiltratedEventConsoleParams,+ getFrameDataUrl: (() => string | null) | undefined,+) {+ const schedule =+ typeof requestIdleCallback === "function"+ ? (fn: () => void) => requestIdleCallback(fn, { timeout: 750 })+ : (fn: () => void) => window.setTimeout(fn, 0);++ schedule(() => {+ try {+ const dataUrl = getFrameDataUrl?.();+ if (!dataUrl) {+ return;+ }+ useRecordingStore.getState().addScreenshot({+ timestampMs: params.timestamp,+ dataUrl,+ xp: params.mousePosition.xp,+ yp: params.mousePosition.yp,+ });+ } catch {+ // toDataURL can throw on a tainted/headless canvas; shots are optional+ }+ });+}++function handleMessage(+ data: unknown,+ ws: WebSocket | null,+ clipboard: RecordingClipboardMode,+ getFrameDataUrl: (() => string | null) | undefined,+ onBeginExfiltrationError: () => void,+) {+ const message = getMessage(data);++ if (!message) {+ console.warn("Unknown message received on message channel:", data);+ return;+ }++ const kind = message.kind;++ const respond = (response: CommandAskForClipboardResponse) => {+ if (!ws) {+ console.warn("Cannot send message, as message socket is null.");+ console.warn(response);+ return;+ }++ ws.send(JSON.stringify(response));+ };++ switch (kind) {+ case "ask-for-clipboard": {+ if (clipboard !== "vnc") {+ break;+ }+ if (!navigator.clipboard) {+ console.warn("Clipboard API not available.");+ return;+ }++ navigator.clipboard+ .readText()+ .then((text) => {+ toast({+ title: "Pasting Into Browser",+ description:+ "Pasting your current clipboard text into the browser.",+ });++ respond({+ kind: "ask-for-clipboard-response",+ text,+ });+ })+ .catch((err) => {+ console.error("Failed to read clipboard contents: ", err);+ });++ break;+ }+ case "copied-text": {+ if (clipboard === "none") {+ break;+ }+ const text = message.text;++ copyText(text)+ .then((success) => {+ if (success) {+ toast({+ title: "Copied to Clipboard",+ description: "The text has been copied to your clipboard.",+ });+ } else {+ toast({+ variant: "destructive",+ title: "Failed to write to Clipboard",+ description: "The text could not be copied to your clipboard.",+ });+ }+ })+ .catch((err) => {+ console.error("Failed to write to clipboard:", err);++ toast({+ variant: "destructive",+ title: "Failed to write to Clipboard",+ description: "The text could not be copied to your clipboard.",+ });+ });++ break;+ }+ case "error": {+ if (message.failed_kind === "begin-exfiltration") {+ onBeginExfiltrationError();+ } else {+ console.warn("Message channel command failed:", message);+ }+ break;+ }+ case "exfiltrated-event": {+ // Read store state fresh: this handler is attached once per socket+ // and would otherwise see a stale isRecording.+ const store = useRecordingStore.getState();+ if (!store.isRecording && !store.finishRequested) {+ break;+ }+ if (store.isCapturePaused()) {+ break;+ }+ if (+ store.isRecording &&+ message.source === "console" &&+ message.params.type === "click"+ ) {+ captureRecordingScreenshot(message.params, getFrameDataUrl);+ }+ if (+ store.isRecording &&+ !store.finishRequested &&+ message.source === "cdp" &&+ (message.event_name === "nav:frame_navigated" ||+ message.event_name === "nav:navigated_within_document")+ ) {+ if (ws) {+ ws.send(JSON.stringify({ kind: "recording-rearm-capture" }));+ }+ }+ if (store.isRecording && !store.finishRequested) {+ const optimistic = buildOptimisticStep(message);+ if (optimistic) {+ store.addOptimisticStep(optimistic);+ }+ }+ store.add(message);+ break;+ }+ case "recording-interpretation-update": {+ useRecordingStore.getState().applyInterpretationUpdate({+ interpretation_session_id: message.interpretation_session_id,+ session_revision: message.session_revision,+ steps: message.steps,+ changed_steps: message.changed_steps,+ is_snapshot: message.is_snapshot,+ pending: message.pending,+ finalized: message.finalized,+ });+ break;+ }+ default: {+ const _exhaustive: never = kind;+ return _exhaustive;+ }+ }+}++export function useRecordingMessageChannel(+ options: UseRecordingMessageChannelOptions,+): UseRecordingMessageChannelResult {+ const {+ browserSessionId,+ enabled,+ exfiltrate,+ workflowPermanentId,+ socketUrl,+ reconnectTrigger,+ } = options;+ const [messageSocket, setMessageSocket] = useState<WebSocket | null>(null);+ const [isMessageConnected, setIsMessageConnected] = useState(false);+ const recordingAttemptId = useRecordingStore(+ (state) => state.recordingAttemptId,+ );+ const messageSocketRef = useRef<WebSocket | null>(null);+ const getWebSocketParams = useWebSocketParams();+ const optionsRef = useRef(options);+ const exfiltrateRef = useRef(exfiltrate);+ const beganRef = useRef(false);+ const previousExfiltrateRef = useRef(false);+ const beginRetryAttemptsRef = useRef(0);+ const beginRetryTimerRef = useRef<ReturnType<typeof setTimeout> | null>(null);+ optionsRef.current = options;+ exfiltrateRef.current = exfiltrate;++ const clearBeginRetry = useCallback(() => {+ if (beginRetryTimerRef.current) {+ clearTimeout(beginRetryTimerRef.current);+ beginRetryTimerRef.current = null;+ }+ }, []);++ const sendBeginExfiltration = useCallback(() => {+ const socket = messageSocketRef.current;+ if (+ !socket ||+ socket.readyState !== WebSocket.OPEN ||+ !exfiltrateRef.current+ ) {+ return;+ }+ const currentOptions = optionsRef.current;+ socket.send(+ JSON.stringify({+ kind: "begin-exfiltration",+ workflow_permanent_id: currentOptions.workflowPermanentId ?? undefined,+ live_interpretation_enabled: Boolean(+ currentOptions.workflowPermanentId,+ ),+ supports_interpretation_deltas: true,+ recording_attempt_id:+ useRecordingStore.getState().recordingAttemptId ?? undefined,+ }),+ );+ beganRef.current = true;+ }, []);++ const scheduleBeginRetry = useCallback(() => {+ if (+ !exfiltrateRef.current ||+ beginRetryTimerRef.current ||+ beginRetryAttemptsRef.current >= 5+ ) {+ return;+ }+ beginRetryAttemptsRef.current += 1;+ beginRetryTimerRef.current = setTimeout(() => {+ beginRetryTimerRef.current = null;+ sendBeginExfiltration();+ }, 2000);+ }, [sendBeginExfiltration]);++ useEffect(() => {+ setIsMessageConnected(false);+ setMessageSocket(null);+ }, [browserSessionId]);++ useEffect(() => {+ if (!enabled || !browserSessionId) {+ return;+ }++ let ws: WebSocket | null = null;+ let cancelled = false;++ const handleDisconnected = (+ event: CloseEvent,+ disconnectedSocket: WebSocket | null,+ ) => {+ if (+ disconnectedSocket === null ||+ messageSocketRef.current === disconnectedSocket+ ) {+ messageSocketRef.current = null;+ setIsMessageConnected(false);+ setMessageSocket(null);+ }+ if (cancelled) return;+ optionsRef.current.onConnectionChange?.(false, event);+ };++ const connect = async () => {+ const wsParams = await getWebSocketParams();+ if (cancelled) return;+ const messageUrl = `${socketUrl ?? `${newWssBaseUrl}/stream/messages/browser_session/${browserSessionId}`}?${wsParams}`;++ ws = new WebSocket(messageUrl);++ ws.onopen = () => {+ if (cancelled) return;+ messageSocketRef.current = ws;+ setIsMessageConnected(true);+ setMessageSocket(ws);+ optionsRef.current.onConnectionChange?.(true);+ };++ ws.onmessage = (event) => {+ const data = event.data;++ try {+ const message = JSON.parse(data);+ const currentOptions = optionsRef.current;+ handleMessage(+ message,+ ws,+ currentOptions.clipboard,+ currentOptions.getFrameDataUrl,+ scheduleBeginRetry,+ );+ } catch (e) {+ console.error(+ "Error parsing message from message channel:",+ e,+ event,+ );+ }+ };++ ws.onclose = (event) => {+ handleDisconnected(event, ws);+ };+ };++ void connect().catch((error) => {+ if (cancelled) return;+ console.error("Failed to set up recording message channel:", error);+ handleDisconnected(+ new CloseEvent("close", { code: 1011, reason: "setup_failed" }),+ null,+ );+ });++ return () => {+ cancelled = true;+ clearBeginRetry();+ // A mid-recording disconnect must leave the backend interpretation+ // session resumable (SKY-12429), so it does not send END. Once the store+ // says recording ended, cleanup flushes END for a same-commit panel+ // unmount that prevented the exfiltrate falling-edge effect from running.+ if (+ ws?.readyState === WebSocket.OPEN &&+ beganRef.current &&+ !useRecordingStore.getState().isRecording+ ) {+ ws.send(JSON.stringify({ kind: "end-exfiltration" }));+ beganRef.current = false;+ }+ messageSocketRef.current = null;+ try {+ ws && ws.close();+ } catch (e) {+ // pass+ }+ };+ // NOTE: adding getWebSocketParams causes constant reconnects of message channel when,+ // for instance, take-control or cede-control is clicked+ // eslint-disable-next-line react-hooks/exhaustive-deps+ }, [+ browserSessionId,+ clearBeginRetry,+ enabled,+ reconnectTrigger,+ scheduleBeginRetry,+ socketUrl,+ ]);++ const sendCommand = useCallback((command: Command) => {+ if (!messageSocketRef.current) {+ return;+ }++ messageSocketRef.current.send(JSON.stringify(command));+ }, []);++ // effect for exfiltration+ useEffect(() => {+ const risingEdge = exfiltrate && !previousExfiltrateRef.current;+ previousExfiltrateRef.current = exfiltrate;++ if (exfiltrate) {+ if (risingEdge) {+ beginRetryAttemptsRef.current = 0;+ }+ clearBeginRetry();+ sendBeginExfiltration();+ } else {+ clearBeginRetry();+ beginRetryAttemptsRef.current = 0;+ const socket = messageSocketRef.current;+ if (socket?.readyState === WebSocket.OPEN && beganRef.current) {+ socket.send(JSON.stringify({ kind: "end-exfiltration" }));+ beganRef.current = false;+ }+ }+ }, [+ clearBeginRetry,+ exfiltrate,+ messageSocket,+ recordingAttemptId,+ sendBeginExfiltration,+ workflowPermanentId,+ ]);++ const manualCapturePaused = useRecordingStore(+ (state) => state.manualCapturePaused,+ );+ const draftEditDepth = useRecordingStore((state) => state.draftEditDepth);+ const capturePaused = manualCapturePaused || draftEditDepth > 0;+ const previousCapturePausedRef = useRef(false);++ // Pause exfiltration + live interpretation while the operator edits drafts+ // or explicitly pauses capture.+ useEffect(() => {+ if (!exfiltrate || !messageSocket) {+ // Backend pause state is per exfiltration session, so start the next+ // session's edge detection from "not paused". A recording that ended+ // while paused would otherwise fire a spurious resume on the next start;+ // and if capture IS paused on a mid-recording reconnect, this re-sends+ // the pause to the new socket (idempotent) instead of assuming it.+ previousCapturePausedRef.current = false;+ return;+ }++ const wasPaused = previousCapturePausedRef.current;+ if (!wasPaused && capturePaused) {+ messageSocket.send(JSON.stringify({ kind: "recording-capture-pause" }));+ } else if (wasPaused && !capturePaused) {+ messageSocket.send(JSON.stringify({ kind: "recording-capture-resume" }));+ }++ previousCapturePausedRef.current = capturePaused;+ }, [capturePaused, exfiltrate, messageSocket]);++ return { messageSocket, isMessageConnected, sendCommand };+}diff --git a/skyvern-frontend/src/routes/streaming/webSocketParams.ts b/skyvern-frontend/src/routes/streaming/webSocketParams.tsnew file mode 100644index 000000000..c55f2bb4a--- /dev/null+++ b/skyvern-frontend/src/routes/streaming/webSocketParams.ts@@ -0,0 +1,18 @@+import { useCallback } from "react";++import { useCredentialGetter } from "@/hooks/useCredentialGetter";+import { useClientIdStore } from "@/store/useClientIdStore";+import { getCredentialParam } from "@/util/env";++export function useWebSocketParams(): () => Promise<string> {+ const credentialGetter = useCredentialGetter();+ const clientId = useClientIdStore((state) => state.clientId);++ return useCallback(async () => {+ const params = new URLSearchParams(+ await getCredentialParam(credentialGetter),+ );+ params.set("client_id", clientId);+ return params.toString();+ }, [clientId, credentialGetter]);+}diff --git a/skyvern-frontend/src/routes/workflows/editor/Workspace.tsx b/skyvern-frontend/src/routes/workflows/editor/Workspace.tsxindex 2729ee916..2279d7370 100644--- a/skyvern-frontend/src/routes/workflows/editor/Workspace.tsx+++ b/skyvern-frontend/src/routes/workflows/editor/Workspace.tsx@@ -33,7 +33,7 @@ import {Edge,} from "@xyflow/react";import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";-import { usePostHog } from "posthog-js/react";+import { useFeatureFlagEnabled, usePostHog } from "posthog-js/react";import {useWorkflowYamlEditorStore,@@ -49,6 +49,11 @@ import { useActiveRunSessionQuery } from "../hooks/useActiveRunSessionQuery";import { useDebugSessionQuery } from "../hooks/useDebugSessionQuery";import { useIsGlobalWorkflow } from "../hooks/useIsGlobalWorkflow";import { resolveWorkspaceBrowserSessionBindings } from "./browserSessionBindings";+import {+ resolveBrowserPanelMode,+ resolveCdpRecordingExfiltrate,+ updateBrowserPanelLatch,+} from "./browserPanelMode";import { useBlockScriptsQuery } from "@/routes/workflows/hooks/useBlockScriptsQuery";import { BrowserSessionStream } from "@/routes/browserSessions/BrowserSessionStream";import { useStreamTransport } from "@/hooks/useRuntimeConfig";@@ -127,6 +132,7 @@ import { isMacPlatform } from "@/util/platform";import { parseHeaderJson } from "@/util/secretHeaders";import { getJsonParseErrorDetail } from "@/util/jsonParseError";import { cn } from "@/util/utils";+import { RECORD_BROWSER_CDP_TRANSPORT_FLAG } from "@/util/featureFlags";import { FlowRenderer, type FlowRendererProps } from "./FlowRenderer";import { useCacheKeyValueUrlSync } from "./hooks/useCacheKeyValueUrlSync";@@ -814,11 +820,37 @@ function Workspace({const { streamTransport } = useStreamTransport(activeDebugSession?.browser_session_id,);- const isCdpStreamingMode =- streamTransport === "cdp" && !recordingStore.isRecording;- // Record Browser exfiltration requires VNC even when the transport is CDP streaming.- const preferVncStream =- streamTransport !== "cdp" || recordingStore.isRecording;+ const cdpRecordingFlagEnabled =+ useFeatureFlagEnabled(RECORD_BROWSER_CDP_TRANSPORT_FLAG) ?? false;+ const browserPanelLatchRef = useRef({+ streamTransport,+ cdpRecordingEnabled: cdpRecordingFlagEnabled,+ });+ browserPanelLatchRef.current = updateBrowserPanelLatch(+ browserPanelLatchRef.current,+ {+ streamTransport,+ cdpRecordingEnabled: cdpRecordingFlagEnabled,+ },+ recordingStore.isRecording,+ );+ const { streamTransport: latchedStreamTransport, cdpRecordingEnabled } =+ browserPanelLatchRef.current;+ // Keep the panel mode stable if transport resolution or PostHog changes mid-recording.+ const { showCdp: isCdpStreamingMode, preferVnc: preferVncStream } =+ resolveBrowserPanelMode({+ streamTransport: latchedStreamTransport,+ isRecording: recordingStore.isRecording,+ cdpRecordingEnabled,+ });+ const recordingTransport =+ showBrowser && latchedStreamTransport === "cdp" && cdpRecordingEnabled+ ? "cdp"+ : "vnc";+ const setRecordingTransport = recordingStore.setRecordingTransport;+ useLayoutEffect(() => {+ setRecordingTransport(recordingTransport);+ }, [setRecordingTransport, recordingTransport]);const workflowChangesStore = useWorkflowHasChangesStore();@@ -2698,6 +2730,12 @@ function Workspace({) : isFlowCanvasReady || recordingStore.isRecording ? (<BrowserSessionStreambrowserSessionId={displayBrowserSessionId}+ exfiltrate={resolveCdpRecordingExfiltrate({+ cdpRecordingEnabled,+ isRecording: recordingStore.isRecording,+ finishRequested: recordingStore.finishRequested,+ })}+ workflowPermanentId={workflowPermanentId ?? null}interactive={true}showControlButtons={true}// The CDP transport streams the page viewport only, sodiff --git a/skyvern-frontend/src/routes/workflows/editor/browserPanelMode.test.ts b/skyvern-frontend/src/routes/workflows/editor/browserPanelMode.test.tsnew file mode 100644index 000000000..20cc65025--- /dev/null+++ b/skyvern-frontend/src/routes/workflows/editor/browserPanelMode.test.ts@@ -0,0 +1,90 @@+import { describe, expect, it } from "vitest";++import {+ resolveBrowserPanelMode,+ resolveCdpRecordingExfiltrate,+ updateBrowserPanelLatch,+} from "./browserPanelMode";++describe("resolveBrowserPanelMode", () => {+ it("downgrades a flag-off CDP recording to VNC", () => {+ expect(+ resolveBrowserPanelMode({+ streamTransport: "cdp",+ isRecording: true,+ cdpRecordingEnabled: false,+ }),+ ).toEqual({ showCdp: false, preferVnc: true });+ });++ it("keeps a flag-on CDP recording on CDP", () => {+ expect(+ resolveBrowserPanelMode({+ streamTransport: "cdp",+ isRecording: true,+ cdpRecordingEnabled: true,+ }),+ ).toEqual({ showCdp: true, preferVnc: false });+ });++ it("prefers VNC while the transport is pending", () => {+ expect(+ resolveBrowserPanelMode({+ streamTransport: undefined,+ isRecording: false,+ cdpRecordingEnabled: true,+ }),+ ).toEqual({ showCdp: false, preferVnc: true });+ });+});++describe("updateBrowserPanelLatch", () => {+ it("keeps a pending transport from switching to CDP mid-recording", () => {+ const latch = {+ streamTransport: undefined,+ cdpRecordingEnabled: true,+ } as const;++ const duringRecording = updateBrowserPanelLatch(+ latch,+ {+ streamTransport: "cdp",+ cdpRecordingEnabled: true,+ },+ true,+ );+ expect(+ resolveBrowserPanelMode({+ ...duringRecording,+ isRecording: true,+ }),+ ).toEqual({ showCdp: false, preferVnc: true });++ const afterRecording = updateBrowserPanelLatch(+ duringRecording,+ {+ streamTransport: "cdp",+ cdpRecordingEnabled: true,+ },+ false,+ );+ expect(+ resolveBrowserPanelMode({+ ...afterRecording,+ isRecording: false,+ }),+ ).toEqual({ showCdp: true, preferVnc: false });+ });+});++describe("resolveCdpRecordingExfiltrate", () => {+ it("leaves CDP recording messages disabled while the flag is off", () => {+ expect(+ resolveCdpRecordingExfiltrate({+ cdpRecordingEnabled: false,+ isRecording: true,+ finishRequested: false,+ }),+ ).toBeUndefined();+ });+});diff --git a/skyvern-frontend/src/routes/workflows/editor/browserPanelMode.ts b/skyvern-frontend/src/routes/workflows/editor/browserPanelMode.tsnew file mode 100644index 000000000..77110856b--- /dev/null+++ b/skyvern-frontend/src/routes/workflows/editor/browserPanelMode.ts@@ -0,0 +1,42 @@+import type { BrowserStreamingMode } from "@/hooks/useRuntimeConfig";++export interface BrowserPanelLatch {+ streamTransport: BrowserStreamingMode | undefined;+ cdpRecordingEnabled: boolean;+}++export function updateBrowserPanelLatch(+ latched: BrowserPanelLatch,+ current: BrowserPanelLatch,+ isRecording: boolean,+): BrowserPanelLatch {+ return isRecording ? latched : current;+}++export function resolveCdpRecordingExfiltrate({+ cdpRecordingEnabled,+ isRecording,+ finishRequested,+}: {+ cdpRecordingEnabled: boolean;+ isRecording: boolean;+ finishRequested: boolean;+}): boolean | undefined {+ return cdpRecordingEnabled ? isRecording && !finishRequested : undefined;+}++export function resolveBrowserPanelMode({+ streamTransport,+ isRecording,+ cdpRecordingEnabled,+}: {+ streamTransport: BrowserStreamingMode | undefined;+ isRecording: boolean;+ cdpRecordingEnabled: boolean;+}): { showCdp: boolean; preferVnc: boolean } {+ return {+ showCdp: streamTransport === "cdp" && (cdpRecordingEnabled || !isRecording),+ preferVnc:+ streamTransport !== "cdp" || (!cdpRecordingEnabled && isRecording),+ };+}diff --git a/skyvern-frontend/src/store/useRecordingStore.test.ts b/skyvern-frontend/src/store/useRecordingStore.test.tsindex 777574e1f..855001f40 100644--- a/skyvern-frontend/src/store/useRecordingStore.test.ts+++ b/skyvern-frontend/src/store/useRecordingStore.test.ts@@ -1,4 +1,6 @@-import { beforeEach, describe, expect, it } from "vitest";+import { beforeEach, describe, expect, it, vi } from "vitest";++import { captureRecordBrowser } from "@/util/recordBrowserTelemetry";import {upsertDraftSteps,@@ -10,6 +12,10 @@ import {type RecordingInterpretationUpdate,} from "./useRecordingStore";+vi.mock("@/util/recordBrowserTelemetry", () => ({+ captureRecordBrowser: vi.fn(),+}));+let seq = 0;function opt(kind: OptimisticActionKind = "click"): OptimisticStep {seq += 1;@@ -65,6 +71,8 @@ const store = () => useRecordingStore.getState();beforeEach(() => {store().reset();+ store().setRecordingTransport("vnc");+ vi.clearAllMocks();});describe("addOptimisticStep", () => {@@ -188,6 +196,66 @@ describe("commit safety and resets", () => {expect(second).toBeTruthy();expect(second).not.toBe(first);});++ it("reports the selected transport when recording starts", () => {+ store().setRecordingTransport("cdp");++ store().setIsRecording(true, {+ workflowPermanentId: "wpid-1",+ browserSessionId: "pbs-1",+ });++ expect(captureRecordBrowser).toHaveBeenCalledWith(+ "record_browser.started",+ expect.objectContaining({ transport: "cdp" }),+ );+ });++ it("preserves the selected transport for the next recording after reset", () => {+ store().setRecordingTransport("cdp");+ store().setIsRecording(true);+ store().setIsRecording(false);+ store().reset();+ vi.mocked(captureRecordBrowser).mockClear();++ store().setIsRecording(true);++ expect(captureRecordBrowser).toHaveBeenCalledWith(+ "record_browser.started",+ expect.objectContaining({ transport: "cdp" }),+ );+ });++ it("reports unfinished resets as abandoned but excludes finish and cancel paths", () => {+ store().setRecordingTransport("cdp");+ store().setIsRecording(true);+ vi.mocked(captureRecordBrowser).mockClear();++ store().reset();++ expect(captureRecordBrowser).toHaveBeenCalledWith(+ "record_browser.abandoned",+ expect.objectContaining({ transport: "cdp" }),+ );++ store().setIsRecording(true);+ store().requestFinish();+ vi.mocked(captureRecordBrowser).mockClear();+ store().reset();+ expect(captureRecordBrowser).not.toHaveBeenCalledWith(+ "record_browser.abandoned",+ expect.anything(),+ );++ store().setIsRecording(true);+ store().setIsRecording(false);+ vi.mocked(captureRecordBrowser).mockClear();+ store().reset();+ expect(captureRecordBrowser).not.toHaveBeenCalledWith(+ "record_browser.abandoned",+ expect.anything(),+ );+ });});describe("upsertDraftSteps", () => {diff --git a/skyvern-frontend/src/store/useRecordingStore.ts b/skyvern-frontend/src/store/useRecordingStore.tsindex 884a00892..3f2f96d4f 100644--- a/skyvern-frontend/src/store/useRecordingStore.ts+++ b/skyvern-frontend/src/store/useRecordingStore.ts@@ -2,6 +2,8 @@ import { create } from "zustand";import { captureRecordBrowser } from "@/util/recordBrowserTelemetry";+export type RecordingTransport = "cdp" | "vnc";+const EVENT_CAPTURED_SAMPLE_RATE = 0.1;/**@@ -243,6 +245,7 @@ interface RecordingStore {*/isRecording: boolean;recordingStartedAtMs: number | null;+ recordingTransport: RecordingTransport;/*** The workflow the recording will be committed to. Required to enable* backend live interpretation.@@ -344,6 +347,7 @@ interface RecordingStore {browserSessionId?: string | null;},) => void;+ setRecordingTransport: (transport: RecordingTransport) => void;/*** Flush any pending events into a compressed chunk.* Call this before consuming the data.@@ -521,6 +525,7 @@ export const useRecordingStore = create<RecordingStore>((set, get) => ({isCompressing: false,isRecording: false,recordingStartedAtMs: null,+ recordingTransport: "vnc",workflowPermanentId: null,recordingAttemptId: null,draftSteps: [],@@ -744,28 +749,47 @@ export const useRecordingStore = create<RecordingStore>((set, get) => ({set(emptyRecordingState());},- reset: () =>+ reset: () => {+ const state = get();+ if (state.isRecording && !state.finishRequested) {+ captureRecordBrowser("record_browser.abandoned", {+ transport: state.recordingTransport,+ duration_ms: Math.round(state.getSecondsRecording() * 1000),+ event_count: state.getEventCount(),+ optimistic_step_count: state.optimisticSteps.length,+ });+ }set({...emptyRecordingState(),isCompressing: false,isRecording: false,workflowPermanentId: null,- }),+ });+ },++ setRecordingTransport: (recordingTransport) => {+ if (!get().isRecording) {+ set({ recordingTransport });+ }+ },setIsRecording: (isRecording, meta) => {if (isRecording) {const state = get();if (!state.isRecording) {+ const recordingTransport = state.recordingTransport;get().clear();set({isRecording: true,recordingStartedAtMs: Date.now(),+ recordingTransport,workflowPermanentId: meta?.workflowPermanentId ?? null,recordingAttemptId: crypto.randomUUID(),});captureRecordBrowser("record_browser.started", {workflow_permanent_id: meta?.workflowPermanentId ?? undefined,browser_session_id: meta?.browserSessionId ?? undefined,+ transport: recordingTransport,});}return;@@ -773,7 +797,6 @@ export const useRecordingStore = create<RecordingStore>((set, get) => ({set({isRecording: false,- recordingStartedAtMs: null,finishRequested: false,isCommitting: false,});diff --git a/skyvern-frontend/src/util/featureFlags.ts b/skyvern-frontend/src/util/featureFlags.tsindex ef57b7478..1f3f92af0 100644--- a/skyvern-frontend/src/util/featureFlags.ts+++ b/skyvern-frontend/src/util/featureFlags.ts@@ -37,3 +37,6 @@ export const CREDENTIAL_FALLBACK_RETRY_FLAG = "CREDENTIAL_FALLBACK_RETRY";// Opt-in preview (0% base): recordings synthesize code blocks instead of agent blocks.export const RECORD_BROWSER_CODE_FIRST_FLAG = "record_browser_code_first";++// Opt-in (0% base): recording keeps the CDP stream instead of swapping to VNC.+export const RECORD_BROWSER_CDP_TRANSPORT_FLAG = "record_browser_cdp_transport";diff --git a/skyvern/forge/sdk/routes/agent_protocol.py b/skyvern/forge/sdk/routes/agent_protocol.pyindex 866f9ccab..04791ff97 100644--- a/skyvern/forge/sdk/routes/agent_protocol.py+++ b/skyvern/forge/sdk/routes/agent_protocol.py@@ -4263,6 +4263,11 @@ async def _parse_and_gate_tag_filter_terms("/runs",tags=["agent"],response_model=list[TaskRunListItem],+ summary="List runs",+ description=(+ "List the organization's task and agent runs, newest first, filterable by status, run type, agent, "+ "and a free-text search term. Returns a paginated array of run summaries."+ ),openapi_extra={"x-hidden": True,"x-fern-sdk-method-name": "get_runs_v2",@@ -5222,6 +5227,10 @@ async def get_workflow_templates() -> list[Workflow]:response_model=Workflow,tags=["Agents"],summary="Get an agent by id",+ description=(+ "Fetch a single agent definition by its permanent id, optionally pinned to a specific version. "+ "Returns the agent's blocks, parameters, and metadata."+ ),openapi_extra={"x-fern-sdk-method-name": "get_workflow",},@@ -5649,6 +5658,11 @@ async def get_api_keys(@base_router.post("/upload_file",tags=["Files"],+ summary="Upload a file",+ description=(+ "Upload a file to Skyvern storage so runs can reference it as an input. Returns the file id, its "+ "storage URI, a presigned download URL, and the expiry implied by the requested retention period."+ ),openapi_extra={"x-fern-sdk-method-name": "upload_file",},diff --git a/skyvern/forge/sdk/routes/streaming/cdp_input.py b/skyvern/forge/sdk/routes/streaming/cdp_input.pyindex 06602cfff..acc2792c8 100644--- a/skyvern/forge/sdk/routes/streaming/cdp_input.py+++ b/skyvern/forge/sdk/routes/streaming/cdp_input.py@@ -70,6 +70,8 @@ _MAX_URL_LEN = 2083ACTIVE_PAGE_INPUT_REFRESH_INTERVAL = 0.5_NAVIGATION_RESET_TIMEOUT_MS = 5_000_TARGET_CLOSED_ERROR_TYPES = frozenset({"TargetClosedError", "CdpTargetClosedError"})+_PIPELINED_INPUT_KINDS = frozenset({"mouseEvent", "wheelEvent", "keyEvent"})+_MAX_IN_FLIGHT_INPUT_DISPATCHES = 32def _input_kind_label(kind: object) -> str:@@ -304,6 +306,28 @@ _EVENT_DISPATCH_MAP: dict[str, tuple[t.Callable[[dict], dict | None], str]] = {}+def _validate_cdp_dispatch(+ kind: str,+ msg: dict,+ log_id_key: str,+ log_id_value: str,+) -> tuple[str, dict] | None:+ entry = _EVENT_DISPATCH_MAP.get(kind)+ if entry is None:+ return None+ validator, cdp_method = entry+ validated = validator(msg)+ if validated is not None:+ return cdp_method, validated+ LOG.warning(+ "CDP input: validation failed",+ **{log_id_key: log_id_value},+ kind=kind,+ raw_event_type=msg.get("eventType"),+ )+ return None++async def _reset_page_after_navigation_failure(page: object,log_id_key: str,@@ -443,20 +467,11 @@ async def _dispatch_event(await _dispatch_history_event(cdp_session, kind, log_id_key, log_id_value, websocket)return- entry = _EVENT_DISPATCH_MAP.get(kind)- if entry is None:+ dispatch = _validate_cdp_dispatch(kind, msg, log_id_key, log_id_value)+ if dispatch is None:return- validator, cdp_method = entry- validated = validator(msg)- if validated:- await cdp_session.send(cdp_method, validated)- else:- LOG.warning(- "CDP input: validation failed",- **{log_id_key: log_id_value},- kind=kind,- raw_event_type=msg.get("eventType"),- )+ cdp_method, validated = dispatch+ await cdp_session.send(cdp_method, validated)async def _run_input_loop(@@ -468,74 +483,144 @@ async def _run_input_loop() -> None:dropped_log_count = 0no_active_page_log_count = 0- while True:- try:- raw = await websocket.receive_text()- except WebSocketDisconnect:- break- received_at = time.monotonic()-+ dispatch_semaphore = asyncio.Semaphore(_MAX_IN_FLIGHT_INPUT_DISPATCHES)+ dispatch_tasks: set[asyncio.Task[None]] = set()+ dispatch_failure_close_started = False++ async def dispatch_pipelined_event(+ cdp_session: CDPSession,+ kind: str,+ cdp_method: str,+ validated: dict,+ received_at: float,+ ) -> None:+ nonlocal dispatch_failure_close_started+ attributes = {"event_kind": _input_kind_label(kind)}+ dispatch_started = time.monotonic()+ _input_wait_seconds.record(dispatch_started - received_at, attributes)try:- msg = json.loads(raw)- except json.JSONDecodeError:- LOG.warning("CDP input: malformed JSON", **{log_id_key: log_id_value})- continue-- kind = msg.get("kind") or msg.get("type")-- if kind == "take-control":- channel.interactor = "user"- LOG.info("CDP input: take-control received", **{log_id_key: log_id_value}, client_id=channel.client_id)- continue- if kind == "cede-control":- channel.interactor = "agent"- LOG.info("CDP input: cede-control received", **{log_id_key: log_id_value}, client_id=channel.client_id)- continue-- if channel.interactor != "user":- if dropped_log_count < 5:- LOG.info(- "CDP input: event dropped",- interactor=channel.interactor,+ try:+ await cdp_session.send(cdp_method, validated)+ finally:+ _input_dispatch_seconds.record(time.monotonic() - dispatch_started, attributes)+ except Exception as error:+ if _is_navigation_target_loss(error):+ LOG.debug(+ "CDP input: dropped event for detached pipelined session",**{log_id_key: log_id_value},kind=kind,+ error_type=type(error).__name__,)- dropped_log_count += 1- continue-- try:- cdp_session = await input_session.get_session()- except Exception:+ returnLOG.warning(- "CDP input: failed to resolve active page; closing input channel",+ "CDP input: failed to dispatch event; closing input channel",**{log_id_key: log_id_value},kind=kind,exc_info=True,)- await websocket.close(code=4411, reason="active_page_resolution_failed")- break+ if not dispatch_failure_close_started:+ dispatch_failure_close_started = True+ await _close_ws_safely(websocket, code=4411, reason="dispatch_failed")+ finally:+ dispatch_semaphore.release()- if cdp_session is None:- if no_active_page_log_count < 5:- LOG.info("CDP input: no active page; event skipped", **{log_id_key: log_id_value}, kind=kind)- no_active_page_log_count += 1- continue+ try:+ while True:+ try:+ raw = await websocket.receive_text()+ except WebSocketDisconnect:+ break+ received_at = time.monotonic()++ try:+ msg = json.loads(raw)+ except json.JSONDecodeError:+ LOG.warning("CDP input: malformed JSON", **{log_id_key: log_id_value})+ continue++ kind = msg.get("kind") or msg.get("type")++ if kind == "take-control":+ channel.interactor = "user"+ LOG.info("CDP input: take-control received", **{log_id_key: log_id_value}, client_id=channel.client_id)+ continue+ if kind == "cede-control":+ channel.interactor = "agent"+ LOG.info("CDP input: cede-control received", **{log_id_key: log_id_value}, client_id=channel.client_id)+ continue++ if channel.interactor != "user":+ if dropped_log_count < 5:+ LOG.info(+ "CDP input: event dropped",+ interactor=channel.interactor,+ **{log_id_key: log_id_value},+ kind=kind,+ )+ dropped_log_count += 1+ continue++ try:+ cdp_session = await input_session.get_session()+ except Exception:+ LOG.warning(+ "CDP input: failed to resolve active page; closing input channel",+ **{log_id_key: log_id_value},+ kind=kind,+ exc_info=True,+ )+ await websocket.close(code=4411, reason="active_page_resolution_failed")+ break- attributes = {"event_kind": _input_kind_label(kind)}- dispatch_started = time.monotonic()- _input_wait_seconds.record(dispatch_started - received_at, attributes)- try:- await _dispatch_event(cdp_session, input_session.page, kind, msg, log_id_key, log_id_value, websocket)- except Exception:- LOG.warning(- "CDP input: failed to dispatch event; closing input channel",- **{log_id_key: log_id_value},- kind=kind,- exc_info=True,- )- await websocket.close(code=4411, reason="dispatch_failed")- break- _input_dispatch_seconds.record(time.monotonic() - dispatch_started, attributes)+ if cdp_session is None:+ if no_active_page_log_count < 5:+ LOG.info("CDP input: no active page; event skipped", **{log_id_key: log_id_value}, kind=kind)+ no_active_page_log_count += 1+ continue++ if kind in _PIPELINED_INPUT_KINDS:+ dispatch = _validate_cdp_dispatch(kind, msg, log_id_key, log_id_value)+ if dispatch is None:+ continue+ cdp_method, validated = dispatch+ await dispatch_semaphore.acquire()+ if dispatch_failure_close_started:+ dispatch_semaphore.release()+ break+ task = asyncio.create_task(+ dispatch_pipelined_event(cdp_session, kind, cdp_method, validated, received_at)+ )+ dispatch_tasks.add(task)+ task.add_done_callback(dispatch_tasks.discard)+ # CDPSession.send writes to one transport before awaiting a response, preserving receive order here.+ await asyncio.sleep(0)+ if dispatch_failure_close_started:+ break+ continue++ attributes = {"event_kind": _input_kind_label(kind)}+ dispatch_started = time.monotonic()+ _input_wait_seconds.record(dispatch_started - received_at, attributes)+ try:+ await _dispatch_event(cdp_session, input_session.page, kind, msg, log_id_key, log_id_value, websocket)+ except Exception:+ LOG.warning(+ "CDP input: failed to dispatch event; closing input channel",+ **{log_id_key: log_id_value},+ kind=kind,+ exc_info=True,+ )+ if not dispatch_failure_close_started:+ dispatch_failure_close_started = True+ await websocket.close(code=4411, reason="dispatch_failed")+ break+ _input_dispatch_seconds.record(time.monotonic() - dispatch_started, attributes)+ finally:+ pending_tasks = tuple(dispatch_tasks)+ for task in pending_tasks:+ task.cancel()+ if pending_tasks:+ await asyncio.gather(*pending_tasks, return_exceptions=True)@legacy_base_router.websocket("/stream/cdp_input/workflow_run/{workflow_run_id}")diff --git a/skyvern/forge/sdk/routes/streaming/channels/cdp.py b/skyvern/forge/sdk/routes/streaming/channels/cdp.pyindex dee210ae2..9ef3cf9ac 100644--- a/skyvern/forge/sdk/routes/streaming/channels/cdp.py+++ b/skyvern/forge/sdk/routes/streaming/channels/cdp.py@@ -31,11 +31,29 @@ from skyvern.webeye.driver_connection import close_driver_connection_on_transporfrom skyvern.webeye.main_world_eval import evaluate_in_main_worldif t.TYPE_CHECKING:- from skyvern.forge.sdk.routes.streaming.channels.vnc import VncChannel+ from skyvern.forge.sdk.schemas.persistent_browser_sessions import AddressablePersistentBrowserSessionLOG = structlog.get_logger()+class ChannelContext(t.Protocol):+ """The connection identity a CdpChannel dials with. Members are read-only+ properties so implementations may delegate to live channel state (a+ session's browser_address can rotate mid-connection)."""++ @property+ def organization_id(self) -> str: ...++ @property+ def x_api_key(self) -> str: ...++ @property+ def browser_session(self) -> AddressablePersistentBrowserSession | None: ...++ @property+ def identity(self) -> dict[str, t.Any]: ...++@functools.lru_cache(maxsize=None)def _load_js_asset(file_name: str) -> str:# Module-level so the cache key is the asset name only. A method-level lru_cache@@ -54,10 +72,7 @@ def _load_js_asset(file_name: str) -> str:class CdpChannel:- """- CdpChannel. Relies on a VncChannel - without one, a CdpChannel has no- r'aison d'etre.- """+ """A CDP channel backed by browser session context."""def __new__(cls, *_: t.Iterable[t.Any], **__: t.Mapping[str, t.Any]) -> t.Self: # noqa: N805if cls is CdpChannel:@@ -65,8 +80,8 @@ class CdpChannel:return super().__new__(cls)- def __init__(self, *, vnc_channel: VncChannel) -> None:- self.vnc_channel = vnc_channel+ def __init__(self, *, context: ChannelContext) -> None:+ self.context = context# --self.browser: Browser | None = Noneself.browser_context: BrowserContext | None = None@@ -84,7 +99,7 @@ class CdpChannel:@propertydef identity(self) -> t.Dict[str, t.Any]:- base = self.vnc_channel.identity+ base = self.context.identity# This mapping is splatted into every log line this channel writes, and the url it holds# is the session's own address — which carries the session token.@@ -107,8 +122,8 @@ class CdpChannel:if cdp_url:url = cdp_url- elif self.vnc_channel.browser_session and self.vnc_channel.browser_session.browser_address:- url = self.vnc_channel.browser_session.browser_address+ elif self.context.browser_session and self.context.browser_session.browser_address:+ url = self.context.browser_session.browser_addresselse:url = settings.BROWSER_REMOTE_DEBUGGING_URL@@ -126,11 +141,11 @@ class CdpChannel:self.pw = pwheaders: dict[str, str] | None = None- if self.vnc_channel.x_api_key:- headers = {"x-api-key": self.vnc_channel.x_api_key}- if self.vnc_channel.browser_session and is_local_pbs_cdp_url(url):+ if self.context.x_api_key:+ headers = {"x-api-key": self.context.x_api_key}+ if self.context.browser_session and is_local_pbs_cdp_url(url):headers = headers or {}- headers["X-Session-Id"] = self.vnc_channel.browser_session.persistent_browser_session_id+ headers["X-Session-Id"] = self.context.browser_session.persistent_browser_session_iddef on_close() -> None:if self._closing:@@ -171,10 +186,10 @@ class CdpChannel:return selfasync def apply_download_behavior(self, browser: Browser) -> t.Self:- org_id = self.vnc_channel.organization_id+ org_id = self.context.organization_idbrowser_session_id = (- self.vnc_channel.browser_session.persistent_browser_session_id if self.vnc_channel.browser_session else None+ self.context.browser_session.persistent_browser_session_id if self.context.browser_session else None)download_path = f"/app/downloads/{org_id}/{browser_session_id}" if browser_session_id else "/app/downloads/"diff --git a/skyvern/forge/sdk/routes/streaming/channels/execution.py b/skyvern/forge/sdk/routes/streaming/channels/execution.pyindex 0db51b629..285cb61ef 100644--- a/skyvern/forge/sdk/routes/streaming/channels/execution.py+++ b/skyvern/forge/sdk/routes/streaming/channels/execution.py@@ -246,8 +246,8 @@ class ExecutionChannel(CdpChannel):class LocalExecutionChannel(ExecutionChannel):def __init__(self, *, page: Page) -> None: # type: ignore[override]- # bypass CdpChannel.__init__ which requires a VncChannel- self.vnc_channel = None # type: ignore[assignment]+ # bypass CdpChannel.__init__ which requires a ChannelContext+ self.context = None # type: ignore[assignment]self.browser = Noneself.browser_context = page.contextself.page = page@@ -266,7 +266,7 @@ class LocalExecutionChannel(ExecutionChannel):expression: str,arg: str | int | float | bool | list | dict | None = None,) -> str | int | float | bool | list | dict | None:- # Skip the inherited connect() — it dereferences self.vnc_channel,+ # Skip the inherited connect() — it dereferences self.context,# which LocalExecutionChannel intentionally leaves None.if not self.page:raise RuntimeError(f"{self.class_name} evaluate_js: no page available.")@@ -345,7 +345,7 @@ async def execution_channel(vnc_channel: VncChannel) -> t.AsyncIterator[ExecutioIf it turns out it's too slow, we can refactor to keep a persistent channel per vnc client."""- channel = ExecutionChannel(vnc_channel=vnc_channel)+ channel = ExecutionChannel(context=vnc_channel)try:await channel.connect()diff --git a/skyvern/forge/sdk/routes/streaming/channels/exfiltration.py b/skyvern/forge/sdk/routes/streaming/channels/exfiltration.pyindex 1d1293849..8d53980b0 100644--- a/skyvern/forge/sdk/routes/streaming/channels/exfiltration.py+++ b/skyvern/forge/sdk/routes/streaming/channels/exfiltration.py@@ -23,8 +23,7 @@ import weakrefimport structlogfrom playwright.async_api import CDPSession, ConsoleMessage, Frame, Page-from skyvern.forge.sdk.routes.streaming.channels.cdp import CdpChannel-from skyvern.forge.sdk.routes.streaming.channels.vnc import VncChannel+from skyvern.forge.sdk.routes.streaming.channels.cdp import CdpChannel, ChannelContextLOG = structlog.get_logger()@@ -98,7 +97,7 @@ class ExfiltrationChannel(CdpChannel):_rearm_in_flight_pages: t.ClassVar[weakref.WeakKeyDictionary[Page, bool]] = weakref.WeakKeyDictionary()_rearm_pending_full_nav_pages: t.ClassVar[weakref.WeakSet[Page]] = weakref.WeakSet()- def __init__(self, *, on_event: OnExfiltrationEvent, vnc_channel: VncChannel) -> None:+ def __init__(self, *, on_event: OnExfiltrationEvent, context: ChannelContext) -> None:self.cdp_session: CDPSession | None = Noneself.on_event = on_eventself._page_console_captures: weakref.WeakKeyDictionary[Page, PageConsoleCapture] = weakref.WeakKeyDictionary()@@ -115,7 +114,7 @@ class ExfiltrationChannel(CdpChannel):self._capture_seq = 0self._drain_token = uuid.uuid4().hex- super().__init__(vnc_channel=vnc_channel)+ super().__init__(context=context)def _next_capture_seq(self) -> int:seq = self._capture_seqdiff --git a/skyvern/forge/sdk/routes/streaming/channels/message.py b/skyvern/forge/sdk/routes/streaming/channels/message.pyindex bb0c50f23..9e67a4721 100644--- a/skyvern/forge/sdk/routes/streaming/channels/message.py+++ b/skyvern/forge/sdk/routes/streaming/channels/message.py@@ -24,6 +24,8 @@ from pydantic import BaseModelfrom starlette.websockets import WebSocketStatefrom websockets.exceptions import ConnectionClosedError+from skyvern.forge.sdk.routes.streaming.auth import get_x_api_key+from skyvern.forge.sdk.routes.streaming.channels.cdp import ChannelContextfrom skyvern.forge.sdk.routes.streaming.channels.execution import execution_for_message_channelfrom skyvern.forge.sdk.routes.streaming.channels.exfiltration import ExfiltratedEvent, ExfiltrationChannelfrom skyvern.forge.sdk.routes.streaming.payload_limits import MAX_CLIPBOARD_PASTE_BYTES@@ -44,6 +46,7 @@ from skyvern.services.browser_recording.session_registry import interpretation_rfrom skyvern.services.browser_recording.types import RecordingDraftStep, RecordingInterpretationUpdateLOG = structlog.get_logger()+_MAX_IN_FLIGHT_CLIPBOARD_TASKS = 2Loops = list[asyncio.Task] # aka "queue-less actors"; or "programs"@@ -491,6 +494,28 @@ class MessageChannel:self.out_queue.put_nowait({"kind": "copied-text", "text": copied_text})+class MessageChannelContext:+ """ChannelContext for recording without a VNC channel. Delegates to the live+ message channel so a browser_session the verifier swaps or clears mid-recording+ is observed, matching how a VncChannel-backed context behaves."""++ message_channel: MessageChannel+ x_api_key: str++ @property+ def organization_id(self) -> str:+ return self.message_channel.organization_id++ @property+ def browser_session(self) -> AddressablePersistentBrowserSession | None:+ return self.message_channel.browser_session++ @property+ def identity(self) -> dict[str, t.Any]:+ return dict(self.message_channel.identity)++async def loop_stream_messages(message_channel: MessageChannel) -> None:"""Stream messages and their results back and forth.@@ -501,6 +526,25 @@ async def loop_stream_messages(message_channel: MessageChannel) -> None:class_name = message_channel.class_nameexfiltration_channel: ExfiltrationChannel | None = Nonelive_interpretation_browser_session_id: str | None = None+ clipboard_tasks: set[asyncio.Task[None]] = set()+ clipboard_task_count = 0++ async def track_clipboard_task(coroutine_factory: t.Callable[[], t.Coroutine[t.Any, t.Any, None]]) -> None:+ nonlocal clipboard_task_count+ try:+ await coroutine_factory()+ finally:+ clipboard_task_count -= 1++ def run_clipboard_task(coroutine_factory: t.Callable[[], t.Coroutine[t.Any, t.Any, None]]) -> bool:+ nonlocal clipboard_task_count+ if clipboard_task_count >= _MAX_IN_FLIGHT_CLIPBOARD_TASKS:+ return False+ clipboard_task_count += 1+ task = asyncio.create_task(track_clipboard_task(coroutine_factory))+ clipboard_tasks.add(task)+ task.add_done_callback(clipboard_tasks.discard)+ return Trueasync def send(message: MessageOut) -> None:# Single-writer: enqueue only; backend_to_frontend is the sole task that@@ -538,35 +582,40 @@ async def loop_stream_messages(message_channel: MessageChannel) -> None:match message.kind:case MessageKind.ASK_FOR_CLIPBOARD_RESPONSE:- text = message.text- paste_byte_len = len(text.encode("utf-8"))- if paste_byte_len > MAX_CLIPBOARD_PASTE_BYTES:- LOG.warning(- f"{class_name} ask-for-clipboard-response paste exceeds size cap; rejecting.",- size=paste_byte_len,- max_size=MAX_CLIPBOARD_PASTE_BYTES,- **message_channel.identity,- )- await send_error(message.kind, "Clipboard payload too large.")- return+ async def paste_clipboard_response() -> None:+ text = message.text- try:- async with execution_for_message_channel(message_channel) as execute:- await execute.paste_text(text)- except Exception:- LOG.exception(- f"{class_name} failed to paste clipboard response into browser.",- **message_channel.identity,- )- await send_error(message.kind, "Failed to paste into browser.")+ paste_byte_len = len(text.encode("utf-8"))+ if paste_byte_len > MAX_CLIPBOARD_PASTE_BYTES:+ LOG.warning(+ f"{class_name} ask-for-clipboard-response paste exceeds size cap; rejecting.",+ size=paste_byte_len,+ max_size=MAX_CLIPBOARD_PASTE_BYTES,+ **message_channel.identity,+ )+ await send_error(message.kind, "Clipboard payload too large.")+ return++ try:+ async with execution_for_message_channel(message_channel) as execute:+ await execute.paste_text(text)+ except Exception:+ LOG.exception(+ f"{class_name} failed to paste clipboard response into browser.",+ **message_channel.identity,+ )+ await send_error(message.kind, "Failed to paste into browser.")++ if not run_clipboard_task(paste_clipboard_response):+ await send_error(message.kind, "Clipboard is busy; try again.")case MessageKind.BEGIN_EXFILTRATION:vnc_channel = get_vnc_channel(message_channel.client_id)- if not vnc_channel:+ if vnc_channel is None and message_channel.browser_session is None:LOG.warning(- f"{class_name} no vnc channel client found for message channel - cannot exfiltrate.",+ f"{class_name} no vnc channel and no browser session for message channel - cannot exfiltrate.",message=message,**message_channel.identity,)@@ -644,13 +693,30 @@ async def loop_stream_messages(message_channel: MessageChannel) -> None:if live_interpretation_browser_session_id:interpretation_registry.ingest_events(live_interpretation_browser_session_id, events)+ if vnc_channel is not None:+ context: ChannelContext = vnc_channel+ else:+ # A transient token-lookup failure must not escape handle_data+ # and kill the websocket loop; the client re-sends+ # begin-exfiltration on its next attempt.+ try:+ x_api_key = await get_x_api_key(message_channel.organization_id)+ except Exception:+ LOG.exception(+ f"{class_name} failed to resolve api key for recording capture.",+ **message_channel.identity,+ )+ await send_error(message.kind, "Failed to start recording capture.")+ return+ context = MessageChannelContext(message_channel=message_channel, x_api_key=x_api_key)+# A dead browser target (ECONNREFUSED / 502 from connect_over_cdp) must# not escape handle_data: that kills the websocket loop, the frontend# reconnects and re-sends begin-exfiltration, and the recording spins# in a crash-loop capturing nothing.new_channel = ExfiltrationChannel(on_event=on_event,- vnc_channel=vnc_channel,+ context=context,)try:exfiltration_channel = await new_channel.start()@@ -716,57 +782,65 @@ async def loop_stream_messages(message_channel: MessageChannel) -> None:await send_error(message.kind, "Failed to clear browsing history.")case MessageKind.CLIPBOARD_COPY:- try:- async with execution_for_message_channel(message_channel) as execute:- copied_text = await execute.get_selected_text()- await message_channel.send_copied_text(copied_text)- except Exception:- LOG.exception(- f"{class_name} failed to copy text from browser.",- **message_channel.identity,- )- await send_error(message.kind, "Failed to copy selected text.")++ async def copy_clipboard() -> None:+ try:+ async with execution_for_message_channel(message_channel) as execute:+ copied_text = await execute.get_selected_text()+ await message_channel.send_copied_text(copied_text)+ except Exception:+ LOG.exception(+ f"{class_name} failed to copy text from browser.",+ **message_channel.identity,+ )+ await send_error(message.kind, "Failed to copy selected text.")++ if not run_clipboard_task(copy_clipboard):+ await send_error(message.kind, "Clipboard is busy; try again.")case MessageKind.CLIPBOARD_PASTE:- text = message.text- paste_byte_len = len(text.encode("utf-8"))- if paste_byte_len > MAX_CLIPBOARD_PASTE_BYTES:- LOG.warning(- f"{class_name} clipboard-paste payload exceeds size cap; rejecting.",- size=paste_byte_len,- max_size=MAX_CLIPBOARD_PASTE_BYTES,- **message_channel.identity,- )- await send_error(message.kind, "Clipboard payload too large.")- return+ async def paste_clipboard() -> None:+ text = message.text- try:- async with execution_for_message_channel(message_channel) as execute:- await execute.paste_text(text)- except Exception:- LOG.exception(- f"{class_name} failed to paste text into browser.",- **message_channel.identity,- )- await send_error(message.kind, "Failed to paste into browser.")+ paste_byte_len = len(text.encode("utf-8"))+ if paste_byte_len > MAX_CLIPBOARD_PASTE_BYTES:+ LOG.warning(+ f"{class_name} clipboard-paste payload exceeds size cap; rejecting.",+ size=paste_byte_len,+ max_size=MAX_CLIPBOARD_PASTE_BYTES,+ **message_channel.identity,+ )+ await send_error(message.kind, "Clipboard payload too large.")+ return- case MessageKind.END_EXFILTRATION:- if exfiltration_channel is None:- return+ try:+ async with execution_for_message_channel(message_channel) as execute:+ await execute.paste_text(text)+ except Exception:+ LOG.exception(+ f"{class_name} failed to paste text into browser.",+ **message_channel.identity,+ )+ await send_error(message.kind, "Failed to paste into browser.")++ if not run_clipboard_task(paste_clipboard):+ await send_error(message.kind, "Clipboard is busy; try again.")+ case MessageKind.END_EXFILTRATION:# Channel teardown is best-effort: a browser whose target already# closed raises here, and that must never skip the interpretation# flush below — losing every draft the user just recorded.- try:- await exfiltration_channel.stop()- except Exception:- # Expected race (target already closed), so warning, not error.- LOG.warning(- f"{class_name} failed to stop recording capture cleanly.",- **message_channel.identity,- exc_info=True,- )+ if exfiltration_channel is not None:+ try:+ await exfiltration_channel.stop()+ except Exception:+ # Expected race (target already closed), so warning, not error.+ LOG.warning(+ f"{class_name} failed to stop recording capture cleanly.",+ **message_channel.identity,+ exc_info=True,+ )exfiltration_channel = Noneif live_interpretation_browser_session_id:@@ -982,6 +1056,11 @@ async def loop_stream_messages(message_channel: MessageChannel) -> None:for task in loops:task.cancel()await asyncio.gather(*loops, return_exceptions=True)+ pending_clipboard_tasks = tuple(clipboard_tasks)+ for task in pending_clipboard_tasks:+ task.cancel()+ if pending_clipboard_tasks:+ await asyncio.gather(*pending_clipboard_tasks, return_exceptions=True)LOG.debug(f"{class_name} Closing the message channel stream.", **message_channel.identity)if exfiltration_channel is not None:try:diff --git a/skyvern/forge/sdk/routes/workflow_schedules.py b/skyvern/forge/sdk/routes/workflow_schedules.pyindex 8353cca38..fbe731dec 100644--- a/skyvern/forge/sdk/routes/workflow_schedules.py+++ b/skyvern/forge/sdk/routes/workflow_schedules.py@@ -191,6 +191,10 @@ async def _set_schedule_enabled(tags=["Schedules"],operation_id="schedules_list_all",summary="List all schedules for the organization",+ description=(+ "List every schedule in the organization, across all agents, filterable by active/paused status and "+ "a search term matched against agent title or schedule name. Returns a paginated list plus the total count."+ ),)async def list_organization_schedules(page: int = Query(default=1, ge=1),@@ -231,6 +235,10 @@ async def list_organization_schedules(tags=["Schedules"],operation_id="schedules_create",summary="Create a schedule for an agent",+ description=(+ "Create a cron schedule that runs the given agent automatically with a fixed set of parameters. "+ "Returns the stored schedule and its next upcoming run times."+ ),)async def create_workflow_schedule(workflow_permanent_id: str,@@ -370,6 +378,7 @@ async def create_workflow_schedule(tags=["Schedules"],operation_id="schedules_list",summary="List schedules for an agent",+ description="List all schedules attached to a single agent. Returns the schedules in creation order.",)async def list_workflow_schedules(workflow_permanent_id: str,@@ -391,6 +400,10 @@ async def list_workflow_schedules(tags=["Schedules"],operation_id="schedules_get",summary="Get an agent schedule by id",+ description=(+ "Fetch one schedule belonging to an agent. Returns the schedule's cron expression, timezone, "+ "parameters, enabled state, and next upcoming run times."+ ),)async def get_workflow_schedule(workflow_permanent_id: str,@@ -418,6 +431,10 @@ async def get_workflow_schedule(tags=["Schedules"],operation_id="schedules_update",summary="Update an agent schedule",+ description=(+ "Replace a schedule's cron expression, timezone, run parameters, and enabled state. "+ "Returns the updated schedule and its next upcoming run times."+ ),)async def update_workflow_schedule(workflow_permanent_id: str,@@ -562,6 +579,7 @@ async def update_workflow_schedule(tags=["Schedules"],operation_id="schedules_enable",summary="Enable an agent schedule",+ description="Resume a paused schedule so it starts triggering runs again. Returns the updated schedule.",)async def enable_workflow_schedule(workflow_permanent_id: str,@@ -587,6 +605,7 @@ async def enable_workflow_schedule(tags=["Schedules"],operation_id="schedules_disable",summary="Disable an agent schedule",+ description="Pause a schedule so it stops triggering runs, without deleting it. Returns the updated schedule.",)async def disable_workflow_schedule(workflow_permanent_id: str,@@ -611,6 +630,7 @@ async def disable_workflow_schedule(tags=["Schedules"],operation_id="schedules_delete",summary="Delete an agent schedule",+ description="Permanently delete a schedule so it never triggers again. Returns an acknowledgement flag.",)async def delete_workflow_schedule_route(workflow_permanent_id: str,diff --git a/tests/unit/forge/sdk/routes/streaming/test_cdp_input_session.py b/tests/unit/forge/sdk/routes/streaming/test_cdp_input_session.pyindex 8f9e86fbe..bde5731f7 100644--- a/tests/unit/forge/sdk/routes/streaming/test_cdp_input_session.py+++ b/tests/unit/forge/sdk/routes/streaming/test_cdp_input_session.py@@ -6,17 +6,61 @@ import asyncioimport jsonfrom types import SimpleNamespacefrom typing import Any-from unittest.mock import AsyncMock, Mock+from unittest.mock import Mockimport pytestfrom fastapi import WebSocketDisconnect+from playwright._impl._cdp_session import CDPSession as ImplCDPSession+from playwright._impl._connection import Connectionfrom playwright._impl._errors import TargetClosedError+from playwright._impl._object_factory import create_remote_object+from playwright._impl._transport import Transport+from playwright.async_api import CDPSessionfrom playwright.async_api import Error as PlaywrightErrorfrom playwright.async_api import TimeoutError as PlaywrightTimeoutErrorfrom skyvern.forge.sdk.routes.streaming import cdp_input+class _RecordingPlaywrightTransport(Transport):+ def __init__(self, loop: asyncio.AbstractEventLoop) -> None:+ super().__init__(loop)+ self.sent: list[dict[str, Any]] = []++ def request_stop(self) -> None:+ pass++ async def wait_until_stopped(self) -> None:+ pass++ async def connect(self) -> None:+ pass++ async def run(self) -> None:+ pass++ def send(self, message: dict[str, Any]) -> None:+ self.sent.append(message)+++async def test_playwright_cdp_send_writes_transport_in_task_submission_order() -> None:+ loop = asyncio.get_running_loop()+ transport = _RecordingPlaywrightTransport(loop)+ connection = Connection(None, create_remote_object, transport, loop)+ session = CDPSession(ImplCDPSession(connection, "CDPSession", "cdp-session", {}))++ first_send = asyncio.create_task(session.send("Input.dispatchMouseEvent", {"sequence": 1}))+ second_send = asyncio.create_task(session.send("Input.dispatchMouseEvent", {"sequence": 2}))+ await asyncio.sleep(0)++ assert [message["params"]["params"]["sequence"] for message in transport.sent] == [1, 2]++ for message in transport.sent:+ transport.on_message({"id": message["id"], "result": {"value": {}}})+ await asyncio.gather(first_send, second_send)++class _FakeSession:def __init__(self, name: str, history: dict | None = None) -> None:self.name = name@@ -169,6 +213,28 @@ class _FakeWebSocket:self.closed = (code, reason)+class _BlockingWebSocket(_FakeWebSocket):+ def __init__(self, messages: list[str]) -> None:+ super().__init__(messages)+ self.all_received = asyncio.Event()+ self.disconnected = asyncio.Event()+ self.close_calls: list[tuple[int, str]] = []++ async def receive_text(self) -> str:+ if self._messages:+ raw = self._messages.pop(0)+ if not self._messages:+ self.all_received.set()+ return raw+ await self.disconnected.wait()+ raise WebSocketDisconnect()++ async def close(self, code: int = 1000, reason: str = "") -> None:+ await super().close(code, reason)+ self.close_calls.append((code, reason))+ self.disconnected.set()++class TestNavigateEvent:"""SKY-13683: a live-view URL input navigates the remote page over the existingcdp_input WebSocket, gated by the same take-control check as mouse/keyboard input,@@ -540,6 +606,89 @@ class TestHistoryNavigation:assert session.sent == []+async def test_pointer_burst_is_received_before_dispatches_complete() -> None:+ event_count = 10+ release_sends = asyncio.Event()++ class _ControlledSession(_FakeSession):+ def __init__(self) -> None:+ super().__init__("s")+ self.started: list[tuple[str, dict]] = []++ async def send(self, method: str, params: dict) -> None:+ self.started.append((method, params))+ await release_sends.wait()+ self.sent.append((method, params))++ session = _ControlledSession()+ input_session = _FakeInputSession(session)+ channel = SimpleNamespace(interactor="user", client_id="c1")+ websocket = _BlockingWebSocket(+ [+ json.dumps({"type": "wheelEvent", "x": 10, "y": 20, "deltaX": 0, "deltaY": index + 1})+ for index in range(event_count)+ ]+ )+ loop_task = asyncio.create_task(+ cdp_input._run_input_loop(websocket, channel, input_session, "browser_session_id", "pbs_test")+ )++ try:+ await asyncio.wait_for(websocket.all_received.wait(), timeout=0.5)+ async with asyncio.timeout(0.5):+ while len(session.started) < event_count:+ await asyncio.sleep(0)+ assert len(session.started) == event_count+ assert session.sent == []+ finally:+ release_sends.set()+ websocket.disconnected.set()+ await loop_task++ assert len(session.sent) == event_count+++async def test_target_closed_background_dispatch_is_dropped_without_closing_input_channel() -> None:+ dispatch_attempted = asyncio.Event()++ class _StaleSession(_FakeSession):+ async def send(self, method: str, params: dict) -> None:+ dispatch_attempted.set()+ raise TargetClosedError("Target page, context or browser has been closed")++ input_session = _FakeInputSession(_StaleSession("s"))+ channel = SimpleNamespace(interactor="user", client_id="c1")+ websocket = _BlockingWebSocket([json.dumps({"type": "wheelEvent", "x": 10, "y": 20, "deltaX": 0, "deltaY": 1})])+ loop_task = asyncio.create_task(+ cdp_input._run_input_loop(websocket, channel, input_session, "browser_session_id", "pbs_test")+ )++ try:+ await asyncio.wait_for(dispatch_attempted.wait(), timeout=0.5)+ await asyncio.sleep(0)+ assert websocket.close_calls == []+ finally:+ websocket.disconnected.set()+ await loop_task+++async def test_background_dispatch_failure_closes_input_channel_once() -> None:+ class _FailingSession(_FakeSession):+ async def send(self, method: str, params: dict) -> None:+ raise RuntimeError("dispatch failed")++ input_session = _FakeInputSession(_FailingSession("s"))+ channel = SimpleNamespace(interactor="user", client_id="c1")+ websocket = _BlockingWebSocket([json.dumps({"type": "wheelEvent", "x": 10, "y": 20, "deltaX": 0, "deltaY": 1})])++ await cdp_input._run_input_loop(websocket, channel, input_session, "browser_session_id", "pbs_test")++ assert websocket.close_calls == [(4411, "dispatch_failed")]++@pytest.mark.asyncioasync def test_dispatched_input_event_records_wait_and_dispatch_latency(monkeypatch: pytest.MonkeyPatch) -> None:fake_session = _FakeSession("s1")@@ -560,11 +709,6 @@ async def test_dispatched_input_event_records_wait_and_dispatch_latency(monkeypa)]- async def _receive_text() -> str:- if incoming:- return incoming.pop(0)- raise WebSocketDisconnect(code=1000)-async def _get_session() -> _FakeSession:await asyncio.sleep(0.01)return fake_session@@ -574,11 +718,18 @@ async def test_dispatched_input_event_records_wait_and_dispatch_latency(monkeypafake_session.sent.append((method, params))fake_session.send = _send # type: ignore[method-assign]- websocket = SimpleNamespace(receive_text=_receive_text, close=AsyncMock(), send_json=AsyncMock())+ websocket = _BlockingWebSocket(incoming)channel = SimpleNamespace(interactor="user", client_id="c1")input_session = SimpleNamespace(get_session=_get_session, page=object())- await cdp_input._run_input_loop(websocket, channel, input_session, "browser_session_id", "pbs_1")+ loop_task = asyncio.create_task(+ cdp_input._run_input_loop(websocket, channel, input_session, "browser_session_id", "pbs_1")+ )+ async with asyncio.timeout(0.5):+ while not fake_session.sent:+ await asyncio.sleep(0)+ websocket.disconnected.set()+ await loop_taskassert fake_session.sent[0][0] == "Input.dispatchMouseEvent"dispatch_value, attributes = dispatch_hist.record.call_args.argsdiff --git a/tests/unit/forge/sdk/routes/streaming/test_execution_channel.py b/tests/unit/forge/sdk/routes/streaming/test_execution_channel.pyindex 9a2d6ce23..469422162 100644--- a/tests/unit/forge/sdk/routes/streaming/test_execution_channel.py+++ b/tests/unit/forge/sdk/routes/streaming/test_execution_channel.py@@ -12,7 +12,7 @@ from playwright._impl._errors import TargetClosedErrorfrom skyvern.forge.sdk.routes.streaming.channels.execution import ExecutionChannel, execution_channelfrom tests.unit.forge.sdk.routes.streaming.test_exfiltration_channel import (_FakePw,- _make_vnc_channel,+ _make_context,_patch_pw_stack,)@@ -37,7 +37,7 @@ async def test_execution_channel_cm_does_not_resurrect_driver(monkeypatch: pytes# on_close handler in CdpChannel.connect must not chain a fresh driver spawn.state = _patch_pw_stack(monkeypatch, fire_disconnect_on_close=True)- async with execution_channel(_make_vnc_channel()):+ async with execution_channel(_make_context()):passawait _drain_loop()@@ -47,7 +47,7 @@ async def test_execution_channel_cm_does_not_resurrect_driver(monkeypatch: pytes@pytest.mark.asyncioasync def test_stop_releases_driver_when_browser_close_raises() -> None:- channel = ExecutionChannel(vnc_channel=_make_vnc_channel())+ channel = ExecutionChannel(context=_make_context())browser = _RaisingBrowser()pw = _FakePw()channel.browser = browser # type: ignore[assignment]diff --git a/tests/unit/forge/sdk/routes/streaming/test_exfiltration_channel.py b/tests/unit/forge/sdk/routes/streaming/test_exfiltration_channel.pyindex c99bab8de..d16acdb0f 100644--- a/tests/unit/forge/sdk/routes/streaming/test_exfiltration_channel.py+++ b/tests/unit/forge/sdk/routes/streaming/test_exfiltration_channel.py@@ -18,21 +18,24 @@ from skyvern.forge.sdk.routes.streaming.channels.exfiltration import (ExfiltrationChannel,PageConsoleCapture,)+from skyvern.forge.sdk.routes.streaming.channels.message import MessageChannelContext-def _make_vnc_channel() -> MagicMock:+def _make_context() -> MagicMock:browser_session = MagicMock()browser_session.browser_address = "http://localhost:9222"browser_session.persistent_browser_session_id = "pbs_123"- vnc_channel = MagicMock()- vnc_channel.browser_session = browser_session- vnc_channel.identity = {+ context = MagicMock()+ context.organization_id = "org_123"+ context.x_api_key = "api-key-123"+ context.browser_session = browser_session+ context.identity = {"client_id": "client-1","browser_session_id": browser_session.persistent_browser_session_id,}- return vnc_channel+ return contextdef _make_event_data() -> dict[str, object]:@@ -65,7 +68,7 @@ def _make_page(url: str = "https://example.com") -> MagicMock:def _make_channel(on_event: MagicMock | None = None) -> tuple[ExfiltrationChannel, MagicMock]:event_callback = on_event or MagicMock()- return ExfiltrationChannel(on_event=event_callback, vnc_channel=_make_vnc_channel()), event_callback+ return ExfiltrationChannel(on_event=event_callback, context=_make_context()), event_callback@pytest.fixture(autouse=True)@@ -788,7 +791,7 @@ def _patch_pw_stack(monkeypatch: pytest.MonkeyPatch, *, fire_disconnect_on_close"""import skyvern.forge.sdk.routes.streaming.channels.cdp as cdp_mod- state = SimpleNamespace(start_calls=0, pws=[], browsers=[])+ state = SimpleNamespace(start_calls=0, pws=[], browsers=[], connections=[])def _make_pw() -> _FakePw:state.start_calls += 1@@ -802,6 +805,7 @@ def _patch_pw_stack(monkeypatch: pytest.MonkeyPatch, *, fire_disconnect_on_closeasync def _fake_connect(pw: object, url: str, headers: dict | None = None, **kwargs: object) -> _FakePwBrowser:browser = _FakePwBrowser(fire_disconnect_on_close=fire_disconnect_on_close)state.browsers.append(browser)+ state.connections.append((url, headers))return browsermonkeypatch.setattr(cdp_mod, "async_playwright", _fake_async_playwright)@@ -810,6 +814,38 @@ def _patch_pw_stack(monkeypatch: pytest.MonkeyPatch, *, fire_disconnect_on_closeclass TestExfiltrationChannelLifecycle:+ @pytest.mark.asyncio+ async def test_message_channel_context_connects_like_vnc_context(self, monkeypatch: pytest.MonkeyPatch) -> None:+ import skyvern.forge.sdk.routes.streaming.channels.cdp as cdp_mod++ monkeypatch.setattr(cdp_mod.settings, "ENV", "local")+ monkeypatch.setenv("LOCAL_CDP_HOST_PORT", "9224")+ state = _patch_pw_stack(monkeypatch)++ vnc_context = _make_context()+ backing_message_channel = MagicMock()+ backing_message_channel.organization_id = vnc_context.organization_id+ backing_message_channel.browser_session = vnc_context.browser_session+ backing_message_channel.identity = dict(vnc_context.identity)+ message_context = MessageChannelContext(+ message_channel=backing_message_channel,+ x_api_key=vnc_context.x_api_key,+ )+ vnc_channel = ExfiltrationChannel(on_event=lambda _events: None, context=vnc_context)+ message_channel = ExfiltrationChannel(on_event=lambda _events: None, context=message_context)++ await vnc_channel.connect()+ await message_channel.connect()++ expected_connection = (+ "http://localhost:9224",+ {"x-api-key": "api-key-123", "X-Session-Id": "pbs_123"},+ )+ assert state.connections == [expected_connection, expected_connection]++ await vnc_channel.stop()+ await message_channel.stop()+def test_js_asset_cache_is_keyed_by_file_not_instance(self) -> None:from skyvern.forge.sdk.routes.streaming.channels.cdp import _load_js_asset@@ -829,8 +865,10 @@ class TestExfiltrationChannelLifecycle:def test_using_js_does_not_pin_channel_instance(self) -> None:# A cycle-free vnc stand-in so the channel is reclaimed by refcounting the# moment the JS cache stops pinning it (a MagicMock carries internal cycles).- vnc_channel = SimpleNamespace(identity={"client_id": "c"}, browser_session=None, x_api_key=None)- channel = ExfiltrationChannel(on_event=lambda _events: None, vnc_channel=vnc_channel) # type: ignore[arg-type]+ context = SimpleNamespace(+ identity={"client_id": "c"}, organization_id="org_123", browser_session=None, x_api_key="api-key-123"+ )+ channel = ExfiltrationChannel(on_event=lambda _events: None, context=context) # type: ignore[arg-type]channel.js("exfiltrate")ref = weakref.ref(channel)diff --git a/tests/unit/forge/sdk/routes/streaming/test_message_channel_recording_resilience.py b/tests/unit/forge/sdk/routes/streaming/test_message_channel_recording_resilience.pyindex 07aab9214..96dc832d6 100644--- a/tests/unit/forge/sdk/routes/streaming/test_message_channel_recording_resilience.py+++ b/tests/unit/forge/sdk/routes/streaming/test_message_channel_recording_resilience.py@@ -18,6 +18,8 @@ never skips the draft flush or the channel close.from __future__ import annotationsimport asyncio+import typing as t+from contextlib import asynccontextmanagerfrom unittest.mock import AsyncMock, MagicMockimport pytest@@ -74,7 +76,12 @@ def _install_recording_doubles(channel: object,) -> MagicMock:"""Stub the vnc registry, exfiltration channel factory, and interpretation registry."""- monkeypatch.setattr(message_module, "get_vnc_channel", lambda _client_id: MagicMock())+ context = MagicMock()+ context.organization_id = "org_123"+ context.x_api_key = "api-key-123"+ context.browser_session = MagicMock(persistent_browser_session_id=PBS_ID)+ context.identity = {"organization_id": "org_123", "browser_session_id": PBS_ID}+ monkeypatch.setattr(message_module, "get_vnc_channel", lambda _client_id: context)monkeypatch.setattr(message_module, "ExfiltrationChannel", MagicMock(return_value=channel))registry = MagicMock()@@ -85,6 +92,40 @@ def _install_recording_doubles(return registry+async def test_begin_exfiltration_starts_without_vnc_channel(monkeypatch: pytest.MonkeyPatch) -> None:+ created_channel: object | None = None++ class RecordingChannel:+ def __init__(self, *, on_event: object, context: object) -> None:+ nonlocal created_channel+ self.context = context+ self.started = False+ created_channel = self++ async def start(self) -> RecordingChannel:+ self.started = True+ return self++ async def stop(self) -> RecordingChannel:+ return self++ message_channel = _message_channel([BEGIN_EXFILTRATION_DATA, WebSocketDisconnect()])+ browser_session = message_channel.browser_session+ monkeypatch.setattr(message_module, "get_vnc_channel", lambda _client_id: None)+ monkeypatch.setattr(message_module, "get_x_api_key", AsyncMock(return_value="message-api-key"))+ monkeypatch.setattr(message_module, "ExfiltrationChannel", RecordingChannel)+ monkeypatch.setattr(message_module, "interpretation_registry", MagicMock())++ await loop_stream_messages(message_channel)++ assert isinstance(created_channel, RecordingChannel)+ assert created_channel.started is True+ assert created_channel.context.browser_session is browser_session+ assert created_channel.context.x_api_key == "message-api-key"+ assert created_channel.context.organization_id == message_channel.organization_id++def _started_channel(*, stop_error: Exception | None = None) -> MagicMock:channel = MagicMock()channel.start = AsyncMock(return_value=channel)@@ -112,7 +153,7 @@ async def test_begin_exfiltration_start_failure_does_not_kill_message_loop(message_channel = _message_channel([BEGIN_EXFILTRATION_DATA, END_EXFILTRATION_DATA, WebSocketDisconnect()],)- _install_recording_doubles(monkeypatch, channel=channel)+ registry = _install_recording_doubles(monkeypatch, channel=channel)await loop_stream_messages(message_channel)@@ -120,6 +161,119 @@ async def test_begin_exfiltration_start_failure_does_not_kill_message_loop(assert message_channel.websocket.receive_json.await_count == 3# The failure was surfaced to the frontend rather than swallowed silently.assert MessageKind.BEGIN_EXFILTRATION.value in _sent_error_kinds(message_channel)+ registry.stop_session.assert_awaited_once_with(PBS_ID)+++async def test_blocked_clipboard_does_not_delay_end_and_is_cancelled_on_teardown(+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ channel = _started_channel()+ message_channel = _message_channel([])+ registry = _install_recording_doubles(monkeypatch, channel=channel)+ clipboard_started = asyncio.Event()+ clipboard_cancelled = asyncio.Event()+ receive_count = 0++ async def receive_json() -> dict[str, str]:+ nonlocal receive_count+ receive_count += 1+ if receive_count == 1:+ return BEGIN_EXFILTRATION_DATA+ if receive_count == 2:+ return {"kind": MessageKind.CLIPBOARD_COPY.value}+ if receive_count == 3:+ await clipboard_started.wait()+ return END_EXFILTRATION_DATA+ raise WebSocketDisconnect()++ @asynccontextmanager+ async def blocked_execution(_: object) -> t.AsyncIterator[MagicMock]:+ clipboard_started.set()+ try:+ await asyncio.Event().wait()+ yield MagicMock()+ finally:+ clipboard_cancelled.set()++ message_channel.websocket.receive_json = receive_json+ monkeypatch.setattr(message_module, "execution_for_message_channel", blocked_execution)++ await asyncio.wait_for(loop_stream_messages(message_channel), timeout=2)++ assert receive_count == 4+ channel.stop.assert_awaited_once()+ registry.stop_session.assert_awaited_once_with(PBS_ID)+ assert clipboard_cancelled.is_set()+++async def test_clipboard_task_limit_rejects_third_and_frees_slot_after_completion(+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ message_channel = _message_channel([])+ two_started = asyncio.Event()+ release_first = asyncio.Event()+ first_completed = asyncio.Event()+ slot_reused = asyncio.Event()+ executions_started = 0+ started_at_capacity: list[int] = []+ receive_count = 0++ async def receive_json() -> dict[str, str]:+ nonlocal receive_count+ receive_count += 1+ if receive_count <= 2:+ return {"kind": MessageKind.CLIPBOARD_COPY.value}+ if receive_count == 3:+ await two_started.wait()+ return {"kind": MessageKind.CLIPBOARD_COPY.value}+ if receive_count == 4:+ started_at_capacity.append(executions_started)+ release_first.set()+ await first_completed.wait()+ return {"kind": MessageKind.CLIPBOARD_COPY.value}+ await slot_reused.wait()+ raise WebSocketDisconnect()++ @asynccontextmanager+ async def controlled_execution(_: object) -> t.AsyncIterator[MagicMock]:+ nonlocal executions_started+ execution_index = executions_started+ executions_started += 1+ if executions_started == 2:+ two_started.set()+ elif executions_started == 3:+ slot_reused.set()+ try:+ if execution_index == 0:+ await release_first.wait()+ else:+ await asyncio.Event().wait()+ execute = MagicMock()+ execute.get_selected_text = AsyncMock(return_value=f"copy-{execution_index}")+ yield execute+ finally:+ if execution_index == 0:+ first_completed.set()++ message_channel.websocket.receive_json = receive_json+ message_channel.send_copied_text = AsyncMock()+ monkeypatch.setattr(message_module, "execution_for_message_channel", controlled_execution)++ await asyncio.wait_for(loop_stream_messages(message_channel), timeout=2)++ sent_errors = [+ sent+ for call in message_channel.send_nowait.call_args_list+ for sent in call.kwargs.get("messages", [])+ if isinstance(sent, MessageOutError)+ ]+ assert started_at_capacity == [2]+ assert executions_started == 3+ assert [(error.failed_kind, error.message) for error in sent_errors] == [+ (MessageKind.CLIPBOARD_COPY.value, "Clipboard is busy; try again.")+ ]@pytest.mark.asynciodiff --git a/tests/unit/forge/sdk/routes/streaming/test_message_reify.py b/tests/unit/forge/sdk/routes/streaming/test_message_reify.pyindex db9ebfd0f..1453a46e7 100644--- a/tests/unit/forge/sdk/routes/streaming/test_message_reify.py+++ b/tests/unit/forge/sdk/routes/streaming/test_message_reify.py@@ -202,7 +202,7 @@ class TestExecutionChannelHelpers:page = MagicMock()page.url = "https://example.com/current"- channel = ExecutionChannel(vnc_channel=vnc_channel)+ channel = ExecutionChannel(context=vnc_channel)channel.url = "ws://cdp.example/devtools/browser/123"channel.page = page@@ -237,7 +237,7 @@ class TestExecutionChannelHelpers:)async def test_navigate_refuses_internal_destination(self, url: str) -> None:"""The live-session navigate control renders the response, so an internal host must fail closed."""- channel = ExecutionChannel(vnc_channel=MagicMock(identity={"client_id": "abc"}))+ channel = ExecutionChannel(context=MagicMock(identity={"client_id": "abc"}))channel.page = MagicMock()channel.page.goto = AsyncMock()@@ -250,7 +250,7 @@ class TestExecutionChannelHelpers:async def test_navigate_uses_the_validated_url(self, monkeypatch: pytest.MonkeyPatch) -> None:validate = MagicMock(return_value="https://example.test/validated")monkeypatch.setattr(execution_module, "validate_fetch_url", validate)- channel = ExecutionChannel(vnc_channel=MagicMock(identity={"client_id": "abc"}))+ channel = ExecutionChannel(context=MagicMock(identity={"client_id": "abc"}))channel.page = MagicMock()channel.page.goto = AsyncMock()@@ -294,7 +294,7 @@ class TestExecutionChannelHelpers:page.go_forward = AsyncMock()page.context.new_cdp_session = AsyncMock()- channel = ExecutionChannel(vnc_channel=vnc_channel)+ channel = ExecutionChannel(context=vnc_channel)channel.page = pagewith patch(diff --git a/tests/unit/services/test_browser_recording.py b/tests/unit/services/test_browser_recording.pyindex b83ae356b..2515a3b71 100644--- a/tests/unit/services/test_browser_recording.py+++ b/tests/unit/services/test_browser_recording.py@@ -604,7 +604,7 @@ async def test_network_activity_trailing_flush_preserves_throttled_activity() ->events: list[StreamingExfiltratedEvent] = []channel = ExfiltrationChannel(on_event=lambda messages: events.extend(messages),- vnc_channel=t.cast(t.Any, DummyVncChannel()),+ context=t.cast(t.Any, DummyVncChannel()),)channel.NETWORK_ACTIVITY_THROTTLE_SECONDS = 0.01diff --git a/tests/unit/test_record_browser_teardown_integration.py b/tests/unit/test_record_browser_teardown_integration.pyindex 1b845c153..b5e2fb086 100644--- a/tests/unit/test_record_browser_teardown_integration.py+++ b/tests/unit/test_record_browser_teardown_integration.py@@ -16,6 +16,7 @@ import pytestfrom playwright._impl._errors import TargetClosedErrorfrom skyvern.forge import app+from skyvern.forge.sdk.routes.streaming.channels.cdp import ChannelContextfrom skyvern.forge.sdk.routes.streaming.channels.exfiltration import ExfiltratedEvent as StreamingExfiltratedEventfrom skyvern.forge.sdk.routes.streaming.channels.exfiltration import (ExfiltratedEventSource as StreamingExfiltratedEventSource,@@ -23,6 +24,7 @@ from skyvern.forge.sdk.routes.streaming.channels.exfiltration import (from skyvern.forge.sdk.routes.streaming.channels.exfiltration import (ExfiltrationChannel,)+from skyvern.forge.sdk.routes.streaming.channels.message import MessageChannelContextfrom skyvern.services.browser_recording.service import Processorfrom skyvern.services.browser_recording.session_registry import RecordingInterpretationSessionRegistry@@ -49,19 +51,32 @@ def _click_event(*, capture_seq: int, sky_id: str, target_id: str) -> StreamingE)-def _vnc_channel() -> MagicMock:- vnc_channel = MagicMock()- vnc_channel.browser_session = MagicMock(+def _vnc_context() -> MagicMock:+ context = MagicMock()+ context.organization_id = ORG_ID+ context.x_api_key = "api-key-123"+ context.browser_session = MagicMock(browser_address="http://localhost:9222",persistent_browser_session_id=PBS_ID,)- vnc_channel.identity = {"client_id": "client-1", "browser_session_id": PBS_ID}- return vnc_channel+ context.identity = {"client_id": "client-1", "browser_session_id": PBS_ID}+ return context-def _channel_with_closed_page() -> ExfiltrationChannel:+def _message_context() -> MessageChannelContext:+ message_channel = MagicMock()+ message_channel.organization_id = ORG_ID+ message_channel.browser_session = MagicMock(+ browser_address="http://localhost:9222",+ persistent_browser_session_id=PBS_ID,+ )+ message_channel.identity = {"organization_id": ORG_ID, "browser_session_id": PBS_ID}+ return MessageChannelContext(message_channel=message_channel, x_api_key="api-key-123")+++def _channel_with_closed_page(context: ChannelContext) -> ExfiltrationChannel:"""An exfiltration channel whose only page's target is already closed."""- channel = ExfiltrationChannel(on_event=lambda _messages: None, vnc_channel=_vnc_channel())+ channel = ExfiltrationChannel(on_event=lambda _messages: None, context=context)closed_page = MagicMock()closed_page.url = "https://example.com"@@ -77,8 +92,10 @@ def _channel_with_closed_page() -> ExfiltrationChannel:return channel-async def test_end_exfiltration_on_closed_target_preserves_drafts_into_blocks(monkeypatch: pytest.MonkeyPatch) -> None:+async def _assert_closed_target_preserves_drafts(+ monkeypatch: pytest.MonkeyPatch,+ context: ChannelContext,+) -> None:async def fake_llm(*args: object, **kwargs: object) -> dict[str, object]:return {"block_label": "click_submit", "title": "Click Submit", "prompt": "Click the submit button."}@@ -105,7 +122,7 @@ async def test_end_exfiltration_on_closed_target_preserves_drafts_into_blocks(moassert session.steps, "precondition: the recording accumulated drafts"# Replay the END_EXFILTRATION handler sequence against a closed browser target.- channel = _channel_with_closed_page()+ channel = _channel_with_closed_page(context)await channel.stop() # message.py:727 — must not raise on a closed targetdrafts = await registry.stop_session(PBS_ID) # message.py:731 — only reached if stop() didn't crash@@ -113,3 +130,15 @@ async def test_end_exfiltration_on_closed_target_preserves_drafts_into_blocks(moassert drafts, "teardown dropped the recorded drafts"blocks = Processor(PBS_ID, ORG_ID, WP_ID).drafts_to_blocks(drafts)assert blocks, "surviving drafts did not produce workflow blocks"+++async def test_end_exfiltration_on_closed_target_preserves_drafts_into_blocks(monkeypatch: pytest.MonkeyPatch) -> None:+ await _assert_closed_target_preserves_drafts(monkeypatch, _vnc_context())+++async def test_end_exfiltration_without_vnc_on_closed_target_preserves_drafts_into_blocks(+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ await _assert_closed_target_preserves_drafts(monkeypatch, _message_context())