Automate browser based workflows with AI
Python aiapiautomationbrowserbrowser-automationcomputergptllmplaywrightpowerautomatepuppeteerpythonrpaseleniumvisionworkflow
[HOLD] Prepare disabled curator production wiring (SKY-18657) (#8969)
Andrew Neilson926f4725e6c6
diff --git a/skyvern-frontend/src/routes/workflows/copilot/WorkflowCopilotChat.demonstration.test.tsx b/skyvern-frontend/src/routes/workflows/copilot/WorkflowCopilotChat.demonstration.test.tsxindex a237c35d9..37d14d464 100644--- a/skyvern-frontend/src/routes/workflows/copilot/WorkflowCopilotChat.demonstration.test.tsx+++ b/skyvern-frontend/src/routes/workflows/copilot/WorkflowCopilotChat.demonstration.test.tsx@@ -186,7 +186,7 @@ async function renderChat(const queryClient = new QueryClient({defaultOptions: { queries: { retry: false } },});- render(+ const { rerender } = render(<QueryClientProvider client={queryClient}><WorkflowCopilotChat docked={false} {...props} /></QueryClientProvider>,@@ -196,6 +196,12 @@ async function renderChat(screen.getByRole("group", { name: "Copilot message composer" }),).toBeTruthy(),);+ return (next: ComponentProps<typeof WorkflowCopilotChat>) =>+ rerender(+ <QueryClientProvider client={queryClient}>+ <WorkflowCopilotChat docked={false} {...next} />+ </QueryClientProvider>,+ );}async function startDemonstration({@@ -770,6 +776,111 @@ describe("WorkflowCopilotChat demonstration", () => {expect(screen.queryByRole("button", { name: "Resume" })).toBeNull();});+ it("keeps captured actions and says so when the browser restarts mid-demonstration", async () => {+ const rerenderChat = await renderChat({+ liveBrowserSessionId: "browser-1",+ });+ const call = await startDemonstration();+ act(() => {+ call.onMessage({+ type: "demonstration_action",+ seq: 1,+ label: "Open form",+ tool_name: "click",+ });+ });++ rerenderChat({ liveBrowserSessionId: "browser-2" });++ expect(+ await screen.findByText(+ /The browser restarted, so the demonstration was interrupted/,+ ),+ ).toBeTruthy();+ expect(sansApiPost).toHaveBeenCalledWith(+ "/workflow/copilot/demonstration/control",+ {+ demonstration_id: "demonstration-1",+ action: "stop",+ stop_reason: "browser_gone",+ },+ );+ await waitFor(() =>+ expect(+ (+ screen.getByRole("button", {+ name: "Build the workflow",+ }) as HTMLButtonElement+ ).disabled,+ ).toBe(false),+ );+ expect(screen.queryByRole("button", { name: "Resume" })).toBeNull();+ expect(+ within(+ screen.getByRole("group", { name: "Your demonstration" }),+ ).getAllByRole("listitem"),+ ).toHaveLength(1);+ });++ it("pauses on a stream gap and keeps the recording through a gap mid-resume or mid-build", async () => {+ const rerenderChat = await renderChat({+ liveBrowserSessionId: "browser-1",+ });+ const call = await startDemonstration();+ act(() => {+ call.onMessage({+ type: "demonstration_action",+ seq: 1,+ label: "Open form",+ tool_name: "click",+ });+ });+ const recordCalls = () =>+ streamCalls.filter((item) => item.path.endsWith("/record"));++ rerenderChat({ liveBrowserSessionId: null });+ rerenderChat({ liveBrowserSessionId: "browser-1" });+ fireEvent.click(await screen.findByRole("button", { name: "Resume" }));+ await waitFor(() => expect(recordCalls()).toHaveLength(2));+ expect(recordCalls()[1]?.body.demonstration_id).toBe("demonstration-1");+ const resumeStream = postStreaming.mock.calls[+ postStreaming.mock.calls.length - 1+ ] as unknown[];++ rerenderChat({ liveBrowserSessionId: null });+ expect((resumeStream[3] as { signal: AbortSignal }).signal.aborted).toBe(+ true,+ );+ rerenderChat({ liveBrowserSessionId: "browser-1" });+ expect(+ (+ (await screen.findByRole("button", {+ name: "Resume",+ })) as HTMLButtonElement+ ).disabled,+ ).toBe(false);+ expect(screen.queryByText(/The browser restarted/)).toBeNull();++ let rejectSend: ((reason: Error) => void) | undefined;+ postStreaming.mockImplementationOnce((path, body, onMessage) => {+ streamCalls.push({ path, body, onMessage });+ return new Promise((_, reject) => {+ rejectSend = reject;+ });+ });+ fireEvent.click(screen.getByRole("button", { name: "Build the workflow" }));+ await waitFor(() => expect(rejectSend).toBeDefined());+ rerenderChat({ liveBrowserSessionId: null });+ rerenderChat({ liveBrowserSessionId: "browser-1" });+ act(() => {+ rejectSend?.(new Error("send failed"));+ });++ expect(+ await screen.findByText("Demonstration paused · 1 action"),+ ).toBeTruthy();+ });+it.each(["stopped", "stopping"] as const)("restores a %s recording and renders history demonstrations",async (status) => {diff --git a/skyvern-frontend/src/routes/workflows/copilot/WorkflowCopilotChat.tsx b/skyvern-frontend/src/routes/workflows/copilot/WorkflowCopilotChat.tsxindex 26199d769..26c8757a9 100644--- a/skyvern-frontend/src/routes/workflows/copilot/WorkflowCopilotChat.tsx+++ b/skyvern-frontend/src/routes/workflows/copilot/WorkflowCopilotChat.tsx@@ -12300,7 +12300,9 @@ export function WorkflowCopilotChat({<span>{demonstrationRecorder.phase === "recording"? "Demonstrating"- : "Demonstration paused"}+ : demonstrationRecorder.browserRestarted+ ? "Demonstration interrupted"+ : "Demonstration paused"}{` · ${demonstrationRecorder.actionCount} ${demonstrationRecorder.actionCount === 1? "action"@@ -12326,7 +12328,9 @@ export function WorkflowCopilotChat({</button>{demonstrationRecorder.phase === "stopped" &&demonstrationRecorder.demonstrationId &&- !demonstrationRecorder.limitReached ? (+ liveBrowserSessionId &&+ !demonstrationRecorder.limitReached &&+ !demonstrationRecorder.browserRestarted ? (<buttontype="button"disabled={demonstrationRecorder.busy}@@ -12345,6 +12349,18 @@ export function WorkflowCopilotChat({</div></div>) : null}+ {demonstrationRecorder.phase === "stopped" &&+ demonstrationRecorder.browserRestarted ? (+ <div className="border-b border-border px-3 py-1.5">+ <RunLifecycleLine+ content={+ demonstrationRecorder.actionCount > 0+ ? "The browser restarted, so the demonstration was interrupted. Build the workflow from the captured actions, or discard them to start over."+ : "The browser restarted, so the demonstration was interrupted. Discard it to start over."+ }+ />+ </div>+ ) : null}{demonstrationRecorder.hasSkippedSensitiveField ? (<div className="border-b border-border px-3 py-1.5"><RunLifecycleLine content="Sensitive field skipped — its value was not recorded." />diff --git a/skyvern-frontend/src/routes/workflows/copilot/useDemonstrationRecorder.ts b/skyvern-frontend/src/routes/workflows/copilot/useDemonstrationRecorder.tsindex 412e4e267..7d5b057df 100644--- a/skyvern-frontend/src/routes/workflows/copilot/useDemonstrationRecorder.ts+++ b/skyvern-frontend/src/routes/workflows/copilot/useDemonstrationRecorder.ts@@ -54,6 +54,7 @@ export function useDemonstrationRecorder({const [hasSkippedSensitiveField, setHasSkippedSensitiveField] =useState(false);const [limitReached, setLimitReached] = useState(false);+ const [browserRestarted, setBrowserRestarted] = useState(false);const busyRef = useRef(false);const streamControllerRef = useRef<AbortController | null>(null);const demonstrationIdRef = useRef<string | null>(null);@@ -63,6 +64,7 @@ export function useDemonstrationRecorder({onDoneRef.current = onDone;const onStartFailedRef = useRef(onStartFailed);onStartFailedRef.current = onStartFailed;+ const sessionRef = useRef({ workflowPermanentId, browserSessionId });const updateBusy = useCallback((next: boolean) => {busyRef.current = next;@@ -91,6 +93,7 @@ export function useDemonstrationRecorder({setCanFillCredentials(false);setHasSkippedSensitiveField(false);setLimitReached(false);+ setBrowserRestarted(false);updateBusy(false);insertionRef.current = undefined;}, [updateBusy, updateDemonstrationId, updatePhase]);@@ -393,6 +396,50 @@ export function useDemonstrationRecorder({}, [clear, sendControl, updateBusy]);useEffect(() => {+ const previous = sessionRef.current;+ const sameWorkflow = previous.workflowPermanentId === workflowPermanentId;+ // A stream readiness gap reports a null session, so only a different real session is a restart.+ sessionRef.current = {+ workflowPermanentId,+ browserSessionId:+ browserSessionId ?? (sameWorkflow ? previous.browserSessionId : null),+ };+ const id = demonstrationIdRef.current;+ const restarted =+ !!browserSessionId && browserSessionId !== previous.browserSessionId;+ // Done keeps the recording (phase idle, busy) until its send settles.+ if (sameWorkflow && id && phaseRef.current === "idle" && busyRef.current) {+ if (restarted) setBrowserRestarted(true);+ return;+ }+ if (sameWorkflow && id && phaseRef.current !== "idle") {+ // Early returns register no cleanup, and an aborted stream skips its busy reset once its ref is gone.+ const resuming =+ streamControllerRef.current !== null &&+ phaseRef.current !== "recording";+ streamControllerRef.current?.abort();+ streamControllerRef.current = null;+ if (resuming) updateBusy(false);+ setSensitiveField(null);+ if (!restarted) {+ updatePhase("stopped");+ return;+ }+ // The recording is bound to the old session: build or discard only.+ const wasRecording = phaseRef.current === "recording";+ setHasSkippedSensitiveField(false);+ setBrowserRestarted(true);+ updatePhase("stopped");+ if (wasRecording) {+ updateBusy(true);+ void sendControl({ action: "stop", stop_reason: "browser_gone" }, id)+ .catch(() => undefined)+ .finally(() => {+ if (demonstrationIdRef.current === id) updateBusy(false);+ });+ }+ return;+ }clear();if (!workflowPermanentId || !browserSessionId) return;const controller = new AbortController();@@ -445,6 +492,8 @@ export function useDemonstrationRecorder({browserSessionId,clear,credentialGetter,+ sendControl,+ updateBusy,updateDemonstrationId,updatePhase,workflowPermanentId,@@ -466,6 +515,7 @@ export function useDemonstrationRecorder({canFillCredentials,hasSkippedSensitiveField,limitReached,+ browserRestarted,busy,start,resume,diff --git a/skyvern-frontend/src/routes/workflows/copilot/workflowCopilotTypes.ts b/skyvern-frontend/src/routes/workflows/copilot/workflowCopilotTypes.tsindex 8a233d703..ceb39cd6f 100644--- a/skyvern-frontend/src/routes/workflows/copilot/workflowCopilotTypes.ts+++ b/skyvern-frontend/src/routes/workflows/copilot/workflowCopilotTypes.ts@@ -619,6 +619,7 @@ export interface WorkflowCopilotDemonstrationControlRequest {selector?: string | null;credential_id?: string | null;field?: "password" | "totp" | null;+ stop_reason?: "browser_gone" | null;}export interface WorkflowCopilotDemonstrationControlResult {diff --git a/skyvern/forge/sdk/copilot/demonstration_recorder.py b/skyvern/forge/sdk/copilot/demonstration_recorder.pyindex 8b729196c..fbc2eb77b 100644--- a/skyvern/forge/sdk/copilot/demonstration_recorder.py+++ b/skyvern/forge/sdk/copilot/demonstration_recorder.py@@ -426,7 +426,7 @@ async def append_demonstration_control(if request.action == "stop":if record.status == "recording":record.status = "stopping"- record.stop_reason = "stopped"+ record.stop_reason = request.stop_reason or "stopped"await cache.set(record_key, encode_demonstration_record(record), ex=DEMONSTRATION_TTL)return 0if request.action == "cancel":diff --git a/skyvern/forge/sdk/schemas/workflow_copilot.py b/skyvern/forge/sdk/schemas/workflow_copilot.pyindex 5c24df8f1..86e65ef90 100644--- a/skyvern/forge/sdk/schemas/workflow_copilot.py+++ b/skyvern/forge/sdk/schemas/workflow_copilot.py@@ -601,6 +601,8 @@ class WorkflowCopilotDemonstrationControlRequest(BaseModel):selector: str | None = Field(default=None, max_length=2000)credential_id: str | None = Field(default=None, max_length=128)field: Literal["password", "totp"] | None = None+ # A stop the user did not ask for, e.g. a browser restart, so replay reports the recording as interrupted.+ stop_reason: Literal["browser_gone"] | None = Noneclass WorkflowCopilotDemonstrationControlResult(BaseModel):diff --git a/tests/unit/test_copilot_demonstration.py b/tests/unit/test_copilot_demonstration.pyindex 923350eaa..ca440a4a7 100644--- a/tests/unit/test_copilot_demonstration.py+++ b/tests/unit/test_copilot_demonstration.py@@ -4,7 +4,7 @@ import asyncioimport jsonfrom datetime import UTC, datetime, timedeltafrom types import SimpleNamespace-from typing import Any, ClassVar+from typing import Any, ClassVar, Literalfrom unittest.mock import AsyncMock, MagicMockimport pytest@@ -803,7 +803,10 @@ async def test_record_claim_never_locks_the_browser_index_key_and_keeps_orgs_iso@pytest.mark.asyncio-async def test_stop_control_flushes_focused_typing_before_recorder_commits_stopped() -> None:[email protected](("stop_reason", "expected_reason"), [(None, "stopped"), ("browser_gone", "browser_gone")])+async def test_stop_control_flushes_focused_typing_before_recorder_commits_stopped(+ monkeypatch: pytest.MonkeyPatch, stop_reason: Literal["browser_gone"] | None, expected_reason: str+) -> None:cache = _SharedCache()record = DemonstrationRecord(workflow_permanent_id="wfp-1",@@ -820,11 +823,13 @@ async def test_stop_control_flushes_focused_typing_before_recorder_commits_stoppawait append_demonstration_control(cache, # type: ignore[arg-type]organization_id="org-1",- request=WorkflowCopilotDemonstrationControlRequest(demonstration_id="demo-1", action="stop"),+ request=WorkflowCopilotDemonstrationControlRequest(+ demonstration_id="demo-1", action="stop", stop_reason=stop_reason+ ),)stopping = await load_demonstration_record(cache, "org-1", "demo-1") # type: ignore[arg-type]- assert stopping is not None and stopping.status == "stopping" and stopping.stop_reason == "stopped"+ assert stopping is not None and stopping.status == "stopping" and stopping.stop_reason == expected_reasonpage = SimpleNamespace(url="https://example.test/form", is_closed=lambda: False)typed = TapEvent(page=page,@@ -856,10 +861,17 @@ async def test_stop_control_flushes_focused_typing_before_recorder_commits_stoppawait recorder._stop("disconnected")stopped = await load_demonstration_record(cache, "org-1", "demo-1") # type: ignore[arg-type]- assert stopped is not None and stopped.status == "stopped" and stopped.stop_reason == "stopped"+ assert stopped is not None and stopped.status == "stopped" and stopped.stop_reason == expected_reasonevent_key = demonstration_event_key("org-1", "demo-1", 1)assert json.loads(cache.store[event_key])["value"] == "last field value"assert cache.expirations[event_key] == recorder_module.DEMONSTRATION_TTL+ if stop_reason is not None:+ monkeypatch.setattr(app, "CACHE", cache)+ monkeypatch.setattr(replay_module, "resolve_raw_secret_safety_handler", AsyncMock(return_value=None))+ ctx = make_copilot_ctx(organization_id="org-1", workflow_permanent_id="wfp-1")+ ctx.demonstration_id = "demo-1"+ history = await replay_demonstration(ctx, SimpleNamespace(call_tool=AsyncMock(return_value={"ok": True}))) # type: ignore[arg-type]+ assert any("browser gone" in str(item.get("content")) for item in history)@pytest.mark.asyncio