Automate browser based workflows with AI
Python aiapiautomationbrowserbrowser-automationcomputergptllmplaywrightpowerautomatepuppeteerpythonrpaseleniumvisionworkflow
Show a queued Copilot message as a strip on the message box (SKY-17126) (#8659)
Shuchang Zheng113b98f181b3
diff --git a/docs/cloud/building-agents/configure-blocks.mdx b/docs/cloud/building-agents/configure-blocks.mdxindex 5ef272a82..2ccb2df8e 100644--- a/docs/cloud/building-agents/configure-blocks.mdx+++ b/docs/cloud/building-agents/configure-blocks.mdx@@ -221,7 +221,7 @@ With Google and a single `site:example.com` or `site:example.com/path` filter, tAutomatic starts with Google. It tries Exa only if Google fails before returning results. An empty search does not trigger fallback. It succeeds unless a configured outcome terminates the block. Selecting Google or Exa uses only that provider.-Leave Prompt blank to make no LLM calls. When supplied, Prompt receives only the normalized search results. It runs on an empty list unless you set No Results Error Code. It cannot fetch result pages. Exa supports a single positive `site:domain` restriction; unsupported site expressions fail instead of expanding the search.+Leave Prompt blank to make no LLM calls. When supplied, Prompt receives only the normalized search results. It runs on an empty list unless you set No Results Error Code. It cannot fetch result pages. Exa supports a single positive `site:domain` restriction; unsupported site expressions fail instead of expanding the search. With Exa, a result's `snippet` is empty when Exa has no cached copy of the page or when the request for page highlights fails.If a Prompt response fails JSON validation, the Prompt retries once with validation feedback before the block fails. For filter-style Prompts, use an array Data Schema so a no-match answer is `[]`, which downstream blocks can branch on.diff --git a/skyvern-frontend/src/components/icons/CornerDownRightIcon.tsx b/skyvern-frontend/src/components/icons/CornerDownRightIcon.tsxnew file mode 100644index 000000000..79131b22e--- /dev/null+++ b/skyvern-frontend/src/components/icons/CornerDownRightIcon.tsx@@ -0,0 +1,24 @@+type Props = {+ className?: string;+};++function CornerDownRightIcon({ className }: Props) {+ return (+ <svg+ xmlns="http://www.w3.org/2000/svg"+ viewBox="0 0 24 24"+ fill="none"+ stroke="currentColor"+ strokeWidth="2"+ strokeLinecap="round"+ strokeLinejoin="round"+ className={className}+ aria-hidden="true"+ >+ <path d="m15 10 5 5-5 5" />+ <path d="M4 4v7a4 4 0 0 0 4 4h12" />+ </svg>+ );+}++export { CornerDownRightIcon };diff --git a/skyvern-frontend/src/routes/workflows/copilot/CopilotWorkingStatus.test.tsx b/skyvern-frontend/src/routes/workflows/copilot/CopilotWorkingStatus.test.tsxindex 47b777ac3..5d6011467 100644--- a/skyvern-frontend/src/routes/workflows/copilot/CopilotWorkingStatus.test.tsx+++ b/skyvern-frontend/src/routes/workflows/copilot/CopilotWorkingStatus.test.tsx@@ -1,7 +1,7 @@// @vitest-environment jsdom-import { cleanup, fireEvent, render, screen } from "@testing-library/react";-import { afterEach, describe, expect, it, vi } from "vitest";+import { cleanup, render, screen } from "@testing-library/react";+import { afterEach, describe, expect, it } from "vitest";import { CopilotWorkingStatus } from "./CopilotWorkingStatus";@@ -11,26 +11,14 @@ afterEach(() => {describe("CopilotWorkingStatus", () => {it("announces the state once, without the cycling verb", () => {- const { rerender } = render(- <CopilotWorkingStatus queued={false} onDismissQueued={() => {}} />,- );+ const { rerender } = render(<CopilotWorkingStatus queued={false} />);expect(screen.getByText("Working")).toBeTruthy();- rerender(<CopilotWorkingStatus queued onDismissQueued={() => {}} />);+ rerender(<CopilotWorkingStatus queued />);expect(screen.getByText("Message queued")).toBeTruthy();// The verb re-renders every few seconds, so it must stay out of the// announcement or a screen reader repeats it forever.const verb = screen.getByTestId("copilot-working-status").firstElementChild;expect(verb?.getAttribute("aria-hidden")).toBe("true");});-- it("hands the queued message back when the pill is dismissed", () => {- const onDismissQueued = vi.fn();- render(<CopilotWorkingStatus queued onDismissQueued={onDismissQueued} />);-- fireEvent.click(- screen.getByRole("button", { name: "Edit queued message" }),- );- expect(onDismissQueued).toHaveBeenCalledTimes(1);- });});diff --git a/skyvern-frontend/src/routes/workflows/copilot/CopilotWorkingStatus.tsx b/skyvern-frontend/src/routes/workflows/copilot/CopilotWorkingStatus.tsxindex 3e6ddf2a4..216bddd74 100644--- a/skyvern-frontend/src/routes/workflows/copilot/CopilotWorkingStatus.tsx+++ b/skyvern-frontend/src/routes/workflows/copilot/CopilotWorkingStatus.tsx@@ -1,14 +1,12 @@-import { Pencil1Icon } from "@radix-ui/react-icons";import { useEffect, useState } from "react";import { VERB_CYCLE_MS, pickWorkingVerb } from "./workingVerbs";type Props = {queued: boolean;- onDismissQueued: () => void;};-export function CopilotWorkingStatus({ queued, onDismissQueued }: Props) {+export function CopilotWorkingStatus({ queued }: Props) {const [verb, setVerb] = useState(() => pickWorkingVerb());useEffect(() => {@@ -36,22 +34,6 @@ export function CopilotWorkingStatus({ queued, onDismissQueued }: Props) {<span className="sr-only" aria-live="polite">{queued ? "Message queued" : "Working"}</span>- {queued ? (- <div className="ml-auto flex shrink-0 items-center gap-1 whitespace-nowrap rounded-full bg-slate-400/[0.12] py-0.5 pl-2.5 pr-1 text-xs text-muted-foreground">- 1 message queued- {/* A cross here would read as "cancel the queued message"; this- returns it to the composer for editing. */}- <button- type="button"- onClick={onDismissQueued}- title="Edit queued message"- aria-label="Edit queued message"- className="rounded px-1 hover:text-accent-foreground"- >- <Pencil1Icon className="h-3 w-3" />- </button>- </div>- ) : null}</div>);}diff --git a/skyvern-frontend/src/routes/workflows/copilot/QueuedMessageStrip.tsx b/skyvern-frontend/src/routes/workflows/copilot/QueuedMessageStrip.tsxnew file mode 100644index 000000000..2c4149fb5--- /dev/null+++ b/skyvern-frontend/src/routes/workflows/copilot/QueuedMessageStrip.tsx@@ -0,0 +1,83 @@+import { Cross2Icon, FileIcon, Pencil1Icon } from "@radix-ui/react-icons";+import type { ReactNode } from "react";++import { CornerDownRightIcon } from "@/components/icons/CornerDownRightIcon";+import { TooltipProvider } from "@/components/ui/tooltip";+import { ControlTooltip } from "@/routes/workflows/studio/ControlTooltip";++import type { CopilotAttachedFile } from "./workflowCopilotTypes";++type Props = {+ text: string;+ attachments: CopilotAttachedFile[];+ // Omitted for a product action's receipt, which has no words of the user's to edit.+ onEdit?: () => void;+ onRemove: () => void;+};++export function QueuedMessageStrip({+ text,+ attachments,+ onEdit,+ onRemove,+}: Props) {+ return (+ <div+ data-testid="copilot-queued-message"+ className="group/queued flex items-center gap-2 rounded-t-lg border border-b-0 border-input bg-slate-elevation1 py-[3px] pl-2.5 pr-1 text-[12.5px] text-muted-foreground transition-colors duration-200 animate-in fade-in slide-in-from-bottom-2 motion-reduce:animate-none [&:has(+[role=group]:focus-within)]:border-ring"+ >+ <CornerDownRightIcon className="h-3 w-3 shrink-0" />+ <span className="min-w-0 flex-1 truncate" title={text}>+ {text}+ </span>+ {attachments.length > 0 ? (+ <span+ className="flex shrink-0 items-center gap-1"+ title={attachments.map((item) => item.filename).join(", ")}+ >+ <FileIcon aria-hidden className="h-3 w-3" />+ <span className="max-w-24 truncate">+ {attachments.length === 1+ ? attachments[0]!.filename+ : `${attachments.length} files`}+ </span>+ </span>+ ) : null}+ <TooltipProvider>+ <span className="flex shrink-0 opacity-55 transition-opacity group-focus-within/queued:opacity-100 group-hover/queued:opacity-100">+ {onEdit ? (+ <StripButton label="Edit queued message" onClick={onEdit}>+ <Pencil1Icon className="h-3 w-3" />+ </StripButton>+ ) : null}+ <StripButton label="Remove queued message" onClick={onRemove}>+ <Cross2Icon className="h-3 w-3" />+ </StripButton>+ </span>+ </TooltipProvider>+ </div>+ );+}++function StripButton({+ label,+ onClick,+ children,+}: {+ label: string;+ onClick: () => void;+ children: ReactNode;+}) {+ return (+ <ControlTooltip content={label} side="top">+ <button+ type="button"+ aria-label={label}+ onClick={onClick}+ className="grid h-6 w-6 place-items-center rounded text-muted-foreground hover:bg-slate-elevation3 hover:text-foreground focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-ring"+ >+ {children}+ </button>+ </ControlTooltip>+ );+}diff --git a/skyvern-frontend/src/routes/workflows/copilot/WorkflowCopilotChat.accountChoice.test.tsx b/skyvern-frontend/src/routes/workflows/copilot/WorkflowCopilotChat.accountChoice.test.tsxindex 3c3899df1..8c452a251 100644--- a/skyvern-frontend/src/routes/workflows/copilot/WorkflowCopilotChat.accountChoice.test.tsx+++ b/skyvern-frontend/src/routes/workflows/copilot/WorkflowCopilotChat.accountChoice.test.tsx@@ -370,7 +370,13 @@ describe("WorkflowCopilotChat connected account choices", () => {);});expect(postStreaming).toHaveBeenCalledTimes(1);- if (replaceText) await submit("Read a different sheet");+ if (replaceText) {+ // A picked account is not the user's words, so the composer says it will be replaced.+ expect(+ screen.getByPlaceholderText("Type to replace the queued message…"),+ ).toBeTruthy();+ await submit("Read a different sheet");+ }view.rerender(chatElement({requiresLiveBrowser: true,diff --git a/skyvern-frontend/src/routes/workflows/copilot/WorkflowCopilotChat.composerControls.test.tsx b/skyvern-frontend/src/routes/workflows/copilot/WorkflowCopilotChat.composerControls.test.tsxindex ec8caf159..8702cfddf 100644--- a/skyvern-frontend/src/routes/workflows/copilot/WorkflowCopilotChat.composerControls.test.tsx+++ b/skyvern-frontend/src/routes/workflows/copilot/WorkflowCopilotChat.composerControls.test.tsx@@ -439,15 +439,12 @@ describe("WorkflowCopilotChat — unflagged S4 composer", () => {fireEvent.click(button);});- // Queued, not sent as a second concurrent turn.+ // Queued, not sent as a second concurrent turn, and stated once: on the strip.expect(postStreaming).toHaveBeenCalledTimes(1);- // The queue now rides in the working row's pill; the standalone chip and- // the legacy prose status line are both gone, so the state is stated once.- expect(screen.getByText(/1 message queued/)).toBeTruthy();- expect(screen.queryByText("Queued")).toBeNull();- expect(- screen.queryByText("Queued — sends when this turn finishes."),- ).toBeNull();+ expect(screen.getAllByText("also grab the story scores")).toHaveLength(1);+ expect(screen.getByTestId("copilot-queued-message").textContent).toContain(+ "also grab the story scores",+ );});it("shows a cycling Skyvern verb instead of the prose working line", async () => {@@ -476,15 +473,9 @@ describe("WorkflowCopilotChat — unflagged S4 composer", () => {});await submit("build me a workflow");- // No turn started yet — queued purely on the live-browser gate. The- // status now lives on the queued bubble's footer, not the composer- // chip (that's reserved for the working-reason queue) — getByText- // throws on a duplicate match, so this also proves there's only one.+ // No turn started yet — queued purely on the live-browser gate.expect(postStreaming).not.toHaveBeenCalled();- expect(- screen.getByText("Prompt queued. Waiting for live browser..."),- ).toBeTruthy();- expect(screen.queryByText("Queued")).toBeNull();+ expect(screen.getAllByText("build me a workflow")).toHaveLength(1);const button = screen.getByRole("button", {name: "Send disabled — waiting for live browser",@@ -497,10 +488,8 @@ describe("WorkflowCopilotChat — unflagged S4 composer", () => {await act(async () => {fireEvent.click(cancel);});- expect(screen.queryByText("Queued")).toBeNull();- expect(- screen.queryByText("Prompt queued. Waiting for live browser..."),- ).toBeNull();+ expect(screen.queryByTestId("copilot-queued-message")).toBeNull();+ expect(textarea().value).toBe("build me a workflow");});it("embeds the input: idle placeholder matches the mock, textarea borderless inside a focus-within container", async () => {diff --git a/skyvern-frontend/src/routes/workflows/copilot/WorkflowCopilotChat.historyRace.test.tsx b/skyvern-frontend/src/routes/workflows/copilot/WorkflowCopilotChat.historyRace.test.tsxindex 6f69b9462..32e3aa9e6 100644--- a/skyvern-frontend/src/routes/workflows/copilot/WorkflowCopilotChat.historyRace.test.tsx+++ b/skyvern-frontend/src/routes/workflows/copilot/WorkflowCopilotChat.historyRace.test.tsx@@ -819,25 +819,21 @@ describe("WorkflowCopilotChat — startup and live-browser queue", () => {boolFlags.current = {};await renderChat({ requiresLiveBrowser: true, isLiveBrowserReady: false });await submit("log into the portal");- expect(- screen.queryByText("Prompt queued. Waiting for live browser..."),- ).toBeNull();+ expect(screen.queryByTestId("copilot-queued-message")).toBeNull();expect(postStreaming).not.toHaveBeenCalled();await flushHistory(historyData({ chat_history: [aiHistoryMessage(null, "Earlier chat.")] }),);await submit("log into the portal");- expect(- screen.getByText("Prompt queued. Waiting for live browser..."),- ).toBeTruthy();+ expect(screen.getByTestId("copilot-queued-message").textContent).toContain(+ "log into the portal",+ );await act(async () =>fireEvent.click(screen.getByRole("button", { name: "Edit queued message" }),),);- expect(- screen.queryByText("Prompt queued. Waiting for live browser..."),- ).toBeNull();+ expect(screen.queryByTestId("copilot-queued-message")).toBeNull();});});diff --git a/skyvern-frontend/src/routes/workflows/copilot/WorkflowCopilotChat.queue.test.tsx b/skyvern-frontend/src/routes/workflows/copilot/WorkflowCopilotChat.queue.test.tsxindex 39680ba69..a2f4b6cc6 100644--- a/skyvern-frontend/src/routes/workflows/copilot/WorkflowCopilotChat.queue.test.tsx+++ b/skyvern-frontend/src/routes/workflows/copilot/WorkflowCopilotChat.queue.test.tsx@@ -5,6 +5,7 @@ import {render,screen,waitFor,+ within,} from "@testing-library/react";import { useEffect, useState, type ComponentProps } from "react";import { flushSync } from "react-dom";@@ -258,6 +259,10 @@ function HomeHandoffChat({);}+function queuedStrip() {+ return within(screen.getByTestId("copilot-queued-message"));+}+function textarea(): HTMLTextAreaElement {return screen.getByRole("textbox") as HTMLTextAreaElement;}@@ -841,11 +846,14 @@ describe("WorkflowCopilotChat — keep the chat live during a turn", () => {// The synchronous in-flight ref must prevent a second concurrent stream.expect(postStreaming).toHaveBeenCalledTimes(1);- expect(screen.getByText("1 message queued")).toBeTruthy();expect(screen.getByRole("button", { name: "Stop" })).toBeTruthy();+ // Undelivered, the message lives only on the strip: no bubble in the thread and no toast.+ expect(screen.getAllByText("second message")).toHaveLength(1);+ expect(queuedStrip().getByText("second message")).toBeTruthy();expect(- screen.getByRole("button", { name: "Edit queued message" }),+ queuedStrip().getByRole("button", { name: "Edit queued message" }),).toBeTruthy();+ expect(toast).not.toHaveBeenCalled();});it("drains the queued message into one new stream after the turn ends", async () => {@@ -951,9 +959,7 @@ describe("WorkflowCopilotChat — keep the chat live during a turn", () => {await completeOldestStream("first done");await waitFor(() =>- expect(- screen.getByText("Prompt queued. Waiting for live browser..."),- ).toBeTruthy(),+ expect(queuedStrip().getByText("parse the queued sheet")).toBeTruthy(),);expect(postStreaming).toHaveBeenCalledTimes(1);expect(@@ -1038,7 +1044,7 @@ describe("WorkflowCopilotChat — keep the chat live during a turn", () => {expect(screen.queryByText("over 10MB")).toBeNull();});- it("drops a failed chip when it replaces a queued message", async () => {+ it("drops a failed chip when it adds to a queued message", async () => {await renderChat();await submit("first message");await waitFor(() => expect(postStreaming).toHaveBeenCalledTimes(1));@@ -1049,7 +1055,7 @@ describe("WorkflowCopilotChat — keep the chat live during a turn", () => {await submit("read the scan instead");expect(postStreaming).toHaveBeenCalledTimes(1);- expect(screen.getByText("read the scan instead")).toBeTruthy();+ expect(queuedStrip().getByText(/read the scan instead/)).toBeTruthy();expect(screen.queryByText("over 10MB")).toBeNull();});@@ -1212,6 +1218,35 @@ describe("WorkflowCopilotChat — keep the chat live during a turn", () => {expect(streamCalls[0]?.body.attached_file_ids).toEqual(["file_1"]);});+ it("adds text once when Enter is pressed again while dictation finishes stopping", async () => {+ await renderChat();+ await submit("build me a workflow");+ await waitFor(() => expect(postStreaming).toHaveBeenCalledTimes(1));+ await deliverFirstFrame();+ await submit("use the staging site");++ speechState.isListening = true;+ let finishStopping: () => void = () => {};+ speechState.stop.mockImplementationOnce(+ () =>+ new Promise<Blob | null>((resolve) => {+ finishStopping = () => resolve(null);+ }),+ );+ await submit("and log in first");+ speechState.isListening = false;+ await act(async () => {+ fireEvent.keyDown(textarea(), { key: "Enter" });+ });+ await act(async () => {+ finishStopping();+ });++ expect(+ queuedStrip().getByText("use the staging site and log in first"),+ ).toBeTruthy();+ });+it("deletes a sent file whose request never went out because the composer unmounted", async () => {const view = await renderChat();await attachSpreadsheet("mine.csv");@@ -1420,7 +1455,7 @@ describe("WorkflowCopilotChat — keep the chat live during a turn", () => {);});- // The queued bubble must not show, and the drain must not send, an upload that was deleted.+ // The queued strip must not show, and the drain must not send, an upload that was deleted.await waitFor(() => expect(screen.queryByTitle("queued.csv")).toBeNull());await completeOldestStream("first done");await waitFor(() => expect(postStreaming).toHaveBeenCalledTimes(2));@@ -1941,7 +1976,7 @@ describe("WorkflowCopilotChat — keep the chat live during a turn", () => {expect(deleteFile).not.toHaveBeenCalled();});- it("returns a replaced queued message's file to the tray", async () => {+ it("sends both files when a second message is added to a queued one", async () => {await renderChat();await submit("first message");await waitFor(() => expect(postStreaming).toHaveBeenCalledTimes(1));@@ -1950,20 +1985,24 @@ describe("WorkflowCopilotChat — keep the chat live during a turn", () => {await submit("parse the first sheet");expect(postStreaming).toHaveBeenCalledTimes(1);- // Replacing the queued message with a different file must not strand the first one.+ // Adding to the queued message must not drop the file it already carries.await attachSpreadsheet("second.csv");- await submit("parse the second sheet instead");+ await submit("and the second sheet");expect(postStreaming).toHaveBeenCalledTimes(1);- expect(- screen.getByRole("button", { name: "Remove first.csv" }),- ).toBeTruthy();+ expect(queuedStrip().getByText("2 files")).toBeTruthy();await completeOldestStream("first done");await waitFor(() => expect(postStreaming).toHaveBeenCalledTimes(2));- expect(streamCalls[1]?.body.attached_file_ids).toEqual(["file_2"]);+ expect(streamCalls[1]?.body.message).toBe(+ "parse the first sheet\nand the second sheet",+ );+ expect(streamCalls[1]?.body.attached_file_ids).toEqual([+ "file_1",+ "file_2",+ ]);});- it("shows a queued message's attachment on its bubble", async () => {+ it("shows a queued message's attachment on the queued strip", async () => {await renderChat();await submit("first message");await waitFor(() => expect(postStreaming).toHaveBeenCalledTimes(1));@@ -1972,11 +2011,11 @@ describe("WorkflowCopilotChat — keep the chat live during a turn", () => {await submit("parse the queued sheet");expect(postStreaming).toHaveBeenCalledTimes(1);- // The tray is cleared on queue, so the bubble is the only place the file is visible.+ // The tray is cleared on queue, so the strip is the only place the file is visible.expect(screen.queryByRole("button", { name: "Remove queued.csv" }),).toBeNull();- expect(screen.getByTitle("queued.csv")).toBeTruthy();+ expect(queuedStrip().getByTitle("queued.csv")).toBeTruthy();});it("returns the file to the composer, still deletable, when the server errors before a turn starts", async () => {@@ -3054,8 +3093,7 @@ describe("WorkflowCopilotChat — a repeat of the turn's own message is not re-rawait renderChat();await attachSpreadsheet("rows.csv");- // Two Enter presses before React commits: the second still sees the same text and tray, so it- // queues an exact copy of the request the first one just sent.+ // Two Enter presses before React commits: the second still sees the same text and tray.await act(async () => {fireEvent.change(textarea(), { target: { value: "parse the sheet" } });const ta = textarea();@@ -3068,6 +3106,7 @@ describe("WorkflowCopilotChat — a repeat of the turn's own message is not re-r});await waitFor(() => expect(postStreaming).toHaveBeenCalledTimes(1));expect(streamCalls[0]?.body.attached_file_ids).toEqual(["file_1"]);+ expect(screen.queryByTestId("copilot-queued-message")).toBeNull();await completeOldestStream("first done");await act(async () => {});@@ -3075,41 +3114,6 @@ describe("WorkflowCopilotChat — a repeat of the turn's own message is not re-rexpect(postStreaming).toHaveBeenCalledTimes(1);});- it("keeps a started turn's file when its queued duplicate is edited and the file removed", async () => {- await renderChat();- await attachSpreadsheet("rows.csv");- await act(async () => {- fireEvent.change(textarea(), { target: { value: "parse the sheet" } });- const ta = textarea();- ta.dispatchEvent(- new KeyboardEvent("keydown", { key: "Enter", bubbles: true }),- );- ta.dispatchEvent(- new KeyboardEvent("keydown", { key: "Enter", bubbles: true }),- );- });- await waitFor(() => expect(postStreaming).toHaveBeenCalledTimes(1));- await deliverFirstFrame();-- // Editing the duplicate hands its ids back to the tray while the first turn still uses them.- await act(async () => {- fireEvent.keyDown(textarea(), { key: "Escape" });- });- await waitFor(() =>- expect(- screen.getByRole("button", { name: "Remove rows.csv" }),- ).toBeTruthy(),- );- await act(async () => {- fireEvent.click(screen.getByRole("button", { name: "Remove rows.csv" }));- });- await act(async () => {- await new Promise((resolve) => setTimeout(resolve, 0));- });-- expect(deleteFile).not.toHaveBeenCalled();- });-it("drains an identical queued prompt when the turn ends in a response-framed error", async () => {await renderChat();await submit("build me a workflow");@@ -3365,22 +3369,6 @@ describe("WorkflowCopilotChat — a repeat of the turn's own message is not re-rawait waitFor(() => expect(postStreaming).toHaveBeenCalledTimes(3));expect(streamCalls[2]!.body.message).toBe(blockBuildMessage);});-- it("drops a queued prompt that a replacement send rewrote into a repeat", async () => {- await renderChat();- await submit("build me a workflow");- await waitFor(() => expect(postStreaming).toHaveBeenCalledTimes(1));-- await submit("something else entirely");- await submit("build me a workflow");-- await completeOldestStream("first done");- await act(async () => {});-- expect(postStreaming).toHaveBeenCalledTimes(1);- expect(screen.queryByText("something else entirely")).toBeNull();- expect(screen.getAllByText("build me a workflow")).toHaveLength(1);- });});describe("WorkflowCopilotChat — a stop never replays a queued message", () => {@@ -3445,40 +3433,62 @@ describe("WorkflowCopilotChat — the composer stays usable while a prompt is paexpect(textarea().disabled).toBe(false);expect(- screen.getByPlaceholderText("Type to replace the queued message…"),+ screen.getByPlaceholderText("Add to the queued message…"),).toBeTruthy();});- it("does not clobber half-typed composer text when a stop returns the queued one", async () => {+ it("keeps half-typed composer text after the queued text when a stop returns it", async () => {await renderChat();await submit("build me a workflow");await waitFor(() => expect(postStreaming).toHaveBeenCalledTimes(1));await deliverFirstFrame();await submit("queued answer");- // Half-typed replacement, never submitted.+ // Half-typed addition, never submitted.fireEvent.change(textarea(), {- target: { value: "half typed replacement" },+ target: { value: "half typed addition" },});await act(async () => useCopilotActionStore.getState().requestCancel());- expect(textarea().value).toBe("half typed replacement");+ expect(textarea().value).toBe("queued answer\nhalf typed addition");});- it("replaces the parked prompt rather than swallowing the second send", async () => {+ it("Remove discards the queued message and hands its file back to the tray", async () => {await renderChat();await submit("build me a workflow");await waitFor(() => expect(postStreaming).toHaveBeenCalledTimes(1));- await submit("wrong code 000000");- await submit("correct code 123456");+ await attachSpreadsheet("queued.csv");+ await submit("parse this sheet");++ fireEvent.click(+ queuedStrip().getByRole("button", { name: "Remove queued message" }),+ );++ expect(screen.queryByTestId("copilot-queued-message")).toBeNull();+ expect(textarea().value).toBe("");+ expect(+ screen.getByRole("button", { name: "Remove queued.csv" }),+ ).toBeTruthy();+ await completeOldestStream("done");+ await act(async () => {});+ expect(postStreaming).toHaveBeenCalledTimes(1);+ });++ it("adds to the parked prompt rather than replacing or swallowing the second send", async () => {+ await renderChat();+ await submit("build me a workflow");+ await waitFor(() => expect(postStreaming).toHaveBeenCalledTimes(1));+ await submit("use the staging site");+ await submit("and log in first");- expect(screen.queryByText("wrong code 000000")).toBeNull();- expect(screen.getAllByText("correct code 123456")).toHaveLength(1);// Still exactly one parked prompt, and still no second stream.expect(postStreaming).toHaveBeenCalledTimes(1);await completeOldestStream("done");await waitFor(() => expect(postStreaming).toHaveBeenCalledTimes(2));- expect(streamCalls[1]!.body.message).toBe("correct code 123456");+ expect(streamCalls[1]!.body.message).toBe(+ "use the staging site\nand log in first",+ );+ expect(screen.queryByTestId("copilot-queued-message")).toBeNull();});});diff --git a/skyvern-frontend/src/routes/workflows/copilot/WorkflowCopilotChat.reviewGate.test.tsx b/skyvern-frontend/src/routes/workflows/copilot/WorkflowCopilotChat.reviewGate.test.tsxindex 1677996c3..facc41912 100644--- a/skyvern-frontend/src/routes/workflows/copilot/WorkflowCopilotChat.reviewGate.test.tsx+++ b/skyvern-frontend/src/routes/workflows/copilot/WorkflowCopilotChat.reviewGate.test.tsx@@ -7953,6 +7953,68 @@ describe("WorkflowCopilotChat — g2 review gate", () => {expect(screen.queryByText("Tested")).toBeNull();});+ it("does not clear another chat's persisted proposal when Reject's known chat returns 404", async () => {+ const otherChatProposal = proposedWorkflowPayload({+ title: "Other chat's draft",+ });+ const persistedProposals = new Map<string, Record<string, unknown> | null>([+ ["chat-1", proposedWorkflowPayload()],+ ["chat-2", otherChatProposal],+ ]);+ historyGet.mockResolvedValueOnce(historyResponse);+ historyGet.mockImplementation(() =>+ Promise.resolve({+ data: {+ ...historyResponse.data,+ workflow_copilot_chat_id: "chat-2",+ proposed_workflow: persistedProposals.get("chat-2") ?? null,+ },+ }),+ );+ cancelPost.mockImplementation(+ (+ _path: string,+ body: {+ workflow_copilot_chat_id: string;+ owner_turn_id?: string | null;+ revision?: number | null;+ },+ ) => {+ if (body.workflow_copilot_chat_id === "chat-1") {+ return Promise.reject({ response: { status: 404 } });+ }+ // The backend infers legacy proposal tokens from the named row, which is+ // exactly why a tokenless retry against chat-2 would clear this proposal.+ if (body.owner_turn_id === null && body.revision === null) {+ persistedProposals.set(body.workflow_copilot_chat_id, null);+ return Promise.resolve({ data: {} });+ }+ return Promise.reject({ response: { status: 409 } });+ },+ );++ await renderChat();+ await waitFor(() => expect(historyGet).toHaveBeenCalledTimes(1));+ await submit("build me a workflow");+ await waitFor(() => expect(postStreaming).toHaveBeenCalledTimes(1));+ await act(async () => {+ // Legacy proposals do not have owner/revision tokens to scope the clear.+ streamCalls[0]!.onMessage(+ proposalResponse("Draft ready.", {+ proposed_workflow_metadata: null,+ }),+ );+ streamCalls[0]!.resolve();+ });++ await act(async () => {+ fireEvent.click(screen.getByRole("button", { name: "Reject" }));+ await new Promise((resolve) => setTimeout(resolve, 0));+ });++ expect(persistedProposals.get("chat-2")).toEqual(otherChatProposal);+ });+it("clears the proposal and shows a discarded receipt on a late Reject", async () => {await renderChat();@@ -8510,45 +8572,94 @@ describe("WorkflowCopilotChat — g2 review gate", () => {).toBeGreaterThan(0);});- it("names the unsaved canvas edits that a saved-gate retry would discard", async () => {- // `saved`'s Try again REPLACES the canvas with the workflow the server confirmed. The card- // already said "this replaces what's on the canvas" generically; it said the same thing when- // there was nothing to lose and when there was. The editor already tracks the difference -- // `hasChanges`, guarded by beginInternalUpdate so our own applies do not set it - and- // `reconcileCanonicalWorkflow` already refuses to overwrite on exactly that signal. This card- // names the cost while the work still exists.- const onWorkflowUpdate = vi.fn(() => {- throw new Error("editor could not load it");+ it("does not claim unsaved changes after a failed turn restores the clean snapshot", async () => {+ const onWorkflowUpdate = vi.fn<NonNullable<ChatProps["onWorkflowUpdate"]>>(+ (_workflow, options) => {+ if (options?.persisted) {+ throw new Error("editor could not load the saved workflow");+ }+ },+ );+ const restore = vi.fn((snapshot: EditorStateSnapshot) => {+ const result = restoreLive(snapshot);+ // A restore can leave the editor's coarse dirty signal set even though the+ // snapshot is the clean canonical graph. The card must not call that a user edit.+ if (result === "restored") {+ useWorkflowHasChangesStore.getState().setHasChanges(true);+ }+ return result;});- await renderChat({ onWorkflowUpdate });+ await renderChat({ onWorkflowUpdate, onRestore: restore });await submit("build me a workflow");- await waitFor(() => expect(postStreaming).toHaveBeenCalledTimes(1));+ await waitFor(() => expect(streamCalls).toHaveLength(1));+ const stagedWorkflow = proposedWorkflowPayload({ title: "Staged draft" });await act(async () => {- streamCalls[0]!.onMessage(proposalResponse("Draft ready."));- streamCalls[0]!.resolve();+ streamCalls[0]!.onMessage({+ type: "turn_start",+ turn_id: "turn-1",+ turn_index: 0,+ mode: "build",+ timestamp: "2026-07-09T00:00:00Z",+ });+ streamCalls[0]!.onMessage({+ type: "workflow_draft",+ workflow: stagedWorkflow,+ block_count: 0,+ block_labels: [],+ timestamp: "2026-07-09T00:00:01Z",+ });});- const savedWorkflow = proposedWorkflowPayload({- workflow_id: "wf_saved",- }) as unknown as WorkflowApiResponse;- cancelPost.mockResolvedValueOnce({ data: savedWorkflow });+ expect(onWorkflowUpdate).toHaveBeenLastCalledWith(+ stagedWorkflow,+ expect.objectContaining({ midTurnDraft: true }),+ );+ vi.useFakeTimers();await act(async () => {- fireEvent.click(screen.getByRole("button", { name: "Accept" }));+ streamCalls[0]!.onMessage({+ type: "error",+ turn_id: "turn-1",+ error: "Build failed",+ });+ streamCalls[0]!.resolve();});- expect(await screen.findByText("Saved, not shown")).toBeTruthy();+ expect(restore).not.toHaveBeenCalled();+ finishTurnHistory();+ await act(async () => vi.advanceTimersByTimeAsync(2_000));+ expect(restore).toHaveBeenCalledOnce();+ expect(editorNodes.find((node) => node.id === "loop")?.data).toMatchObject({+ loopValue: "unsaved_items",+ loopVariableReference: "{{ item }}",+ });+ expect(useWorkflowHasChangesStore.getState().hasChanges).toBe(true);+ vi.useRealTimers();- // NEGATIVE ARM: a clean canvas has nothing to lose, so the card must not invent a cost.+ await submit("try a different approach");+ await waitFor(() => expect(streamCalls).toHaveLength(2));await act(async () => {- useWorkflowHasChangesStore.setState({ hasChanges: false });+ streamCalls[1]!.onMessage(+ proposalResponse("Draft ready.", {+ turn_id: "turn-2",+ narrative_payload: proposalNarrativePayload({+ turnId: "turn-2",+ turnIndex: 1,+ }),+ }),+ );+ streamCalls[1]!.resolve();+ });+ cancelPost.mockResolvedValueOnce({+ data: proposedWorkflowPayload({ workflow_id: "wf_saved" }),});- // Scoped to the ADDED sentence: the card's base copy already ends with "...which discards- // unsaved canvas edits", so a loose match here would assert against the wrong text.- expect(screen.queryByText(/canvas has unsaved changes/i)).toBeNull();-- // POSITIVE ARM: the user repaired something under the fence. Now it has to say so.await act(async () => {- useWorkflowHasChangesStore.setState({ hasChanges: true });+ fireEvent.click(screen.getByRole("button", { name: "Accept" }));});- expect(await screen.findByText(/canvas has unsaved changes/i)).toBeTruthy();+ expect(await screen.findByText("Saved, not shown")).toBeTruthy();+ const warning = screen.getByRole("alert").textContent;+ expect(warning).not.toMatch(/(?:has|have) unsaved/i);+ expect(warning).toMatch(/replaces.*canvas/i);+ expect(+ screen.getByRole("button", { name: "Try again" }).matches(":disabled"),+ ).toBe(false);});it("does not let a stale reload retry resurrect the card a newer one cleared", async () => {diff --git a/skyvern-frontend/src/routes/workflows/copilot/WorkflowCopilotChat.runGrounding.test.tsx b/skyvern-frontend/src/routes/workflows/copilot/WorkflowCopilotChat.runGrounding.test.tsxindex 08d7aadc2..0aa97770a 100644--- a/skyvern-frontend/src/routes/workflows/copilot/WorkflowCopilotChat.runGrounding.test.tsx+++ b/skyvern-frontend/src/routes/workflows/copilot/WorkflowCopilotChat.runGrounding.test.tsx@@ -1818,12 +1818,9 @@ describe("WorkflowCopilotChat — run grounding bridge", () => {const view = render(chatUi(props));await waitFor(() =>expect(- screen.getByText("Diagnose run wr_queued and repair the workflow."),- ).toBeTruthy(),+ screen.getByTestId("copilot-queued-message").textContent,+ ).toContain("Diagnose run wr_queued and repair the workflow."),);- expect(- screen.getByText("Prompt queued. Waiting for live browser..."),- ).toBeTruthy();expect(postStreaming).not.toHaveBeenCalled();view.rerender(diff --git a/skyvern-frontend/src/routes/workflows/copilot/WorkflowCopilotChat.tsx b/skyvern-frontend/src/routes/workflows/copilot/WorkflowCopilotChat.tsxindex 5dee33f63..39ce6a62f 100644--- a/skyvern-frontend/src/routes/workflows/copilot/WorkflowCopilotChat.tsx+++ b/skyvern-frontend/src/routes/workflows/copilot/WorkflowCopilotChat.tsx@@ -51,7 +51,6 @@ import {Cross2Icon,ChevronDownIcon,ArrowUpIcon,- Pencil1Icon,FileIcon,UploadIcon,PlusIcon,@@ -132,6 +131,7 @@ import { selectAutoBoundReceiptIndexes } from "./autoBoundReceiptIndexes";import { shouldWaitForLiveBrowser } from "./browserReadiness";import {QueuedPromptReason,+ appendQueuedText,resolveDrainAction,resolveSendAction,} from "./sendQueue";@@ -140,6 +140,7 @@ import { InstantAckPlaceholder, NarrativeView } from "./NarrativeView";import { CopilotMarkdown } from "./CopilotMarkdown";import { FeedbackThumbs } from "@/components/feedback/FeedbackThumbs";import { CopilotWorkingStatus } from "./CopilotWorkingStatus";+import { QueuedMessageStrip } from "./QueuedMessageStrip";import {RecordingRefinementProgressCard,type RecordingRefinementStatus,@@ -797,7 +798,12 @@ const snapshotRecording = (): RecordingSnapshot => {};};+// Only "typed" text is added to by a later send; a programmatic message (account choice, block+// rebuild, armed action) is replaced, and a product receipt has no text to edit.+type QueuedPromptOrigin = "typed" | "programmatic" | "product";+type QueuedPrompt = {+ origin: QueuedPromptOrigin;selectedConnectedAccountId?: string;id: string;content: string;@@ -1744,6 +1750,13 @@ export function WorkflowCopilotChat({// 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);+ // Composer text a send just took. A second Enter from a stale closure (same tick, or while+ // dictation finalizes) still reads it, and would queue or append it a second time. Held while+ // the composer stays empty, since only a stale closure can offer that text then.+ const consumedComposerTextRef = useRef<string | null>(null);+ useEffect(() => {+ if (inputValue !== "") consumedComposerTextRef.current = null;+ }, [inputValue]);// What the turn was asked to do. completedNormally starts false and is set// only on a clean terminal, so every other exit drains the queue as before.const lastTurnRef = useRef<{@@ -2531,14 +2544,6 @@ export function WorkflowCopilotChat({(state.authoringInProgress &&(!recordingAuthoringActive || recordingIsFinishing)),);- // The editor already tracks this. It is NOT user-authorship: Workspace sets it on any apply- // without `persisted`, the copilot's own mid-turn draft included, and beginInternalUpdate does- // not gate that branch - so the card says "the canvas has unsaved changes", never "your edits".- // What it does attest is that something unsaved is on the canvas, which is what Try again- // discards - the same fact reconcileCanonicalWorkflow already refuses to overwrite on.- const canvasHasEdits = useWorkflowHasChangesStore(- (state) => state.hasChanges,- );const hasInitializedPosition = useRef(false);const hasAutoSentRef = useRef(false);const isWaitingForLiveBrowser = shouldWaitForLiveBrowser({@@ -5791,10 +5796,10 @@ export function WorkflowCopilotChat({} catch (error) {if (!isCopilotTurnCurrent(reservation)) return false;const status = getErrorStatus(error);- // A caller that NAMES its chat must not fall back here: the latest chat is someone else's- // row, and clearing it deletes that chat's pending review. Only Reject reaches this today,- // and it names nothing; re-add that guard with any caller that does.- if (status === 404) {+ // A known chat must not fall back here: the latest chat can be someone else's row, and+ // clearing it deletes that chat's pending review. Retry only when this clear began before+ // the pane had a chat ID to name.+ if (status === 404 && !startingChatId) {try {const refreshedChatId = await fetchLatestChatId();if (refreshedChatId && refreshedChatId !== chatId) {@@ -5977,41 +5982,44 @@ export function WorkflowCopilotChat({const blockGenInFlightRef = useRef(false);// Disposal path that hands the queued text back to the composer as an- // editable draft; the drain effect's duplicate drop is the one path that- // discards instead. Reads the synchronous ref, not state, so a stop can- // clear the queue before isLoading flips and the drain effect runs.- const restoreQueuedPromptToComposer = useCallback(() => {- const queued = queuedPromptRef.current;- if (!queued) {- return;- }+ // editable draft; Remove (keepText: false) and the drain effect's duplicate+ // drop are the paths that discard it. Reads the synchronous ref, not state, so+ // a stop can clear the queue before isLoading flips and the drain effect runs.+ const restoreQueuedPromptToComposer = useCallback(+ ({ keepText = true }: { keepText?: boolean } = {}) => {+ const queued = queuedPromptRef.current;+ if (!queued) {+ return;+ }- // A product action's queued text is the server's receipt, not words the user wrote, so- // handing it back as an editable draft would repost it as a user message.- const wasProductAuthoredAction = isProductAuthoredAction(- productActionRef.current,- );+ // A product action's queued text is the server's receipt, not words the user wrote, so+ // handing it back as an editable draft would repost it as a user message.+ const wasProductAuthoredAction = isProductAuthoredAction(+ productActionRef.current,+ );- updateQueuedPrompt(null);- // Drop the queued block-build target and end-to-end action so neither leaks into the next- // message. Deferring paths (queue_working / queue_live_browser) keep the action armed on- // purpose; only abandoning the message disarms it.- blockBuildTargetLabelRef.current = null;- productActionRef.current = null;- setMessages((prev) => prev.filter((message) => message.id !== queued.id));- // Text already in the composer is the newer intent — the user was part way- // through replacing the queued message — so it wins over what comes back.- if (!wasProductAuthoredAction) {- setInputValue((current) => (current.trim() ? current : queued.content));- }- // The files belong to the message being edited, so they return to the tray with its text.- // Without this the resubmitted message silently goes out with no attachment.- returnFilesToTray(queued.attachments ?? []);- window.requestAnimationFrame(() => {- textareaRef.current?.focus();- adjustTextareaHeight();- });- }, [adjustTextareaHeight, returnFilesToTray, updateQueuedPrompt]);+ updateQueuedPrompt(null);+ // Drop the queued block-build target and end-to-end action so neither leaks into the next+ // message. Deferring paths (queue_working / queue_live_browser) keep the action armed on+ // purpose; only abandoning the message disarms it.+ blockBuildTargetLabelRef.current = null;+ productActionRef.current = null;+ setMessages((prev) => prev.filter((message) => message.id !== queued.id));+ // Text half-typed in the composer was going to be added to the queued message, so it+ // follows the queued text rather than replacing it.+ if (keepText && !wasProductAuthoredAction) {+ setInputValue((current) => appendQueuedText(queued.content, current));+ }+ // The files belong to the queued message, so they return to the tray whether it is edited+ // or removed. Without this the resubmitted message silently goes out with no attachment.+ returnFilesToTray(queued.attachments ?? []);+ window.requestAnimationFrame(() => {+ textareaRef.current?.focus();+ adjustTextareaHeight();+ });+ },+ [adjustTextareaHeight, returnFilesToTray, updateQueuedPrompt],+ );const cancelSend = useCallback(async (@@ -6489,6 +6497,18 @@ export function WorkflowCopilotChat({prev.filter((item) => item.status !== "error"),);};+ if (composerSend && consumedComposerTextRef.current === candidate) {+ return false;+ }+ const incomingOrigin = (): QueuedPromptOrigin =>+ isProductAuthoredAction(productActionRef.current)+ ? "product"+ : options.selectedConnectedAccountId !== undefined ||+ options.idempotencyKey !== undefined ||+ blockBuildTargetLabelRef.current !== null ||+ productActionRef.current !== null+ ? "programmatic"+ : "typed";let action = resolveSendAction({inFlight: inFlightRef.current || recoveredTurnOwnerRef.current !== null,hasQueuedPrompt: Boolean(queuedPromptRef.current),@@ -6554,6 +6574,25 @@ export function WorkflowCopilotChat({});return false;}+ const withQueuedFiles = (tray: CopilotAttachedFile[]) => {+ const queuedFiles = queuedPromptRef.current?.attachments ?? [];+ const queuedFileIds = new Set(queuedFiles.map((item) => item.file_id));+ return [+ ...queuedFiles,+ ...tray.filter((item) => !queuedFileIds.has(item.file_id)),+ ];+ };+ // Refuse before dictation is finalized below, which consumes the recording.+ if (action === "append_queued" && composerSend) {+ const combinedCount = withQueuedFiles(attachments).length;+ if (combinedCount > ATTACHMENT_COUNT_LIMIT) {+ toast({+ title: "Too many files",+ description: `A message can carry up to ${ATTACHMENT_COUNT_LIMIT} files. Remove ${combinedCount - ATTACHMENT_COUNT_LIMIT} to add these to the queued message.`,+ });+ return false;+ }+ }let messageAudioBlob = options.audioBlob ?? null;if (!messageAudioBlob && messageOverride === undefined) {@@ -6562,6 +6601,10 @@ export function WorkflowCopilotChat({}messageAudioBlob = messageAudioBlob ?? takeSpeechAudioBlob();}+ // A second Enter pressed while dictation finalized may have queued this text already.+ if (composerSend && consumedComposerTextRef.current === candidate) {+ return false;+ }if (composerSend) {// The tray stays interactive while dictation finalizes, so a file removed then must not go.sentAttachments = attachmentsRef.current;@@ -6583,52 +6626,60 @@ export function WorkflowCopilotChat({});}- if (action === "replace_queued") {+ if (action === "append_queued") {const queued = queuedPromptRef.current;if (!queued) {return false;}- const replacedAttachments =- composerSend && sentAttachments.length > 0- ? sentAttachments- : queued.attachments;- // New text: the block-build scope and the end-to-end action belonged to the message being- // replaced. Carrying the action over would run the whole workflow for real on text the user- // wrote to say something else.+ const combinedAttachments = composerSend+ ? withQueuedFiles(sentAttachments)+ : (queued.attachments ?? []);+ if (combinedAttachments.length > ATTACHMENT_COUNT_LIMIT) {+ toast({+ title: "Too many files",+ description: `A message can carry up to ${ATTACHMENT_COUNT_LIMIT} files. Remove ${combinedAttachments.length - ATTACHMENT_COUNT_LIMIT} to add these to the queued message.`,+ });+ return false;+ }+ // Only typed text is added to typed text; anything programmatic replaces as it always has.+ const addsToUserText = composerSend && queued.origin === "typed";+ // Until cleared below, the armed refs are the queued message's, not a composer send's.+ const origin = composerSend ? "typed" : incomingOrigin();+ // New text: the block-build scope and the end-to-end action belonged to the message as it+ // was queued. Carrying the action over would run the whole workflow for real on text the+ // user added to say something else.blockBuildTargetLabelRef.current = null;productActionRef.current = null;+ const content = addsToUserText+ ? appendQueuedText(queued.content, candidate)+ : candidate;updateQueuedPrompt({...queued,- content: candidate,- audioBlob: messageAudioBlob,+ origin,+ content,+ audioBlob: addsToUserText+ ? (messageAudioBlob ?? queued.audioBlob)+ : messageAudioBlob,idempotencyKey: options.idempotencyKey,selectedConnectedAccountId: options.selectedConnectedAccountId,- attachments: replacedAttachments,+ attachments: combinedAttachments,recording: options.recording ?? snapshotRecording(),});if (composerSend) {clearSentTray();- // Files the replaced queued message carried and the new one does not were never sent,- // so they return to the tray rather than becoming unreachable uploads.- const kept = new Set(- (replacedAttachments ?? []).map((item) => item.file_id),- );- returnFilesToTray(- (queued.attachments ?? []).filter(- (item) => !kept.has(item.file_id),- ),- );+ consumedComposerTextRef.current = candidate;}+ // Only a Home handoff has a bubble while queued; keep it in step with what will be sent.setMessages((prev) =>prev.map((message) =>message.id === queued.id? {...message,sender: "user",- content: candidate,+ content,attachedFiles:- replacedAttachments && replacedAttachments.length > 0- ? replacedAttachments+ combinedAttachments.length > 0+ ? combinedAttachments: undefined,}: message,@@ -6649,6 +6700,7 @@ export function WorkflowCopilotChat({crypto.randomUUID();updateQueuedPrompt({id: queuedId,+ origin: incomingOrigin(),content: candidate,reason,audioBlob: messageAudioBlob,@@ -6660,38 +6712,12 @@ export function WorkflowCopilotChat({if (composerSend) {clearSentTray();}- // 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 && !options.optimisticMessageId) {- setMessages((prev) => [- ...prev,- {- id: queuedId,- sender: echoSenderForArmedAction(),- content: candidate,- attachedFiles:- sentAttachments.length > 0 ? sentAttachments : undefined,- },- ]);- }+ if (composerSend) consumedComposerTextRef.current = candidate;+ // The queued strip above the composer stands in for the message until it is delivered;+ // the send path adds its bubble then.if (messageOverride === undefined) {setInputValue("");}- 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 true;}@@ -6754,33 +6780,33 @@ export function WorkflowCopilotChat({lastFollowedLabelRef.current = null;pendingMessageId.current = userMessageId;- if (!options.queuedMessageId && !options.optimisticMessageId) {- setMessages((prev) => [...prev, userMessage]);- } else {- // Also when the filtered list is empty: a queued bubble must not keep showing files the- // request did not carry.- setMessages((prev) =>- prev.map((message) =>- message.id === userMessageId- ? {- ...message,- kind: recordingRefinement- ? "recording_refinement"- : message.kind,- recordingRefinement:- recordingRefinement ?? message.recordingRefinement,- attachedFiles:- sentAttachments.length > 0 ? sentAttachments : undefined,- }- : message,- ),- );- }+ // A queued message gets its bubble here, at delivery. Only a Home handoff already has one.+ setMessages((prev) =>+ prev.some((message) => message.id === userMessageId)+ ? prev.map((message) =>+ message.id === userMessageId+ ? {+ ...message,+ kind: recordingRefinement+ ? "recording_refinement"+ : message.kind,+ recordingRefinement:+ recordingRefinement ?? message.recordingRefinement,+ // Also when the filtered list is empty: the bubble must not keep showing+ // files the request did not carry.+ attachedFiles:+ sentAttachments.length > 0 ? sentAttachments : undefined,+ }+ : message,+ )+ : [...prev, userMessage],+ );const messageContent = candidate;let chatIdForRequest = workflowCopilotChatId;if (messageOverride === undefined && !options.queuedMessageId) {setInputValue("");}+ if (composerSend) consumedComposerTextRef.current = candidate;setIsLoading(true);inFlightRef.current = true;sendEpoch.current += 1;@@ -8642,13 +8668,6 @@ export function WorkflowCopilotChat({: null;}- const queuedPromptWaitingStatus =- queuedPrompt?.reason === "working"- ? "Queued — sends when this turn finishes."- : "Prompt queued. Waiting for live browser...";- // queuedPromptWaitingStatus already surfaces via the composer chip- // (working reason) or the queued bubble's footer (live_browser reason);- // don't duplicate it as a second status line above the composer.const browserStatusText = isWaitingForLiveBrowser? "Live browser is starting. Your next send will wait until it connects.": null;@@ -8729,15 +8748,13 @@ export function WorkflowCopilotChat({const showWorkingRow = isLoading;// A live_browser-reason queued prompt parks with no active turn to stop, so// an empty composer's morph button would render as a guaranteed no-op "Send".- // With text typed it does act — it rewrites the parked prompt.+ // With text typed it does act — it adds to the parked prompt.const waitingOnQueueOnly =queuedPrompt?.reason === "live_browser" && !hasComposerText;- // When the initial history load drops the queued bubble, the composer chip- // takes over its live_browser status/Cancel (footer-else-chip).- const queuedBubbleOrphaned = Boolean(- queuedPrompt &&- queuedPrompt.reason === "live_browser" &&- !messages.some((message) => message.id === queuedPrompt.id),+ // A Home handoff already shows its queued prompt as a bubble with its own footer, so the strip+ // would repeat it.+ const showQueuedStrip = Boolean(+ queuedPrompt && !messages.some((message) => message.id === queuedPrompt.id),);const showsStopGlyph =isStopping || (turnObservablyRunning && !hasComposerText);@@ -8756,7 +8773,9 @@ export function WorkflowCopilotChat({: morphButtonPending? "Starting…": queuedPrompt && hasComposerText- ? "Replace queued message"+ ? queuedPrompt.origin === "typed"+ ? "Add to the queued message"+ : "Replace queued message": !turnObservablyRunning? isLoading? "Queue for next turn"@@ -9056,8 +9075,7 @@ export function WorkflowCopilotChat({}if (message.kind === "run_lifecycle" ||- (message.sender === "product" &&- message.id !== queuedPrompt?.id)+ message.sender === "product") {return (<RunLifecycleLine@@ -9205,7 +9223,6 @@ export function WorkflowCopilotChat({<ProposalRunFactsLine facts={pendingProposalRun} />) : null}<ReviewGateCard- canvasHasEdits={canvasHasEdits}turn={message.narrative}pending={index === gateIndex && gateHasSubject}verdict={getReviewGateVerdict(@@ -9377,11 +9394,13 @@ export function WorkflowCopilotChat({: message}queuedStatus={- queuedPrompt?.reason === "live_browser" &&- queuedPrompt.id === message.id+ queuedPrompt?.id === message.id? {- text: queuedPromptWaitingStatus,- onCancel: restoreQueuedPromptToComposer,+ text:+ queuedPrompt.reason === "working"+ ? "Queued — sends when this turn finishes."+ : "Prompt queued. Waiting for live browser...",+ onCancel: () => restoreQueuedPromptToComposer(),}: null}@@ -9393,7 +9412,6 @@ export function WorkflowCopilotChat({) : null}{isGateOwnerOrLast ? (<ReviewGateCard- canvasHasEdits={canvasHasEdits}pendingverdict={getReviewGateVerdict(gateOwnerNarrative,@@ -9464,7 +9482,6 @@ export function WorkflowCopilotChat({<ProposalRunFactsLine facts={pendingProposalRun} />) : null}<ReviewGateCard- canvasHasEdits={canvasHasEdits}pendingverdict={getReviewGateVerdict(undefined, proposedWorkflow)}settled={null}@@ -9773,31 +9790,7 @@ export function WorkflowCopilotChat({</div>) : null}{showWorkingRow ? (- <CopilotWorkingStatus- queued={Boolean(queuedPrompt)}- onDismissQueued={restoreQueuedPromptToComposer}- />- ) : null}- {!showWorkingRow &&- queuedPrompt &&- (queuedPrompt.reason === "working" || queuedBubbleOrphaned) ? (- // Same state as the working row's queued pill, which a user on this- // flag path also sees — so it takes the same tinted-pill grammar- // rather than a bordered box, and the same edit glyph.- <div className="mb-2 flex items-center gap-2 rounded-full bg-slate-400/[0.12] py-0.5 pl-2.5 pr-1 text-xs text-muted-foreground">- <ReloadIcon className="h-3 w-3 shrink-0 animate-spin" />- <span className="shrink-0 font-medium text-foreground">Queued</span>- <span className="flex-1 truncate">{queuedPromptWaitingStatus}</span>- <button- type="button"- onClick={restoreQueuedPromptToComposer}- title="Edit queued message"- aria-label="Edit queued message"- className="shrink-0 rounded px-1 text-muted-foreground hover:text-accent-foreground"- >- <Pencil1Icon className="h-3 w-3" />- </button>- </div>+ <CopilotWorkingStatus queued={Boolean(queuedPrompt)} />) : null}{inputStatusText && !showWorkingRow ? (<div@@ -9874,6 +9867,21 @@ export function WorkflowCopilotChat({))}</div>) : null}+ <span className="sr-only" aria-live="polite">+ {queuedPrompt && !showWorkingRow ? "Message queued" : ""}+ </span>+ {showQueuedStrip && queuedPrompt ? (+ <QueuedMessageStrip+ text={queuedPrompt.content}+ attachments={queuedPrompt.attachments ?? []}+ onEdit={+ queuedPrompt.origin === "product"+ ? undefined+ : () => restoreQueuedPromptToComposer()+ }+ onRemove={() => restoreQueuedPromptToComposer({ keepText: false })}+ />+ ) : null}<divrole="group"aria-label="Copilot message composer"@@ -9881,7 +9889,10 @@ export function WorkflowCopilotChat({onDragOver={handleComposerDragOver}onDragLeave={handleComposerDragLeave}onDrop={handleComposerDrop}- className="relative flex items-end gap-1.5 rounded-lg border border-input bg-slate-elevation2 py-1.5 pl-3 pr-2.5 transition-colors focus-within:border-ring"+ className={cn(+ "relative flex items-end gap-1.5 rounded-lg border border-input bg-slate-elevation2 py-1.5 pl-3 pr-2.5 transition-colors focus-within:border-ring",+ showQueuedStrip && "rounded-t-none",+ )}>{isFileDragging ? (<div@@ -9896,7 +9907,11 @@ export function WorkflowCopilotChat({<textarearef={setTextareaRef}placeholder={composerPlaceholder({- queuedPrompt: Boolean(queuedPrompt),+ queuedPrompt: queuedPrompt+ ? queuedPrompt.origin === "typed"+ ? "add"+ : "replace"+ : null,isLoading,isWaitingForLiveBrowser,latestTurnIsAsk,diff --git a/skyvern-frontend/src/routes/workflows/copilot/cards/ReviewGateCard.tsx b/skyvern-frontend/src/routes/workflows/copilot/cards/ReviewGateCard.tsxindex 3c416ff7b..707f24ee1 100644--- a/skyvern-frontend/src/routes/workflows/copilot/cards/ReviewGateCard.tsx+++ b/skyvern-frontend/src/routes/workflows/copilot/cards/ReviewGateCard.tsx@@ -148,12 +148,6 @@ interface ReviewGateCardProps {gateId?: string;// Transient highlight when the pending-proposal chip scrolls to this gate.flash?: boolean;- // The canvas holds unsaved changes. `saved`'s Try again REPLACES the canvas with the workflow- // the server confirmed, so they go with it - a destructive control has to say so while the work- // still exists. Deliberately not phrased as the USER's edits: the editor sets this flag on any- // apply without `persisted`, including the copilot's own mid-turn draft, so authorship is not- // something this flag can attest.- canvasHasEdits?: boolean;}const REVIEW_SECTIONS = [@@ -203,7 +197,6 @@ export function ReviewGateCard({onRetry,gateId,flash = false,- canvasHasEdits = false,}: ReviewGateCardProps) {const draft = turn?.draft ?? null;const gateStatus = failure@@ -325,12 +318,6 @@ export function ReviewGateCard({<span className="min-w-0 flex-1 text-[11px] leading-snug text-muted-foreground">{(!hasProposal && gateStatus.lineWithoutProposal) ||gateStatus.line}- {failure === "saved" && canvasHasEdits ? (- <strong className="font-semibold text-foreground">- {" "}- The canvas has unsaved changes; Try again discards them.- </strong>- ) : null}</span>{/* In recover and reload this is the only live control on the card, so it is abutton in its own right and sits outside the disabled action row. */}diff --git a/skyvern-frontend/src/routes/workflows/copilot/composerPlaceholder.test.ts b/skyvern-frontend/src/routes/workflows/copilot/composerPlaceholder.test.tsindex 6a9fddf4f..08238f1fd 100644--- a/skyvern-frontend/src/routes/workflows/copilot/composerPlaceholder.test.ts+++ b/skyvern-frontend/src/routes/workflows/copilot/composerPlaceholder.test.ts@@ -3,7 +3,7 @@ import { describe, expect, it } from "vitest";import { composerPlaceholder } from "./composerPlaceholder";const base = {- queuedPrompt: false,+ queuedPrompt: null,isLoading: false,isWaitingForLiveBrowser: false,latestTurnIsAsk: false,diff --git a/skyvern-frontend/src/routes/workflows/copilot/composerPlaceholder.ts b/skyvern-frontend/src/routes/workflows/copilot/composerPlaceholder.tsindex bfc12f661..c91b81171 100644--- a/skyvern-frontend/src/routes/workflows/copilot/composerPlaceholder.ts+++ b/skyvern-frontend/src/routes/workflows/copilot/composerPlaceholder.ts@@ -6,12 +6,14 @@ export function composerPlaceholder({isWaitingForLiveBrowser,latestTurnIsAsk,}: {- queuedPrompt: boolean;+ // Whether a send adds to the queued message or replaces it (a programmatic one).+ queuedPrompt: "add" | "replace" | null;isLoading: boolean;isWaitingForLiveBrowser: boolean;latestTurnIsAsk: boolean;}): string {- if (queuedPrompt) return "Type to replace the queued message…";+ if (queuedPrompt === "add") return "Add to the queued message…";+ if (queuedPrompt === "replace") return "Type to replace the queued message…";if (isLoading) return "Type to queue a message…";if (isWaitingForLiveBrowser) return "Type a prompt to send when ready...";// While a question is pending the composer is the answer path for anything the card cannotdiff --git a/skyvern-frontend/src/routes/workflows/copilot/sendQueue.test.ts b/skyvern-frontend/src/routes/workflows/copilot/sendQueue.test.tsindex 42c409e5a..9a0f0c7ea 100644--- a/skyvern-frontend/src/routes/workflows/copilot/sendQueue.test.ts+++ b/skyvern-frontend/src/routes/workflows/copilot/sendQueue.test.ts@@ -25,12 +25,12 @@ describe("resolveSendAction", () => {});// A parked turn (awaiting the user) never ends, so a swallowed second send- // left the composer permanently dead. Rewriting the parked prompt keeps the+ // left the composer permanently dead. Adding to the parked prompt keeps the// one-queued-prompt invariant without the dead end.- it("rewrites the parked prompt when a second send arrives", () => {+ it("adds to the parked prompt when a second send arrives", () => {expect(resolveSendAction(sendInput({ hasQueuedPrompt: true, isDrain: false })),- ).toBe("replace_queued");+ ).toBe("append_queued");});it("still returns noop for an empty candidate while a prompt is queued", () => {diff --git a/skyvern-frontend/src/routes/workflows/copilot/sendQueue.ts b/skyvern-frontend/src/routes/workflows/copilot/sendQueue.tsindex a25a1a4b7..43782c9a6 100644--- a/skyvern-frontend/src/routes/workflows/copilot/sendQueue.ts+++ b/skyvern-frontend/src/routes/workflows/copilot/sendQueue.ts@@ -9,7 +9,7 @@ export type SendAction =| "send"| "queue_working"| "queue_live_browser"- | "replace_queued"+ | "append_queued"| "noop";type ResolveSendInput = {@@ -39,11 +39,11 @@ export function resolveSendAction({if (!candidate.trim()) {return "noop";}- // One queued prompt at a time still holds — a second send rewrites the one+ // One queued prompt at a time still holds — a second send adds to the one// that's parked rather than being swallowed, so the composer is never a// dead box while a turn is parked waiting on the user.if (hasQueuedPrompt && !isDrain) {- return "replace_queued";+ return "append_queued";}if (inFlight) {return "queue_working";@@ -61,6 +61,11 @@ export function resolveSendAction({return "send";}+// Queued text and anything added to it stay one message, in the order typed.+export function appendQueuedText(queued: string, addition: string): string {+ return addition.trim() ? `${queued}\n${addition}` : queued;+}+export type DrainAction =| "drain_skip_queue"| "drain_requeue"diff --git a/skyvern/browser_extension/extension/build_hash.json b/skyvern/browser_extension/extension/build_hash.jsonindex af43fdc27..52f103fcf 100644--- a/skyvern/browser_extension/extension/build_hash.json+++ b/skyvern/browser_extension/extension/build_hash.json@@ -1,3 +1,3 @@{- "sha256": "729e1b1fd61e61e519d501976997e6a2e3d20c1aebd2f8d2faa6ab8cdd17c988"+ "sha256": "df25fdc72514f593b3699c34801c301b9cfeaa4706a6a64854be949f0b55b309"}diff --git a/skyvern/browser_extension/extension/manifest.json b/skyvern/browser_extension/extension/manifest.jsonindex 86778878c..2767d6ef1 100644--- a/skyvern/browser_extension/extension/manifest.json+++ b/skyvern/browser_extension/extension/manifest.json@@ -1,7 +1,7 @@{"manifest_version": 3,"name": "Skyvern Agent",- "version": "0.2.10",+ "version": "0.2.11","description": "Connects explicitly shared Chrome tabs to a local Skyvern browser session.","minimum_chrome_version": "138","key": "MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAwePOj+WEmgtKAfyF3PkP6UHuWMvHhJgt0K+53fM9I/WNgu2N4YwCqYjD0h5fr4wCZfwiElUfgwxjDBHwX/Re/Y4G7WlSEG4lDTFNSRGQczHYQnerh8NHR3Gtpq59WKtRxzbbl/e1sVxab6ZyvKjiPZlbmjL44455SldRDPBNJ/5XiSflRkgV1hJ/OOdsVT4ghzjRTJsFhFTK8X0LeMupnYbjgcLb6he0ox+dX/eeDlRt3Sq5uu9+QfJg93/yOo55c0NAa7AW+1+r37GfAtezbqk3fNSraNFfhH+GQhnA6d/KPKTC7Ut2SH1Y8NYHh1yDkyYVr2bq4T6Twr/H0YgL/wIDAQAB",diff --git a/skyvern/browser_extension/extension/tab_scope.js b/skyvern/browser_extension/extension/tab_scope.jsindex dd81e254f..8215473db 100644--- a/skyvern/browser_extension/extension/tab_scope.js+++ b/skyvern/browser_extension/extension/tab_scope.js@@ -16,6 +16,8 @@ const PENDING_CREATION_KEY = "pendingTabCreation";const SKYVERN_GROUP_TITLE = "Skyvern Controlled";const SKYVERN_GROUP_COLOR = "purple";const TAB_GROUP_ID_NONE = -1;+const ALL_WINDOW_TYPES = ["normal", "popup", "panel", "app", "devtools"];+const POPUP_GROUP_SWEEP_ALARM = "skyvern-popup-group-sweep";const ANY_GROUP_ID = Symbol("anyGroupId");const TAB_OPERATION_TIMEOUT_MS = 28_000;const CREATION_TIMEOUT_MS = 3_000;@@ -87,6 +89,23 @@ export class TabScope {this.resolveReady = resolve;});+ chrome.alarms.onAlarm.addListener((alarm) => {+ if (alarm.name === POPUP_GROUP_SWEEP_ALARM) {+ void this.ready.then(() => this.sweepPopupGroups());+ }+ });+ chrome.tabs.onAttached.addListener((tabId) => {+ if (this.scopedTabIds.has(tabId)) {+ this.cancelTabOperations(+ tabId,+ new ProtocolError(+ ERROR_CODES.TAB_NOT_SCOPED,+ "The controlled tab moved windows.",+ ),+ );+ }+ void this.handleTabAttached(tabId);+ });chrome.tabs.onCreated.addListener((tab) => {void this.handleTabCreated(tab);});@@ -158,7 +177,7 @@ export class TabScope {if (this.scopedTabIds.has(numericTabId) &&Number.isInteger(groupId) &&- groupId >= 0+ groupId >= TAB_GROUP_ID_NONE) {this.scopedGroupIds.set(numericTabId, groupId);}@@ -193,6 +212,7 @@ export class TabScope {await this.writeCreationMarker(null);}}+ await this.sweepPopupGroups();this.resolveReady();await this.reconcileStoredTabs();}@@ -244,7 +264,7 @@ export class TabScope {}await Promise.all(scopedGroups.map(async ([tabId, groupId]) => {- if (!Number.isInteger(groupId)) {+ if (!Number.isInteger(groupId) || groupId < 0) {return;}try {@@ -351,17 +371,33 @@ export class TabScope {}lease?.assertCurrent();await this.assertScoped(tabId);- const expectedGroupId = this.scopedGroupIds.get(tabId);- let controlledGroup = null;- if (expectedGroupId !== undefined && tab.groupId === expectedGroupId) {- controlledGroup = await this.getControlledGroup(tab.groupId);- lease?.assertCurrent();+ let windowType;+ try {+ windowType = await this.getWindowType(tab.windowId);+ } catch (error) {+ await this.removeFromScopeLocked(tabId, "unshared", true, lease);+ throw error;}- if (- expectedGroupId === undefined ||- tab.groupId !== expectedGroupId ||- controlledGroup === null- ) {+ lease?.assertCurrent();+ const expectedGroupId = this.scopedGroupIds.get(tabId);+ const controlledGroup = await this.getControlledGroup(tab.groupId);+ lease?.assertCurrent();+ const validGroupless =+ expectedGroupId === TAB_GROUP_ID_NONE &&+ tab.groupId === TAB_GROUP_ID_NONE &&+ windowType !== "normal";+ const validGrouped =+ expectedGroupId !== undefined &&+ expectedGroupId >= 0 &&+ tab.groupId === expectedGroupId &&+ controlledGroup !== null &&+ windowType === "normal";+ if (!validGroupless && !validGrouped) {+ if (windowType !== "normal" && controlledGroup !== null) {+ if (!(await this.ungroupTabLocked(tabId, tab.groupId))) {+ await this.schedulePopupGroupSweep();+ }+ }await this.removeFromScopeLocked(tabId, "unshared", true, lease);throw new ProtocolError(ERROR_CODES.TAB_NOT_SCOPED,@@ -496,11 +532,15 @@ export class TabScope {const controlledGroup = await this.getControlledGroup(this.scopedGroupIds.get(tab.id),);+ const groupedTab = await this.getCreationTab(tab.id);+ const windowType = await this.getWindowType(groupedTab.windowId);currentTab = await this.getCreationTab(tab.id);this.validateCreation(creation, currentTab);if (controlledGroup === null ||- currentTab.groupId !== this.scopedGroupIds.get(tab.id)+ currentTab.groupId !== this.scopedGroupIds.get(tab.id) ||+ currentTab.windowId !== groupedTab.windowId ||+ windowType !== "normal")throw creationError();this.expectedGroupTransitions.delete(tab.id);@@ -972,6 +1012,24 @@ export class TabScope {);}+ async handleTabAttached(tabId) {+ await this.ready;+ if (!this.scopedTabIds.has(tabId)) return;+ this.cancelTabOperations(+ tabId,+ new ProtocolError(+ ERROR_CODES.TAB_NOT_SCOPED,+ "The controlled tab moved windows.",+ ),+ );+ await this.runTabOperation(+ tabId,+ (lease) => this.removeFromScopeLocked(tabId, "unshared", true, lease),+ this.operationGeneration,+ false,+ );+ }+async handleTabUpdated(tabId, changeInfo, expectedGroupTransition = null) {await this.ready;const admitTabUpdate = async () => {@@ -1012,8 +1070,40 @@ export class TabScope {return;}- const controlledGroup = await this.getControlledGroup(tab.groupId);+ let windowType;+ try {+ windowType = await this.getWindowType(tab.windowId);+ } catch {+ await this.removeFromScopeLocked(tabId, "unshared", true, lease);+ return;+ }+ let controlledGroup = null;+ if (tab.groupId !== TAB_GROUP_ID_NONE) {+ try {+ const group = await chrome.tabGroups.get(tab.groupId);+ if (group.title === SKYVERN_GROUP_TITLE)+ controlledGroup = group;+ } catch {+ if (windowType !== "normal")+ await this.schedulePopupGroupSweep();+ }+ }lease.assertCurrent();+ if (windowType !== "normal" && controlledGroup !== null) {+ const ungrouped = await this.ungroupTabLocked(tabId, tab.groupId);+ lease.assertCurrent();+ try {+ await this.removeFromScopeLocked(+ tabId,+ "unshared",+ true,+ lease,+ );+ } finally {+ if (!ungrouped) await this.schedulePopupGroupSweep();+ }+ return;+ }if (this.scopedTabIds.has(tabId)) {const expectedGroupId = this.scopedGroupIds.get(tabId);if (tab.groupId === expectedGroupId) {@@ -1124,6 +1214,10 @@ export class TabScope {lease?.assertCurrent();return await this.assertControllableLocked(tab.id, lease);} catch (error) {+ const scopedGroupId = this.scopedGroupIds.get(tab.id);+ if (Number.isInteger(scopedGroupId) && scopedGroupId >= 0) {+ await this.ungroupTabLocked(tab.id, scopedGroupId);+ }this.scopedTabIds.delete(tab.id);this.scopedGroupIds.delete(tab.id);await this.persistScope(lease);@@ -1184,12 +1278,36 @@ export class TabScope {async groupTabLocked(tab, lease = null) {const tabId = tab.id;+ tab = await this.getTab(tabId);+ lease?.assertCurrent();if (!Number.isInteger(tabId) || !Number.isInteger(tab.windowId)) {throw new ProtocolError(ERROR_CODES.TAB_NOT_FOUND,"Chrome returned an invalid tab for Skyvern Controlled.",);}+ const windowType = await this.getWindowType(tab.windowId);+ lease?.assertCurrent();+ if (windowType !== "normal") {+ if (tab.groupId !== TAB_GROUP_ID_NONE) {+ const controlledGroup = await this.getControlledGroup(tab.groupId);+ lease?.assertCurrent();+ if (+ controlledGroup === null ||+ !(await this.ungroupTabLocked(tabId, tab.groupId))+ ) {+ if (controlledGroup !== null) await this.schedulePopupGroupSweep();+ throw new ProtocolError(+ ERROR_CODES.TAB_NOT_SCOPED,+ "The popup tab could not be ungrouped.",+ );+ }+ }+ lease?.assertCurrent();+ this.scopedGroupIds.set(tabId, TAB_GROUP_ID_NONE);+ await this.persistScope(lease);+ return;+ }let groupId;try {const groups = await chrome.tabGroups.query({ windowId: tab.windowId });@@ -1206,15 +1324,44 @@ export class TabScope {groupId: existingGroup.id,tabIds: [tabId],})- : await chrome.tabs.group({ tabIds: [tabId] });+ : await chrome.tabs.group({+ tabIds: [tabId],+ // Chrome otherwise creates the group in the current window.+ createProperties: { windowId: tab.windowId },+ });grouped = true;lease?.assertCurrent();+ const groupedTab = await this.getTab(tabId);+ lease?.assertCurrent();+ if (+ groupedTab.windowId !== tab.windowId ||+ groupedTab.groupId !== groupId+ ) {+ throw new ProtocolError(+ ERROR_CODES.TAB_NOT_SCOPED,+ "The tab moved while grouping.",+ );+ }} finally {if (!grouped) {this.clearExpectedGroupTransition(tabId, transition);}}+ lease?.assertCurrent();+ this.scopedGroupIds.set(tabId, groupId);+ await this.persistScope(lease);+ if (!(await this.updateControlledGroup(groupId))) {+ throw new ProtocolError(+ ERROR_CODES.INTERNAL,+ "Chrome could not label the Skyvern Controlled group.",+ );+ }+ lease?.assertCurrent();} catch (error) {+ // A cancelled lease must still undo a completed Chrome grouping.+ if (Number.isInteger(groupId)) {+ await this.ungroupTabLocked(tabId, groupId);+ }lease?.assertCurrent();this.scopedGroupIds.delete(tabId);await this.persistScope(lease);@@ -1226,43 +1373,107 @@ export class TabScope {"Chrome could not add the tab to Skyvern Controlled.",);}- lease?.assertCurrent();- this.scopedGroupIds.set(tabId, groupId);- await this.persistScope(lease);- if (!(await this.updateControlledGroup(groupId))) {- await this.ungroupTabLocked(tabId, groupId);- this.scopedGroupIds.delete(tabId);- await this.persistScope(lease);+ }++ async getWindowType(windowId) {+ try {+ const window = await chrome.windows.get(windowId, {+ windowTypes: ALL_WINDOW_TYPES,+ });+ if (!ALL_WINDOW_TYPES.includes(window.type)) {+ throw new Error("Unknown window type");+ }+ return window.type;+ } catch {throw new ProtocolError(- ERROR_CODES.INTERNAL,- "Chrome could not label the Skyvern Controlled group.",+ ERROR_CODES.TAB_NOT_SCOPED,+ "The tab's window could not be verified.",);}}async ungroupTabLocked(tabId, scopedGroupId) {- if (!Number.isInteger(scopedGroupId)) {- return;+ for (let attempt = 0; attempt < 3; attempt += 1) {+ let transition = null;+ let ungrouped = false;+ try {+ const tab = await chrome.tabs.get(tabId);+ if (tab.groupId === TAB_GROUP_ID_NONE) return true;+ if (+ !Number.isInteger(scopedGroupId) ||+ scopedGroupId < 0 ||+ tab.groupId !== scopedGroupId+ ) {+ return false;+ }+ transition = this.expectGroupTransition(tabId, TAB_GROUP_ID_NONE);+ await chrome.tabs.ungroup([tabId]);+ ungrouped =+ (await chrome.tabs.get(tabId)).groupId === TAB_GROUP_ID_NONE;+ if (ungrouped) return true;+ } catch {+ // Chrome can reject an ungroup while it restores or moves a tab.+ } finally {+ if (!ungrouped && transition !== null) {+ this.clearExpectedGroupTransition(tabId, transition);+ }+ }}- let tab;+ return false;+ }++ async schedulePopupGroupSweep() {+ if (await chrome.alarms.get(POPUP_GROUP_SWEEP_ALARM)) return;+ await chrome.alarms.create(POPUP_GROUP_SWEEP_ALARM, {+ delayInMinutes: 0.5,+ });+ }++ async sweepPopupGroups() {+ let retry = false;try {- tab = await chrome.tabs.get(tabId);+ const windows = await chrome.windows.getAll({+ populate: true,+ windowTypes: ALL_WINDOW_TYPES,+ });+ for (const window of windows) {+ if (window.type === "normal") continue;+ for (const tab of window.tabs ?? []) {+ try {+ await this.runTabOperation(tab.id, async (lease) => {+ const liveTab = await this.getTab(tab.id);+ const windowType = await this.getWindowType(liveTab.windowId);+ lease.assertCurrent();+ if (+ windowType === "normal" ||+ liveTab.groupId === TAB_GROUP_ID_NONE+ )+ return;+ const group = await chrome.tabGroups.get(liveTab.groupId);+ lease.assertCurrent();+ if (group.title !== SKYVERN_GROUP_TITLE) return;+ if (!(await this.ungroupTabLocked(tab.id, liveTab.groupId))) {+ retry = true;+ }+ lease.assertCurrent();+ await this.removeFromScopeLocked(tab.id, "unshared", true, lease);+ });+ } catch (error) {+ retry = true;+ if (isScopeRevocation(error)) {+ await this.removeFromScopeLocked(tab.id, "unshared", true);+ }+ }+ }+ }} catch {- return;- }- if (tab.groupId !== scopedGroupId) {- return;+ retry = true;}- const transition = this.expectGroupTransition(tabId, TAB_GROUP_ID_NONE);- let ungrouped = false;- try {- await chrome.tabs.ungroup([tabId]);- ungrouped = true;- } catch {- return;- } finally {- if (!ungrouped) {- this.clearExpectedGroupTransition(tabId, transition);+ if (retry) {+ try {+ await this.schedulePopupGroupSweep();+ } catch {+ // Alarm failures must not prevent the service worker from becoming ready.}}}@@ -1382,34 +1593,15 @@ export class TabScope {}const generation = this.operationGeneration;for (const tabId of [...this.scopedTabIds]) {- await this.runTabOperation(- tabId,- async (lease) => {- let tab;- try {- tab = await chrome.tabs.get(tabId);- } catch {- lease.assertCurrent();- await this.removeFromScopeLocked(tabId, "closed", false, lease);- return;- }- lease.assertCurrent();- if (isTabRestricted(tab)) {- await this.removeFromScopeLocked(tabId, "unshared", true, lease);- return;- }- const expectedGroupId = this.scopedGroupIds.get(tabId);- if (- expectedGroupId === undefined ||- tab.groupId !== expectedGroupId- ) {- await this.removeFromScopeLocked(tabId, "unshared", true, lease);- return;- }- await this.assertControllableLocked(tabId, lease);- },- generation,- );+ try {+ await this.runTabOperation(+ tabId,+ (lease) => this.assertControllableLocked(tabId, lease),+ generation,+ );+ } catch (error) {+ if (!isScopeRevocation(error)) throw error;+ }}}diff --git a/skyvern/forge/sdk/workflow/models/web_search_block.py b/skyvern/forge/sdk/workflow/models/web_search_block.pyindex 13b5019ad..65402d783 100644--- a/skyvern/forge/sdk/workflow/models/web_search_block.py+++ b/skyvern/forge/sdk/workflow/models/web_search_block.py@@ -221,14 +221,7 @@ class WebSearchBlock(Block):continueseen.add(link)title = item.get("title")- snippet = item.get("snippet")- if response.provider == "exa":- highlights = item.get("highlights") or []- snippet = (- "\n".join(text for text in highlights if isinstance(text, str))- if isinstance(highlights, list)- else ""- )+ snippet = item.get("snippet") if response.provider == "google" else ""display_link = item.get("displayed_link")validated_results.append(SearchResult(@@ -310,9 +303,8 @@ class WebSearchBlock(Block):"query": query,"type": "auto","numResults": self.num_results,- "contents": {"highlights": {"maxCharacters": 1000}},}- site_tokens = re.findall(r"\S*(?<!\w)site:\S*", query, re.IGNORECASE)+ site_tokens = [token for token in query.split() if re.search(r"(?<!\w)site:", token, re.IGNORECASE)]if site_tokens:if len(site_tokens) != 1 or not re.fullmatch(r"site:([a-z0-9-]+\.)+[a-z0-9-]+", site_tokens[0], re.IGNORECASE@@ -329,6 +321,54 @@ class WebSearchBlock(Block):if body.get("error"):raise WebSearchError("Exa search did not complete successfully.")self._append_results(response, body.get("results"))+ if not response.results:+ return+ try:+ contents = await self._request(+ "exa",+ "https://api.exa.ai/contents",+ {+ "urls": [result["link"] for result in response.results],+ "highlights": {"maxCharacters": 1000, "query": payload["query"]},+ "maxAgeHours": -1,+ },+ )+ if contents.get("error"):+ raise WebSearchError("Exa highlights request did not complete successfully.")+ items = contents.get("results")+ if not isinstance(items, list):+ raise WebSearchError("Exa highlights request returned an invalid results list.")+ snippets = {result["link"]: "" for result in response.results}+ unmatched_count = 0+ for item in items:+ if not isinstance(item, dict) or not isinstance(item.get("url"), str):+ raise WebSearchError("Exa highlights request returned an invalid result URL.")+ if item["url"] in snippets:+ highlights = item.get("highlights")+ snippets[item["url"]] = (+ "\n".join(text for text in highlights if isinstance(text, str))+ if isinstance(highlights, list)+ else ""+ )+ else:+ unmatched_count += 1+ except Exception as exc: # noqa: BLE001+ with contained_effect("log Exa highlights failure"):+ LOG.warning(+ "Exa highlights request failed; results keep empty snippets",+ error_type=type(exc).__name__,+ reason=str(exc) if isinstance(exc, (WebSearchError, TimeoutError)) else None,+ )+ return+ for result in response.results:+ result["snippet"] = snippets[result["link"]]+ if unmatched_count:+ with contained_effect("log Exa highlights mismatch"):+ LOG.warning(+ "Exa highlights returned pages that match no search result",+ unmatched_count=unmatched_count,+ result_count=len(response.results),+ )def _prompt_block(self, context: WorkflowRunContext) -> TextPromptBlock | None:if not self.prompt or not self.prompt.strip():diff --git a/tests/unit/browser_extension/test_extension_bridge_hardening.py b/tests/unit/browser_extension/test_extension_bridge_hardening.pyindex 72f150cd4..a7299df81 100644--- a/tests/unit/browser_extension/test_extension_bridge_hardening.py+++ b/tests/unit/browser_extension/test_extension_bridge_hardening.py@@ -7,6 +7,73 @@ from pathlib import Pathimport pytest+_WINDOW_GROUP_FAKES = """+function installWindowGroupFakes(chrome, tabs, updates) {+ const state = {+ types: new Map(), lookupFailures: new Set(), enumerationFailure: false,+ ungroupFails: false, ungroupNoop: false, groupCalls: [], alarms: [],+ attached: [], alarmListeners: [], focusedWindowId: 99,+ groupLookupFailures: new Set(), groupTitles: new Map(), pendingAlarms: new Map(), now: 0,+ };+ const allTypes = ["normal", "popup", "panel", "app", "devtools"];+ chrome.windows = {+ ...chrome.windows,+ async get(id, options) {+ assert.deepEqual(options.windowTypes, allTypes);+ if (state.lookupFailures.has(id)) throw new Error("window lookup failed");+ return { id, type: state.types.get(id) ?? "normal" };+ },+ async getAll(options) {+ assert.equal(options.populate, true);+ assert.deepEqual(options.windowTypes, allTypes);+ if (state.enumerationFailure) throw new Error("window enumeration failed");+ return [...new Set([...tabs.values()].map((tab) => tab.windowId))].map((id) => ({+ id, type: state.types.get(id) ?? "normal",+ tabs: [...tabs.values()].filter((tab) => tab.windowId === id).map((tab) => ({ ...tab })),+ }));+ },+ };+ chrome.tabs.onAttached = { addListener(fn) { state.attached.push(fn); } };+ const getGroup = chrome.tabGroups.get;+ chrome.tabGroups.get = async (id) => {+ if (state.groupLookupFailures.has(id)) throw new Error("group lookup failed");+ const group = await getGroup(id);+ return { ...group, title: state.groupTitles.get(id) ?? group.title };+ };+ chrome.alarms = {+ ...chrome.alarms,+ onAlarm: { addListener(fn) { state.alarmListeners.push(fn); } },+ async get(name) { return state.pendingAlarms.get(name); },+ async create(name, options) {+ state.alarms.push({ name, options });+ state.pendingAlarms.set(name, { name, scheduledTime: state.now + options.delayInMinutes * 60_000 });+ },+ };+ state.fireAlarm = (name) => {+ const alarm = state.pendingAlarms.get(name);+ assert(alarm, "no pending alarm");+ state.pendingAlarms.delete(name);+ state.alarmListeners.forEach((fn) => fn(alarm));+ };+ chrome.tabs.group = async (options) => {+ state.groupCalls.push(structuredClone(options));+ const windowId = options.createProperties?.windowId ??+ (options.groupId === undefined ? state.focusedWindowId : tabs.get(options.tabIds[0]).windowId);+ if ((state.types.get(windowId) ?? "normal") !== "normal") throw new Error("cannot group this window");+ for (const id of options.tabIds) Object.assign(tabs.get(id), { windowId, groupId: options.groupId ?? 700 });+ return options.groupId ?? 700;+ };+ chrome.tabs.ungroup = async (ids) => {+ if (state.ungroupFails) throw new Error("ungroup failed");+ if (!state.ungroupNoop) for (const id of ids) {+ tabs.get(id).groupId = -1;+ updates.forEach((fn) => fn(id, { groupId: -1 }));+ }+ };+ return state;+}+"""+@pytest.mark.parametrize("revocation", ["target_closed", "canceled_by_user", "unshared", "restricted_url"])def test_created_tab_survives_scope_revocation_and_reset(revocation: str) -> None:@@ -38,13 +105,6 @@ globalThis.chrome = {{assert(tabs.has(tabId));return {{ ...tabs.get(tabId) }};}},- async group({{ tabIds }}) {{- for (const tabId of tabIds) tabs.get(tabId).groupId = 700;- return 700;- }},- async ungroup(tabIds) {{- for (const tabId of tabIds) tabs.get(tabId).groupId = -1;- }},async remove(tabId) {{ removed.push(tabId); tabs.delete(tabId); }},}},tabGroups: {{@@ -59,6 +119,8 @@ globalThis.chrome = {{}} }},debugger: {{ onEvent: listener, onDetach: listener }},}};+{_WINDOW_GROUP_FAKES}+installWindowGroupFakes(chrome, tabs, updates);const {{ TabScope }} = await import({json.dumps((extension_dir / "tab_scope.js").as_uri())});const {{ DebuggerRouter }} = await import({json.dumps((extension_dir / "debugger_router.js").as_uri())});const scope = new TabScope({{ sendEvent: (event, params) => events.push({{ event, params }}) }});@@ -568,6 +630,7 @@ def test_extension_reset_and_debugger_lifecycle_contract() -> None:protocol_uri = (extension_dir / "protocol.js").as_uri()tab_scope_uri = (extension_dir / "tab_scope.js").as_uri()script = f"""+import assert from "node:assert/strict";const listeners = {{ created: [], removed: [], updated: [], debuggerEvent: [], debuggerDetach: [] }};const tabs = new Map();const sessionState = {{}};@@ -595,17 +658,6 @@ globalThis.chrome = {{.filter((tab) => !values.lastFocusedWindow || tab.windowId === lastFocusedWindowId).map((tab) => ({{ ...tab }}));}},- async group({{ tabIds }}) {{- const tab = tabs.get(tabIds[0]);- if (tab) tab.groupId = 700;- return 700;- }},- async ungroup(tabIds) {{- for (const tabId of tabIds) {{- const tab = tabs.get(tabId);- if (tab) tab.groupId = -1;- }}- }},async remove(tabId) {{ tabs.delete(tabId); }},async update(tabId, values) {{ Object.assign(tabs.get(tabId), values); }},}},@@ -632,6 +684,8 @@ globalThis.chrome = {{}};globalThis.WebSocket = {{ OPEN: 1, CONNECTING: 0, CLOSING: 2 }};+{_WINDOW_GROUP_FAKES}+installWindowGroupFakes(chrome, tabs, listeners.updated);const {{ BridgeConnection }} = await import({json.dumps(bridge_uri)});const {{ DebuggerRouter }} = await import({json.dumps(debugger_uri)});const {{ ERROR_CODES }} = await import({json.dumps(protocol_uri)});@@ -951,7 +1005,6 @@ scope.scopedGroupIds.delete(28);tabs.delete(28);// Creation completion is required even when the URL already matches.-const assert = (await import("node:assert/strict")).default;const emit = (id, change) => {{if (tabs.has(id)) Object.assign(tabs.get(id), change);listeners.updated.forEach((fn) => fn(id, change));@@ -2030,3 +2083,290 @@ await waitUntil(() => !router.attachedTabs.has(21) && !router.attachStates.has(2)assert result.returncode == 0, result.stderr+++ "case",+ [+ "child_popup",+ "child_panel",+ "child_app",+ "child_devtools",+ "child_normal",+ "startup_match",+ "startup_unscoped",+ "startup_ungroup_failure",+ "startup_ungroup_noop",+ "startup_enumeration_failure",+ "startup_group_lookup_failure",+ "startup_attached",+ "startup_attached_unowned",+ "restore_groupless",+ "normal_groupless",+ "popup_positive",+ "lookup_failure",+ "attached",+ "regroup_scoped",+ "regroup_unscoped",+ "regroup_lookup_failure",+ "create_popup",+ "group_race",+ "admission_validation_race",+ ],+)+def test_popup_window_scope_contract(case: str) -> None:+ node = shutil.which("node")+ if node is None:+ pytest.skip("node is required for the extension scope test")+ extension_dir = Path(__file__).parents[3] / "skyvern" / "browser_extension" / "extension"+ script = f"""+import assert from "node:assert/strict";+const tabs = new Map();+const stored = {{}};+const events = [];+const removed = [];+const updates = [];+const commands = [];+const listener = {{ addListener() {{}} }};+globalThis.chrome = {{+ tabs: {{+ onCreated: listener, onRemoved: listener,+ onUpdated: {{ addListener(fn) {{ updates.push(fn); }} }},+ async get(id) {{ if (!tabs.has(id)) throw new Error("missing tab"); return {{ ...tabs.get(id) }}; }},+ async query() {{ return [...tabs.values()]; }},+ async remove(id) {{ removed.push(id); tabs.delete(id); }},+ async create({{ url }}) {{+ const tab = {{ id: 3, windowId: 2, groupId: -1, url, status: "complete" }};+ tabs.set(tab.id, tab);+ updates.forEach((fn) => fn(tab.id, {{ status: "complete" }}));+ return {{ ...tab }};+ }},+ }},+ tabGroups: {{+ async query() {{ return []; }},+ async get(id) {{ return {{ id, title: "Skyvern Controlled" }}; }},+ async update() {{}},+ }},+ storage: {{ session: {{+ async get(defaults) {{ return {{ ...defaults, ...stored }}; }},+ async set(values) {{ Object.assign(stored, structuredClone(values)); }},+ async remove(keys) {{ for (const key of keys) delete stored[key]; }},+ }} }},+ debugger: {{+ onEvent: listener, onDetach: listener,+ async attach() {{}}, async detach() {{}},+ async sendCommand(target, method) {{ commands.push({{ target, method }}); return {{}}; }},+ }},+}};+{_WINDOW_GROUP_FAKES}+const state = installWindowGroupFakes(chrome, tabs, updates);+state.types.set(2, "popup");+const {{ TabScope }} = await import({json.dumps((extension_dir / "tab_scope.js").as_uri())});+const {{ DebuggerRouter }} = await import({json.dumps((extension_dir / "debugger_router.js").as_uri())});+const caseName = {json.dumps(case)};+const tab = {{ id: 2, windowId: 2, groupId: -1, url: "https://popup.example.test" }};+tabs.set(2, tab);+const scope = new TabScope({{ sendEvent: (event, params) => events.push({{ event, params }}) }});+const waitUntil = async (predicate) => {{+ for (let i = 0; i < 100; i++) {{+ if (predicate()) return;+ await new Promise((resolve) => setTimeout(resolve, 1));+ }}+ assert.fail("event did not settle");+}};+if (caseName.startsWith("startup_attached")) {{+ state.types.set(2, "normal");+ tab.groupId = 700;+ stored.scopedTabIds = [2];+ stored.scopedTabGroupIds = {{ 2: 700 }};+ stored.createdTabIds = caseName === "startup_attached" ? [2] : [];+ let releaseStorage;+ chrome.storage.session.get = () => new Promise((resolve) => {{ releaseStorage = resolve; }});+ const initializing = scope.initialize();+ tab.windowId = 3;+ state.attached.forEach((fn) => fn(2, {{ newWindowId: 3 }}));+ releaseStorage(structuredClone(stored));+ await initializing;+ await waitUntil(() => events.some((entry) => entry.event === "scope.tabRemoved" && entry.params.reason === "unshared"));+ assert(!scope.isScoped(2));+ assert(!scope.createdTabIds.has(2));+ assert(!stored.scopedTabIds.includes(2));+ assert(!stored.createdTabIds.includes(2));+ await assert.rejects(scope.assertControllableLocked(2), {{ code: "TAB_NOT_SCOPED" }});+}} else if (caseName.startsWith("startup_") || caseName === "restore_groupless") {{+ tab.groupId = caseName === "restore_groupless" ? -1 : 700;+ const unscoped = ["startup_unscoped", "startup_group_lookup_failure"].includes(caseName);+ stored.scopedTabIds = unscoped ? [] : [2];+ stored.createdTabIds = unscoped ? [] : [2];+ stored.scopedTabGroupIds = {{ 2: tab.groupId }};+ // A failed lookup on another restored tab must not abort initialization.+ tabs.set(4, {{ id: 4, windowId: 4, groupId: 700, url: "https://missing.example.test" }});+ stored.scopedTabIds.push(4);+ stored.scopedTabGroupIds[4] = 700;+ state.lookupFailures.add(4);+ state.ungroupFails = caseName === "startup_ungroup_failure";+ state.ungroupNoop = caseName === "startup_ungroup_noop";+ state.enumerationFailure = caseName === "startup_enumeration_failure";+ if (caseName === "startup_group_lookup_failure") {{+ state.groupLookupFailures.add(700);+ state.groupTitles.set(702, "Other group");+ tabs.set(5, {{ ...tab, id: 5, groupId: 702 }});+ }}+ await scope.initialize();+ await scope.ready;+ assert(!scope.isScoped(4));+ if (state.ungroupFails || state.ungroupNoop || state.groupLookupFailures.size) {{+ assert.equal(tab.groupId, 700);+ assert(!scope.isScoped(2));+ assert(!scope.createdTabIds.has(2));+ assert.equal(scope.scopedGroupIds.get(2), undefined);+ assert.equal(stored.scopedTabGroupIds[2], undefined);+ assert(!(await scope.helloTabs()).some((item) => item.tabId === 2));+ assert(!(await scope.list()).tabs.some((item) => item.tabId === 2));+ assert.deepEqual(state.alarms.at(-1), {{ name: "skyvern-popup-group-sweep", options: {{ delayInMinutes: 0.5 }} }});+ const deadline = state.pendingAlarms.get("skyvern-popup-group-sweep").scheduledTime;+ state.now += 10_000;+ await scope.sweepPopupGroups();+ assert.equal(state.pendingAlarms.get("skyvern-popup-group-sweep").scheduledTime, deadline);+ state.ungroupFails = false;+ state.ungroupNoop = false;+ state.groupLookupFailures.clear();+ state.fireAlarm("skyvern-popup-group-sweep");+ await waitUntil(() => tab.groupId === -1 && scope.activeOperationCount === 0);+ assert(!scope.isScoped(2));+ assert(!scope.createdTabIds.has(2));+ assert.equal(scope.scopedGroupIds.get(2), undefined);+ if (caseName === "startup_group_lookup_failure") assert.equal(tabs.get(5).groupId, 702);+ }} else if (state.enumerationFailure) {{+ assert(state.alarms.some((alarm) => alarm.name === "skyvern-popup-group-sweep"));+ }} else {{+ assert.equal(tab.groupId, -1);+ const keepsScope = caseName === "restore_groupless";+ assert.equal(scope.isScoped(2), keepsScope);+ assert.equal(scope.createdTabIds.has(2), keepsScope);+ assert.equal(scope.scopedGroupIds.get(2), keepsScope ? -1 : undefined);+ }}+}} else {{+ await scope.initialize();+ if (caseName.startsWith("child_")) {{+ const type = caseName.slice(6);+ state.types.set(2, type);+ tabs.set(1, {{ id: 1, windowId: 1, groupId: 700, url: "https://opener.example.test" }});+ scope.scopedTabIds.add(1);+ scope.scopedGroupIds.set(1, 700);+ tab.openerTabId = 1;+ // The event snapshot is stale. Grouping must use the live destination.+ await scope.handleTabCreated({{ ...tab, windowId: 1 }});+ assert(scope.isScoped(2));+ assert((await scope.list()).tabs.some((item) => item.tabId === 2));+ assert.equal(tab.windowId, 2);+ assert.equal(tab.groupId, type === "normal" ? 700 : -1);+ assert.equal(state.groupCalls.length, type === "normal" ? 1 : 0);+ if (type === "normal") assert.equal(state.groupCalls[0].createProperties.windowId, 2);+ const router = new DebuggerRouter({{ tabScope: scope, sendEvent() {{}}, onAttachedChange() {{}} }});+ await router.attach({{ tabId: 2 }});+ await router.send({{ tabId: 2, method: "Runtime.evaluate", params: {{ expression: "1" }} }});+ assert(commands.some((command) => command.target.tabId === 2 && command.method === "Runtime.evaluate"));+ }} else if (caseName === "create_popup") {{+ await assert.rejects(scope.create({{ url: "https://created.example.test" }}));+ assert.deepEqual(removed, [3]);+ assert.equal(state.groupCalls.length, 0);+ assert.equal(events.filter((entry) => entry.event === "scope.tabAdded" || entry.event === "tabs.created").length, 0);+ }} else if (caseName === "group_race") {{+ state.types.set(2, "normal");+ state.types.set(3, "normal");+ const group = chrome.tabs.group;+ chrome.tabs.group = async (options) => {{+ const id = await group(options);+ tab.windowId = 3;+ state.attached.forEach((fn) => fn(2, {{ newWindowId: 3 }}));+ return id;+ }};+ await assert.rejects(scope.shareTab(2), {{ code: "TAB_NOT_SCOPED" }});+ await waitUntil(() => scope.activeOperationCount === 0);+ assert.equal(tab.windowId, 3);+ assert.equal(tab.groupId, -1);+ assert(!scope.isScoped(2));+ assert.equal(state.pendingAlarms.size, 0);+ }} else if (caseName === "admission_validation_race") {{+ state.types.set(2, "normal");+ state.types.set(3, "normal");+ const get = chrome.tabs.get;+ let moved = false;+ chrome.tabs.get = async (id) => {{+ // The group record is written after groupTabLocked's own tab validation.+ if (id === 2 && !moved && scope.scopedGroupIds.get(2) === 700) {{+ moved = true;+ tab.windowId = 3;+ state.attached.forEach((fn) => fn(2, {{ newWindowId: 3 }}));+ }}+ return get(id);+ }};+ await assert.rejects(scope.shareTab(2), {{ code: "TAB_NOT_SCOPED" }});+ await waitUntil(() => scope.activeOperationCount === 0);+ assert(moved);+ assert.equal(tab.groupId, -1);+ assert(!scope.isScoped(2));+ assert.equal(scope.scopedGroupIds.get(2), undefined);+ assert.equal(state.pendingAlarms.size, 0);+ }} else {{+ if (caseName !== "regroup_unscoped") {{+ scope.scopedTabIds.add(2);+ scope.scopedGroupIds.set(2, -1);+ }}+ if (caseName === "regroup_lookup_failure") {{+ tab.groupId = 700;+ state.groupLookupFailures.add(700);+ await scope.handleTabUpdated(2, {{ groupId: 700 }});+ assert(!scope.isScoped(2));+ assert.equal(scope.scopedGroupIds.get(2), undefined);+ assert.equal(tab.groupId, 700);+ assert(state.pendingAlarms.has("skyvern-popup-group-sweep"));+ state.groupLookupFailures.clear();+ state.fireAlarm("skyvern-popup-group-sweep");+ await waitUntil(() => scope.activeOperationCount === 0 && tab.groupId === -1);+ assert(!scope.isScoped(2));+ }} else if (caseName.startsWith("regroup_")) {{+ for (const ungroupFails of [false, true]) {{+ if (caseName === "regroup_scoped") {{+ scope.scopedTabIds.add(2);+ scope.scopedGroupIds.set(2, -1);+ scope.createdTabIds.add(2);+ }}+ tab.groupId = 700;+ state.ungroupFails = ungroupFails;+ updates.forEach((fn) => fn(2, {{ groupId: 700 }}));+ await waitUntil(() => !scope.isScoped(2) && (ungroupFails ? state.pendingAlarms.size > 0 : tab.groupId === -1));+ assert(!scope.createdTabIds.has(2));+ assert.equal(scope.scopedGroupIds.get(2), undefined);+ if (ungroupFails) {{+ state.ungroupFails = false;+ state.fireAlarm("skyvern-popup-group-sweep");+ }}+ await waitUntil(() => tab.groupId === -1 && scope.activeOperationCount === 0);+ }}+ }} else if (caseName === "attached") {{+ let lease;+ const running = scope.runTabOperation(2, async (value) => {{ lease = value; await value.invalidated; }});+ const rejected = assert.rejects(running, {{ code: "TAB_NOT_SCOPED" }});+ await waitUntil(() => lease !== undefined);+ tab.windowId = 1;+ state.attached.forEach((fn) => fn(2, {{ newWindowId: 1 }}));+ await rejected;+ await waitUntil(() => events.some((entry) => entry.event === "scope.tabRemoved" && entry.params.reason === "unshared"));+ assert(!scope.isScoped(2));+ }} else {{+ if (caseName === "normal_groupless") state.types.set(2, "normal");+ if (caseName === "popup_positive") {{ tab.groupId = 700; scope.scopedGroupIds.set(2, 700); }}+ if (caseName === "lookup_failure") state.lookupFailures.add(2);+ await assert.rejects(scope.assertControllableLocked(2), {{ code: "TAB_NOT_SCOPED" }});+ assert(!scope.isScoped(2));+ assert.equal(tab.groupId, -1);+ }}+ }}+}}+"""+ result = subprocess.run(+ [node, "--input-type=module", "--eval", script], capture_output=True, text=True, check=False, timeout=10+ )+ assert result.returncode == 0, result.stderrdiff --git a/tests/unit/workflow/test_web_search_block.py b/tests/unit/workflow/test_web_search_block.pyindex 54917d404..71cdff52f 100644--- a/tests/unit/workflow/test_web_search_block.py+++ b/tests/unit/workflow/test_web_search_block.py@@ -105,6 +105,49 @@ def search_setup(monkeypatch: pytest.MonkeyPatch) -> tuple[WebSearchBlock, Workfreturn block, context, handler[email protected]("contents_fails", [False, True], ids=["uncached-page", "contents-failure"])+async def test_exa_search_keeps_pages_without_cached_content(+ search_setup: tuple[WebSearchBlock, WorkflowRunContext, AsyncMock],+ monkeypatch: pytest.MonkeyPatch,+ contents_fails: bool,+) -> None:+ block, _, _ = search_setup+ block.prompt = None+ links = ["https://a.example.com/1", "https://b.example.com/2", "https://c.example.com/3"]+ payloads: dict[str, dict[str, Any]] = {}++ async def request(+ self: WebSearchBlock, provider: str, url: str, payload: dict[str, Any] | None = None+ ) -> dict[str, Any]:+ assert payload is not None+ payloads[url] = payload+ if url == "https://api.exa.ai/search":+ return {"results": [{"url": link} for link in links]}+ assert url == "https://api.exa.ai/contents"+ if contents_fails:+ raise WebSearchError("Exa search failed (HTTP 500).")+ return {+ "results": [+ {"url": links[0], "highlights": ["a1", "a2"]},+ {"url": links[2], "highlights": ["c1"]},+ ]+ }++ monkeypatch.setattr(WebSearchBlock, "_request", request)+ result = await block.execute("workflow-run-test", "block-run-test", "org-test")++ assert "contents" not in payloads["https://api.exa.ai/search"]+ assert payloads["https://api.exa.ai/contents"]["urls"] == links+ assert (+ payloads["https://api.exa.ai/contents"]["highlights"]["query"] == payloads["https://api.exa.ai/search"]["query"]+ )+ assert result.status == BlockStatus.completed+ results = result.output_parameter_value["results"]+ assert [item["link"] for item in results] == links+ assert [item["snippet"] for item in results] == (["", "", ""] if contents_fails else ["a1\na2", "", "c1"])++@pytest.mark.asyncioasync def test_search_retries_schema_echo_with_feedback(search_setup: tuple[WebSearchBlock, WorkflowRunContext, AsyncMock],@@ -300,7 +343,9 @@ async def test_search_first_page_timeout_preserves_fallback() -> None:original, _, handler = search_setupblock = original.model_copy(update={"provider": provider})- request = AsyncMock(side_effect=[TimeoutError("Google search timed out after 30 seconds."), PROVIDER_PAGE])+ request = AsyncMock(+ side_effect=[TimeoutError("Google search timed out after 30 seconds."), PROVIDER_PAGE, PROVIDER_PAGE]+ )monkeypatch.setattr(search_module.settings, "SERPAPI_API_KEY", "test-google-key")monkeypatch.setattr(WebSearchBlock, "_request", request)handler.return_value = {"llm_response": "Results processed."}