Automate browser based workflows with AI
Python aiapiautomationbrowserbrowser-automationcomputergptllmplaywrightpowerautomatepuppeteerpythonrpaseleniumvisionworkflow
fix: dedupe re-captured live browser-recording steps (#6951)
Cindy Li0bd0da7d7c58
diff --git a/skyvern-frontend/src/routes/workflows/studio/runview/RunHero.test.tsx b/skyvern-frontend/src/routes/workflows/studio/runview/RunHero.test.tsxindex a4fcdb9df..67e6cba19 100644--- a/skyvern-frontend/src/routes/workflows/studio/runview/RunHero.test.tsx+++ b/skyvern-frontend/src/routes/workflows/studio/runview/RunHero.test.tsx@@ -77,6 +77,50 @@ describe("RunHero Code surface (single source of truth)", () => {});});+describe("RunHero header dedupe", () => {+ test("recording view does not echo the active toggle label in the header", () => {+ render(+ <RunHero+ {...baseProps}+ showDebugStream={false}+ running={false}+ recordingUrls={["https://example.com/rec.mp4"]}+ />,+ );+ // Only the toggle should say "Recording" — not the header label too.+ expect(screen.getAllByText("Recording")).toHaveLength(1);+ });++ test("code view does not echo the active toggle as a header label", () => {+ useRunViewStore.getState().setCenterView("code");+ render(<RunHero {...baseProps} showDebugStream={false} />);+ // The Code toggle communicates the view; the "Generated code" header is redundant.+ expect(screen.queryByText("Generated code")).toBeNull();+ });++ test("scrubbed action description appears once, not in the header too", () => {+ useRunViewStore.getState().pinFrame("f1");+ render(+ <RunHero+ {...baseProps}+ showDebugStream={false}+ running={false}+ heroSelection={{ kind: "thought", thoughtId: "t1" }}+ heroLabel="Click the login button"+ />,+ );+ // The in-card "Inspecting step" bar owns the action description.+ expect(screen.getAllByText("Click the login button")).toHaveLength(1);+ });++ test("view toggles live in the labeled segmented control, on the leading edge", () => {+ render(<RunHero {...baseProps} showDebugStream={false} />);+ const group = screen.getByRole("group", { name: "Center view" });+ expect(group.contains(screen.getByText("Live"))).toBe(true);+ expect(group.contains(screen.getByText("Code"))).toBe(true);+ });+});+describe("RunHero failure banner", () => {const failedProps = {...baseProps,diff --git a/skyvern-frontend/src/routes/workflows/studio/runview/RunHero.tsx b/skyvern-frontend/src/routes/workflows/studio/runview/RunHero.tsxindex daa33bf9a..95b27553f 100644--- a/skyvern-frontend/src/routes/workflows/studio/runview/RunHero.tsx+++ b/skyvern-frontend/src/routes/workflows/studio/runview/RunHero.tsx@@ -178,33 +178,16 @@ export function RunHero({? "recording": "screenshot";+ // The right-side toggles own the view identity (Live/Recording/Code) and the+ // in-card "Inspecting step" bar owns a scrubbed action's description; the+ // header only adds context they don't surface — the live page URL, or the+ // final frame's label when nothing else names it.const headerLabel =center === "stream"- ? // VNC streams carry no page URL (pixels only); only the CDP path sets- // streamUrl, so fall back to a neutral label instead of "Loading…".- (streamUrl ?? "Live browser")- : center === "recording"- ? "Recording"- : center === "code"- ? "Generated code"- : center === "inputs"- ? "Inputs"- : center === "outputs"- ? "Outputs"- : (heroLabel ?? "Screenshot");-- const headerIcon =- center === "recording" ? (- <PlayIcon className="h-3.5 w-3.5 shrink-0 text-muted-foreground" />- ) : center === "code" ? (- <CodeIcon className="h-3.5 w-3.5 shrink-0 text-muted-foreground" />- ) : center === "inputs" ? (- <ListBulletIcon className="h-3.5 w-3.5 shrink-0 text-muted-foreground" />- ) : center === "outputs" ? (- <FileTextIcon className="h-3.5 w-3.5 shrink-0 text-muted-foreground" />- ) : (- <GlobeIcon className="h-3.5 w-3.5 shrink-0 text-muted-foreground" />- );+ ? streamUrl+ : center === "screenshot" && !scrubbing+ ? heroLabel+ : null;const toggleCenter = (view: "code" | "inputs" | "outputs") =>setCenterView(centerView === view ? "default" : view);@@ -215,13 +198,11 @@ export function RunHero({ref={headerRef}className="flex items-center gap-2 border-b border-border px-3 py-2">- <div className="flex min-w-0 flex-1 items-center gap-1.5">- {headerIcon}- <span className="min-w-0 flex-1 truncate text-sm font-medium text-foreground">- {headerLabel}- </span>- </div>- <div className="flex shrink-0 items-center gap-1">+ <div+ role="group"+ aria-label="Center view"+ className="flex shrink-0 items-center gap-0.5 rounded-md border border-slate-700 bg-slate-elevation2 p-0.5"+ >{showDebugStream ? (<><ViewToggle@@ -305,6 +286,18 @@ export function RunHero({icon={<FileTextIcon className="h-3 w-3" />}/>) : null}+ </div>+ <div className="flex min-w-0 flex-1 items-center gap-1.5">+ {headerLabel ? (+ <>+ <GlobeIcon className="h-3.5 w-3.5 shrink-0 text-muted-foreground" />+ <span className="min-w-0 flex-1 truncate text-sm font-medium text-foreground">+ {headerLabel}+ </span>+ </>+ ) : null}+ </div>+ <div className="flex shrink-0 items-center gap-1">{overview || actions ? (<div className="mx-0.5 h-4 w-px bg-border" />) : null}diff --git a/skyvern/forge/sdk/routes/streaming/channels/exfiltration.py b/skyvern/forge/sdk/routes/streaming/channels/exfiltration.pyindex 343648061..3f3e339f3 100644--- a/skyvern/forge/sdk/routes/streaming/channels/exfiltration.py+++ b/skyvern/forge/sdk/routes/streaming/channels/exfiltration.py@@ -184,11 +184,18 @@ class ExfiltrationChannel(CdpChannel):for fingerprint in expired:self._recent_console_event_fingerprints.pop(fingerprint, None)- def _should_emit_console_event(self, event_data: dict[str, t.Any]) -> bool:+ # Excluded from the fingerprint: advances by ms when one interaction is re-captured across a reconnect.+ _CONSOLE_FINGERPRINT_VOLATILE_KEYS: t.ClassVar[frozenset[str]] = frozenset({"timestamp"})++ def _console_fingerprint(self, event_data: dict[str, t.Any]) -> str:+ stable = {k: v for k, v in event_data.items() if k not in self._CONSOLE_FINGERPRINT_VOLATILE_KEYS}try:- fingerprint = json.dumps(event_data, sort_keys=True, separators=(",", ":"))+ return json.dumps(stable, sort_keys=True, separators=(",", ":"))except TypeError:- fingerprint = json.dumps(event_data, sort_keys=True, separators=(",", ":"), default=str)+ return json.dumps(stable, sort_keys=True, separators=(",", ":"), default=str)++ def _should_emit_console_event(self, event_data: dict[str, t.Any]) -> bool:+ fingerprint = self._console_fingerprint(event_data)now = time.monotonic()self._prune_console_dedup_cache(now)diff --git a/skyvern/services/browser_recording/service.py b/skyvern/services/browser_recording/service.pyindex eeaa470d5..dca34c640 100644--- a/skyvern/services/browser_recording/service.py+++ b/skyvern/services/browser_recording/service.py@@ -66,6 +66,10 @@ LOG = structlog.get_logger(__name__)MAX_BASE64_SIZE = 14 * 1024 * 1024 # ~10MB compressed + base64 overheadDEFAULT_DRAFT_ACTION_TITLE = "Browser Action"+# Re-captures of one interaction land within this browser-clock (ms) window; genuine repeats fall outside it.+DUPLICATE_ACTION_WINDOW_MS = 250+DUPLICATE_ACTION_SCAN_DEPTH = 8+def _action_identity(action: Action) -> tuple[str, str, str, str]:"""Stable identity fields used for duplicate-action suppression."""@@ -79,20 +83,20 @@ def _action_identity(action: Action) -> tuple[str, str, str, str]:def _is_duplicate_action(candidate: Action, existing_actions: list[Action]) -> bool:"""- Suppress duplicate actions emitted from duplicate transport events.-- We only dedupe when the latest action has the exact same identity and- timestamps, which keeps intentional repeated clicks intact.+ Suppress duplicate actions from duplicate transport events: a recent action (within+ DUPLICATE_ACTION_WINDOW_MS, by identity) marks the candidate a duplicate. The tail scan and+ window catch non-adjacent, ms-jittered re-captures while keeping intentional repeats intact."""if not existing_actions:return False- previous = existing_actions[-1]- return (- _action_identity(previous) == _action_identity(candidate)- and previous.timestamp_start == candidate.timestamp_start- and previous.timestamp_end == candidate.timestamp_end- )+ for previous in reversed(existing_actions[-DUPLICATE_ACTION_SCAN_DEPTH:]):+ if _action_identity(previous) != _action_identity(candidate):+ continue+ if abs(candidate.timestamp_start - previous.timestamp_start) <= DUPLICATE_ACTION_WINDOW_MS:+ return True++ return Falsedef deterministic_goto_url_label(url: str) -> str:diff --git a/tests/unit/forge/sdk/routes/streaming/test_exfiltration_channel.py b/tests/unit/forge/sdk/routes/streaming/test_exfiltration_channel.pyindex 8dd3d4073..1a8891a32 100644--- a/tests/unit/forge/sdk/routes/streaming/test_exfiltration_channel.py+++ b/tests/unit/forge/sdk/routes/streaming/test_exfiltration_channel.py@@ -294,6 +294,46 @@ class TestExfiltrationChannelEvents:page.add_init_script.assert_not_awaited()assert page.evaluate.await_count == 2+ def test_console_fingerprint_ignores_volatile_timestamp(self) -> None:+ channel, _ = _make_channel()+ first = {**_make_event_data(), "timestamp": 1000.0}+ jittered = {**_make_event_data(), "timestamp": 1002.0}++ assert channel._console_fingerprint(first) == channel._console_fingerprint(jittered)++ def test_should_emit_console_event_dedupes_across_ms_jitter(self) -> None:+ channel, _ = _make_channel()+ first = {**_make_event_data(), "timestamp": 1000.0}+ jittered = {**_make_event_data(), "timestamp": 1002.0}++ assert channel._should_emit_console_event(first) is True+ assert channel._should_emit_console_event(jittered) is False++ def test_should_emit_console_event_keeps_distinct_interactions(self) -> None:+ channel, _ = _make_channel()+ first = {**_make_event_data(), "timestamp": 1000.0}+ distinct_target = {+ **_make_event_data(),+ "timestamp": 1002.0,+ "target": {"tagName": "BUTTON", "id": "cancel", "skyId": "sky-2", "text": ["Cancel"]},+ }++ assert channel._should_emit_console_event(first) is True+ assert channel._should_emit_console_event(distinct_target) is True++ def test_reconnect_recapture_with_jitter_emits_single_interaction(self) -> None:+ channel, on_event = _make_channel()+ page = _make_page()+ ExfiltrationChannel._active_binding_channels[page] = channel++ # A reconnect re-injects the exfiltrate script, re-emitting the same DOM+ # interaction with an advanced browser clock; the stable fingerprint dedupes+ # it even though the channel instance (and its cache) survived the reconnect.+ channel._handle_binding_event({"page": page}, {**_make_event_data(), "timestamp": 1000.0})+ channel._handle_binding_event({"page": page}, {**_make_event_data(), "timestamp": 1002.0})++ on_event.assert_called_once()+class TestNavigationReExfiltration:@pytest.mark.asynciodiff --git a/tests/unit/services/test_browser_recording.py b/tests/unit/services/test_browser_recording.pyindex 69990b3c2..da8522a3b 100644--- a/tests/unit/services/test_browser_recording.py+++ b/tests/unit/services/test_browser_recording.py@@ -18,11 +18,14 @@ from skyvern.forge.sdk.routes.streaming.channels.exfiltration import ()from skyvern.services.browser_recording.interpretation import RecordingInterpretationSessionfrom skyvern.services.browser_recording.service import (+ DUPLICATE_ACTION_WINDOW_MS,Processor,+ _is_duplicate_action,deterministic_input_text_parameter_key,summarize_exfiltrated_recording_events,)from skyvern.services.browser_recording.types import (+ ActionClick,ActionInputText,ActionKind,ActionTarget,@@ -159,6 +162,50 @@ def test_identical_click_events_are_deduped() -> None:assert actions[0].kind == "click"+def _click_action(*, timestamp: float, sky_id: str = "sky-123", target_id: str = "button-1") -> ActionClick:+ return ActionClick(+ kind=ActionKind.CLICK,+ target=ActionTarget(+ id=target_id,+ sky_id=sky_id,+ tag_name="BUTTON",+ texts=["Click me"],+ mouse=Mouse(xp=0.5, yp=0.5),+ ),+ timestamp_start=timestamp,+ timestamp_end=timestamp,+ url="https://example.com",+ )+++def test_is_duplicate_action_empty_list_is_not_duplicate() -> None:+ assert _is_duplicate_action(_click_action(timestamp=1000.0), []) is False+++def test_is_duplicate_action_suppresses_jittered_recapture() -> None:+ existing = [_click_action(timestamp=1000.0)]+ jittered = _click_action(timestamp=1000.0 + 2)++ assert _is_duplicate_action(jittered, existing) is True+++def test_is_duplicate_action_suppresses_non_adjacent_duplicate() -> None:+ existing = [+ _click_action(timestamp=1000.0, sky_id="sky-a", target_id="a"),+ _click_action(timestamp=1010.0, sky_id="sky-b", target_id="b"),+ ]+ duplicate_of_first = _click_action(timestamp=1005.0, sky_id="sky-a", target_id="a")++ assert _is_duplicate_action(duplicate_of_first, existing) is True+++def test_is_duplicate_action_keeps_intentional_repeat_outside_window() -> None:+ existing = [_click_action(timestamp=1000.0)]+ later_repeat = _click_action(timestamp=1000.0 + DUPLICATE_ACTION_WINDOW_MS + 1)++ assert _is_duplicate_action(later_repeat, existing) is False++def test_hover() -> None:target = dict(id="button-1", skyId="sky-123", text=["Click me"])diff --git a/tests/unit/test_browser_recording_interpretation.py b/tests/unit/test_browser_recording_interpretation.pyindex b2eb66b2c..bed7a1cad 100644--- a/tests/unit/test_browser_recording_interpretation.py+++ b/tests/unit/test_browser_recording_interpretation.py@@ -232,6 +232,67 @@ def _click_streaming_event()+async def test_jittered_reclick_yields_single_draft_step(monkeypatch: pytest.MonkeyPatch) -> None:+ async def fake_llm(*args: object, **kwargs: object) -> dict[str, object]:+ return {"block_label": "click_submit", "title": "Click Submit", "prompt": "Click the submit button."}++ monkeypatch.setattr(app, "LLM_API_HANDLER", fake_llm)++ session = RecordingInterpretationSession(+ browser_session_id=PBS_ID,+ organization_id=ORG_ID,+ workflow_permanent_id=WP_ID,+ on_update=lambda _: None,+ debounce_seconds=0.01,+ max_wait_seconds=0.05,+ )++ session.ingest_events([_click_streaming_event(timestamp=1000.0, capture_seq=0)])+ session.ingest_events([_click_streaming_event(timestamp=1002.0, capture_seq=1)])+ steps = await session.flush()++ assert len(steps) == 1+++async def test_non_adjacent_duplicate_suppressed_but_later_repeat_kept(monkeypatch: pytest.MonkeyPatch) -> None:+ async def fake_llm(*args: object, **kwargs: object) -> dict[str, object]:+ return {"block_label": "click", "title": "Click", "prompt": "Click."}++ monkeypatch.setattr(app, "LLM_API_HANDLER", fake_llm)++ session = RecordingInterpretationSession(+ browser_session_id=PBS_ID,+ organization_id=ORG_ID,+ workflow_permanent_id=WP_ID,+ on_update=lambda _: None,+ debounce_seconds=0.01,+ max_wait_seconds=0.05,+ )++ session.ingest_events(+ [+ _click_streaming_event(timestamp=1000.0, capture_seq=0, sky_id="sky-a", target_id="a"),+ _click_streaming_event(timestamp=1010.0, capture_seq=1, sky_id="sky-b", target_id="b"),+ _click_streaming_event(timestamp=1005.0, capture_seq=2, sky_id="sky-a", target_id="a"),+ ]+ )+ steps = await session.flush()++ assert [(step.action_kind, step.timestamp_start) for step in steps] == [+ (ActionKind.CLICK, 1000.0),+ (ActionKind.CLICK, 1010.0),+ ]++ # A genuine later repeat of A (well outside the dedup window) is preserved.+ session.ingest_events([_click_streaming_event(timestamp=5000.0, capture_seq=3, sky_id="sky-a", target_id="a")])+ steps = await session.flush()++ assert len(steps) == 3+ assert steps[-1].timestamp_start == 5000.0++@pytest.mark.asyncioasync def test_ingest_events_sorts_unprocessed_tail_by_capture_seq() -> None:session = RecordingInterpretationSession(