Skip to content

Automate browser based workflows with AI

Route every eligible Lever run to the dedicated lane and stop routing in staging (SKY-16970) (#8768)

Shuchang Zheng902c716922ee
diff --git a/skyvern-frontend/src/routes/workflows/copilot/NarrativeView.tsx b/skyvern-frontend/src/routes/workflows/copilot/NarrativeView.tsx
index de65dcd0f..671a30266 100644
--- a/skyvern-frontend/src/routes/workflows/copilot/NarrativeView.tsx
+++ b/skyvern-frontend/src/routes/workflows/copilot/NarrativeView.tsx
@@ -1,4 +1,11 @@
-import { useCallback, useEffect, useMemo, useRef, useState } from "react";
+import {
+ useCallback,
+ useEffect,
+ useLayoutEffect,
+ useMemo,
+ useRef,
+ useState,
+} from "react";
import {
CheckIcon,
ChevronRightIcon,
@@ -19,6 +26,7 @@ import {
revealedCountAt,
} from "./actionReveal";
import { humanizeBlockLabel } from "./blockLabel";
+import { fitSteps, STEP_SEPARATOR } from "./fitSteps";
import { CopilotMarkdown } from "./CopilotMarkdown";
import {
ACTIVITY_KIND_WORD,
@@ -1532,6 +1540,49 @@ function FCardCodeChange({
);
}
+function FFittedSteps({ steps }: { steps: string[] }) {
+ const ref = useRef<HTMLSpanElement>(null);
+ const [[head, tail], setFit] = useState<[string, string]>(() => [
+ steps.join(STEP_SEPARATOR),
+ "",
+ ]);
+ useLayoutEffect(() => {
+ const el = ref.current;
+ if (!el || typeof ResizeObserver === "undefined") return;
+ const context = document.createElement("canvas").getContext("2d");
+ if (!context) return;
+ const style = getComputedStyle(el);
+ context.font = `${style.fontStyle} ${style.fontWeight} ${style.fontSize} ${style.fontFamily}`;
+ const fit = () =>
+ setFit(
+ fitSteps(steps, el.clientWidth, (t) => context.measureText(t).width),
+ );
+ fit();
+ const observer = new ResizeObserver(fit);
+ observer.observe(el);
+ return () => observer.disconnect();
+ }, [steps]);
+ // whitespace-pre keeps the tail's leading separator, which a flex item
+ // would otherwise strip; the head's huge shrink factor makes it give up
+ // its width before the tail does.
+ return (
+ <span
+ ref={ref}
+ aria-hidden="true"
+ className="flex min-w-0 flex-1 overflow-hidden"
+ >
+ <span className="min-w-0 overflow-hidden text-ellipsis whitespace-pre [flex-shrink:9999]">
+ {head}
+ </span>
+ {tail ? (
+ <span className="min-w-0 overflow-hidden text-ellipsis whitespace-pre">
+ {tail}
+ </span>
+ ) : null}
+ </span>
+ );
+}
+
// One call in an expanded step. A result reads inline beside the call and
// opens to its full text; an error opens as its own box.
function FCallItem({
@@ -1562,6 +1613,7 @@ function FCallItem({
// A cancelled turn can end with a call that never got its result.
const pending = entry.kind === "tool_call" && !turnEnded;
const diffs = entry.codeDiffs ?? [];
+ const steps = failed ? undefined : entry.browserSteps;
const lineClass = `flex w-full min-w-0 items-center gap-1.5 py-px text-left text-[12px] leading-[1.5] ${STEP_TEXT}`;
const inner = (
<>
@@ -1570,19 +1622,31 @@ function FCallItem({
aria-hidden="true"
className="size-3 shrink-0 text-muted-foreground"
/>
- <span className="min-w-0 break-words">
- {callLabel(entry)}
- {count > 1 ? (
- <span className="text-muted-foreground">{` ×${count}`}</span>
- ) : null}
- {failed ? (
- <span className="text-muted-foreground"> · attempt failed</span>
- ) : null}
- <AttemptsBadge attempts={entry.attempts} />
- </span>
+ {steps?.length ? (
+ // A finished browser code call is labelled by what it did.
+ <>
+ <span className="sr-only">{steps.join(STEP_SEPARATOR)}</span>
+ <FFittedSteps steps={steps} />
+ {count > 1 ? (
+ <span className="shrink-0 text-muted-foreground">{`×${count}`}</span>
+ ) : null}
+ <AttemptsBadge attempts={entry.attempts} />
+ </>
+ ) : (
+ <span className="min-w-0 break-words">
+ {callLabel(entry)}
+ {count > 1 ? (
+ <span className="text-muted-foreground">{` ×${count}`}</span>
+ ) : null}
+ {failed ? (
+ <span className="text-muted-foreground"> · attempt failed</span>
+ ) : null}
+ <AttemptsBadge attempts={entry.attempts} />
+ </span>
+ )}
{/* Shown beside the label until opened, then in full below it; the
button's name stays the call, not its result. */}
- {inlineResult === null || open ? null : (
+ {inlineResult === null || open || steps?.length ? null : (
<span
aria-hidden="true"
className="min-w-0 flex-1 truncate font-mono text-[11px] text-muted-foreground"
diff --git a/skyvern-frontend/src/routes/workflows/copilot/fitSteps.test.ts b/skyvern-frontend/src/routes/workflows/copilot/fitSteps.test.ts
new file mode 100644
index 000000000..cc34308af
--- /dev/null
+++ b/skyvern-frontend/src/routes/workflows/copilot/fitSteps.test.ts
@@ -0,0 +1,32 @@
+import { describe, expect, it } from "vitest";
+import { fitSteps } from "./fitSteps";
+
+const byLength = (text: string) => text.length;
+const steps = ["Opened a page", "waited", "read ×10", "clicked '#next'"];
+
+describe("fitSteps", () => {
+ it("shows every step when they fit", () => {
+ expect(fitSteps(steps, 1000, byLength)).toEqual([
+ "Opened a page → waited → read ×10 → clicked '#next'",
+ "",
+ ]);
+ });
+
+ it("fills after the first step and bridges to the last", () => {
+ expect(fitSteps(steps, 45, byLength)).toEqual([
+ "Opened a page → waited",
+ " → … → clicked '#next'",
+ ]);
+ });
+
+ it("keeps the last step apart from the head when nothing else fits", () => {
+ expect(fitSteps(steps, 5, byLength)).toEqual([
+ "Opened a page",
+ " → … → clicked '#next'",
+ ]);
+ expect(fitSteps(steps.slice(0, 2), 5, byLength)).toEqual([
+ "Opened a page",
+ " → waited",
+ ]);
+ });
+});
diff --git a/skyvern-frontend/src/routes/workflows/copilot/fitSteps.ts b/skyvern-frontend/src/routes/workflows/copilot/fitSteps.ts
new file mode 100644
index 000000000..b2980af9b
--- /dev/null
+++ b/skyvern-frontend/src/routes/workflows/copilot/fitSteps.ts
@@ -0,0 +1,24 @@
+export const STEP_SEPARATOR = " → ";
+
+// Returns [head, tail]: the first step plus as many following steps as fit in
+// maxWidth, and an ellipsis bridge to the last step ("" when everything fits).
+// The caller lets head truncate before tail so the last step stays visible.
+export function fitSteps(
+ steps: string[],
+ maxWidth: number,
+ measure: (text: string) => number,
+): [string, string] {
+ const all = steps.join(STEP_SEPARATOR);
+ if (steps.length <= 1 || measure(all) <= maxWidth) return [all, ""];
+ const tail =
+ steps.length === 2
+ ? `${STEP_SEPARATOR}${steps[1]!}`
+ : `${STEP_SEPARATOR}…${STEP_SEPARATOR}${steps[steps.length - 1]!}`;
+ let head = steps[0]!;
+ for (const step of steps.slice(1, -1)) {
+ const next = head + STEP_SEPARATOR + step;
+ if (measure(next + tail) > maxWidth) break;
+ head = next;
+ }
+ return [head, tail];
+}
diff --git a/skyvern-frontend/src/routes/workflows/copilot/narrativeState.ts b/skyvern-frontend/src/routes/workflows/copilot/narrativeState.ts
index 19e5bd479..7976ac55a 100644
--- a/skyvern-frontend/src/routes/workflows/copilot/narrativeState.ts
+++ b/skyvern-frontend/src/routes/workflows/copilot/narrativeState.ts
@@ -347,6 +347,9 @@ export interface ActivityEntry {
// Server-computed line delta per code block this write changed. Absent on
// every other row and on payloads from a backend that predates it.
codeDiffs?: CodeWriteDiff[];
+ // A successful run_browser_code result's operations as display phrases,
+ // in order. Absent on every other row.
+ browserSteps?: string[];
// Stable per-event id used as React key.
id: string;
// Consecutive same-tool retries folded into this row by
@@ -577,7 +580,7 @@ export interface TurnWorkPlan {
items: string[];
}
-function parseWorkPlanItems(value: unknown): string[] | null {
+function parseStringList(value: unknown): string[] | null {
return Array.isArray(value) && value.every((item) => typeof item === "string")
? [...value]
: null;
@@ -586,7 +589,7 @@ function parseWorkPlanItems(value: unknown): string[] | null {
function parseTurnWorkPlan(value: unknown): TurnWorkPlan | null {
if (!value || typeof value !== "object") return null;
const o = value as Record<string, unknown>;
- const items = parseWorkPlanItems(o.items);
+ const items = parseStringList(o.items);
return typeof o.toolCallId === "string" && o.toolCallId && items
? { toolCallId: o.toolCallId, items }
: null;
@@ -772,6 +775,7 @@ const ACTIVITY_TOOL_DISPLAY_LABELS: Record<string, string> = {
list_credentials: "Checking saved credentials",
get_organization_usage_quota: "Checking account usage",
extend_browser_session: "Extending the browser session",
+ run_browser_code: "Working in the browser",
fill_credential_field: "Entering saved credentials",
edit_block: "Editing block",
add_block: "Adding block",
@@ -909,6 +913,7 @@ function buildActivityFromToolResult(
success: event.success,
detail: event.detail || undefined,
codeDiffs: parseCodeDiffs(event.code_diffs),
+ browserSteps: parseStringList(event.browser_steps) ?? undefined,
reason: actionReason(event.reason),
activityBucket: parseActivityBucket(event.activity_bucket),
activityStartedAt: event.activity_started_at ?? undefined,
@@ -1516,7 +1521,7 @@ export function applyNarrativeEvent(
}
case "tool_result": {
- const planItems = parseWorkPlanItems(event.work_plan);
+ const planItems = parseStringList(event.work_plan);
const workPlan = planItems
? { toolCallId: event.tool_call_id, items: planItems }
: prev.workPlan;
@@ -1685,6 +1690,7 @@ function normalizeActivityEntries(raw: unknown): ActivityEntry[] {
typeof o.activeLabel === "string" ? o.activeLabel : undefined,
success: typeof o.success === "boolean" ? o.success : undefined,
codeDiffs: parseCodeDiffs(o.codeDiffs),
+ browserSteps: parseStringList(o.browserSteps) ?? undefined,
id: o.id,
reason: actionReason(o.reason),
activityBucket: parseActivityBucket(o.activityBucket),
diff --git a/skyvern-frontend/src/routes/workflows/copilot/workflowCopilotTypes.ts b/skyvern-frontend/src/routes/workflows/copilot/workflowCopilotTypes.ts
index 1de35b4bc..65fe39d2e 100644
--- a/skyvern-frontend/src/routes/workflows/copilot/workflowCopilotTypes.ts
+++ b/skyvern-frontend/src/routes/workflows/copilot/workflowCopilotTypes.ts
@@ -483,6 +483,8 @@ export interface WorkflowCopilotToolResultUpdate {
code_diffs?: CodeWriteDiff[] | null;
// The plan a successful set_work_plan stored. Absent on every other tool.
work_plan?: string[] | null;
+ // A successful run_browser_code call's operations as display phrases.
+ browser_steps?: string[] | null;
detail?: string | null;
timestamp?: string | null;
}
diff --git a/skyvern/forge/sdk/copilot/context.py b/skyvern/forge/sdk/copilot/context.py
index e5feed226..246f748f9 100644
--- a/skyvern/forge/sdk/copilot/context.py
+++ b/skyvern/forge/sdk/copilot/context.py
@@ -114,6 +114,7 @@ class NarrativeActivityEntry(TypedDict):
activeLabel: NotRequired[str]
outcomeLabel: NotRequired[str]
codeDiffs: NotRequired[list[CodeWriteDiff]]
+ browserSteps: NotRequired[list[str]]
id: str
# Server clock read for the event this entry describes, shared with the SSE
# update so a rehydrated row renders the same elapsed the live row did.
diff --git a/skyvern/forge/sdk/copilot/narration.py b/skyvern/forge/sdk/copilot/narration.py
index 38b959af2..6124f93ef 100644
--- a/skyvern/forge/sdk/copilot/narration.py
+++ b/skyvern/forge/sdk/copilot/narration.py
@@ -84,7 +84,7 @@ _TOOL_ACTIVITY_DISPLAY_LABELS = {
"start_fresh_browser": "Starting a fresh browser",
"extend_browser_session": "Extending the browser session",
"upload_attached_file": "Attaching your file to the page",
- "run_browser_code": "Running browser code",
+ "run_browser_code": "Working in the browser",
"edit_block": "Editing block",
"add_block": "Adding block",
"delete_block": "Deleting block",
@@ -149,6 +149,7 @@ def build_tool_result_activity(
timestamp: datetime,
display_label: str | None = None,
code_diffs: list[CodeWriteDiff] | None = None,
+ browser_steps: list[str] | None = None,
) -> NarrativeActivityEntry | None:
if tool_name in ACTIVITY_TOOL_DENYLIST:
return None
@@ -165,6 +166,8 @@ def build_tool_result_activity(
}
if code_diffs:
entry["codeDiffs"] = code_diffs
+ if browser_steps:
+ entry["browserSteps"] = browser_steps
return entry
diff --git a/skyvern/forge/sdk/copilot/output_utils.py b/skyvern/forge/sdk/copilot/output_utils.py
index 0b622295f..69a4d6951 100644
--- a/skyvern/forge/sdk/copilot/output_utils.py
+++ b/skyvern/forge/sdk/copilot/output_utils.py
@@ -4,6 +4,7 @@ from __future__ import annotations
import base64
import binascii
+import itertools
import json
import re
import unicodedata
@@ -1959,6 +1960,79 @@ def _workflow_write_phrase(data: dict[str, Any]) -> str:
return "Staged a workflow draft" if data.get("persistence") else "Workflow updated"
+_BROWSER_CODE_OPERATION_PHRASES = {
+ "goto": "opened a page",
+ "go_back": "went back",
+ "reload": "reloaded the page",
+ "click": "clicked",
+ "dblclick": "double-clicked",
+ "fill": "filled",
+ "type": "typed into",
+ "press": "pressed a key",
+ "check": "checked",
+ "uncheck": "unchecked",
+ "select_option": "selected an option",
+ "hover": "hovered",
+ "count": "counted",
+ "text_content": "read",
+ "inner_text": "read",
+ "inner_html": "read",
+ "all_text_contents": "read",
+ "all_inner_texts": "read",
+ "get_attribute": "read",
+ "input_value": "read",
+ "is_visible": "checked visibility of",
+ "content": "read the page",
+ "title": "read the title",
+ "evaluate": "ran a page script",
+ "wait_for_selector": "waited for",
+ "wait_for": "waited for",
+ "wait_for_url": "waited for navigation",
+ "wait_for_load_state": "waited for the page to load",
+ "wait_for_timeout": "waited",
+ "search_web": "searched the web",
+ "solve_captcha": "ran the CAPTCHA solver",
+ "click_and_download": "downloaded a file",
+ "click_and_wait_for_popup": "opened a popup",
+}
+_MAX_BROWSER_CODE_SELECTOR_CHARS = 40
+
+
+def browser_code_steps_for_user(tool_name: str, result: dict[str, Any]) -> list[str] | None:
+ """A successful run_browser_code call's reported operations as phrases, e.g. ``["Opened a page", "read ×10"]``."""
+ if tool_name != "run_browser_code" or result.get("ok") is not True:
+ return None
+ operations = result.get("operations")
+ if not isinstance(operations, list):
+ return None
+ facts = [op for op in operations if isinstance(op, dict) and isinstance(op.get("operation"), str)]
+ steps: list[str] = []
+ for name, group in itertools.groupby(facts, key=lambda op: op["operation"]):
+ run = list(group)
+ step = _BROWSER_CODE_OPERATION_PHRASES.get(name, name.replace("_", " "))
+ selectors = {op.get("selector") for op in run}
+ selector = next(iter(selectors)) if len(selectors) == 1 else None
+ if isinstance(selector, str) and selector.strip():
+ # Model-authored; collapsed and clamped so one long selector cannot take over the row.
+ shown = " ".join(selector.split())
+ if len(shown) > _MAX_BROWSER_CODE_SELECTOR_CHARS:
+ shown = shown[: _MAX_BROWSER_CODE_SELECTOR_CHARS - 1] + "…"
+ step += f" '{shown}'"
+ if len(run) > 1:
+ step += f" ×{len(run)}"
+ if any(op.get("status") == "failed" for op in run):
+ step += " (failed)"
+ steps.append(step)
+ if not steps:
+ return None
+ omitted = result.get("operations_omitted")
+ if isinstance(omitted, int) and omitted > 0:
+ # Only the first operations are listed, so the true last action is unknown.
+ steps.append(f"{omitted} more operation(s)")
+ steps[0] = steps[0][:1].upper() + steps[0][1:]
+ return steps
+
+
_PAGE_CHALLENGE_OUTCOME_SUMMARIES = {
"solved": "Challenge solver reported the challenge solved",
"typed": "Challenge solver typed the CAPTCHA image's text",
@@ -2092,6 +2166,10 @@ def summarize_tool_result(tool_name: str, result: dict[str, Any], *, for_display
count = len(operations) if isinstance(operations, list) else 0
url = result.get("current_url")
summary = f"Ran browser code ({count} operation(s))"
+ # Only the display form changes: context.merge_turn_summary parses "Ran browser code ... at <url>".
+ steps = browser_code_steps_for_user(tool_name, result) if for_display else None
+ if steps:
+ summary = " → ".join(steps)
return f"{summary} at {url[:80]}" if isinstance(url, str) and url else summary
return "OK"
diff --git a/skyvern/forge/sdk/copilot/streaming_adapter.py b/skyvern/forge/sdk/copilot/streaming_adapter.py
index 147eb54a2..8a15e023d 100644
--- a/skyvern/forge/sdk/copilot/streaming_adapter.py
+++ b/skyvern/forge/sdk/copilot/streaming_adapter.py
@@ -41,6 +41,7 @@ from skyvern.forge.sdk.copilot.narration import (
tool_activity_display_label,
)
from skyvern.forge.sdk.copilot.output_utils import (
+ browser_code_steps_for_user,
format_tool_result_for_user,
summarize_tool_result_detail,
user_facing_success,
@@ -450,6 +451,7 @@ async def stream_to_sse(
tool_result_ts = datetime.now(timezone.utc)
code_diffs = _drain_code_write_diffs(ctx, tool_name, call_id)
work_plan = _tool_result_work_plan(tool_name, parsed)
+ browser_steps = browser_code_steps_for_user(tool_name, parsed)
narrator_state.record_activity(
_present_activity(
build_tool_result_activity(
@@ -461,6 +463,7 @@ async def stream_to_sse(
timestamp=tool_result_ts,
display_label=result_label,
code_diffs=code_diffs,
+ browser_steps=browser_steps,
),
presentation,
)
@@ -483,6 +486,7 @@ async def stream_to_sse(
tool_call_id=call_id,
code_diffs=code_diffs,
work_plan=work_plan,
+ browser_steps=browser_steps,
detail=detail,
workflow_run_id=_tool_result_workflow_run_id(tool_name, parsed),
executed_source_reference=_tool_result_executed_source_reference(tool_name, parsed),
@@ -608,6 +612,7 @@ async def flush_goal_satisfied_tool_result(stream: EventSourceStream, ctx: Copil
flush_ts = datetime.now(timezone.utc)
code_diffs = _drain_code_write_diffs(ctx, pending.tool_name, pending.call_id)
work_plan = _tool_result_work_plan(pending.tool_name, parsed)
+ browser_steps = browser_code_steps_for_user(pending.tool_name, parsed)
narrator_state = ctx.narrator_state
if narrator_state is not None:
narrator_state.record_activity(
@@ -621,6 +626,7 @@ async def flush_goal_satisfied_tool_result(stream: EventSourceStream, ctx: Copil
timestamp=flush_ts,
display_label=display_label,
code_diffs=code_diffs,
+ browser_steps=browser_steps,
),
pending,
)
@@ -643,6 +649,7 @@ async def flush_goal_satisfied_tool_result(stream: EventSourceStream, ctx: Copil
tool_call_id=pending.call_id,
code_diffs=code_diffs,
work_plan=work_plan,
+ browser_steps=browser_steps,
detail=summarize_tool_result_detail(
parsed, tool_name=pending.tool_name, blocker_signal=blocker_signals, success=success
),
diff --git a/skyvern/forge/sdk/schemas/workflow_copilot.py b/skyvern/forge/sdk/schemas/workflow_copilot.py
index 692bbb489..6f5e9d6af 100644
--- a/skyvern/forge/sdk/schemas/workflow_copilot.py
+++ b/skyvern/forge/sdk/schemas/workflow_copilot.py
@@ -764,6 +764,10 @@ class WorkflowCopilotToolResultUpdate(BaseModel):
None,
description="The plan a successful set_work_plan stored, as stored. None for every other tool",
)
+ browser_steps: list[str] | None = Field(
+ None,
+ description="A successful run_browser_code call's reported operations as display phrases, in order",
+ )
detail: str | None = Field(
None,
description=(
diff --git a/tests/unit/test_copilot_output_utils.py b/tests/unit/test_copilot_output_utils.py
index dd21df8e0..d0bd2f735 100644
--- a/tests/unit/test_copilot_output_utils.py
+++ b/tests/unit/test_copilot_output_utils.py
@@ -27,6 +27,7 @@ from skyvern.forge.sdk.copilot.output_utils import (
MCP_RESULT_PROVENANCE_KEY,
MCP_RESULT_PROVENANCE_VALUE,
_sanitize_failure_text,
+ browser_code_steps_for_user,
build_run_blocks_response,
format_tool_result_for_user,
iter_failure_reasons,
@@ -1651,6 +1652,37 @@ class TestFormatToolResultForUser:
)
assert agent_summary == "Ran browser code (2 operation(s)) at https://example.com/members?page=3"
+ def test_format_tool_result_for_user_describes_browser_code_steps(self) -> None:
+ result = {
+ "ok": True,
+ "current_url": "https://example.com/jobs",
+ "operations": [
+ {"operation": "goto", "status": "ok"},
+ {"operation": "wait_for_selector", "status": "ok", "selector": ".job"},
+ *({"operation": "text_content", "status": "ok", "selector": f".job:nth({i})"} for i in range(10)),
+ {"operation": "click", "status": "failed", "selector": "#next"},
+ {"operation": "screenshot", "status": "ok"},
+ ],
+ }
+ assert browser_code_steps_for_user("run_browser_code", {**result, "operations_omitted": 3}) == [
+ "Opened a page",
+ "waited for '.job'",
+ "read ×10",
+ "clicked '#next' (failed)",
+ "screenshot",
+ "3 more operation(s)",
+ ]
+ assert format_tool_result_for_user("run_browser_code", result) == (
+ "Opened a page → waited for '.job' → read ×10 → clicked '#next' (failed) → screenshot"
+ " at https://example.com/jobs"
+ )
+ assert summarize_tool_result("run_browser_code", result) == (
+ "Ran browser code (14 operation(s)) at https://example.com/jobs"
+ )
+ assert format_tool_result_for_user("run_browser_code", {"ok": True, "operations": []}) == (
+ "Ran browser code (0 operation(s))"
+ )
+
class TestUserFacingSuccess:
@staticmethod
diff --git a/tests/unit/test_copilot_streaming_adapter.py b/tests/unit/test_copilot_streaming_adapter.py
index 580e2ca69..de86438b7 100644
--- a/tests/unit/test_copilot_streaming_adapter.py
+++ b/tests/unit/test_copilot_streaming_adapter.py
@@ -840,6 +840,45 @@ async def test_a_stored_work_plan_outlives_its_row_being_capped_away() -> None:
assert ctx.narrator_state.work_plan == {"toolCallId": "p1", "items": plan}
+async def test_browser_code_steps_ride_the_result_event_and_its_saved_row() -> None:
+ def tool_output(call_id: str, payload: dict[str, Any]) -> RunItemStreamEvent:
+ out_item = MagicMock(spec=RunItem)
+ out_item.raw_item = {"call_id": call_id}
+ out_item.output = [{"type": "text", "text": json.dumps(payload)}]
+ return RunItemStreamEvent(name="tool_output", item=out_item)
+
+ operations = [{"operation": "goto", "status": "ok"}, {"operation": "click", "status": "ok", "selector": "#next"}]
+ result = MagicMock()
+ result.stream_events = lambda: _stream_events_from(
+ _tool_called_event("b1", "run_browser_code"),
+ tool_output("b1", {"ok": True, "operations": operations}),
+ _tool_called_event("b2", "run_browser_code"),
+ tool_output("b2", {"ok": False, "error": "boom", "operations": operations}),
+ )
+ result.cancel = MagicMock()
+
+ sent: list[Any] = []
+
+ async def _send(payload: Any) -> bool:
+ sent.append(payload)
+ return True
+
+ stream = MagicMock()
+ stream.is_disconnected = AsyncMock(return_value=False)
+ stream.send = _send
+ ctx = _new_ctx()
+
+ await stream_to_sse(result, stream, ctx)
+
+ steps = ["Opened a page", "clicked '#next'"]
+ tool_results = [p for p in sent if getattr(p, "type", None) == WorkflowCopilotStreamMessageType.TOOL_RESULT]
+ assert [p.browser_steps for p in tool_results] == [steps, None]
+ rows = {row["id"]: row for row in ctx.narrator_state.design_activity}
+ assert rows["tr-b1"]["browserSteps"] == steps
+ assert "browserSteps" not in rows["tr-b2"]
+
+
@pytest.mark.asyncio
async def test_a_stashed_write_diff_rides_one_result_and_no_later_foreign_one() -> None:
diffs = [{"label": "download_step", "added": 3, "removed": 1, "patch": "@@\n-old\n+new"}]