Skip to content

Automate browser based workflows with AI

Remove the dead Task V3 auto-observe code path (#8418)

pedrohsdb2040830373a0
diff --git a/skyvern-frontend/src/components/onboarding/OnboardingProgressBand.test.tsx b/skyvern-frontend/src/components/onboarding/OnboardingProgressBand.test.tsx
deleted file mode 100644
index d93dc0c91..000000000
--- a/skyvern-frontend/src/components/onboarding/OnboardingProgressBand.test.tsx
+++ /dev/null
@@ -1,218 +0,0 @@
-// @vitest-environment jsdom
-import { act, fireEvent, render, screen } from "@testing-library/react";
-import { MemoryRouter } from "react-router-dom";
-import { expect, it, vi } from "vitest";
-
-import { OnboardingProgressBand } from "./OnboardingProgressBand";
-
-const activeProgress = (completedCount: 0 | 1) => ({
- state: "active" as const,
- completed_count: completedCount,
- next_action_key:
- completedCount === 0
- ? ("first_agent_created" as const)
- : ("first_successful_run" as const),
- items: [
- {
- key: "first_agent_created" as const,
- completed_at: completedCount === 0 ? null : "2026-08-20T12:00:00Z",
- },
- { key: "first_successful_run" as const, completed_at: null },
- ],
-});
-
-const completedProgress = {
- state: "completed" as const,
-};
-
-const forbiddenCopy =
- /heuristic|reward|credential|api|mcp|channel|schedule|questionnaire|social|follow|role|company|referral|credits?|points?|survey/i;
-
-it.each([
- [
- 0,
- "1 of 3",
- "Describe your first agent",
- "How to build an agent",
- "https://www.skyvern.com/docs/cloud/building-agents/build-an-agent",
- ],
- [
- 1,
- "2 of 3",
- "Run agent",
- "How to run an agent",
- "https://www.skyvern.com/docs/cloud/building-agents/run-an-agent",
- ],
-] as const)(
- "renders %s server milestones as endowed progress",
- (completedCount, displayCount, primaryLabel, resourceLabel, resourceHref) => {
- const onDismiss = vi.fn();
- const onDescribeAgent = vi.fn();
- render(
- <OnboardingProgressBand
- progress={activeProgress(completedCount)}
- isPending={false}
- onDismiss={onDismiss}
- onRestore={vi.fn()}
- onDescribeAgent={onDescribeAgent}
- />,
- { wrapper: MemoryRouter },
- );
-
- expect(screen.getByText(displayCount)).toBeTruthy();
- expect(screen.getByRole("progressbar").getAttribute("aria-valuenow")).toBe(
- String(completedCount + 1),
- );
- const accountRow = screen.getByText("Account created").parentElement;
- expect(accountRow?.textContent).toContain("Complete: Account created");
- expect(accountRow?.querySelector(".sr-only")?.textContent).toBe(
- "Complete: ",
- );
- const primaryAction = screen.getByRole(
- completedCount === 0 ? "button" : "link",
- { name: primaryLabel },
- );
- if (completedCount === 0) {
- fireEvent.click(primaryAction);
- expect(onDescribeAgent).toHaveBeenCalledOnce();
- } else {
- expect(primaryAction.getAttribute("href")).toBe("/agents");
- expect(onDescribeAgent).not.toHaveBeenCalled();
- }
- expect(
- screen.getByRole("link", { name: resourceLabel }).getAttribute("href"),
- ).toBe(resourceHref);
- expect(screen.getByRole("region").textContent).not.toMatch(forbiddenCopy);
- expect(
- screen.getByText(
- "An agent is a browser automation you describe in plain words.",
- ),
- ).toBeTruthy();
-
- fireEvent.click(screen.getByRole("button", { name: "Hide setup" }));
- expect(onDismiss).toHaveBeenCalledOnce();
- },
-);
-
-it("announces pending progress and prevents another visibility mutation", () => {
- const onDismiss = vi.fn();
- render(
- <OnboardingProgressBand
- progress={activeProgress(0)}
- isPending
- onDismiss={onDismiss}
- onRestore={vi.fn()}
- onDescribeAgent={vi.fn()}
- />,
- { wrapper: MemoryRouter },
- );
-
- expect(screen.getByRole("region").getAttribute("aria-busy")).toBe("true");
- expect(
- screen.getByText("Saving setup progress…").getAttribute("aria-live"),
- ).toBe("polite");
- const hide = screen.getByRole("button", { name: "Hide setup" });
- expect(hide.getAttribute("aria-disabled")).toBe("true");
- expect(
- screen
- .getByRole("button", { name: "Describe your first agent" })
- .hasAttribute("disabled"),
- ).toBe(true);
- expect(
- screen
- .getByRole("button", { name: "How to build an agent" })
- .hasAttribute("disabled"),
- ).toBe(true);
- fireEvent.click(hide);
- expect(onDismiss).not.toHaveBeenCalled();
-});
-
-it("restores a dismissed band", () => {
- const onRestore = vi.fn();
- render(
- <OnboardingProgressBand
- progress={{ state: "dismissed" }}
- isPending={false}
- onDismiss={vi.fn()}
- onRestore={onRestore}
- onDescribeAgent={vi.fn()}
- />,
- { wrapper: MemoryRouter },
- );
-
- expect(screen.queryByText("Build your first agent")).toBeNull();
- fireEvent.click(screen.getByRole("button", { name: "Resume setup" }));
- expect(onRestore).toHaveBeenCalledOnce();
-});
-
-it("celebrates only an active to completed transition", () => {
- vi.useFakeTimers();
- const props = {
- isPending: false,
- onDismiss: vi.fn(),
- onRestore: vi.fn(),
- onDescribeAgent: vi.fn(),
- };
- const view = render(
- <MemoryRouter>
- <OnboardingProgressBand progress={activeProgress(1)} {...props} />
- </MemoryRouter>,
- );
-
- view.rerender(
- <MemoryRouter>
- <OnboardingProgressBand progress={completedProgress} {...props} />
- </MemoryRouter>,
- );
- expect(screen.getByRole("status").textContent).toContain("3 of 3 complete");
- expect(screen.getByText("First agent ready")).toBeTruthy();
-
- act(() => vi.advanceTimersByTime(1800));
- expect(screen.queryByText("First agent ready")).toBeNull();
- vi.useRealTimers();
-});
-
-it.each([
- [{ state: "completed" }],
- [{ state: "ineligible" }],
- [{ state: "unknown" }],
- [null],
-])("fails closed for non-renderable progress %#", (progress) => {
- const { container } = render(
- <OnboardingProgressBand
- progress={progress}
- isPending={false}
- onDismiss={vi.fn()}
- onRestore={vi.fn()}
- onDescribeAgent={vi.fn()}
- />,
- { wrapper: MemoryRouter },
- );
- expect(container.innerHTML).toBe("");
-});
-
-it("offers the working example as a quiet focus handoff from step 2", () => {
- render(
- <OnboardingProgressBand
- progress={activeProgress(0)}
- isPending={false}
- onDismiss={vi.fn()}
- onRestore={vi.fn()}
- onDescribeAgent={vi.fn()}
- >
- <h2 id="working-example-heading" tabIndex={-1}>
- What a finished run looks like
- </h2>
- </OnboardingProgressBand>,
- { wrapper: MemoryRouter },
- );
-
- const affordance = screen.getByRole("link", {
- name: "or copy a working example",
- });
- expect(affordance.getAttribute("href")).toBe("#working-example-heading");
- fireEvent.click(affordance);
- expect(document.activeElement).toBe(
- screen.getByRole("heading", { name: "What a finished run looks like" }),
- );
-});
diff --git a/skyvern-frontend/src/components/onboarding/OnboardingProgressBand.tsx b/skyvern-frontend/src/components/onboarding/OnboardingProgressBand.tsx
index 1e777a084..7373dd236 100644
--- a/skyvern-frontend/src/components/onboarding/OnboardingProgressBand.tsx
+++ b/skyvern-frontend/src/components/onboarding/OnboardingProgressBand.tsx
@@ -1,62 +1,7 @@
-import { CheckIcon, ExternalLinkIcon, ReloadIcon } from "@radix-ui/react-icons";
-import { useEffect, useRef, useState, type ReactNode } from "react";
-import { Link } from "react-router-dom";
+import { ReloadIcon } from "@radix-ui/react-icons";
-import { Button } from "@/components/ui/button";
-
-type ProgressActionKey = "first_agent_created" | "first_successful_run";
-type Progress = {
- state: string;
- completed_count?: number;
- next_action_key?: ProgressActionKey | null;
- items?: Array<{
- key: ProgressActionKey;
- completed_at: string | null;
- }>;
-};
-type ActiveProgress = Progress & {
- state: "active";
- completed_count: 0 | 1;
- next_action_key: ProgressActionKey;
- items: NonNullable<Progress["items"]>;
-};
-type OnboardingProgressBandProps = {
- progress: Progress | null;
- isPending: boolean;
- onDismiss: () => void;
- onRestore: () => void;
- onDescribeAgent: () => void;
- trackRemaining?: number;
- onDismissHandoff?: () => void;
- trackDismissed?: boolean;
- trackPending?: boolean;
- onRestoreTrack?: () => void;
- children?: ReactNode;
-};
type StepState = "complete" | "active" | "pending" | "upcoming";
-const milestoneLabels = [
- "Account created",
- "Create your first agent",
- "Run your first agent",
-] as const;
-
-const primaryActions = {
- first_agent_created: {
- label: "Describe your first agent",
- resourceLabel: "How to build an agent",
- resourceHref:
- "https://www.skyvern.com/docs/cloud/building-agents/build-an-agent",
- },
- first_successful_run: {
- label: "Run agent",
- href: "/agents",
- resourceLabel: "How to run an agent",
- resourceHref:
- "https://www.skyvern.com/docs/cloud/building-agents/run-an-agent",
- },
-} as const;
-
function PendingIcon() {
return (
<ReloadIcon
@@ -88,7 +33,7 @@ function StepDot({ state, index }: { state: StepState; index: number }) {
function ProgressSegments({
completedSteps,
- totalSteps = milestoneLabels.length,
+ totalSteps = 3,
label = "Setup progress",
}: {
completedSteps: number;
@@ -118,428 +63,5 @@ function ProgressSegments({
);
}
-function SetupRow({
- label,
- index,
- state,
- affordance,
- secondaryAffordance,
-}: {
- label: string;
- index: number;
- state: StepState;
- affordance?: ReactNode;
- secondaryAffordance?: ReactNode;
-}) {
- const isComplete = state === "complete";
- return (
- <li className="grid min-h-11 grid-cols-[auto_1fr_2.75rem] items-center gap-3 rounded-md border border-border/70 bg-background/70 px-3 py-2 text-sm">
- <StepDot state={state} index={index} />
- <div>
- <span
- className={
- isComplete ? "text-muted-foreground" : "font-medium text-foreground"
- }
- >
- <span className="sr-only">
- {isComplete
- ? "Complete: "
- : state === "active"
- ? "Current step: "
- : state === "pending"
- ? "Saving current step: "
- : "Upcoming step: "}
- </span>
- {label}
- </span>
- {secondaryAffordance}
- </div>
- <span className="flex min-h-11 items-center justify-end">
- {affordance}
- </span>
- </li>
- );
-}
-
-function QuietResourceLink({
- href,
- label,
- isPending,
-}: {
- href: string;
- label: string;
- isPending: boolean;
-}) {
- if (isPending) {
- return (
- <Button
- type="button"
- variant="disabled"
- disabled
- aria-label={label}
- className="size-11 p-0"
- >
- <ExternalLinkIcon aria-hidden="true" className="size-4" />
- </Button>
- );
- }
-
- return (
- <a
- href={href}
- target="_blank"
- rel="noopener noreferrer"
- title={label}
- aria-label={label}
- className="inline-flex size-11 touch-manipulation items-center justify-center rounded-md text-muted-foreground transition-colors hover:text-foreground focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-ring"
- >
- <ExternalLinkIcon aria-hidden="true" className="size-4" />
- </a>
- );
-}
-
-function ProgressPrimaryAction({
- nextActionKey,
- isPending,
- onDescribeAgent,
-}: {
- nextActionKey: ProgressActionKey;
- isPending: boolean;
- onDescribeAgent: () => void;
-}) {
- const action = primaryActions[nextActionKey];
- if (isPending) {
- return (
- <Button
- type="button"
- variant="disabled"
- disabled
- className="h-11 w-full sm:w-auto"
- >
- {action.label}
- </Button>
- );
- }
-
- if (nextActionKey === "first_agent_created") {
- return (
- <Button
- type="button"
- className="h-11 w-full touch-manipulation sm:w-auto"
- onClick={onDescribeAgent}
- >
- {action.label}
- </Button>
- );
- }
-
- return (
- <Button asChild className="h-11 w-full touch-manipulation sm:w-auto">
- <Link to={primaryActions.first_successful_run.href}>{action.label}</Link>
- </Button>
- );
-}
-
-function WorkingExampleAffordance() {
- return (
- <a
- href="#working-example-heading"
- className="ml-2 inline-flex min-h-11 touch-manipulation items-center text-xs font-normal text-muted-foreground underline-offset-4 hover:text-foreground hover:underline focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-ring"
- onClick={() => {
- document
- .getElementById("working-example-heading")
- ?.focus({ preventScroll: true });
- }}
- >
- or copy a working example
- </a>
- );
-}
-
-function HandoffRow({
- remaining,
- onDismiss,
-}: {
- remaining: number;
- onDismiss?: () => void;
-}) {
- return (
- <section
- aria-labelledby="onboarding-handoff-heading"
- aria-live="polite"
- role="status"
- className="flex min-h-11 flex-wrap items-center gap-3 rounded-lg border border-border bg-background px-5 py-3 shadow-sm motion-safe:animate-in motion-safe:fade-in motion-reduce:animate-none sm:px-6"
- >
- <span className="flex size-6 shrink-0 items-center justify-center rounded-full bg-badge-success text-foreground">
- <CheckIcon aria-hidden="true" className="size-3.5" />
- </span>
- <p
- id="onboarding-handoff-heading"
- className="text-sm font-semibold tracking-tight"
- >
- First agent ready.
- </p>
- <Link
- to="/getting-started"
- onClick={onDismiss}
- className="inline-flex min-h-11 touch-manipulation items-center text-sm text-muted-foreground underline-offset-4 hover:text-foreground hover:underline focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-ring"
- >
- Keep going: {remaining} more {remaining === 1 ? "step" : "steps"} →
- </Link>
- <Button
- type="button"
- variant="ghost"
- className="ml-auto h-11 touch-manipulation text-muted-foreground hover:text-foreground"
- onClick={onDismiss}
- >
- Hide
- </Button>
- </section>
- );
-}
-
-// A hidden track has no sidebar row and no handoff, so Home keeps one quiet
-// way back to it.
-function ResumeTrackRow({
- isPending,
- onRestore,
-}: {
- isPending: boolean;
- onRestore?: () => void;
-}) {
- return (
- <div className="flex justify-end">
- <Button
- type="button"
- variant={isPending ? "disabled" : "ghost"}
- className="h-11 touch-manipulation text-muted-foreground hover:text-foreground"
- aria-disabled={isPending}
- aria-busy={isPending}
- onClick={() => {
- if (!isPending) onRestore?.();
- }}
- >
- Resume getting started
- </Button>
- </div>
- );
-}
-
-function CompletionBand() {
- return (
- <section
- aria-labelledby="onboarding-progress-heading"
- aria-live="polite"
- role="status"
- className="overflow-hidden rounded-lg border border-border bg-background shadow-sm"
- >
- <div className="border-b border-border bg-card px-5 py-4 sm:px-6">
- <div className="flex items-center gap-3">
- <span className="flex size-8 items-center justify-center rounded-full bg-badge-success text-foreground motion-safe:animate-in motion-safe:fade-in motion-safe:zoom-in-75 motion-reduce:animate-none">
- <CheckIcon aria-hidden="true" className="size-4" />
- </span>
- <h2
- id="onboarding-progress-heading"
- className="text-base font-semibold tracking-tight"
- >
- First agent ready
- </h2>
- </div>
- <p className="mt-1 text-sm text-muted-foreground">
- <span className="sr-only">Complete: </span>3 of 3 complete
- </p>
- <div className="mt-3">
- <ProgressSegments completedSteps={3} />
- </div>
- </div>
- </section>
- );
-}
-
-function isActiveProgress(
- progress: Progress | null,
-): progress is ActiveProgress {
- return (
- progress?.state === "active" &&
- (progress.completed_count === 0 || progress.completed_count === 1) &&
- (progress.next_action_key === "first_agent_created" ||
- progress.next_action_key === "first_successful_run") &&
- Array.isArray(progress.items)
- );
-}
-
-function OnboardingProgressBand({
- progress,
- isPending,
- onDismiss,
- onRestore,
- onDescribeAgent,
- trackRemaining = 0,
- onDismissHandoff,
- trackDismissed = false,
- trackPending = false,
- onRestoreTrack,
- children,
-}: OnboardingProgressBandProps) {
- const previousState = useRef(progress?.state);
- const [isCelebrating, setIsCelebrating] = useState(false);
- // Completed progress with an active track keeps a compact handoff in place
- // of the retired band; the timed celebration only remains for a null track.
- const showHandoff = progress?.state === "completed" && trackRemaining > 0;
-
- useEffect(() => {
- const completedFromActive =
- previousState.current === "active" && progress?.state === "completed";
- previousState.current = progress?.state;
- if (!completedFromActive || showHandoff) {
- setIsCelebrating(false);
- return;
- }
-
- setIsCelebrating(true);
- const timeout = window.setTimeout(() => setIsCelebrating(false), 1800);
- return () => window.clearTimeout(timeout);
- }, [progress?.state, showHandoff]);
-
- const resumeTrack = trackDismissed ? (
- <ResumeTrackRow isPending={trackPending} onRestore={onRestoreTrack} />
- ) : null;
- if (showHandoff) {
- return (
- <HandoffRow remaining={trackRemaining} onDismiss={onDismissHandoff} />
- );
- }
- if (isCelebrating) return <CompletionBand />;
-
- const activeProgress = isActiveProgress(progress) ? progress : null;
- const isDismissed = progress?.state === "dismissed";
- if (!activeProgress && !isDismissed) return resumeTrack;
-
- const completedSteps = activeProgress
- ? activeProgress.completed_count + 1
- : 0;
- const action = activeProgress
- ? primaryActions[activeProgress.next_action_key]
- : null;
- const activeIndex = activeProgress?.items.some(
- (item) => item.key === "first_agent_created" && item.completed_at !== null,
- )
- ? 2
- : 1;
-
- return (
- <>
- <div className={activeProgress ? "relative" : "flex justify-end"}>
- <Button
- type="button"
- variant={isPending ? "disabled" : "ghost"}
- className={`z-10 h-11 touch-manipulation text-muted-foreground hover:text-foreground ${
- activeProgress ? "absolute right-5 top-4" : ""
- }`}
- aria-disabled={isPending}
- aria-busy={isPending}
- onClick={() => {
- if (isPending) return;
- if (activeProgress) onDismiss();
- else onRestore();
- }}
- >
- {isPending && <PendingIcon />}
- {activeProgress ? "Hide setup" : "Resume setup"}
- </Button>
-
- {activeProgress && action ? (
- <section
- aria-labelledby="onboarding-progress-heading"
- aria-busy={isPending}
- className="overflow-hidden rounded-lg border border-border bg-background shadow-sm"
- >
- {isPending ? (
- <span className="sr-only" aria-live="polite">
- Saving setup progress…
- </span>
- ) : null}
- <div className="border-b border-border bg-card px-5 py-4 sm:px-6">
- <div className="pr-28">
- <h2
- id="onboarding-progress-heading"
- className="text-base font-semibold tracking-tight"
- >
- Build your first agent
- </h2>
- <p className="mt-1 text-sm text-muted-foreground">
- An agent is a browser automation you describe in plain words.
- </p>
- <p className="mt-1 text-sm text-muted-foreground">
- <span className="font-semibold tabular-nums text-foreground">
- {completedSteps} of 3
- </span>{" "}
- complete
- </p>
- </div>
-
- <div className="mt-4">
- <ProgressSegments completedSteps={completedSteps} />
- </div>
-
- <ol aria-label="Setup milestones" className="mt-4 grid gap-2">
- {milestoneLabels.map((label, index) => {
- const state: StepState =
- index < completedSteps
- ? "complete"
- : isPending && index === activeIndex
- ? "pending"
- : index === activeIndex
- ? "active"
- : "upcoming";
- return (
- <SetupRow
- key={label}
- label={label}
- index={index}
- state={state}
- secondaryAffordance={
- index === 1 &&
- activeProgress.next_action_key ===
- "first_agent_created" ? (
- <WorkingExampleAffordance />
- ) : undefined
- }
- affordance={
- index === activeIndex ? (
- <QuietResourceLink
- href={action.resourceHref}
- label={action.resourceLabel}
- isPending={isPending}
- />
- ) : undefined
- }
- />
- );
- })}
- </ol>
-
- <div className="mt-4 flex flex-col items-stretch gap-2 sm:flex-row sm:items-center">
- <ProgressPrimaryAction
- nextActionKey={activeProgress.next_action_key}
- isPending={isPending}
- onDescribeAgent={onDescribeAgent}
- />
- </div>
- </div>
-
- {children && (
- <div className="[&>section]:rounded-none [&>section]:border-0">
- {children}
- </div>
- )}
- </section>
- ) : null}
- </div>
- {resumeTrack}
- </>
- );
-}
-
-export { OnboardingProgressBand, PendingIcon, ProgressSegments, StepDot };
+export { PendingIcon, ProgressSegments, StepDot };
export type { StepState };
diff --git a/skyvern-frontend/src/components/onboarding/WorkingExampleInspector.test.tsx b/skyvern-frontend/src/components/onboarding/WorkingExampleInspector.test.tsx
deleted file mode 100644
index 220b31db3..000000000
--- a/skyvern-frontend/src/components/onboarding/WorkingExampleInspector.test.tsx
+++ /dev/null
@@ -1,38 +0,0 @@
-import { fireEvent, render, screen } from "@testing-library/react";
-import { expect, it, vi } from "vitest";
-import { WorkingExampleInspector } from "./WorkingExampleInspector";
-
-it("shows provenance, structure, playback, and result before one safe copy", () => {
- const onMakeCopy = vi.fn();
- render(<WorkingExampleInspector isPending={false} onMakeCopy={onMakeCopy} />);
- expect(screen.getByText("Example data, not your run")).toBeTruthy();
- expect(
- screen.getByRole("heading", { name: "How the agent is built" }),
- ).toBeTruthy();
- expect(screen.getByText("Visit a public page")).toBeTruthy();
- expect(
- screen.getByRole("heading", { name: "What the agent did" }),
- ).toBeTruthy();
- expect(
- screen.getByText(
- "Opened https://www.skyvern.com/ in this static agent example.",
- ),
- ).toBeTruthy();
- expect(screen.getByRole("heading", { name: "Example result" })).toBeTruthy();
- expect(screen.getByText("Product summary")).toBeTruthy();
- expect(screen.getByRole("region").textContent).not.toMatch(/workflow/i);
- expect(onMakeCopy).not.toHaveBeenCalled();
- const copy = screen.getByRole("button", { name: "Make a copy" });
- expect(copy.className).toContain("border-input");
- fireEvent.click(copy);
- expect(onMakeCopy).toHaveBeenCalledTimes(1);
-});
-
-it("disables a pending copy and prevents duplicate callback", () => {
- const onMakeCopy = vi.fn();
- render(<WorkingExampleInspector isPending onMakeCopy={onMakeCopy} />);
- const button = screen.getByRole("button", { name: "Make a copy" });
- expect(button.hasAttribute("disabled")).toBe(true);
- fireEvent.click(button);
- expect(onMakeCopy).not.toHaveBeenCalled();
-});
diff --git a/skyvern-frontend/src/components/onboarding/WorkingExampleInspector.tsx b/skyvern-frontend/src/components/onboarding/WorkingExampleInspector.tsx
deleted file mode 100644
index 9ca2aa77c..000000000
--- a/skyvern-frontend/src/components/onboarding/WorkingExampleInspector.tsx
+++ /dev/null
@@ -1,103 +0,0 @@
-import { ReloadIcon } from "@radix-ui/react-icons";
-
-import { Button } from "@/components/ui/button";
-import { onboardingExamplePresentation } from "@/routes/discover/onboardingExample";
-
-type WorkingExampleInspectorProps = {
- isPending: boolean;
- onMakeCopy: () => void;
-};
-
-function WorkingExampleInspector({
- isPending,
- onMakeCopy,
-}: WorkingExampleInspectorProps) {
- const { title, provenance, structure, playback, result } =
- onboardingExamplePresentation;
-
- return (
- <section
- aria-labelledby="working-example-heading"
- className="overflow-hidden rounded-lg border border-border bg-background"
- >
- <header className="flex flex-wrap items-start justify-between gap-3 border-b border-border px-5 py-4 sm:px-6">
- <h2
- id="working-example-heading"
- tabIndex={-1}
- className="scroll-mt-24 text-base font-semibold"
- >
- {title}
- </h2>
- <p className="shrink-0 text-xs font-medium text-muted-foreground">
- {provenance}
- </p>
- </header>
- <div className="grid gap-5 p-5 sm:p-6 lg:grid-cols-3">
- <div className="min-w-0">
- <h3 className="text-sm font-semibold">How the agent is built</h3>
- <ol className="mt-3 list-decimal space-y-3 pl-4 marker:text-muted-foreground">
- {structure.map((step) => (
- <li key={step.title} className="break-words pl-1">
- <p className="text-sm font-medium">{step.title}</p>
- <p className="mt-0.5 text-xs leading-5 text-muted-foreground">
- {step.detail}
- </p>
- </li>
- ))}
- </ol>
- </div>
- <div className="min-w-0">
- <h3 className="text-sm font-semibold">What the agent did</h3>
- <ol className="mt-3 list-decimal space-y-2 pl-4 marker:text-muted-foreground">
- {playback.map((detail) => (
- <li
- key={detail}
- className="break-words pl-1 text-xs leading-5 text-muted-foreground"
- >
- {detail}
- </li>
- ))}
- </ol>
- </div>
- <div className="min-w-0">
- <h3 className="text-sm font-semibold">{result.title}</h3>
- <dl className="mt-3 divide-y divide-border rounded-md border border-border">
- {result.fields.map(({ label, value }) => (
- <div
- key={label}
- className="grid gap-1 px-3 py-2.5 sm:grid-cols-[7rem_1fr] sm:gap-3"
- >
- <dt className="break-words text-xs font-medium text-muted-foreground">
- {label}
- </dt>
- <dd className="min-w-0 break-words text-xs leading-5">
- {value}
- </dd>
- </div>
- ))}
- </dl>
- </div>
- </div>
- <footer className="flex justify-end border-t border-border px-5 py-4 sm:px-6">
- <Button
- type="button"
- variant="outline"
- className="h-11 w-full touch-manipulation sm:w-auto"
- disabled={isPending}
- aria-busy={isPending}
- onClick={onMakeCopy}
- >
- {isPending && (
- <ReloadIcon
- aria-hidden="true"
- className="mr-2 h-4 w-4 motion-safe:animate-spin motion-reduce:animate-none"
- />
- )}
- Make a copy
- </Button>
- </footer>
- </section>
- );
-}
-
-export { WorkingExampleInspector };
diff --git a/skyvern-frontend/src/routes/discover/DiscoverPage.test.tsx b/skyvern-frontend/src/routes/discover/DiscoverPage.test.tsx
index 64501052a..b972d0cdb 100644
--- a/skyvern-frontend/src/routes/discover/DiscoverPage.test.tsx
+++ b/skyvern-frontend/src/routes/discover/DiscoverPage.test.tsx
@@ -1,5 +1,5 @@
// @vitest-environment jsdom
-import { StrictMode, useState } from "react";
+import { StrictMode, useEffect, useRef, useState, type ReactNode } from "react";
import {
act,
cleanup,
@@ -8,7 +8,12 @@ import {
screen,
waitFor,
} from "@testing-library/react";
-import { MemoryRouter } from "react-router-dom";
+import {
+ MemoryRouter,
+ useLocation,
+ useNavigate,
+ useSearchParams,
+} from "react-router-dom";
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
import type {
ConfirmedPatch,
@@ -19,22 +24,12 @@ import type {
} from "@/store/onboarding/types";
import { OnboardingContext } from "@/store/onboarding/useOnboardingState";
import { DiscoverPage } from "./DiscoverPage";
-import { onboardingExampleRequest } from "./onboardingExample";
-
-type ProgressState = "active" | "dismissed" | "completed" | "ineligible";
-type ProgressActionKey = "first_agent_created" | "first_successful_run";
const mocks = vi.hoisted(() => ({
confirmed: vi.fn<(patch: ConfirmedPatch) => Promise<ConfirmedWriteResult>>(),
- progressState: null as ProgressState | null,
- completedCount: 0 as 0 | 1,
- firstMilestoneComplete: false,
- nextActionKey: "first_agent_created" as ProgressActionKey,
createPending: false,
createWorkflow: vi.fn(),
- progressPending: false,
- dismiss: vi.fn(),
- restore: vi.fn(),
+ focusAndPrefillExample: vi.fn<(key: string) => void>(),
telemetry: {
registerVariant: vi.fn(),
flowStarted: vi.fn(),
@@ -45,28 +40,6 @@ const mocks = vi.hoisted(() => ({
},
}));
-function progressForMocks() {
- if (mocks.progressState === null) return null;
- if (mocks.progressState !== "active") {
- return { state: mocks.progressState };
- }
- return {
- state: mocks.progressState,
- completed_count: mocks.completedCount,
- total_count: 2,
- next_action_key: mocks.nextActionKey,
- items: [
- {
- key: "first_agent_created",
- completed_at: mocks.firstMilestoneComplete
- ? "2026-08-20T12:00:00Z"
- : null,
- },
- { key: "first_successful_run", completed_at: null },
- ],
- };
-}
-
vi.mock("posthog-js/react", () => ({
useFeatureFlagVariantKey: () => "template-first",
}));
@@ -107,6 +80,7 @@ vi.mock("@/routes/tasks/create/PromptBox", async () => {
const textareaRef = React.useRef<HTMLTextAreaElement>(null);
React.useImperativeHandle(ref, () => ({
focusAndPrefillExample: (key) => {
+ mocks.focusAndPrefillExample(key);
setValue((current) => (current.trim() ? current : key));
textareaRef.current?.focus({ preventScroll: true });
},
@@ -130,14 +104,6 @@ vi.mock("./WorkflowTemplates", () => ({
<div data-testid="discover-templates">templates</div>
),
}));
-vi.mock("./useOnboardingProgress", () => ({
- useOnboardingProgress: () => ({
- progress: progressForMocks(),
- isPending: mocks.progressPending,
- dismiss: mocks.dismiss,
- restore: mocks.restore,
- }),
-}));
vi.mock("@/components/onboarding/QuestionnaireDetailsStep", () => ({
QuestionnaireDetailsStep: ({
expectedRevision,
@@ -207,19 +173,55 @@ function deferred<T>() {
return { promise, resolve };
}
+function LocationProbe() {
+ return <span data-testid="location">{useLocation().search}</span>;
+}
+
+function NavigationProbe() {
+ const navigate = useNavigate();
+ return (
+ <button type="button" onClick={() => navigate("/discover?focus=prompt")}>
+ Focus prompt
+ </button>
+ );
+}
+
+function PlanCleanup({ children }: { children: ReactNode }) {
+ const [searchParams, setSearchParams] = useSearchParams();
+ const handled = useRef(false);
+ useEffect(() => {
+ if (handled.current || !searchParams.has("plan")) return;
+ handled.current = true;
+ const next = new URLSearchParams(searchParams);
+ next.delete("plan");
+ setSearchParams(next, { replace: true });
+ }, [searchParams, setSearchParams]);
+ return <>{children}</>;
+}
+
function TestProvider({
initialState,
isNewUser = true,
+ initialEntries,
+ isLoading = false,
+ stateOverride,
+ showNavigation = false,
+ withPlanCleanup = false,
}: {
initialState: OnboardingState;
isNewUser?: boolean;
+ initialEntries?: string[];
+ isLoading?: boolean;
+ stateOverride?: OnboardingState | null;
+ showNavigation?: boolean;
+ withPlanCleanup?: boolean;
}) {
const [state, setState] = useState(initialState);
return (
<OnboardingContext.Provider
value={{
- state,
- isLoading: false,
+ state: stateOverride === undefined ? state : stateOverride,
+ isLoading,
updateState: (patch) =>
setState((current) => ({ ...current, ...patch })),
updateStateConfirmed: async (patch) => {
@@ -234,8 +236,16 @@ function TestProvider({
recoveryGuidanceAssignment: null,
}}
>
- <MemoryRouter>
- <DiscoverPage />
+ <MemoryRouter initialEntries={initialEntries}>
+ {withPlanCleanup ? (
+ <PlanCleanup>
+ <DiscoverPage />
+ </PlanCleanup>
+ ) : (
+ <DiscoverPage />
+ )}
+ <LocationProbe />
+ {showNavigation ? <NavigationProbe /> : null}
</MemoryRouter>
</OnboardingContext.Provider>
);
@@ -245,21 +255,21 @@ function renderDiscover(
initialState: OnboardingState,
strict = false,
isNewUser = true,
+ initialEntries?: string[],
) {
const page = (
- <TestProvider initialState={initialState} isNewUser={isNewUser} />
+ <TestProvider
+ initialState={initialState}
+ isNewUser={isNewUser}
+ initialEntries={initialEntries}
+ />
);
return render(strict ? <StrictMode>{page}</StrictMode> : page);
}
beforeEach(() => {
sessionStorage.clear();
- mocks.progressState = null;
mocks.createPending = false;
- mocks.completedCount = 0;
- mocks.firstMilestoneComplete = false;
- mocks.nextActionKey = "first_agent_created";
- mocks.progressPending = false;
mocks.confirmed.mockResolvedValue({
onboarding_state: baseState,
launch_date_at_signup: "2026-01-01T00:00:00Z",
@@ -272,6 +282,127 @@ afterEach(() => {
vi.clearAllMocks();
});
+describe("DiscoverPage focus param", () => {
+ const resolvedState = {
+ ...baseState,
+ user_intent: "fill_forms",
+ questionnaire_prompted_at: "2026-08-27T00:00:00Z",
+ questionnaire: questionnaire(true),
+ };
+
+ it("focuses and prefills once, preserving unrelated search params", async () => {
+ renderDiscover(resolvedState, false, true, [
+ "/discover?focus=prompt&foo=bar",
+ ]);
+ const prompt = await screen.findByLabelText("Discover prompt");
+ await waitFor(() =>
+ expect(mocks.focusAndPrefillExample).toHaveBeenCalledOnce(),
+ );
+ expect(mocks.focusAndPrefillExample).toHaveBeenCalledWith(
+ "contact_us_forms",
+ );
+ expect((prompt as HTMLTextAreaElement).value).toBe("contact_us_forms");
+ expect(document.activeElement).toBe(prompt);
+ expect(screen.getByTestId("location").textContent).toBe("?foo=bar");
+ expect(mocks.createWorkflow).not.toHaveBeenCalled();
+ });
+
+ it("waits for onboarding intent before consuming the focus param", async () => {
+ const view = render(
+ <TestProvider
+ initialState={resolvedState}
+ stateOverride={null}
+ isLoading
+ initialEntries={["/discover?focus=prompt"]}
+ />,
+ );
+ expect(mocks.focusAndPrefillExample).not.toHaveBeenCalled();
+ expect(screen.getByTestId("location").textContent).toBe("?focus=prompt");
+
+ view.rerender(
+ <TestProvider
+ initialState={resolvedState}
+ stateOverride={resolvedState}
+ initialEntries={["/discover?focus=prompt"]}
+ />,
+ );
+
+ await waitFor(() =>
+ expect(mocks.focusAndPrefillExample).toHaveBeenCalledOnce(),
+ );
+ expect(mocks.focusAndPrefillExample).toHaveBeenCalledWith(
+ "contact_us_forms",
+ );
+ expect(screen.getByTestId("location").textContent).toBe("");
+ });
+
+ it("prefills exactly once in StrictMode", async () => {
+ renderDiscover(resolvedState, true, true, ["/discover?focus=prompt"]);
+ await waitFor(() =>
+ expect(mocks.focusAndPrefillExample).toHaveBeenCalledOnce(),
+ );
+ });
+
+ it("does nothing when the focus param is absent", () => {
+ renderDiscover(resolvedState, false, true, ["/discover?foo=bar"]);
+ expect(mocks.focusAndPrefillExample).not.toHaveBeenCalled();
+ expect(screen.getByTestId("location").textContent).toBe("?foo=bar");
+ });
+
+ it("preserves a typed draft during same-page focus navigation", async () => {
+ render(
+ <TestProvider
+ initialState={resolvedState}
+ initialEntries={["/discover"]}
+ showNavigation
+ />,
+ );
+ const prompt = screen.getByLabelText("Discover prompt");
+ fireEvent.change(prompt, { target: { value: "my draft" } });
+ fireEvent.click(screen.getByRole("button", { name: "Focus prompt" }));
+
+ await waitFor(() =>
+ expect(mocks.focusAndPrefillExample).toHaveBeenCalledOnce(),
+ );
+ expect((prompt as HTMLTextAreaElement).value).toBe("my draft");
+ expect(document.activeElement).toBe(prompt);
+ expect(screen.getByTestId("location").textContent).toBe("");
+ });
+
+ it("handles a later same-page focus navigation again", async () => {
+ render(
+ <TestProvider
+ initialState={resolvedState}
+ initialEntries={["/discover?focus=prompt&foo=bar"]}
+ showNavigation
+ />,
+ );
+ await waitFor(() =>
+ expect(mocks.focusAndPrefillExample).toHaveBeenCalledOnce(),
+ );
+ expect(screen.getByTestId("location").textContent).toBe("?foo=bar");
+ fireEvent.click(screen.getByRole("button", { name: "Focus prompt" }));
+ await waitFor(() =>
+ expect(mocks.focusAndPrefillExample).toHaveBeenCalledTimes(2),
+ );
+ expect(screen.getByTestId("location").textContent).toBe("");
+ });
+
+ it("strips the param again when an ancestor writer restores it in the same commit", async () => {
+ render(
+ <TestProvider
+ initialState={resolvedState}
+ initialEntries={["/discover?focus=prompt&plan=pro&foo=bar"]}
+ withPlanCleanup
+ />,
+ );
+ await waitFor(() =>
+ expect(screen.getByTestId("location").textContent).toBe("?foo=bar"),
+ );
+ expect(mocks.focusAndPrefillExample).toHaveBeenCalledOnce();
+ });
+});
+
describe("DiscoverPage onboarding mount", () => {
it("preserves content order and mounts over seeded template data", async () => {
renderDiscover(baseState);
@@ -279,6 +410,9 @@ describe("DiscoverPage onboarding mount", () => {
expect(content?.textContent).toBe(
"Create an agentpromptSkip — start with blank canvas →templates",
);
+ expect(screen.queryByText("Build your first agent")).toBeNull();
+ expect(screen.queryByText(/Keep going/)).toBeNull();
+ expect(screen.queryByText("Resume getting started")).toBeNull();
expect(await screen.findByRole("dialog")).toBeTruthy();
});
@@ -369,7 +503,11 @@ describe("DiscoverPage onboarding mount", () => {
});
it("renders without onboarding UI when no provider exists", () => {
- render(<DiscoverPage />);
+ render(
+ <MemoryRouter>
+ <DiscoverPage />
+ </MemoryRouter>,
+ );
expect(screen.queryByRole("dialog")).toBeNull();
expect(mocks.telemetry.modalRenderError).not.toHaveBeenCalled();
});
@@ -422,148 +560,3 @@ describe("DiscoverPage onboarding mount", () => {
expect(mocks.confirmed).not.toHaveBeenCalled();
});
});
-
-describe("DiscoverPage progress surfaces", () => {
- it("renders after PromptBox without an eager write, single-flights creation, and preserves focus on dismissal", () => {
- mocks.progressState = "active";
- const { container, rerender } = render(<DiscoverPage />);
- expect(container.innerHTML).toMatch(
- /<h1[^>]*>Create an agent<\/h1>.*prompt.*Build your first agent.*What a finished run looks like.*templates/s,
- );
- expect(screen.getByText("1 of 3")).toBeTruthy();
- expect(mocks.createWorkflow).not.toHaveBeenCalled();
-
- const describeAgent = screen.getByRole("button", {
- name: "Describe your first agent",
- });
- const prompt = screen.getByRole("textbox", { name: "Discover prompt" });
- fireEvent.change(prompt, { target: { value: "Keep my typed prompt" } });
- fireEvent.click(describeAgent);
- expect((prompt as HTMLTextAreaElement).value).toBe("Keep my typed prompt");
- expect(document.activeElement).toBe(prompt);
- expect(mocks.createWorkflow).not.toHaveBeenCalled();
-
- const workingExampleLink = screen.getByRole("link", {
- name: "or copy a working example",
- });
- const workingExampleHeading = screen.getByRole("heading", {
- name: "What a finished run looks like",
- });
- expect(workingExampleLink.getAttribute("href")).toBe(
- "#working-example-heading",
- );
- expect(workingExampleHeading.getAttribute("tabindex")).toBe("-1");
- workingExampleLink.focus();
- expect(document.activeElement).toBe(workingExampleLink);
- fireEvent.keyDown(workingExampleLink, { key: "Enter" });
- fireEvent.click(workingExampleLink);
- expect(document.activeElement).toBe(workingExampleHeading);
- const copy = screen.getByRole("button", { name: "Make a copy" });
- const skip = screen.getByRole("button", {
- name: /Skip — start with blank canvas/,
- });
- fireEvent.click(copy);
- fireEvent.click(skip);
- expect(mocks.createWorkflow).toHaveBeenCalledTimes(1);
- expect(mocks.createWorkflow).toHaveBeenCalledWith(
- {
- ...onboardingExampleRequest,
- _via: "onboarding_example",
- },
- { onSettled: expect.any(Function) },
- );
-
- mocks.createWorkflow.mock.calls[0]?.[1]?.onSettled?.();
- fireEvent.click(skip);
- expect(mocks.createWorkflow).toHaveBeenCalledTimes(2);
-
- const hide = screen.getByRole("button", { name: "Hide setup" });
- hide.focus();
- fireEvent.click(hide);
- expect(mocks.dismiss).toHaveBeenCalledTimes(1);
-
- mocks.progressPending = true;
- rerender(<DiscoverPage />);
- const pendingHide = screen.getByRole("button", { name: "Hide setup" });
- expect(pendingHide).toBe(hide);
- expect(document.activeElement).toBe(pendingHide);
- expect(pendingHide.getAttribute("aria-disabled")).toBe("true");
- expect(pendingHide.hasAttribute("disabled")).toBe(false);
- fireEvent.click(pendingHide);
- expect(mocks.dismiss).toHaveBeenCalledTimes(1);
-
- mocks.progressState = "dismissed";
- mocks.progressPending = false;
- rerender(<DiscoverPage />);
- const resume = screen.getByRole("button", { name: "Resume setup" });
- expect(resume).toBe(hide);
- expect(document.activeElement).toBe(resume);
- expect(screen.queryByText("What a finished run looks like")).toBeNull();
- fireEvent.click(resume);
- expect(mocks.restore).toHaveBeenCalledTimes(1);
- });
-
- it.each([
- ["fill_forms", "contact_us_forms"],
- ["extract_data", "hackernews"],
- ["monitor_website", "AAPLStockPrice"],
- ["something_else", "finditparts"],
- [null, "finditparts"],
- ] as const)(
- "prefills the %s intent example without creating",
- (intent, key) => {
- mocks.progressState = "active";
- renderDiscover({
- ...baseState,
- user_intent: intent,
- questionnaire_prompted_at: "2026-08-27T00:00:00Z",
- questionnaire: questionnaire(true),
- });
-
- fireEvent.click(
- screen.getByRole("button", { name: "Describe your first agent" }),
- );
- const prompt = screen.getByRole("textbox", { name: "Discover prompt" });
- expect((prompt as HTMLTextAreaElement).value).toBe(key);
- expect(document.activeElement).toBe(prompt);
- expect(mocks.createWorkflow).not.toHaveBeenCalled();
- },
- );
-
- it("briefly celebrates an active to completed transition", () => {
- vi.useFakeTimers();
- mocks.progressState = "active";
- mocks.completedCount = 1;
- mocks.firstMilestoneComplete = true;
- mocks.nextActionKey = "first_successful_run";
- const { rerender } = render(
- <MemoryRouter>
- <DiscoverPage />
- </MemoryRouter>,
- );
-
- mocks.progressState = "completed";
- rerender(
- <MemoryRouter>
- <DiscoverPage />
- </MemoryRouter>,
- );
- expect(screen.getByRole("status").textContent).toContain("3 of 3 complete");
- expect(screen.queryByText("What a finished run looks like")).toBeNull();
-
- act(() => vi.advanceTimersByTime(1800));
- expect(screen.queryByText("First agent ready")).toBeNull();
- vi.useRealTimers();
- });
-
- it.each(["completed", "ineligible", null] as const)(
- "retires all progress surfaces for %s progress",
- (state) => {
- mocks.progressState = state;
- render(<DiscoverPage />);
- expect(document.body.textContent).not.toMatch(
- /Build your first agent|What a finished run looks like|Hide setup|Resume setup/,
- );
- },
- );
-});
diff --git a/skyvern-frontend/src/routes/discover/DiscoverPage.tsx b/skyvern-frontend/src/routes/discover/DiscoverPage.tsx
index f9c62fbc2..c249a26be 100644
--- a/skyvern-frontend/src/routes/discover/DiscoverPage.tsx
+++ b/skyvern-frontend/src/routes/discover/DiscoverPage.tsx
@@ -1,4 +1,4 @@
-import { useRef } from "react";
+import { useEffect, useRef } from "react";
import { GetStartedModal } from "@/components/onboarding/GetStartedModal";
import { OnboardingErrorBoundary } from "@/components/onboarding/OnboardingErrorBoundary";
import { OnboardingTelemetry } from "@/util/onboarding/OnboardingTelemetry";
@@ -12,12 +12,9 @@ import {
import { WorkflowTemplates } from "./WorkflowTemplates";
import { useCreateWorkflowMutation } from "../workflows/hooks/useCreateWorkflowMutation";
import { Button } from "@/components/ui/button";
+import { useSearchParams } from "react-router-dom";
import { ReloadIcon } from "@radix-ui/react-icons";
import { defaultWorkflowRequest } from "../workflows/defaultWorkflowRequest";
-import { WorkingExampleInspector } from "@/components/onboarding/WorkingExampleInspector";
-import { OnboardingProgressBand } from "@/components/onboarding/OnboardingProgressBand";
-import { useOnboardingProgress } from "./useOnboardingProgress";
-import { onboardingExampleRequest } from "./onboardingExample";
function getIntentExampleKey(
intent: string | null | undefined,
@@ -34,31 +31,14 @@ function getIntentExampleKey(
}
}
-function DiscoverPage({
- trackRemaining = 0,
- onDismissHandoff,
- trackDismissed = false,
- trackPending = false,
- onRestoreTrack,
-}: {
- trackRemaining?: number;
- onDismissHandoff?: () => void;
- trackDismissed?: boolean;
- trackPending?: boolean;
- onRestoreTrack?: () => void;
-} = {}) {
+function DiscoverPage() {
const enableCopilotHandoff =
useFeatureFlag("ENABLE_DISCOVER_COPILOT_HANDOFF") === true;
const createWorkflowMutation = useCreateWorkflowMutation();
const createInFlight = useRef(false);
const promptBoxRef = useRef<PromptBoxHandle>(null);
+ const handledFocus = useRef(false);
const onboarding = useOnboardingStateOptional();
- const {
- progress,
- isPending: onboardingProgressPending,
- dismiss,
- restore,
- } = useOnboardingProgress();
const createWorkflow = (
request: Parameters<typeof createWorkflowMutation.mutate>[0],
@@ -72,18 +52,37 @@ function DiscoverPage({
});
};
- const handleExampleCopy = () => {
- createWorkflow({
- ...onboardingExampleRequest,
- _via: "onboarding_example",
- });
- };
-
- const handleDescribeAgent = () => {
- promptBoxRef.current?.focusAndPrefillExample(
- getIntentExampleKey(onboarding?.state?.user_intent),
+ // `/discover?focus=prompt` is the sidebar card's first-agent link: focus + prefill once, then drop the param.
+ const [searchParams, setSearchParams] = useSearchParams();
+ const focusPrompt = searchParams.get("focus") === "prompt";
+ useEffect(() => {
+ if (!focusPrompt) {
+ handledFocus.current = false;
+ return;
+ }
+ if (onboarding?.isLoading) return;
+ if (!handledFocus.current) {
+ const promptBox = promptBoxRef.current;
+ if (!promptBox) return;
+ handledFocus.current = true;
+ promptBox.focusAndPrefillExample(
+ getIntentExampleKey(onboarding?.state?.user_intent),
+ );
+ }
+ setSearchParams(
+ (current) => {
+ const next = new URLSearchParams(current);
+ next.delete("focus");
+ return next;
+ },
+ { replace: true },
);
- };
+ }, [
+ focusPrompt,
+ onboarding?.isLoading,
+ onboarding?.state?.user_intent,
+ setSearchParams,
+ ]);
return (
<div className="space-y-10">
@@ -116,27 +115,6 @@ function DiscoverPage({
</Button>
</div>
</div>
- <OnboardingProgressBand
- progress={progress}
- isPending={onboardingProgressPending}
- onDismiss={dismiss}
- onRestore={restore}
- onDescribeAgent={handleDescribeAgent}
- trackRemaining={trackRemaining}
- onDismissHandoff={onDismissHandoff}
- trackDismissed={trackDismissed}
- trackPending={trackPending}
- onRestoreTrack={onRestoreTrack}
- >
- {progress?.state === "active" ? (
- <WorkingExampleInspector
- isPending={
- createWorkflowMutation.isPending || onboardingProgressPending
- }
- onMakeCopy={handleExampleCopy}
- />
- ) : null}
- </OnboardingProgressBand>
<WorkflowTemplates />
{onboarding ? (
<OnboardingErrorBoundary
diff --git a/skyvern-frontend/src/routes/discover/onboardingExample.test.ts b/skyvern-frontend/src/routes/discover/onboardingExample.test.ts
deleted file mode 100644
index 5d785996a..000000000
--- a/skyvern-frontend/src/routes/discover/onboardingExample.test.ts
+++ /dev/null
@@ -1,45 +0,0 @@
-import { expect, it } from "vitest";
-import { RunEngine } from "@/api/types";
-import * as example from "./onboardingExample";
-const sensitiveKey =
- /credential|session|profile|header|webhook|totp|(^|_)id($|_)/i;
-function assertNoSensitiveKeys(value: unknown): void {
- if (Array.isArray(value)) return value.forEach(assertNoSensitiveKeys);
- if (typeof value !== "object" || value === null) return;
- Object.entries(value).forEach(([key, nested]) => {
- expect(key).not.toMatch(sensitiveKey);
- assertNoSensitiveKeys(nested);
- });
-}
-it("keeps the copy payload to one passive public task", () => {
- const { blocks } = example.onboardingExampleRequest.workflow_definition;
- expect(blocks).toHaveLength(1);
- const task = blocks[0]!;
- expect(task).toMatchObject({
- block_type: "task",
- url: "https://www.skyvern.com/",
- navigation_goal: null,
- });
- expect(task.engine).toBe(RunEngine.SkyvernV1);
- assertNoSensitiveKeys(example.onboardingExampleRequest);
-});
-it("labels playback and result data as synthetic examples", () => {
- const { title, provenance, playback, result } =
- example.onboardingExamplePresentation;
- expect(title).toBe("What a finished run looks like");
- expect(provenance).toBe("Example data, not your run");
- expect(playback[0]).toMatch(/static agent example/);
- expect(playback[2]).toMatch(/agent result/);
- expect(result.title).toBe("Example result");
- expect(result.fields.map(({ label }) => label)).toEqual([
- "Headline",
- "Product summary",
- ]);
- expect(
- JSON.stringify({
- presentation: example.onboardingExamplePresentation,
- title: example.onboardingExampleRequest.title,
- description: example.onboardingExampleRequest.description,
- }),
- ).not.toMatch(/workflow/i);
-});
diff --git a/skyvern-frontend/src/routes/discover/onboardingExample.ts b/skyvern-frontend/src/routes/discover/onboardingExample.ts
deleted file mode 100644
index b32a6865b..000000000
--- a/skyvern-frontend/src/routes/discover/onboardingExample.ts
+++ /dev/null
@@ -1,74 +0,0 @@
-import { RunEngine } from "@/api/types";
-import type { WorkflowCreateYAMLRequest } from "@/routes/workflows/types/workflowYamlTypes";
-
-export const onboardingExamplePresentation = {
- title: "What a finished run looks like",
- provenance: "Example data, not your run",
- structure: [
- {
- title: "Visit a public page",
- detail: "Open Skyvern's public homepage without signing in.",
- },
- {
- title: "Read public content",
- detail: "Extract the headline and a short product summary.",
- },
- {
- title: "Return structured data",
- detail: "Keep the result to two short text fields.",
- },
- ],
- playback: [
- "Opened https://www.skyvern.com/ in this static agent example.",
- "The agent read the public headline and product description.",
- "Prepared the bounded agent result shown below.",
- ],
- result: {
- title: "Example result",
- fields: [
- {
- label: "Headline",
- value: "Automate browser-based work with AI",
- },
- {
- label: "Product summary",
- value:
- "Skyvern runs browser agents that interact with websites and extract structured data.",
- },
- ],
- },
-} as const;
-
-export const onboardingExampleRequest = {
- title: "Copyable agent example: Skyvern homepage summary",
- description:
- "Create an agent draft that reads public content from Skyvern's homepage.",
- workflow_definition: {
- parameters: [],
- blocks: [
- {
- block_type: "task",
- label: "Read Skyvern homepage",
- url: "https://www.skyvern.com/",
- navigation_goal: null,
- data_extraction_goal:
- "Extract the public headline and a short summary of what Skyvern does.",
- data_schema: {
- type: "object",
- properties: {
- headline: { type: "string", maxLength: 160 },
- product_summary: { type: "string", maxLength: 320 },
- },
- required: ["headline", "product_summary"],
- additionalProperties: false,
- },
- error_code_mapping: null,
- disable_cache: false,
- complete_criterion: null,
- terminate_criterion: null,
- include_action_history_in_verification: false,
- engine: RunEngine.SkyvernV1,
- },
- ],
- },
-} satisfies WorkflowCreateYAMLRequest;
diff --git a/skyvern-frontend/src/routes/discover/useOnboardingProgress.test.tsx b/skyvern-frontend/src/routes/discover/useOnboardingProgress.test.tsx
index 7fecaf0a0..70147d748 100644
--- a/skyvern-frontend/src/routes/discover/useOnboardingProgress.test.tsx
+++ b/skyvern-frontend/src/routes/discover/useOnboardingProgress.test.tsx
@@ -1,38 +1,21 @@
-import { useState, type ReactNode } from "react";
+import type { ReactNode } from "react";
import {
QueryClient,
QueryClientProvider,
QueryObserver,
} from "@tanstack/react-query";
-import {
- act,
- fireEvent,
- render,
- renderHook,
- screen,
- waitFor,
-} from "@testing-library/react";
-import { MemoryRouter } from "react-router-dom";
-import { afterEach, beforeEach, expect, it, vi } from "vitest";
-import { OnboardingProgressBand } from "@/components/onboarding/OnboardingProgressBand";
+import { act, renderHook, waitFor } from "@testing-library/react";
+import { beforeEach, expect, it, vi } from "vitest";
const mocks = vi.hoisted<{
get: ReturnType<typeof vi.fn>;
flag: boolean | undefined;
org: string | undefined;
user: string | undefined;
- trackRemaining: number;
- dismissHandoff: ReturnType<typeof vi.fn<() => void>>;
- trackDismissed: boolean;
- restoreTrack: ReturnType<typeof vi.fn<() => void>>;
}>(() => ({
get: vi.fn(),
flag: true,
org: "org-test",
user: "user-test",
- trackRemaining: 0,
- dismissHandoff: vi.fn<() => void>(),
- trackDismissed: false,
- restoreTrack: vi.fn<() => void>(),
}));
vi.mock("@/api/AxiosClient", () => ({
getClient: () => Promise.resolve({ get: mocks.get }),
@@ -64,23 +47,6 @@ const validPayload = () => ({
{ key: "first_successful_run", completed_at: null },
],
});
-const completedPayload = () => ({
- ...validPayload(),
- state: "completed",
- completed_count: 2,
- next_action_key: null,
- items: [
- { key: "first_agent_created", completed_at: "2026-08-20T12:00:00Z" },
- { key: "first_successful_run", completed_at: "2026-08-20T12:01:00Z" },
- ],
-});
-function deferred<T>() {
- let resolve!: (value: T) => void;
- const promise = new Promise<T>((resolvePromise) => {
- resolve = resolvePromise;
- });
- return { promise, resolve };
-}
function renderProgress(client = new QueryClient()) {
const wrapper = ({ children }: { children: ReactNode }) => (
<QueryClientProvider client={client}>{children}</QueryClientProvider>
@@ -88,44 +54,12 @@ function renderProgress(client = new QueryClient()) {
const hook = renderHook(() => useOnboardingProgress(), { wrapper });
return { client, ...hook };
}
-function ProgressBand() {
- const { progress, isPending, dismiss, restore } = useOnboardingProgress();
- const [trackRemaining, setTrackRemaining] = useState(mocks.trackRemaining);
- return (
- <OnboardingProgressBand
- progress={progress}
- isPending={isPending}
- onDismiss={dismiss}
- onRestore={restore}
- onDescribeAgent={vi.fn()}
- trackRemaining={trackRemaining}
- onDismissHandoff={() => {
- mocks.dismissHandoff();
- setTrackRemaining(0);
- }}
- trackDismissed={mocks.trackDismissed}
- onRestoreTrack={mocks.restoreTrack}
- />
- );
-}
-function renderProgressBand(client: QueryClient) {
- return render(
- <QueryClientProvider client={client}>
- <MemoryRouter>
- <ProgressBand />
- </MemoryRouter>
- </QueryClientProvider>,
- );
-}
beforeEach(() => {
vi.clearAllMocks();
mocks.flag = true;
mocks.org = "org-test";
mocks.user = "user-test";
- mocks.trackRemaining = 0;
- mocks.trackDismissed = false;
});
-afterEach(() => vi.useRealTimers());
it.each([
[false, "org-test", "user-test"],
[undefined, "org-test", "user-test"],
@@ -190,113 +124,6 @@ it("refetches fresh cached progress when Discover remounts", async () => {
);
expect(secondMount.result.current.progress).toEqual(refreshedPayload);
});
-it("keeps one way back to a hidden track on Home", async () => {
- mocks.trackDismissed = true;
- mocks.get.mockResolvedValueOnce({ data: completedPayload() });
- renderProgressBand(new QueryClient());
- const resume = await screen.findByRole("button", {
- name: "Resume getting started",
- });
- expect(screen.queryByText(/First agent ready/)).toBeNull();
- fireEvent.click(resume);
- expect(mocks.restoreTrack).toHaveBeenCalledOnce();
-});
-
-it("keeps a persistent handoff instead of the timed celebration when the track is active", async () => {
- const client = new QueryClient();
- mocks.get.mockResolvedValueOnce({ data: validPayload() });
- const activeMount = renderProgressBand(client);
- expect(await screen.findByText("Build your first agent")).toBeTruthy();
- activeMount.unmount();
-
- const completedRequest = deferred<{ data: unknown }>();
- mocks.get.mockReturnValueOnce(completedRequest.promise);
- mocks.trackRemaining = 4;
- vi.useFakeTimers();
- const completionMount = renderProgressBand(client);
- completedRequest.resolve({ data: completedPayload() });
- await completedRequest.promise;
- await act(() => vi.advanceTimersByTimeAsync(0));
- const handoff = screen.getByRole("link", {
- name: "Keep going: 4 more steps →",
- });
- expect(handoff.getAttribute("href")).toBe("/getting-started");
- expect(screen.getByRole("status").textContent).toContain(
- "First agent ready.",
- );
- expect(screen.queryByText("3 of 3 complete")).toBeNull();
- act(() => vi.advanceTimersByTime(5000));
- expect(
- screen.getByRole("link", { name: "Keep going: 4 more steps →" }),
- ).toBeTruthy();
- fireEvent.click(screen.getByRole("button", { name: "Hide" }));
- expect(mocks.dismissHandoff).toHaveBeenCalledOnce();
- expect(screen.queryByText(/First agent ready/)).toBeNull();
- act(() => vi.advanceTimersByTime(1800));
- expect(screen.queryByText(/First agent ready/)).toBeNull();
- completionMount.unmount();
- vi.useRealTimers();
-
- mocks.get.mockResolvedValueOnce({ data: completedPayload() });
- renderProgressBand(new QueryClient());
- expect(
- await screen.findByRole("link", { name: "Keep going: 4 more steps →" }),
- ).toBeTruthy();
- expect(screen.queryByText("3 of 3 complete")).toBeNull();
-});
-it("celebrates only cached active progress completing on remount", async () => {
- const freshClient = new QueryClient();
- mocks.get.mockResolvedValueOnce({ data: completedPayload() });
- const freshMount = renderProgressBand(freshClient);
-
- await waitFor(() => expect(mocks.get).toHaveBeenCalledOnce());
- await waitFor(() =>
- expect(
- freshClient.getQueryData([
- "onboarding-progress",
- "user-test",
- "org-test",
- ]),
- ).toEqual(completedPayload()),
- );
- expect(screen.queryByText("First agent ready")).toBeNull();
- expect(screen.queryByRole("status")).toBeNull();
- freshMount.unmount();
-
- const client = new QueryClient();
- mocks.get.mockResolvedValueOnce({ data: validPayload() });
- const activeMount = renderProgressBand(client);
- expect(await screen.findByText("Build your first agent")).toBeTruthy();
- activeMount.unmount();
-
- const completedRequest = deferred<{ data: unknown }>();
- mocks.get.mockReturnValueOnce(completedRequest.promise);
- vi.useFakeTimers();
- const completionMount = renderProgressBand(client);
- expect(screen.getByText("Build your first agent")).toBeTruthy();
-
- completedRequest.resolve({ data: completedPayload() });
- await completedRequest.promise;
- await act(() => vi.advanceTimersByTimeAsync(0));
- expect(screen.getAllByText("First agent ready")).toHaveLength(1);
- expect(screen.getByRole("status").textContent).toContain("3 of 3 complete");
- expect(screen.queryByRole("link", { name: /Keep going/ })).toBeNull();
-
- act(() => vi.advanceTimersByTime(1799));
- expect(screen.getByText("First agent ready")).toBeTruthy();
- act(() => vi.advanceTimersByTime(1));
- expect(screen.queryByText("First agent ready")).toBeNull();
- completionMount.unmount();
-
- const finalRequest = deferred<{ data: unknown }>();
- mocks.get.mockReturnValueOnce(finalRequest.promise);
- const finalMount = renderProgressBand(client);
- expect(finalMount.container.innerHTML).toBe("");
- finalRequest.resolve({ data: completedPayload() });
- await finalRequest.promise;
- await act(() => vi.advanceTimersByTimeAsync(0));
- expect(finalMount.container.innerHTML).toBe("");
-});
it("isolates progress cache entries by authenticated user", async () => {
mocks.flag = true;
mocks.org = "org-test";
diff --git a/skyvern/config.py b/skyvern/config.py
index b204e4e58..ea45c6725 100644
--- a/skyvern/config.py
+++ b/skyvern/config.py
@@ -522,9 +522,6 @@ class Settings(BaseSettings):
# Fraction of Task V3 runs (keyed by workflow run, else task) that persist their last pre-submit
# page frames as artifacts. Instrumentation sampling, not a traffic knob; 0 disables.
TASK_V3_PRE_SUBMIT_CAPTURE_SAMPLE_RATE: float = 0.25
- # Append a fresh observe digest to a page-changing action batch's tool result, so the model can act
- # from it without spending a separate perception turn.
- TASK_V3_AUTO_OBSERVE: bool = False
# Kill switch for the tier-1 semantic commit read (SKY-15322): decisive-accept-only ARIA/value
# probe consulted before the shape heuristics, which remain the fallback either way.
TASK_V3_SEMANTIC_COMMIT_VERIFY: bool = True
diff --git a/skyvern/forge/agent.py b/skyvern/forge/agent.py
index 36de9de93..e10d6533a 100644
--- a/skyvern/forge/agent.py
+++ b/skyvern/forge/agent.py
@@ -1405,7 +1405,6 @@ class ForgeAgent:
close_browser_on_completion: bool,
browser_session_id: str | None,
task_block: BaseTaskBlock | None = None,
- workflow_permanent_id: str | None = None,
) -> tuple[Step, Task]:
"""Run a whole task via the native Task V3 tool-loop (one persistent conversation).
@@ -2020,10 +2019,6 @@ class ForgeAgent:
starting_url=task.url,
downloads_dir=get_download_dir(download_id),
organization_id=organization.organization_id,
- task_id=task.task_id,
- # Task.workflow_permanent_id is never populated on the execution path (get_task
- # builds Task without it); the caller sources it from the WorkflowRun row.
- workflow_permanent_id=workflow_permanent_id,
max_action_steps=step_cap,
max_action_steps_ceiling=workflow_step_ceiling,
max_turns=max_turns,
@@ -2558,7 +2553,6 @@ class ForgeAgent:
close_browser_on_completion=close_browser_on_completion,
browser_session_id=browser_session_id,
task_block=task_block,
- workflow_permanent_id=workflow_run.workflow_permanent_id if workflow_run else None,
)
finally:
await app.ARTIFACT_MANAGER.flush_step_archive(step.step_id)
diff --git a/skyvern/forge/agent_functions.py b/skyvern/forge/agent_functions.py
index 3629fb34f..34d8034d0 100644
--- a/skyvern/forge/agent_functions.py
+++ b/skyvern/forge/agent_functions.py
@@ -70,7 +70,6 @@ from skyvern.forge.sdk.services import (
from skyvern.forge.sdk.services.credentials import AuthenticatorTotpParseResult
from skyvern.forge.sdk.trace import traced
from skyvern.forge.sdk.workflow.models.block import BaseTaskBlock, BlockTypeVar
-from skyvern.forge.taskv3.auto_observe import AutoObserveDecision, auto_observe_from_setting
from skyvern.schemas.run_enums import RunEngine, RunType
from skyvern.schemas.workflows import BlockResult, FileStorageType, FileUploadDestination
from skyvern.services.otp_email import EmailOTPSearchError, EmailOTPVerificationContext, build_email_otp_sources
@@ -891,12 +890,6 @@ class AgentFunction:
) -> RunEngine:
return requested_engine
- # OSS resolves auto-observe from the static setting; cloud overrides to bucket a run per task_id.
- async def resolve_task_v3_auto_observe(
- self, *, task_id: str | None, organization_id: str | None, workflow_permanent_id: str | None = None
- ) -> AutoObserveDecision:
- return auto_observe_from_setting()
-
# OSS has no ATS-scoped guidance; cloud overrides to supply pre-authorized eligibility defaults
# behind a flag when the task targets a gated application-tracking-system host.
async def resolve_task_v3_extra_guidance(self, *, task: Task, organization: Organization) -> str | None:
diff --git a/skyvern/forge/taskv3/auto_observe.py b/skyvern/forge/taskv3/auto_observe.py
deleted file mode 100644
index d16f1a002..000000000
--- a/skyvern/forge/taskv3/auto_observe.py
+++ /dev/null
@@ -1,23 +0,0 @@
-"""Per-run decision for Task V3 auto-observe. The engine consumes it through the AgentFunction seam,
-so an OSS deployment resolves from the static setting while cloud can bucket a run into an A/B."""
-
-from __future__ import annotations
-
-from dataclasses import dataclass
-from typing import Literal
-
-from skyvern.config import settings
-
-AutoObserveArm = Literal["treatment", "control", "setting", "default"]
-
-
-@dataclass(frozen=True)
-class AutoObserveDecision:
- enabled: bool
- arm: AutoObserveArm
-
-
-def auto_observe_from_setting() -> AutoObserveDecision:
- if settings.TASK_V3_AUTO_OBSERVE:
- return AutoObserveDecision(enabled=True, arm="setting")
- return AutoObserveDecision(enabled=False, arm="default")
diff --git a/skyvern/forge/taskv3/engine.py b/skyvern/forge/taskv3/engine.py
index 17ad4a254..a15b59287 100644
--- a/skyvern/forge/taskv3/engine.py
+++ b/skyvern/forge/taskv3/engine.py
@@ -29,11 +29,9 @@ from typing import Any, Awaitable, Callable
import structlog
from skyvern.config import settings
-from skyvern.forge import app
from skyvern.forge.sdk.api.llm.api_handler_factory import VISION_FALLBACK_PROMPT_NAMES
from skyvern.forge.sdk.api.llm.exceptions import LLMProviderErrorRetryableTask
from skyvern.forge.sdk.core import skyvern_context
-from skyvern.forge.taskv3.auto_observe import AutoObserveDecision
from skyvern.forge.taskv3.loop import (
DEFAULT_MAX_SETTLE_DEFERRALS,
ActivityRecency,
@@ -114,10 +112,6 @@ DOWNLOAD_REQUIRED_GUIDANCE = """
This task cannot finish as completed until a file download has finished. Trigger the download and let it land, then call finish(status=completed) with the extracted output. If the download cannot be triggered, call finish with status=failed or status=terminated and say why."""
-AUTO_OBSERVE_GUIDANCE = """
-
-When an action result already ends with an auto-observe block, act from that snapshot instead of calling observe again. If an action changes only styling or focus (hover menus, toggles), the result may say no markup change was detected — observe if you expect something new to be visible. If the next action on the same page does not depend on seeing this one's result, put it in the same turn (the button that advances the form included); type a whole value or key sequence in one `type`/`press_key`, never one character per turn."""
-
def taskv3_runaway_backstops(max_action_steps: int | None) -> tuple[int, int, int]:
"""Return (max_turns, max_tool_calls, max_tokens) anti-runaway guards for an action-step budget.
@@ -221,8 +215,6 @@ async def run_task_v3_agent_loop(
starting_url: str | None = None,
downloads_dir: str | None = None,
organization_id: str | None = None,
- task_id: str | None = None,
- workflow_permanent_id: str | None = None,
max_turns: int = DEFAULT_MAX_TURNS,
max_tool_calls: int = DEFAULT_MAX_TOOL_CALLS,
max_action_steps: int | None = None,
@@ -336,24 +328,6 @@ async def run_task_v3_agent_loop(
verification_blocker=verification_blocker,
)
tools = browser_tools + (extra_tools or []) + [finish_tool]
- # Resolved through the AgentFunction seam so cloud can bucket the run into an A/B; a page-free
- # run has no observe to append, so it is never resolved and never bands as an arm.
- auto_observe_decision = (
- AutoObserveDecision(enabled=False, arm="default")
- if page_free
- else await app.AGENT_FUNCTION.resolve_task_v3_auto_observe(
- task_id=task_id, organization_id=organization_id, workflow_permanent_id=workflow_permanent_id
- )
- )
- auto_observe = auto_observe_decision.enabled
- if not page_free:
- LOG.info(
- "taskv3 auto-observe resolved",
- task_id=task_id,
- organization_id=organization_id,
- auto_observe=auto_observe,
- auto_observe_arm=auto_observe_decision.arm,
- )
base_system_prompt = PAGE_FREE_SYSTEM_PROMPT if page_free else SYSTEM_PROMPT
# Keyed on which hooks are present, not completion_probe alone: an extraction blocker-only
# case needs the model told it ends the run itself; a wait-only probe has nothing to explain.
@@ -361,8 +335,6 @@ async def run_task_v3_agent_loop(
extra_system_guidance = extra_system_guidance + DOWNLOAD_COMPLETION_GUIDANCE
elif completion_blocker is not None and completion_probe is None:
extra_system_guidance = extra_system_guidance + DOWNLOAD_REQUIRED_GUIDANCE
- if auto_observe:
- extra_system_guidance = extra_system_guidance + AUTO_OBSERVE_GUIDANCE
system_prompt = base_system_prompt + extra_system_guidance
system_prompt += datetime.now(ctx.tz_info if ctx and ctx.tz_info else UTC).strftime(
"\n\nToday's date is %Y-%m-%d (%A), %Z."
@@ -397,7 +369,6 @@ async def run_task_v3_agent_loop(
page_probe=None if page_free else page_probe,
page_fingerprint=None if page_free else page_fingerprint,
reload_page=None if page_free else reload_page,
- auto_observe=auto_observe,
)
finally:
# The context outlives this run; a signal raised as the loop was cancelled must not fire
@@ -416,7 +387,6 @@ async def run_task_v3_agent_loop(
tool_seconds=outcome.tool_seconds,
action_steps=outcome.action_steps,
no_tool_call_turns=outcome.no_tool_call_turns,
- auto_observe_arm=auto_observe_decision.arm,
tool_choice_requested=settings.TASK_V3_TOOL_CHOICE_REQUIRED,
tool_choice_in_effect=outcome.tool_choice_in_effect,
duration_seconds=time.monotonic() - loop_started_at,
diff --git a/skyvern/forge/taskv3/loop.py b/skyvern/forge/taskv3/loop.py
index 8bf84f0dd..43890c34b 100644
--- a/skyvern/forge/taskv3/loop.py
+++ b/skyvern/forge/taskv3/loop.py
@@ -251,17 +251,6 @@ NAV_DEAD_END_REASON_PREFIX = "navigation_dead_end:"
# be stabilized, and acting on it would mean acting on a page declared stale.
PAGE_REFRESH_EXHAUSTED_REASON_PREFIX = "page_refresh_exhausted:"
-# Delimiters around an auto-observe digest appended to a batch's tool message. Distinctive enough
-# that page content cannot plausibly collide with them; _compact_transcript keys off their presence
-# to treat the carrying message as an observe-class snapshot.
-AUTO_OBSERVE_BEGIN = "<<auto-observe>>"
-AUTO_OBSERVE_END = "<</auto-observe>>"
-
-# Settle-wait before the auto-observe DOM walk. Tests lower these via monkeypatch, mirroring
-# _PAGE_PROBE_TIMEOUT_SECONDS.
-AUTO_OBSERVE_SETTLE_INTERVAL_SECONDS = 0.7
-AUTO_OBSERVE_SETTLE_CAP_SECONDS = 2.0
-
# Emitted, never acted on, when the oscillation rule WOULD have terminated. The step engine's
# tripwires (skyvern/forge/sdk/fail_fast/shadow.py) earn the right to act by publishing this event
# first and deriving a decision precision from it; a rule that ADDS terminations gets the same
@@ -614,71 +603,6 @@ async def _sample_probe(probe: Callable[[], Awaitable[str | None]], deadline_at:
return None
-async def _auto_observe_settle_wait(
- page_probe: Callable[[], Awaitable[str | None]] | None,
- should_cancel: Callable[[], Awaitable[bool]] | None,
- deadline_at: float | None = None,
- page_fingerprint: Callable[[], Awaitable[str | None]] | None = None,
-) -> float:
- """Falls back to one flat sleep when neither sampler is available. Prefers `page_fingerprint`
- (rendered-content quiescence) over `page_probe` (document identity) when both are supplied, since a
- settle wait is asking "did the RENDER finish", not "is this still the same document" -- the same
- preference the end-of-batch decision applies. Reads the AUTO_OBSERVE_SETTLE_* module globals (not
- defaults) so tests can lower them via monkeypatch. The clock starts before the first probe sample,
- so a slow probe counts against the cap; the wait is also capped at `deadline_at` (time.monotonic
- clock, mirroring `_settled`), so probing cannot outlive the loop's own bounds. Returns the real
- elapsed wall-clock time, including probe durations."""
- started = time.monotonic()
- sampler = page_fingerprint if page_fingerprint is not None else page_probe
- if sampler is None:
- wait = AUTO_OBSERVE_SETTLE_INTERVAL_SECONDS
- if deadline_at is not None:
- wait = min(wait, deadline_at - time.monotonic())
- if wait > 0:
- await asyncio.sleep(wait)
- return time.monotonic() - started
- prev = await _sample_probe(sampler, deadline_at=deadline_at)
- while True:
- elapsed = time.monotonic() - started
- interval = min(AUTO_OBSERVE_SETTLE_INTERVAL_SECONDS, AUTO_OBSERVE_SETTLE_CAP_SECONDS - elapsed)
- if deadline_at is not None:
- interval = min(interval, deadline_at - time.monotonic())
- if interval <= 0:
- break
- await asyncio.sleep(interval)
- if should_cancel is not None and await should_cancel():
- break
- current = await _sample_probe(sampler, deadline_at=deadline_at)
- if current is not None and current == prev:
- break
- prev = current
- return time.monotonic() - started
-
-
-async def _resample_after_one_settle_interval(
- sampler: Callable[[], Awaitable[str | None]],
- before: str | None,
- should_cancel: Callable[[], Awaitable[bool]] | None,
- deadline_at: float | None,
-) -> tuple[bool, float]:
- """An immediate post-batch sample that read as unchanged can just be too early for an async
- render (a spinner resolving, a debounce firing) that hasn't touched the DOM yet. Wait one bounded
- settle interval and take a single resample; ``changed`` is only ever a positive signal (a genuine
- None either side proves nothing). Returns (changed, waited_seconds)."""
- interval = AUTO_OBSERVE_SETTLE_INTERVAL_SECONDS
- if deadline_at is not None:
- interval = min(interval, deadline_at - time.monotonic())
- started = time.monotonic()
- if interval > 0 and not (should_cancel is not None and await should_cancel()):
- await asyncio.sleep(interval)
- waited = time.monotonic() - started
- if should_cancel is not None and await should_cancel():
- return False, waited
- after = await _sample_probe(sampler, deadline_at=deadline_at)
- changed = before is not None and after is not None and after != before
- return changed, waited
-
-
def _may_submit(tool_name: str, args: dict[str, Any]) -> bool:
"""A click, an Enter press, or a type that pressed Enter: the loop cannot tell a submit from any of them."""
return tool_name == "click" or _is_enter_submit(tool_name, args)
@@ -944,7 +868,6 @@ class _ProgressEvidence(str, Enum):
PERCEPTION_DIGEST = "perception_digest"
CROSS_BATCH_MOVEMENT = "cross_batch_movement"
PROBE_MISMATCH = "probe_mismatch"
- AUTO_OBSERVE_VERDICT = "auto_observe_verdict"
PAGE_STATE_VERDICT = "page_state_verdict"
TERMINAL_BATCH_FINGERPRINT = "terminal_batch_fingerprint"
@@ -1287,32 +1210,10 @@ def make_finish_tool(
_COMPACTED_PREFIX = "[superseded "
-_AUTO_OBSERVE_SPAN_RE = re.compile(
- r"\n\n" + re.escape(AUTO_OBSERVE_BEGIN) + r".*?" + re.escape(AUTO_OBSERVE_END), re.DOTALL
-)
-
-
-def _neutralize_auto_observe_markers(digest: str) -> str:
- """Break any BEGIN/END delimiter that appears verbatim in page-controlled digest text, so the
- digest can never forge a fake span boundary once wrapped. A space after the leading `<` keeps the
- text readable while making the substring no longer match the delimiter."""
- return digest.replace(AUTO_OBSERVE_BEGIN, "< " + AUTO_OBSERVE_BEGIN[1:]).replace(
- AUTO_OBSERVE_END, "< " + AUTO_OBSERVE_END[1:]
- )
-
-
-def _elide_auto_observe_span(content: str) -> str:
- """Only the marker span is elided; the tool's own text (e.g. a click's confirmation) survives,
- since it was never a perception result."""
- return _AUTO_OBSERVE_SPAN_RE.sub(
- f"\n\n{_COMPACTED_PREFIX}auto-observe output elided to bound context]", content, count=1
- )
-
def _compact_transcript(
messages: list[dict[str, Any]],
snapshot_indices: set[int],
- auto_carrier_indices: set[int] | None = None,
) -> None:
"""Bound the persistent conversation by eliding stale perception snapshots.
@@ -1329,48 +1230,25 @@ def _compact_transcript(
`snapshot_indices`, so it can neither be elided nor shadow the real snapshot and leave the agent
with no usable page view — regardless of content length (a verbose provider error included).
- A message carrying an appended auto-observe block is grouped into the same "observe" supersession
- class as a real `observe` result, whichever tool actually produced it. Only its marker span is
- elided; the tool's own text is never touched. Membership in that class is decided by
- `auto_carrier_indices` (the loop's own record of which index it appended a digest to), NEVER by
- sniffing message content for `AUTO_OBSERVE_BEGIN` -- a page whose own text happens to contain that
- literal string must not be able to forge its way into the carrier class, and content-sniffing would
- also force neutralizing every ordinary tool result up front (breaking byte-identity for auto_observe
- OFF runs) just to keep that forgery from mattering.
-
Only a `tool` message's content is shrunk, never removed, so every tool_call keeps a matching result
and the transcript stays valid. Eliding also drops the index, so re-running is a no-op and an elided
placeholder can never re-anchor as the live snapshot."""
if not snapshot_indices:
return
- if auto_carrier_indices is None:
- auto_carrier_indices = set()
last_assistant_idx = -1
for i in range(len(messages) - 1, -1, -1):
if messages[i].get("role") == "assistant":
last_assistant_idx = i
break
- def _snapshot_class(i: int) -> str:
- return "observe" if i in auto_carrier_indices else messages[i]["name"]
-
seen: set[str] = set()
for i in sorted(snapshot_indices, reverse=True):
- cls = _snapshot_class(i)
+ cls = messages[i]["name"]
if i > last_assistant_idx or cls not in seen:
seen.add(cls) # the still-unread latest round, or the newest snapshot of this class — keep
continue
- content = messages[i]["content"]
- # The marker-span-only elision is for a non-compactable carrier (a click/type result an
- # auto-observe digest rode along on): its own text must survive. Gated on the explicit index
- # set, not on `messages[i]["name"]`, since a carrier is by construction never a compactable
- # tool's own result (batch_carrier_idx skips compactable specs).
- if i in auto_carrier_indices:
- messages[i]["content"] = _elide_auto_observe_span(content)
- else:
- messages[i]["content"] = f"{_COMPACTED_PREFIX}{cls} output elided to bound context]"
+ messages[i]["content"] = f"{_COMPACTED_PREFIX}{cls} output elided to bound context]"
snapshot_indices.discard(i)
- auto_carrier_indices.discard(i)
async def run_agent_tool_loop(
@@ -1409,7 +1287,6 @@ async def run_agent_tool_loop(
reload_page: Callable[[], Awaitable[None]] | None = None,
max_refresh_cycles: int = 3,
page_fingerprint: Callable[[], Awaitable[str | None]] | None = None,
- auto_observe: bool = False,
) -> LoopOutcome:
tool_by_name = {tool.name: tool for tool in tools}
outcome: LoopOutcome | None = None
@@ -1445,16 +1322,7 @@ async def run_agent_tool_loop(
# Indices into `messages` of successful perception results, recorded as they are appended so
# compaction can keep only the newest of each without inferring "real snapshot" from content size.
snapshot_indices: set[int] = set()
- # Indices carrying an appended auto-observe digest, recorded by the loop itself the moment it
- # wraps one on -- _compact_transcript classifies a carrier off THIS set, never by sniffing message
- # content for AUTO_OBSERVE_BEGIN, so a page whose own text happens to contain that literal string
- # can never forge its way into the carrier class.
- auto_carrier_indices: set[int] = set()
perception = _PerceptionLedger()
- # Auto-observe's own ledger: separate state so an auto snapshot's digest can never pad the
- # model-issued no-arg observe's streak (both key on ("observe", "{}")) into the model's own
- # can_terminate=True verdict.
- auto_perception = _PerceptionLedger()
# Net-progress ledger (additive shadow); None disables it, mirroring the guard's *_after knobs.
progress = _ProgressLedger(window=progress_window) if progress_window is not None else None
canonical = _CanonicalProgressTracker()
@@ -1526,7 +1394,6 @@ async def run_agent_tool_loop(
page_state_nudge_delivered = False
page_state_prev_fp = None
perception.reset()
- auto_perception.reset()
if activity is not None:
activity.perception_stall_imminent = False
pending_screenshots = []
@@ -1544,8 +1411,7 @@ async def run_agent_tool_loop(
def _progress_observe_shadow(
observe_summary: dict[str, int], tool_name: str, attribution: dict[str, Any], baseline_before: int | None
) -> None:
- """Shared by the model-dispatched and auto-observe paths so an auto-observe feeds the same
- ledger a model-issued no-arg observe would."""
+ """Feeds a model-issued no-arg observe's invalid-fields count into the net-progress ledger."""
if progress is None or not observe_summary:
return
invalid_fields = observe_summary.get("invalid_fields")
@@ -1570,9 +1436,8 @@ async def run_agent_tool_loop(
)
def _absorb_result_data(tool_name: str, spec: ToolSpec | None, result_data: dict[str, Any]) -> bool:
- """Shared by the model-dispatched and auto-observe paths so a download/page-change signal
- in a tool's result.data has the same effect (staged_downloads, action-state clear, progress
- hard_progress) regardless of which path produced it. Returns whether marks were renumbered."""
+ """Absorbs a download/page-change signal in a tool's result.data (staged_downloads,
+ action-state clear, progress hard_progress). Returns whether marks were renumbered."""
if staged_downloads is not None and result_data.get("staged_download"):
staged_downloads.add(result_data["staged_download"])
if spec is not None and (result_data.get("download_notice") or result_data.get("page_state_changed")):
@@ -1585,13 +1450,12 @@ async def run_agent_tool_loop(
_clear_action_state()
if result_data.get("same_url_reload") or result_data.get("nav_revisit"):
# A reload destroys the observed document and a revisit replaces it with a fresh
- # instance of known territory: re-baseline the perception ledgers (as the refresh
+ # instance of known territory: re-baseline the perception ledger (as the refresh
# path does) so the first post-navigation look cannot diff against a pre-navigation
# digest and read as progress — and clear the evidence stamp in both cases, since
# navigation is non-billable and a surviving stamp would stay maximally recent
# through any amount of oscillation.
perception.reset()
- auto_perception.reset()
nonlocal last_change_evidence_step
last_change_evidence_step = None
if activity is not None:
@@ -1631,8 +1495,7 @@ async def run_agent_tool_loop(
async def _completion_probe_outcome(
tool_name: str, spec: ToolSpec | None, result_data: dict[str, Any]
) -> LoopOutcome | None:
- """Shared by the model-dispatched and auto-observe paths: a download an auto-observe reports
- must reach completion exactly as it would if the model had called observe itself."""
+ """Consults the completion probe after a billable or download-signaling tool result."""
if not (
completion_probe is not None
and spec is not None
@@ -1664,25 +1527,18 @@ async def run_agent_tool_loop(
*,
content_only_digest: str | None = None,
refresh_pending: bool = False,
- can_terminate: bool = True,
) -> tuple[LoopOutcome | None, list[tuple[str, int]]]:
- """Shared by the model-dispatched and auto-observe paths so both trip the same nudge/terminate
- thresholds identically — each against its OWN ledger, so an auto snapshot can never pad the
- model ledger's streak toward a can_terminate=True verdict."""
+ """Trips the nudge/terminate thresholds off ``ledger``'s own streak."""
stall_nudges: list[tuple[str, int]] = []
snap = ledger.record(action_key, content_digest)
if snap.progressed:
# This probe saw the page change since it last looked — fresh evidence of progress, so
# repeat counts for actions taken against the old state are stale. A first-time probe has
# no baseline and proves nothing, which is what keeps varied-selector probing from
- # laundering repetition into progress. NOT gated on can_terminate: a multi-page wizard that
- # clicks the same selector (e.g. "next") on every page relies on THIS clear to survive —
- # page_transitioned alone deliberately does not clear the action-loop guard (see below), so
- # only a progressed snapshot does, and progress is progress regardless of which ledger (the
- # model's own observe, or auto-observe) happened to see it. What stays gated on
- # can_terminate is below: auto-observe must never arm perception_stall_imminent or return a
- # terminate verdict, since it fires far more often than the model calls observe on its own
- # and would trip those far too eagerly for a path the model never asked to take.
+ # laundering repetition into progress. A multi-page wizard that clicks the same selector
+ # (e.g. "next") on every page relies on THIS clear to survive — page_transitioned alone
+ # deliberately does not clear the action-loop guard (see below), so only a progressed
+ # snapshot does.
_clear_action_state()
# Two landed digests that differ are positive evidence, exactly like a fingerprint
# mismatch — and the only movement evidence there is when page_fingerprint is absent.
@@ -1698,45 +1554,28 @@ async def run_agent_tool_loop(
if ring is None:
ring = ledger.content_only.setdefault(action_key, deque(maxlen=PERCEPTION_RING))
ring.append(content_only_digest)
- if can_terminate and activity is not None and stall_terminate_after is not None:
- # Auto-observe (can_terminate=False) is a path the model never asked to take, so its
- # snapshots must not arm this flag: it feeds the failure-evidence retry gate below, and a
- # model-issued submit later in the SAME turn must not have its retry suppressed by a
- # probe the model never saw.
+ if activity is not None and stall_terminate_after is not None:
activity.perception_stall_imminent = ledger.next_snapshot_can_trip(stall_terminate_after)
# A refresh about to be honored re-baselines this ledger anyway, so a stall verdict raised on
# the stale page it is replacing would be wrong the instant the reload lands.
if stall_terminate_after is not None and snap.live >= stall_terminate_after and not refresh_pending:
- if not can_terminate:
- # Auto-observe feeds the same ledger a model observe would (for progress detection and
- # the shadow/suppressed reporting below), but it is a NEW path the model never asked
- # to take — it must not be the thing that ends the run. Detection parity, not action
- # parity: log what a model observe would have done here and continue.
- LOG.info(
- "taskv3 auto observe stall would terminate",
- tool=tool_name,
- identical_count=snap.live,
- turn=turns,
- **attribution,
- )
- else:
- LOG.info(
- "taskv3 loop perception stalled",
- tool=tool_name,
- identical_count=snap.live,
- turn=turns,
- **attribution,
- )
- return (
- LoopOutcome(
- "terminated",
- f"{PERCEPTION_STALL_REASON_PREFIX} {snap.live} consecutive identical snapshots from "
- f"one {tool_name} probe — the page stopped changing in response to actions, so the goal "
- "cannot progress (commonly a blocker the run cannot perceive or operate, e.g. inside a "
- "cross-origin frame)",
- ),
- stall_nudges,
- )
+ LOG.info(
+ "taskv3 loop perception stalled",
+ tool=tool_name,
+ identical_count=snap.live,
+ turn=turns,
+ **attribution,
+ )
+ return (
+ LoopOutcome(
+ "terminated",
+ f"{PERCEPTION_STALL_REASON_PREFIX} {snap.live} consecutive identical snapshots from "
+ f"one {tool_name} probe — the page stopped changing in response to actions, so the goal "
+ "cannot progress (commonly a blocker the run cannot perceive or operate, e.g. inside a "
+ "cross-origin frame)",
+ ),
+ stall_nudges,
+ )
if (
stall_terminate_after is not None
and snap.tool_identical == stall_terminate_after
@@ -1847,7 +1686,7 @@ async def run_agent_tool_loop(
# Elide superseded perception results before re-sending the transcript, so a perception-heavy
# run can't balloon the context to the token backstop (the pre-compaction runaway mode).
- _compact_transcript(messages, snapshot_indices, auto_carrier_indices)
+ _compact_transcript(messages, snapshot_indices)
llm_caller.message_history = list(messages)
# Consume any pending look image into THIS call only, then clear: the image rides one request
# and is never appended to `messages`, so the turn after carries zero image blocks.
@@ -1946,29 +1785,21 @@ async def run_agent_tool_loop(
# Loop events minted this batch, emitted only after every progress signal the batch can
# produce has been absorbed (see the end-of-batch emission below).
pending_canonical_fires: list[dict[str, Any]] = []
- # Auto-observe signals, gathered across the whole batch so the end-of-batch check reads the
- # batch's net effect rather than any one call's.
- batch_observed_ok = False
batch_page_change_reason: str | None = None
- batch_probe_before: str | None = None
batch_fp_before: str | None = None
# Sample only when the batch can actually land a billable action -- the end-of-batch check
# below gates on turn_did_action, so a finish-only or perception-only batch has no use for
- # these baselines and shouldn't pay their round-trip.
+ # this baseline and shouldn't pay its round-trip.
batch_has_billable_call = any(
tool_by_name.get(tool_name) is not None and tool_by_name[tool_name].billable
for _, tool_name, _ in tool_calls
)
- # A cancellation that already landed makes this batch's baselines dead work: the per-call
- # check below (before the first dispatch) ends the batch before anything they'd inform runs.
- batch_will_sample_baseline = batch_has_billable_call and (
- page_fingerprint is not None or (auto_observe and page_probe is not None)
- )
+ # A cancellation that already landed makes this batch's baseline dead work: the per-call
+ # check below (before the first dispatch) ends the batch before anything it'd inform runs.
+ batch_will_sample_baseline = batch_has_billable_call and page_fingerprint is not None
batch_cancelled = batch_will_sample_baseline and should_cancel is not None and await should_cancel()
- if auto_observe and page_probe is not None and batch_has_billable_call and not batch_cancelled:
- batch_probe_before = await _sample_probe(page_probe, deadline_at=deadline_at)
- # Sampled on BOTH arms (not just auto-observe): the page-state stall detector reads the
- # before/after fingerprint pair for every billable batch.
+ # The page-state stall detector (SKY-15265) reads the before/after fingerprint pair for
+ # every billable batch.
if page_fingerprint is not None and batch_has_billable_call and not batch_cancelled:
batch_fp_before = await _sample_probe(page_fingerprint, deadline_at=deadline_at)
if page_state_prev_fp is not None and batch_fp_before is not None and batch_fp_before != page_state_prev_fp:
@@ -1978,17 +1809,6 @@ async def run_agent_tool_loop(
# incumbent stall counters keep their end-of-batch turn_did_action gate.
canonical.progress(_ProgressEvidence.CROSS_BATCH_MOVEMENT)
batch_fp_after: str | None = None
- # The auto-observe path's FINAL page-changed verdict (resample included) when it ran; the
- # stall detector prefers this over re-comparing raw samples so the two can never disagree.
- batch_auto_page_changed: bool | None = None
- # Whether that verdict rested on POSITIVE evidence (a flag or two landed samples that
- # differ) rather than the missing-sample "assume changed" fallback.
- batch_auto_page_change_evidence: bool = False
- # The batch's carrier for an auto-observe digest: the LAST tool message appended for an
- # EXECUTED (dispatched) call whose spec is not compactable -- i.e. a real action result, never
- # a skip stub and never a compactable perception dump that would otherwise elide the digest's
- # own index away the next time it's superseded (see _compact_transcript).
- batch_carrier_idx: int | None = None
for idx, (tool_call_id, tool_name, args) in enumerate(tool_calls):
# Enforce the cap per tool call so one batched turn cannot overrun it, and honor a
# cancellation that arrives mid-batch before the next click/type/submit runs. Neither
@@ -2255,8 +2075,6 @@ async def run_agent_tool_loop(
messages.append(
{"role": "tool", "tool_call_id": tool_call_id, "name": tool_name, "content": model_facing_content}
)
- if spec is not None and not spec.compactable:
- batch_carrier_idx = len(messages) - 1
# A look's annotated screenshot is shown to the model on the next call only, never stored in
# the transcript. Consumed and cleared at the top of the next turn. Only the LATEST snapshot
# survives: a second look in the same turn supersedes the first (its marks replace the prior
@@ -2264,18 +2082,7 @@ async def run_agent_tool_loop(
if result.screenshots:
pending_screenshots = list(result.screenshots)
result_data = result.data or {}
- if auto_observe:
- # batch_observed_ok tracks FRESHNESS, not "did an observe happen this batch": any
- # dispatched call that is not a perception snapshot (compactable) invalidates it,
- # since that observe's snapshot now predates a page-changing call -- navigate/scroll/
- # wait are non-billable but still change what a later observe would return.
- if spec is not None and not spec.compactable:
- batch_observed_ok = False
- if tool_name == "observe" and result.status == "ok":
- batch_observed_ok = True
- # Accumulated on BOTH arms (hoisted out of the auto-observe gate for SKY-15265): the
- # page-state stall detector re-baselines on these flags, and a hover or file-upload
- # signal only the auto arm could see would false-kill the manual arm. Keeps the FIRST
+ # The page-state stall detector (SKY-15265) re-baselines on these flags. Keeps the FIRST
# qualifying signal this batch -- the reason field is diagnostic (telemetry), not the
# decision itself, so a later call's signal never overwrites it.
if batch_page_change_reason is None or batch_page_change_reason == "page_transitioned":
@@ -2472,289 +2279,10 @@ async def run_agent_tool_loop(
"the target no longer exists or has been removed, so the goal cannot be completed there",
)
- # Runs BEFORE the nudge message is assembled below (not after): auto-observe's own stall
- # nudge must land in the SAME user message as a model-issued stall/action nudge, not a
- # second consecutive one -- so this collects ao_nudges_result for the assembly below rather
- # than appending its own message. Nav-dead-end still takes priority (checked above).
- # Never touches action_steps/tool_calls accounting -- this is not a model-issued tool call.
- ao_nudges_result: list[tuple[str, int]] = []
- if outcome is None and auto_observe and turn_did_action and not batch_observed_ok and batch_carrier_idx is None:
- # No executed non-compactable call landed a carrier this batch (every dispatched call was
- # compactable, e.g. get_html/look, or every call was skipped) -- nowhere safe to attach a
- # digest that would survive compaction.
- LOG.info(
- "taskv3 auto observe", turn=turns, fired=False, reason="no_carrier", digest_chars=0, wait_seconds=0.0
- )
- elif (
- outcome is None
- and auto_observe
- and turn_did_action
- and not batch_observed_ok
- and batch_carrier_idx is not None
- ):
- wait_seconds = 0.0
- # The deadline is honored at every step below, not just around sleeps: a probe or the
- # observe handler itself can outlive the loop's deadline just as easily as a sleep can,
- # so each sampler call is bounded to whatever's left of the deadline (via _sample_probe's
- # deadline_at) and the path bails with reason="deadline" the instant nothing is left.
- if deadline_at is not None and deadline_at - time.monotonic() <= 0:
- LOG.info(
- "taskv3 auto observe",
- turn=turns,
- fired=False,
- reason="deadline",
- signal="none",
- digest_chars=0,
- wait_seconds=0.0,
- )
- else:
- page_changed: bool
- reason: str
- signal: str
- # Distinguishes a POSITIVELY observed change (a flag, or two landed samples that
- # differ) from the missing-sample fallback below, which is a model-facing "assume
- # changed" but is not evidence and must not clear the canonical tracker.
- page_change_evidence: bool
- if batch_page_change_reason is not None:
- page_changed, reason, signal = True, batch_page_change_reason, "flag"
- page_change_evidence = True
- elif page_fingerprint is not None:
- # The fingerprint samples rendered content (innerHTML), so it catches an in-page
- # mutation (a dropdown, a validation error, a revealed section) the document-identity
- # probe below reads as "unchanged". Only trusted when BOTH samples landed -- a missing
- # before or after reading is not evidence either way, so it falls back to the probe.
- fp_after = await _sample_probe(page_fingerprint, deadline_at=deadline_at)
- batch_fp_after = fp_after
- if batch_fp_before is not None and fp_after is not None:
- page_changed = fp_after != batch_fp_before
- page_change_evidence = page_changed
- reason = "fingerprint_mismatch" if page_changed else "unchanged"
- signal = "fingerprint"
- elif page_probe is not None:
- probe_after = await _sample_probe(page_probe, deadline_at=deadline_at)
- if batch_probe_before is None or probe_after is None or probe_after != batch_probe_before:
- page_changed, reason = True, "probe_mismatch"
- page_change_evidence = batch_probe_before is not None and probe_after is not None
- else:
- page_changed, reason = False, "unchanged"
- page_change_evidence = False
- signal = "probe"
- else:
- page_changed, reason, signal = False, "unchanged", "none"
- page_change_evidence = False
- elif page_probe is not None:
- probe_after = await _sample_probe(page_probe, deadline_at=deadline_at)
- if batch_probe_before is None or probe_after is None or probe_after != batch_probe_before:
- page_changed, reason = True, "probe_mismatch"
- page_change_evidence = batch_probe_before is not None and probe_after is not None
- else:
- page_changed, reason = False, "unchanged"
- page_change_evidence = False
- signal = "probe"
- else:
- page_changed, reason, signal = False, "unchanged", "none"
- page_change_evidence = False
-
- if not page_changed and signal in ("fingerprint", "probe"):
- # The immediate comparison above can be too early for an async render; give it one
- # more settle interval and resample once before accepting "unchanged".
- resample_sampler = page_fingerprint if signal == "fingerprint" else page_probe
- resample_before = batch_fp_before if signal == "fingerprint" else batch_probe_before
- if resample_sampler is not None:
- resampled_changed, resample_wait = await _resample_after_one_settle_interval(
- resample_sampler, resample_before, should_cancel, deadline_at
- )
- wait_seconds += resample_wait
- if resampled_changed:
- page_changed = True
- page_change_evidence = True
- reason = "fingerprint_mismatch" if signal == "fingerprint" else "probe_mismatch"
-
- batch_auto_page_changed = page_changed
- batch_auto_page_change_evidence = page_change_evidence
- if page_changed and page_change_evidence:
- canonical.progress(_ProgressEvidence.AUTO_OBSERVE_VERDICT)
- if not page_changed:
- messages[batch_carrier_idx]["content"] = (
- str(messages[batch_carrier_idx]["content"]) + "\n\n[no markup change detected after this batch]"
- )
- LOG.info(
- "taskv3 auto observe",
- turn=turns,
- fired=False,
- reason=reason,
- signal=signal,
- digest_chars=0,
- wait_seconds=wait_seconds,
- )
- elif deadline_at is not None and deadline_at - time.monotonic() <= 0:
- LOG.info(
- "taskv3 auto observe",
- turn=turns,
- fired=False,
- reason="deadline",
- signal=signal,
- digest_chars=0,
- wait_seconds=wait_seconds,
- )
- else:
- wait_seconds += await _auto_observe_settle_wait(
- page_probe, should_cancel, deadline_at, page_fingerprint=page_fingerprint
- )
- if should_cancel is not None and await should_cancel():
- # Re-checked after the settle wait: skip the observe dispatch and let the loop's
- # own top-of-turn cancellation check end the run as canceled.
- LOG.info(
- "taskv3 auto observe",
- turn=turns,
- fired=False,
- reason="canceled",
- signal=signal,
- digest_chars=0,
- wait_seconds=wait_seconds,
- )
- elif deadline_at is not None and deadline_at - time.monotonic() <= 0:
- LOG.info(
- "taskv3 auto observe",
- turn=turns,
- fired=False,
- reason="deadline",
- signal=signal,
- digest_chars=0,
- wait_seconds=wait_seconds,
- )
- else:
- observe_spec = tool_by_name.get("observe")
- ao_result: ToolResult | None = None
- if observe_spec is not None:
- observe_remaining = None if deadline_at is None else deadline_at - time.monotonic()
- observe_timeout = (
- _PAGE_PROBE_TIMEOUT_SECONDS
- if observe_remaining is None
- else min(_PAGE_PROBE_TIMEOUT_SECONDS, observe_remaining)
- )
- ao_started = time.monotonic()
- try:
- ao_result = await asyncio.wait_for(observe_spec.handler({}), timeout=observe_timeout)
- except Exception:
- LOG.debug("taskv3 auto observe handler raised", turn=turns, exc_info=True)
- ao_result = None
- finally:
- # Counted the same way the normal dispatch path counts tool_seconds
- # (below, at "tool_duration_seconds"): this IS a tool call, just one
- # the loop issued instead of the model.
- tool_seconds += time.monotonic() - ao_started
- # Mirrors the model-dispatched path's post-call check (skyvern_ctx.refresh_working_page,
- # further up): the injected observe can raise this flag exactly like any other
- # handler, whether or not it also raised an exception or returned content, so it is
- # consumed here before the digest below is trusted — a digest from a call that also
- # declared the page stale describes a page the next turn must not plan from.
- ao_ctx = skyvern_context.current()
- if ao_ctx is not None and ao_ctx.refresh_working_page:
- await _consume_refresh_signal(
- ao_ctx, "observe", [], round_actions, drop=reload_page is None
- )
- LOG.info(
- "taskv3 auto observe",
- turn=turns,
- fired=False,
- reason="refresh",
- signal=signal,
- digest_chars=0,
- wait_seconds=wait_seconds,
- )
- elif ao_result is not None and ao_result.status == "ok":
- # Absorbed the same way a model-dispatched observe's result.data would be,
- # so a download/page-change the injected observe reports (staged_downloads,
- # progress, and completion) lands identically whichever path produced it —
- # independent of whether the observe also produced a digest below.
- ao_result_data = ao_result.data or {}
- ao_baseline_before = progress.invalid_baseline if progress is not None else None
- _absorb_result_data("observe", observe_spec, ao_result_data)
- completion_outcome = await _completion_probe_outcome(
- "observe", observe_spec, ao_result_data
- )
- if completion_outcome is not None:
- outcome = completion_outcome
- if ao_result.content:
- digest = ao_result.content
- ao_skyvern_ctx = skyvern_context.current()
- model_facing_digest = (
- ao_skyvern_ctx.hide_from_model(digest) if ao_skyvern_ctx is not None else digest
- )
- model_facing_digest = _neutralize_auto_observe_markers(model_facing_digest)
- messages[batch_carrier_idx]["content"] = (
- str(messages[batch_carrier_idx]["content"])
- + "\n\n"
- + AUTO_OBSERVE_BEGIN
- + "[auto-observe after this batch — page changed]\n"
- + model_facing_digest
- + AUTO_OBSERVE_END
- )
- snapshot_indices.add(batch_carrier_idx)
- auto_carrier_indices.add(batch_carrier_idx)
- ao_action_key = ("observe", "{}")
- ao_digest = hashlib.sha256(
- _canonical_perception_content(ao_result.content).encode()
- ).hexdigest()
- ao_attribution: dict[str, Any] = {
- "action_key_hash": telemetry_hash(telemetry_salt, *ao_action_key),
- "snapshot_digest": telemetry_hash(telemetry_salt, ao_digest),
- "probe_first_time": auto_perception.first_time(ao_action_key),
- }
- _progress_observe_shadow(
- _observe_summary_fields(ao_result), "observe", ao_attribution, ao_baseline_before
- )
- stall_outcome, ao_nudges_result = _perception_stall_check(
- auto_perception,
- ao_digest,
- ao_action_key,
- "observe",
- ao_attribution,
- content_only_digest=hashlib.sha256(
- _content_only_perception(ao_result.content).encode()
- ).hexdigest(),
- can_terminate=False,
- )
- if stall_outcome is not None:
- outcome = stall_outcome
- LOG.info(
- "taskv3 auto observe",
- turn=turns,
- fired=True,
- reason=reason,
- signal=signal,
- digest_chars=len(digest),
- wait_seconds=wait_seconds,
- )
- else:
- LOG.debug("taskv3 auto observe produced no usable digest", turn=turns, reason=reason)
- LOG.info(
- "taskv3 auto observe",
- turn=turns,
- fired=False,
- reason="error",
- signal=signal,
- digest_chars=0,
- wait_seconds=wait_seconds,
- )
- else:
- LOG.debug("taskv3 auto observe produced no usable digest", turn=turns, reason=reason)
- LOG.info(
- "taskv3 auto observe",
- turn=turns,
- fired=False,
- reason="error",
- signal=signal,
- digest_chars=0,
- wait_seconds=wait_seconds,
- )
-
# Page-state stall detector (SKY-15265): tool-independent — any batch of billable work that
# leaves the rendered document byte-identical ticks the counter, whatever tools produced it.
# A missing sample is no evidence either way; any page-change flag or fingerprint movement
- # re-baselines. When the auto-observe path already resolved the batch's verdict (resample
- # included), that verdict is reused so the two can never disagree.
+ # re-baselines.
if outcome is None and turn_did_action and page_fingerprint is not None and batch_fp_before is not None:
if page_state_prev_fp is not None and batch_fp_before != page_state_prev_fp:
# The page moved BETWEEN batches (a delayed render landing after the prior
@@ -2764,10 +2292,6 @@ async def run_agent_tool_loop(
page_state_changed: bool | None
if batch_page_change_reason is not None and batch_page_change_reason != "page_transitioned":
page_state_changed = True
- elif batch_auto_page_changed is not None and batch_page_change_reason is None:
- # The auto verdict treats ANY flag as changed, so when the only signal is the
- # URL-only page_transitioned hint, fall through to the raw fingerprint instead.
- page_state_changed = batch_auto_page_changed
else:
if batch_fp_after is None and not (deadline_at is not None and deadline_at - time.monotonic() <= 0):
batch_fp_after = await _sample_probe(page_fingerprint, deadline_at=deadline_at)
@@ -2776,15 +2300,7 @@ async def run_agent_tool_loop(
if page_state_changed is True:
page_state_stall_rounds = 0
page_state_nudge_delivered = False
- # The auto verdict's missing-sample fallback ("assume changed") re-baselines the
- # incumbent counters above but is not positive evidence: only a flagged or
- # sample-confirmed change may clear the canonical tracker.
- if not (
- batch_page_change_reason is None
- and batch_auto_page_changed is True
- and not batch_auto_page_change_evidence
- ):
- canonical.progress(_ProgressEvidence.PAGE_STATE_VERDICT)
+ canonical.progress(_ProgressEvidence.PAGE_STATE_VERDICT)
elif page_state_changed is False:
page_state_stall_rounds += 1
if page_state_stall_rounds == PAGE_STATE_STALL_TERMINATE_AFTER and page_state_nudge_delivered:
@@ -2824,8 +2340,7 @@ async def run_agent_tool_loop(
# Warn only after the batch completes: a user message may not sit between an assistant
# turn's tool results, and the model reads it with the snapshot that tripped it. Every note
- # due this turn (including auto-observe's own stall nudge, folded in above) shares ONE user
- # message so the transcript keeps alternating roles.
+ # due this turn shares ONE user message so the transcript keeps alternating roles.
nudge_parts: list[str] = []
if outcome is None and refresh_nudge_due:
nudge_parts.append(_refresh_nudge_text())
@@ -2838,8 +2353,6 @@ async def run_agent_tool_loop(
page_state_nudge_delivered = True
LOG.info("taskv3 loop page state stall nudged", rounds=page_state_stall_rounds, turn=turns)
nudge_parts.append(_page_state_nudge_text(page_state_stall_rounds))
- if outcome is None and ao_nudges_result:
- nudge_parts.append(_stall_nudge_text(ao_nudges_result, set(tool_by_name)))
if outcome is None and action_nudges_due:
# Deliver only warnings whose streak survived the batch AND spans turns: a later call in
# the same batch (an observe showing the page changed, a download) may have cleared it,
diff --git a/tests/unit/force_stub_app.py b/tests/unit/force_stub_app.py
index 3010f7077..ff5809994 100644
--- a/tests/unit/force_stub_app.py
+++ b/tests/unit/force_stub_app.py
@@ -45,8 +45,6 @@ def create_forge_stub_app() -> ForgeApp:
# Class constant, not a method — _LazyNamespace would auto-mock it into a non-iterable AsyncMock
# and break every caller that scans it for close-page phrases.
fake_app_module.AGENT_FUNCTION.MAGIC_LINK_CLOSE_SIGNALS = base_agent_function.MAGIC_LINK_CLOSE_SIGNALS
- # Auto-mocked, its truthy MagicMock decision would switch auto-observe on for every engine test.
- fake_app_module.AGENT_FUNCTION.resolve_task_v3_auto_observe = base_agent_function.resolve_task_v3_auto_observe
# Same footgun: _LazyNamespace's truthy AsyncMock would inject extra guidance text into every
# v3 task's extra_system_guidance join.
fake_app_module.AGENT_FUNCTION.resolve_task_v3_extra_guidance = base_agent_function.resolve_task_v3_extra_guidance
diff --git a/tests/unit/test_agent_task_v3.py b/tests/unit/test_agent_task_v3.py
index e4d73e833..29514183a 100644
--- a/tests/unit/test_agent_task_v3.py
+++ b/tests/unit/test_agent_task_v3.py
@@ -45,7 +45,7 @@ from skyvern.forge.sdk.workflow.models.block import (
ValidationBlock,
)
from skyvern.forge.sdk.workflow.models.parameter import CredentialParameter, OutputParameter, ParameterType
-from skyvern.forge.sdk.workflow.models.workflow import WorkflowRun, WorkflowRunStatus
+from skyvern.forge.sdk.workflow.models.workflow import WorkflowRunStatus
from skyvern.forge.taskv3.engine import MIN_ACTION_STEPS
from skyvern.forge.taskv3.loop import LoopOutcome
from skyvern.schemas.workflows import BlockStatus, BlockType
@@ -83,7 +83,6 @@ async def _run_execute_task_v3(
context_overrides: dict[str, Any] | None = None,
own_block_row: WorkflowRunBlock | None = None,
own_block_lookup_raises: BaseException | None = None,
- workflow_permanent_id: str | None = None,
**task_overrides: Any,
) -> tuple[Step, Any, AsyncMock, AsyncMock]:
agent = ForgeAgent()
@@ -190,7 +189,6 @@ async def _run_execute_task_v3(
close_browser_on_completion=True,
browser_session_id=None,
task_block=task_block,
- workflow_permanent_id=workflow_permanent_id,
)
finally:
skyvern_context.reset()
@@ -214,9 +212,7 @@ async def test_execute_task_v3_bills_per_browser_action(monkeypatch: pytest.Monk
monkeypatch, outcome, data_extraction_goal=None, extracted_information_schema=None
)
- # The whole task runs as one loop invocation, keyed to this task so per-run gates bucket on it.
assert loop_mock.await_count == 1
- assert loop_mock.await_args.kwargs["task_id"] == task.task_id
assert step.status == StepStatus.completed
# Every reported browser action becomes one action-result with a non-empty results list,
@@ -233,18 +229,6 @@ async def test_execute_task_v3_bills_per_browser_action(monkeypatch: pytest.Monk
assert len(billed_step.output.actions_and_results) == 3
-async def test_execute_task_v3_threads_workflow_permanent_id_to_the_loop(monkeypatch: pytest.MonkeyPatch) -> None:
- # Task.workflow_permanent_id is never populated on the execution path (get_task builds Task
- # without it), so the executor must receive the workflow run's wpid explicitly and hand it to
- # the loop for per-workflow flag targeting.
- outcome = LoopOutcome(status="completed", reason="ok", extracted_output={"k": "v"})
- _step, _task, loop_mock, _post = await _run_execute_task_v3(
- monkeypatch, outcome, workflow_permanent_id="wpid_from_workflow_run"
- )
- assert loop_mock.await_args.kwargs["workflow_permanent_id"] == "wpid_from_workflow_run"
-
-
@pytest.mark.asyncio
async def test_execute_task_v3_no_actions_bills_nothing(monkeypatch: pytest.MonkeyPatch) -> None:
# A terminate with no browser mutations: the hook still runs (it no-ops on zero actions).
@@ -1104,31 +1088,6 @@ async def _run_execute_step_gate(
return v3_mock, step_engine_mock
-async def test_execute_step_sources_wpid_from_the_workflow_run_row() -> None:
- # Task.workflow_permanent_id is never populated on the execution path, so the dispatch site
- # must source the wpid from the WorkflowRun row it already fetched.
- block = _make_block(TaskBlock)
- now = datetime.now(UTC)
- workflow_run = WorkflowRun(
- workflow_run_id="wr_gate",
- workflow_id="w_gate",
- workflow_permanent_id="wpid_from_row",
- organization_id="o_1",
- status=WorkflowRunStatus.running,
- created_at=now,
- modified_at=now,
- )
- v3_mock, _ = await _run_execute_step_gate(
- engine=agent_module.RunEngine.skyvern_v3,
- task_block=block,
- workflow_run=workflow_run,
- workflow_run_id="wr_gate",
- )
- v3_mock.assert_awaited_once()
- assert v3_mock.await_args.kwargs["workflow_permanent_id"] == "wpid_from_row"
-
-
@pytest.mark.asyncio
@pytest.mark.parametrize("block_cls,overrides", _ALLOWED_BLOCK_CASES, ids=_ALLOWED_BLOCK_IDS)
async def test_execute_step_dispatches_supported_block_types_to_v3(
diff --git a/tests/unit/test_taskv3_engine.py b/tests/unit/test_taskv3_engine.py
index 48032a2e4..f1d31c47a 100644
--- a/tests/unit/test_taskv3_engine.py
+++ b/tests/unit/test_taskv3_engine.py
@@ -622,9 +622,9 @@ async def test_engine_forwards_the_page_probe_and_withholds_it_from_page_free_ru
async def test_engine_forwards_the_page_fingerprint_and_withholds_it_from_page_free_runs(
monkeypatch: pytest.MonkeyPatch,
) -> None:
- # The innerHTML fingerprint sampler also drives the loop's auto-observe change decision (not just
- # make_finish_tool's settle gate) -- drop it anywhere on the way to run_agent_tool_loop and
- # auto-observe silently falls back to the document-identity probe for every in-page mutation.
+ # The innerHTML fingerprint sampler also drives the loop's page-state stall detector (not just
+ # make_finish_tool's settle gate) -- drop it anywhere on the way to run_agent_tool_loop and the
+ # detector silently loses its rendered-content signal.
from skyvern.forge.taskv3 import engine as engine_mod
from skyvern.forge.taskv3.loop import LoopOutcome
@@ -1107,71 +1107,6 @@ async def test_engine_drops_a_leftover_refresh_signal_when_the_loop_is_cancelled
assert ctx.refresh_working_page is False
-async def test_system_prompt_carries_auto_observe_guidance_only_when_the_flag_is_on(
- monkeypatch: pytest.MonkeyPatch,
-) -> None:
- # SYSTEM_PROMPT itself must stay byte-identical to the flag-off prompt: the two auto-observe
- # sentences belong in an addendum appended at the call site, never baked into the base constant,
- # or TASK_V3_AUTO_OBSERVE=off would no longer be a no-op against the base engine.
- from skyvern.config import settings
- from skyvern.forge.taskv3.engine import SYSTEM_PROMPT
- from skyvern.forge.taskv3.loop import LoopOutcome
-
- loop_kwargs: dict[str, Any] = {}
-
- async def fake_loop(**kwargs: Any) -> LoopOutcome:
- loop_kwargs.update(kwargs)
- return LoopOutcome(status="completed", reason="ok")
-
- monkeypatch.setattr(engine_mod, "run_agent_tool_loop", fake_loop)
-
- when_auto_observe_present = "act from that snapshot instead of calling observe again"
- when_batching_present = "put it in the same turn"
-
- monkeypatch.setattr(settings, "TASK_V3_AUTO_OBSERVE", False)
- await run_task_v3_agent_loop(
- page_provider=_fixed_page_provider(_FakePage()), llm_caller=_ScriptedCaller([]), goal="fill the form"
- )
- system_prompt = loop_kwargs["system_prompt"]
- assert system_prompt.startswith(SYSTEM_PROMPT)
- assert when_auto_observe_present not in system_prompt
- assert when_batching_present not in system_prompt
-
- loop_kwargs.clear()
- monkeypatch.setattr(settings, "TASK_V3_AUTO_OBSERVE", True)
- await run_task_v3_agent_loop(
- page_provider=_fixed_page_provider(_FakePage()), llm_caller=_ScriptedCaller([]), goal="fill the form"
- )
- system_prompt = loop_kwargs["system_prompt"]
- assert when_auto_observe_present in system_prompt
- assert when_batching_present in system_prompt
-
-
-async def test_page_free_run_never_gets_auto_observe_guidance_even_with_the_flag_on(
- monkeypatch: pytest.MonkeyPatch,
-) -> None:
- from skyvern.config import settings
- from skyvern.forge.taskv3.loop import LoopOutcome
-
- loop_kwargs: dict[str, Any] = {}
-
- async def fake_loop(**kwargs: Any) -> LoopOutcome:
- loop_kwargs.update(kwargs)
- return LoopOutcome(status="completed", reason="ok")
-
- monkeypatch.setattr(engine_mod, "run_agent_tool_loop", fake_loop)
- monkeypatch.setattr(settings, "TASK_V3_AUTO_OBSERVE", True)
-
- async def no_page() -> Any:
- raise AssertionError("page provider must never be consulted in page-free mode")
-
- await run_task_v3_agent_loop(page_provider=no_page, llm_caller=_ScriptedCaller([]), goal="decide", page_free=True)
- assert loop_kwargs["auto_observe"] is False
- assert "act from that snapshot instead of calling observe again" not in loop_kwargs["system_prompt"]
-
-
def test_caller_level_bridge_check_denies_raw_client_dispatch() -> None:
# A custom/BYO model can be NAMED gpt-5.6-* yet dispatch through the raw OpenAI client branch,
# which never bridges — the dict form there is a schema violation on every call. The caller-level
diff --git a/tests/unit/test_taskv3_loop.py b/tests/unit/test_taskv3_loop.py
index f51e9203d..67ee9d1fa 100644
--- a/tests/unit/test_taskv3_loop.py
+++ b/tests/unit/test_taskv3_loop.py
@@ -2052,9 +2052,9 @@ async def test_action_step_budget_extension_not_stamped_by_replayed_download_not
def test_content_only_perception_ignores_the_url_value() -> None:
# The URL is a hint, not content: the evidence lane's digest ignores a history.pushState URL
- # flip (which under auto-observe would otherwise read as a progressed snapshot on a frozen
- # document), while the full canonicalization keeps the URL so wizard pages that differ only by
- # URL still clear the repeat guards.
+ # flip (which would otherwise read as a progressed snapshot on a frozen document), while the
+ # full canonicalization keeps the URL so wizard pages that differ only by URL still clear the
+ # repeat guards.
from skyvern.forge.taskv3.loop import _content_only_perception
a = _content_only_perception("url=https://site.test/a title='T' (3 interactive elements)\nbutton#x")
@@ -2083,8 +2083,7 @@ def test_budget_extension_gate_deadline_scales_with_observed_pace() -> None:
async def test_page_state_stall_nudges_then_terminates_a_frozen_page_cycle() -> None:
# SKY-15265: a tool cycle that leaves the page fingerprint byte-identical round after round is
# a stall no per-tool guard can see (varied selectors never streak; scroll/wait carry no
- # digest). The detector re-plans the model once, then ends the run with a facetable verdict —
- # on EITHER arm (auto-observe off here).
+ # digest). The detector re-plans the model once, then ends the run with a facetable verdict.
clicks: list[tuple[str, dict[str, Any]]] = []
click = _recording_tool("click", clicks, billable=True)
observe = _perception_tool("observe", [f"panel variant {i}" for i in range(30)])
@@ -4587,6 +4586,59 @@ async def test_deadline_already_elapsed_bounds_every_reachable_batch_probe(scena
assert outcome.status in ("budget_exhausted", "completed")
+async def test_pre_batch_fingerprint_sample_is_bounded_by_an_already_elapsed_deadline() -> None:
+ # The stall detector's pre-batch fingerprint baseline passes deadline_at, so a slow LLM turn that
+ # burns the whole deadline must skip the sample entirely -- a hanging sampler there would otherwise
+ # run the full 10s probe timeout with the run already over.
+ fp_calls = {"n": 0}
+
+ async def hanging_fingerprint() -> str | None:
+ fp_calls["n"] += 1
+ await asyncio.sleep(5.0)
+ return "fp"
+
+ async def click_handler(_args: dict[str, Any]) -> ToolResult:
+ return ToolResult.ok("click done")
+
+ tools = [
+ ToolSpec(
+ name="click",
+ description="click",
+ parameters={"type": "object", "properties": {}},
+ handler=click_handler,
+ billable=True,
+ ),
+ make_finish_tool(),
+ ]
+
+ class _SlowFirstCallCaller(_ScriptedCaller):
+ async def call(self, **kwargs: Any) -> dict[str, Any]:
+ if self.calls == 0:
+ await asyncio.sleep(0.2) # eats the whole deadline before this turn's batch dispatches
+ return await super().call(**kwargs)
+
+ caller = _SlowFirstCallCaller(
+ [[("click", {"selector": "#next"})], [("finish", {"status": "completed", "reason": "ok"})]]
+ )
+ started = time.monotonic()
+ outcome = await run_agent_tool_loop(
+ llm_caller=caller,
+ system_prompt="sys",
+ user_prompt="goal",
+ tools=tools,
+ max_turns=20,
+ max_tool_calls=100,
+ page_fingerprint=hanging_fingerprint,
+ deadline_seconds=0.05,
+ )
+ elapsed = time.monotonic() - started
+
+ assert outcome.status == "budget_exhausted"
+ assert fp_calls["n"] == 0 # deadline already gone -- the hanging sampler was never awaited
+ assert elapsed <= 0.3
+
+
@pytest.mark.asyncio
async def test_a_confirmed_page_completes_even_though_a_submit_just_fired() -> None:
# The control, and the direction that decides whether the gate is safe: a run whose clicked
@@ -5816,47 +5868,6 @@ async def test_progress_ledger_shadow_fires_on_varied_action_zero_net_progress()
assert not outcome.reason.startswith(ACTION_LOOP_REASON_PREFIX)
-async def test_auto_observe_progress_ledger_shadow_fires_on_plateaued_invalid_fields(
- monkeypatch: pytest.MonkeyPatch,
-) -> None:
- # Mirrors test_progress_ledger_shadow_fires_on_varied_action_zero_net_progress for the
- # auto-observe path: the model never calls `observe` itself here, so the ONLY way the ledger sees
- # this plateau is if the auto-observe dispatch also feeds _progress_observe_shadow. Pins that call
- # (loop.py, the end-of-batch auto-observe block) against being silently dropped -- every other
- # test in this file stays green even if it is.
- monkeypatch.setattr(loop_module, "AUTO_OBSERVE_SETTLE_INTERVAL_SECONDS", 0.0)
- # No page_transitioned/page_state_changed flag on click -- that would call progress.hard_progress()
- # on every round (a real page transition IS progress) and mask the plateau under test. A changing
- # fingerprint fires auto-observe every round without touching that hard-progress signal.
- fp_calls = {"n": 0}
-
- async def fingerprint() -> str:
- fp_calls["n"] += 1
- return f"v{fp_calls['n']}"
-
- rounds = PROGRESS_LEDGER_WINDOW + 2
- clicks: list[tuple[str, dict[str, Any]]] = []
- tools = [
- _billable_tool("click", clicks),
- _form_observe("observe", [3] * rounds),
- make_finish_tool(),
- ]
- script = [[("click", {"selector": f"#f{i}"})] for i in range(rounds)]
- script.append([("finish", {"status": "completed", "reason": "done"})])
- with capture_logs() as logs:
- outcome, _ = await _run(
- script, tools, auto_observe=True, page_fingerprint=fingerprint, max_turns=200, max_tool_calls=500
- )
- fires = [e for e in logs if e.get("event") == PROGRESS_LEDGER_SHADOW_EVENT]
- assert len(fires) == 1 # one-shot per run
- assert fires[0]["form_armed"] is True
- assert fires[0]["invalid_fields"] == 3
- assert outcome.status == "completed"
- assert not outcome.reason.startswith(PERCEPTION_STALL_REASON_PREFIX)
- assert not outcome.reason.startswith(ACTION_LOOP_REASON_PREFIX)
-
-
@pytest.mark.asyncio
async def test_progress_ledger_silent_when_invalid_fields_ratchets_down() -> None:
# A slow-but-progressing form: the invalid-field count reaches a NEW LOW every few actions, which
@@ -6790,1958 +6801,157 @@ async def test_pending_refresh_is_consumed_before_the_pre_action_hook() -> None:
assert hook_calls == [] and click_calls == []
-# Auto-observe: appends a fresh observe digest to a page-changing action batch's last tool message
-# so the model can act from it without spending a separate perception turn.
-
-
@pytest.mark.asyncio
-async def test_auto_observe_appends_digest_after_page_changing_batch(monkeypatch: pytest.MonkeyPatch) -> None:
- monkeypatch.setattr(loop_module, "AUTO_OBSERVE_SETTLE_INTERVAL_SECONDS", 0.0)
- from skyvern.forge.taskv3.loop import AUTO_OBSERVE_BEGIN
-
+async def test_model_only_perception_stall_still_terminates_at_the_configured_threshold() -> None:
+ # A run stuck re-reading an identical digest must terminate once the streak crosses the
+ # configured threshold.
clicks: list[tuple[str, dict[str, Any]]] = []
- observe_calls = {"n": 0}
-
- async def observe_handler(_args: dict[str, Any]) -> ToolResult:
- observe_calls["n"] += 1
- return ToolResult.ok(
- "url=x AUTO_DIGEST_MARKER (1 interactive elements)", data={"summary": {"invalid_fields": 0}}
- )
-
tools = [
_billable_tool("click", clicks, data={"page_transitioned": True}),
- ToolSpec(
- name="observe",
- description="o",
- parameters={"type": "object", "properties": {}},
- handler=observe_handler,
- compactable=True,
- ),
+ _perception_tool("observe", "url=x FROZEN (1 interactive elements)"),
make_finish_tool(),
]
- script = [
- [("click", {"selector": "#next"})],
- [("finish", {"status": "completed", "reason": "ok"})],
- ]
- outcome, _ = await _run(script, tools, auto_observe=True)
+ script = [[("click", {"selector": f"#btn{i}"}), ("observe", {})] for i in range(10)]
+ outcome, _ = await _run(script, tools, stall_terminate_after=4, max_turns=30)
- assert outcome.status == "completed"
- assert outcome.action_steps == 1
- assert outcome.turns == 2 # no extra turn spent perceiving -- the digest rides the click's result
- assert observe_calls["n"] == 1
- click_msgs = [m for m in outcome.messages if m.get("role") == "tool" and m.get("name") == "click"]
- assert len(click_msgs) == 1
- assert "click done" in click_msgs[0]["content"]
- assert AUTO_OBSERVE_BEGIN in click_msgs[0]["content"]
- assert "AUTO_DIGEST_MARKER" in click_msgs[0]["content"]
+ assert outcome.status == "terminated"
+ assert outcome.reason.startswith(PERCEPTION_STALL_REASON_PREFIX)
+ assert len(clicks) < 10
@pytest.mark.asyncio
-async def test_auto_observe_download_notice_reaches_completion_probe_like_a_model_observe(
- monkeypatch: pytest.MonkeyPatch,
-) -> None:
- # The injected auto-observe's own result.data can carry the download signal (staged_download +
- # download_notice) just as a model-issued observe's would; it must reach staged_downloads and the
- # completion probe exactly the same way, ending the run without any finish call.
- monkeypatch.setattr(loop_module, "AUTO_OBSERVE_SETTLE_INTERVAL_SECONDS", 0.0)
+async def test_model_observe_perception_stall_still_terminates_the_same_digest_sequence() -> None:
+ # Same identical-digest shape as above, over a longer run: the streak must keep terminating
+ # rather than being diluted by the extra rounds.
clicks: list[tuple[str, dict[str, Any]]] = []
- staged_downloads: set[str] = set()
- probe_calls: list[frozenset[str]] = []
-
- async def probe(staged: frozenset[str]) -> str | None:
- probe_calls.append(staged)
- return "a file finished downloading" if "report.csv" in staged else None
-
- async def observe_handler(_args: dict[str, Any]) -> ToolResult:
- return ToolResult.ok(
- "url=x (1 interactive elements)",
- data={"staged_download": "report.csv", "download_notice": True, "summary": {"invalid_fields": 0}},
- )
-
tools = [
_billable_tool("click", clicks, data={"page_transitioned": True}),
- ToolSpec(
- name="observe",
- description="o",
- parameters={"type": "object", "properties": {}},
- handler=observe_handler,
- compactable=True,
- ),
+ _perception_tool("observe", "url=x FROZEN (1 interactive elements)"),
make_finish_tool(),
]
- script = [[("click", {"selector": "#download"})]]
-
- outcome, _ = await _run(script, tools, auto_observe=True, completion_probe=probe, staged_downloads=staged_downloads)
+ script = [[("click", {"selector": f"#btn{i}"}), ("observe", {})] for i in range(20)]
+ outcome, caller = await _run(script, tools, max_turns=30, max_tool_calls=200)
- assert outcome.status == "completed"
- assert outcome.reason == "a file finished downloading"
- assert "report.csv" in staged_downloads
- assert any("report.csv" in staged for staged in probe_calls)
+ assert outcome.status == "terminated"
+ assert outcome.reason.startswith(PERCEPTION_STALL_REASON_PREFIX)
+ assert len(clicks) < 20 # bounded well below the full script
+ assert caller.calls <= 20
@pytest.mark.asyncio
-async def test_auto_observe_without_download_data_leaves_completion_unaffected(
- monkeypatch: pytest.MonkeyPatch,
-) -> None:
- # Negative counterpart: an injected observe whose result carries no download data must not
- # complete the run via the probe -- the model's own finish call decides the outcome as today.
- monkeypatch.setattr(loop_module, "AUTO_OBSERVE_SETTLE_INTERVAL_SECONDS", 0.0)
+async def test_model_observe_repeated_identical_snapshots_arms_perception_stall_imminent() -> None:
+ # Approaching the stall threshold must arm perception_stall_imminent, which suppresses the
+ # failure-evidence retry gate for a later submit failure.
clicks: list[tuple[str, dict[str, Any]]] = []
- staged_downloads: set[str] = set()
- probe_calls: list[frozenset[str]] = []
-
- async def probe(staged: frozenset[str]) -> str | None:
- probe_calls.append(staged)
- return "a file finished downloading" if "report.csv" in staged else None
-
- async def observe_handler(_args: dict[str, Any]) -> ToolResult:
- return ToolResult.ok("url=x (1 interactive elements)", data={"summary": {"invalid_fields": 0}})
-
tools = [
_billable_tool("click", clicks, data={"page_transitioned": True}),
- ToolSpec(
- name="observe",
- description="o",
- parameters={"type": "object", "properties": {}},
- handler=observe_handler,
- compactable=True,
- ),
+ _perception_tool("observe", "url=x FROZEN (1 interactive elements)"),
make_finish_tool(),
]
- script = [
- [("click", {"selector": "#download"})],
- [("finish", {"status": "completed", "reason": "manual finish"})],
- ]
+ script = [[("click", {"selector": f"#btn{i}"}), ("observe", {})] for i in range(20)]
+ activity = ActivityRecency()
+ outcome, _ = await _run(script, tools, activity=activity, max_turns=30, max_tool_calls=200)
- outcome, _ = await _run(script, tools, auto_observe=True, completion_probe=probe, staged_downloads=staged_downloads)
+ assert outcome.status == "terminated"
+ assert activity.perception_stall_imminent is True
- assert outcome.status == "completed"
- assert outcome.reason == "manual finish" # not the probe's reason -- the probe never fired on it
- assert staged_downloads == set()
- assert all("report.csv" not in staged for staged in probe_calls)
+class _ReasoningDictSensitiveCaller(_ScriptedCaller):
+ """Rejects any call carrying a dict reasoning_effort, as a provider without the responses
+ bridge would."""
-async def test_auto_observe_pre_batch_baselines_skip_non_billable_batches(monkeypatch: pytest.MonkeyPatch) -> None:
- # The end-of-batch auto-observe check is gated on turn_did_action, which only a billable tool
- # call sets. A batch with no billable call (observe-only, finish-only) can never reach that
- # check, so sampling the batch_probe_before/batch_fp_before baselines before it runs is pure
- # waste -- up to two round-trips per turn for nothing on a wedged renderer.
- #
- # page_fingerprint isolates the fix cleanly: unlike page_probe (also sampled per-call for an
- # unrelated navigate-dead-end check), it is touched ONLY by the batch baseline and the
- # turn_did_action-gated end-of-batch check, so any non-zero count here is exactly the waste
- # this fix removes.
- monkeypatch.setattr(loop_module, "AUTO_OBSERVE_SETTLE_INTERVAL_SECONDS", 0.0)
+ def __init__(self, script: list[list[tuple[str, dict[str, Any]]]]) -> None:
+ super().__init__(script)
+ self.reasoning_per_call: list[Any] = []
- observe_calls: list[tuple[str, dict[str, Any]]] = []
- fp_calls = {"n": 0}
+ async def call(self, **kwargs: Any) -> dict[str, Any]:
+ self.reasoning_per_call.append(kwargs.get("reasoning_effort"))
+ if isinstance(kwargs.get("reasoning_effort"), dict):
+ raise LLMProviderErrorRetryableTask("TEST_KEY")
+ return await super().call(**kwargs)
- async def fingerprint() -> str | None:
- fp_calls["n"] += 1
- return "f"
- tools = [_recording_tool("observe", observe_calls), make_finish_tool()]
- script = [
- [("observe", {})],
- [("finish", {"status": "completed", "reason": "ok"})],
- ]
- outcome, _ = await _run(script, tools, auto_observe=True, page_fingerprint=fingerprint)
+async def test_loop_drops_reasoning_dict_and_retries_the_turn_after_a_call_failure() -> None:
+ # A bridge-gate false positive must degrade to the config's own reasoning_effort, not end the
+ # run on turn 1.
+ caller = _ReasoningDictSensitiveCaller([[("finish", {"status": "completed", "reason": "ok"})]])
+ outcome = await run_agent_tool_loop(
+ llm_caller=caller,
+ system_prompt="sys",
+ user_prompt="goal",
+ tools=[make_finish_tool()],
+ max_turns=5,
+ max_tool_calls=10,
+ call_kwargs={"reasoning_effort": {"effort": "high", "summary": "auto"}},
+ retryable_call_exceptions=(LLMProviderErrorRetryableTask,),
+ max_call_retries=2,
+ call_retry_base_delay=0.0,
+ )
assert outcome.status == "completed"
- assert fp_calls["n"] == 0
-
- # A batch with a billable click must still sample the baseline exactly once BEFORE the click
- # dispatches -- captured via a snapshot taken inside the click handler itself, since that is
- # the earliest point any post-dispatch (end-of-batch) sampling could have added to the count.
- click_calls: list[tuple[str, dict[str, Any]]] = []
- fp_calls_click = {"n": 0}
- fp_snapshot_at_click: dict[str, int] = {}
+ dict_calls = [r for r in caller.reasoning_per_call if isinstance(r, dict)]
+ assert dict_calls and caller.reasoning_per_call[-1] is None
- async def fingerprint_click() -> str | None:
- fp_calls_click["n"] += 1
- return "f"
- async def click_handler(args: dict[str, Any]) -> ToolResult:
- click_calls.append(("click", args))
- fp_snapshot_at_click["n"] = fp_calls_click["n"]
- return ToolResult.ok("click done")
+class _ReasoningDictOnlySensitiveCaller(_ScriptedCaller):
+ """Rejects only the dict reasoning_effort; tool_choice is independently supported."""
- click_tool = ToolSpec(
- name="click",
- description="click",
- parameters={"type": "object", "properties": {}},
- handler=click_handler,
- billable=True,
- )
- tools_with_click = [click_tool, make_finish_tool()]
- script_with_click = [
- [("click", {"selector": "#next"})],
- [("finish", {"status": "completed", "reason": "ok"})],
- ]
- outcome_click, _ = await _run(
- script_with_click,
- tools_with_click,
- auto_observe=True,
- page_fingerprint=fingerprint_click,
- )
+ def __init__(self, script: list[list[tuple[str, dict[str, Any]]]]) -> None:
+ super().__init__(script)
+ self.kwargs_per_call: list[tuple[Any, Any]] = []
- assert outcome_click.status == "completed"
- assert fp_snapshot_at_click["n"] == 1
+ async def call(self, **kwargs: Any) -> dict[str, Any]:
+ self.kwargs_per_call.append((kwargs.get("reasoning_effort"), kwargs.get("tool_choice")))
+ if isinstance(kwargs.get("reasoning_effort"), dict):
+ raise LLMProviderErrorRetryableTask("TEST_KEY")
+ return await super().call(**kwargs)
@pytest.mark.asyncio
-async def test_auto_observe_pre_batch_baselines_skip_when_already_canceled(monkeypatch: pytest.MonkeyPatch) -> None:
- # A cancellation that already landed before a billable batch makes its baseline sample dead work:
- # the per-call check ends the batch (as canceled) before the click, or anything the baseline would
- # inform, ever runs.
- monkeypatch.setattr(loop_module, "AUTO_OBSERVE_SETTLE_INTERVAL_SECONDS", 0.0)
+async def test_degrading_the_summary_dict_keeps_tool_choice() -> None:
+ caller = _ReasoningDictOnlySensitiveCaller([[("finish", {"status": "completed", "reason": "ok"})]])
+ outcome = await run_agent_tool_loop(
+ llm_caller=caller,
+ system_prompt="sys",
+ user_prompt="goal",
+ tools=[make_finish_tool()],
+ max_turns=5,
+ max_tool_calls=10,
+ call_kwargs={"reasoning_effort": {"effort": "high", "summary": "auto"}, "tool_choice": "required"},
+ retryable_call_exceptions=(LLMProviderErrorRetryableTask,),
+ max_call_retries=2,
+ call_retry_base_delay=0.0,
+ )
+ assert outcome.status == "completed"
+ final_reasoning, final_tool_choice = caller.kwargs_per_call[-1]
+ assert final_reasoning is None
+ assert final_tool_choice == "required"
- fp_calls = {"n": 0}
- async def fingerprint() -> str | None:
- fp_calls["n"] += 1
- return "f"
+def test_canonical_progress_tracker_counts_targets_and_clears_on_progress() -> None:
+ from skyvern.forge.taskv3.loop import _CanonicalProgressTracker, _ProgressEvidence
- async def should_cancel() -> bool:
- return True
+ t = _CanonicalProgressTracker()
+ assert t.record_touch("#code", True) == (1, 1)
+ assert t.record_touch("#code", True) == (2, 2)
+ assert t.record_touch("#other", False) == (1, 0)
+ assert t.record_touch("#code", True) == (3, 3)
+ assert t.looping_targets() == 0 # below the 4-touch rung
+ assert t.record_touch("#code", False) == (4, 3)
+ assert t.looping_targets() == 1
+ t.progress(_ProgressEvidence.FRESH_DOWNLOAD_OR_NAVIGATION)
+ assert t.record_touch("#code", True) == (1, 1) # streak reset by progress
+ assert t.looping_targets() == 0
- click_calls: list[tuple[str, dict[str, Any]]] = []
- tools = [_billable_tool("click", click_calls), make_finish_tool()]
- script = [[("click", {"selector": "#next"})]]
- outcome, _ = await _run(script, tools, auto_observe=True, page_fingerprint=fingerprint, should_cancel=should_cancel)
-
- assert outcome.status == "canceled"
- assert fp_calls["n"] == 0
- assert click_calls == []
-
-
-async def test_auto_observe_digest_lands_in_tool_message_not_the_action_nudge(
- monkeypatch: pytest.MonkeyPatch,
-) -> None:
- # The action-repeat nudge appends a `role: user` message AFTER the batch's tool results, so it
- # becomes messages[-1] by the time auto-observe runs. The digest must still land on the batch's
- # own tool message, not overwrite the nudge.
- monkeypatch.setattr(loop_module, "AUTO_OBSERVE_SETTLE_INTERVAL_SECONDS", 0.0)
- from skyvern.forge.taskv3.loop import AUTO_OBSERVE_BEGIN
-
- clicks: list[tuple[str, dict[str, Any]]] = []
- observe_calls = {"n": 0}
-
- async def observe_handler(_args: dict[str, Any]) -> ToolResult:
- observe_calls["n"] += 1
- return ToolResult.ok(
- "url=x AUTO_DIGEST_MARKER (1 interactive elements)", data={"summary": {"invalid_fields": 0}}
- )
-
- tools = [
- _billable_tool("click", clicks, data={"page_transitioned": True}),
- ToolSpec(
- name="observe",
- description="o",
- parameters={"type": "object", "properties": {}},
- handler=observe_handler,
- compactable=True,
- ),
- make_finish_tool(),
- ]
- script = [
- [("click", {"selector": "#retry"})],
- [("click", {"selector": "#retry"})], # same action, second turn -- crosses the nudge threshold
- [("finish", {"status": "completed", "reason": "ok"})],
- ]
- outcome, _ = await _run(script, tools, auto_observe=True, action_nudge_after=2, action_terminate_after=10)
-
- assert outcome.status == "completed"
- click_msgs = [m for m in outcome.messages if m.get("role") == "tool" and m.get("name") == "click"]
- assert len(click_msgs) == 2
- second_click = click_msgs[-1]
- assert AUTO_OBSERVE_BEGIN in second_click["content"]
- assert "AUTO_DIGEST_MARKER" in second_click["content"]
-
- nudge_msgs = [m for m in outcome.messages if m.get("role") == "user" and "#retry" in str(m.get("content"))]
- assert len(nudge_msgs) == 1
- nudge_content = str(nudge_msgs[0]["content"])
- assert "click on #retry 2 times" in nudge_content
- assert "unchanged since before the first attempt" in nudge_content
- assert AUTO_OBSERVE_BEGIN not in nudge_content
-
- assert outcome.messages.index(second_click) < outcome.messages.index(nudge_msgs[0])
-
-
-async def test_auto_observe_unchanged_page_appends_notice_without_calling_observe() -> None:
- clicks: list[tuple[str, dict[str, Any]]] = []
- observe_calls = {"n": 0}
-
- async def observe_handler(_args: dict[str, Any]) -> ToolResult:
- observe_calls["n"] += 1
- return ToolResult.ok("should never be called")
-
- async def stable_probe() -> str:
- return "same-fingerprint"
-
- tools = [
- _billable_tool("click", clicks), # no page_transitioned/page_state_changed flag
- ToolSpec(
- name="observe",
- description="o",
- parameters={"type": "object", "properties": {}},
- handler=observe_handler,
- compactable=True,
- ),
- make_finish_tool(),
- ]
- script = [
- [("click", {"selector": "#toggle"})],
- [("finish", {"status": "completed", "reason": "ok"})],
- ]
- outcome, _ = await _run(script, tools, auto_observe=True, page_probe=stable_probe)
-
- assert observe_calls["n"] == 0
- click_msgs = [m for m in outcome.messages if m.get("role") == "tool" and m.get("name") == "click"]
- assert click_msgs[0]["content"] == "click done\n\n[no markup change detected after this batch]"
-
-
-async def test_auto_observe_fingerprint_mismatch_fires_when_probe_is_stable(monkeypatch: pytest.MonkeyPatch) -> None:
- # The document-identity probe (URL + nonce) is blind to an in-page DOM mutation (a dropdown
- # opened, a validation error rendered) that never re-maps the document -- the innerHTML
- # fingerprint is what catches it. No page_transitioned/page_state_changed flag and an identical
- # probe reading must not suppress the fire when the fingerprint disagrees.
- monkeypatch.setattr(loop_module, "AUTO_OBSERVE_SETTLE_INTERVAL_SECONDS", 0.0)
- from skyvern.forge.taskv3.loop import AUTO_OBSERVE_BEGIN
-
- clicks: list[tuple[str, dict[str, Any]]] = []
- observe_calls = {"n": 0}
-
- async def observe_handler(_args: dict[str, Any]) -> ToolResult:
- observe_calls["n"] += 1
- return ToolResult.ok(
- "url=x AUTO_DIGEST_MARKER (1 interactive elements)", data={"summary": {"invalid_fields": 0}}
- )
-
- async def stable_probe() -> str:
- return "same-document"
-
- fp_values = iter(["fp-before", "fp-after", "fp-after", "fp-after"])
-
- async def changing_fingerprint() -> str:
- return next(fp_values)
-
- tools = [
- _billable_tool("click", clicks), # no page_transitioned/page_state_changed flag
- ToolSpec(
- name="observe",
- description="o",
- parameters={"type": "object", "properties": {}},
- handler=observe_handler,
- compactable=True,
- ),
- make_finish_tool(),
- ]
- script = [
- [("click", {"selector": "#toggle"})],
- [("finish", {"status": "completed", "reason": "ok"})],
- ]
- with capture_logs() as logs:
- outcome, _ = await _run(
- script, tools, auto_observe=True, page_probe=stable_probe, page_fingerprint=changing_fingerprint
- )
-
- assert outcome.status == "completed"
- assert observe_calls["n"] == 1
- click_msgs = [m for m in outcome.messages if m.get("role") == "tool" and m.get("name") == "click"]
- assert AUTO_OBSERVE_BEGIN in click_msgs[0]["content"]
- fires = [e for e in logs if e.get("event") == "taskv3 auto observe" and e.get("fired") is True]
- assert len(fires) == 1
- assert fires[0]["reason"] == "fingerprint_mismatch"
- assert fires[0]["signal"] == "fingerprint"
-
-
-async def test_auto_observe_fingerprint_and_probe_both_stable_appends_notice() -> None:
- clicks: list[tuple[str, dict[str, Any]]] = []
- observe_calls = {"n": 0}
-
- async def observe_handler(_args: dict[str, Any]) -> ToolResult:
- observe_calls["n"] += 1
- return ToolResult.ok("should never be called")
-
- async def stable_probe() -> str:
- return "same-document"
-
- async def stable_fingerprint() -> str:
- return "same-markup"
-
- tools = [
- _billable_tool("click", clicks), # no page_transitioned/page_state_changed flag
- ToolSpec(
- name="observe",
- description="o",
- parameters={"type": "object", "properties": {}},
- handler=observe_handler,
- compactable=True,
- ),
- make_finish_tool(),
- ]
- script = [
- [("click", {"selector": "#toggle"})],
- [("finish", {"status": "completed", "reason": "ok"})],
- ]
- with capture_logs() as logs:
- outcome, _ = await _run(
- script, tools, auto_observe=True, page_probe=stable_probe, page_fingerprint=stable_fingerprint
- )
-
- assert observe_calls["n"] == 0
- click_msgs = [m for m in outcome.messages if m.get("role") == "tool" and m.get("name") == "click"]
- assert click_msgs[0]["content"] == "click done\n\n[no markup change detected after this batch]"
- fires = [e for e in logs if e.get("event") == "taskv3 auto observe" and e.get("fired") is False]
- assert any(f.get("reason") == "unchanged" and f.get("signal") == "fingerprint" for f in fires)
-
-
-async def test_auto_observe_resamples_after_unchanged_and_fires_when_it_now_differs(
- monkeypatch: pytest.MonkeyPatch,
-) -> None:
- # An async render (a spinner resolving, a debounced mutation) can still be in flight at the
- # immediate post-batch sample: reading "unchanged" there is too early, not necessarily true. One
- # bounded settle interval plus a single resample must catch it before the batch is written off.
- monkeypatch.setattr(loop_module, "AUTO_OBSERVE_SETTLE_INTERVAL_SECONDS", 0.0)
- monkeypatch.setattr(loop_module, "AUTO_OBSERVE_SETTLE_CAP_SECONDS", 0.0)
- from skyvern.forge.taskv3.loop import AUTO_OBSERVE_BEGIN
-
- clicks: list[tuple[str, dict[str, Any]]] = []
- observe_calls = {"n": 0}
-
- async def observe_handler(_args: dict[str, Any]) -> ToolResult:
- observe_calls["n"] += 1
- return ToolResult.ok(
- "url=x AUTO_DIGEST_MARKER (1 interactive elements)", data={"summary": {"invalid_fields": 0}}
- )
-
- # before, immediate-after (equal -> reads unchanged), resample (differs); clamps to the last
- # value for any further sample the settle wait takes.
- fp_values = ["baseline", "baseline", "changed"]
- fp_calls = {"n": 0}
-
- async def fingerprint() -> str:
- idx = min(fp_calls["n"], len(fp_values) - 1)
- fp_calls["n"] += 1
- return fp_values[idx]
-
- tools = [
- _billable_tool("click", clicks), # no page_transitioned/page_state_changed flag
- ToolSpec(
- name="observe",
- description="o",
- parameters={"type": "object", "properties": {}},
- handler=observe_handler,
- compactable=True,
- ),
- make_finish_tool(),
- ]
- script = [
- [("click", {"selector": "#save"})],
- [("finish", {"status": "completed", "reason": "ok"})],
- ]
- with capture_logs() as logs:
- outcome, _ = await _run(script, tools, auto_observe=True, page_fingerprint=fingerprint)
-
- assert outcome.status == "completed"
- assert observe_calls["n"] == 1 # the auto-observe dispatch fired
- click_msgs = [m for m in outcome.messages if m.get("role") == "tool" and m.get("name") == "click"]
- assert AUTO_OBSERVE_BEGIN in click_msgs[0]["content"]
- fires = [e for e in logs if e.get("event") == "taskv3 auto observe" and e.get("fired") is True]
- assert len(fires) == 1
- assert fires[0]["reason"] == "fingerprint_mismatch"
- assert fires[0]["signal"] == "fingerprint"
-
-
-async def test_auto_observe_resamples_after_unchanged_and_stays_unchanged_when_still_equal(
- monkeypatch: pytest.MonkeyPatch,
-) -> None:
- # The other side of the resample: a genuinely frozen page must still read as unchanged after the
- # extra settle interval, and that wait is accounted for in the logged wait_seconds rather than
- # silently dropped.
- monkeypatch.setattr(loop_module, "AUTO_OBSERVE_SETTLE_INTERVAL_SECONDS", 0.01)
-
- clicks: list[tuple[str, dict[str, Any]]] = []
- observe_calls = {"n": 0}
-
- async def observe_handler(_args: dict[str, Any]) -> ToolResult:
- observe_calls["n"] += 1
- return ToolResult.ok("should never be called")
-
- async def stable_fingerprint() -> str:
- return "same-markup"
-
- tools = [
- _billable_tool("click", clicks),
- ToolSpec(
- name="observe",
- description="o",
- parameters={"type": "object", "properties": {}},
- handler=observe_handler,
- compactable=True,
- ),
- make_finish_tool(),
- ]
- script = [
- [("click", {"selector": "#save"})],
- [("finish", {"status": "completed", "reason": "ok"})],
- ]
- with capture_logs() as logs:
- outcome, _ = await _run(script, tools, auto_observe=True, page_fingerprint=stable_fingerprint)
-
- assert outcome.status == "completed"
- assert observe_calls["n"] == 0
- click_msgs = [m for m in outcome.messages if m.get("role") == "tool" and m.get("name") == "click"]
- assert click_msgs[0]["content"] == "click done\n\n[no markup change detected after this batch]"
- fires = [e for e in logs if e.get("event") == "taskv3 auto observe" and e.get("fired") is False]
- assert len(fires) == 1
- assert fires[0]["reason"] == "unchanged"
- assert fires[0]["wait_seconds"] >= 0.01
-
-
-async def test_auto_observe_fingerprint_unavailable_falls_back_to_probe(monkeypatch: pytest.MonkeyPatch) -> None:
- # A None reading from the fingerprint sampler (no page to sample, or a raising probe) is not
- # evidence either way, so the decision falls back to the document-identity probe instead of
- # defaulting to "unchanged".
- monkeypatch.setattr(loop_module, "AUTO_OBSERVE_SETTLE_INTERVAL_SECONDS", 0.0)
- from skyvern.forge.taskv3.loop import AUTO_OBSERVE_BEGIN
-
- clicks: list[tuple[str, dict[str, Any]]] = []
- observe_calls = {"n": 0}
-
- async def observe_handler(_args: dict[str, Any]) -> ToolResult:
- observe_calls["n"] += 1
- return ToolResult.ok(
- "url=x AUTO_DIGEST_MARKER (1 interactive elements)", data={"summary": {"invalid_fields": 0}}
- )
-
- async def unavailable_fingerprint() -> str | None:
- return None
-
- probe_values = iter(["url|nonce-1", "url|nonce-2"])
-
- async def changing_probe() -> str:
- return next(probe_values)
-
- tools = [
- _billable_tool("click", clicks),
- ToolSpec(
- name="observe",
- description="o",
- parameters={"type": "object", "properties": {}},
- handler=observe_handler,
- compactable=True,
- ),
- make_finish_tool(),
- ]
- script = [
- [("click", {"selector": "#toggle"})],
- [("finish", {"status": "completed", "reason": "ok"})],
- ]
- with capture_logs() as logs:
- outcome, _ = await _run(
- script,
- tools,
- auto_observe=True,
- page_probe=changing_probe,
- page_fingerprint=unavailable_fingerprint,
- )
-
- assert outcome.status == "completed"
- assert observe_calls["n"] == 1
- click_msgs = [m for m in outcome.messages if m.get("role") == "tool" and m.get("name") == "click"]
- assert AUTO_OBSERVE_BEGIN in click_msgs[0]["content"]
- fires = [e for e in logs if e.get("event") == "taskv3 auto observe" and e.get("fired") is True]
- assert len(fires) == 1
- assert fires[0]["reason"] == "probe_mismatch"
- assert fires[0]["signal"] == "probe"
-
-
-async def test_auto_observe_settle_wait_prefers_fingerprint_quiescence(monkeypatch: pytest.MonkeyPatch) -> None:
- # When both samplers are supplied, quiescence is driven by the fingerprint (rendered content),
- # not the document-identity probe -- settling asks "did the render finish", not "is this the
- # same document". The probe callable must never be invoked.
- from skyvern.forge.taskv3.loop import _auto_observe_settle_wait
-
- monkeypatch.setattr(loop_module, "AUTO_OBSERVE_SETTLE_INTERVAL_SECONDS", 0.01)
- monkeypatch.setattr(loop_module, "AUTO_OBSERVE_SETTLE_CAP_SECONDS", 1.0)
-
- fp_calls = {"n": 0}
- fp_values = ["rendering-1", "rendering-2", "settled", "settled"]
-
- async def fingerprint() -> str:
- fp_calls["n"] += 1
- return fp_values[min(fp_calls["n"] - 1, len(fp_values) - 1)]
-
- probe_calls = {"n": 0}
-
- async def probe_never_called() -> str:
- probe_calls["n"] += 1
- return "probe-value"
-
- waited = await _auto_observe_settle_wait(probe_never_called, None, None, page_fingerprint=fingerprint)
-
- assert waited > 0
- assert probe_calls["n"] == 0
- # Two equal consecutive samples ("settled", "settled") are what stopped the loop.
- assert fp_values[fp_calls["n"] - 2 : fp_calls["n"]] == ["settled", "settled"]
-
-
-async def test_auto_observe_skips_when_batch_already_observed(monkeypatch: pytest.MonkeyPatch) -> None:
- monkeypatch.setattr(loop_module, "AUTO_OBSERVE_SETTLE_INTERVAL_SECONDS", 0.0)
- clicks: list[tuple[str, dict[str, Any]]] = []
- observe_calls = {"n": 0}
-
- async def observe_handler(_args: dict[str, Any]) -> ToolResult:
- observe_calls["n"] += 1
- return ToolResult.ok("url=x MODEL_OBSERVE_DIGEST", data={"summary": {"invalid_fields": 0}})
-
- tools = [
- _billable_tool("click", clicks, data={"page_transitioned": True}),
- ToolSpec(
- name="observe",
- description="o",
- parameters={"type": "object", "properties": {}},
- handler=observe_handler,
- compactable=True,
- ),
- make_finish_tool(),
- ]
- script = [
- [("click", {"selector": "#next"}), ("observe", {})],
- [("finish", {"status": "completed", "reason": "ok"})],
- ]
- outcome, _ = await _run(script, tools, auto_observe=True)
-
- assert observe_calls["n"] == 1 # only the model's own call -- no extra auto-observe dispatch
- observe_msgs = [m for m in outcome.messages if m.get("role") == "tool" and m.get("name") == "observe"]
- assert len(observe_msgs) == 1
- assert "auto-observe" not in observe_msgs[0]["content"]
-
-
-async def test_auto_observe_fires_when_a_billable_action_follows_an_earlier_observe(
- monkeypatch: pytest.MonkeyPatch,
-) -> None:
- # batch_observed_ok tracks freshness, not batch membership: an observe early in the batch is
- # stale once a later billable call (here a page-transitioning click) has moved the page, so the
- # model's only snapshot predates the current state and auto-observe must still fire.
- monkeypatch.setattr(loop_module, "AUTO_OBSERVE_SETTLE_INTERVAL_SECONDS", 0.0)
- from skyvern.forge.taskv3.loop import AUTO_OBSERVE_BEGIN
-
- clicks: list[tuple[str, dict[str, Any]]] = []
- observe_calls = {"n": 0}
-
- async def observe_handler(_args: dict[str, Any]) -> ToolResult:
- observe_calls["n"] += 1
- return ToolResult.ok(
- "url=x AUTO_DIGEST_MARKER (1 interactive elements)", data={"summary": {"invalid_fields": 0}}
- )
-
- tools = [
- _billable_tool("click", clicks, data={"page_transitioned": True}),
- ToolSpec(
- name="observe",
- description="o",
- parameters={"type": "object", "properties": {}},
- handler=observe_handler,
- compactable=True,
- ),
- make_finish_tool(),
- ]
- script = [
- [("observe", {}), ("click", {"selector": "#next"})],
- [("finish", {"status": "completed", "reason": "ok"})],
- ]
- outcome, _ = await _run(script, tools, auto_observe=True)
-
- assert outcome.status == "completed"
- assert observe_calls["n"] == 2 # the model's observe, then the auto-observe dispatch
- click_msgs = [m for m in outcome.messages if m.get("role") == "tool" and m.get("name") == "click"]
- assert len(click_msgs) == 1
- assert AUTO_OBSERVE_BEGIN in click_msgs[0]["content"]
-
-
-async def test_auto_observe_fires_with_navigate_reason_after_a_successful_navigate(
- monkeypatch: pytest.MonkeyPatch,
-) -> None:
- # navigate is neither billable nor compactable, yet it changes what a later observe would
- # return -- a successful navigate must both (a) reset freshness like any non-perception call and
- # (b) flag the batch's change reason directly, the same way a hover does.
- monkeypatch.setattr(loop_module, "AUTO_OBSERVE_SETTLE_INTERVAL_SECONDS", 0.0)
- from skyvern.forge.taskv3.loop import AUTO_OBSERVE_BEGIN
-
- clicks: list[tuple[str, dict[str, Any]]] = []
- observe_calls = {"n": 0}
-
- async def observe_handler(_args: dict[str, Any]) -> ToolResult:
- observe_calls["n"] += 1
- return ToolResult.ok(
- "url=x AUTO_DIGEST_MARKER (1 interactive elements)", data={"summary": {"invalid_fields": 0}}
- )
-
- async def navigate_handler(_args: dict[str, Any]) -> ToolResult:
- return ToolResult.ok("navigated") # no page_state_changed flag -- isolates the navigate branch
-
- tools = [
- _billable_tool("click", clicks),
- ToolSpec(
- name="observe",
- description="o",
- parameters={"type": "object", "properties": {}},
- handler=observe_handler,
- compactable=True,
- ),
- ToolSpec(
- name="navigate", description="n", parameters={"type": "object", "properties": {}}, handler=navigate_handler
- ),
- make_finish_tool(),
- ]
- script = [
- [("click", {"selector": "#a"}), ("observe", {}), ("navigate", {"url": "https://example.test"})],
- [("finish", {"status": "completed", "reason": "ok"})],
- ]
- with capture_logs() as logs:
- outcome, _ = await _run(script, tools, auto_observe=True)
-
- assert outcome.status == "completed"
- assert observe_calls["n"] == 2 # the model's observe, then the auto-observe dispatch
- navigate_msgs = [m for m in outcome.messages if m.get("role") == "tool" and m.get("name") == "navigate"]
- assert AUTO_OBSERVE_BEGIN in navigate_msgs[0]["content"]
- fires = [e for e in logs if e.get("event") == "taskv3 auto observe" and e.get("fired") is True]
- assert len(fires) == 1
- assert fires[0]["reason"] == "navigate"
- assert fires[0]["signal"] == "flag"
-
-
-async def test_auto_observe_fires_after_scroll_resets_freshness_from_an_earlier_observe(
- monkeypatch: pytest.MonkeyPatch,
-) -> None:
- # scroll is neither billable nor compactable. Keying freshness off `billable` alone (the pre-fix
- # behavior) would leave batch_observed_ok True after [observe, scroll] and skip auto-observe
- # entirely; keying off `not compactable` resets it, so a fingerprint change after the scroll is
- # still caught.
- monkeypatch.setattr(loop_module, "AUTO_OBSERVE_SETTLE_INTERVAL_SECONDS", 0.0)
- from skyvern.forge.taskv3.loop import AUTO_OBSERVE_BEGIN
-
- clicks: list[tuple[str, dict[str, Any]]] = []
- observe_calls = {"n": 0}
-
- async def observe_handler(_args: dict[str, Any]) -> ToolResult:
- observe_calls["n"] += 1
- return ToolResult.ok(
- "url=x AUTO_DIGEST_MARKER (1 interactive elements)", data={"summary": {"invalid_fields": 0}}
- )
-
- async def scroll_handler(_args: dict[str, Any]) -> ToolResult:
- return ToolResult.ok("scrolled")
-
- fp_calls = {"n": 0}
-
- async def fingerprint() -> str:
- fp_calls["n"] += 1
- return f"v{fp_calls['n']}" # each sample differs -- before != after
-
- tools = [
- _billable_tool("click", clicks),
- ToolSpec(
- name="observe",
- description="o",
- parameters={"type": "object", "properties": {}},
- handler=observe_handler,
- compactable=True,
- ),
- ToolSpec(
- name="scroll", description="s", parameters={"type": "object", "properties": {}}, handler=scroll_handler
- ),
- make_finish_tool(),
- ]
- script = [
- [("click", {"selector": "#a"}), ("observe", {}), ("scroll", {"direction": "down"})],
- [("finish", {"status": "completed", "reason": "ok"})],
- ]
- outcome, _ = await _run(script, tools, auto_observe=True, page_fingerprint=fingerprint)
-
- assert outcome.status == "completed"
- assert observe_calls["n"] == 2 # the model's observe, then the auto-observe dispatch
- scroll_msgs = [m for m in outcome.messages if m.get("role") == "tool" and m.get("name") == "scroll"]
- assert AUTO_OBSERVE_BEGIN in scroll_msgs[0]["content"]
-
-
-async def test_auto_observe_fires_on_hover_despite_an_identical_fingerprint(monkeypatch: pytest.MonkeyPatch) -> None:
- # A hover-revealed submenu is CSS-only (:hover) -- it changes neither innerHTML nor document
- # identity, so both samplers read "unchanged". Hover's only purpose is to reveal, so a
- # successful hover dispatch must force the fire on its own, with reason "hover".
- monkeypatch.setattr(loop_module, "AUTO_OBSERVE_SETTLE_INTERVAL_SECONDS", 0.0)
- from skyvern.forge.taskv3.loop import AUTO_OBSERVE_BEGIN
-
- hovers: list[tuple[str, dict[str, Any]]] = []
- observe_calls = {"n": 0}
-
- async def observe_handler(_args: dict[str, Any]) -> ToolResult:
- observe_calls["n"] += 1
- return ToolResult.ok(
- "url=x AUTO_DIGEST_MARKER (1 interactive elements)", data={"summary": {"invalid_fields": 0}}
- )
-
- async def stable_probe() -> str:
- return "same-document"
-
- async def stable_fingerprint() -> str:
- return "same-markup"
-
- tools = [
- _billable_tool("hover", hovers), # no page_transitioned/page_state_changed flag
- ToolSpec(
- name="observe",
- description="o",
- parameters={"type": "object", "properties": {}},
- handler=observe_handler,
- compactable=True,
- ),
- make_finish_tool(),
- ]
- script = [
- [("hover", {"selector": "#menu"})],
- [("finish", {"status": "completed", "reason": "ok"})],
- ]
- with capture_logs() as logs:
- outcome, _ = await _run(
- script, tools, auto_observe=True, page_probe=stable_probe, page_fingerprint=stable_fingerprint
- )
-
- assert outcome.status == "completed"
- assert observe_calls["n"] == 1
- hover_msgs = [m for m in outcome.messages if m.get("role") == "tool" and m.get("name") == "hover"]
- assert AUTO_OBSERVE_BEGIN in hover_msgs[0]["content"]
- fires = [e for e in logs if e.get("event") == "taskv3 auto observe" and e.get("fired") is True]
- assert len(fires) == 1
- assert fires[0]["reason"] == "hover"
- assert fires[0]["signal"] == "flag"
-
-
-async def test_auto_observe_off_by_default_leaves_tool_messages_unchanged() -> None:
- clicks: list[tuple[str, dict[str, Any]]] = []
- tools = [_billable_tool("click", clicks, data={"page_transitioned": True}), make_finish_tool()]
- script = [
- [("click", {"selector": "#next"})],
- [("finish", {"status": "completed", "reason": "ok"})],
- ]
- outcome, _ = await _run(script, tools) # auto_observe defaults False
-
- click_msgs = [m for m in outcome.messages if m.get("role") == "tool" and m.get("name") == "click"]
- assert click_msgs[0]["content"] == "click done"
-
-
-async def test_auto_observe_perception_stall_never_terminates_but_logs_would_terminate(
- monkeypatch: pytest.MonkeyPatch,
-) -> None:
- # Auto-observe feeds the SAME perception ledger (action_key=("observe", "{}")) a model-issued
- # no-arg observe would -- for progress detection and the shadow/suppressed reporting -- but it is
- # a path the model never chose to take, so it must never be the thing that ends the run. This is
- # parity of DETECTION, not of action: the run must survive the whole script (bounded well above
- # PERCEPTION_STALL_TERMINATE_AFTER) while the would-terminate log still fires.
- monkeypatch.setattr(loop_module, "AUTO_OBSERVE_SETTLE_INTERVAL_SECONDS", 0.0)
- clicks: list[tuple[str, dict[str, Any]]] = []
- tools = [
- _billable_tool("click", clicks, data={"page_transitioned": True}),
- _perception_tool("observe", "url=x FROZEN (1 interactive elements)"),
- make_finish_tool(),
- ]
- script = [[("click", {"selector": f"#btn{i}"})] for i in range(20)]
- script.append([("finish", {"status": "completed", "reason": "done"})])
- with capture_logs() as logs:
- outcome, _ = await _run(script, tools, auto_observe=True, max_turns=30, max_tool_calls=200)
-
- assert outcome.status == "completed"
- assert len(clicks) == 20 # the full script ran -- auto-observe never cut it short
- assert not [e for e in logs if e.get("event") == "taskv3 loop perception stalled"]
- would_terminate = [e for e in logs if e.get("event") == "taskv3 auto observe stall would terminate"]
- # Fires once per round from the threshold onward (20 - PERCEPTION_STALL_TERMINATE_AFTER + 1 rounds).
- assert len(would_terminate) == 20 - PERCEPTION_STALL_TERMINATE_AFTER + 1
- assert would_terminate[0]["identical_count"] == PERCEPTION_STALL_TERMINATE_AFTER
-
-
-async def test_auto_snapshots_never_pad_a_model_observes_streak_toward_termination() -> None:
- # Regression for the reviewer's exact repro: auto snapshots and a model-issued no-arg observe key
- # on the SAME action_key (("observe", "{}")). If both fed one shared ledger, the two auto
- # snapshots below would pad the model observe's own streak from 2 to 4 and the model's SECOND
- # observe (can_terminate=True) would terminate the run on padding it never saw. Each path must
- # keep its own ledger so the interleaved sequence completes.
- clicks: list[tuple[str, dict[str, Any]]] = []
- tools = [
- _billable_tool("click", clicks, data={"page_transitioned": True}),
- _perception_tool("observe", "url=x FROZEN (1 interactive elements)"),
- make_finish_tool(),
- ]
- script = [
- [("click", {"selector": "#btn0"})], # auto snapshot #1
- [("observe", {})], # model observe #1
- [("click", {"selector": "#btn1"})], # auto snapshot #2 -- combined count would hit 4 here
- [("observe", {})], # model observe #2 -- the call that would wrongly terminate under the bug
- [("finish", {"status": "completed", "reason": "done"})],
- ]
- with capture_logs() as logs:
- outcome, _ = await _run(script, tools, auto_observe=True, stall_terminate_after=4, max_turns=30)
-
- assert outcome.status == "completed"
- assert len(clicks) == 2
- assert not [e for e in logs if e.get("event") == "taskv3 loop perception stalled"]
- # The would-terminate shadow log is a property of the AUTO ledger alone: with only two auto
- # snapshots recorded (below the threshold of 4), it must not fire either.
- assert not [e for e in logs if e.get("event") == "taskv3 auto observe stall would terminate"]
-
-
-async def test_auto_only_stall_would_terminate_log_fires_at_the_auto_ledgers_own_threshold() -> None:
- # Companion to the test above: once AUTO snapshots alone (with no model observes interleaved)
- # reach the threshold, the shadow "would terminate" log must still fire -- proving the separate
- # ledger did not also break auto-only stall detection.
- clicks: list[tuple[str, dict[str, Any]]] = []
- tools = [
- _billable_tool("click", clicks, data={"page_transitioned": True}),
- _perception_tool("observe", "url=x FROZEN (1 interactive elements)"),
- make_finish_tool(),
- ]
- script = [[("click", {"selector": f"#btn{i}"})] for i in range(4)]
- script.append([("finish", {"status": "completed", "reason": "done"})])
- with capture_logs() as logs:
- outcome, _ = await _run(script, tools, auto_observe=True, stall_terminate_after=4, max_turns=30)
-
- assert outcome.status == "completed"
- assert len(clicks) == 4
- would_terminate = [e for e in logs if e.get("event") == "taskv3 auto observe stall would terminate"]
- assert len(would_terminate) == 1
- assert would_terminate[0]["identical_count"] == 4
-
-
-async def test_model_only_perception_stall_still_terminates_at_the_configured_threshold() -> None:
- # The model-only path (auto_observe off) must keep terminating at the SAME threshold used above,
- # proving the ledger split did not weaken detection for the path the model actually chose.
- clicks: list[tuple[str, dict[str, Any]]] = []
- tools = [
- _billable_tool("click", clicks, data={"page_transitioned": True}),
- _perception_tool("observe", "url=x FROZEN (1 interactive elements)"),
- make_finish_tool(),
- ]
- script = [[("click", {"selector": f"#btn{i}"}), ("observe", {})] for i in range(10)]
- outcome, _ = await _run(script, tools, stall_terminate_after=4, max_turns=30)
-
- assert outcome.status == "terminated"
- assert outcome.reason.startswith(PERCEPTION_STALL_REASON_PREFIX)
- assert len(clicks) < 10
-
-
-async def test_model_observe_perception_stall_still_terminates_the_same_digest_sequence() -> None:
- # Same identical-digest shape as above, dispatched by the MODEL itself (auto_observe off): this
- # path must keep terminating, proving the change above is scoped to auto-observe's authority and
- # did not weaken the shared detection.
- clicks: list[tuple[str, dict[str, Any]]] = []
- tools = [
- _billable_tool("click", clicks, data={"page_transitioned": True}),
- _perception_tool("observe", "url=x FROZEN (1 interactive elements)"),
- make_finish_tool(),
- ]
- script = [[("click", {"selector": f"#btn{i}"}), ("observe", {})] for i in range(20)]
- outcome, caller = await _run(script, tools, max_turns=30, max_tool_calls=200)
-
- assert outcome.status == "terminated"
- assert outcome.reason.startswith(PERCEPTION_STALL_REASON_PREFIX)
- assert len(clicks) < 20 # bounded well below the full script
- assert caller.calls <= 20
-
-
-async def test_auto_observe_digest_carrier_is_the_non_compactable_action_not_get_html(
- monkeypatch: pytest.MonkeyPatch,
-) -> None:
- # A batch that ends with a compactable get_html call must not become the digest's carrier: that
- # message's own snapshot class ("get_html") would otherwise be misclassified as "observe" by the
- # marker it carries, and a later same-class supersession would only shave the marker span off
- # (leaving the large get_html body stuck in the transcript for the rest of the run). The carrier
- # must be the batch's last EXECUTED non-compactable call (the click), so the click's own text
- # survives a later elision while get_html is compacted normally.
- monkeypatch.setattr(loop_module, "AUTO_OBSERVE_SETTLE_INTERVAL_SECONDS", 0.0)
- from skyvern.forge.taskv3.loop import AUTO_OBSERVE_BEGIN
-
- clicks: list[tuple[str, dict[str, Any]]] = []
- observe_contents = ["AUTO_DIGEST_1 (1 interactive elements)", "OBSERVE_LATEST_2 (1 interactive elements)"]
- get_html_contents = ["HTML_DUMP_1 " + "a" * 300, "HTML_DUMP_2 " + "b" * 300]
-
- tools = [
- _billable_tool("click", clicks, data={"page_transitioned": True}),
- _perception_tool("get_html", get_html_contents),
- _perception_tool("observe", observe_contents),
- make_finish_tool(),
- ]
- script = [
- [("click", {"selector": "#next"}), ("get_html", {"selector": "#panel"})],
- [("observe", {}), ("get_html", {"selector": "#panel"})],
- [("finish", {"status": "completed", "reason": "ok"})],
- ]
- outcome, _ = await _run(script, tools, auto_observe=True)
-
- assert outcome.status == "completed"
- click_msgs = [m for m in outcome.messages if m.get("role") == "tool" and m.get("name") == "click"]
- get_html_msgs = [m for m in outcome.messages if m.get("role") == "tool" and m.get("name") == "get_html"]
- assert len(click_msgs) == 1
- assert len(get_html_msgs) == 2
-
- # The click survives as the carrier: its own text is intact, its digest span elided once superseded.
- assert click_msgs[0]["content"].startswith("click done")
- assert AUTO_OBSERVE_BEGIN not in click_msgs[0]["content"]
- assert "[superseded auto-observe output elided to bound context]" in click_msgs[0]["content"]
-
- # The first (superseded) get_html is fully elided under its OWN class -- proof it never carried the
- # digest marker (a marker-carrying message would report class "observe" in the placeholder instead).
- assert get_html_msgs[0]["content"] == "[superseded get_html output elided to bound context]"
- # The second (newest) get_html is untouched.
- assert get_html_msgs[1]["content"].startswith("HTML_DUMP_2")
-
-
-async def test_auto_observe_carrier_skips_a_batch_ending_skip_stub(monkeypatch: pytest.MonkeyPatch) -> None:
- # A batch whose LAST appended message is a skip stub (here: a stale mark=N after an in-batch look
- # renumbered the marks) must not become the digest's carrier -- the carrier is the last EXECUTED
- # non-compactable call, which precedes it in this batch.
- monkeypatch.setattr(loop_module, "AUTO_OBSERVE_SETTLE_INTERVAL_SECONDS", 0.0)
- from skyvern.forge.taskv3.loop import AUTO_OBSERVE_BEGIN
-
- clicks: list[tuple[str, dict[str, Any]]] = []
-
- async def look_handler(_args: dict[str, Any]) -> ToolResult:
- return ToolResult.ok("look done", data={"marks_renumbered": True})
-
- async def observe_handler(_args: dict[str, Any]) -> ToolResult:
- return ToolResult.ok("AUTO_DIGEST (1 interactive elements)", data={"summary": {"invalid_fields": 0}})
-
- tools = [
- _billable_tool("click", clicks, data={"page_transitioned": True}),
- ToolSpec(
- name="look",
- description="look",
- parameters={"type": "object", "properties": {}},
- handler=look_handler,
- compactable=True,
- ),
- ToolSpec(
- name="observe",
- description="observe",
- parameters={"type": "object", "properties": {}},
- handler=observe_handler,
- compactable=True,
- ),
- make_finish_tool(),
- ]
- script = [
- [("click", {"selector": "#next"}), ("look", {}), ("click", {"mark": 5})],
- [("finish", {"status": "completed", "reason": "ok"})],
- ]
- outcome, _ = await _run(script, tools, auto_observe=True)
-
- assert outcome.status == "completed"
- click_msgs = [m for m in outcome.messages if m.get("role") == "tool" and m.get("name") == "click"]
- assert len(click_msgs) == 2
- executed_click, skipped_click = click_msgs
- assert executed_click["content"].startswith("click done")
- assert AUTO_OBSERVE_BEGIN in executed_click["content"]
- assert skipped_click["content"].startswith("skipped:")
- assert AUTO_OBSERVE_BEGIN not in skipped_click["content"]
-
-
-async def test_auto_observe_skips_dispatch_when_canceled_during_settle_wait(monkeypatch: pytest.MonkeyPatch) -> None:
- # Cancellation signaled while waiting for the page to settle must stop the observe handler from
- # ever being invoked, and the run must end canceled rather than completing on a stale digest.
- monkeypatch.setattr(loop_module, "AUTO_OBSERVE_SETTLE_INTERVAL_SECONDS", 0.0)
- clicks: list[tuple[str, dict[str, Any]]] = []
- observe_calls = {"n": 0}
-
- async def observe_handler(_args: dict[str, Any]) -> ToolResult:
- observe_calls["n"] += 1
- return ToolResult.ok("should never be dispatched")
-
- cancel_calls = {"n": 0}
-
- async def should_cancel() -> bool:
- cancel_calls["n"] += 1
- # False for the loop's own top-of-turn and per-call checks; True from the auto-observe path's
- # post-settle-wait re-check onward.
- return cancel_calls["n"] > 2
-
- tools = [
- _billable_tool("click", clicks, data={"page_transitioned": True}),
- ToolSpec(
- name="observe",
- description="observe",
- parameters={"type": "object", "properties": {}},
- handler=observe_handler,
- compactable=True,
- ),
- make_finish_tool(),
- ]
- script = [
- [("click", {"selector": "#next"})],
- [("finish", {"status": "completed", "reason": "ok"})],
- ]
- with capture_logs() as logs:
- outcome, _ = await _run(script, tools, auto_observe=True, should_cancel=should_cancel)
-
- assert outcome.status == "canceled"
- assert observe_calls["n"] == 0
- fires = [e for e in logs if e.get("event") == "taskv3 auto observe"]
- assert any(f.get("fired") is False and f.get("reason") == "canceled" for f in fires)
-
-
-async def test_auto_observe_settle_wait_bounds_a_slow_probe(monkeypatch: pytest.MonkeyPatch) -> None:
- # The clock starts before the first probe sample, so a probe slower than the cap still bounds the
- # total wait (to roughly the cap plus that one probe's own duration, not an unbounded pile-up of
- # further probes), and the wait never outlives an explicit deadline_at.
- from skyvern.forge.taskv3.loop import _auto_observe_settle_wait
-
- monkeypatch.setattr(loop_module, "AUTO_OBSERVE_SETTLE_INTERVAL_SECONDS", 0.05)
- monkeypatch.setattr(loop_module, "AUTO_OBSERVE_SETTLE_CAP_SECONDS", 0.1)
-
- probe_calls = {"n": 0}
-
- async def slow_probe() -> str:
- probe_calls["n"] += 1
- await asyncio.sleep(0.3) # much longer than the settle cap itself
- return f"state-{probe_calls['n']}"
-
- started = time.monotonic()
- waited = await _auto_observe_settle_wait(slow_probe, None, None)
- elapsed = time.monotonic() - started
-
- assert probe_calls["n"] == 1 # the cap trips before a second slow probe is ever dispatched
- assert waited <= 0.1 + 0.3 + 0.2 # cap + one probe duration, with slack for scheduling jitter
- assert elapsed <= 0.1 + 0.3 + 0.2
- assert waited == pytest.approx(elapsed, abs=0.05) # the returned value is the real elapsed time
-
- probe_calls["n"] = 0
- deadline_at = time.monotonic() + 0.02 # tighter than the probe's own duration
- waited2 = await _auto_observe_settle_wait(slow_probe, None, deadline_at)
-
- assert probe_calls["n"] == 1
- assert waited2 <= 0.02 + 0.2 # the first sample is cut at the deadline too, not run to completion
-
-
-def test_compact_transcript_elides_superseded_auto_observe_span_only() -> None:
- # A carrier message (a click's own confirmation with an appended auto-observe digest) is grouped
- # into the same "observe" supersession class as a real observe result; once a NEWER observe-class
- # snapshot lands, only the marker span is elided -- the click's own text must survive.
- from skyvern.forge.taskv3.loop import AUTO_OBSERVE_BEGIN, AUTO_OBSERVE_END, _compact_transcript
-
- carrier_content = (
- "clicked #submit — now at https://example.test/next\n\n"
- + AUTO_OBSERVE_BEGIN
- + "[auto-observe after this batch — page changed]\n"
- + "url=x AUTO_DIGEST "
- + "a" * 200
- + AUTO_OBSERVE_END
- )
- messages = [
- _assistant_turn("c"), # round 1: the auto-observe carrier (now superseded)
- _tool_msg("c", "click", carrier_content), # idx 1
- _assistant_turn("o"), # round 2 (latest): a real model observe
- _tool_msg("o", "observe", "OBSERVE_LATEST " + "z" * 300), # idx 3
- ]
- snapshots = {1, 3}
- auto_carriers = {1} # the loop's own record of which index it appended a digest to
- _compact_transcript(messages, snapshots, auto_carriers)
-
- assert messages[1]["content"].startswith("clicked #submit — now at https://example.test/next")
- assert "[superseded auto-observe output elided to bound context]" in messages[1]["content"]
- assert AUTO_OBSERVE_BEGIN not in messages[1]["content"]
- assert AUTO_OBSERVE_END not in messages[1]["content"]
- assert messages[3]["content"].startswith("OBSERVE_LATEST") # newest kept intact
- assert snapshots == {3}
- assert auto_carriers == set() # discarded alongside snapshot_indices once elided
-
-
-def test_neutralize_auto_observe_markers_breaks_verbatim_delimiters() -> None:
- # SKY-15056 round-4 H3: page-controlled digest text can contain the literal delimiters the loop
- # uses to wrap an auto-observe digest. Neutralizing them before wrapping is what keeps the
- # non-greedy compaction regex from matching a forged boundary INSIDE the digest instead of the
- # real one the loop appended.
- from skyvern.forge.taskv3.loop import AUTO_OBSERVE_BEGIN, AUTO_OBSERVE_END, _neutralize_auto_observe_markers
-
- digest = f"page text says: {AUTO_OBSERVE_BEGIN} then later {AUTO_OBSERVE_END} verbatim"
- neutralized = _neutralize_auto_observe_markers(digest)
-
- assert AUTO_OBSERVE_BEGIN not in neutralized
- assert AUTO_OBSERVE_END not in neutralized
- # Readable, not corrupted -- just no longer an exact delimiter match.
- assert "auto-observe" in neutralized
-
-
[email protected]("auto_observe", [False, True])
-async def test_click_result_with_literal_markers_is_never_classified_as_a_carrier(
- auto_observe: bool, monkeypatch: pytest.MonkeyPatch
-) -> None:
- # SKY-15056 exhaustive audit, corrected design: a carrier is identified by auto_carrier_indices
- # (the loop's own record of which index it appended a digest to), never by sniffing message
- # content for AUTO_OBSERVE_BEGIN/END. Ordinary tool results are NOT neutralized -- doing so would
- # rewrite page text on every run regardless of auto_observe, breaking byte-identity for the
- # (far more common) flag-off path. So an ordinary click result whose OWN page-controlled text
- # happens to contain the literal delimiters (e.g. echoing an element's label) must survive
- # completely untouched, in EITHER auto_observe posture, and must never be swept into the
- # "observe" supersession class merely because its raw text looks like a carrier.
- monkeypatch.setattr(loop_module, "AUTO_OBSERVE_SETTLE_INTERVAL_SECONDS", 0.0)
- from skyvern.forge.taskv3.loop import AUTO_OBSERVE_BEGIN, AUTO_OBSERVE_END
-
- forged_text = f"clicked #decoy — label was '{AUTO_OBSERVE_BEGIN}fake span{AUTO_OBSERVE_END}'"
- calls = {"n": 0}
-
- async def click_handler(_args: dict[str, Any]) -> ToolResult:
- calls["n"] += 1
- if calls["n"] == 1:
- # No page_transitioned/page_state_changed flag: this call never arms a genuine
- # auto-observe append, so the forged markers are the ONLY thing that could (incorrectly)
- # make this message read as a carrier.
- return ToolResult.ok(forged_text)
- return ToolResult.ok(f"click {calls['n']} done", data={"page_transitioned": True})
-
- tools = [
- ToolSpec(
- name="click",
- description="click",
- parameters={"type": "object", "properties": {}},
- handler=click_handler,
- billable=True,
- ),
- _perception_tool("observe", "url=x page state " + "z" * 100),
- make_finish_tool(),
- ]
- script = [
- [("click", {"selector": "#decoy"})],
- [("click", {"selector": "#b"})],
- [("click", {"selector": "#c"})],
- [("finish", {"status": "completed", "reason": "ok"})],
- ]
- outcome, _ = await _run(script, tools, auto_observe=auto_observe, max_turns=10, max_tool_calls=50)
-
- assert outcome.status == "completed"
- click_msgs = [m for m in outcome.messages if m.get("role") == "tool" and m.get("name") == "click"]
- assert len(click_msgs) == 3
- decoy_content = click_msgs[0]["content"]
- # Byte-identical to the tool's own return: never neutralized, never elided (whole-message or
- # marker-span), never touched at all -- it was never added to snapshot_indices in the first
- # place, so compaction never even considers it a candidate.
- assert "[superseded" not in decoy_content
- assert decoy_content.count(AUTO_OBSERVE_BEGIN) == 1
- assert decoy_content.count(AUTO_OBSERVE_END) == 1
- if auto_observe:
- # A legitimate, unrelated pre-existing suffix ("no markup change") may follow -- this batch's
- # click carried no page-change signal -- but the forged text itself is an untouched prefix.
- assert decoy_content.startswith(forged_text)
- else:
- assert decoy_content == forged_text
-
- if auto_observe:
- # Meanwhile the REAL carriers (turns 2 and 3, which DID signal page_transitioned) still work
- # normally: the older one is superseded and marker-span-elided once the newer one lands.
- assert "[superseded auto-observe output elided to bound context]" in click_msgs[1]["content"]
- assert AUTO_OBSERVE_BEGIN not in click_msgs[1]["content"]
- assert AUTO_OBSERVE_BEGIN in click_msgs[2]["content"] # newest carrier kept intact
-
-
-async def test_auto_observe_digest_containing_verbatim_markers_wraps_with_exactly_one_pair() -> None:
- # End-to-end version of the unit test above: a hostile page whose rendered text happens to
- # contain the literal BEGIN/END delimiters must not be able to forge a second span boundary once
- # the loop appends its own real one.
- from skyvern.forge.taskv3.loop import AUTO_OBSERVE_BEGIN, AUTO_OBSERVE_END
-
- clicks: list[tuple[str, dict[str, Any]]] = []
- adversarial_digest = f"url=x text: 'click {AUTO_OBSERVE_BEGIN} here {AUTO_OBSERVE_END} to continue'"
- tools = [
- _billable_tool("click", clicks, data={"page_transitioned": True}),
- _perception_tool("observe", adversarial_digest),
- make_finish_tool(),
- ]
- script = [
- [("click", {"selector": "#next"})],
- [("finish", {"status": "completed", "reason": "ok"})],
- ]
- outcome, _ = await _run(script, tools, auto_observe=True)
-
- assert outcome.status == "completed"
- click_msgs = [m for m in outcome.messages if m.get("role") == "tool" and m.get("name") == "click"]
- assert len(click_msgs) == 1
- content = click_msgs[0]["content"]
- assert content.count(AUTO_OBSERVE_BEGIN) == 1
- assert content.count(AUTO_OBSERVE_END) == 1
-
-
-def test_compaction_fully_elides_an_auto_observe_span_whose_digest_contained_markers() -> None:
- # Companion to the wrap-time test above: once neutralized at wrap time, a digest that USED to
- # contain a verbatim END delimiter can no longer end the non-greedy compaction span early -- the
- # whole appended block is elided and only the carrier's own text plus the elision notice remain.
- from skyvern.forge.taskv3.loop import (
- AUTO_OBSERVE_BEGIN,
- AUTO_OBSERVE_END,
- _compact_transcript,
- _neutralize_auto_observe_markers,
- )
-
- adversarial_digest = f"url=x text: 'click {AUTO_OBSERVE_BEGIN} here {AUTO_OBSERVE_END} to continue'"
- carrier_content = (
- "clicked #next — now at https://example.test/next\n\n"
- + AUTO_OBSERVE_BEGIN
- + "[auto-observe after this batch — page changed]\n"
- + _neutralize_auto_observe_markers(adversarial_digest)
- + AUTO_OBSERVE_END
- )
- messages = [
- _assistant_turn("c"), # round 1: the auto-observe carrier (now superseded)
- _tool_msg("c", "click", carrier_content), # idx 1
- _assistant_turn("o"), # round 2 (latest): a real model observe
- _tool_msg("o", "observe", "OBSERVE_LATEST " + "z" * 300), # idx 3
- ]
- snapshots = {1, 3}
- _compact_transcript(messages, snapshots, {1})
-
- assert messages[1]["content"] == (
- "clicked #next — now at https://example.test/next\n\n[superseded auto-observe output elided to bound context]"
- )
- assert AUTO_OBSERVE_BEGIN not in messages[1]["content"]
- assert AUTO_OBSERVE_END not in messages[1]["content"]
-
-
-async def test_auto_observe_after_a_mid_batch_refresh_samples_the_reloaded_page_once(
- monkeypatch: pytest.MonkeyPatch,
-) -> None:
- # Coexistence of #16265's refresh signal and SKY-15056's auto-observe: the refresh path itself
- # never calls observe (only reloads), so if auto-observe fires afterward it must be the ONLY
- # observe dispatched, and it must sample the page probe/handler AFTER the reload -- not a stale
- # pre-refresh reading. The refresh's perception.reset() must also not leave a stall verdict primed
- # for auto-observe's own (first-ever) snapshot.
- monkeypatch.setattr(loop_module, "AUTO_OBSERVE_SETTLE_INTERVAL_SECONDS", 0.0)
- from skyvern.forge.taskv3.loop import AUTO_OBSERVE_BEGIN
-
- probe_state = {"nonce": "before"}
-
- async def page_probe() -> str | None:
- return probe_state["nonce"]
-
- async def reload_page() -> None:
- probe_state["nonce"] = "after"
-
- click_calls: list[tuple[str, dict[str, Any]]] = []
- observe_calls = {"n": 0}
-
- async def observe_handler(_args: dict[str, Any]) -> ToolResult:
- observe_calls["n"] += 1
- return ToolResult.ok(f"url=x nonce={probe_state['nonce']} (1 interactive elements)")
-
- tools = [
- _refresh_signaling_click(click_calls),
- ToolSpec(
- name="observe",
- description="o",
- parameters={"type": "object", "properties": {}},
- handler=observe_handler,
- compactable=True,
- ),
- make_finish_tool(),
- ]
- script: list[list[tuple[str, dict[str, Any]]]] = [
- [("click", {"selector": "#submit"})],
- [("finish", {"status": "completed", "reason": "done"})],
- ]
-
- ctx = SkyvernContext(task_id="tsk_refresh_and_auto_observe")
- skyvern_context.set(ctx)
- try:
- outcome, _ = await _run(script, tools, reload_page=reload_page, page_probe=page_probe, auto_observe=True)
- finally:
- skyvern_context.reset()
-
- assert outcome.status == "completed"
- # Exactly one observe dispatched: the refresh path only reloads, auto-observe supplies the look.
- assert observe_calls["n"] == 1
- click_msgs = [m for m in outcome.messages if m.get("role") == "tool" and m.get("name") == "click"]
- assert len(click_msgs) == 1
- assert AUTO_OBSERVE_BEGIN in click_msgs[0]["content"]
- # The digest was sampled AFTER the reload, not the stale pre-refresh reading.
- assert "nonce=after" in click_msgs[0]["content"]
-
-
-async def test_auto_observe_skips_entirely_once_the_deadline_has_already_passed() -> None:
- # SKY-15056 round-3 G1: the deadline must be honored at batch END, not just around sleeps -- a
- # batch whose own dispatch ate the whole deadline must not sample a probe or dispatch observe.
- probe_calls = {"n": 0}
-
- async def page_probe() -> str:
- probe_calls["n"] += 1
- return "state"
-
- observe_calls = {"n": 0}
-
- async def observe_handler(_args: dict[str, Any]) -> ToolResult:
- observe_calls["n"] += 1
- return ToolResult.ok("should never be dispatched")
-
- async def slow_click(_args: dict[str, Any]) -> ToolResult:
- await asyncio.sleep(0.15) # eats the whole deadline before the batch even finishes
- return ToolResult.ok("click done")
-
- tools = [
- ToolSpec(
- name="click",
- description="click",
- parameters={"type": "object", "properties": {}},
- handler=slow_click,
- billable=True,
- ),
- ToolSpec(
- name="observe",
- description="observe",
- parameters={"type": "object", "properties": {}},
- handler=observe_handler,
- compactable=True,
- ),
- make_finish_tool(),
- ]
- script = [
- [("click", {"selector": "#next"})],
- [("finish", {"status": "completed", "reason": "ok"})],
- ]
- with capture_logs() as logs:
- outcome, _ = await _run(script, tools, auto_observe=True, page_probe=page_probe, deadline_seconds=0.1)
-
- assert outcome.status == "budget_exhausted" # the deadline is gone before a second turn can start
- # 2 pre-dispatch samples (the batch baseline, plus the per-call pre-dispatch poisoning check) --
- # neither is part of the auto-observe path this fix covers. None sampled AFTER the batch.
- assert probe_calls["n"] == 2
- assert observe_calls["n"] == 0
- fires = [e for e in logs if e.get("event") == "taskv3 auto observe"]
- assert any(f.get("fired") is False and f.get("reason") == "deadline" for f in fires)
-
-
-async def test_auto_observe_bounds_a_hanging_sampler_to_the_remaining_deadline() -> None:
- # SKY-15056 round-3 G1: a probe slower than what's left of the deadline must be cut off near the
- # deadline (not run to completion), and once the deadline is gone the observe handler must never
- # be dispatched.
- probe_calls = {"n": 0}
-
- async def page_probe() -> str | None:
- probe_calls["n"] += 1
- # The first 2 calls are pre-dispatch (the batch baseline, then the per-call poisoning-check
- # sample) and read fast; only the 3rd call -- the auto-observe path's own post-batch sample
- # -- is the slow one this fix must bound.
- if probe_calls["n"] <= 2:
- return "before"
- await asyncio.sleep(2.0) # far longer than what's left of the deadline
- return "after"
-
- observe_calls = {"n": 0}
-
- async def observe_handler(_args: dict[str, Any]) -> ToolResult:
- observe_calls["n"] += 1
- return ToolResult.ok("should never be dispatched")
-
- async def click_handler(_args: dict[str, Any]) -> ToolResult:
- await asyncio.sleep(0.1) # leaves ~0.05s of the deadline for the post-batch sample
- return ToolResult.ok("click done")
-
- tools = [
- ToolSpec(
- name="click",
- description="click",
- parameters={"type": "object", "properties": {}},
- handler=click_handler,
- billable=True,
- ),
- ToolSpec(
- name="observe",
- description="observe",
- parameters={"type": "object", "properties": {}},
- handler=observe_handler,
- compactable=True,
- ),
- make_finish_tool(),
- ]
- script = [
- [("click", {"selector": "#next"})],
- [("finish", {"status": "completed", "reason": "ok"})],
- ]
- with capture_logs() as logs:
- started = time.monotonic()
- outcome, _ = await _run(script, tools, auto_observe=True, page_probe=page_probe, deadline_seconds=0.15)
- elapsed = time.monotonic() - started
-
- assert outcome.status == "budget_exhausted"
- assert observe_calls["n"] == 0
- assert probe_calls["n"] == 3 # 2 fast pre-dispatch samples, plus one bounded (cut-off) post-batch sample
- # Nowhere near the probe's own 2s sleep -- proves the sampler was cut off near the deadline
- # instead of being allowed to run to completion.
- assert elapsed <= 1.0
- fires = [e for e in logs if e.get("event") == "taskv3 auto observe"]
- assert any(f.get("fired") is False and f.get("reason") == "deadline" for f in fires)
-
-
-async def test_auto_observe_pre_batch_fingerprint_sample_is_bounded_by_an_already_elapsed_deadline() -> None:
- # SKY-15056 round-4 H2: the PRE-batch samples auto-observe takes before dispatching a batch
- # (batch_probe_before / batch_fp_before) omitted deadline_at, so a hanging sampler there could run
- # the full 10s probe timeout even though the run's own deadline was already gone -- a slow LLM
- # call is enough to burn the whole deadline in the gap between the top-of-turn check and here. A
- # hanging fingerprint sampler must not be awaited once the deadline has already elapsed.
- fp_calls = {"n": 0}
-
- async def hanging_fingerprint() -> str | None:
- fp_calls["n"] += 1
- await asyncio.sleep(5.0)
- return "fp"
-
- async def click_handler(_args: dict[str, Any]) -> ToolResult:
- return ToolResult.ok("click done")
-
- async def observe_handler(_args: dict[str, Any]) -> ToolResult:
- return ToolResult.ok("should never be dispatched")
-
- tools = [
- ToolSpec(
- name="click",
- description="click",
- parameters={"type": "object", "properties": {}},
- handler=click_handler,
- billable=True,
- ),
- ToolSpec(
- name="observe",
- description="observe",
- parameters={"type": "object", "properties": {}},
- handler=observe_handler,
- compactable=True,
- ),
- make_finish_tool(),
- ]
-
- class _SlowFirstCallCaller(_ScriptedCaller):
- async def call(self, **kwargs: Any) -> dict[str, Any]:
- if self.calls == 0:
- await asyncio.sleep(0.2) # eats the whole deadline before this turn's batch dispatches
- return await super().call(**kwargs)
-
- caller = _SlowFirstCallCaller(
- [[("click", {"selector": "#next"})], [("finish", {"status": "completed", "reason": "ok"})]]
- )
- started = time.monotonic()
- outcome = await run_agent_tool_loop(
- llm_caller=caller,
- system_prompt="sys",
- user_prompt="goal",
- tools=tools,
- max_turns=20,
- max_tool_calls=100,
- auto_observe=True,
- page_fingerprint=hanging_fingerprint,
- deadline_seconds=0.05,
- )
- elapsed = time.monotonic() - started
-
- assert outcome.status == "budget_exhausted"
- assert fp_calls["n"] == 0 # deadline already gone -- the hanging sampler was never awaited
- assert elapsed <= 0.3
-
-
-async def test_auto_observe_handler_hang_past_deadline_is_cut_off_and_loop_continues(
- monkeypatch: pytest.MonkeyPatch,
-) -> None:
- # SKY-15056 round-3 G1: once the page-changed detection and settle wait leave a sliver of
- # deadline, the observe HANDLER dispatch itself must still be bounded to what's left -- a hung
- # handler must not be able to block past the loop's own deadline.
- monkeypatch.setattr(loop_module, "AUTO_OBSERVE_SETTLE_INTERVAL_SECONDS", 0.0)
- observe_calls = {"n": 0}
-
- async def observe_handler(_args: dict[str, Any]) -> ToolResult:
- observe_calls["n"] += 1
- await asyncio.sleep(2.0) # far longer than what's left of the deadline
- return ToolResult.ok("should never land")
-
- clicks: list[tuple[str, dict[str, Any]]] = []
- tools = [
- _billable_tool("click", clicks, data={"page_transitioned": True}), # page_changed via "flag" -- no sampler
- ToolSpec(
- name="observe",
- description="observe",
- parameters={"type": "object", "properties": {}},
- handler=observe_handler,
- compactable=True,
- ),
- make_finish_tool(),
- ]
- script = [
- [("click", {"selector": "#next"})],
- [("finish", {"status": "completed", "reason": "ok"})],
- ]
- with capture_logs() as logs:
- started = time.monotonic()
- outcome, _ = await _run(script, tools, auto_observe=True, deadline_seconds=0.08)
- elapsed = time.monotonic() - started
-
- # Nowhere near the handler's own 2s sleep -- proves the dispatch was cut off, not left to hang.
- assert elapsed <= 1.0
- assert outcome.status in ("completed", "budget_exhausted")
- fires = [e for e in logs if e.get("event") == "taskv3 auto observe"]
- assert any(f.get("fired") is False and f.get("reason") in ("error", "deadline") for f in fires)
-
-
-async def test_auto_observe_dispatch_duration_counts_toward_tool_seconds() -> None:
- # SKY-15056 round-3 G2: the auto-observe handler IS a tool call, just one the loop issues instead
- # of the model -- its wall-clock must land in tool_seconds like every model-dispatched call does.
- clicks: list[tuple[str, dict[str, Any]]] = []
-
- async def observe_handler(_args: dict[str, Any]) -> ToolResult:
- await asyncio.sleep(0.05)
- return ToolResult.ok("url=x (1 interactive elements)")
-
- tools = [
- _billable_tool("click", clicks, data={"page_transitioned": True}),
- ToolSpec(
- name="observe",
- description="observe",
- parameters={"type": "object", "properties": {}},
- handler=observe_handler,
- compactable=True,
- ),
- make_finish_tool(),
- ]
- script = [
- [("click", {"selector": "#next"})],
- [("finish", {"status": "completed", "reason": "ok"})],
- ]
- outcome, _ = await _run(script, tools, auto_observe=True)
-
- assert outcome.status == "completed"
- assert outcome.tool_seconds >= 0.05
-
-
-async def test_auto_observe_repeated_identical_snapshots_never_arm_perception_stall_imminent(
- monkeypatch: pytest.MonkeyPatch,
-) -> None:
- # SKY-15056 round-3 G3: auto-observe's own stall detection (can_terminate=False) must not arm
- # activity.perception_stall_imminent -- that flag suppresses the failure-evidence retry gate for
- # a LATER model-issued submit failure, and auto-observe is a path the model never chose to take.
- monkeypatch.setattr(loop_module, "AUTO_OBSERVE_SETTLE_INTERVAL_SECONDS", 0.0)
- clicks: list[tuple[str, dict[str, Any]]] = []
- tools = [
- _billable_tool("click", clicks, data={"page_transitioned": True}),
- _perception_tool("observe", "url=x FROZEN (1 interactive elements)"),
- make_finish_tool(),
- ]
- script = [[("click", {"selector": f"#btn{i}"})] for i in range(20)]
- script.append([("finish", {"status": "completed", "reason": "done"})])
- activity = ActivityRecency()
- outcome, _ = await _run(script, tools, auto_observe=True, activity=activity, max_turns=30, max_tool_calls=200)
-
- assert outcome.status == "completed"
- assert activity.perception_stall_imminent is False
-
-
-async def test_model_observe_repeated_identical_snapshots_arms_perception_stall_imminent() -> None:
- # Same identical-digest shape, dispatched by the MODEL itself (auto_observe off): can_terminate
- # stays True there, so the flag must still arm -- proving G3's gate is scoped to auto-observe.
- clicks: list[tuple[str, dict[str, Any]]] = []
- tools = [
- _billable_tool("click", clicks, data={"page_transitioned": True}),
- _perception_tool("observe", "url=x FROZEN (1 interactive elements)"),
- make_finish_tool(),
- ]
- script = [[("click", {"selector": f"#btn{i}"}), ("observe", {})] for i in range(20)]
- activity = ActivityRecency()
- outcome, _ = await _run(script, tools, activity=activity, max_turns=30, max_tool_calls=200)
-
- assert outcome.status == "terminated"
- assert activity.perception_stall_imminent is True
-
-
-async def test_auto_observe_stall_nudge_folds_into_the_same_nudge_message_as_a_model_stall_nudge() -> None:
- # SKY-15056 round-3 G4: auto-observe's own stall nudge (the ("observe", "{}") ledger) must not
- # land as a SECOND consecutive `role: user` message after a model-issued stall nudge (a DIFFERENT
- # tool's ledger, get_html, crossing the same threshold the same turn) -- both belong in the one
- # nudge message a turn is allowed, so roles keep alternating.
- clicks: list[tuple[str, dict[str, Any]]] = []
- tools = [
- _billable_tool("click", clicks, data={"page_transitioned": True}), # page always "changes" -> flag
- _perception_tool("get_html", "identical html"), # model-issued perception tool, own ledger key
- _perception_tool("observe", "url=x FROZEN (1 interactive elements)"), # auto-observe's ledger key
- make_finish_tool(),
- ]
- # Every turn: model calls get_html (compactable -- its own stall counter) then a page-changing
- # click (a fresh selector each turn so the UNRELATED action-repeat guard never trips); auto-observe
- # fires right after on the identical "observe" digest, incrementing its OWN ("observe", "{}")
- # counter in lockstep, one read per turn, starting together on turn 1 -- so both cross
- # PERCEPTION_STALL_NUDGE_AFTER on the exact same turn.
- script = [[("get_html", {}), ("click", {"selector": f"#step{i}"})] for i in range(PERCEPTION_STALL_NUDGE_AFTER)]
- script.append([("finish", {"status": "completed", "reason": "done"})])
- outcome, _ = await _run(script, tools, auto_observe=True, max_turns=30, max_tool_calls=200)
-
- assert outcome.status == "completed"
- user_messages = [m.get("content", "") for m in outcome.messages if m.get("role") == "user"]
- combined = [c for c in user_messages if "get_html" in c and "observe" in c]
- assert combined, f"expected one user message naming both stalled tools, got: {user_messages}"
- # Roles keep alternating -- no two consecutive `role: user` entries anywhere in the transcript.
- for idx, message in enumerate(outcome.messages):
- if message.get("role") == "user" and idx > 0:
- assert outcome.messages[idx - 1].get("role") != "user"
-
-
-async def test_auto_observe_progress_clears_action_repeat_guard_across_a_multi_page_wizard() -> None:
- # SKY-15056 round-5 K1: a multi-page wizard clicking the SAME "#next" selector on every page must
- # not accrue the model-issued action-repeat guard's counters just because page_transitioned alone
- # (deliberately) never clears them -- auto-observe's OWN progressed snapshot must, even though
- # auto-observe can never terminate the run itself (can_terminate=False).
- clicks: list[tuple[str, dict[str, Any]]] = []
- digests = [f"url=page{i} (1 interactive elements)" for i in range(8)]
- tools = [
- _billable_tool("click", clicks, data={"page_transitioned": True}),
- _perception_tool("observe", digests),
- make_finish_tool(),
- ]
- script: list[list[tuple[str, dict[str, Any]]]] = [[("click", {"selector": "#next"})] for _ in range(7)]
- script.append([("finish", {"status": "completed", "reason": "done"})])
- outcome, _ = await _run(
- script,
- tools,
- auto_observe=True,
- action_nudge_after=3,
- action_terminate_after=6,
- max_turns=30,
- max_tool_calls=200,
- )
-
- assert outcome.status == "completed"
- assert len(clicks) == 7
- nudge_msgs = [m for m in outcome.messages if m.get("role") == "user" and "#next" in str(m.get("content"))]
- assert nudge_msgs == []
-
-
-async def test_auto_observe_unchanged_digest_leaves_action_repeat_guard_terminating_as_today() -> None:
- # SKY-15056 round-5 K1 negative: an UNCHANGED auto-observe digest must not clear the model-issued
- # action-repeat guard -- the fix clears on PROGRESS, not merely because auto-observe ran, so the
- # existing repeat guard still nudges and terminates exactly as it did before the fix.
- clicks: list[tuple[str, dict[str, Any]]] = []
- tools = [
- _billable_tool("click", clicks, data={"page_transitioned": True}),
- _perception_tool("observe", "url=x FROZEN (1 interactive elements)"),
- make_finish_tool(),
- ]
- script: list[list[tuple[str, dict[str, Any]]]] = [[("click", {"selector": "#next"})] for _ in range(8)]
- outcome, _ = await _run(
- script,
- tools,
- auto_observe=True,
- action_nudge_after=3,
- action_terminate_after=6,
- max_turns=30,
- max_tool_calls=200,
- )
-
- assert outcome.status == "terminated"
- assert outcome.reason.startswith(ACTION_LOOP_REASON_PREFIX)
- assert len(clicks) == 6
-
-
-async def test_auto_observe_consumes_a_refresh_signal_the_observe_handler_raises(
- monkeypatch: pytest.MonkeyPatch,
-) -> None:
- # SKY-15056 round-5 K2: the injected (auto) observe call can set ctx.refresh_working_page exactly
- # like any model-dispatched handler -- the auto path must consume it (reload, ledger resets, nudge)
- # BEFORE trusting its digest, mirroring the model-dispatched path's post-call check, rather than
- # exposing a digest read from a page the run has already declared stale.
- monkeypatch.setattr(loop_module, "AUTO_OBSERVE_SETTLE_INTERVAL_SECONDS", 0.0)
- from skyvern.forge.taskv3.loop import AUTO_OBSERVE_BEGIN
-
- reload_calls: list[None] = []
-
- async def reload_page() -> None:
- reload_calls.append(None)
-
- clicks: list[tuple[str, dict[str, Any]]] = []
- observe_calls = {"n": 0}
-
- async def observe_handler(_args: dict[str, Any]) -> ToolResult:
- observe_calls["n"] += 1
- ctx = skyvern_context.current()
- assert ctx is not None
- ctx.refresh_working_page = True
- return ToolResult.ok("url=x STALE (1 interactive elements)")
-
- tools = [
- _billable_tool("click", clicks, data={"page_transitioned": True}),
- ToolSpec(
- name="observe",
- description="o",
- parameters={"type": "object", "properties": {}},
- handler=observe_handler,
- compactable=True,
- ),
- make_finish_tool(),
- ]
- script: list[list[tuple[str, dict[str, Any]]]] = [
- [("click", {"selector": "#next"})],
- [("finish", {"status": "completed", "reason": "done"})],
- ]
-
- ctx = SkyvernContext(task_id="tsk_auto_observe_refresh")
- skyvern_context.set(ctx)
- try:
- with capture_logs() as logs:
- outcome, _ = await _run(script, tools, reload_page=reload_page, auto_observe=True)
- finally:
- skyvern_context.reset()
-
- assert outcome.status == "completed"
- assert observe_calls["n"] == 1
- assert len(reload_calls) == 1
-
- click_msgs = [m for m in outcome.messages if m.get("role") == "tool" and m.get("name") == "click"]
- assert len(click_msgs) == 1
- assert AUTO_OBSERVE_BEGIN not in click_msgs[0]["content"]
-
- user_notes = [str(m["content"]) for m in outcome.messages if m.get("role") == "user"]
- refresh_notes = [n for n in user_notes if "re-observe" in n and "refreshed" in n]
- assert len(refresh_notes) == 1
-
- assert any(e.get("event") == "taskv3 loop honored page refresh signal" for e in logs)
- fires = [e for e in logs if e.get("event") == "taskv3 auto observe"]
- refresh_fires = [f for f in fires if f.get("fired") is False and f.get("reason") == "refresh"]
- assert len(refresh_fires) == 1
-
-
-class _ReasoningDictSensitiveCaller(_ScriptedCaller):
- """Rejects any call carrying a dict reasoning_effort, as a provider without the responses
- bridge would."""
-
- def __init__(self, script: list[list[tuple[str, dict[str, Any]]]]) -> None:
- super().__init__(script)
- self.reasoning_per_call: list[Any] = []
-
- async def call(self, **kwargs: Any) -> dict[str, Any]:
- self.reasoning_per_call.append(kwargs.get("reasoning_effort"))
- if isinstance(kwargs.get("reasoning_effort"), dict):
- raise LLMProviderErrorRetryableTask("TEST_KEY")
- return await super().call(**kwargs)
-
-
-async def test_loop_drops_reasoning_dict_and_retries_the_turn_after_a_call_failure() -> None:
- # A bridge-gate false positive must degrade to the config's own reasoning_effort, not end the
- # run on turn 1.
- caller = _ReasoningDictSensitiveCaller([[("finish", {"status": "completed", "reason": "ok"})]])
- outcome = await run_agent_tool_loop(
- llm_caller=caller,
- system_prompt="sys",
- user_prompt="goal",
- tools=[make_finish_tool()],
- max_turns=5,
- max_tool_calls=10,
- call_kwargs={"reasoning_effort": {"effort": "high", "summary": "auto"}},
- retryable_call_exceptions=(LLMProviderErrorRetryableTask,),
- max_call_retries=2,
- call_retry_base_delay=0.0,
- )
-
- assert outcome.status == "completed"
- dict_calls = [r for r in caller.reasoning_per_call if isinstance(r, dict)]
- assert dict_calls and caller.reasoning_per_call[-1] is None
-
-
-class _ReasoningDictOnlySensitiveCaller(_ScriptedCaller):
- """Rejects only the dict reasoning_effort; tool_choice is independently supported."""
-
- def __init__(self, script: list[list[tuple[str, dict[str, Any]]]]) -> None:
- super().__init__(script)
- self.kwargs_per_call: list[tuple[Any, Any]] = []
-
- async def call(self, **kwargs: Any) -> dict[str, Any]:
- self.kwargs_per_call.append((kwargs.get("reasoning_effort"), kwargs.get("tool_choice")))
- if isinstance(kwargs.get("reasoning_effort"), dict):
- raise LLMProviderErrorRetryableTask("TEST_KEY")
- return await super().call(**kwargs)
-
-
-async def test_degrading_the_summary_dict_keeps_tool_choice() -> None:
- caller = _ReasoningDictOnlySensitiveCaller([[("finish", {"status": "completed", "reason": "ok"})]])
- outcome = await run_agent_tool_loop(
- llm_caller=caller,
- system_prompt="sys",
- user_prompt="goal",
- tools=[make_finish_tool()],
- max_turns=5,
- max_tool_calls=10,
- call_kwargs={"reasoning_effort": {"effort": "high", "summary": "auto"}, "tool_choice": "required"},
- retryable_call_exceptions=(LLMProviderErrorRetryableTask,),
- max_call_retries=2,
- call_retry_base_delay=0.0,
- )
- assert outcome.status == "completed"
- final_reasoning, final_tool_choice = caller.kwargs_per_call[-1]
- assert final_reasoning is None
- assert final_tool_choice == "required"
-
-
-def test_canonical_progress_tracker_counts_targets_and_clears_on_progress() -> None:
- from skyvern.forge.taskv3.loop import _CanonicalProgressTracker, _ProgressEvidence
-
- t = _CanonicalProgressTracker()
- assert t.record_touch("#code", True) == (1, 1)
- assert t.record_touch("#code", True) == (2, 2)
- assert t.record_touch("#other", False) == (1, 0)
- assert t.record_touch("#code", True) == (3, 3)
- assert t.looping_targets() == 0 # below the 4-touch rung
- assert t.record_touch("#code", False) == (4, 3)
- assert t.looping_targets() == 1
- t.progress(_ProgressEvidence.FRESH_DOWNLOAD_OR_NAVIGATION)
- assert t.record_touch("#code", True) == (1, 1) # streak reset by progress
- assert t.looping_targets() == 0
-
-
-def test_canonical_ring_state_is_touched_only_through_the_tracker() -> None:
- # The choke-point contract: a clear that bypasses progress() (poking the ring's fields
- # directly) is behavior-identical and invisible to every other test in this file, so the
- # invariant is pinned at the source level — the ring's state must have no references
- # outside _CanonicalProgressTracker's own body.
- import ast
- import inspect
+def test_canonical_ring_state_is_touched_only_through_the_tracker() -> None:
+ # The choke-point contract: a clear that bypasses progress() (poking the ring's fields
+ # directly) is behavior-identical and invisible to every other test in this file, so the
+ # invariant is pinned at the source level — the ring's state must have no references
+ # outside _CanonicalProgressTracker's own body.
+ import ast
+ import inspect
import skyvern.forge.taskv3.loop as loop_module
@@ -9065,9 +7275,8 @@ async def test_canonical_loop_suppressed_when_completion_probe_fires_on_the_rung
@pytest.mark.asyncio
async def test_canonical_loop_not_masked_by_missing_probe_samples() -> None:
- # Auto-observe deliberately treats a missing probe sample as "assume changed" for the model's
- # benefit, but that fallback is not evidence: intermittent probe timeouts must not keep
- # clearing the ring and permanently mask a genuine loop.
+ # A missing probe sample around a failed dispatch is not evidence of a page change: intermittent
+ # probe timeouts must not keep clearing the ring and permanently mask a genuine loop.
from skyvern.forge.taskv3.loop import CANONICAL_LOOP_EVENT
touches: list[tuple[str, dict[str, Any]]] = []
@@ -9089,9 +7298,7 @@ async def test_canonical_loop_not_masked_by_missing_probe_samples() -> None:
script.append([("finish", {"status": "failed", "reason": "kept refusing"})])
tools = [_error_billable_tool("click", touches), observe, make_finish_tool()]
with capture_logs() as logs:
- outcome, _ = await _run(
- script, tools, auto_observe=True, page_probe=dead_probe, max_turns=50, max_tool_calls=100
- )
+ outcome, _ = await _run(script, tools, page_probe=dead_probe, max_turns=50, max_tool_calls=100)
assert outcome.status == "failed"
assert len(touches) == 4
fires = [e for e in logs if e.get("event") == CANONICAL_LOOP_EVENT]