Skip to content

Automate browser based workflows with AI

feat(landing): carry first-touch UTM into app CTA links (SKY-15370) (#8375)

Marc Kelechavadf8739a518fb
diff --git a/skyvern-frontend/src/components/BrowserStream.test.tsx b/skyvern-frontend/src/components/BrowserStream.test.tsx
index c5e121f3b..fd0d69c7f 100644
--- a/skyvern-frontend/src/components/BrowserStream.test.tsx
+++ b/skyvern-frontend/src/components/BrowserStream.test.tsx
@@ -88,7 +88,6 @@ const mocks = vi.hoisted(() => {
const recordingStore = {
add: vi.fn(),
- addScreenshot: vi.fn(),
applyInterpretationUpdate: vi.fn(),
compressedChunks: [],
draftEditDepth: 0,
@@ -203,7 +202,6 @@ vi.mock("@/store/useRecordingStore", () => {
const useRecordingStore = (
selector?: (state: typeof mocks.recordingStore) => unknown,
) => (selector ? selector(mocks.recordingStore) : mocks.recordingStore);
- // Also read imperatively (reset/addScreenshot/etc.) via getState().
useRecordingStore.getState = () => mocks.recordingStore;
return {
useRecordingStore,
diff --git a/skyvern-frontend/src/components/BrowserStream.tsx b/skyvern-frontend/src/components/BrowserStream.tsx
index 6ec59e4cd..3229377fe 100644
--- a/skyvern-frontend/src/components/BrowserStream.tsx
+++ b/skyvern-frontend/src/components/BrowserStream.tsx
@@ -221,10 +221,6 @@ function BrowserStream({
entity !== "browserSession" || hasBrowserSession;
const isBrowserSessionBackendReady =
entity !== "browserSession" || isBrowserSessionStarted;
- const getFrameDataUrl = useCallback(() => {
- const canvas = canvasContainer?.querySelector("canvas");
- return canvas?.toDataURL("image/jpeg", 0.5) ?? null;
- }, [canvasContainer]);
const handleMessageConnectionChange = useCallback(
(connected: boolean, event?: CloseEvent) => {
if (connected) {
@@ -268,7 +264,6 @@ function BrowserStream({
isBrowserSessionBackendReady,
exfiltrate,
workflowPermanentId,
- getFrameDataUrl,
clipboard: "vnc",
socketUrl: legacyMessageSocketUrl,
reconnectTrigger: messagesDisconnectedTrigger,
diff --git a/skyvern-frontend/src/routes/browserSessions/BrowserSessionStream.tsx b/skyvern-frontend/src/routes/browserSessions/BrowserSessionStream.tsx
index 0b28f49c1..3723d7bd9 100644
--- a/skyvern-frontend/src/routes/browserSessions/BrowserSessionStream.tsx
+++ b/skyvern-frontend/src/routes/browserSessions/BrowserSessionStream.tsx
@@ -202,10 +202,6 @@ function BrowserSessionStream({
enabled: recordingChannelEnabled,
exfiltrate: !!exfiltrate,
workflowPermanentId: workflowPermanentId ?? null,
- getFrameDataUrl: () =>
- streamImgSrcRef.current
- ? `data:image/${streamFormat};base64,${streamImgSrcRef.current}`
- : null,
clipboard: "message",
reconnectTrigger: recordingReconnectTrigger,
onConnectionChange: handleRecordingConnectionChange,
diff --git a/skyvern-frontend/src/routes/streaming/useRecordingMessageChannel.test.ts b/skyvern-frontend/src/routes/streaming/useRecordingMessageChannel.test.ts
index 7120f4260..39fe9cd48 100644
--- a/skyvern-frontend/src/routes/streaming/useRecordingMessageChannel.test.ts
+++ b/skyvern-frontend/src/routes/streaming/useRecordingMessageChannel.test.ts
@@ -3,7 +3,6 @@ import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
import {
useRecordingStore,
- type MessageInExfiltratedConsoleEvent,
type RecordingDraftStep,
} from "@/store/useRecordingStore";
@@ -65,29 +64,6 @@ async function openSocket() {
return socket;
}
-function consoleClick(timestamp: number): MessageInExfiltratedConsoleEvent {
- return {
- kind: "exfiltrated-event",
- event_name: "user_interaction",
- source: "console",
- timestamp: timestamp / 1000,
- params: {
- type: "click",
- url: "https://example.test",
- timestamp,
- target: { tagName: "BUTTON", text: ["Submit"] },
- mousePosition: { xa: 640, ya: 360, xp: 0.5, yp: 0.5 },
- activeElement: { tagName: "BUTTON" },
- window: {
- width: 1280,
- height: 720,
- scrollX: 0,
- scrollY: 0,
- },
- },
- };
-}
-
describe("useRecordingMessageChannel", () => {
beforeEach(() => {
vi.clearAllMocks();
@@ -374,36 +350,6 @@ describe("useRecordingMessageChannel", () => {
expect(useRecordingStore.getState().pendingEvents).toContainEqual(event);
});
- it("stores the current frame for an inbound console click", async () => {
- const getFrameDataUrl = vi.fn(() => "data:image/jpeg;base64,frame");
- vi.stubGlobal("requestIdleCallback", (callback: IdleRequestCallback) => {
- callback({ didTimeout: false, timeRemaining: () => 50 });
- return 1;
- });
- useRecordingStore.setState({ isRecording: true });
- renderHook(() =>
- useRecordingMessageChannel({
- browserSessionId: "pbs-1",
- enabled: true,
- exfiltrate: true,
- workflowPermanentId: null,
- getFrameDataUrl,
- clipboard: "none",
- }),
- );
- const socket = await openSocket();
-
- act(() => socket.emitMessage(consoleClick(1_700_000_000_000)));
-
- expect(getFrameDataUrl).toHaveBeenCalled();
- expect(useRecordingStore.getState().screenshots).toContainEqual({
- timestampMs: 1_700_000_000_000,
- dataUrl: "data:image/jpeg;base64,frame",
- xp: 0.5,
- yp: 0.5,
- });
- });
-
it("applies inbound interpretation updates to the recording store", async () => {
useRecordingStore.setState({ isRecording: true });
renderHook(() =>
diff --git a/skyvern-frontend/src/routes/streaming/useRecordingMessageChannel.ts b/skyvern-frontend/src/routes/streaming/useRecordingMessageChannel.ts
index 8692b2b10..5524a4563 100644
--- a/skyvern-frontend/src/routes/streaming/useRecordingMessageChannel.ts
+++ b/skyvern-frontend/src/routes/streaming/useRecordingMessageChannel.ts
@@ -4,7 +4,6 @@ import { toast } from "@/components/ui/use-toast";
import { buildOptimisticStep } from "@/routes/workflows/editor/recording/optimisticSteps";
import {
useRecordingStore,
- type ExfiltratedEventConsoleParams,
type MessageInExfiltratedEvent,
type RecordingInterpretationUpdate,
} from "@/store/useRecordingStore";
@@ -22,8 +21,6 @@ export interface UseRecordingMessageChannelOptions {
/** recording active: drives begin/end-exfiltration on edges */
exfiltrate: boolean;
workflowPermanentId: string | null;
- /** returns a data URL of the current frame for click screenshots, or null */
- getFrameDataUrl?: () => string | null;
clipboard: RecordingClipboardMode;
socketUrl?: string;
reconnectTrigger?: number;
@@ -247,38 +244,10 @@ function getMessage(data: unknown): MessageIn | undefined {
}
}
-function captureRecordingScreenshot(
- params: ExfiltratedEventConsoleParams,
- getFrameDataUrl: (() => string | null) | undefined,
-) {
- const schedule =
- typeof requestIdleCallback === "function"
- ? (fn: () => void) => requestIdleCallback(fn, { timeout: 750 })
- : (fn: () => void) => window.setTimeout(fn, 0);
-
- schedule(() => {
- try {
- const dataUrl = getFrameDataUrl?.();
- if (!dataUrl) {
- return;
- }
- useRecordingStore.getState().addScreenshot({
- timestampMs: params.timestamp,
- dataUrl,
- xp: params.mousePosition.xp,
- yp: params.mousePosition.yp,
- });
- } catch {
- // toDataURL can throw on a tainted/headless canvas; shots are optional
- }
- });
-}
-
function handleMessage(
data: unknown,
ws: WebSocket | null,
clipboard: RecordingClipboardMode,
- getFrameDataUrl: (() => string | null) | undefined,
onBeginExfiltrationError: () => void,
) {
const message = getMessage(data);
@@ -381,13 +350,6 @@ function handleMessage(
if (store.isCapturePaused()) {
break;
}
- if (
- store.isRecording &&
- message.source === "console" &&
- message.params.type === "click"
- ) {
- captureRecordingScreenshot(message.params, getFrameDataUrl);
- }
if (
store.isRecording &&
!store.finishRequested &&
@@ -555,7 +517,6 @@ export function useRecordingMessageChannel(
message,
ws,
currentOptions.clipboard,
- currentOptions.getFrameDataUrl,
scheduleBeginRetry,
);
} catch (e) {
diff --git a/skyvern-frontend/src/routes/workflows/editor/recording/RecordingPanel.tsx b/skyvern-frontend/src/routes/workflows/editor/recording/RecordingPanel.tsx
index 94802b0d3..6fa378bd6 100644
--- a/skyvern-frontend/src/routes/workflows/editor/recording/RecordingPanel.tsx
+++ b/skyvern-frontend/src/routes/workflows/editor/recording/RecordingPanel.tsx
@@ -1,12 +1,10 @@
import {
CheckIcon,
CursorArrowIcon,
- EnterFullScreenIcon,
PauseIcon,
Pencil1Icon,
PlayIcon,
TrashIcon,
- ZoomInIcon,
} from "@radix-ui/react-icons";
import { useEffect, useMemo, useRef, useState } from "react";
import { useShallow } from "zustand/react/shallow";
@@ -31,11 +29,9 @@ import { useRecordedBlocksStore } from "@/store/RecordedBlocksStore";
import { useWorkflowPanelStore } from "@/store/WorkflowPanelStore";
import {
applyDraftStepOverlays,
- findScreenshotForStep,
useRecordingStore,
type RecordingActionKind,
type RecordingDraftStep,
- type RecordingScreenshot,
} from "@/store/useRecordingStore";
import { captureRecordBrowser } from "@/util/recordBrowserTelemetry";
import { formatRecordingClock } from "@/util/recordingClock";
@@ -88,55 +84,6 @@ function formatDraftStepDisplayTitle(step: RecordingDraftStep): string {
return step.label;
}
-function StepScreenshot({ screenshot }: { screenshot: RecordingScreenshot }) {
- const [showFullPage, setShowFullPage] = useState(false);
- const xp = screenshot.xp ?? 0.5;
- const yp = screenshot.yp ?? 0.5;
-
- return (
- <div className="group/shot relative h-36 overflow-hidden rounded-md border bg-black">
- <div
- className="absolute inset-0"
- style={
- showFullPage
- ? {
- backgroundImage: `url(${screenshot.dataUrl})`,
- backgroundSize: "contain",
- backgroundRepeat: "no-repeat",
- backgroundPosition: "center",
- }
- : {
- // background-position p% pins image point p% to container
- // point p%, keeping the zoomed crop in-bounds with the click
- // point at the same relative spot as the ring below.
- backgroundImage: `url(${screenshot.dataUrl})`,
- backgroundSize: "250% auto",
- backgroundRepeat: "no-repeat",
- backgroundPosition: `${xp * 100}% ${yp * 100}%`,
- }
- }
- />
- <button
- type="button"
- className="absolute bottom-2 right-2 inline-flex items-center gap-1 rounded bg-black/70 px-2 py-1 text-[10.5px] text-slate-200 opacity-0 transition-opacity group-hover/shot:opacity-100"
- onClick={() => setShowFullPage(!showFullPage)}
- >
- {showFullPage ? (
- <>
- <ZoomInIcon className="h-3 w-3" />
- Zoom to action
- </>
- ) : (
- <>
- <EnterFullScreenIcon className="h-3 w-3" />
- Full page
- </>
- )}
- </button>
- </div>
- );
-}
-
function credentialPromptForKind(
kind: NonNullable<RecordingDraftStep["credential_kind"]>,
): {
@@ -188,7 +135,6 @@ function DraftStepCard({
step,
index,
baselineMs,
- screenshot,
onDelete,
onRename,
showCredentialPrompt,
@@ -199,7 +145,6 @@ function DraftStepCard({
step: RecordingDraftStep;
index: number;
baselineMs: number | null;
- screenshot: RecordingScreenshot | null;
onDelete: () => void;
onRename: (value: string) => void;
showCredentialPrompt: boolean;
@@ -322,11 +267,6 @@ function DraftStepCard({
</button>
</div>
</div>
- {screenshot && (
- <div className="pl-8">
- <StepScreenshot screenshot={screenshot} />
- </div>
- )}
{showCredentialPrompt && (
<div className="flex flex-wrap items-center gap-2 pl-8">
<Button
@@ -435,7 +375,6 @@ function RecordingPanel({ browserSessionId }: Props) {
deletedStepIds,
stepPatches,
dismissedCredentialStepIds,
- screenshots,
sessionRevision,
optimisticSteps: rawOptimisticSteps,
workflowPermanentId,
@@ -451,7 +390,6 @@ function RecordingPanel({ browserSessionId }: Props) {
deletedStepIds: state.deletedStepIds,
stepPatches: state.stepPatches,
dismissedCredentialStepIds: state.dismissedCredentialStepIds,
- screenshots: state.screenshots,
sessionRevision: state.sessionRevision,
optimisticSteps: state.optimisticSteps,
workflowPermanentId: state.workflowPermanentId,
@@ -643,7 +581,6 @@ function RecordingPanel({ browserSessionId }: Props) {
step={step}
index={index}
baselineMs={baselineMs}
- screenshot={findScreenshotForStep(step, screenshots)}
showCredentialPrompt={
Boolean(step.credential_kind) &&
!dismissedCredentialStepIds.includes(step.step_id)
diff --git a/skyvern-frontend/src/store/useRecordingStore.ts b/skyvern-frontend/src/store/useRecordingStore.ts
index 721ab4138..f608bc567 100644
--- a/skyvern-frontend/src/store/useRecordingStore.ts
+++ b/skyvern-frontend/src/store/useRecordingStore.ts
@@ -205,25 +205,6 @@ let optimisticStepSeq = 0;
export const nextOptimisticStepId = (): string =>
`optimistic-${(optimisticStepSeq += 1)}`;
-/**
- * The last committed frame of the live browser stream, grabbed at the moment
- * of a recorded click, matched to draft steps by source-event timestamp
- * (ms epoch).
- */
-export interface RecordingScreenshot {
- timestampMs: number;
- dataUrl: string;
- xp: number | null;
- yp: number | null;
-}
-
-const MAX_SCREENSHOTS = 40;
-// dataUrl.length tracks base64-encoded JPEG bytes; cap total in-memory footprint.
-const MAX_SCREENSHOT_BYTES = 8 * 1024 * 1024;
-
-/** Tolerance when matching a screenshot to a step's source-event window. */
-const SCREENSHOT_MATCH_TOLERANCE_MS = 750;
-
/**
* Number of events per compressed chunk.
*/
@@ -303,7 +284,6 @@ interface RecordingStore {
* resumed.
*/
manualCapturePaused: boolean;
- screenshots: Array<RecordingScreenshot>;
/**
* Set when the user hits Done: exfiltration stops, and the commit fires once
* the finalized interpretation snapshot arrives (or a timeout elapses).
@@ -327,7 +307,6 @@ interface RecordingStore {
endDraftEdit: () => void;
setManualCapturePaused: (paused: boolean) => void;
isCapturePaused: () => boolean;
- addScreenshot: (screenshot: RecordingScreenshot) => void;
requestFinish: () => void;
setIsCommitting: (isCommitting: boolean) => void;
/**
@@ -453,38 +432,6 @@ export function countVisibleDraftSteps(
return count;
}
-/**
- * The screenshot taken closest to the step's source-event window, if any.
- *
- * Both sides of the comparison are the same clock: the screenshot's
- * `timestampMs` is the exfiltrated event's `params.timestamp` (remote-browser
- * `Date.now()`, ms epoch), and the step's `timestamp_start`/`timestamp_end`
- * are the backend echoing that same source-event timestamp back
- * (RecordingDraftStep "Source-action event timestamps (ms epoch)").
- */
-export function findScreenshotForStep(
- step: RecordingDraftStep,
- screenshots: Array<RecordingScreenshot>,
-): RecordingScreenshot | null {
- const start = step.timestamp_start;
- if (start === null || start === undefined) {
- return null;
- }
- const end = step.timestamp_end ?? start;
-
- let best: RecordingScreenshot | null = null;
- let bestDistance = Infinity;
- for (const screenshot of screenshots) {
- const t = screenshot.timestampMs;
- const distance = t < start ? start - t : t > end ? t - end : 0; // 0 inside the window
- if (distance <= SCREENSHOT_MATCH_TOLERANCE_MS && distance < bestDistance) {
- best = screenshot;
- bestDistance = distance;
- }
- }
- return best;
-}
-
const EXPOSED_CONSOLE_EVENT_TYPES = new Set(["focus", "click", "keypress"]);
const isExposedEvent = (event: MessageInExfiltratedEvent): boolean => {
@@ -524,7 +471,6 @@ function emptyRecordingState() {
dismissedCredentialStepIds: [] as Array<string>,
draftEditDepth: 0,
manualCapturePaused: false,
- screenshots: [] as Array<RecordingScreenshot>,
finishRequested: false,
isCommitting: false,
};
@@ -551,7 +497,6 @@ export const useRecordingStore = create<RecordingStore>((set, get) => ({
dismissedCredentialStepIds: [],
draftEditDepth: 0,
manualCapturePaused: false,
- screenshots: [],
finishRequested: false,
isCommitting: false,
@@ -703,24 +648,6 @@ export const useRecordingStore = create<RecordingStore>((set, get) => ({
return state.manualCapturePaused || state.draftEditDepth > 0;
},
- addScreenshot: (screenshot) => {
- const screenshots = [...get().screenshots, screenshot];
- let totalBytes = screenshots.reduce(
- (sum, item) => sum + item.dataUrl.length,
- 0,
- );
- while (screenshots.length > 1 && totalBytes > MAX_SCREENSHOT_BYTES) {
- const removed = screenshots.shift();
- if (removed) {
- totalBytes -= removed.dataUrl.length;
- }
- }
- if (screenshots.length > MAX_SCREENSHOTS) {
- screenshots.splice(0, screenshots.length - MAX_SCREENSHOTS);
- }
- set({ screenshots });
- },
-
requestFinish: () => {
if (get().finishRequested) {
return;
diff --git a/skyvern/forge/taskv3/tools.py b/skyvern/forge/taskv3/tools.py
index c4ac427a5..b9015afcd 100644
--- a/skyvern/forge/taskv3/tools.py
+++ b/skyvern/forge/taskv3/tools.py
@@ -1813,13 +1813,22 @@ _COMMIT_SURFACE_JS = (
// Actual instruction SYNTAX, not a keyword alone ("Austin, Clear Lake" is a place, not an
// instruction) — mirror of the Python _INSTRUCTION_CLAUSE_RE.
const INSTRUCTION_RE = /\b(?:press|tap|click|hit)\s+(?:delete|backspace|enter|escape)\b|\bto\s+(?:delete|remove|clear|dismiss|deselect)\b|\b(?:delete|remove|clear|dismiss|deselect|backspace)\s+(?:the\s+)?(?:value|values|selection|selections|item|items|option|options|entry|entries|choice|choices|tag|tags|this|it|all)\b/i;
+ // Exact, or the value plus ONE parenthesized decoration ("United Kingdom (+44)") — the canonical-
+ // label idiom that otherwise loops a covered field forever. Nothing looser: a prefix without its
+ // own " (" boundary and a non-parenthetical suffix both stay refusals.
+ const satisfied = (text) => {
+ if (text === want) return true;
+ if (!(text.length > want.length + 3 && text.startsWith(want + ' (') && text.endsWith(')'))) return false;
+ const inner = text.slice(want.length + 2, -1);
+ return inner.length > 0 && !inner.includes('(') && !inner.includes(')');
+ };
const clauseHolds = (raw) => {
const own = nrm(raw).split('|')[0].trim();
if (!own) return false;
- if (own === want) return true;
+ if (satisfied(own)) return true;
const cut = own.lastIndexOf(',');
if (cut <= 0 || !INSTRUCTION_RE.test(own.slice(cut + 1))) return false;
- return own.slice(0, cut).trim() === want;
+ return satisfied(own.slice(0, cut).trim());
};
// The stamped [data-tv3-sugglist] container is the LIVE option list of the pick in flight: its
// rows are offers, never commits, and a re-render that strips row tags keeps the container stamp.
@@ -1871,7 +1880,7 @@ _COMMIT_SURFACE_JS = (
// committed label beside a field whose own value is an opaque id). Exact match only.
for (const cand of scope.querySelectorAll('*')) {
if (cand.children.length > 0 || excluded(cand) || !visible(cand)) continue;
- if (nrm(cand.textContent) === want || nrm(cand.getAttribute('aria-label')) === want) return true;
+ if (satisfied(nrm(cand.textContent)) || satisfied(nrm(cand.getAttribute('aria-label')))) return true;
}
}
return false;
@@ -7426,6 +7435,15 @@ def build_browser_tools(
if not want:
return False
+ def satisfied(text: str) -> bool:
+ # Exact, or the value plus ONE parenthesized decoration ("United Kingdom (+44)") — the
+ # canonical-label idiom that otherwise loops a covered field forever. Nothing looser:
+ # a prefix without its own " (" boundary ("United" vs "United Kingdom (+44)") and a
+ # non-parenthetical suffix both stay refusals.
+ if text == want:
+ return True
+ return bool(re.fullmatch(re.escape(want) + r" \([^()]+\)", text))
+
def holds(raw: object) -> bool:
# The committed label may itself contain commas ("Korea, Republic of"); the widget's
# instruction ("press delete to clear value.") is ONE trailing comma-clause. Strip it
@@ -7434,12 +7452,12 @@ def build_browser_tools(
own = norm(str(raw or "")).split("|")[0].strip()
if not own:
return False
- if own == want:
+ if satisfied(own):
return True
head, _, tail = own.rpartition(",")
if not head or not _INSTRUCTION_CLAUSE_RE.search(tail):
return False
- return head.strip() == want
+ return satisfied(head.strip())
if holds((occluder or {}).get("name")):
return True
diff --git a/skyvern/services/browser_recording/types.py b/skyvern/services/browser_recording/types.py
index ef86dba3f..77a19f8fa 100644
--- a/skyvern/services/browser_recording/types.py
+++ b/skyvern/services/browser_recording/types.py
@@ -132,8 +132,6 @@ class RecordingDraftStep(BaseModel):
editable_fields: list[RecordingDraftStepEditableField] = Field(default_factory=list)
parameters: list[dict[str, t.Any]] = Field(default_factory=list)
parameter_keys: list[str] = Field(default_factory=list)
- # Source-action event timestamps (ms epoch), so clients can correlate
- # locally-captured artifacts (e.g. stream screenshots) with each step.
timestamp_start: float | None = None
timestamp_end: float | None = None
credential_kind: CredentialKind | None = None
diff --git a/tests/unit/test_browser_health.py b/tests/unit/test_browser_health.py
index d5e8dceff..329bd701a 100644
--- a/tests/unit/test_browser_health.py
+++ b/tests/unit/test_browser_health.py
@@ -100,7 +100,7 @@ class TestEvaluateRecordsBrowserHealth:
frame=MagicMock(),
expression="() => 7",
evaluate_expression=answers,
- timeout_ms=1000,
+ timeout_ms=30_000,
)
== 7
)
@@ -124,7 +124,7 @@ class TestEvaluateRecordsBrowserHealth:
)
frame.wait_for_load_state = AsyncMock()
- assert await SkyvernFrame.evaluate(frame=frame, expression="() => 7", timeout_ms=1000) == 7
+ assert await SkyvernFrame.evaluate(frame=frame, expression="() => 7", timeout_ms=30_000) == 7
assert context.browser_health.consecutive_timeouts == 0
assert not context.browser_health.stuck_operations
diff --git a/tests/unit/test_taskv3_tools.py b/tests/unit/test_taskv3_tools.py
index aa3c40bfa..662bb3082 100644
--- a/tests/unit/test_taskv3_tools.py
+++ b/tests/unit/test_taskv3_tools.py
@@ -19750,6 +19750,46 @@ async def test_select_combobox_prefix_completion_commit_is_accepted() -> None:
)
+# SKY-15364: a committed pill whose label is the requested value plus a parenthesized decoration
+# ("United Kingdom (+44)") must satisfy the covered-field already-holds read — and nothing looser.
+def _decorated_pill_covered_html(pill_label: str) -> str:
+ return f"""
+<!doctype html><html><body style="margin:0;font:14px sans-serif">
+<div id="wrapd" style="position:absolute;top:0;left:0;width:340px">
+ <label for="cityd">Phone code</label>
+ <input id="cityd" type="text" autocomplete="off" style="width:300px;height:26px">
+ <span class="pill">{pill_label}</span>
+</div>
+<div id="overlayd" style="position:absolute;top:0;left:0;width:340px;height:60px;background:#fffc;z-index:50">{pill_label}</div>
+</body></html>
+"""
+
+
+@_skip_no_browser
+ ("pill", "value", "expect_ok"),
+ [
+ ("United Kingdom (+44), press delete to clear value.", "United Kingdom", True),
+ ("United Kingdom (+44)", "United Kingdom", True),
+ # Precision: a shorter request must not match a longer decorated label...
+ ("United Kingdom (+44), press delete to clear value.", "United", False),
+ # ...and a non-parenthetical suffix is not a decoration.
+ ("United Kingdom +44, press delete to clear value.", "United Kingdom", False),
+ ],
+ ids=["decorated-with-instruction", "decorated-bare", "shorter-request-refused", "non-parenthetical-refused"],
+)
+async def test_covered_field_decorated_pill_already_holds(pill: str, value: str, expect_ok: bool) -> None:
+ async with _content_page(_decorated_pill_covered_html(pill)) as page:
+ tools = build_browser_tools(_fixed_page_provider(page))
+ picked = await _tool(tools, "select_combobox").handler({"selector": "#cityd", "value": value})
+ if expect_ok:
+ assert picked.status == "ok", picked.content
+ assert "already" in picked.content, picked.content
+ else:
+ assert picked.status == "error", picked.content
+
+
@_skip_no_browser
@pytest.mark.asyncio
async def test_select_combobox_errored_pre_click_snapshot_fails_closed() -> None: