Skip to content

Automate browser based workflows with AI

SKY-13353 Follow Copilot test runs in Live Browser (#7972)

Andrew Neilsonebff93798973
diff --git a/docs/api-reference/openapi.json b/docs/api-reference/openapi.json
index 582863ad7..203789464 100644
--- a/docs/api-reference/openapi.json
+++ b/docs/api-reference/openapi.json
@@ -11126,6 +11126,18 @@
},
"CreateBrowserSessionRequest": {
"properties": {
+ "url": {
+ "anyOf": [
+ {
+ "type": "string"
+ },
+ {
+ "type": "null"
+ }
+ ],
+ "title": "Url",
+ "description": "Optional URL to open when the standalone browser session starts."
+ },
"timeout": {
"anyOf": [
{
diff --git a/fern/openapi/skyvern_openapi.json b/fern/openapi/skyvern_openapi.json
index 3d500c0dd..e696f9c74 100644
--- a/fern/openapi/skyvern_openapi.json
+++ b/fern/openapi/skyvern_openapi.json
@@ -10698,6 +10698,18 @@
},
"CreateBrowserSessionRequest": {
"properties": {
+ "url": {
+ "anyOf": [
+ {
+ "type": "string"
+ },
+ {
+ "type": "null"
+ }
+ ],
+ "title": "Url",
+ "description": "Optional URL to open when the standalone browser session starts."
+ },
"timeout": {
"anyOf": [
{
diff --git a/skyvern-frontend/src/api/types.ts b/skyvern-frontend/src/api/types.ts
index a9c31b32d..bd9698aa9 100644
--- a/skyvern-frontend/src/api/types.ts
+++ b/skyvern-frontend/src/api/types.ts
@@ -787,6 +787,10 @@ export type DebugSessionApiResponse = {
pbs_browser_profile_id: string | null;
};
+export type DebugSessionViewerStateApiResponse = {
+ active_run_session_id: string | null;
+};
+
export type DebugLoginBlockCompatibilityResponse = {
compatible: boolean;
reason: "pbs_no_profile" | "pbs_different_profile" | null;
diff --git a/skyvern-frontend/src/routes/workflows/copilot/WorkflowCopilotChat.runSessionRefresh.test.tsx b/skyvern-frontend/src/routes/workflows/copilot/WorkflowCopilotChat.runSessionRefresh.test.tsx
new file mode 100644
index 000000000..ab0ac1ad5
--- /dev/null
+++ b/skyvern-frontend/src/routes/workflows/copilot/WorkflowCopilotChat.runSessionRefresh.test.tsx
@@ -0,0 +1,27 @@
+import { act, renderHook } from "@testing-library/react";
+import { describe, expect, test, vi } from "vitest";
+
+import { useTurnActivityChange } from "./useTurnActivityChange";
+
+describe("useTurnActivityChange", () => {
+ test("reports local turn start, terminal completion, and unmount", () => {
+ const onTurnActivityChange = vi.fn();
+ const { rerender, unmount } = renderHook(
+ ({ active }) => useTurnActivityChange(active, onTurnActivityChange),
+ { initialProps: { active: false } },
+ );
+
+ expect(onTurnActivityChange).toHaveBeenLastCalledWith(false);
+
+ act(() => rerender({ active: true }));
+ expect(onTurnActivityChange).toHaveBeenLastCalledWith(true);
+
+ act(() => rerender({ active: false }));
+ expect(onTurnActivityChange).toHaveBeenLastCalledWith(false);
+
+ onTurnActivityChange.mockClear();
+ unmount();
+ expect(onTurnActivityChange).toHaveBeenCalledOnce();
+ expect(onTurnActivityChange).toHaveBeenCalledWith(false);
+ });
+});
diff --git a/skyvern-frontend/src/routes/workflows/copilot/WorkflowCopilotChat.tsx b/skyvern-frontend/src/routes/workflows/copilot/WorkflowCopilotChat.tsx
index 4e3c86b0f..596ed27c1 100644
--- a/skyvern-frontend/src/routes/workflows/copilot/WorkflowCopilotChat.tsx
+++ b/skyvern-frontend/src/routes/workflows/copilot/WorkflowCopilotChat.tsx
@@ -98,6 +98,7 @@ import {
parseUtcIsoMs,
} from "./narrativeState";
import { computeFollowSignature, useStickToBottom } from "./useStickToBottom";
+import { useTurnActivityChange } from "./useTurnActivityChange";
import { useSpeechToTextField } from "@/hooks/useSpeechToTextField";
import { SpeechInputButton } from "@/components/SpeechInputButton";
import { useFeatureFlag, useFeatureFlagValue } from "@/hooks/useFeatureFlag";
@@ -575,6 +576,7 @@ interface WorkflowCopilotChatProps {
isOpen?: boolean;
onClose?: () => void;
onMessageCountChange?: (count: number) => void;
+ onTurnActivityChange?: (active: boolean) => void;
buttonRef?: React.RefObject<HTMLButtonElement>;
liveBrowserSessionId?: string | null;
workflowRunId?: string | null;
@@ -654,6 +656,7 @@ export function WorkflowCopilotChat({
isOpen = true,
onClose,
onMessageCountChange,
+ onTurnActivityChange,
buttonRef,
liveBrowserSessionId,
workflowRunId: workflowRunIdProp,
@@ -766,6 +769,7 @@ export function WorkflowCopilotChat({
const [inputValue, setInputValue] = useState("");
const dismissPasteSkillHint = usePasteSkillHintStore((s) => s.dismiss);
const [isLoading, setIsLoading] = useState(false);
+ useTurnActivityChange(isLoading, onTurnActivityChange);
const [queuedPrompt, setQueuedPrompt] = useState<QueuedPrompt | null>(null);
const [narrative, setNarrative] =
useState<TurnNarrativeState>(EMPTY_NARRATIVE);
diff --git a/skyvern-frontend/src/routes/workflows/copilot/useTurnActivityChange.ts b/skyvern-frontend/src/routes/workflows/copilot/useTurnActivityChange.ts
new file mode 100644
index 000000000..050eb64b4
--- /dev/null
+++ b/skyvern-frontend/src/routes/workflows/copilot/useTurnActivityChange.ts
@@ -0,0 +1,17 @@
+import { useEffect } from "react";
+
+export function useTurnActivityChange(
+ active: boolean,
+ onTurnActivityChange?: (active: boolean) => void,
+) {
+ useEffect(() => {
+ onTurnActivityChange?.(active);
+ }, [active, onTurnActivityChange]);
+
+ useEffect(
+ () => () => {
+ onTurnActivityChange?.(false);
+ },
+ [onTurnActivityChange],
+ );
+}
diff --git a/skyvern-frontend/src/routes/workflows/editor/Workspace.browserSessionBinding.test.tsx b/skyvern-frontend/src/routes/workflows/editor/Workspace.browserSessionBinding.test.tsx
new file mode 100644
index 000000000..2c5d7765d
--- /dev/null
+++ b/skyvern-frontend/src/routes/workflows/editor/Workspace.browserSessionBinding.test.tsx
@@ -0,0 +1,21 @@
+import { describe, expect, test } from "vitest";
+
+import { resolveWorkspaceBrowserSessionBindings } from "./browserSessionBindings";
+
+describe("resolveWorkspaceBrowserSessionBindings", () => {
+ test("uses the active run only as the display session", () => {
+ expect(
+ resolveWorkspaceBrowserSessionBindings("pbs_debug", "pbs_run"),
+ ).toEqual({
+ debugBrowserSessionId: "pbs_debug",
+ displayBrowserSessionId: "pbs_run",
+ });
+ });
+
+ test("rebinds the display to the debug session after release", () => {
+ expect(resolveWorkspaceBrowserSessionBindings("pbs_debug", null)).toEqual({
+ debugBrowserSessionId: "pbs_debug",
+ displayBrowserSessionId: "pbs_debug",
+ });
+ });
+});
diff --git a/skyvern-frontend/src/routes/workflows/editor/Workspace.tsx b/skyvern-frontend/src/routes/workflows/editor/Workspace.tsx
index 562ab494d..942b422a4 100644
--- a/skyvern-frontend/src/routes/workflows/editor/Workspace.tsx
+++ b/skyvern-frontend/src/routes/workflows/editor/Workspace.tsx
@@ -44,8 +44,10 @@ import { DebugSessionApiResponse, ProxyLocation } from "@/api/types";
import { useCredentialGetter } from "@/hooks/useCredentialGetter";
import { useMountEffect } from "@/hooks/useMountEffect";
import { useBrowserSessionRateLimit } from "../hooks/useBrowserSessionRateLimit";
+import { useActiveRunSessionQuery } from "../hooks/useActiveRunSessionQuery";
import { useDebugSessionQuery } from "../hooks/useDebugSessionQuery";
import { useIsGlobalWorkflow } from "../hooks/useIsGlobalWorkflow";
+import { resolveWorkspaceBrowserSessionBindings } from "./browserSessionBindings";
import { useBlockScriptsQuery } from "@/routes/workflows/hooks/useBlockScriptsQuery";
import { BrowserSessionStream } from "@/routes/browserSessions/BrowserSessionStream";
import { useBrowserStreamingMode } from "@/hooks/useRuntimeConfig";
@@ -572,6 +574,7 @@ function Workspace({
// restores the pre-YAML dirty state instead of leaving it stuck true.
const yamlEntryHadChangesRef = useRef(false);
const [shouldFetchDebugSession, setShouldFetchDebugSession] = useState(false);
+ const [isCopilotTurnActive, setIsCopilotTurnActive] = useState(false);
const blockScriptStore = useBlockScriptStore();
const recordingStore = useRecordingStore();
const isCdpStreamingMode =
@@ -762,6 +765,12 @@ function Workspace({
isRateLimited,
keepAliveBrowserSession: true,
});
+ const { data: viewerState } = useActiveRunSessionQuery({
+ workflowPermanentId,
+ enabled:
+ shouldFetchDebugSession && Boolean(workflowPermanentId) && !isRateLimited,
+ isTurnActive: isCopilotTurnActive,
+ });
const activeDebugSession = debugSession ?? null;
@@ -769,7 +778,13 @@ function Workspace({
const showBreakoutButton =
activeDebugSession && activeDebugSession.browser_session_id;
- const liveBrowserSessionId = activeDebugSession?.browser_session_id ?? null;
+ const { debugBrowserSessionId, displayBrowserSessionId } =
+ resolveWorkspaceBrowserSessionBindings(
+ activeDebugSession?.browser_session_id ?? null,
+ viewerState?.active_run_session_id ?? null,
+ );
+ const activeRunSessionIdRef = useRef<string | null>(null);
+ activeRunSessionIdRef.current = viewerState?.active_run_session_id ?? null;
const showVncBrowserPanel =
preferVncStream &&
shouldFetchDebugSession &&
@@ -783,11 +798,11 @@ function Workspace({
// guard keeps the null -> first-id transition from clearing a recording that
// started before the session resolved.
useEffect(() => {
- if (embedded || !liveBrowserSessionId) {
+ if (embedded || !debugBrowserSessionId) {
return;
}
return () => useRecordingStore.getState().reset();
- }, [embedded, liveBrowserSessionId]);
+ }, [embedded, debugBrowserSessionId]);
// Embedded: the shell owns the stream, so bind the copilot once the backend
// session exists — else it gets a null id and the backend spins a separate browser.
const copilotRequiresLiveBrowser =
@@ -797,28 +812,28 @@ function Workspace({
// from the previous session cannot leak into the next render.
const copilotLiveBrowserReady = resolveCopilotLiveBrowserReady({
displayReady: Boolean(
- readyBrowserSessionId && readyBrowserSessionId === liveBrowserSessionId,
+ readyBrowserSessionId && readyBrowserSessionId === debugBrowserSessionId,
),
- hasBackendSession: Boolean(liveBrowserSessionId),
+ hasBackendSession: Boolean(debugBrowserSessionId),
headlessTurnDrainEnabled: headlessTurnDrainEnabled || embedded,
});
const debugSessionExpiryWarningKeyRef = useRef<string | null>(null);
const { data: liveBrowserSession, dataUpdatedAt: liveBrowserSessionNowMs } =
useQuery<BrowserSessionData>({
- queryKey: ["browserSession", liveBrowserSessionId],
+ queryKey: ["browserSession", debugBrowserSessionId],
queryFn: async () => {
- if (!liveBrowserSessionId) {
+ if (!debugBrowserSessionId) {
throw new Error("Cannot fetch browser session without an ID");
}
const client = await getClient(credentialGetter, "sans-api-v1");
const response = await client.get<BrowserSessionData>(
- `/browser_sessions/${liveBrowserSessionId}`,
+ `/browser_sessions/${debugBrowserSessionId}`,
);
return response.data;
},
enabled:
- Boolean(liveBrowserSessionId) &&
+ Boolean(debugBrowserSessionId) &&
shouldFetchDebugSession &&
!isRateLimited,
refetchInterval: DEBUG_SESSION_EXPIRY_STATUS_REFETCH_MS,
@@ -827,6 +842,9 @@ function Workspace({
const handleLiveBrowserReadyChange = useCallback(
(ready: boolean, sessionId: string | null) => {
+ if (activeRunSessionIdRef.current !== null) {
+ return;
+ }
setReadyBrowserSessionId(ready ? sessionId : null);
},
[],
@@ -1356,7 +1374,7 @@ function Workspace({
});
setIsRecording(true, {
workflowPermanentId: workflowPermanentId ?? null,
- browserSessionId: liveBrowserSessionId,
+ browserSessionId: debugBrowserSessionId,
});
}, [
getNodes,
@@ -1364,7 +1382,7 @@ function Workspace({
setWorkflowPanelState,
setIsRecording,
workflowPermanentId,
- liveBrowserSessionId,
+ debugBrowserSessionId,
]);
useEffect(() => {
if (!embedded) {
@@ -2477,7 +2495,7 @@ function Workspace({
panels that each fire their own commit. */}
{!embedded && recordingStore.isRecording && (
<div className="absolute inset-0 z-20 h-full px-6 pb-4 pt-[8.5rem]">
- <RecordingPanel browserSessionId={liveBrowserSessionId} />
+ <RecordingPanel browserSessionId={debugBrowserSessionId} />
</div>
)}
</div>
@@ -2518,7 +2536,7 @@ function Workspace({
{showVncBrowserPanel && (
<div className="skyvern-vnc-browser flex h-full w-[calc(100%_-_6rem)] flex-1 flex-col items-center justify-center">
<div key={reloadKey} className="w-full flex-1">
- {!liveBrowserSessionId ? (
+ {!displayBrowserSessionId ? (
isDebugSessionError ? (
<StreamStatusPanel
diagnostic={{
@@ -2548,13 +2566,13 @@ function Workspace({
)
) : isFlowCanvasReady || recordingStore.isRecording ? (
<BrowserStream
- key={liveBrowserSessionId}
+ key={displayBrowserSessionId}
exfiltrate={
recordingStore.isRecording &&
!recordingStore.finishRequested
}
interactive={true}
- browserSessionId={liveBrowserSessionId}
+ browserSessionId={displayBrowserSessionId}
showControlButtons={true}
// The recording panel overlays the canvas whenever a
// recording is live here, so the REC pill is redundant.
@@ -2616,7 +2634,7 @@ function Workspace({
key={reloadKey}
className="flex w-full flex-1 items-center justify-center"
>
- {!liveBrowserSessionId ? (
+ {!displayBrowserSessionId ? (
isDebugSessionError ? (
<StreamStatusPanel
diagnostic={{
@@ -2646,7 +2664,7 @@ function Workspace({
)
) : isFlowCanvasReady || recordingStore.isRecording ? (
<BrowserSessionStream
- browserSessionId={liveBrowserSessionId}
+ browserSessionId={displayBrowserSessionId}
interactive={true}
showControlButtons={true}
onReadyChange={handleLiveBrowserReadyChange}
@@ -2818,8 +2836,9 @@ function Workspace({
onMessageCountChange={setCopilotMessageCount}
buttonRef={copilotButtonRef}
liveBrowserSessionId={
- copilotLiveBrowserReady ? liveBrowserSessionId : null
+ copilotLiveBrowserReady ? debugBrowserSessionId : null
}
+ onTurnActivityChange={setIsCopilotTurnActive}
workflowRunId={copilotRunId({ embedded, studioRunId })}
requiresLiveBrowser={copilotRequiresLiveBrowser}
isLiveBrowserReady={copilotLiveBrowserReady}
diff --git a/skyvern-frontend/src/routes/workflows/editor/browserSessionBindings.ts b/skyvern-frontend/src/routes/workflows/editor/browserSessionBindings.ts
new file mode 100644
index 000000000..65e2bb18a
--- /dev/null
+++ b/skyvern-frontend/src/routes/workflows/editor/browserSessionBindings.ts
@@ -0,0 +1,9 @@
+export function resolveWorkspaceBrowserSessionBindings(
+ debugBrowserSessionId: string | null,
+ activeRunSessionId: string | null,
+) {
+ return {
+ debugBrowserSessionId,
+ displayBrowserSessionId: activeRunSessionId ?? debugBrowserSessionId,
+ };
+}
diff --git a/skyvern-frontend/src/routes/workflows/hooks/useActiveRunSessionQuery.test.ts b/skyvern-frontend/src/routes/workflows/hooks/useActiveRunSessionQuery.test.ts
new file mode 100644
index 000000000..39aba21ad
--- /dev/null
+++ b/skyvern-frontend/src/routes/workflows/hooks/useActiveRunSessionQuery.test.ts
@@ -0,0 +1,35 @@
+import { describe, expect, test } from "vitest";
+
+import {
+ ACTIVE_RUN_SESSION_REFETCH_INTERVAL_MS,
+ getActiveRunSessionRefetchInterval,
+} from "./useActiveRunSessionQuery";
+
+describe("getActiveRunSessionRefetchInterval", () => {
+ test("polls while the local Copilot turn is active", () => {
+ expect(
+ getActiveRunSessionRefetchInterval(
+ { data: { active_run_session_id: null } },
+ true,
+ ),
+ ).toBe(ACTIVE_RUN_SESSION_REFETCH_INTERVAL_MS);
+ });
+
+ test("keeps polling a server-reported run after a mid-run reload", () => {
+ expect(
+ getActiveRunSessionRefetchInterval(
+ { data: { active_run_session_id: "pbs_run" } },
+ false,
+ ),
+ ).toBe(ACTIVE_RUN_SESSION_REFETCH_INTERVAL_MS);
+ });
+
+ test("stops after both local and server activity are terminal", () => {
+ expect(
+ getActiveRunSessionRefetchInterval(
+ { data: { active_run_session_id: null } },
+ false,
+ ),
+ ).toBe(false);
+ });
+});
diff --git a/skyvern-frontend/src/routes/workflows/hooks/useActiveRunSessionQuery.ts b/skyvern-frontend/src/routes/workflows/hooks/useActiveRunSessionQuery.ts
new file mode 100644
index 000000000..00370dd91
--- /dev/null
+++ b/skyvern-frontend/src/routes/workflows/hooks/useActiveRunSessionQuery.ts
@@ -0,0 +1,65 @@
+import { getClient } from "@/api/AxiosClient";
+import { DebugSessionViewerStateApiResponse } from "@/api/types";
+import { useCredentialGetter } from "@/hooks/useCredentialGetter";
+import { useQuery } from "@tanstack/react-query";
+import { useEffect, useRef } from "react";
+
+const ACTIVE_RUN_SESSION_REFETCH_INTERVAL_MS = 1000;
+
+type ActiveRunSessionRefetchState = {
+ data?: DebugSessionViewerStateApiResponse;
+};
+
+function getActiveRunSessionRefetchInterval(
+ queryState: ActiveRunSessionRefetchState,
+ isTurnActive: boolean,
+): number | false {
+ return isTurnActive || Boolean(queryState.data?.active_run_session_id)
+ ? ACTIVE_RUN_SESSION_REFETCH_INTERVAL_MS
+ : false;
+}
+
+interface Opts {
+ workflowPermanentId?: string;
+ enabled?: boolean;
+ isTurnActive: boolean;
+}
+
+function useActiveRunSessionQuery({
+ workflowPermanentId,
+ enabled = true,
+ isTurnActive,
+}: Opts) {
+ const credentialGetter = useCredentialGetter();
+ const query = useQuery<DebugSessionViewerStateApiResponse>({
+ queryKey: ["debugSessionViewerState", workflowPermanentId],
+ queryFn: async () => {
+ const client = await getClient(credentialGetter, "sans-api-v1");
+ const response = await client.get<DebugSessionViewerStateApiResponse>(
+ `/debug-session/${workflowPermanentId}/viewer-state`,
+ );
+ return response.data;
+ },
+ enabled: enabled && Boolean(workflowPermanentId),
+ refetchInterval: (activeQuery) =>
+ getActiveRunSessionRefetchInterval(activeQuery.state, isTurnActive),
+ refetchIntervalInBackground: true,
+ refetchOnWindowFocus: true,
+ });
+ const priorTurnActive = useRef(isTurnActive);
+
+ useEffect(() => {
+ if (priorTurnActive.current !== isTurnActive && enabled) {
+ void query.refetch();
+ }
+ priorTurnActive.current = isTurnActive;
+ }, [enabled, isTurnActive, query]);
+
+ return query;
+}
+
+export {
+ ACTIVE_RUN_SESSION_REFETCH_INTERVAL_MS,
+ getActiveRunSessionRefetchInterval,
+ useActiveRunSessionQuery,
+};
diff --git a/skyvern/client/client.py b/skyvern/client/client.py
index 11a6902e0..a162adc6b 100644
--- a/skyvern/client/client.py
+++ b/skyvern/client/client.py
@@ -2135,6 +2135,7 @@ class Skyvern:
def create_browser_session(
self,
*,
+ url: typing.Optional[str] = OMIT,
timeout: typing.Optional[int] = OMIT,
proxy_location: typing.Optional[CreateBrowserSessionRequestProxyLocation] = OMIT,
proxy_session_id: typing.Optional[str] = OMIT,
@@ -2149,6 +2150,9 @@ class Skyvern:
Parameters
----------
+ url : typing.Optional[str]
+ Optional URL to open when the standalone browser session starts.
+
timeout : typing.Optional[int]
Timeout in minutes for the session. Timeout is applied after the session is started. Must be at least 5; values above 240 are capped at 240. Defaults to 60.
@@ -2222,6 +2226,7 @@ class Skyvern:
client.create_browser_session()
"""
_response = self._raw_client.create_browser_session(
+ url=url,
timeout=timeout,
proxy_location=proxy_location,
proxy_session_id=proxy_session_id,
@@ -6285,6 +6290,7 @@ class AsyncSkyvern:
async def create_browser_session(
self,
*,
+ url: typing.Optional[str] = OMIT,
timeout: typing.Optional[int] = OMIT,
proxy_location: typing.Optional[CreateBrowserSessionRequestProxyLocation] = OMIT,
proxy_session_id: typing.Optional[str] = OMIT,
@@ -6299,6 +6305,9 @@ class AsyncSkyvern:
Parameters
----------
+ url : typing.Optional[str]
+ Optional URL to open when the standalone browser session starts.
+
timeout : typing.Optional[int]
Timeout in minutes for the session. Timeout is applied after the session is started. Must be at least 5; values above 240 are capped at 240. Defaults to 60.
@@ -6380,6 +6389,7 @@ class AsyncSkyvern:
asyncio.run(main())
"""
_response = await self._raw_client.create_browser_session(
+ url=url,
timeout=timeout,
proxy_location=proxy_location,
proxy_session_id=proxy_session_id,
diff --git a/skyvern/client/raw_client.py b/skyvern/client/raw_client.py
index 411b229fc..393aaf332 100644
--- a/skyvern/client/raw_client.py
+++ b/skyvern/client/raw_client.py
@@ -3193,6 +3193,7 @@ class RawSkyvern:
def create_browser_session(
self,
*,
+ url: typing.Optional[str] = OMIT,
timeout: typing.Optional[int] = OMIT,
proxy_location: typing.Optional[CreateBrowserSessionRequestProxyLocation] = OMIT,
proxy_session_id: typing.Optional[str] = OMIT,
@@ -3207,6 +3208,9 @@ class RawSkyvern:
Parameters
----------
+ url : typing.Optional[str]
+ Optional URL to open when the standalone browser session starts.
+
timeout : typing.Optional[int]
Timeout in minutes for the session. Timeout is applied after the session is started. Must be at least 5; values above 240 are capped at 240. Defaults to 60.
@@ -3274,6 +3278,7 @@ class RawSkyvern:
"v1/browser_sessions",
method="POST",
json={
+ "url": url,
"timeout": timeout,
"proxy_location": convert_and_respect_annotation_metadata(
object_=proxy_location, annotation=CreateBrowserSessionRequestProxyLocation, direction="write"
@@ -8793,6 +8798,7 @@ class AsyncRawSkyvern:
async def create_browser_session(
self,
*,
+ url: typing.Optional[str] = OMIT,
timeout: typing.Optional[int] = OMIT,
proxy_location: typing.Optional[CreateBrowserSessionRequestProxyLocation] = OMIT,
proxy_session_id: typing.Optional[str] = OMIT,
@@ -8807,6 +8813,9 @@ class AsyncRawSkyvern:
Parameters
----------
+ url : typing.Optional[str]
+ Optional URL to open when the standalone browser session starts.
+
timeout : typing.Optional[int]
Timeout in minutes for the session. Timeout is applied after the session is started. Must be at least 5; values above 240 are capped at 240. Defaults to 60.
@@ -8874,6 +8883,7 @@ class AsyncRawSkyvern:
"v1/browser_sessions",
method="POST",
json={
+ "url": url,
"timeout": timeout,
"proxy_location": convert_and_respect_annotation_metadata(
object_=proxy_location, annotation=CreateBrowserSessionRequestProxyLocation, direction="write"
diff --git a/skyvern/forge/sdk/copilot/active_run_session.py b/skyvern/forge/sdk/copilot/active_run_session.py
new file mode 100644
index 000000000..e9cd1905a
--- /dev/null
+++ b/skyvern/forge/sdk/copilot/active_run_session.py
@@ -0,0 +1,129 @@
+from __future__ import annotations
+
+import asyncio
+import json
+import uuid
+from contextlib import asynccontextmanager
+from dataclasses import dataclass
+from datetime import datetime, timedelta, timezone
+from typing import AsyncIterator
+
+from pydantic import BaseModel
+
+from skyvern.forge import app
+
+ACTIVE_RUN_SESSION_TTL = timedelta(minutes=20)
+_CLEAR_SENTINEL = ""
+
+
+@dataclass
+class _LocalLockEntry:
+ lock: asyncio.Lock
+ users: int = 0
+
+
+_LOCAL_LOCKS: dict[tuple[asyncio.AbstractEventLoop, str], _LocalLockEntry] = {}
+
+
+class ActiveRunSessionAssociation(BaseModel):
+ organization_id: str
+ workflow_permanent_id: str
+ debug_browser_session_id: str
+ run_browser_session_id: str
+ workflow_run_id: str
+ turn_id: str
+ generation: str
+ expires_at: datetime
+
+
+def active_run_session_cache_key(organization_id: str, debug_browser_session_id: str) -> str:
+ return f"copilot_active_run_session:{organization_id}:{debug_browser_session_id}"
+
+
+def _lock_key(organization_id: str, debug_browser_session_id: str) -> str:
+ return f"copilot_active_run_session_lock:{organization_id}:{debug_browser_session_id}"
+
+
+@asynccontextmanager
+async def _association_lock(organization_id: str, debug_browser_session_id: str) -> AsyncIterator[None]:
+ cache_key = active_run_session_cache_key(organization_id, debug_browser_session_id)
+ local_key = (asyncio.get_running_loop(), cache_key)
+ entry = _LOCAL_LOCKS.setdefault(local_key, _LocalLockEntry(lock=asyncio.Lock()))
+ entry.users += 1
+ try:
+ async with entry.lock:
+ async with app.CACHE.get_lock(_lock_key(organization_id, debug_browser_session_id)):
+ yield
+ finally:
+ entry.users -= 1
+ if entry.users == 0 and _LOCAL_LOCKS.get(local_key) is entry:
+ _LOCAL_LOCKS.pop(local_key, None)
+
+
+def _decode_association(raw: bytes | str | None) -> ActiveRunSessionAssociation | None:
+ if not raw:
+ return None
+ try:
+ payload = json.loads(raw)
+ association = ActiveRunSessionAssociation.model_validate(payload)
+ except (TypeError, ValueError):
+ return None
+ expires_at = association.expires_at
+ if expires_at.tzinfo is None:
+ expires_at = expires_at.replace(tzinfo=timezone.utc)
+ if expires_at <= datetime.now(timezone.utc):
+ return None
+ return association
+
+
+async def publish_active_run_session(
+ *,
+ organization_id: str,
+ workflow_permanent_id: str,
+ debug_browser_session_id: str,
+ run_browser_session_id: str,
+ workflow_run_id: str,
+ turn_id: str,
+) -> ActiveRunSessionAssociation:
+ expires_at = datetime.now(timezone.utc) + ACTIVE_RUN_SESSION_TTL
+ association = ActiveRunSessionAssociation(
+ organization_id=organization_id,
+ workflow_permanent_id=workflow_permanent_id,
+ debug_browser_session_id=debug_browser_session_id,
+ run_browser_session_id=run_browser_session_id,
+ workflow_run_id=workflow_run_id,
+ turn_id=turn_id,
+ generation=uuid.uuid4().hex,
+ expires_at=expires_at,
+ )
+ async with _association_lock(organization_id, debug_browser_session_id):
+ await app.CACHE.set(
+ active_run_session_cache_key(organization_id, debug_browser_session_id),
+ association.model_dump_json(),
+ ex=ACTIVE_RUN_SESSION_TTL,
+ )
+ return association
+
+
+async def get_active_run_session(
+ *,
+ organization_id: str,
+ debug_browser_session_id: str,
+) -> ActiveRunSessionAssociation | None:
+ raw = await app.CACHE.get(active_run_session_cache_key(organization_id, debug_browser_session_id))
+ return _decode_association(raw)
+
+
+async def clear_active_run_session(
+ *,
+ organization_id: str,
+ debug_browser_session_id: str,
+ generation: str,
+) -> bool:
+ async with _association_lock(organization_id, debug_browser_session_id):
+ key = active_run_session_cache_key(organization_id, debug_browser_session_id)
+ current = _decode_association(await app.CACHE.get(key))
+ if current is None or current.generation != generation:
+ return False
+ await app.CACHE.set(key, _CLEAR_SENTINEL, ex=1)
+ return True
diff --git a/skyvern/forge/sdk/copilot/tools/run_execution.py b/skyvern/forge/sdk/copilot/tools/run_execution.py
index c4dca3f06..441713309 100644
--- a/skyvern/forge/sdk/copilot/tools/run_execution.py
+++ b/skyvern/forge/sdk/copilot/tools/run_execution.py
@@ -18,6 +18,11 @@ import structlog
from skyvern.exceptions import CopilotInlineSequentialCredentialUnsupported
from skyvern.forge import app
from skyvern.forge.sdk.artifact.models import Artifact, ArtifactType
+from skyvern.forge.sdk.copilot.active_run_session import (
+ ActiveRunSessionAssociation,
+ clear_active_run_session,
+ publish_active_run_session,
+)
from skyvern.forge.sdk.copilot.blocker_signal import (
CopilotToolBlockerSignal,
clear_blocker_signal_for_reason_codes,
@@ -127,7 +132,7 @@ from skyvern.forge.sdk.schemas.workflow_copilot import WorkflowCopilotRunOutcome
from skyvern.forge.sdk.settings_manager import SettingsManager
from skyvern.forge.sdk.utils.pdf_parser import extract_pdf_file
from skyvern.forge.sdk.workflow.models.block import CodeBlock
-from skyvern.forge.sdk.workflow.models.parameter import WorkflowParameter
+from skyvern.forge.sdk.workflow.models.parameter import OutputParameter, WorkflowParameter
from skyvern.forge.sdk.workflow.models.workflow import Workflow, WorkflowRun, WorkflowRunStatus
from skyvern.schemas.workflows import BlockType
from skyvern.utils.files import initialize_skyvern_state_file
@@ -1130,7 +1135,10 @@ def _registered_output_identity_workflow(
dispatch_workflow: Workflow | None,
runtime_workflow: Workflow,
) -> Workflow | None:
- if dispatch_to_worker:
+ # Any persisted run snapshot regenerates output-parameter ids, including the inline
+ # prior-draft path. Registered WorkflowRunOutputParameter rows therefore identify the
+ # snapshot definition, not the in-memory runtime workflow.
+ if dispatch_workflow is not None:
return dispatch_workflow
return runtime_workflow
@@ -1656,7 +1664,7 @@ async def _run_blocks_and_collect_debug(
runtime_frontier_starter_url_seeded = False
user_params: dict[str, Any] = params.get("parameters") or {}
- all_workflow_params, all_output_params = await asyncio.gather(
+ persisted_workflow_params, persisted_output_params = await asyncio.gather(
app.WORKFLOW_SERVICE.get_workflow_parameters(workflow_id=workflow.workflow_id),
app.DATABASE.workflow_params.get_workflow_output_parameters(workflow_id=workflow.workflow_id),
)
@@ -1667,7 +1675,7 @@ async def _run_blocks_and_collect_debug(
invariant_error = (
None
if resolved_from_prior_draft
- else _parameter_binding_invariant_error(workflow, all_workflow_params, all_output_params)
+ else _parameter_binding_invariant_error(workflow, persisted_workflow_params, persisted_output_params)
)
if invariant_error is not None:
summary, missing_persisted, missing_from_definition = invariant_error
@@ -1694,18 +1702,12 @@ async def _run_blocks_and_collect_debug(
},
}
- # Multi-word/PII values the persist-time policy withholds from default_value are bound run-scoped
- # here (WorkflowRequestBody.data, never default_value) so the test run uses the scout-proven value.
- scout_ephemeral_values = _scout_ephemeral_values(ctx, {wp.key for wp in all_workflow_params})
- data, ctx.unbound_required_parameter_keys = _resolve_run_data_and_unbound_keys(
- all_workflow_params, user_params, scout_ephemeral_values
- )
-
use_fresh_session = _should_use_fresh_session_for_login_first_replay(ctx, labels_to_execute, workflow)
# True when the run was threaded into a fresh session rather than the scout's debug session;
# gates the post-run rebind (~:1135) so the ephemeral run session is not adopted as the
# context session.
used_fresh_run_session = False
+ debug_session_id: str | None = None
# Without a session, the workflow service launches the browser in-process,
# which only works in worker pods (cloakbrowser isn't in the API image).
@@ -1748,23 +1750,17 @@ async def _run_blocks_and_collect_debug(
runtime_frontier_starter_url_seeded = seeded_runtime_workflow is not runtime_workflow
runtime_workflow = seeded_runtime_workflow
- workflow_request = WorkflowRequestBody(
- data=data if data else None,
- browser_session_id=run_session_id,
- # Copilot test runs don't need scrolling post-action screenshots;
- # the ForgeAgent's split screenshots (used for LLM context) are unaffected.
- max_screenshot_scrolls=0,
- )
-
- # Snapshot version persisted for a dispatched run; the run is created against its exact
- # workflow_id so the worker resolves the wrapped definition via run.workflow_id, and it is
- # soft-deleted once the run resolves so it never lingers as the latest-by-permanent-id pointer
- # for edit/view. None for the inline dev path.
+ # Snapshot version persisted for a worker-dispatched run or an inline run sourced from an
+ # unsaved prior draft. The run is created against its exact workflow_id so prepare_workflow
+ # reads parameter rows from the same definition execute_workflow receives. Without the inline
+ # prior-draft snapshot, newly drafted parameters exist only in memory and are omitted from the
+ # WorkflowRunParameter rows, causing block execution to fail before it reaches the browser.
+ # The snapshot is soft-deleted once the run resolves so it never lingers as the latest version.
dispatch_draft_workflow_id: str | None = None
# The persisted dispatch version (its own regenerated parameter ids) used for post-run output
# mapping on the dispatch path; runtime_workflow / ctx.staged_workflow is left unmutated.
dispatch_workflow: Workflow | None = None
- if dispatch_to_worker:
+ if dispatch_to_worker or resolved_from_prior_draft:
# Persist the wrapped runtime workflow as a real new version (with its own parameter /
# output-parameter rows) through the normal create machinery. The run is then created
# against this version so the worker resolves it by run.workflow_id and registers block
@@ -1777,11 +1773,48 @@ async def _run_blocks_and_collect_debug(
dispatch_draft_workflow_id = dispatch_workflow.workflow_id
except Exception:
LOG.warning(
- "Failed to persist copilot dispatch version; blocking execution",
+ "Failed to persist copilot run snapshot; blocking execution",
workflow_permanent_id=ctx.workflow_permanent_id,
+ dispatch_to_worker=dispatch_to_worker,
+ resolved_from_prior_draft=resolved_from_prior_draft,
exc_info=True,
)
- return _copilot_sandbox_unavailable_result()
+ if dispatch_to_worker:
+ return _copilot_sandbox_unavailable_result()
+ return {
+ "ok": False,
+ "error": "Unable to prepare the Copilot test-run snapshot; execution was not started.",
+ }
+
+ if dispatch_workflow is not None:
+ all_workflow_params = [
+ parameter
+ for parameter in dispatch_workflow.workflow_definition.parameters
+ if isinstance(parameter, WorkflowParameter)
+ ]
+ all_output_params = [
+ parameter
+ for parameter in dispatch_workflow.workflow_definition.parameters
+ if isinstance(parameter, OutputParameter)
+ ]
+ else:
+ all_workflow_params = persisted_workflow_params
+ all_output_params = persisted_output_params
+
+ # Multi-word/PII values the persist-time policy withholds from default_value are bound run-scoped
+ # here (WorkflowRequestBody.data, never default_value) so the test run uses the scout-proven value.
+ scout_ephemeral_values = _scout_ephemeral_values(ctx, {wp.key for wp in all_workflow_params})
+ data, ctx.unbound_required_parameter_keys = _resolve_run_data_and_unbound_keys(
+ all_workflow_params, user_params, scout_ephemeral_values
+ )
+
+ workflow_request = WorkflowRequestBody(
+ data=data if data else None,
+ browser_session_id=run_session_id,
+ # Copilot test runs don't need scrolling post-action screenshots;
+ # the ForgeAgent's split screenshots (used for LLM context) are unaffected.
+ max_screenshot_scrolls=0,
+ )
# run_task is the in-process inline execution task, only ever set on the dev-only inline path.
# For dispatched runs it stays None: the worker owns execution and the watchdog observes purely
@@ -1880,423 +1913,465 @@ async def _run_blocks_and_collect_debug(
dispatch_draft_workflow_id = None
raise
- # The OpenAI Agents SDK wraps this tool in
- # ``asyncio.wait_for(..., timeout=RUN_BLOCKS_SAFETY_CEILING_SECONDS)``, so
- # the inner budget leaves 10 s of headroom for the cancel-drain and
- # post-drain reconcile to finish before the SDK's own cancel fires.
- #
- # Do NOT short-circuit on client disconnect: the agent loop runs to
- # completion after the SSE stream is gone so its reply persists
- # (SKY-8986); aborting mid-block would strand the run without debug
- # output for the final chat message.
- initial_run, initial_step_ts, initial_block_ts = await _read_progress_sources(ctx, workflow_run.workflow_run_id)
- progress_marker = _progress_marker(initial_run, initial_step_ts, initial_block_ts)
- last_progress_monotonic = time.monotonic()
- started_monotonic = last_progress_monotonic
- final_status: str | None = None
- run: Any = initial_run
- exit_reason: WatchdogExitReason | None = None
- run_cancelled_by_watchdog = False
- # Quiet blocks (WAIT/TEXT_PROMPT/HUMAN_INTERACTION) legitimately have
- # DB-silent periods; disable stagnation for any invocation that includes
- # one. Safety ceiling still applies.
- stagnation_enabled = not _any_quiet_block_requested(ctx, labels_to_execute)
- # Active block runs use the tighter per-tool budget so a single in-flight
- # call cannot consume the whole copilot session. Quiet-block runs keep the
- # long safety ceiling because HumanInteractionBlock can legitimately pause
- # indefinitely.
- budget_exit_reason: WatchdogExitReason
- if stagnation_enabled:
- budget_seconds = _active_block_run_budget_seconds(ctx)
- budget_exit_reason = "per_tool_budget"
- else:
- budget_seconds = max(1, RUN_BLOCKS_SAFETY_CEILING_SECONDS - 10)
- budget_exit_reason = "ceiling"
-
- # Mid-tool narrator bridge: feed block-status changes and step-level
- # heartbeats into NarratorState so the narration ticker keeps emitting
- # while a long workflow run is in flight.
- narrator_state: NarratorState | None = getattr(ctx, "narrator_state", None)
- narrator_enabled = narrator_state is not None and narration_handler_available()
- seen_block_states: dict[str, str] = {}
- prior_block_ts: datetime | None = initial_block_ts
- last_block_fetch_monotonic = 0.0
+ active_run_association: ActiveRunSessionAssociation | None = None
+ if used_fresh_run_session and debug_session_id and run_session_id:
+ try:
+ active_run_association = await publish_active_run_session(
+ organization_id=ctx.organization_id,
+ workflow_permanent_id=ctx.workflow_permanent_id,
+ debug_browser_session_id=debug_session_id,
+ run_browser_session_id=run_session_id,
+ workflow_run_id=workflow_run.workflow_run_id,
+ turn_id=ctx.turn_id,
+ )
+ except Exception:
+ LOG.warning(
+ "Failed to publish active Copilot run session",
+ organization_id=ctx.organization_id,
+ workflow_permanent_id=ctx.workflow_permanent_id,
+ workflow_run_id=workflow_run.workflow_run_id,
+ debug_browser_session_id=debug_session_id,
+ run_browser_session_id=run_session_id,
+ exc_info=True,
+ )
+
try:
- while True:
- await asyncio.sleep(RUN_BLOCKS_POLL_INTERVAL_SECONDS)
-
- run, step_ts, block_ts = await _read_progress_sources(ctx, workflow_run.workflow_run_id)
-
- if narrator_enabled:
- assert narrator_state is not None # narrator_enabled implies non-None
- tick_result = await narrator_poll_tick(
- narrator_state,
- current_block_ts=block_ts,
- prior_block_ts=prior_block_ts,
- last_block_fetch_monotonic=last_block_fetch_monotonic,
- seen_block_states=seen_block_states,
- fetch_block_statuses=lambda: app.DATABASE.observer.get_workflow_run_blocks(
+ # The OpenAI Agents SDK wraps this tool in
+ # ``asyncio.wait_for(..., timeout=RUN_BLOCKS_SAFETY_CEILING_SECONDS)``, so
+ # the inner budget leaves 10 s of headroom for the cancel-drain and
+ # post-drain reconcile to finish before the SDK's own cancel fires.
+ #
+ # Do NOT short-circuit on client disconnect: the agent loop runs to
+ # completion after the SSE stream is gone so its reply persists
+ # (SKY-8986); aborting mid-block would strand the run without debug
+ # output for the final chat message.
+ initial_run, initial_step_ts, initial_block_ts = await _read_progress_sources(ctx, workflow_run.workflow_run_id)
+ progress_marker = _progress_marker(initial_run, initial_step_ts, initial_block_ts)
+ last_progress_monotonic = time.monotonic()
+ started_monotonic = last_progress_monotonic
+ final_status: str | None = None
+ run: Any = initial_run
+ exit_reason: WatchdogExitReason | None = None
+ run_cancelled_by_watchdog = False
+ # Quiet blocks (WAIT/TEXT_PROMPT/HUMAN_INTERACTION) legitimately have
+ # DB-silent periods; disable stagnation for any invocation that includes
+ # one. Safety ceiling still applies.
+ stagnation_enabled = not _any_quiet_block_requested(ctx, labels_to_execute)
+ # Active block runs use the tighter per-tool budget so a single in-flight
+ # call cannot consume the whole copilot session. Quiet-block runs keep the
+ # long safety ceiling because HumanInteractionBlock can legitimately pause
+ # indefinitely.
+ budget_exit_reason: WatchdogExitReason
+ if stagnation_enabled:
+ budget_seconds = _active_block_run_budget_seconds(ctx)
+ budget_exit_reason = "per_tool_budget"
+ else:
+ budget_seconds = max(1, RUN_BLOCKS_SAFETY_CEILING_SECONDS - 10)
+ budget_exit_reason = "ceiling"
+
+ # Mid-tool narrator bridge: feed block-status changes and step-level
+ # heartbeats into NarratorState so the narration ticker keeps emitting
+ # while a long workflow run is in flight.
+ narrator_state: NarratorState | None = getattr(ctx, "narrator_state", None)
+ narrator_enabled = narrator_state is not None and narration_handler_available()
+ seen_block_states: dict[str, str] = {}
+ prior_block_ts: datetime | None = initial_block_ts
+ last_block_fetch_monotonic = 0.0
+ try:
+ while True:
+ await asyncio.sleep(RUN_BLOCKS_POLL_INTERVAL_SECONDS)
+
+ run, step_ts, block_ts = await _read_progress_sources(ctx, workflow_run.workflow_run_id)
+
+ if narrator_enabled:
+ assert narrator_state is not None # narrator_enabled implies non-None
+ tick_result = await narrator_poll_tick(
+ narrator_state,
+ current_block_ts=block_ts,
+ prior_block_ts=prior_block_ts,
+ last_block_fetch_monotonic=last_block_fetch_monotonic,
+ seen_block_states=seen_block_states,
+ fetch_block_statuses=lambda: app.DATABASE.observer.get_workflow_run_blocks(
+ workflow_run_id=workflow_run.workflow_run_id,
+ organization_id=ctx.organization_id,
+ ),
+ stream=ctx.stream,
+ block_state_map=ctx.block_state_map,
+ block_started_at_map=ctx.block_started_at_map,
+ block_ended_at_map=ctx.block_ended_at_map,
workflow_run_id=workflow_run.workflow_run_id,
- organization_id=ctx.organization_id,
- ),
- stream=ctx.stream,
- block_state_map=ctx.block_state_map,
- block_started_at_map=ctx.block_started_at_map,
- block_ended_at_map=ctx.block_ended_at_map,
- workflow_run_id=workflow_run.workflow_run_id,
- )
- prior_block_ts = tick_result.prior_block_ts
- last_block_fetch_monotonic = tick_result.last_block_fetch_monotonic
-
- if run and WorkflowRunStatus(run.status).is_final():
- final_status = run.status
- exit_reason = "success"
- break
-
- if run_task is not None and run_task.done():
- # Row not terminal yet — shared reconcile path below flips
- # most of these back to success after post-drain reread.
- # Dispatched runs have no in-process task, so loop exit is anchored purely
- # on the DB-terminal status check above.
- exit_reason = "task_exit_unfinalized"
- break
-
- now = time.monotonic()
- new_marker = _progress_marker(run, step_ts, block_ts)
- # A run in ``paused`` status (e.g. HumanInteractionBlock) is a
- # user-driven wait, not stagnation — never trip.
- is_paused = run is not None and run.status == WorkflowRunStatus.paused.value
- stagnation_active = stagnation_enabled and not is_paused
-
- if new_marker != progress_marker:
- progress_marker = new_marker
- last_progress_monotonic = now
- elif stagnation_active and now - last_progress_monotonic >= RUN_BLOCKS_STAGNATION_WINDOW_SECONDS:
- exit_reason = "stagnation"
- break
-
- if now - started_monotonic >= budget_seconds:
- exit_reason = budget_exit_reason
- break
-
- if exit_reason is not None and exit_reason != "success":
- # Pre-cancel read first: a legitimate self-finalize (user/block
- # cancel, or any terminal the run wrote itself) can land between
- # the last poll and here, and trusting it avoids the
- # synthetic-``canceled`` ambiguity that the post-drain reread
- # has to exclude. Then cancel + reread +
- # ``_trusted_post_drain_status`` applies SKY-9167's success-race
- # recovery uniformly to all three non-success exit reasons.
- pre_cancel_run = await _safe_read_workflow_run(
- workflow_run.workflow_run_id, ctx.organization_id, context="pre-cancel"
- )
- if pre_cancel_run is not None and WorkflowRunStatus(pre_cancel_run.status).is_final():
- final_status = pre_cancel_run.status
- run = pre_cancel_run
- exit_reason = "success"
- else:
- if pre_cancel_run is not None:
- run = pre_cancel_run
- if run is None or not WorkflowRunStatus(run.status).is_final():
- if run_task is not None:
- await _cancel_run_task_if_not_final(run_task, workflow_run.workflow_run_id)
- else:
- # Dispatched run — cooperative DB cancel so the worker stops.
- await _cooperative_cancel_dispatched_run(workflow_run.workflow_run_id)
- run_cancelled_by_watchdog = True
- run = await _safe_read_workflow_run(
- workflow_run.workflow_run_id, ctx.organization_id, context="post-drain"
)
- trusted = _trusted_post_drain_status(run)
- if trusted is not None:
- final_status = trusted
+ prior_block_ts = tick_result.prior_block_ts
+ last_block_fetch_monotonic = tick_result.last_block_fetch_monotonic
+
+ if run and WorkflowRunStatus(run.status).is_final():
+ final_status = run.status
exit_reason = "success"
+ break
- if exit_reason != "success":
- assert exit_reason is not None # narrows for mypy; outer check excludes "success" but not None
- _mark_pending_reconciliation_run(ctx, workflow_run.workflow_run_id)
- error_msg = await _watchdog_error_message(
- exit_reason, ctx, workflow_run.workflow_run_id, run, budget_seconds, dispatch_to_worker
- )
- user_failure_reason = _watchdog_user_failure_reason(
- exit_reason, workflow_run.workflow_run_id, budget_seconds, run
- )
- user_facing_summary = _watchdog_user_facing_summary(exit_reason, budget_seconds, run)
- # Dispatched runs: the worker owns the run session, so do not attach to it over CDP.
- current_url, page_title = (
- ("", "") if dispatch_to_worker else await _fallback_page_info(ctx, session_id_override=run_session_id)
- )
- result: dict[str, Any] = {
- "ok": False,
- "error": error_msg,
- "data": {
- "workflow_run_id": workflow_run.workflow_run_id,
- "overall_status": run.status if run is not None else None,
- "failure_reason": user_failure_reason,
- "current_url": current_url,
- "page_title": page_title,
- },
- }
- result["data"]["control_signal"] = {
- "kind": f"watchdog_{exit_reason}",
- "user_facing_summary": user_facing_summary,
- }
- result["data"]["user_facing_summary"] = user_facing_summary
- if exit_reason == "per_tool_budget":
- # Stable failure_categories entry so consecutive budget trips
- # hash to the same streak signature; without it the run_id in
- # ``error_msg`` would make every trip unique.
- result["data"]["failure_categories"] = [
- {
- "category": PER_TOOL_BUDGET_FAILURE_CATEGORY,
- "confidence_float": 1.0,
- "reasoning": (
- f"Per-tool-call budget of {budget_seconds}s exceeded; "
- "the run was making progress but cannot fit in a single tool call."
- ),
- }
- ]
- if run_cancelled_by_watchdog:
- result[_INTERNAL_RUN_CANCELLED_BY_WATCHDOG_KEY] = True
- return result
- except asyncio.CancelledError:
- # The SDK's @function_tool(timeout=...) cancelled us mid-poll. Shield
- # the cleanup so the parent cancellation can't interrupt it mid-await.
- # If the shield itself is cancelled, fall back to a detached task
- # that outlives tool teardown and still reconciles workflow state.
- cancel_cleanup = (
- _cancel_run_task_if_not_final(run_task, workflow_run.workflow_run_id)
- if run_task is not None
- # Dispatched run: no in-process task, cooperatively flip the DB status instead.
- else _cooperative_cancel_dispatched_run(workflow_run.workflow_run_id)
- )
- try:
- await asyncio.shield(cancel_cleanup)
+ if run_task is not None and run_task.done():
+ # Row not terminal yet — shared reconcile path below flips
+ # most of these back to success after post-drain reread.
+ # Dispatched runs have no in-process task, so loop exit is anchored purely
+ # on the DB-terminal status check above.
+ exit_reason = "task_exit_unfinalized"
+ break
+
+ now = time.monotonic()
+ new_marker = _progress_marker(run, step_ts, block_ts)
+ # A run in ``paused`` status (e.g. HumanInteractionBlock) is a
+ # user-driven wait, not stagnation — never trip.
+ is_paused = run is not None and run.status == WorkflowRunStatus.paused.value
+ stagnation_active = stagnation_enabled and not is_paused
+
+ if new_marker != progress_marker:
+ progress_marker = new_marker
+ last_progress_monotonic = now
+ elif stagnation_active and now - last_progress_monotonic >= RUN_BLOCKS_STAGNATION_WINDOW_SECONDS:
+ exit_reason = "stagnation"
+ break
+
+ if now - started_monotonic >= budget_seconds:
+ exit_reason = budget_exit_reason
+ break
+
+ if exit_reason is not None and exit_reason != "success":
+ # Pre-cancel read first: a legitimate self-finalize (user/block
+ # cancel, or any terminal the run wrote itself) can land between
+ # the last poll and here, and trusting it avoids the
+ # synthetic-``canceled`` ambiguity that the post-drain reread
+ # has to exclude. Then cancel + reread +
+ # ``_trusted_post_drain_status`` applies SKY-9167's success-race
+ # recovery uniformly to all three non-success exit reasons.
+ pre_cancel_run = await _safe_read_workflow_run(
+ workflow_run.workflow_run_id, ctx.organization_id, context="pre-cancel"
+ )
+ if pre_cancel_run is not None and WorkflowRunStatus(pre_cancel_run.status).is_final():
+ final_status = pre_cancel_run.status
+ run = pre_cancel_run
+ exit_reason = "success"
+ else:
+ if pre_cancel_run is not None:
+ run = pre_cancel_run
+ if run is None or not WorkflowRunStatus(run.status).is_final():
+ if run_task is not None:
+ await _cancel_run_task_if_not_final(run_task, workflow_run.workflow_run_id)
+ else:
+ # Dispatched run — cooperative DB cancel so the worker stops.
+ await _cooperative_cancel_dispatched_run(workflow_run.workflow_run_id)
+ run_cancelled_by_watchdog = True
+ run = await _safe_read_workflow_run(
+ workflow_run.workflow_run_id, ctx.organization_id, context="post-drain"
+ )
+ trusted = _trusted_post_drain_status(run)
+ if trusted is not None:
+ final_status = trusted
+ exit_reason = "success"
+
+ if exit_reason != "success":
+ assert exit_reason is not None # narrows for mypy; outer check excludes "success" but not None
+ _mark_pending_reconciliation_run(ctx, workflow_run.workflow_run_id)
+ error_msg = await _watchdog_error_message(
+ exit_reason, ctx, workflow_run.workflow_run_id, run, budget_seconds, dispatch_to_worker
+ )
+ user_failure_reason = _watchdog_user_failure_reason(
+ exit_reason, workflow_run.workflow_run_id, budget_seconds, run
+ )
+ user_facing_summary = _watchdog_user_facing_summary(exit_reason, budget_seconds, run)
+ # Dispatched runs: the worker owns the run session, so do not attach to it over CDP.
+ current_url, page_title = (
+ ("", "")
+ if dispatch_to_worker
+ else await _fallback_page_info(ctx, session_id_override=run_session_id)
+ )
+ result: dict[str, Any] = {
+ "ok": False,
+ "error": error_msg,
+ "data": {
+ "workflow_run_id": workflow_run.workflow_run_id,
+ "overall_status": run.status if run is not None else None,
+ "failure_reason": user_failure_reason,
+ "current_url": current_url,
+ "page_title": page_title,
+ },
+ }
+ result["data"]["control_signal"] = {
+ "kind": f"watchdog_{exit_reason}",
+ "user_facing_summary": user_facing_summary,
+ }
+ result["data"]["user_facing_summary"] = user_facing_summary
+ if exit_reason == "per_tool_budget":
+ # Stable failure_categories entry so consecutive budget trips
+ # hash to the same streak signature; without it the run_id in
+ # ``error_msg`` would make every trip unique.
+ result["data"]["failure_categories"] = [
+ {
+ "category": PER_TOOL_BUDGET_FAILURE_CATEGORY,
+ "confidence_float": 1.0,
+ "reasoning": (
+ f"Per-tool-call budget of {budget_seconds}s exceeded; "
+ "the run was making progress but cannot fit in a single tool call."
+ ),
+ }
+ ]
+ if run_cancelled_by_watchdog:
+ result[_INTERNAL_RUN_CANCELLED_BY_WATCHDOG_KEY] = True
+ return result
except asyncio.CancelledError:
- fallback_cleanup = (
+ # The SDK's @function_tool(timeout=...) cancelled us mid-poll. Shield
+ # the cleanup so the parent cancellation can't interrupt it mid-await.
+ # If the shield itself is cancelled, fall back to a detached task
+ # that outlives tool teardown and still reconciles workflow state.
+ cancel_cleanup = (
_cancel_run_task_if_not_final(run_task, workflow_run.workflow_run_id)
if run_task is not None
+ # Dispatched run: no in-process task, cooperatively flip the DB status instead.
else _cooperative_cancel_dispatched_run(workflow_run.workflow_run_id)
)
- fallback = asyncio.ensure_future(fallback_cleanup)
- _DETACHED_CLEANUP_TASKS.add(fallback)
- fallback.add_done_callback(_DETACHED_CLEANUP_TASKS.discard)
- fallback.add_done_callback(_log_detached_cleanup_failure)
- raise
- finally:
- # If any exit path above missed a cancel — e.g. an unexpected exception bubbling out of the
- # poll loop — signal the run_task so we don't leak it. Dispatched runs have no in-process
- # task, so there is nothing to signal.
- if run_task is not None and not run_task.done():
- run_task.cancel()
- # Soft-delete the pinned draft so it never lingers as the latest version. Gated on a final
- # run state: on the normal path the poll loop only exits once the run is terminal, but an
- # unexpected exception can reach here before the worker has loaded the draft, and deleting
- # it then would 404 the worker's get_workflow(run.workflow_id). Runs on every exit path
- # (success fall-through, failure return, cancel raise).
- if dispatch_draft_workflow_id is not None:
- await _delete_dispatch_draft_if_run_final(
- dispatch_draft_workflow_id, workflow_run.workflow_run_id, ctx.organization_id
- )
-
- # Skip the rebind when a fresh run session was used so the scout's restored
- # debug session stays the context session for the rest of the turn.
- if not used_fresh_run_session and run and run.browser_session_id:
- ctx.browser_session_id = run.browser_session_id
+ try:
+ await asyncio.shield(cancel_cleanup)
+ except asyncio.CancelledError:
+ fallback_cleanup = (
+ _cancel_run_task_if_not_final(run_task, workflow_run.workflow_run_id)
+ if run_task is not None
+ else _cooperative_cancel_dispatched_run(workflow_run.workflow_run_id)
+ )
+ fallback = asyncio.ensure_future(fallback_cleanup)
+ _DETACHED_CLEANUP_TASKS.add(fallback)
+ fallback.add_done_callback(_DETACHED_CLEANUP_TASKS.discard)
+ fallback.add_done_callback(_log_detached_cleanup_failure)
+ raise
+ finally:
+ # If any exit path above missed a cancel — e.g. an unexpected exception bubbling out of the
+ # poll loop — signal the run_task so we don't leak it. Dispatched runs have no in-process
+ # task, so there is nothing to signal.
+ if run_task is not None and not run_task.done():
+ run_task.cancel()
+ # Soft-delete the pinned draft so it never lingers as the latest version. Gated on a final
+ # run state: on the normal path the poll loop only exits once the run is terminal, but an
+ # unexpected exception can reach here before the worker has loaded the draft, and deleting
+ # it then would 404 the worker's get_workflow(run.workflow_id). Runs on every exit path
+ # (success fall-through, failure return, cancel raise).
+ if dispatch_draft_workflow_id is not None:
+ await _delete_dispatch_draft_if_run_final(
+ dispatch_draft_workflow_id, workflow_run.workflow_run_id, ctx.organization_id
+ )
- blocks = await app.DATABASE.observer.get_workflow_run_blocks(
- workflow_run_id=workflow_run.workflow_run_id,
- organization_id=ctx.organization_id,
- )
+ # Skip the rebind when a fresh run session was used so the scout's restored
+ # debug session stays the context session for the rest of the turn.
+ if not used_fresh_run_session and run and run.browser_session_id:
+ ctx.browser_session_id = run.browser_session_id
- results = []
- block_outputs_by_label: dict[str, Any] = {}
- for block in blocks:
- block_result: dict[str, Any] = {
- "label": block.label,
- "block_type": block.block_type.name if hasattr(block.block_type, "name") else str(block.block_type),
- "status": block.status,
- }
- if block.failure_reason:
- block_result["failure_reason"] = block.failure_reason
- if hasattr(block, "output") and block.output:
- block_result["extracted_data"] = block.output
- if block.label is not None:
- block_outputs_by_label[block.label] = block.output
- results.append(block_result)
+ blocks = await app.DATABASE.observer.get_workflow_run_blocks(
+ workflow_run_id=workflow_run.workflow_run_id,
+ organization_id=ctx.organization_id,
+ )
- # Repository returns DESC by created_at; reverse for chronological order.
- run_block_rows = list(reversed(blocks))
- ctx.last_run_blocks_block_ids = list(
- dict.fromkeys(block.workflow_run_block_id for block in run_block_rows if block.workflow_run_block_id)
- )
- ctx.last_run_blocks_block_labels = list(dict.fromkeys(block.label for block in run_block_rows if block.label))
+ results = []
+ block_outputs_by_label: dict[str, Any] = {}
+ for block in blocks:
+ block_result: dict[str, Any] = {
+ "label": block.label,
+ "block_type": block.block_type.name if hasattr(block.block_type, "name") else str(block.block_type),
+ "status": block.status,
+ }
+ if block.failure_reason:
+ block_result["failure_reason"] = block.failure_reason
+ if hasattr(block, "output") and block.output:
+ block_result["extracted_data"] = block.output
+ if block.label is not None:
+ block_outputs_by_label[block.label] = block.output
+ results.append(block_result)
+
+ # Repository returns DESC by created_at; reverse for chronological order.
+ run_block_rows = list(reversed(blocks))
+ ctx.last_run_blocks_block_ids = list(
+ dict.fromkeys(block.workflow_run_block_id for block in run_block_rows if block.workflow_run_block_id)
+ )
+ ctx.last_run_blocks_block_labels = list(dict.fromkeys(block.label for block in run_block_rows if block.label))
- await _attach_action_traces(blocks, results, ctx.organization_id)
- await _attach_failed_block_screenshots(blocks, results, ctx.organization_id)
+ await _attach_action_traces(blocks, results, ctx.organization_id)
+ await _attach_failed_block_screenshots(blocks, results, ctx.organization_id)
- # final_status is guaranteed set here: every non-success exit returns
- # above, and the success path always populates final_status.
- assert final_status is not None
- run_ok = WorkflowRunStatus(final_status) == WorkflowRunStatus.completed
+ # final_status is guaranteed set here: every non-success exit returns
+ # above, and the success path always populates final_status.
+ assert final_status is not None
+ run_ok = WorkflowRunStatus(final_status) == WorkflowRunStatus.completed
- action_trace_summary: list[str] = []
- first_failed = next(
- (r for r in results if r.get("status") in _FAILED_BLOCK_STATUSES and r.get("action_trace")),
- None,
- )
- if first_failed is not None:
- action_trace_summary = _summarize_action_trace(first_failed.get("action_trace"))
-
- # Compute the action-sequence fingerprint BEFORE we strip action_trace.
- # Stash it on a pending ctx field so update_repeated_failure_state can
- # compare the NEW fingerprint against ctx.last_action_sequence_fingerprint
- # (the PRIOR value) and increment the streak. Never enters the LLM-visible
- # packet. Drives the repeated-action streak that hard-aborts a stuck
- # fill→click→re-fill loop in _tool_loop_error.
- ctx.pending_action_sequence_fingerprint = compute_action_sequence_fingerprint(results)
-
- # Per-block action_trace is for derivation only — keep it out of the
- # compact packet. get_run_results remains the heavier inspection path.
- for entry in results:
- entry.pop("action_trace", None)
-
- # Dispatched runs: the worker owns the run session; do not touch it over CDP from the API.
- # current_url/page_title are sourced from worker-persisted run data elsewhere if needed.
- current_url, page_title = (
- ("", "") if dispatch_to_worker else await _fallback_page_info(ctx, session_id_override=run_session_id)
- )
+ action_trace_summary: list[str] = []
+ first_failed = next(
+ (r for r in results if r.get("status") in _FAILED_BLOCK_STATUSES and r.get("action_trace")),
+ None,
+ )
+ if first_failed is not None:
+ action_trace_summary = _summarize_action_trace(first_failed.get("action_trace"))
+
+ # Compute the action-sequence fingerprint BEFORE we strip action_trace.
+ # Stash it on a pending ctx field so update_repeated_failure_state can
+ # compare the NEW fingerprint against ctx.last_action_sequence_fingerprint
+ # (the PRIOR value) and increment the streak. Never enters the LLM-visible
+ # packet. Drives the repeated-action streak that hard-aborts a stuck
+ # fill→click→re-fill loop in _tool_loop_error.
+ ctx.pending_action_sequence_fingerprint = compute_action_sequence_fingerprint(results)
+
+ # Per-block action_trace is for derivation only — keep it out of the
+ # compact packet. get_run_results remains the heavier inspection path.
+ for entry in results:
+ entry.pop("action_trace", None)
+
+ # Dispatched runs: the worker owns the run session; do not touch it over CDP from the API.
+ # current_url/page_title are sourced from worker-persisted run data elsewhere if needed.
+ current_url, page_title = (
+ ("", "") if dispatch_to_worker else await _fallback_page_info(ctx, session_id_override=run_session_id)
+ )
- screenshot_b64: str | None = None
- # Dispatched runs: the worker owns the persistent browser session, so the API side must not
- # grab the live page over CDP. A worker-persisted screenshot artifact can be surfaced from
- # the DB instead (follow-up); for now the dispatched failure packet omits the inline capture.
- if not dispatch_to_worker and not run_ok and run_session_id:
- try:
- browser_state = await app.PERSISTENT_SESSIONS_MANAGER.get_browser_state(
- session_id=run_session_id,
- organization_id=ctx.organization_id,
- )
- if browser_state:
- page = await browser_state.get_or_create_page()
- if SettingsManager.get_settings().BROWSER_CURSOR_VISUALIZATION:
- try:
- await SkyvernFrame.hide_cursor_overlay(page)
- except Exception:
- pass
- try:
- screenshot_bytes = await page.screenshot(type="png")
- finally:
+ screenshot_b64: str | None = None
+ # Dispatched runs: the worker owns the persistent browser session, so the API side must not
+ # grab the live page over CDP. A worker-persisted screenshot artifact can be surfaced from
+ # the DB instead (follow-up); for now the dispatched failure packet omits the inline capture.
+ if not dispatch_to_worker and not run_ok and run_session_id:
+ try:
+ browser_state = await app.PERSISTENT_SESSIONS_MANAGER.get_browser_state(
+ session_id=run_session_id,
+ organization_id=ctx.organization_id,
+ )
+ if browser_state:
+ page = await browser_state.get_or_create_page()
if SettingsManager.get_settings().BROWSER_CURSOR_VISUALIZATION:
try:
- await SkyvernFrame.show_cursor_overlay(page)
+ await SkyvernFrame.hide_cursor_overlay(page)
except Exception:
pass
- screenshot_b64 = base64.b64encode(screenshot_bytes).decode("utf-8")
- except Exception:
- LOG.debug("Failed to capture post-run screenshot", exc_info=True)
-
- if (
- not dispatch_to_worker
- and run_session_id
- and _copilot_block_authoring_policy(ctx) == BlockAuthoringPolicy.CODE_ONLY_BROWSER
- and not ctx.copilot_total_timeout_exceeded
- ):
- # CDP capture against the run session: worker-owned for dispatched runs, so skip it.
- _pin_pre_run_page_reference(ctx, workflow_run.workflow_run_id)
- await _capture_and_store_post_run_page(
- ctx,
- run_session_id=run_session_id,
- run_id=workflow_run.workflow_run_id,
- current_url=current_url,
- )
+ try:
+ screenshot_bytes = await page.screenshot(type="png")
+ finally:
+ if SettingsManager.get_settings().BROWSER_CURSOR_VISUALIZATION:
+ try:
+ await SkyvernFrame.show_cursor_overlay(page)
+ except Exception:
+ pass
+ screenshot_b64 = base64.b64encode(screenshot_bytes).decode("utf-8")
+ except Exception:
+ LOG.debug("Failed to capture post-run screenshot", exc_info=True)
- if not dispatch_to_worker and not ctx.copilot_total_timeout_exceeded:
- await _capture_registered_artifact_evidence(
- ctx,
- run_id=workflow_run.workflow_run_id,
- organization_id=ctx.organization_id,
- downloaded_artifact_ids=_collect_downloaded_artifact_ids(block_outputs_by_label),
- )
+ if (
+ not dispatch_to_worker
+ and run_session_id
+ and _copilot_block_authoring_policy(ctx) == BlockAuthoringPolicy.CODE_ONLY_BROWSER
+ and not ctx.copilot_total_timeout_exceeded
+ ):
+ # CDP capture against the run session: worker-owned for dispatched runs, so skip it.
+ _pin_pre_run_page_reference(ctx, workflow_run.workflow_run_id)
+ await _capture_and_store_post_run_page(
+ ctx,
+ run_session_id=run_session_id,
+ run_id=workflow_run.workflow_run_id,
+ current_url=current_url,
+ )
- # Dispatched runs are worker-owned, so the API cannot CDP-capture the terminal page; read the
- # worker-persisted terminal HTML artifact instead and route it through the same post-run sink.
- if dispatch_to_worker and run_session_id and run_ok and not ctx.copilot_total_timeout_exceeded:
- await _capture_dispatched_terminal_page_evidence(
- ctx,
- run_id=workflow_run.workflow_run_id,
- organization_id=ctx.organization_id,
- current_url=current_url,
- )
+ if not dispatch_to_worker and not ctx.copilot_total_timeout_exceeded:
+ await _capture_registered_artifact_evidence(
+ ctx,
+ run_id=workflow_run.workflow_run_id,
+ organization_id=ctx.organization_id,
+ downloaded_artifact_ids=_collect_downloaded_artifact_ids(block_outputs_by_label),
+ )
- result_data: dict[str, Any] = {
- "workflow_run_id": workflow_run.workflow_run_id,
- "browser_session_id": run_session_id,
- "overall_status": final_status,
- "requested_block_labels": list(block_labels),
- "executed_block_labels": list(labels_to_execute),
- "frontier_start_label": frontier_start_label,
- "blocks": results,
- "current_url": current_url,
- "page_title": page_title,
- "action_trace_summary": action_trace_summary,
- }
- # Code-first only: the guidance steers toward an expect_download code block (ADR 0010), which
- # standard-mode v2 does not author.
- reached_download = (
- _derive_reached_download_from_block_outputs(block_outputs_by_label)
- if _copilot_block_authoring_policy(ctx) == BlockAuthoringPolicy.CODE_ONLY_BROWSER
- else None
- )
- if reached_download is not None:
- result_data["reached_download_target"] = reached_download.to_dict()
- result_data["reached_download_guidance"] = _reached_download_guidance_for(reached_download)
- if runtime_frontier_anchor_url is not None:
- result_data["runtime_frontier_anchor_url"] = runtime_frontier_anchor_url
- if runtime_frontier_starter_url_seeded:
- result_data["runtime_frontier_starter_url_seeded"] = True
- screenshot_b64 = _resolve_run_screenshot_b64(live_capture=screenshot_b64, results=results, run_ok=run_ok)
- if screenshot_b64 is not None:
- result_data["screenshot_base64"] = screenshot_b64
- if not run_ok and run and getattr(run, "failure_reason", None):
- result_data["failure_reason"] = run.failure_reason
+ # Dispatched runs are worker-owned, so the API cannot CDP-capture the terminal page; read the
+ # worker-persisted terminal HTML artifact instead and route it through the same post-run sink.
+ if dispatch_to_worker and run_session_id and run_ok and not ctx.copilot_total_timeout_exceeded:
+ await _capture_dispatched_terminal_page_evidence(
+ ctx,
+ run_id=workflow_run.workflow_run_id,
+ organization_id=ctx.organization_id,
+ current_url=current_url,
+ )
- output_identity_workflow = _registered_output_identity_workflow(
- dispatch_to_worker=dispatch_to_worker,
- dispatch_workflow=dispatch_workflow,
- runtime_workflow=runtime_workflow,
- )
+ result_data: dict[str, Any] = {
+ "workflow_run_id": workflow_run.workflow_run_id,
+ "browser_session_id": run_session_id,
+ "overall_status": final_status,
+ "requested_block_labels": list(block_labels),
+ "executed_block_labels": list(labels_to_execute),
+ "frontier_start_label": frontier_start_label,
+ "blocks": results,
+ "current_url": current_url,
+ "page_title": page_title,
+ "action_trace_summary": action_trace_summary,
+ }
+ # Code-first only: the guidance steers toward an expect_download code block (ADR 0010), which
+ # standard-mode v2 does not author.
+ reached_download = (
+ _derive_reached_download_from_block_outputs(block_outputs_by_label)
+ if _copilot_block_authoring_policy(ctx) == BlockAuthoringPolicy.CODE_ONLY_BROWSER
+ else None
+ )
+ if reached_download is not None:
+ result_data["reached_download_target"] = reached_download.to_dict()
+ result_data["reached_download_guidance"] = _reached_download_guidance_for(reached_download)
+ if runtime_frontier_anchor_url is not None:
+ result_data["runtime_frontier_anchor_url"] = runtime_frontier_anchor_url
+ if runtime_frontier_starter_url_seeded:
+ result_data["runtime_frontier_starter_url_seeded"] = True
+ screenshot_b64 = _resolve_run_screenshot_b64(live_capture=screenshot_b64, results=results, run_ok=run_ok)
+ if screenshot_b64 is not None:
+ result_data["screenshot_base64"] = screenshot_b64
+ if not run_ok and run and getattr(run, "failure_reason", None):
+ result_data["failure_reason"] = run.failure_reason
+
+ output_identity_workflow = _registered_output_identity_workflow(
+ dispatch_to_worker=dispatch_to_worker,
+ dispatch_workflow=dispatch_workflow,
+ runtime_workflow=runtime_workflow,
+ )
- registered_outputs_by_label = await _attach_registered_output_parameter_values(
- workflow_run_id=workflow_run.workflow_run_id,
- workflow=runtime_workflow,
- output_identity_workflow=output_identity_workflow,
- data=result_data,
- persisted_output_parameters=all_output_params,
- )
- for label, output in registered_outputs_by_label.items():
- if isinstance(output, dict) and output:
- block_outputs_by_label[label] = output
-
- # Update verified prefix state ONLY on a fully-successful run. A failed
- # suffix run leaves the browser in post-failure state, so we must not
- # trust blocks that individually succeeded inside it.
- if run_ok and all(r.get("status") == "completed" for r in results):
- for label, output in block_outputs_by_label.items():
- ctx.verified_block_outputs[label] = output
- ctx.verified_terminal_block_outputs = dict(block_outputs_by_label)
- existing_prefix = list(getattr(ctx, "verified_prefix_labels", []) or [])
- existing_set = set(existing_prefix)
- for label in labels_to_execute:
- if label not in existing_set:
- existing_prefix.append(label)
- existing_set.add(label)
- ctx.verified_prefix_labels = existing_prefix
- verified_current_url = _valid_runtime_anchor_url(current_url)
- if verified_current_url is not None:
- ctx.verified_prefix_current_url = verified_current_url
-
- return build_run_blocks_response(run_ok, result_data)
+ registered_outputs_by_label = await _attach_registered_output_parameter_values(
+ workflow_run_id=workflow_run.workflow_run_id,
+ workflow=runtime_workflow,
+ output_identity_workflow=output_identity_workflow,
+ data=result_data,
+ persisted_output_parameters=all_output_params,
+ )
+ for label, output in registered_outputs_by_label.items():
+ if isinstance(output, dict) and output:
+ block_outputs_by_label[label] = output
+
+ # Update verified prefix state ONLY on a fully-successful run. A failed
+ # suffix run leaves the browser in post-failure state, so we must not
+ # trust blocks that individually succeeded inside it.
+ if run_ok and all(r.get("status") == "completed" for r in results):
+ for label, output in block_outputs_by_label.items():
+ ctx.verified_block_outputs[label] = output
+ ctx.verified_terminal_block_outputs = dict(block_outputs_by_label)
+ existing_prefix = list(getattr(ctx, "verified_prefix_labels", []) or [])
+ existing_set = set(existing_prefix)
+ for label in labels_to_execute:
+ if label not in existing_set:
+ existing_prefix.append(label)
+ existing_set.add(label)
+ ctx.verified_prefix_labels = existing_prefix
+ verified_current_url = _valid_runtime_anchor_url(current_url)
+ if verified_current_url is not None:
+ ctx.verified_prefix_current_url = verified_current_url
+
+ return build_run_blocks_response(run_ok, result_data)
+ finally:
+ if active_run_association is not None:
+ try:
+ await clear_active_run_session(
+ organization_id=active_run_association.organization_id,
+ debug_browser_session_id=active_run_association.debug_browser_session_id,
+ generation=active_run_association.generation,
+ )
+ except Exception:
+ LOG.warning(
+ "Failed to clear active Copilot run session",
+ organization_id=active_run_association.organization_id,
+ workflow_run_id=active_run_association.workflow_run_id,
+ debug_browser_session_id=active_run_association.debug_browser_session_id,
+ generation=active_run_association.generation,
+ exc_info=True,
+ )
async def _get_run_results(params: dict[str, Any], ctx: AgentContext) -> dict[str, Any]:
diff --git a/skyvern/forge/sdk/routes/browser_sessions.py b/skyvern/forge/sdk/routes/browser_sessions.py
index 9b8edc96a..4b37a0f05 100644
--- a/skyvern/forge/sdk/routes/browser_sessions.py
+++ b/skyvern/forge/sdk/routes/browser_sessions.py
@@ -201,6 +201,7 @@ async def create_browser_session(
browser_session = await app.PERSISTENT_SESSIONS_MANAGER.create_session(
organization_id=current_org.organization_id,
+ url=browser_session_request.url,
timeout_minutes=browser_session_request.timeout,
proxy_location=proxy_location,
proxy_session_id=proxy_session_id,
diff --git a/skyvern/forge/sdk/routes/debug_sessions.py b/skyvern/forge/sdk/routes/debug_sessions.py
index a4210863b..436d4fbcd 100644
--- a/skyvern/forge/sdk/routes/debug_sessions.py
+++ b/skyvern/forge/sdk/routes/debug_sessions.py
@@ -9,17 +9,20 @@ from fastapi import Depends, HTTPException, Query
from skyvern.config import settings
from skyvern.exceptions import BrowserSessionNotRenewable
from skyvern.forge import app
+from skyvern.forge.sdk.copilot.active_run_session import get_active_run_session
from skyvern.forge.sdk.db.exceptions import NotFoundError
from skyvern.forge.sdk.routes.routers import base_router
from skyvern.forge.sdk.schemas.debug_sessions import (
DebugLoginBlockCompatibility,
DebugSession,
DebugSessionRuns,
+ DebugSessionViewerState,
)
from skyvern.forge.sdk.schemas.organizations import Organization
from skyvern.forge.sdk.schemas.persistent_browser_sessions import PersistentBrowserSession
from skyvern.forge.sdk.services import org_auth_service
from skyvern.forge.sdk.workflow.models.block import LoginBlock
+from skyvern.forge.sdk.workflow.models.workflow import WorkflowRunStatus
from skyvern.forge.sdk.workflow.service import (
DEBUG_SESSION_PROFILE_REASON_DIFFERENT,
DEBUG_SESSION_PROFILE_REASON_NO_PROFILE,
@@ -59,6 +62,66 @@ async def _hydrate_pbs_browser_profile_id(
return debug_session
+@base_router.get(
+ "/debug-session/{workflow_permanent_id}/viewer-state",
+ include_in_schema=False,
+)
+async def get_debug_session_viewer_state(
+ workflow_permanent_id: str,
+ current_org: Organization = Depends(org_auth_service.get_current_org),
+ current_user_id: str = Depends(org_auth_service.get_current_user_id),
+) -> DebugSessionViewerState:
+ """Return the active run viewer target without creating or renewing a debug session."""
+ debug_session = await app.DATABASE.debug.get_debug_session(
+ organization_id=current_org.organization_id,
+ user_id=current_user_id,
+ workflow_permanent_id=workflow_permanent_id,
+ )
+ if debug_session is None:
+ return DebugSessionViewerState()
+
+ try:
+ association = await get_active_run_session(
+ organization_id=current_org.organization_id,
+ debug_browser_session_id=debug_session.browser_session_id,
+ )
+ except Exception:
+ LOG.warning(
+ "Failed to read active Copilot run session",
+ organization_id=current_org.organization_id,
+ workflow_permanent_id=workflow_permanent_id,
+ debug_browser_session_id=debug_session.browser_session_id,
+ exc_info=True,
+ )
+ return DebugSessionViewerState()
+
+ if (
+ association is None
+ or association.organization_id != current_org.organization_id
+ or association.workflow_permanent_id != workflow_permanent_id
+ or association.debug_browser_session_id != debug_session.browser_session_id
+ ):
+ return DebugSessionViewerState()
+
+ workflow_run = await app.DATABASE.workflow_runs.get_workflow_run(
+ workflow_run_id=association.workflow_run_id,
+ organization_id=current_org.organization_id,
+ )
+ try:
+ run_is_final = workflow_run is not None and WorkflowRunStatus(workflow_run.status).is_final()
+ except ValueError:
+ return DebugSessionViewerState()
+ if (
+ workflow_run is None
+ or workflow_run.workflow_permanent_id != workflow_permanent_id
+ or workflow_run.browser_session_id != association.run_browser_session_id
+ or run_is_final
+ ):
+ return DebugSessionViewerState()
+
+ return DebugSessionViewerState(active_run_session_id=association.run_browser_session_id)
+
+
@base_router.get(
"/debug-session/{workflow_permanent_id}",
include_in_schema=False,
diff --git a/skyvern/forge/sdk/schemas/debug_sessions.py b/skyvern/forge/sdk/schemas/debug_sessions.py
index 2a92384e9..5a381b686 100644
--- a/skyvern/forge/sdk/schemas/debug_sessions.py
+++ b/skyvern/forge/sdk/schemas/debug_sessions.py
@@ -61,6 +61,10 @@ class DebugSessionRuns(BaseModel):
runs: list[DebugSessionRun]
+class DebugSessionViewerState(BaseModel):
+ active_run_session_id: str | None = None
+
+
# Backend-authoritative verdict for a single LoginBlock in a debug session.
# The FE pre-check works off a bounded credentials window; this endpoint
# resolves the credential through the org-scoped lookup the run path uses
diff --git a/skyvern/schemas/browser_sessions.py b/skyvern/schemas/browser_sessions.py
index fa0828f43..27d11849d 100644
--- a/skyvern/schemas/browser_sessions.py
+++ b/skyvern/schemas/browser_sessions.py
@@ -8,9 +8,22 @@ from skyvern.schemas.docs.doc_strings import PROXY_LOCATION_DOC_STRING
from skyvern.schemas.proxy_pinning import validate_proxy_session_id
from skyvern.schemas.runs import GeoTarget, ProxyLocationInput
from skyvern.services.browser_recording.types import RecordingDraftStep
+from skyvern.utils.url_validators import validate_url
class CreateBrowserSessionRequest(BaseModel):
+ url: str | None = Field(
+ default=None,
+ description="Optional URL to open when the standalone browser session starts.",
+ )
+
+ @field_validator("url")
+ @classmethod
+ def validate_start_url(cls, value: str | None) -> str | None:
+ if not value:
+ return value
+ return validate_url(value)
+
timeout: int | None = Field(
default=DEFAULT_TIMEOUT,
description=f"Timeout in minutes for the session. Timeout is applied after the session is started. Must be at least {MIN_TIMEOUT}; values above {MAX_TIMEOUT} are capped at {MAX_TIMEOUT}. Defaults to {DEFAULT_TIMEOUT}.",
diff --git a/tests/unit/forge/sdk/copilot/test_active_run_session.py b/tests/unit/forge/sdk/copilot/test_active_run_session.py
new file mode 100644
index 000000000..0f63189fb
--- /dev/null
+++ b/tests/unit/forge/sdk/copilot/test_active_run_session.py
@@ -0,0 +1,167 @@
+import asyncio
+from datetime import datetime, timedelta, timezone
+from types import SimpleNamespace
+from unittest.mock import patch
+
+import pytest
+
+from skyvern.forge.sdk.cache.local import LocalCache
+from skyvern.forge.sdk.copilot import active_run_session as active_run_session_mod
+from skyvern.forge.sdk.copilot.active_run_session import (
+ ActiveRunSessionAssociation,
+ active_run_session_cache_key,
+ clear_active_run_session,
+ get_active_run_session,
+ publish_active_run_session,
+)
+
+
+def cache() -> LocalCache:
+ return LocalCache()
+
+
+async def test_publish_and_get_preserve_typed_identity_and_expiry(cache: LocalCache) -> None:
+ with patch.object(active_run_session_mod, "app", SimpleNamespace(CACHE=cache)):
+ published = await publish_active_run_session(
+ organization_id="org_1",
+ workflow_permanent_id="wpid_1",
+ debug_browser_session_id="pbs_debug",
+ run_browser_session_id="pbs_run",
+ workflow_run_id="wr_1",
+ turn_id="turn_1",
+ )
+ loaded = await get_active_run_session(
+ organization_id="org_1",
+ debug_browser_session_id="pbs_debug",
+ )
+
+ assert loaded == published
+ assert published.expires_at > datetime.now(timezone.utc)
+ assert published.generation
+
+
+async def test_get_rejects_malformed_and_expired_records(cache: LocalCache) -> None:
+ key = active_run_session_cache_key("org_1", "pbs_debug")
+ expired = ActiveRunSessionAssociation(
+ organization_id="org_1",
+ workflow_permanent_id="wpid_1",
+ debug_browser_session_id="pbs_debug",
+ run_browser_session_id="pbs_run",
+ workflow_run_id="wr_1",
+ turn_id="turn_1",
+ generation="old",
+ expires_at=datetime.now(timezone.utc) - timedelta(seconds=1),
+ )
+ with patch.object(active_run_session_mod, "app", SimpleNamespace(CACHE=cache)):
+ await cache.set(key, expired.model_dump_json())
+ assert (
+ await get_active_run_session(
+ organization_id="org_1",
+ debug_browser_session_id="pbs_debug",
+ )
+ is None
+ )
+ await cache.set(key, "{not-json")
+ assert (
+ await get_active_run_session(
+ organization_id="org_1",
+ debug_browser_session_id="pbs_debug",
+ )
+ is None
+ )
+
+
+async def test_older_generation_cannot_clear_successor(cache: LocalCache) -> None:
+ with patch.object(active_run_session_mod, "app", SimpleNamespace(CACHE=cache)):
+ first = await publish_active_run_session(
+ organization_id="org_1",
+ workflow_permanent_id="wpid_1",
+ debug_browser_session_id="pbs_debug",
+ run_browser_session_id="pbs_run_1",
+ workflow_run_id="wr_1",
+ turn_id="turn_1",
+ )
+ second = await publish_active_run_session(
+ organization_id="org_1",
+ workflow_permanent_id="wpid_1",
+ debug_browser_session_id="pbs_debug",
+ run_browser_session_id="pbs_run_2",
+ workflow_run_id="wr_2",
+ turn_id="turn_2",
+ )
+ cleared = await clear_active_run_session(
+ organization_id="org_1",
+ debug_browser_session_id="pbs_debug",
+ generation=first.generation,
+ )
+ loaded = await get_active_run_session(
+ organization_id="org_1",
+ debug_browser_session_id="pbs_debug",
+ )
+
+ assert cleared is False
+ assert loaded == second
+
+
+async def test_matching_generation_clears(cache: LocalCache) -> None:
+ with patch.object(active_run_session_mod, "app", SimpleNamespace(CACHE=cache)):
+ published = await publish_active_run_session(
+ organization_id="org_1",
+ workflow_permanent_id="wpid_1",
+ debug_browser_session_id="pbs_debug",
+ run_browser_session_id="pbs_run",
+ workflow_run_id="wr_1",
+ turn_id="turn_1",
+ )
+ assert await clear_active_run_session(
+ organization_id="org_1",
+ debug_browser_session_id="pbs_debug",
+ generation=published.generation,
+ )
+ assert (
+ await get_active_run_session(
+ organization_id="org_1",
+ debug_browser_session_id="pbs_debug",
+ )
+ is None
+ )
+
+
+async def test_overlapping_successor_publish_survives_older_clear(cache: LocalCache) -> None:
+ with patch.object(active_run_session_mod, "app", SimpleNamespace(CACHE=cache)):
+ first = await publish_active_run_session(
+ organization_id="org_1",
+ workflow_permanent_id="wpid_1",
+ debug_browser_session_id="pbs_debug",
+ run_browser_session_id="pbs_run_1",
+ workflow_run_id="wr_1",
+ turn_id="turn_1",
+ )
+ _, second = await asyncio.gather(
+ clear_active_run_session(
+ organization_id="org_1",
+ debug_browser_session_id="pbs_debug",
+ generation=first.generation,
+ ),
+ publish_active_run_session(
+ organization_id="org_1",
+ workflow_permanent_id="wpid_1",
+ debug_browser_session_id="pbs_debug",
+ run_browser_session_id="pbs_run_2",
+ workflow_run_id="wr_2",
+ turn_id="turn_2",
+ ),
+ )
+ loaded = await get_active_run_session(
+ organization_id="org_1",
+ debug_browser_session_id="pbs_debug",
+ )
+
+ assert loaded == second
+ assert active_run_session_mod._LOCAL_LOCKS == {}
diff --git a/tests/unit/forge/sdk/routes/test_debug_sessions.py b/tests/unit/forge/sdk/routes/test_debug_sessions.py
index 7e643f826..1aba37f1d 100644
--- a/tests/unit/forge/sdk/routes/test_debug_sessions.py
+++ b/tests/unit/forge/sdk/routes/test_debug_sessions.py
@@ -4,6 +4,7 @@ from unittest.mock import AsyncMock, MagicMock, patch
import pytest
from skyvern.config import settings
+from skyvern.forge.sdk.copilot.active_run_session import ActiveRunSessionAssociation
from skyvern.forge.sdk.routes import debug_sessions as debug_sessions_mod
from skyvern.schemas.runs import ProxyLocation
@@ -187,6 +188,125 @@ async def test_new_debug_session_response_carries_pbs_browser_profile_id() -> No
assert created_debug_session.pbs_browser_profile_id == "bp_seeded"
+# ─── read-only viewer-state endpoint ───────────────────────────────────────
+
+
+def _active_association() -> ActiveRunSessionAssociation:
+ from datetime import datetime, timedelta, timezone
+
+ return ActiveRunSessionAssociation(
+ organization_id="org_x",
+ workflow_permanent_id="wpid_x",
+ debug_browser_session_id="pbs_debug",
+ run_browser_session_id="pbs_run",
+ workflow_run_id="wr_x",
+ turn_id="turn_x",
+ generation="generation_x",
+ expires_at=datetime.now(timezone.utc) + timedelta(minutes=5),
+ )
+
+
+def _viewer_state_app(*, run_status: str = "running") -> MagicMock:
+ app_mock = MagicMock()
+ app_mock.DATABASE.debug.get_debug_session = AsyncMock(
+ return_value=SimpleNamespace(browser_session_id="pbs_debug"),
+ )
+ app_mock.DATABASE.workflow_runs.get_workflow_run = AsyncMock(
+ return_value=SimpleNamespace(
+ workflow_permanent_id="wpid_x",
+ browser_session_id="pbs_run",
+ status=run_status,
+ ),
+ )
+ app_mock.PERSISTENT_SESSIONS_MANAGER.renew_or_close_session = AsyncMock()
+ return app_mock
+
+
+async def test_viewer_state_returns_matching_nonterminal_run_without_renewal() -> None:
+ app_mock = _viewer_state_app()
+ with (
+ patch.object(debug_sessions_mod, "app", app_mock),
+ patch.object(
+ debug_sessions_mod,
+ "get_active_run_session",
+ AsyncMock(return_value=_active_association()),
+ ),
+ ):
+ result = await debug_sessions_mod.get_debug_session_viewer_state(
+ "wpid_x",
+ current_org=SimpleNamespace(organization_id="org_x"),
+ current_user_id="user_x",
+ )
+
+ assert result.active_run_session_id == "pbs_run"
+ app_mock.PERSISTENT_SESSIONS_MANAGER.renew_or_close_session.assert_not_awaited()
+
+
+ ("association_update", "run_update"),
+ [
+ ({"organization_id": "org_other"}, {}),
+ ({"workflow_permanent_id": "wpid_other"}, {}),
+ ({"debug_browser_session_id": "pbs_other"}, {}),
+ ({"run_browser_session_id": "pbs_other"}, {}),
+ ({}, {"workflow_permanent_id": "wpid_other"}),
+ ({}, {"browser_session_id": "pbs_other"}),
+ ({}, {"status": "completed"}),
+ ({}, {"status": "malformed"}),
+ ],
+)
+async def test_viewer_state_rejects_mismatched_or_terminal_state(
+ association_update: dict[str, str],
+ run_update: dict[str, str],
+) -> None:
+ app_mock = _viewer_state_app()
+ workflow_run = app_mock.DATABASE.workflow_runs.get_workflow_run.return_value
+ for field, value in run_update.items():
+ setattr(workflow_run, field, value)
+ association = _active_association().model_copy(update=association_update)
+
+ with (
+ patch.object(debug_sessions_mod, "app", app_mock),
+ patch.object(
+ debug_sessions_mod,
+ "get_active_run_session",
+ AsyncMock(return_value=association),
+ ),
+ ):
+ result = await debug_sessions_mod.get_debug_session_viewer_state(
+ "wpid_x",
+ current_org=SimpleNamespace(organization_id="org_x"),
+ current_user_id="user_x",
+ )
+
+ assert result.active_run_session_id is None
+
+
+async def test_viewer_state_returns_null_for_missing_or_unreadable_association() -> None:
+ for association_result in (None, RuntimeError("cache unavailable")):
+ app_mock = _viewer_state_app()
+ lookup = (
+ AsyncMock(side_effect=association_result)
+ if isinstance(association_result, Exception)
+ else AsyncMock(return_value=association_result)
+ )
+ with (
+ patch.object(debug_sessions_mod, "app", app_mock),
+ patch.object(debug_sessions_mod, "get_active_run_session", lookup),
+ ):
+ result = await debug_sessions_mod.get_debug_session_viewer_state(
+ "wpid_x",
+ current_org=SimpleNamespace(organization_id="org_x"),
+ current_user_id="user_x",
+ )
+
+ assert result.active_run_session_id is None
+ app_mock.DATABASE.workflow_runs.get_workflow_run.assert_not_awaited()
+
+
# ─── login-block-compatibility endpoint ────────────────────────────────────
diff --git a/tests/unit/test_browser_session_profile_export_gate.py b/tests/unit/test_browser_session_profile_export_gate.py
index e84a4679f..cbff8106f 100644
--- a/tests/unit/test_browser_session_profile_export_gate.py
+++ b/tests/unit/test_browser_session_profile_export_gate.py
@@ -1,5 +1,11 @@
from datetime import datetime
+from types import SimpleNamespace
+from unittest.mock import AsyncMock, MagicMock, patch
+import pytest
+
+from skyvern.exceptions import SkyvernHTTPException
+from skyvern.forge.sdk.routes import browser_sessions as browser_sessions_mod
from skyvern.forge.sdk.schemas.persistent_browser_sessions import (
PersistentBrowserSession,
export_profile_storage_id,
@@ -38,6 +44,53 @@ def test_create_request_defaults_to_opt_out() -> None:
assert CreateBrowserSessionRequest().generate_browser_profile is False
+def test_create_request_accepts_start_url() -> None:
+ request = CreateBrowserSessionRequest(url="https://example.com/path", generate_browser_profile=True)
+
+ assert request.url == "https://example.com/path"
+
+
+def test_create_request_rejects_invalid_start_url() -> None:
+ with pytest.raises(SkyvernHTTPException):
+ CreateBrowserSessionRequest(url="ftp://example.com")
+
+
+async def test_create_browser_session_passes_start_url_to_session_manager() -> None:
+ created_session = SimpleNamespace(persistent_browser_session_id="pbs_1")
+ response = SimpleNamespace(browser_session_id="pbs_1")
+ app_mock = MagicMock()
+ app_mock.PERSISTENT_SESSIONS_MANAGER.create_session = AsyncMock(return_value=created_session)
+ from_browser_session = AsyncMock(return_value=response)
+
+ with (
+ patch.object(browser_sessions_mod, "app", app_mock),
+ patch.object(browser_sessions_mod.BrowserSessionResponse, "from_browser_session", from_browser_session),
+ ):
+ result = await browser_sessions_mod.create_browser_session(
+ CreateBrowserSessionRequest(
+ url="https://example.com/login",
+ timeout=120,
+ generate_browser_profile=True,
+ ),
+ current_org=SimpleNamespace(organization_id="org_1"),
+ )
+
+ assert result is response
+ app_mock.PERSISTENT_SESSIONS_MANAGER.create_session.assert_awaited_once_with(
+ organization_id="org_1",
+ url="https://example.com/login",
+ timeout_minutes=120,
+ proxy_location=None,
+ proxy_session_id=None,
+ extensions=None,
+ browser_type=None,
+ browser_profile_id=None,
+ generate_browser_profile=True,
+ )
+ from_browser_session.assert_awaited_once_with(created_session)
+
+
def test_update_request_carries_flag() -> None:
assert UpdateBrowserSessionRequest(generate_browser_profile=True).generate_browser_profile is True
assert UpdateBrowserSessionRequest(generate_browser_profile=False).generate_browser_profile is False
diff --git a/tests/unit/test_copilot_run_output_content_gate.py b/tests/unit/test_copilot_run_output_content_gate.py
index 81698059e..0646512f4 100644
--- a/tests/unit/test_copilot_run_output_content_gate.py
+++ b/tests/unit/test_copilot_run_output_content_gate.py
@@ -973,6 +973,64 @@ async def test_inline_registered_output_identity_uses_runtime_override_when_pers
assert [item["output_parameter_id"] for item in data["registered_output_parameter_values"]] == ["op_runtime"]
+async def test_inline_prior_draft_registered_output_identity_uses_snapshot_ids(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ async def fake_get_workflow_run_output_parameters(*, workflow_run_id: str) -> list[SimpleNamespace]:
+ assert workflow_run_id == "wr_inline_snapshot"
+ return [
+ SimpleNamespace(
+ workflow_run_id="wr_inline_snapshot",
+ output_parameter_id="op_snapshot",
+ value={"record_number": "1234567890"},
+ )
+ ]
+
+ monkeypatch.setattr(
+ run_execution.app.DATABASE,
+ "workflow_runs",
+ SimpleNamespace(get_workflow_run_output_parameters=fake_get_workflow_run_output_parameters),
+ )
+
+ def workflow(output_parameter_id: str) -> SimpleNamespace:
+ return SimpleNamespace(
+ organization_id="o",
+ workflow_definition=SimpleNamespace(
+ blocks=[
+ SimpleNamespace(
+ label="extract_record",
+ block_type="CODE",
+ output_parameter=SimpleNamespace(
+ output_parameter_id=output_parameter_id,
+ key="extract_record_output",
+ ),
+ )
+ ]
+ ),
+ )
+
+ runtime_workflow = workflow("op_runtime")
+ snapshot_workflow = workflow("op_snapshot")
+ output_identity_workflow = run_execution._registered_output_identity_workflow(
+ dispatch_to_worker=False,
+ dispatch_workflow=snapshot_workflow, # type: ignore[arg-type]
+ runtime_workflow=runtime_workflow, # type: ignore[arg-type]
+ )
+ data: dict[str, Any] = {"workflow_run_id": "wr_inline_snapshot", "blocks": []}
+
+ by_label = await _attach_registered_output_parameter_values(
+ workflow_run_id="wr_inline_snapshot",
+ workflow=runtime_workflow, # type: ignore[arg-type]
+ output_identity_workflow=output_identity_workflow,
+ data=data,
+ )
+
+ assert output_identity_workflow is snapshot_workflow
+ assert by_label == {"extract_record": {"extract_record_output": {"record_number": "1234567890"}}}
+ assert [item["output_parameter_id"] for item in data["registered_output_parameter_values"]] == ["op_snapshot"]
+
+
def test_satisfied_completion_prevents_empty_output_suspicious_success() -> None:
result = _empty_extraction_run_result()
ctx = _ctx(result["data"]["blocks"])