Automate browser based workflows with AI
Python aiapiautomationbrowserbrowser-automationcomputergptllmplaywrightpowerautomatepuppeteerpythonrpaseleniumvisionworkflow
SKY-10143: keep the copilot chat live during the in-turn test (queue + cancel) (#6268)
Andrew Neilson60c295af1720
diff --git a/skyvern-frontend/src/routes/workflows/copilot/WorkflowCopilotChat.queue.test.tsx b/skyvern-frontend/src/routes/workflows/copilot/WorkflowCopilotChat.queue.test.tsxnew file mode 100644index 000000000..cfa94d7f2--- /dev/null+++ b/skyvern-frontend/src/routes/workflows/copilot/WorkflowCopilotChat.queue.test.tsx@@ -0,0 +1,270 @@+import {+ act,+ cleanup,+ fireEvent,+ render,+ screen,+ waitFor,+} from "@testing-library/react";+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";++import type { WorkflowCopilotStreamResponseUpdate } from "./workflowCopilotTypes";++// Capture every postStreaming call so a test can assert how many streams+// started and drive each one to a terminal frame on demand.+type StreamCall = {+ body: { message: string };+ onMessage: (payload: unknown) => boolean;+ resolve: () => void;+ reject: (error: unknown) => void;+};+const { streamCalls, postStreaming, cancelPost } = vi.hoisted(() => {+ const calls: StreamCall[] = [];+ const post = vi.fn().mockResolvedValue({});+ const streaming = vi.fn(+ (+ _path: string,+ body: { message: string },+ onMessage: (payload: unknown) => boolean,+ ) =>+ new Promise<void>((resolve, reject) => {+ calls.push({ body, onMessage, resolve, reject });+ }),+ );+ return { streamCalls: calls, postStreaming: streaming, cancelPost: post };+});++vi.mock("@/api/sse", () => ({+ getSseClient: vi.fn().mockResolvedValue({ postStreaming }),+}));++vi.mock("@/api/AxiosClient", () => ({+ getClient: vi.fn().mockResolvedValue({+ get: vi.fn().mockResolvedValue({+ data: {+ workflow_copilot_chat_id: null,+ chat_history: [],+ proposed_workflow: null,+ auto_accept: false,+ },+ }),+ post: cancelPost,+ }),+}));++vi.mock("@/hooks/useCredentialGetter", () => ({+ useCredentialGetter: () => null,+}));++vi.mock("@/components/ui/use-toast", () => ({ toast: vi.fn() }));++vi.mock("react-router-dom", async (importOriginal) => {+ const actual = await importOriginal<typeof import("react-router-dom")>();+ return {+ ...actual,+ useParams: () => ({+ workflowPermanentId: "wpid_1",+ workflowRunId: undefined,+ }),+ };+});++const saveData = {+ title: "Test WF",+ workflow: {+ workflow_id: "wf_1",+ workflow_permanent_id: "wpid_1",+ description: "",+ totp_verification_url: null,+ is_saved_task: false,+ status: "published",+ },+ settings: {+ proxyLocation: null,+ webhookCallbackUrl: null,+ persistBrowserSession: false,+ browserProfileId: null,+ model: null,+ maxScreenshotScrolls: null,+ extraHttpHeaders: null,+ runWith: "agent",+ scriptCacheKey: "",+ aiFallback: true,+ codeVersion: 2,+ runSequentially: false,+ sequentialKey: null,+ },+ parameters: [],+ blocks: [],+ workflowDefinitionVersion: 1,+};++vi.mock("@/store/WorkflowHasChangesStore", () => ({+ useWorkflowHasChangesStore: () => ({ getSaveData: () => saveData }),+}));++import { WorkflowCopilotChat } from "./WorkflowCopilotChat";++const terminalResponse = (+ message: string,+): WorkflowCopilotStreamResponseUpdate => ({+ type: "response",+ workflow_copilot_chat_id: "chat-1",+ message,+ updated_workflow: null,+ response_time: "2026-05-25T00:00:05Z",+ proposal_disposition: "no_proposal",+});++const turnStart = () => ({+ type: "turn_start" as const,+ turn_id: "turn-1",+ turn_index: 0,+ mode: "build",+ timestamp: "2026-05-25T00:00:00Z",+});++async function renderChat() {+ const view = render(<WorkflowCopilotChat />);+ // Let the mount-time chat-history fetch settle.+ await waitFor(() =>+ expect(screen.getByPlaceholderText(/Type your message/)).toBeTruthy(),+ );+ return view;+}++function textarea(): HTMLTextAreaElement {+ return screen.getByRole("textbox") as HTMLTextAreaElement;+}++async function submit(value: string) {+ fireEvent.change(textarea(), { target: { value } });+ await act(async () => {+ fireEvent.keyDown(textarea(), { key: "Enter" });+ });+}++// Drive the oldest pending stream to a clean terminal frame.+async function completeOldestStream(message: string) {+ const call = streamCalls.find((c) => c.body.message !== undefined);+ if (!call) throw new Error("no pending stream to complete");+ await act(async () => {+ call.onMessage(terminalResponse(message));+ call.resolve();+ });+}++beforeEach(() => {+ // jsdom has no layout engine.+ HTMLElement.prototype.scrollIntoView = vi.fn();+ streamCalls.length = 0;+ postStreaming.mockClear();+ cancelPost.mockClear();+});++afterEach(() => {+ cleanup();+});++describe("WorkflowCopilotChat — keep the chat live during a turn", () => {+ it("leaves the input enabled while a turn is in flight", async () => {+ await renderChat();+ await submit("build me a workflow");+ await waitFor(() => expect(postStreaming).toHaveBeenCalledTimes(1));++ expect(textarea().disabled).toBe(false);+ expect(screen.getByRole("button", { name: "Cancel run" })).toBeTruthy();+ });++ it("queues a second submit instead of starting a concurrent stream", async () => {+ await renderChat();+ await submit("first message");+ await waitFor(() => expect(postStreaming).toHaveBeenCalledTimes(1));++ await submit("second message");++ // The synchronous in-flight ref must prevent a second concurrent stream.+ expect(postStreaming).toHaveBeenCalledTimes(1);+ expect(+ screen.getAllByText("Queued — sends when this turn finishes.").length,+ ).toBeGreaterThan(0);+ expect(screen.getByRole("button", { name: "Cancel run" })).toBeTruthy();+ expect(screen.getByRole("button", { name: "Edit queued" })).toBeTruthy();+ });++ it("drains the queued message into one new stream after the turn ends", async () => {+ await renderChat();+ await submit("first message");+ await waitFor(() => expect(postStreaming).toHaveBeenCalledTimes(1));+ await submit("second message");+ expect(postStreaming).toHaveBeenCalledTimes(1);++ await completeOldestStream("first done");+ await waitFor(() => expect(postStreaming).toHaveBeenCalledTimes(2));++ expect(streamCalls[1]?.body.message).toBe("second message");+ // The queued bubble is reused on drain — not duplicated.+ expect(screen.getAllByText("second message")).toHaveLength(1);+ });++ it("Escape edits the queued message first, preserving the active run", async () => {+ await renderChat();+ await submit("first message");+ await waitFor(() => expect(postStreaming).toHaveBeenCalledTimes(1));+ await submit("second message");+ expect(textarea().disabled).toBe(true);++ await act(async () => {+ fireEvent.keyDown(window, { key: "Escape" });+ });++ // Queued text returns to the input; the run was not cancelled.+ expect(textarea().value).toBe("second message");+ expect(textarea().disabled).toBe(false);+ expect(cancelPost).not.toHaveBeenCalled();+ expect(screen.getByRole("button", { name: "Cancel run" })).toBeTruthy();+ });++ it("resets the live narrative when a stream throws without a terminal", async () => {+ await renderChat();+ await submit("build me a workflow");+ await waitFor(() => expect(postStreaming).toHaveBeenCalledTimes(1));++ await act(async () => {+ streamCalls[0]?.onMessage(turnStart());+ });+ // The live (non-terminal) narrative bubble is an aria-live status region.+ expect(screen.queryAllByRole("status").length).toBeGreaterThan(0);++ await act(async () => {+ streamCalls[0]?.reject(new Error("network drop"));+ });++ // Resetting the narrative stops the progress/elapsed indicator from+ // ticking forever beside the error message.+ expect(screen.queryAllByRole("status")).toHaveLength(0);+ expect(screen.getByText(/I encountered an error/)).toBeTruthy();+ });++ it("does not orphan a message on a same-tick double submit while working", async () => {+ await renderChat();+ await submit("first message");+ await waitFor(() => expect(postStreaming).toHaveBeenCalledTimes(1));++ // Two synchronous Enter presses before React commits the first queue: the+ // synchronous queuedPromptRef must make the second a no-op, not a 2nd queue.+ await act(async () => {+ fireEvent.change(textarea(), { target: { value: "queued message" } });+ const ta = textarea();+ ta.dispatchEvent(+ new KeyboardEvent("keydown", { key: "Enter", bubbles: true }),+ );+ ta.dispatchEvent(+ new KeyboardEvent("keydown", { key: "Enter", bubbles: true }),+ );+ });++ expect(screen.getAllByText("queued message")).toHaveLength(1);+ expect(postStreaming).toHaveBeenCalledTimes(1);+ });+});diff --git a/skyvern-frontend/src/routes/workflows/copilot/WorkflowCopilotChat.tsx b/skyvern-frontend/src/routes/workflows/copilot/WorkflowCopilotChat.tsxindex 5d73fe52a..cd5e30721 100644--- a/skyvern-frontend/src/routes/workflows/copilot/WorkflowCopilotChat.tsx+++ b/skyvern-frontend/src/routes/workflows/copilot/WorkflowCopilotChat.tsx@@ -36,10 +36,12 @@ import {WorkflowCopilotClearProposedWorkflowRequest,WorkflowCopilotApplyProposedWorkflowRequest,} from "./workflowCopilotTypes";+import { shouldWaitForLiveBrowser } from "./browserReadiness";import {- shouldQueuePromptForLiveBrowser,- shouldWaitForLiveBrowser,-} from "./browserReadiness";+ QueuedPromptReason,+ resolveDrainAction,+ resolveSendAction,+} from "./sendQueue";import { shouldAutoApplyWorkflowResponse } from "./proposalDisposition";import { NarrativeView } from "./NarrativeView";import {@@ -129,6 +131,7 @@ interface ChatMessage {type QueuedPrompt = {id: string;content: string;+ reason: QueuedPromptReason;};type SendOptions = {@@ -303,6 +306,13 @@ export function WorkflowCopilotChat({}, [narrative]);const [isLoadingHistory, setIsLoadingHistory] = useState(false);const streamingAbortController = useRef<AbortController | null>(null);+ // Synchronous in-flight gate. State (isLoading) lags a render behind, so a+ // rapid double-submit would run a stale closure and start a second stream;+ // this ref is set before the first await and read at the top of handleSend.+ const inFlightRef = useRef(false);+ // Synchronous mirror of queuedPrompt (like inFlightRef) so a same-tick double+ // submit can't queue twice and orphan the first message. Set via updateQueuedPrompt.+ const queuedPromptRef = useRef<QueuedPrompt | null>(null);const pendingMessageId = useRef<string | null>(null);const pendingCancelToken = useRef<string | null>(null);const cancelSafetyTimer = useRef<ReturnType<typeof setTimeout> | null>(null);@@ -401,9 +411,14 @@ export function WorkflowCopilotChat({adjustTextareaHeight();}, [adjustTextareaHeight, inputValue]);+ const updateQueuedPrompt = useCallback((next: QueuedPrompt | null) => {+ queuedPromptRef.current = next;+ setQueuedPrompt(next);+ }, []);+const handleNewChat = () => {setMessages([]);- setQueuedPrompt(null);+ updateQueuedPrompt(null);setWorkflowCopilotChatId(null);setProposedWorkflow(null);setAutoAccept(false);@@ -627,7 +642,7 @@ export function WorkflowCopilotChat({useEffect(() => {if (!workflowPermanentId) {setMessages([]);- setQueuedPrompt(null);+ updateQueuedPrompt(null);setWorkflowCopilotChatId(null);setProposedWorkflow(null);setAutoAccept(false);@@ -700,7 +715,7 @@ export function WorkflowCopilotChat({return () => {isMounted = false;};- }, [credentialGetter, workflowPermanentId]);+ }, [credentialGetter, updateQueuedPrompt, workflowPermanentId]);const cancelSend = useCallback(async () => {// Capture upfront so the 15s timer below can't latch onto a next turn's controller.@@ -758,7 +773,7 @@ export function WorkflowCopilotChat({return;}- setQueuedPrompt(null);+ updateQueuedPrompt(null);setMessages((prev) =>prev.filter((message) => message.id !== queuedPrompt.id),);@@ -767,7 +782,7 @@ export function WorkflowCopilotChat({textareaRef.current?.focus();adjustTextareaHeight();});- }, [adjustTextareaHeight, queuedPrompt]);+ }, [adjustTextareaHeight, queuedPrompt, updateQueuedPrompt]);useEffect(() => {const handleKeyDown = (event: KeyboardEvent) => {@@ -792,12 +807,19 @@ export function WorkflowCopilotChat({const handleSend = useCallback(async (messageOverride?: string, options: SendOptions = {}) => {const candidate = messageOverride ?? inputValue;- if (- !candidate.trim() ||- isLoading ||- (queuedPrompt && !options.queuedMessageId)- )+ const isDrain = Boolean(options.queuedMessageId);+ const action = resolveSendAction({+ inFlight: inFlightRef.current,+ hasQueuedPrompt: Boolean(queuedPromptRef.current),+ requiresLiveBrowser,+ isLiveBrowserReady,+ candidate,+ isDrain,+ skipQueue: Boolean(options.skipQueue),+ });+ if (action === "noop") {return;+ }if (!workflowPermanentId) {toast({title: "Missing agent",@@ -806,36 +828,38 @@ export function WorkflowCopilotChat({});return;}- if (- !options.skipQueue &&- shouldQueuePromptForLiveBrowser({- requiresLiveBrowser,- isLiveBrowserReady,- message: candidate,- })- ) {- const queued: QueuedPrompt = {- id: `${Date.now()}-queued`,- content: candidate,- };-- setQueuedPrompt(queued);- setMessages((prev) => [- ...prev,- {- id: queued.id,- sender: "user",- content: queued.content,- },- ]);+ if (action === "queue_working" || action === "queue_live_browser") {+ const reason: QueuedPromptReason =+ action === "queue_working" ? "working" : "live_browser";+ const queuedId = options.queuedMessageId ?? crypto.randomUUID();+ updateQueuedPrompt({ id: queuedId, content: candidate, reason });+ // First queue adds the user bubble; a re-queue (a working drain that+ // then had to wait for the browser) reuses the existing bubble.+ if (!options.queuedMessageId) {+ setMessages((prev) => [+ ...prev,+ { id: queuedId, sender: "user", content: candidate },+ ]);+ }setProposedWorkflow(null);if (messageOverride === undefined) {setInputValue("");}- toast({- title: "Prompt queued",- description: "Copilot will start once the live browser connects.",- });+ if (!options.queuedMessageId) {+ toast(+ reason === "working"+ ? {+ title: "Message queued",+ description:+ "Copilot is finishing the current turn — it will send next.",+ }+ : {+ title: "Prompt queued",+ description:+ "Copilot will start once the live browser connects.",+ },+ );+ }return;}@@ -859,6 +883,7 @@ export function WorkflowCopilotChat({setInputValue("");}setIsLoading(true);+ inFlightRef.current = true;const abortController = new AbortController();streamingAbortController.current?.abort();@@ -1152,9 +1177,13 @@ export function WorkflowCopilotChat({content: "Sorry, I encountered an error. Please try again.",};setMessages((prev) => [...prev, errorMessage]);+ // A thrown stream never emits a terminal narrative event, so clear the+ // bubble or its Working/elapsed indicator would tick forever.+ setNarrative(EMPTY_NARRATIVE);} finally {if (streamingAbortController.current === abortController) {streamingAbortController.current = null;+ inFlightRef.current = false;}if (cancelInFlightController.current === abortController) {cancelInFlightController.current = null;@@ -1175,10 +1204,9 @@ export function WorkflowCopilotChat({getSaveData,inputValue,isLiveBrowserReady,- isLoading,liveBrowserSessionId,- queuedPrompt,requiresLiveBrowser,+ updateQueuedPrompt,workflowCopilotChatId,workflowPermanentId,workflowRunId,@@ -1193,24 +1221,27 @@ export function WorkflowCopilotChat({};useEffect(() => {- // Drain only when the browser is actually ready (non-null session id from- // the parent). If requiresLiveBrowser flips to false without a session- // (rate-limit, pane hidden), the queue stays so user intent isn't sent- // with browser_session_id=null.- if (- !queuedPrompt ||- !liveBrowserSessionId ||- isLoading ||- !workflowPermanentId- ) {+ // isLoading (reactive state) is the in-flight signal here so the effect+ // re-runs when a turn ends; handleSend uses the synchronous ref instead.+ const drainAction = resolveDrainAction({+ queuedReason: queuedPrompt?.reason ?? null,+ inFlight: isLoading,+ hasLiveBrowserSession: Boolean(liveBrowserSessionId),+ hasWorkflowPermanentId: Boolean(workflowPermanentId),+ });+ if (!queuedPrompt || drainAction === "wait") {return;}const promptToSend = queuedPrompt;- setQueuedPrompt(null);+ // Clear before re-entering handleSend so a 'send' resolution leaves no+ // stale queued prompt for the effect to re-drain in a loop. A working+ // prompt that still needs the browser re-queues under the same id and+ // drains via the live_browser path once the session arrives.+ updateQueuedPrompt(null);handleSend(promptToSend.content, {queuedMessageId: promptToSend.id,- skipQueue: true,+ skipQueue: drainAction === "drain_skip_queue",}).catch((error) => {console.error("Queued send failed:", error);});@@ -1219,6 +1250,7 @@ export function WorkflowCopilotChat({isLoading,liveBrowserSessionId,queuedPrompt,+ updateQueuedPrompt,workflowPermanentId,]);@@ -1442,14 +1474,20 @@ export function WorkflowCopilotChat({return null;}- const inputDisabled = isLoading || Boolean(queuedPrompt);+ // Input stays usable while Copilot works; only a parked queued prompt+ // disables it (the message is already captured).+ const inputDisabled = Boolean(queuedPrompt);const queuedPromptWaitingStatus =- "Prompt queued. Waiting for live browser...";+ queuedPrompt?.reason === "working"+ ? "Queued — sends when this turn finishes."+ : "Prompt queued. Waiting for live browser...";const browserStatusText = queuedPrompt? queuedPromptWaitingStatus- : isWaitingForLiveBrowser- ? "Live browser is starting. Send now to queue your prompt."- : null;+ : isLoading+ ? "Copilot is working — message will queue…"+ : isWaitingForLiveBrowser+ ? "Live browser is starting. Send now to queue your prompt."+ : null;return (<div@@ -1660,9 +1698,11 @@ export function WorkflowCopilotChat({placeholder={queuedPrompt? "Prompt queued..."- : isWaitingForLiveBrowser- ? "Type a prompt to queue..."- : "Type your message... (Shift+Enter for new line)"+ : isLoading+ ? "Type a message to queue for the next turn…"+ : isWaitingForLiveBrowser+ ? "Type a prompt to queue..."+ : "Type your message... (Shift+Enter for new line)"}value={inputValue}onChange={(e) => setInputValue(e.target.value)}@@ -1676,10 +1716,44 @@ export function WorkflowCopilotChat({overflow: "auto",}}/>- {isLoading || Boolean(queuedPrompt) ? (+ {isLoading && queuedPrompt ? (+ <>+ <button+ onClick={cancelQueuedPrompt}+ title="Edit queued message"+ className="rounded-md border border-neutral-300 px-3 py-2 text-sm font-medium text-neutral-700 hover:bg-neutral-100 dark:border-neutral-700 dark:text-neutral-300 dark:hover:bg-neutral-900"+ >+ Edit queued+ </button>+ <button+ onClick={cancelSend}+ title="Cancel run"+ className="rounded-md bg-red-600 px-3 py-2 text-sm font-medium text-white hover:bg-red-700"+ >+ Cancel run+ </button>+ </>+ ) : isLoading ? (+ <>+ <button+ onClick={() => handleSend()}+ title="Queue for the next turn"+ className="rounded-md border border-neutral-300 px-3 py-2 text-sm font-medium text-neutral-700 hover:bg-neutral-100 dark:border-neutral-700 dark:text-neutral-300 dark:hover:bg-neutral-900"+ >+ Queue+ </button>+ <button+ onClick={cancelSend}+ title="Cancel run"+ className="rounded-md bg-red-600 px-3 py-2 text-sm font-medium text-white hover:bg-red-700"+ >+ Cancel run+ </button>+ </>+ ) : queuedPrompt ? (<button- onClick={isLoading ? cancelSend : cancelQueuedPrompt}- title={isLoading ? "Stop Copilot" : "Edit queued prompt"}+ onClick={cancelQueuedPrompt}+ title="Edit queued prompt"className="rounded-md bg-red-600 px-4 py-2 text-sm font-medium text-white hover:bg-red-700">Canceldiff --git a/skyvern-frontend/src/routes/workflows/copilot/sendQueue.test.ts b/skyvern-frontend/src/routes/workflows/copilot/sendQueue.test.tsnew file mode 100644index 000000000..122813984--- /dev/null+++ b/skyvern-frontend/src/routes/workflows/copilot/sendQueue.test.ts@@ -0,0 +1,152 @@+import { describe, expect, it } from "vitest";++import { resolveDrainAction, resolveSendAction } from "./sendQueue";++const sendInput = (+ overrides: Partial<Parameters<typeof resolveSendAction>[0]> = {},+): Parameters<typeof resolveSendAction>[0] => ({+ inFlight: false,+ hasQueuedPrompt: false,+ requiresLiveBrowser: false,+ isLiveBrowserReady: false,+ candidate: "hello",+ isDrain: false,+ skipQueue: false,+ ...overrides,+});++describe("resolveSendAction", () => {+ it("returns noop for an empty candidate", () => {+ expect(resolveSendAction(sendInput({ candidate: " " }))).toBe("noop");+ });++ it("returns noop when a prompt is already queued and this is not a drain", () => {+ expect(+ resolveSendAction(sendInput({ hasQueuedPrompt: true, isDrain: false })),+ ).toBe("noop");+ });++ it("queues for the next turn while a turn is in flight", () => {+ expect(resolveSendAction(sendInput({ inFlight: true }))).toBe(+ "queue_working",+ );+ });++ it("prioritizes the in-flight queue over the live-browser queue", () => {+ expect(+ resolveSendAction(+ sendInput({+ inFlight: true,+ requiresLiveBrowser: true,+ isLiveBrowserReady: false,+ }),+ ),+ ).toBe("queue_working");+ });++ it("queues for the live browser when one is required but not ready", () => {+ expect(+ resolveSendAction(+ sendInput({ requiresLiveBrowser: true, isLiveBrowserReady: false }),+ ),+ ).toBe("queue_live_browser");+ });++ it("sends when the required live browser is ready", () => {+ expect(+ resolveSendAction(+ sendInput({ requiresLiveBrowser: true, isLiveBrowserReady: true }),+ ),+ ).toBe("send");+ });++ it("sends when no live browser is required", () => {+ expect(resolveSendAction(sendInput())).toBe("send");+ });++ it("bypasses the single-queue guard while draining", () => {+ expect(+ resolveSendAction(sendInput({ hasQueuedPrompt: true, isDrain: true })),+ ).toBe("send");+ });++ it("skipQueue forces a send past the live-browser predicate", () => {+ expect(+ resolveSendAction(+ sendInput({+ isDrain: true,+ skipQueue: true,+ requiresLiveBrowser: true,+ isLiveBrowserReady: false,+ }),+ ),+ ).toBe("send");+ });+});++const drainInput = (+ overrides: Partial<Parameters<typeof resolveDrainAction>[0]> = {},+): Parameters<typeof resolveDrainAction>[0] => ({+ queuedReason: null,+ inFlight: false,+ hasLiveBrowserSession: false,+ hasWorkflowPermanentId: true,+ ...overrides,+});++describe("resolveDrainAction", () => {+ it("waits when nothing is queued", () => {+ expect(resolveDrainAction(drainInput({ queuedReason: null }))).toBe("wait");+ });++ it("waits while a turn is in flight", () => {+ expect(+ resolveDrainAction(+ drainInput({ queuedReason: "working", inFlight: true }),+ ),+ ).toBe("wait");+ });++ it("waits without a workflow permanent id", () => {+ expect(+ resolveDrainAction(+ drainInput({ queuedReason: "working", hasWorkflowPermanentId: false }),+ ),+ ).toBe("wait");+ });++ it("re-queues a working prompt regardless of browser readiness", () => {+ expect(+ resolveDrainAction(+ drainInput({ queuedReason: "working", hasLiveBrowserSession: false }),+ ),+ ).toBe("drain_requeue");+ expect(+ resolveDrainAction(+ drainInput({ queuedReason: "working", hasLiveBrowserSession: true }),+ ),+ ).toBe("drain_requeue");+ });++ it("skip-queue sends a live_browser prompt only once the session exists", () => {+ expect(+ resolveDrainAction(+ drainInput({+ queuedReason: "live_browser",+ hasLiveBrowserSession: true,+ }),+ ),+ ).toBe("drain_skip_queue");+ });++ it("waits for the session before draining a live_browser prompt", () => {+ expect(+ resolveDrainAction(+ drainInput({+ queuedReason: "live_browser",+ hasLiveBrowserSession: false,+ }),+ ),+ ).toBe("wait");+ });+});diff --git a/skyvern-frontend/src/routes/workflows/copilot/sendQueue.ts b/skyvern-frontend/src/routes/workflows/copilot/sendQueue.tsnew file mode 100644index 000000000..c9ee4f896--- /dev/null+++ b/skyvern-frontend/src/routes/workflows/copilot/sendQueue.ts@@ -0,0 +1,90 @@+import { shouldQueuePromptForLiveBrowser } from "./browserReadiness";++// A queued prompt waits for one of two reasons: the live browser isn't ready+// yet ("live_browser"), or Copilot is mid-turn and the message is for the next+// turn ("working"). The two drain on different signals.+export type QueuedPromptReason = "live_browser" | "working";++export type SendAction =+ | "send"+ | "queue_working"+ | "queue_live_browser"+ | "noop";++type ResolveSendInput = {+ // True while a turn is streaming. MUST be read from a synchronous ref, not+ // React state: a rapid double-submit runs a stale closure where the state is+ // still false, which would start a second concurrent stream.+ inFlight: boolean;+ hasQueuedPrompt: boolean;+ requiresLiveBrowser: boolean;+ isLiveBrowserReady: boolean;+ candidate: string;+ // True when this call is draining an already-queued prompt (it carries the+ // queued message id), so the "one queued prompt at a time" guard is bypassed.+ isDrain: boolean;+ skipQueue: boolean;+};++export function resolveSendAction({+ inFlight,+ hasQueuedPrompt,+ requiresLiveBrowser,+ isLiveBrowserReady,+ candidate,+ isDrain,+ skipQueue,+}: ResolveSendInput): SendAction {+ if (!candidate.trim()) {+ return "noop";+ }+ if (hasQueuedPrompt && !isDrain) {+ return "noop";+ }+ if (inFlight) {+ return "queue_working";+ }+ if (+ !skipQueue &&+ shouldQueuePromptForLiveBrowser({+ requiresLiveBrowser,+ isLiveBrowserReady,+ message: candidate,+ })+ ) {+ return "queue_live_browser";+ }+ return "send";+}++export type DrainAction = "drain_skip_queue" | "drain_requeue" | "wait";++type ResolveDrainInput = {+ queuedReason: QueuedPromptReason | null;+ inFlight: boolean;+ hasLiveBrowserSession: boolean;+ hasWorkflowPermanentId: boolean;+};++// drain_skip_queue is the ONLY path that sends past the live-browser predicate,+// and only for a live_browser-reason prompt whose session is confirmed — so a+// prompt is never sent with a null browser session. A working-reason prompt+// always re-enters handleSend without skipQueue (drain_requeue) so the+// live-browser predicate re-gates it.+export function resolveDrainAction({+ queuedReason,+ inFlight,+ hasLiveBrowserSession,+ hasWorkflowPermanentId,+}: ResolveDrainInput): DrainAction {+ if (queuedReason === null || inFlight || !hasWorkflowPermanentId) {+ return "wait";+ }+ if (queuedReason === "working") {+ return "drain_requeue";+ }+ if (queuedReason === "live_browser" && hasLiveBrowserSession) {+ return "drain_skip_queue";+ }+ return "wait";+}