Automate browser based workflows with AI
Python aiapiautomationbrowserbrowser-automationcomputergptllmplaywrightpowerautomatepuppeteerpythonrpaseleniumvisionworkflow
Move schedule button beside save (#6368)
Suchintan9a93281c1727
diff --git a/docs/screenshots/schedule-button-placement-before.png b/docs/screenshots/schedule-button-placement-before.pngnew file mode 100644index 000000000..caefd1841Binary files /dev/null and b/docs/screenshots/schedule-button-placement-before.png differdiff --git a/docs/screenshots/schedule-button-placement.png b/docs/screenshots/schedule-button-placement.pngnew file mode 100644index 000000000..e2609e94bBinary files /dev/null and b/docs/screenshots/schedule-button-placement.png differdiff --git a/skyvern-frontend/src/components/BrowserStream.tsx b/skyvern-frontend/src/components/BrowserStream.tsxindex 7d31430bd..3fff348bd 100644--- a/skyvern-frontend/src/components/BrowserStream.tsx+++ b/skyvern-frontend/src/components/BrowserStream.tsx@@ -395,11 +395,11 @@ function BrowserStream({prev ??(clean? {- title: "The stream packed up and left",+ title: "The browser stream packed up and left",detail: "The browser stream closed cleanly.",}: {- title: "The connection slipped away",+ title: "The browser stream slipped away",detail:"The browser stream dropped before everything wrapped up.",hint: "Refresh the page or switch to local browser streaming.",@@ -503,13 +503,13 @@ function BrowserStream({prev ??(code === 1006? {- title: "The connection slipped away",+ title: "The messages channel slipped away",detail:"The messages channel dropped before sending a frame.",hint: "Check that the API server is reachable from the UI.",}: {- title: "The stream packed up and left",+ title: "The messages channel packed up and left",detail: `Messages channel closed with code ${code}${reason ? ` (${reason})` : ""}.`,}),);diff --git a/skyvern-frontend/src/routes/workflows/editor/WorkflowHeader.tsx b/skyvern-frontend/src/routes/workflows/editor/WorkflowHeader.tsxindex 4494ff478..faf81406f 100644--- a/skyvern-frontend/src/routes/workflows/editor/WorkflowHeader.tsx+++ b/skyvern-frontend/src/routes/workflows/editor/WorkflowHeader.tsx@@ -259,15 +259,15 @@ function EditorActionToolbar() {<div className="flex items-center gap-2"><BrowserModeButton /><SaveButton />- <EditorOverflowMenu />- <div className="mx-1 h-6 w-px bg-slate-700" aria-hidden="true" />- <PanelToggleButton content="parameters" label="Inputs" /><PanelToggleButtoncontent="schedules"label="Schedule"leadingIcon={<CalendarIcon className="h-5 w-5" />}iconOnly/>+ <EditorOverflowMenu />+ <div className="mx-1 h-6 w-px bg-slate-700" aria-hidden="true" />+ <PanelToggleButton content="parameters" label="Inputs" /><RunButton /></div>);diff --git a/skyvern-frontend/src/routes/workflows/editor/hooks/useIsFirstNodeInWorkflow.tsx b/skyvern-frontend/src/routes/workflows/editor/hooks/useIsFirstNodeInWorkflow.tsxindex 702e0840c..16f8d91d5 100644--- a/skyvern-frontend/src/routes/workflows/editor/hooks/useIsFirstNodeInWorkflow.tsx+++ b/skyvern-frontend/src/routes/workflows/editor/hooks/useIsFirstNodeInWorkflow.tsx@@ -6,6 +6,11 @@ function isFirstNode(nodes: Array<AppNode>, edges: Array<Edge>, id: string) {if (!node) {return false; // doesn't make sense but for TS}+ // Blocks nested inside a conditional or loop always show the tip since they+ // are never connected to the top-level start node.+ if (node.parentId) {+ return true;+ }const incomingEdge = edges.find((edge) => edge.target === node.id);if (!incomingEdge) {return false;@@ -15,7 +20,7 @@ function isFirstNode(nodes: Array<AppNode>, edges: Array<Edge>, id: string) {if (!sourceNode) {return false;}- return !node.parentId && sourceNode.type === "start";+ return sourceNode.type === "start";}type Props = {diff --git a/skyvern-frontend/src/routes/workflows/editor/panels/BlockConfigForm/ValidationBlockForm.test.tsx b/skyvern-frontend/src/routes/workflows/editor/panels/BlockConfigForm/ValidationBlockForm.test.tsxindex a67ad3fab..515a78fee 100644--- a/skyvern-frontend/src/routes/workflows/editor/panels/BlockConfigForm/ValidationBlockForm.test.tsx+++ b/skyvern-frontend/src/routes/workflows/editor/panels/BlockConfigForm/ValidationBlockForm.test.tsx@@ -177,8 +177,9 @@ vi.mock(}),);+const isFirstBlockMock = vi.fn<() => boolean>(() => false);vi.mock("../../hooks/useIsFirstNodeInWorkflow", () => ({- useIsFirstBlockInWorkflow: () => false,+ useIsFirstBlockInWorkflow: () => isFirstBlockMock(),}));// shadcn Switch is a Radix primitive that depends on PointerEvent semantics@@ -225,6 +226,8 @@ beforeEach(() => {vi.useFakeTimers();mockNodes.clear();updateNodeData.mockReset();+ isFirstBlockMock.mockReset();+ isFirstBlockMock.mockReturnValue(false);usePendingCommitsStore.setState({ commits: {} });useSidebarSaveStateStore.getState().reset();});@@ -272,6 +275,20 @@ describe("ValidationBlockForm (SKY-9361)", () => {expect(container.firstChild).toBeNull();});+ test("shows input tip when isFirstBlockInWorkflow returns true (e.g. nested block)", () => {+ isFirstBlockMock.mockReturnValue(true);+ setValidationNode("v1");+ render(<ValidationBlockForm blockId="v1" />);+ expect(screen.getByText(/Use the \+ button to add inputs/i)).toBeDefined();+ });++ test("hides input tip when isFirstBlockInWorkflow returns false", () => {+ isFirstBlockMock.mockReturnValue(false);+ setValidationNode("v1");+ render(<ValidationBlockForm blockId="v1" />);+ expect(screen.queryByText(/Use the \+ button to add inputs/i)).toBeNull();+ });+test("renders both top-level textareas with current values", () => {setValidationNode("v1", {completeCriterion: "the page shows success",diff --git a/skyvern-frontend/src/routes/workflows/workflowRun/ObserverThoughtScreenshot.tsx b/skyvern-frontend/src/routes/workflows/workflowRun/ObserverThoughtScreenshot.tsxindex bb18ec051..d9b59db2f 100644--- a/skyvern-frontend/src/routes/workflows/workflowRun/ObserverThoughtScreenshot.tsx+++ b/skyvern-frontend/src/routes/workflows/workflowRun/ObserverThoughtScreenshot.tsx@@ -21,10 +21,6 @@ function ObserverThoughtScreenshot({ observerThoughtId, taskStatus }: Props) {const credentialGetter = useCredentialGetter();const [imageFailed, setImageFailed] = useState(false);- useEffect(() => {- setImageFailed(false);- }, [observerThoughtId]);-const { data: artifacts, isLoading } = useQuery<Array<ArtifactApiResponse>>({queryKey: ["observerThought", observerThoughtId, "artifacts"],queryFn: async () => {@@ -52,6 +48,10 @@ function ObserverThoughtScreenshot({ observerThoughtId, taskStatus }: Props) {// use the last screenshot as the llmScreenshots are in reverse orderconst screenshot = llmScreenshots?.[llmScreenshots.length - 1];+ useEffect(() => {+ setImageFailed(false);+ }, [observerThoughtId, screenshot?.signed_url]);+if (isLoading) {return (<StreamStatusPaneldiff --git a/skyvern-frontend/src/routes/workflows/workflowRun/WorkflowRunBlockScreenshot.tsx b/skyvern-frontend/src/routes/workflows/workflowRun/WorkflowRunBlockScreenshot.tsxindex df8951881..e1dde0931 100644--- a/skyvern-frontend/src/routes/workflows/workflowRun/WorkflowRunBlockScreenshot.tsx+++ b/skyvern-frontend/src/routes/workflows/workflowRun/WorkflowRunBlockScreenshot.tsx@@ -21,10 +21,6 @@ function WorkflowRunBlockScreenshot({ workflowRunBlockId, runStatus }: Props) {const credentialGetter = useCredentialGetter();const [imageFailed, setImageFailed] = useState(false);- useEffect(() => {- setImageFailed(false);- }, [workflowRunBlockId]);-const { data: artifacts, isLoading } = useQuery<Array<ArtifactApiResponse>>({queryKey: ["workflowRunBlock", workflowRunBlockId, "artifacts"],queryFn: async () => {@@ -53,6 +49,10 @@ function WorkflowRunBlockScreenshot({ workflowRunBlockId, runStatus }: Props) {const screenshot = llmScreenshots?.[0];+ useEffect(() => {+ setImageFailed(false);+ }, [workflowRunBlockId, screenshot?.signed_url]);+if (isLoading) {return (<StreamStatusPaneldiff --git a/skyvern-frontend/vitest.setup.ts b/skyvern-frontend/vitest.setup.tsindex bb03b615f..4d98cfd7e 100644--- a/skyvern-frontend/vitest.setup.ts+++ b/skyvern-frontend/vitest.setup.ts@@ -45,3 +45,16 @@ if (localStorageNeedsShim) {value: storage,});}++// Radix focus primitives create CustomEvent via the global constructor, then+// dispatch on jsdom elements. Keep those constructors from the same realm.+if (typeof window !== "undefined") {+ Object.defineProperty(globalThis, "Event", {+ configurable: true,+ value: window.Event,+ });+ Object.defineProperty(globalThis, "CustomEvent", {+ configurable: true,+ value: window.CustomEvent,+ });+}diff --git a/skyvern/forge/sdk/copilot/composition_browser_expressions.py b/skyvern/forge/sdk/copilot/composition_browser_expressions.pynew file mode 100644index 000000000..7f1b875e9--- /dev/null+++ b/skyvern/forge/sdk/copilot/composition_browser_expressions.py@@ -0,0 +1,66 @@+"""Browser-side expressions used by Workflow Copilot composition inspection."""++from __future__ import annotations++# Keep stripped-body evaluate results under the shared MCP response cap while+# preserving as much below-fold page structure as possible.+COMPOSITION_STRIPPED_HTML_MAX_CHARS = 135000+COMPOSITION_STRIPPED_HTML_EXPRESSION = (+ "(() => {"+ " const b = document.body; if (!b) return '';"+ " const c = b.cloneNode(true);"+ " c.querySelectorAll('script,style,noscript,svg,template,iframe,canvas,link').forEach(n => n.remove());"+ " const w = document.createTreeWalker(c, NodeFilter.SHOW_COMMENT, null);"+ " const comments = []; while (w.nextNode()) comments.push(w.currentNode); comments.forEach(n => n.remove());"+ " const h = c.innerHTML.replace(/>\\s+</g, '><').replace(/\\s{2,}/g, ' ');"+ f" return h.length > {COMPOSITION_STRIPPED_HTML_MAX_CHARS} ? "+ f"h.slice(0, {COMPOSITION_STRIPPED_HTML_MAX_CHARS}) : h;"+ "})()"+)++COMPOSITION_VISUAL_OBSTRUCTION_CANDIDATES_EXPRESSION = (+ "(() => {"+ " const body = document.body; if (!body) return [];"+ " const viewportWidth = window.innerWidth || document.documentElement.clientWidth || 0;"+ " const viewportHeight = window.innerHeight || document.documentElement.clientHeight || 0;"+ " const highZIndex = (value) => {"+ " const numeric = Number.parseFloat(value);"+ " return Number.isFinite(numeric) && numeric >= 10;"+ " };"+ " const visible = (style, rect) => ("+ " style.display !== 'none' && style.visibility !== 'hidden' &&"+ " Number.parseFloat(style.opacity || '1') > 0.05 && rect.width > 0 && rect.height > 0"+ " );"+ " const coversViewport = (rect) => ("+ " viewportWidth > 0 && viewportHeight > 0 &&"+ " rect.left <= viewportWidth * 0.05 && rect.top <= viewportHeight * 0.05 &&"+ " rect.right >= viewportWidth * 0.95 && rect.bottom >= viewportHeight * 0.95"+ " );"+ " const hasControl = (element) => Array.from("+ " element.querySelectorAll('button,a,input,[role=\"button\"]')"+ " ).some((control) => {"+ " const text = `${control.innerText || ''} ${control.value || ''} "+ "${control.getAttribute('aria-label') || ''}`.trim();"+ " if (!text) return false;"+ " const tag = control.tagName.toLowerCase();"+ " const type = (control.getAttribute('type') || '').toLowerCase();"+ " return tag !== 'input' || ['button', 'submit', 'reset'].includes(type);"+ " });"+ " const candidates = [];"+ " for (const element of Array.from(body.querySelectorAll('*'))) {"+ " if (candidates.length >= 5) break;"+ " const style = window.getComputedStyle(element);"+ " if (!['fixed', 'sticky'].includes(style.position)) continue;"+ " if (!highZIndex(style.zIndex)) continue;"+ " const rect = element.getBoundingClientRect();"+ " if (!visible(style, rect) || !coversViewport(rect)) continue;"+ " candidates.push({"+ " source: 'computed_style',"+ " position: style.position,"+ " coverage: 'viewport',"+ " has_visible_controls: hasControl(element),"+ " });"+ " }"+ " return candidates;"+ "})()"+)diff --git a/skyvern/forge/sdk/copilot/composition_evidence.py b/skyvern/forge/sdk/copilot/composition_evidence.pyindex 58a0f991a..3200cb8cf 100644--- a/skyvern/forge/sdk/copilot/composition_evidence.py+++ b/skyvern/forge/sdk/copilot/composition_evidence.py@@ -62,6 +62,7 @@ _MODAL_DISMISS_HINTS: frozenset[str] = frozenset()_MODAL_DISMISS_SYMBOLS: frozenset[str] = frozenset({"x", "\u00d7"})DOM_EVIDENCE_SOURCE = "dom_html"+DOM_STYLE_EVIDENCE_SOURCE = "dom_style"SCREENSHOT_EVIDENCE_SOURCE = "screenshot"VISION_EVIDENCE_SOURCE = "vision_summary"_ANTI_BOT_PATTERNS = (@@ -214,6 +215,9 @@ def page_evidence_needs_visual_fallback(evidence: dict[str, Any]) -> bool:challenge_state = evidence.get("challenge_state")if isinstance(challenge_state, dict) and challenge_state.get("detected") is True:return True+ visual_obstruction_candidates = evidence.get("visual_obstruction_candidates")+ if isinstance(visual_obstruction_candidates, list) and visual_obstruction_candidates:+ return Truereturn bool(evidence.get("anti_bot_indicators") or evidence.get("challenge_controls"))@@ -1005,6 +1009,7 @@ def _empty_evidence(inspected_url: str, current_url: str) -> dict[str, Any]:"challenge_controls": [],"modal_overlays": [],"page_obstructions": [],+ "visual_obstruction_candidates": [],"schema_empty_page": False,"observed_empty_page": False,"empty_page_visual_state": None,@@ -1039,6 +1044,99 @@ def _classes_for(node: Any) -> list[str]:return []+def _inline_style_properties(node: Any) -> dict[str, str]:+ style = _attr_value(node, "style")+ if not style:+ return {}+ properties: dict[str, str] = {}+ for declaration in style.split(";"):+ if ":" not in declaration:+ continue+ key, value = declaration.split(":", 1)+ key = key.strip().lower()+ value = value.strip().lower()+ if key and value:+ properties[key] = value+ return properties+++def _css_zero(value: str) -> bool:+ return value.replace(" ", "") in {"0", "0px", "0%", "0rem", "0em", "0vh", "0vw"}+++def _css_full_width(value: str) -> bool:+ compact = value.replace(" ", "")+ return compact in {"100%", "100vw", "100dvw", "100lvw", "100svw"}+++def _css_full_height(value: str) -> bool:+ compact = value.replace(" ", "")+ return compact in {"100%", "100vh", "100dvh", "100lvh", "100svh"}+++def _z_index_is_high(value: str) -> bool:+ try:+ return int(float(value)) >= 10+ except (TypeError, ValueError):+ return False+++def _style_covers_viewport(properties: dict[str, str]) -> bool:+ inset = properties.get("inset")+ if inset is not None and all(_css_zero(part) for part in inset.split()):+ return True+ covers_edges = all(_css_zero(properties.get(edge, "")) for edge in ("top", "right", "bottom", "left"))+ if covers_edges:+ return True+ starts_at_origin = _css_zero(properties.get("top", "")) and _css_zero(properties.get("left", ""))+ return (+ starts_at_origin+ and _css_full_width(properties.get("width", ""))+ and _css_full_height(properties.get("height", "") or properties.get("min-height", ""))+ )+++def _node_has_clickable_descendant(node: Any) -> bool:+ if not hasattr(node, "find_all"):+ return False+ for control in node.find_all(["button", "a", "input"]):+ tag_name = str(getattr(control, "name", "") or "").lower()+ if tag_name == "input":+ field_type = str(control.get("type") or "").lower()+ if field_type not in {"button", "submit", "reset"}:+ continue+ if _node_text(control) or _attr_value(control, "value") or _attr_value(control, "aria-label"):+ return True+ for control in node.find_all(attrs={"role": "button"}):+ if _node_text(control) or _attr_value(control, "aria-label"):+ return True+ return False+++def _visual_obstruction_candidates(soup: Any) -> list[dict[str, Any]]:+ candidates: list[dict[str, Any]] = []+ for node in soup.find_all(True):+ if len(candidates) >= _MAX_PAGE_OBSTRUCTIONS:+ break+ properties = _inline_style_properties(node)+ position = properties.get("position", "")+ if position not in {"fixed", "sticky"}:+ continue+ if not _z_index_is_high(properties.get("z-index", "")):+ continue+ if not _style_covers_viewport(properties):+ continue+ candidates.append(+ {+ "source": DOM_STYLE_EVIDENCE_SOURCE,+ "position": position,+ "coverage": "viewport",+ "has_visible_controls": _node_has_clickable_descendant(node),+ }+ )+ return candidates++def _css_attr(value: str) -> str:return value.replace("\\", "\\\\").replace('"', '\\"')@@ -1394,6 +1492,7 @@ def parse_composition_html(html: str, *, inspected_url: str, current_url: str) -all_nodes = soup.find_all(True)modal_overlays = _modal_overlays(all_nodes)page_obstructions = _page_obstructions_from_modal_overlays(modal_overlays)+ visual_obstruction_candidates = _visual_obstruction_candidates(soup)forms: list[dict[str, Any]] = []for form in soup.find_all("form")[:_MAX_FORMS]:@@ -1505,6 +1604,7 @@ def parse_composition_html(html: str, *, inspected_url: str, current_url: str) -"challenge_controls": challenge_controls,"modal_overlays": modal_overlays,"page_obstructions": page_obstructions,+ "visual_obstruction_candidates": visual_obstruction_candidates,"schema_empty_page": schema_empty_page,"observed_empty_page": False,"empty_page_visual_state": None,diff --git a/skyvern/forge/sdk/copilot/tools.py b/skyvern/forge/sdk/copilot/tools.pyindex 02660250b..a6af4b04f 100644--- a/skyvern/forge/sdk/copilot/tools.py+++ b/skyvern/forge/sdk/copilot/tools.py@@ -55,6 +55,15 @@ from skyvern.forge.sdk.copilot.completion_verification import (evaluate_completion_criteria,summarize_unsatisfied_outcomes,)+from skyvern.forge.sdk.copilot.composition_browser_expressions import (+ COMPOSITION_STRIPPED_HTML_EXPRESSION as _COMPOSITION_STRIPPED_HTML_EXPRESSION,+)+from skyvern.forge.sdk.copilot.composition_browser_expressions import (+ COMPOSITION_STRIPPED_HTML_MAX_CHARS as _COMPOSITION_STRIPPED_HTML_MAX_CHARS,+)+from skyvern.forge.sdk.copilot.composition_browser_expressions import (+ COMPOSITION_VISUAL_OBSTRUCTION_CANDIDATES_EXPRESSION as _COMPOSITION_VISUAL_OBSTRUCTION_CANDIDATES_EXPRESSION,+)from skyvern.forge.sdk.copilot.composition_evidence import (composition_page_evidence_error,has_bounded_page_schema,@@ -81,7 +90,7 @@ from skyvern.forge.sdk.copilot.failure_tracking import (compute_action_sequence_fingerprint,update_repeated_failure_state,)-from skyvern.forge.sdk.copilot.llm_config import resolve_main_copilot_handler+from skyvern.forge.sdk.copilot.llm_config import resolve_fast_copilot_handler, resolve_main_copilot_handlerfrom skyvern.forge.sdk.copilot.loop_detection import (clear_failed_step_tracker_for_tools_in_ctx,detect_failed_tool_step_loop_for_ctx,@@ -7066,6 +7075,7 @@ def _composition_visual_prompt(evidence: dict[str, Any]) -> str:"form_count": len(evidence.get("forms") or []),"result_container_count": len(evidence.get("result_containers") or []),"page_obstruction_count": len(evidence.get("page_obstructions") or []),+ "visual_obstruction_candidate_count": len(evidence.get("visual_obstruction_candidates") or []),"schema_empty_page": evidence.get("schema_empty_page") is True,}return (@@ -7089,7 +7099,7 @@ def _composition_visual_prompt(evidence: dict[str, Any]) -> str:async def _composition_visual_handler(ctx: CopilotContext) -> Any | None:- return await resolve_main_copilot_handler(+ return await resolve_fast_copilot_handler(getattr(ctx, "workflow_permanent_id", None),getattr(ctx, "organization_id", None),)@@ -7225,6 +7235,7 @@ async def _composition_evidence_after_navigation_failure()if html_truncated:evidence = _composition_add_inspection_warning(evidence, "html_sliced_at_cap")+ evidence = await _augment_composition_evidence_with_computed_obstruction_candidates(ctx, evidence)if page_evidence_needs_visual_fallback(evidence):evidence = await _augment_composition_evidence_with_visual_fallback(ctx, evidence)return evidence@@ -7362,26 +7373,6 @@ _COMPOSITION_HOLLOW_RECAPTURE_DELAY_SECONDS = 2.5_COMPOSITION_NAVIGATE_TIMEOUT_SECONDS = 30.0-# Body HTML stripped of script/style/svg/comments and whitespace-collapsed so the-# evaluate result clears the shared MCP response size cap (MCP_MAX_RESPONSE_CHARS,-# 140k). The aggressive strip is what lets a heavy commerce body (e.g. ~360KB raw,-# ~155k stripped) fit whole (~113k) so the FULL page is parsed; the slice is only a-# last resort for pages still over budget, and is set as high as the cap allows so it-# loses as little below-fold structure (results/cart controls) as possible.-_COMPOSITION_STRIPPED_HTML_MAX_CHARS = 135000-_COMPOSITION_STRIPPED_HTML_EXPRESSION = (- "(() => {"- " const b = document.body; if (!b) return '';"- " const c = b.cloneNode(true);"- " c.querySelectorAll('script,style,noscript,svg,template,iframe,canvas,link').forEach(n => n.remove());"- " const w = document.createTreeWalker(c, NodeFilter.SHOW_COMMENT, null);"- " const comments = []; while (w.nextNode()) comments.push(w.currentNode); comments.forEach(n => n.remove());"- " const h = c.innerHTML.replace(/>\\s+</g, '><').replace(/\\s{2,}/g, ' ');"- f" return h.length > {_COMPOSITION_STRIPPED_HTML_MAX_CHARS} ? h.slice(0, {_COMPOSITION_STRIPPED_HTML_MAX_CHARS}) : h;"- "})()"-)--async def _composition_get_stripped_html(copilot_ctx: Any) -> tuple[str | None, bool]:"""Return (stripped_body_html, truncated). truncated is True when the expression slicedthe body at the cap, so the tail (below-fold forms/controls) is missing from the evidence."""@@ -7403,6 +7394,77 @@ async def _composition_get_stripped_html(copilot_ctx: Any) -> tuple[str | None,return value, len(value) >= _COMPOSITION_STRIPPED_HTML_MAX_CHARS+def _normalize_visual_obstruction_candidates(value: Any) -> list[dict[str, Any]]:+ if not isinstance(value, list):+ return []+ candidates: list[dict[str, Any]] = []+ for item in value:+ if len(candidates) >= 5:+ break+ if not isinstance(item, dict):+ continue+ position = item.get("position")+ coverage = item.get("coverage")+ if position not in {"fixed", "sticky"} or coverage != "viewport":+ continue+ candidates.append(+ {+ "source": "computed_style",+ "position": position,+ "coverage": "viewport",+ "has_visible_controls": item.get("has_visible_controls") is True,+ }+ )+ return candidates+++def _merge_visual_obstruction_candidates(+ evidence: dict[str, Any],+ candidates: list[dict[str, Any]],+) -> dict[str, Any]:+ if not candidates:+ return evidence+ merged = dict(evidence)+ existing = [item for item in merged.get("visual_obstruction_candidates") or [] if isinstance(item, dict)]+ for candidate in candidates:+ if len(existing) >= 5:+ break+ if candidate not in existing:+ existing.append(candidate)+ merged["visual_obstruction_candidates"] = existing[:5]+ return merged+++async def _composition_get_computed_visual_obstruction_candidates(copilot_ctx: Any) -> list[dict[str, Any]]:+ server = getattr(copilot_ctx, "discovery_mcp_server", None)+ if server is None:+ return []+ try:+ result = await asyncio.wait_for(+ server.call_internal_tool(+ "skyvern_evaluate",+ {"expression": _COMPOSITION_VISUAL_OBSTRUCTION_CANDIDATES_EXPRESSION},+ ),+ timeout=_DISCOVERY_PER_CALL_TIMEOUT_SECONDS,+ )+ except Exception:+ return []+ if not isinstance(result, dict) or not result.get("ok"):+ return []+ value = (result.get("data") or {}).get("result")+ return _normalize_visual_obstruction_candidates(value)+++async def _augment_composition_evidence_with_computed_obstruction_candidates(+ copilot_ctx: Any,+ evidence: dict[str, Any],+) -> dict[str, Any]:+ if page_evidence_needs_visual_fallback(evidence) or not has_bounded_page_schema(evidence):+ return evidence+ candidates = await _composition_get_computed_visual_obstruction_candidates(copilot_ctx)+ return _merge_visual_obstruction_candidates(evidence, candidates)++async def _composition_get_html(copilot_ctx: Any) -> tuple[str, str | None, bool]:"""Return body HTML for composition parsing, surviving the MCP response size cap.@@ -7457,6 +7519,8 @@ async def _capture_composition_evidence(await asyncio.sleep(_COMPOSITION_HOLLOW_RECAPTURE_DELAY_SECONDS)if evidence is not None and html_truncated:evidence = _composition_add_inspection_warning(evidence, "html_sliced_at_cap")+ if evidence is not None:+ evidence = await _augment_composition_evidence_with_computed_obstruction_candidates(copilot_ctx, evidence)if evidence is not None and (page_evidence_needs_visual_fallback(evidence)or (evidence.get("schema_empty_page") is True and not has_bounded_page_schema(evidence))diff --git a/tests/unit/test_copilot_composition_evidence.py b/tests/unit/test_copilot_composition_evidence.pyindex aa4a899f4..aabd26512 100644--- a/tests/unit/test_copilot_composition_evidence.py+++ b/tests/unit/test_copilot_composition_evidence.py@@ -195,6 +195,89 @@ def test_composition_parse_html_ignores_hidden_modal_overlay_markup() -> None:assert parsed["page_obstructions"] == []+def test_composition_parse_html_marks_generic_fullscreen_barrier_for_visual_fallback() -> None:+ parsed = parse_composition_html(+ """+ <html><body>+ <form id="search">+ <input id="query" name="query" type="text" />+ <button>Search</button>+ </form>+ <section+ id="interruption"+ style="position: fixed; inset: 0; z-index: 1200; background: rgba(0,0,0,.35);"+ >+ <article>+ <p>Finish this checkpoint before continuing.</p>+ <button>Continue</button>+ </article>+ </section>+ </body></html>+ """,+ inspected_url="https://example.com/results",+ current_url="https://example.com/results",+ )++ assert parsed["modal_overlays"] == []+ assert parsed["page_obstructions"] == []+ assert parsed["visual_obstruction_candidates"] == [+ {+ "source": "dom_style",+ "position": "fixed",+ "coverage": "viewport",+ "has_visible_controls": True,+ }+ ]+ assert has_bounded_page_schema(parsed) is True+ assert page_evidence_needs_visual_fallback(parsed) is True++ merged = merge_visual_composition_evidence(+ parsed,+ visual_summary={+ "summary": "A centered checkpoint panel blocks the search form.",+ "challenge_detected": False,+ "submit_blocked": False,+ "page_obstruction_detected": True,+ "obstruction_kind": "checkpoint_panel",+ "obstruction_location": "Centered over the search form.",+ "underlying_page_blocked": True,+ "visible_dismiss_controls": ["Continue"],+ },+ )++ assert merged["page_obstructions"] == [+ {+ "kind": "checkpoint_panel",+ "source": "vision_summary",+ "visual_location": "Centered over the search form.",+ "visible_controls": [{"text": "Continue"}],+ "underlying_page_blocked": True,+ }+ ]+++def test_composition_parse_html_does_not_screenshot_normal_fixed_footer() -> None:+ parsed = parse_composition_html(+ """+ <html><body>+ <form id="search">+ <input id="query" name="query" type="text" />+ <button>Search</button>+ </form>+ <footer style="position: fixed; bottom: 0; left: 0; right: 0; z-index: 1200;">+ <button>Accept</button>+ </footer>+ </body></html>+ """,+ inspected_url="https://example.com/results",+ current_url="https://example.com/results",+ )++ assert parsed["visual_obstruction_candidates"] == []+ assert has_bounded_page_schema(parsed) is True+ assert page_evidence_needs_visual_fallback(parsed) is False++def test_composition_parse_html_ignores_empty_modal_root_as_bounded_schema() -> None:parsed = parse_composition_html("""diff --git a/tests/unit/test_copilot_discovery.py b/tests/unit/test_copilot_discovery.pyindex 1f16c0a96..63af6d2f3 100644--- a/tests/unit/test_copilot_discovery.py+++ b/tests/unit/test_copilot_discovery.py@@ -180,6 +180,63 @@ class _CurrentPageServer:"html": "<html><body><form><input name='firstName'><button>Search</button></form></body></html>"},}+ if tool_name == "skyvern_evaluate":+ assert "getComputedStyle" in arguments["expression"]+ return {"ok": True, "data": {"result": []}}+ raise AssertionError(f"unexpected tool: {tool_name}")+++class _GenericBarrierServer:+ def __init__(self) -> None:+ self.calls: list[str] = []++ async def call_internal_tool(self, tool_name: str, arguments: dict[str, Any]) -> dict[str, Any]:+ self.calls.append(tool_name)+ if tool_name == "skyvern_navigate":+ return {"ok": True, "data": {"url": arguments["url"]}}+ if tool_name == "skyvern_get_html":+ assert arguments == {"selector": "body"}+ return {+ "ok": True,+ "data": {+ "html": """+ <html><head>+ <style>+ .checkpoint-shell {+ position: fixed;+ inset: 0;+ z-index: 2000;+ background: rgba(0,0,0,.4);+ }+ </style>+ </head><body>+ <form id="search"><input name="q"><button>Search</button></form>+ <section id="checkpoint" class="checkpoint-shell">+ <p>Complete this checkpoint before continuing.</p>+ <button>Continue</button>+ </section>+ </body></html>+ """+ },+ }+ if tool_name == "skyvern_evaluate":+ assert "getComputedStyle" in arguments["expression"]+ return {+ "ok": True,+ "data": {+ "result": [+ {+ "source": "computed_style",+ "position": "fixed",+ "coverage": "viewport",+ "has_visible_controls": True,+ }+ ]+ },+ }+ if tool_name == "skyvern_screenshot":+ assert arguments == {"inline": True}+ return {"ok": True, "data": {"screenshot_base64": "aGVsbG8="}}raise AssertionError(f"unexpected tool: {tool_name}")@@ -201,6 +258,9 @@ class _TargetThenCurrentPageServer:"html": "<html><body><form><input name='firstName'><button>Search</button></form></body></html>"},}+ if tool_name == "skyvern_evaluate":+ assert "getComputedStyle" in arguments["expression"]+ return {"ok": True, "data": {"result": []}}raise AssertionError(f"unexpected tool: {tool_name}")@@ -314,7 +374,7 @@ async def test_inspect_current_page_uses_existing_browser_page(monkeypatch: pyteresult = await _inspect_page_for_composition_impl(ctx, "current_page")assert result["ok"] is True- assert server.calls == ["skyvern_get_html"]+ assert server.calls == ["skyvern_get_html", "skyvern_evaluate"]assert result["data"]["current_url"] == "https://www.example.com/results"assert result["data"]["workflow_run_id"] == "wr_123"assert result["data"]["observed_after_workflow_run"] is True@@ -405,6 +465,57 @@ async def test_inspection_budget_steers_progress_check_instead_of_authoring() ->assert "Compose from existing evidence" not in result["error"]+async def test_target_url_inspection_uses_visual_summary_for_generic_obstruction(+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ server = _GenericBarrierServer()+ ctx = _Ctx(server)++ async def fake_visual_summary(+ _ctx: object,+ *,+ evidence: dict[str, Any],+ screenshot_b64: str,+ ) -> tuple[dict[str, Any], None]:+ assert screenshot_b64 == "aGVsbG8="+ assert evidence["visual_obstruction_candidates"][0]["coverage"] == "viewport"+ return {+ "summary": "A checkpoint panel blocks the search form.",+ "challenge_detected": False,+ "challenge_kind": "",+ "challenge_location": "",+ "submit_blocked": False,+ "blocked_submit_controls": [],+ "empty_page_visible": False,+ "loading_state_visible": False,+ "page_obstruction_detected": True,+ "obstruction_kind": "checkpoint_panel",+ "obstruction_location": "Centered over the form.",+ "underlying_page_blocked": True,+ "visible_dismiss_controls": ["Continue"],+ "omissions": [],+ }, None++ monkeypatch.setattr(tools_module, "_composition_summarize_screenshot", fake_visual_summary)++ result = await _inspect_page_for_composition_impl(ctx, "https://www.example.com/search")++ assert result["ok"] is True+ assert "skyvern_evaluate" in server.calls+ assert "skyvern_screenshot" in server.calls+ assert result["data"]["screenshot_used"] is True+ assert result["data"]["page_obstructions"] == [+ {+ "kind": "checkpoint_panel",+ "source": "vision_summary",+ "visual_location": "Centered over the form.",+ "visible_controls": [{"text": "Continue"}],+ "underlying_page_blocked": True,+ }+ ]++@pytest.mark.asyncioasync def test_target_url_inspection_clears_pending_interaction_credit(monkeypatch: pytest.MonkeyPatch,diff --git a/tests/unit/test_workflow_copilot_llm_config.py b/tests/unit/test_workflow_copilot_llm_config.pyindex 4bcc7765e..37c200d1a 100644--- a/tests/unit/test_workflow_copilot_llm_config.py+++ b/tests/unit/test_workflow_copilot_llm_config.py@@ -1,7 +1,7 @@"""Tests for the workflow-copilot v2 LLM key wiring (SKY-10642).Two optional settings give operators independent control over (a) the main-Copilot reasoning/guardrail/evidence lane and (b) the narration-only fast lane:+Copilot reasoning/guardrail/evidence lane and (b) the fast-consumer lane:``WORKFLOW_COPILOT_AGENT_LLM_KEY`` and ``WORKFLOW_COPILOT_FAST_LLM_KEY``.These tests cover the public contract: defaults, fallback chains, andPostHog → env-specific → default resolution order.@@ -361,18 +361,18 @@ async def test_completion_verification_handler_uses_main_copilot_lane(@pytest.mark.asyncio-async def test_composition_visual_handler_uses_main_copilot_lane(+async def test_composition_visual_handler_uses_fast_copilot_lane(monkeypatch: pytest.MonkeyPatch,) -> None:- main_handler = object()+ fast_handler = object()- async def _main_lookup(workflow_permanent_id: str | None, organization_id: str | None) -> object:+ async def _fast_lookup(workflow_permanent_id: str | None, organization_id: str | None) -> object:assert workflow_permanent_id == "wpid_1"assert organization_id == "org_1"- return main_handler+ return fast_handler- monkeypatch.setattr(copilot_tools, "resolve_main_copilot_handler", _main_lookup)+ monkeypatch.setattr(copilot_tools, "resolve_fast_copilot_handler", _fast_lookup)ctx: Any = SimpleNamespace(workflow_permanent_id="wpid_1", organization_id="org_1")handler = await copilot_tools._composition_visual_handler(ctx)- assert handler is main_handler+ assert handler is fast_handler