Skip to content

Automate browser based workflows with AI

SKY-10346: Plan runtime frontiers from page evidence (PR 9/12) (#6261)

Andrew Neilson1553027b02dd
diff --git a/skyvern-frontend/src/routes/workflows/copilot/NarrativeView.test.ts b/skyvern-frontend/src/routes/workflows/copilot/NarrativeView.test.ts
index b1dd9ed44..e2ea2f8ec 100644
--- a/skyvern-frontend/src/routes/workflows/copilot/NarrativeView.test.ts
+++ b/skyvern-frontend/src/routes/workflows/copilot/NarrativeView.test.ts
@@ -4,6 +4,7 @@ import {
EMPTY_NARRATIVE,
TurnNarrativeState,
applyNarrativeEvent,
+ effectiveMode,
} from "./narrativeState";
import {
WorkflowCopilotBlockProgressUpdate,
@@ -110,13 +111,30 @@ describe("applyNarrativeEvent — turn_start", () => {
turnStart({ turn_id: "t2", turn_index: 1, mode: "edit" }),
);
- expect(s).toEqual({
- ...EMPTY_NARRATIVE,
+ expect(s).toMatchObject({
turnId: "t2",
turnIndex: 1,
mode: "edit",
+ blocks: [],
+ draft: null,
+ designStarted: false,
+ designEnded: false,
+ terminal: null,
});
});
+
+ it("captures prior_block_count on turn_start", () => {
+ const s = applyNarrativeEvent(
+ EMPTY_NARRATIVE,
+ turnStart({ prior_block_count: 3 }),
+ );
+ expect(s.priorBlockCount).toBe(3);
+ });
+
+ it("treats missing prior_block_count as null (cold-start)", () => {
+ const s = applyNarrativeEvent(EMPTY_NARRATIVE, turnStart());
+ expect(s.priorBlockCount).toBeNull();
+ });
});
describe("applyNarrativeEvent — design phase", () => {
@@ -173,6 +191,9 @@ describe("applyNarrativeEvent — block_progress", () => {
blockType: "task",
state: "running",
lastSeenIteration: 0,
+ activity: [],
+ startedAt: "2026-05-25T00:00:04Z",
+ endedAt: null,
},
]);
});
@@ -238,6 +259,65 @@ describe("applyNarrativeEvent — block_progress", () => {
);
expect(s.blocks[0]?.state).toBe(expected);
});
+
+ it("clears endedAt on retry-back-to-running so stale elapsed disappears", () => {
+ let s = applyNarrativeEvent(
+ EMPTY_NARRATIVE,
+ blockProgress({ block_label: "b", status: "running" }),
+ );
+ s = applyNarrativeEvent(
+ s,
+ blockProgress({
+ block_label: "b",
+ status: "failed",
+ timestamp: "2026-05-25T00:01:00Z",
+ }),
+ );
+ expect(s.blocks[0]?.endedAt).toBe("2026-05-25T00:01:00Z");
+ s = applyNarrativeEvent(
+ s,
+ blockProgress({
+ block_label: "b",
+ status: "running",
+ timestamp: "2026-05-25T00:01:30Z",
+ }),
+ );
+ expect(s.blocks[0]?.state).toBe("running");
+ expect(s.blocks[0]?.endedAt).toBeNull();
+ });
+
+ it("overwrites endedAt with the latest terminal wall clock", () => {
+ let s = applyNarrativeEvent(
+ EMPTY_NARRATIVE,
+ blockProgress({ block_label: "b", status: "running" }),
+ );
+ s = applyNarrativeEvent(
+ s,
+ blockProgress({
+ block_label: "b",
+ status: "failed",
+ timestamp: "2026-05-25T00:01:00Z",
+ }),
+ );
+ s = applyNarrativeEvent(
+ s,
+ blockProgress({
+ block_label: "b",
+ status: "running",
+ timestamp: "2026-05-25T00:01:30Z",
+ }),
+ );
+ s = applyNarrativeEvent(
+ s,
+ blockProgress({
+ block_label: "b",
+ status: "completed",
+ timestamp: "2026-05-25T00:02:15Z",
+ }),
+ );
+ expect(s.blocks[0]?.state).toBe("completed");
+ expect(s.blocks[0]?.endedAt).toBe("2026-05-25T00:02:15Z");
+ });
});
describe("applyNarrativeEvent — terminal", () => {
@@ -288,3 +368,56 @@ describe("applyNarrativeEvent — terminal", () => {
expect(s.narrativeSummary).toBe("refused: too risky");
});
});
+
+describe("effectiveMode", () => {
+ it("reports build when classifier said unknown but blocks were drafted from empty prior", () => {
+ const s: TurnNarrativeState = {
+ ...EMPTY_NARRATIVE,
+ mode: "unknown",
+ draft: { blockCount: 2, blockLabels: ["a", "b"], summary: null },
+ terminal: "response",
+ };
+ expect(effectiveMode(s)).toBe("build");
+ });
+
+ it("reports edit when prior_block_count > 0 and turn drafted blocks", () => {
+ const s: TurnNarrativeState = {
+ ...EMPTY_NARRATIVE,
+ mode: "unknown",
+ draft: { blockCount: 2, blockLabels: ["a", "b"], summary: null },
+ terminal: "response",
+ priorBlockCount: 2,
+ };
+ expect(effectiveMode(s)).toBe("edit");
+ });
+
+ it("reports clarify when classifier said draft_only but no blocks were drafted", () => {
+ const s: TurnNarrativeState = {
+ ...EMPTY_NARRATIVE,
+ mode: "draft_only",
+ draft: null,
+ terminal: "response",
+ };
+ expect(effectiveMode(s)).toBe("clarify");
+ });
+
+ it("preserves docs_answer / diagnose / refuse when terminal has no blocks", () => {
+ for (const mode of ["docs_answer", "diagnose", "refuse"]) {
+ const s: TurnNarrativeState = {
+ ...EMPTY_NARRATIVE,
+ mode,
+ terminal: "response",
+ };
+ expect(effectiveMode(s)).toBe(mode);
+ }
+ });
+
+ it("falls back to classifier mode while turn is still in-flight (no terminal)", () => {
+ const s: TurnNarrativeState = {
+ ...EMPTY_NARRATIVE,
+ mode: "build",
+ terminal: null,
+ };
+ expect(effectiveMode(s)).toBe("build");
+ });
+});
diff --git a/skyvern-frontend/src/routes/workflows/copilot/NarrativeView.tsx b/skyvern-frontend/src/routes/workflows/copilot/NarrativeView.tsx
index c33853a5c..cd024f969 100644
--- a/skyvern-frontend/src/routes/workflows/copilot/NarrativeView.tsx
+++ b/skyvern-frontend/src/routes/workflows/copilot/NarrativeView.tsx
@@ -1,148 +1,721 @@
-import { BlockState, BlockUIState, TurnNarrativeState } from "./narrativeState";
+import { useEffect, useMemo, useState } from "react";
-const MODE_CHIP_UNKNOWN = {
- label: "THINKING",
- classes: "bg-slate-700/50 text-slate-200 border-slate-600",
-};
+import {
+ ActivityEntry,
+ BlockState,
+ TurnNarrativeState,
+ effectiveMode,
+ parseUtcIsoMs,
+} from "./narrativeState";
-const MODE_CHIP: Record<string, { label: string; classes: string }> = {
- build: {
- label: "BUILDING",
- classes: "bg-blue-900/40 text-blue-200 border-blue-700/60",
- },
- edit: {
- label: "EDITING",
- classes: "bg-indigo-900/40 text-indigo-200 border-indigo-700/60",
- },
- docs_answer: {
- label: "ANSWERING",
- classes: "bg-emerald-900/40 text-emerald-200 border-emerald-700/60",
- },
- clarify: {
- label: "CLARIFYING",
- classes: "bg-amber-900/40 text-amber-200 border-amber-700/60",
- },
- diagnose: {
- label: "DIAGNOSING",
- classes: "bg-orange-900/40 text-orange-200 border-orange-700/60",
- },
- draft_only: {
- label: "DRAFTING",
- classes: "bg-cyan-900/40 text-cyan-200 border-cyan-700/60",
- },
- refuse: {
- label: "REFUSING",
- classes: "bg-rose-900/40 text-rose-200 border-rose-700/60",
- },
- unknown: MODE_CHIP_UNKNOWN,
-};
+interface BlockPalette {
+ fg: string;
+ bg: string;
+ border: string;
+ glyph: string;
+}
-const BLOCK_STATE_CHIP: Record<
- BlockUIState,
- { label: string; classes: string }
-> = {
- queued: {
- label: "queued",
- classes: "bg-slate-800 text-slate-400 border-slate-700",
- },
- running: {
- label: "running",
- classes: "bg-blue-900/40 text-blue-200 border-blue-700/60",
- },
- completed: {
- label: "done",
- classes: "bg-emerald-900/40 text-emerald-200 border-emerald-700/60",
- },
- failed: {
- label: "failed",
- classes: "bg-rose-900/40 text-rose-200 border-rose-700/60",
- },
- skipped: {
- label: "skipped",
- classes: "bg-slate-800 text-slate-500 border-slate-700",
- },
+const PALETTE_NAV: BlockPalette = {
+ fg: "text-blue-300",
+ bg: "bg-blue-500/15",
+ border: "border-blue-400/60",
+ glyph: "→",
+};
+const PALETTE_CRED: BlockPalette = {
+ fg: "text-amber-300",
+ bg: "bg-amber-500/15",
+ border: "border-amber-400/60",
+ glyph: "⌬",
+};
+const PALETTE_LOOP: BlockPalette = {
+ fg: "text-violet-300",
+ bg: "bg-violet-500/15",
+ border: "border-violet-400/60",
+ glyph: "↻",
+};
+const PALETTE_ACTION: BlockPalette = {
+ fg: "text-emerald-300",
+ bg: "bg-emerald-500/15",
+ border: "border-emerald-400/60",
+ glyph: "✦",
+};
+const PALETTE_EXTRACTION: BlockPalette = {
+ fg: "text-violet-300",
+ bg: "bg-violet-500/15",
+ border: "border-violet-400/60",
+ glyph: "↓",
+};
+const PALETTE_TASK: BlockPalette = {
+ fg: "text-slate-300",
+ bg: "bg-slate-500/15",
+ border: "border-slate-500/60",
+ glyph: "✦",
};
-function ModeChip({ mode }: { mode: string }) {
- const cfg = MODE_CHIP[mode] ?? MODE_CHIP_UNKNOWN;
+function paletteFor(blockType: string): BlockPalette {
+ const key = blockType.toLowerCase();
+ if (key.includes("nav") || key.includes("goto") || key.includes("url")) {
+ return PALETTE_NAV;
+ }
+ if (key.includes("cred") || key.includes("login")) return PALETTE_CRED;
+ if (key.includes("loop") || key.includes("for_each")) return PALETTE_LOOP;
+ if (key.includes("extract")) return PALETTE_EXTRACTION;
+ if (
+ key.includes("task") ||
+ key.includes("action") ||
+ key.includes("send") ||
+ key.includes("email") ||
+ key.includes("code")
+ ) {
+ return PALETTE_ACTION;
+ }
+ return PALETTE_TASK;
+}
+
+function formatElapsed(
+ startedAt: string | null,
+ endedAt: string | null,
+): string | null {
+ const startMs = parseUtcIsoMs(startedAt);
+ const endMs = parseUtcIsoMs(endedAt);
+ if (startMs === null || endMs === null) return null;
+ const seconds = Math.max(0, Math.round((endMs - startMs) / 1000));
+ const m = Math.floor(seconds / 60);
+ const s = seconds % 60;
+ return `${m}:${s.toString().padStart(2, "0")}`;
+}
+
+function liveElapsed(startedAt: string | null): string | null {
+ const ms = parseUtcIsoMs(startedAt);
+ if (ms === null) return null;
+ const secs = Math.max(0, Math.round((Date.now() - ms) / 1000));
+ const m = Math.floor(secs / 60);
+ const s = secs % 60;
+ return `${m}:${s.toString().padStart(2, "0")}`;
+}
+
+function truncate(s: string, n: number): string {
+ if (!s) return "";
+ if (s.length <= n) return s;
+ return s.slice(0, n).replace(/[\s,;:.!?]+$/, "") + "…";
+}
+
+function Spinner({ small = false }: { small?: boolean }) {
+ const sizeClass = small ? "h-2 w-2" : "h-2.5 w-2.5";
return (
<span
- className={`inline-flex items-center gap-1 rounded-full border px-2 py-0.5 text-[10px] font-semibold uppercase tracking-wide ${cfg.classes}`}
+ aria-hidden="true"
+ className={`${sizeClass} inline-block animate-spin rounded-full border-[1.5px] border-blue-400/30 border-t-blue-400`}
+ />
+ );
+}
+
+function FProse({
+ text,
+ muted,
+ italic,
+}: {
+ text: string;
+ muted?: boolean;
+ italic?: boolean;
+}) {
+ return (
+ <div
+ className={[
+ "py-0.5 pl-9 pr-0 text-[13px] leading-[1.55]",
+ muted ? "text-slate-400" : "text-slate-200",
+ italic ? "italic" : "",
+ ]
+ .filter(Boolean)
+ .join(" ")}
>
- {cfg.label}
- </span>
+ {text}
+ </div>
);
}
-function BlockCard({ block }: { block: BlockState }) {
- const stateChip = BLOCK_STATE_CHIP[block.state];
+function FSubRow({
+ glyph,
+ glyphClass,
+ children,
+ italic,
+ muted,
+}: {
+ glyph: React.ReactNode;
+ glyphClass?: string;
+ children: React.ReactNode;
+ italic?: boolean;
+ muted?: boolean;
+}) {
return (
- <div className="flex items-center justify-between gap-2 rounded border border-slate-700/60 bg-slate-900/40 px-2 py-1 text-xs">
- <div className="flex min-w-0 flex-1 items-center gap-2">
- <span className="truncate font-mono text-slate-200">{block.label}</span>
- <span className="shrink-0 text-[10px] text-slate-500">
- {block.blockType}
- </span>
- </div>
+ <div className="flex items-start gap-2 py-px">
<span
- className={`shrink-0 rounded-full border px-1.5 py-px text-[9px] font-bold uppercase tracking-wide ${stateChip.classes}`}
+ className={`mt-[2px] flex w-3.5 shrink-0 justify-center text-[11px] font-bold ${glyphClass ?? "text-slate-400"}`}
+ aria-hidden="true"
>
- {stateChip.label}
+ {glyph}
</span>
+ <div
+ className={[
+ "min-w-0 flex-1 text-[11.5px] leading-[1.55]",
+ muted ? "text-slate-400" : "text-slate-200",
+ italic ? "italic" : "",
+ ]
+ .filter(Boolean)
+ .join(" ")}
+ >
+ {children}
+ </div>
</div>
);
}
-export function NarrativeView({ turn }: { turn: TurnNarrativeState }) {
- const hasBlocks = turn.blocks.length > 0;
- const showDesignSpinner = turn.designStarted && !turn.designEnded;
- const showWaiting = turn.designEnded && !hasBlocks && !turn.terminal;
+function ActivityRow({ entry }: { entry: ActivityEntry }) {
+ if (entry.kind === "narration") {
+ return (
+ <FSubRow glyph="✦" glyphClass="text-violet-300" italic muted>
+ {entry.text}
+ </FSubRow>
+ );
+ }
+ if (entry.kind === "tool_call") {
+ return (
+ <FSubRow glyph="▸" glyphClass="text-slate-400">
+ <span className="font-mono text-slate-200">{entry.toolName}</span>
+ <span className="text-slate-500"> · calling…</span>
+ </FSubRow>
+ );
+ }
+ const ok = entry.success !== false;
+ return (
+ <FSubRow
+ glyph={ok ? "✓" : "✕"}
+ glyphClass={ok ? "text-emerald-300" : "text-rose-300"}
+ >
+ <span className={ok ? "text-slate-200" : "text-rose-200"}>
+ {entry.text}
+ </span>
+ </FSubRow>
+ );
+}
+
+function useSecondTick(active: boolean): void {
+ const [, setTick] = useState(0);
+ useEffect(() => {
+ if (!active) return;
+ const id = setInterval(() => setTick((t) => t + 1), 1000);
+ return () => clearInterval(id);
+ }, [active]);
+}
+
+interface FBlockRunProps {
+ block: BlockState;
+ onSelect?: (label: string) => void;
+}
+
+function FBlockRun({ block, onSelect }: FBlockRunProps) {
+ const palette = paletteFor(block.blockType);
+ const isRunning = block.state === "running";
+ const isOk = block.state === "completed";
+ const isFail = block.state === "failed";
+ const isDraft = block.state === "drafted";
+
+ const accentBorder = isRunning
+ ? "border-blue-400/60"
+ : isOk
+ ? "border-emerald-400/60"
+ : isFail
+ ? "border-rose-400/60"
+ : "border-slate-500/60";
+ const accentText = isRunning
+ ? "text-blue-300"
+ : isOk
+ ? "text-emerald-300"
+ : isFail
+ ? "text-rose-300"
+ : "text-slate-400";
+ const puckBg = isRunning
+ ? "bg-blue-500/15"
+ : isOk
+ ? "bg-emerald-500/15"
+ : isFail
+ ? "bg-rose-500/15"
+ : "bg-slate-elevation3";
+
+ const [userOpen, setUserOpen] = useState<boolean | null>(null);
+ const defaultOpen = isRunning || isFail;
+ const open = userOpen === null ? defaultOpen : userOpen;
+ const toggleable = isOk;
+ useSecondTick(isRunning);
+ const elapsed = formatElapsed(block.startedAt, block.endedAt);
+ const live = isRunning ? liveElapsed(block.startedAt) : null;
+ const statusText = isOk
+ ? (elapsed ?? "done")
+ : isRunning
+ ? `working${live ? ` · ${live}` : ""}`
+ : isFail
+ ? "halted"
+ : isDraft
+ ? "drafted"
+ : "queued";
return (
- <div className="flex flex-col gap-2 text-sm text-slate-200">
- <div className="flex items-center gap-2">
- <ModeChip mode={turn.mode} />
- {turn.draft ? (
- <span className="text-[11px] text-slate-400">
- Drafted workflow with {turn.draft.blockCount} block
- {turn.draft.blockCount === 1 ? "" : "s"}
- {turn.draft.blockLabels.length > 0 ? (
- <>
- :{" "}
- <span className="font-mono text-slate-300">
- {turn.draft.blockLabels.join(", ")}
- </span>
- </>
- ) : null}
+ <div className="flex flex-col">
+ <button
+ type="button"
+ className={`flex w-full items-start gap-3 px-1 py-1 text-left ${
+ toggleable ? "cursor-pointer" : "cursor-default"
+ }`}
+ onClick={() => {
+ onSelect?.(block.label);
+ if (toggleable) {
+ setUserOpen((v) => !(v === null ? defaultOpen : v));
+ }
+ }}
+ title={`Highlight ${block.label} on canvas`}
+ >
+ <span
+ className={`flex h-6 w-6 shrink-0 items-center justify-center rounded-full border text-[11px] font-bold ${accentBorder} ${accentText} ${puckBg}`}
+ aria-hidden="true"
+ >
+ {isOk ? "✓" : isFail ? "✕" : isRunning ? <Spinner /> : palette.glyph}
+ </span>
+ <div className="flex min-w-0 flex-1 flex-col">
+ <div className="flex flex-wrap items-baseline gap-x-1.5 gap-y-0.5">
+ <span className="font-mono text-[12.5px] font-semibold text-slate-100">
+ {block.label}
+ </span>
+ <span className="text-[11px] text-slate-500">·</span>
+ <span className={`font-mono text-[11px] font-medium ${accentText}`}>
+ {statusText}
+ </span>
+ <span className="text-[10.5px] text-slate-500">
+ · {block.blockType}
+ </span>
+ </div>
+ {!open && isOk && block.activity.length > 0 ? (
+ <div className="mt-0.5 text-[12px] leading-[1.5] text-slate-400">
+ {block.activity[block.activity.length - 1]!.text}
+ </div>
+ ) : null}
+ </div>
+ {toggleable ? (
+ <span
+ className={`shrink-0 text-[12px] text-slate-500 transition-transform ${
+ open ? "rotate-90" : ""
+ }`}
+ aria-hidden="true"
+ >
+ ›
</span>
) : null}
- </div>
+ </button>
+
+ {open ? (
+ <div className="ml-9 flex flex-col gap-1.5 border-l border-slate-700/60 py-1.5 pl-3">
+ {isRunning ? (
+ <span className="inline-flex w-fit items-center gap-1.5 rounded-full border border-blue-400/40 bg-blue-500/10 px-2 py-0.5 text-[11px] font-semibold text-blue-300">
+ <span className="h-[5px] w-[5px] animate-pulse rounded-full bg-blue-400" />
+ Active in Live Browser
+ </span>
+ ) : null}
+ {block.activity.length === 0 && isRunning ? (
+ <FSubRow glyph={<Spinner small />} glyphClass="text-blue-300">
+ <span className="text-slate-400">Working…</span>
+ </FSubRow>
+ ) : null}
+ {block.activity.map((entry) => (
+ <ActivityRow key={entry.id} entry={entry} />
+ ))}
+ {isFail ? (
+ <div className="mt-1 flex items-start gap-2 rounded-md border border-rose-400/30 bg-rose-500/10 px-2.5 py-1.5">
+ <span className="text-[11px] font-bold text-rose-300">✕</span>
+ <div className="text-[12px] leading-[1.5] text-rose-200/90">
+ {block.activity.find((e) => e.kind === "tool_result")?.text ??
+ "Halted — see run details."}
+ </div>
+ </div>
+ ) : null}
+ </div>
+ ) : null}
+ </div>
+ );
+}
+
+interface FDesignRowProps {
+ done: boolean;
+ blockLabels: string[];
+ activity: ActivityEntry[];
+}
+
+function FDesignRow({ done, blockLabels, activity }: FDesignRowProps) {
+ const [userOpen, setUserOpen] = useState<boolean | null>(null);
+ const open = userOpen === null ? !done : userOpen;
+ const drafts = blockLabels.length;
+ const thoughts = activity.filter(
+ (e) => e.kind === "narration" || e.kind === "tool_call",
+ ).length;
+ const summary: string[] = [];
+ if (thoughts) {
+ summary.push(`${thoughts} thought${thoughts === 1 ? "" : "s"}`);
+ }
+ if (drafts) {
+ summary.push(`drafted ${drafts} block${drafts === 1 ? "" : "s"}`);
+ }
+ const title = done ? "Designed the workflow" : "Designing the workflow";
+
+ return (
+ <div className="flex flex-col">
+ <button
+ type="button"
+ className="flex w-full items-center gap-3 px-1 py-1 text-left"
+ onClick={() => setUserOpen((v) => !(v === null ? !done : v))}
+ >
+ <span
+ className="flex h-6 w-6 shrink-0 items-center justify-center rounded-full border border-violet-400/60 bg-violet-500/15 text-[11px] font-bold text-violet-300"
+ aria-hidden="true"
+ >
+ {done ? "✓" : <Spinner />}
+ </span>
+ <div className="flex flex-1 items-baseline gap-2 text-left">
+ <span className="text-[12.5px] font-semibold text-slate-100">
+ {title}
+ </span>
+ {summary.length ? (
+ <span className="text-[11px] text-slate-400">
+ · {summary.join(" · ")}
+ </span>
+ ) : null}
+ {!done ? (
+ <span className="text-[10.5px] uppercase tracking-wide text-blue-300">
+ live
+ </span>
+ ) : null}
+ </div>
+ <span
+ className={`shrink-0 text-[12px] text-slate-500 transition-transform ${
+ open ? "rotate-90" : ""
+ }`}
+ aria-hidden="true"
+ >
+ ›
+ </span>
+ </button>
+ {open ? (
+ <div className="ml-9 flex flex-col gap-1 border-l border-slate-700/60 py-1.5 pl-3">
+ {activity.map((entry) => (
+ <ActivityRow key={entry.id} entry={entry} />
+ ))}
+ {blockLabels.map((label) => (
+ <FSubRow key={label} glyph="✦" glyphClass="text-emerald-300">
+ <span className="text-slate-400">Drafted </span>
+ <span className="font-mono text-slate-100">{label}</span>
+ </FSubRow>
+ ))}
+ </div>
+ ) : null}
+ </div>
+ );
+}
+
+interface TurnSummary {
+ headline: string;
+ stats: string[];
+ accent: "ok" | "fail" | "qa";
+ glyph: string;
+ isFail: boolean;
+ isQA: boolean;
+}
+
+function computeTurnSummary(turn: TurnNarrativeState): TurnSummary {
+ const isFail =
+ turn.terminal === "error" || turn.blocks.some((b) => b.state === "failed");
+ const mode = effectiveMode(turn);
+ const isQA =
+ mode === "docs_answer" || mode === "clarify" || mode === "refuse";
+ const hasDrafts = (turn.draft?.blockCount ?? 0) > 0;
+ const hasEdited = (turn.priorBlockCount ?? 0) > 0 && hasDrafts;
+
+ const headline = isFail
+ ? "Run halted"
+ : isQA
+ ? mode === "docs_answer"
+ ? "Answered"
+ : mode === "refuse"
+ ? "Declined"
+ : "Followed up"
+ : hasEdited
+ ? "Applied edits and re-tested"
+ : hasDrafts
+ ? "Built and tested the workflow"
+ : "Completed the run";
- {showDesignSpinner ? (
- <div className="text-xs italic text-slate-400">
- Designing the workflow…
+ const stats: string[] = [];
+ const turnElapsed = formatElapsed(turn.startedAt, turn.endedAt);
+ if (turnElapsed) stats.push(turnElapsed);
+ if (!isQA) {
+ const ok = turn.blocks.filter((b) => b.state === "completed").length;
+ const failed = turn.blocks.filter((b) => b.state === "failed").length;
+ const newBlocks = hasEdited ? 0 : (turn.draft?.blockCount ?? 0);
+ if (ok) stats.push(`${ok} block${ok === 1 ? "" : "s"} ran`);
+ if (newBlocks) stats.push(`${newBlocks} new`);
+ if (failed) stats.push(`${failed} failed`);
+ }
+
+ return {
+ headline,
+ stats,
+ accent: isFail ? "fail" : isQA ? "qa" : "ok",
+ glyph: isFail ? "✕" : isQA ? "✦" : "✓",
+ isFail,
+ isQA,
+ };
+}
+
+function accentBg(accent: TurnSummary["accent"]): string {
+ if (accent === "fail") {
+ return "border-rose-400/60 bg-rose-500/15 text-rose-300";
+ }
+ if (accent === "qa") {
+ return "border-violet-400/60 bg-violet-500/15 text-violet-300";
+ }
+ return "border-emerald-400/60 bg-emerald-500/15 text-emerald-300";
+}
+
+interface RollupCardProps {
+ turn: TurnNarrativeState;
+ summary: TurnSummary;
+ onExpand: () => void;
+}
+
+function RollupCard({ turn, summary, onExpand }: RollupCardProps) {
+ const closing =
+ turn.narrativeSummary?.trim() || turn.terminalMessage?.trim() || "";
+ const completed = turn.blocks.filter((b) => b.state === "completed");
+ const failed = turn.blocks.filter((b) => b.state === "failed");
+ const showCommit = !summary.isQA && completed.length > 0;
+
+ return (
+ <div className="overflow-hidden rounded-xl border border-slate-700/60 bg-slate-elevation2">
+ <button
+ type="button"
+ onClick={onExpand}
+ className="flex w-full items-start gap-3 px-3.5 py-3 text-left"
+ >
+ <span
+ className={`flex h-[26px] w-[26px] shrink-0 items-center justify-center rounded-full border text-[12px] font-bold ${accentBg(
+ summary.accent,
+ )}`}
+ aria-hidden="true"
+ >
+ {summary.glyph}
+ </span>
+ <div className="min-w-0 flex-1">
+ <div className="mb-0.5 flex flex-wrap items-baseline gap-x-2 gap-y-0.5">
+ <span className="text-[14px] font-semibold tracking-tight text-slate-100">
+ {summary.headline}
+ </span>
+ {summary.stats.length ? (
+ <span className="text-[11.5px] text-slate-400">
+ {summary.stats.join(" · ")}
+ </span>
+ ) : null}
+ </div>
+ {closing ? (
+ <div
+ className={`mt-0.5 text-[12.5px] leading-[1.5] ${
+ summary.isFail ? "text-rose-200/90" : "text-slate-400"
+ }`}
+ >
+ {summary.isQA ? truncate(closing, 90) : closing}
+ </div>
+ ) : null}
</div>
+ <span
+ className="mt-1 shrink-0 text-[14px] text-slate-500"
+ aria-hidden="true"
+ >
+ ›
+ </span>
+ </button>
+
+ {showCommit ? (
+ <div className="border-t border-white/5 pb-3 pl-[52px] pr-3.5 pt-2.5">
+ <div className="mb-1.5 text-[10px] font-bold uppercase tracking-[.06em] text-slate-500">
+ What changed
+ </div>
+ <ul className="m-0 flex list-none flex-col gap-1 p-0">
+ {completed.map((b) => {
+ const palette = paletteFor(b.blockType);
+ return (
+ <li
+ key={b.label}
+ className="flex items-baseline gap-1.5 text-[12px] leading-[1.5] text-slate-200"
+ >
+ <span
+ className={`w-3.5 shrink-0 text-center text-[11px] font-bold ${palette.fg}`}
+ aria-hidden="true"
+ >
+ {palette.glyph}
+ </span>
+ <span className="font-mono text-[11px] text-slate-400">
+ {b.label}
+ </span>
+ <span className="text-slate-600">·</span>
+ <span className="text-[11.5px] text-slate-200">
+ {b.blockType}
+ </span>
+ </li>
+ );
+ })}
+ </ul>
+ </div>
+ ) : null}
+
+ {failed.length > 0 ? (
+ <div className="border-t border-white/5 pb-3 pl-[52px] pr-3.5 pt-2.5">
+ <div className="mb-1.5 text-[10px] font-bold uppercase tracking-[.06em] text-rose-400">
+ Halted
+ </div>
+ <ul className="m-0 flex list-none flex-col gap-1 p-0">
+ {failed.map((b) => (
+ <li
+ key={b.label}
+ className="flex items-baseline gap-1.5 text-[12px] leading-[1.5] text-rose-200"
+ >
+ <span
+ className="w-3.5 shrink-0 text-center text-[11px] font-bold text-rose-300"
+ aria-hidden="true"
+ >
+ ✕
+ </span>
+ <span className="font-mono text-[11px] text-rose-300/80">
+ {b.label}
+ </span>
+ </li>
+ ))}
+ </ul>
+ </div>
+ ) : null}
+ </div>
+ );
+}
+
+interface DetailViewProps {
+ turn: TurnNarrativeState;
+ onCollapse: (() => void) | null;
+ onBlockSelect?: (label: string) => void;
+}
+
+function DetailView({ turn, onCollapse, onBlockSelect }: DetailViewProps) {
+ const hasBlocks = turn.blocks.length > 0;
+ const designStarted = turn.designStarted;
+ const designOpen = designStarted && !turn.designEnded;
+ // Hide the "Designed the workflow" cluster on terminal turns that produced
+ // no draft (Q&A / clarify / refuse routes occasionally emit design_start
+ // before the agent decides not to build). Live turns still surface it so a
+ // long design phase isn't silently invisible.
+ const hasDraft = (turn.draft?.blockCount ?? 0) > 0;
+ const showDesign = designStarted && (hasDraft || hasBlocks || !turn.terminal);
+ const preBlockNarration = turn.designActivity.filter(
+ (e) => e.kind === "narration",
+ );
+
+ return (
+ <div className="relative flex flex-col gap-2.5">
+ {onCollapse ? (
+ <button
+ type="button"
+ className="absolute -top-1 right-0 flex h-6 w-6 -rotate-90 items-center justify-center rounded-md text-[16px] text-slate-400 hover:bg-slate-700/60 hover:text-slate-100"
+ onClick={onCollapse}
+ aria-label="Collapse turn"
+ title="Collapse turn"
+ >
+ ›
+ </button>
+ ) : null}
+
+ {showDesign ? (
+ <FDesignRow
+ done={!designOpen}
+ blockLabels={turn.draft?.blockLabels ?? []}
+ activity={turn.designActivity}
+ />
+ ) : preBlockNarration.length > 0 ? (
+ preBlockNarration.map((e) => (
+ <FProse key={e.id} text={e.text} muted italic />
+ ))
) : null}
{hasBlocks ? (
<div className="flex flex-col gap-1">
{turn.blocks.map((b) => (
- <BlockCard key={b.workflowRunBlockId} block={b} />
+ <FBlockRun
+ key={b.workflowRunBlockId || b.label}
+ block={b}
+ onSelect={onBlockSelect}
+ />
))}
</div>
) : null}
- {showWaiting ? (
- <div className="text-xs italic text-slate-500">
+ {!hasBlocks &&
+ !designStarted &&
+ !turn.terminal &&
+ !["docs_answer", "refuse", "clarify"].includes(effectiveMode(turn)) ? (
+ <div className="pl-9 text-[12px] italic text-slate-500">
Waiting for the first block to start…
</div>
) : null}
- {turn.terminal && turn.narrativeSummary ? (
- <div className="rounded border border-slate-700/40 bg-slate-900/30 px-2 py-1 text-xs text-slate-300">
- {turn.narrativeSummary}
+ {turn.terminal && (turn.narrativeSummary || turn.terminalMessage) ? (
+ <div className="whitespace-pre-wrap pl-9 pr-8 text-[13px] leading-[1.55] text-slate-200">
+ {turn.narrativeSummary?.trim() || turn.terminalMessage?.trim()}
</div>
) : null}
</div>
);
}
+
+interface NarrativeViewProps {
+ turn: TurnNarrativeState;
+ onBlockSelect?: (blockLabel: string) => void;
+ // Past turns render rolled-up by default; the latest / in-flight turn
+ // renders in detail. Parent decides via this flag.
+ defaultExpanded?: boolean;
+}
+
+export function NarrativeView({
+ turn,
+ onBlockSelect,
+ defaultExpanded = true,
+}: NarrativeViewProps) {
+ const summary = useMemo(() => computeTurnSummary(turn), [turn]);
+ const isInFlight = turn.terminal === null;
+ const isComplete = !isInFlight;
+ const defaultRolled = isComplete && !defaultExpanded;
+ const [userRolled, setUserRolled] = useState<boolean | null>(null);
+ const rolled = userRolled === null ? defaultRolled : userRolled;
+
+ useEffect(() => {
+ setUserRolled(null);
+ }, [defaultExpanded]);
+
+ if (rolled && isComplete) {
+ return (
+ <RollupCard
+ turn={turn}
+ summary={summary}
+ onExpand={() => setUserRolled(false)}
+ />
+ );
+ }
+
+ return (
+ <DetailView
+ turn={turn}
+ onCollapse={isComplete ? () => setUserRolled(true) : null}
+ onBlockSelect={onBlockSelect}
+ />
+ );
+}
diff --git a/skyvern-frontend/src/routes/workflows/copilot/WorkflowCopilotChat.tsx b/skyvern-frontend/src/routes/workflows/copilot/WorkflowCopilotChat.tsx
index b6f6d1f1a..5d73fe52a 100644
--- a/skyvern-frontend/src/routes/workflows/copilot/WorkflowCopilotChat.tsx
+++ b/skyvern-frontend/src/routes/workflows/copilot/WorkflowCopilotChat.tsx
@@ -16,7 +16,6 @@ import { WorkflowCreateYAMLRequest } from "@/routes/workflows/types/workflowYaml
import { WorkflowApiResponse } from "@/routes/workflows/types/workflowTypes";
import { toast } from "@/components/ui/use-toast";
import { getSseClient } from "@/api/sse";
-import { cn } from "@/util/utils";
import {
WorkflowCopilotCancelRequest,
WorkflowCopilotChatHistoryResponse,
@@ -47,13 +46,84 @@ import {
EMPTY_NARRATIVE,
TurnNarrativeState,
applyNarrativeEvent,
+ hydrateNarrativeFromPayload,
+ parseUtcIsoMs,
} from "./narrativeState";
+// Cap on retained per-turn snap-back snapshots. A typical session has a
+// handful of turns; this ceiling guards a runaway long-running chat.
+const MAX_TURN_SNAPSHOTS = 20;
+
+function formatElapsedSeconds(ms: number): string {
+ const seconds = Math.max(0, Math.round(ms / 1000));
+ const m = Math.floor(seconds / 60);
+ const s = seconds % 60;
+ return `${m}:${s.toString().padStart(2, "0")}`;
+}
+
+function ConvoAggregatePill({
+ messages,
+ isInFlight,
+}: {
+ messages: ChatMessage[];
+ isInFlight: boolean;
+}) {
+ const turnsWithNarrative = messages.filter(
+ (m) => m.sender === "ai" && m.narrative,
+ );
+ if (turnsWithNarrative.length < 2) return null;
+ let earliestMs: number | null = null;
+ let latestMs: number | null = null;
+ for (const m of turnsWithNarrative) {
+ const startMs = parseUtcIsoMs(m.narrative?.startedAt);
+ if (startMs !== null) {
+ earliestMs =
+ earliestMs === null ? startMs : Math.min(earliestMs, startMs);
+ }
+ const endMs =
+ parseUtcIsoMs(m.narrative?.endedAt) ?? parseUtcIsoMs(m.timestamp);
+ if (endMs !== null) {
+ latestMs = latestMs === null ? endMs : Math.max(latestMs, endMs);
+ }
+ }
+ const elapsedLabel =
+ earliestMs !== null && latestMs !== null && latestMs > earliestMs
+ ? formatElapsedSeconds(latestMs - earliestMs)
+ : null;
+ const anyError = turnsWithNarrative.some(
+ (m) => m.narrative?.terminal === "error",
+ );
+ const status = isInFlight ? "In flight" : anyError ? "Halted" : "Done";
+ const dotClass = isInFlight
+ ? "bg-blue-400"
+ : anyError
+ ? "bg-rose-400"
+ : "bg-emerald-400";
+ return (
+ <div className="flex justify-center pb-1">
+ <span className="inline-flex items-center gap-2 rounded-full border border-slate-700 bg-slate-900/60 px-3 py-0.5 text-[11px] text-slate-300">
+ <span
+ aria-hidden="true"
+ className={`inline-block h-1.5 w-1.5 rounded-full ${dotClass}`}
+ />
+ {turnsWithNarrative.length} turns
+ {elapsedLabel ? ` · ${elapsedLabel} elapsed` : ""}
+ {" · "}
+ {status}
+ </span>
+ </div>
+ );
+}
+
interface ChatMessage {
id: string;
sender: WorkflowCopilotChatSender;
content: string;
timestamp?: string;
+ // frozen narrative-bubble state captured at terminal RESPONSE
+ // so the per-block cards persist as the user scrolls back through past
+ // turns. Live in-flight narrative is rendered separately at the bottom.
+ narrative?: TurnNarrativeState;
}
type QueuedPrompt = {
@@ -97,29 +167,28 @@ interface MessageItemProps {
}
const MessageItem = memo(({ message, footer }: MessageItemProps) => {
- return (
- <div className="flex items-start gap-3">
- <div
- className={cn(
- "flex h-8 w-8 shrink-0 items-center justify-center rounded-full text-xs font-bold",
- message.sender === "ai"
- ? "bg-neutral-950 text-white dark:bg-neutral-100 dark:text-neutral-950"
- : "bg-neutral-200 text-neutral-900 dark:bg-neutral-800 dark:text-neutral-100",
- )}
- >
- {message.sender === "ai" ? "AI" : "U"}
- </div>
- <div className="relative flex-1 rounded-lg bg-neutral-100 p-3 pr-12 dark:bg-neutral-900">
- <p className="whitespace-pre-wrap pr-3 text-sm text-neutral-900 dark:text-neutral-100">
- {message.content}
- </p>
- {footer ? <div className="mt-3 flex gap-2">{footer}</div> : null}
- {message.timestamp ? (
- <span className="pointer-events-none absolute bottom-2 right-2 rounded bg-white/80 px-1.5 py-0.5 text-[10px] text-neutral-500 dark:bg-neutral-950/70 dark:text-neutral-500">
- {formatChatTimestamp(message.timestamp)}
- </span>
- ) : null}
+ if (message.sender === "user") {
+ return (
+ <div className="flex justify-end">
+ <div className="relative max-w-[85%] rounded-xl border border-white/5 bg-slate-elevation4 px-3.5 py-2.5 text-[13.5px] leading-[1.5] text-foreground">
+ <p className="whitespace-pre-wrap pr-12">{message.content}</p>
+ {message.timestamp ? (
+ <span className="pointer-events-none absolute bottom-2 right-2 rounded bg-slate-elevation1/70 px-1.5 py-0.5 text-[10px] text-muted-foreground">
+ {formatChatTimestamp(message.timestamp)}
+ </span>
+ ) : null}
+ </div>
</div>
+ );
+ }
+ return (
+ <div className="flex flex-col gap-2">
+ <p className="whitespace-pre-wrap pl-1 text-[13px] leading-[1.55] text-slate-200">
+ {message.content}
+ </p>
+ {footer ? (
+ <div className="flex flex-wrap gap-2 pl-1">{footer}</div>
+ ) : null}
</div>
);
});
@@ -134,6 +203,10 @@ interface WorkflowCopilotChatProps {
workflow: WorkflowApiResponse,
clearPending: () => void,
) => void;
+ // parent receives the block label when the user clicks a block
+ // card in the narrative bubble. The editor uses this to flash-highlight
+ // the matching canvas node.
+ onBlockSelect?: (blockLabel: string) => void;
isOpen?: boolean;
onClose?: () => void;
onMessageCountChange?: (count: number) => void;
@@ -145,6 +218,15 @@ interface WorkflowCopilotChatProps {
onInitialMessageConsumed?: () => void;
}
+// Snap-back state keyed by turn_id so rapid resubmits don't clobber a prior
+// turn's snapshot before its terminal frame lands. The snapshot captures
+// pre-submit canvas state (including unsaved local edits) so Reject / Cancel /
+// ERROR can revert exactly what the user submitted.
+interface TurnSnapshot {
+ snapshot: WorkflowApiResponse | null;
+ hadStagedDraft: boolean;
+}
+
const AUTO_SEND_TIMEOUT_MS = 5000;
const DEFAULT_WINDOW_WIDTH = 600;
@@ -192,6 +274,7 @@ const constrainPosition = (
export function WorkflowCopilotChat({
onWorkflowUpdate,
onReviewWorkflow,
+ onBlockSelect,
isOpen = true,
onClose,
onMessageCountChange,
@@ -211,6 +294,13 @@ export function WorkflowCopilotChat({
const [queuedPrompt, setQueuedPrompt] = useState<QueuedPrompt | null>(null);
const [narrative, setNarrative] =
useState<TurnNarrativeState>(EMPTY_NARRATIVE);
+ // mirror of the latest narrative state so async SSE handlers
+ // closed over `handleSend`'s scope can read the live value instead of the
+ // stale closure capture from submit time.
+ const narrativeRef = useRef<TurnNarrativeState>(EMPTY_NARRATIVE);
+ useEffect(() => {
+ narrativeRef.current = narrative;
+ }, [narrative]);
const [isLoadingHistory, setIsLoadingHistory] = useState(false);
const streamingAbortController = useRef<AbortController | null>(null);
const pendingMessageId = useRef<string | null>(null);
@@ -225,6 +315,13 @@ export function WorkflowCopilotChat({
// Mirrors workflowCopilotChatId for async handlers that would otherwise
// close over a stale value across renders (e.g. clearProposedWorkflow).
const workflowCopilotChatIdRef = useRef<string | null>(null);
+ const turnSnapshots = useRef<Map<string, TurnSnapshot>>(new Map());
+ // Snapshot captured at submit time. Moved into turnSnapshots once
+ // turn_start lands and we know the BE-assigned turn_id.
+ const pendingSubmitSnapshot = useRef<WorkflowApiResponse | null>(null);
+ // Most recent turn_id observed via turn_start; used by Reject and by
+ // legacy error frames that don't carry a turn_id.
+ const latestTurnId = useRef<string | null>(null);
useEffect(() => {
workflowCopilotChatIdRef.current = workflowCopilotChatId;
}, [workflowCopilotChatId]);
@@ -311,6 +408,9 @@ export function WorkflowCopilotChat({
setProposedWorkflow(null);
setAutoAccept(false);
setNarrative(EMPTY_NARRATIVE);
+ turnSnapshots.current.clear();
+ pendingSubmitSnapshot.current = null;
+ latestTurnId.current = null;
hasScrolledOnLoad.current = false;
};
@@ -410,6 +510,14 @@ export function WorkflowCopilotChat({
};
const handleRejectWorkflow = () => {
+ // The staged proposal was rendered onto the canvas mid-turn (via
+ // WORKFLOW_DRAFT). Reject must revert the canvas to the pre-submit
+ // canvas state captured client-side at submit time.
+ const turnId = latestTurnId.current;
+ const entry = turnId ? turnSnapshots.current.get(turnId) : null;
+ if (entry?.snapshot) {
+ applyWorkflowUpdate(entry.snapshot);
+ }
setProposedWorkflow(null);
void clearProposedWorkflow(false);
};
@@ -554,6 +662,23 @@ export function WorkflowCopilotChat({
sender: message.sender,
content: message.content,
timestamp: message.created_at,
+ narrative: (() => {
+ const hydrated = hydrateNarrativeFromPayload(
+ message.narrative_payload,
+ );
+ if (!hydrated) return undefined;
+ // Fall back to the legacy message body when the persisted
+ // payload predates terminal-text capture.
+ if (!hydrated.terminalMessage && message.content) {
+ return {
+ ...hydrated,
+ terminalMessage: message.content,
+ narrativeSummary:
+ hydrated.narrativeSummary ?? message.content,
+ };
+ }
+ return hydrated;
+ })(),
}),
);
setMessages(historyMessages);
@@ -814,6 +939,20 @@ export function WorkflowCopilotChat({
};
workflowYaml = convertToYAML(requestBody);
+
+ // Snapshot pre-submit canvas state (including unsaved local edits)
+ // so Reject / Cancel / ERROR can revert the canvas to exactly what
+ // the user submitted. ``saveData.workflow`` is the last-loaded
+ // canonical; overlay it with the live canvas blocks/parameters.
+ pendingSubmitSnapshot.current = {
+ ...saveData.workflow,
+ title: saveData.title,
+ workflow_definition: {
+ ...saveData.workflow.workflow_definition,
+ parameters: saveData.parameters,
+ blocks: saveData.blocks,
+ },
+ } as WorkflowApiResponse;
}
const handleProcessingUpdate = (
@@ -840,16 +979,33 @@ export function WorkflowCopilotChat({
pendingCancelToken.current = null;
setWorkflowCopilotChatId(response.workflow_copilot_chat_id);
+ // freeze the current narrative state into the AI message
+ // so per-block cards persist as the user scrolls past this turn.
+ // Read via narrativeRef because this callback was closed over at
+ // handleSend time (pre-turn_start), so the React state binding is
+ // stale here.
+ const liveNarrative = narrativeRef.current;
+ const frozenNarrative: TurnNarrativeState | undefined =
+ liveNarrative.turnId !== null
+ ? applyNarrativeEvent(liveNarrative, response)
+ : undefined;
+
const aiMessage: ChatMessage = {
id: Date.now().toString(),
sender: "ai",
content: response.message,
timestamp: response.response_time,
+ narrative: frozenNarrative,
};
setMessages((prev) => [...prev, aiMessage]);
const userCancelledThisTurn =
cancelInFlightController.current === abortController;
+ const responseTurnId =
+ response.turn_id ?? latestTurnId.current ?? null;
+ const responseEntry = responseTurnId
+ ? (turnSnapshots.current.get(responseTurnId) ?? null)
+ : null;
if (
response.updated_workflow &&
shouldAutoApplyWorkflowResponse(
@@ -859,19 +1015,47 @@ export function WorkflowCopilotChat({
)
) {
applyWorkflowUpdate(response.updated_workflow);
+ } else if (
+ // Cancel terminal on a turn that produced staged content →
+ // snap canvas back to the pre-submit client snapshot.
+ response.cancelled &&
+ responseEntry?.hadStagedDraft &&
+ responseEntry?.snapshot
+ ) {
+ applyWorkflowUpdate(responseEntry.snapshot);
+ setProposedWorkflow(null);
} else {
+ // Informational reply OR proposal pending review. For
+ // proposals, the Accept/Reject card is the user's next gate;
+ // canvas keeps the staged content until the user acts.
setProposedWorkflow(response.updated_workflow ?? null);
}
};
const handleError = (payload: WorkflowCopilotStreamErrorUpdate) => {
pendingCancelToken.current = null;
+ const liveNarrative = narrativeRef.current;
+ const frozenNarrative: TurnNarrativeState | undefined =
+ liveNarrative.turnId !== null
+ ? applyNarrativeEvent(liveNarrative, payload)
+ : undefined;
const errorMessage: ChatMessage = {
id: Date.now().toString(),
sender: "ai",
content: payload.error,
+ narrative: frozenNarrative,
};
setMessages((prev) => [...prev, errorMessage]);
+ // Error on a turn that produced staged content → snap canvas
+ // back. Errors on no-draft turns leave the canvas alone.
+ const errorTurnId = payload.turn_id ?? latestTurnId.current ?? null;
+ const errorEntry = errorTurnId
+ ? (turnSnapshots.current.get(errorTurnId) ?? null)
+ : null;
+ if (errorEntry?.hadStagedDraft && errorEntry?.snapshot) {
+ applyWorkflowUpdate(errorEntry.snapshot);
+ setProposedWorkflow(null);
+ }
};
const client = await getSseClient(credentialGetter);
@@ -892,27 +1076,57 @@ export function WorkflowCopilotChat({
case "processing_update":
handleProcessingUpdate(payload);
return false;
- // Legacy in-flight signals — the narrative bubble derives its
- // state from turn_start/design_*/block_progress/workflow_draft
- // instead, so these are intentionally dropped here.
+ case "condensing":
+ return false;
case "tool_call":
case "tool_result":
- case "condensing":
case "narration":
- return false;
case "block_progress":
setNarrative((prev) => applyNarrativeEvent(prev, payload));
return false;
- case "turn_start":
+ case "turn_start": {
+ // Move the pre-submit canvas snapshot into the per-turn
+ // map keyed by the BE-assigned turn_id; cap the map so a
+ // long-running chat does not retain every turn's snapshot.
+ const map = turnSnapshots.current;
+ map.set(payload.turn_id, {
+ snapshot: pendingSubmitSnapshot.current,
+ hadStagedDraft: false,
+ });
+ pendingSubmitSnapshot.current = null;
+ while (map.size > MAX_TURN_SNAPSHOTS) {
+ const oldest = map.keys().next().value;
+ if (oldest === undefined) break;
+ map.delete(oldest);
+ }
+ latestTurnId.current = payload.turn_id;
setNarrative(() =>
applyNarrativeEvent(EMPTY_NARRATIVE, payload),
);
return false;
+ }
case "design_start":
case "design_end":
- case "workflow_draft":
setNarrative((prev) => applyNarrativeEvent(prev, payload));
return false;
+ case "workflow_draft": {
+ // Render the staged workflow on the canvas mid-turn. Only
+ // mark the turn as having staged content if applyWorkflowUpdate
+ // succeeds — a swallowed update would otherwise trigger a
+ // spurious snap-back at terminal.
+ if (payload.workflow) {
+ const applied = applyWorkflowUpdate(payload.workflow);
+ if (applied) {
+ const turnId = latestTurnId.current;
+ if (turnId) {
+ const entry = turnSnapshots.current.get(turnId);
+ if (entry) entry.hadStagedDraft = true;
+ }
+ }
+ }
+ setNarrative((prev) => applyNarrativeEvent(prev, payload));
+ return false;
+ }
case "response":
setNarrative((prev) => applyNarrativeEvent(prev, payload));
handleResponse(payload);
@@ -1298,11 +1512,75 @@ export function WorkflowCopilotChat({
</p>
</div>
) : null}
+ <ConvoAggregatePill
+ messages={messages}
+ isInFlight={
+ isLoading ||
+ (narrative.turnId !== null && narrative.terminal === null)
+ }
+ />
{messages.map((message, index) => {
const isLastMessage = index === messages.length - 1;
- const showProposedPanel = isLastMessage && proposedWorkflow;
const showQueuedFooter =
isQueuedPromptWaiting && message.id === queuedPrompt?.id;
+ // Per-message frozen narrative. When an AI message carries a
+ // frozen narrative, render the narrative card stack in place
+ // of the legacy text bubble so the per-block cards survive
+ // subsequent turns. The Accept/Reject controls render only on
+ // the latest message AND while the proposal is pending review.
+ if (message.sender === "ai" && message.narrative) {
+ const showProposalActions =
+ isLastMessage && Boolean(proposedWorkflow);
+ return (
+ <div
+ key={message.id}
+ className="flex flex-col gap-2"
+ role="status"
+ aria-live="polite"
+ >
+ <NarrativeView
+ turn={message.narrative}
+ onBlockSelect={onBlockSelect}
+ defaultExpanded={isLastMessage}
+ />
+ {showProposalActions && proposedWorkflow ? (
+ <div className="flex flex-wrap gap-2 pl-1">
+ <button
+ type="button"
+ onClick={() => handleReviewWorkflow(proposedWorkflow)}
+ className="rounded border border-brand/60 bg-brand/10 px-3 py-1 text-xs text-foreground hover:bg-brand/20"
+ >
+ Review
+ </button>
+ <button
+ type="button"
+ onClick={() => handleAcceptWorkflow(proposedWorkflow)}
+ className="rounded bg-success px-3 py-1 text-xs text-success-foreground hover:bg-success/90"
+ >
+ Accept
+ </button>
+ <button
+ type="button"
+ onClick={() =>
+ handleAcceptWorkflow(proposedWorkflow, true)
+ }
+ className="rounded bg-success px-3 py-1 text-xs text-success-foreground hover:bg-success/80"
+ >
+ Always accept
+ </button>
+ <button
+ type="button"
+ onClick={handleRejectWorkflow}
+ className="rounded bg-destructive px-3 py-1 text-xs text-destructive-foreground hover:bg-destructive/90"
+ >
+ Reject
+ </button>
+ </div>
+ ) : null}
+ </div>
+ );
+ }
+ const showProposedPanel = isLastMessage && proposedWorkflow;
return (
<MessageItem
key={message.id}
@@ -1351,18 +1629,18 @@ export function WorkflowCopilotChat({
/>
);
})}
- {narrative.turnId !== null && (
+ {/*
+ Bottom in-flight narrative bubble. Suppressed once the terminal
+ RESPONSE has frozen the narrative into the latest AI message —
+ otherwise the same turn would render twice.
+ */}
+ {narrative.turnId !== null && narrative.terminal === null && (
<div
- className="flex items-start gap-3"
+ className="flex flex-col gap-2"
role="status"
aria-live="polite"
>
- <div className="flex h-8 w-8 shrink-0 items-center justify-center rounded-full bg-blue-600 text-xs font-bold text-white">
- AI
- </div>
- <div className="flex-1 rounded-lg bg-slate-800 p-3">
- <NarrativeView turn={narrative} />
- </div>
+ <NarrativeView turn={narrative} onBlockSelect={onBlockSelect} />
</div>
)}
<div ref={messagesEndRef} />
diff --git a/skyvern-frontend/src/routes/workflows/copilot/narrativeState.ts b/skyvern-frontend/src/routes/workflows/copilot/narrativeState.ts
index 4b0140630..385afbb79 100644
--- a/skyvern-frontend/src/routes/workflows/copilot/narrativeState.ts
+++ b/skyvern-frontend/src/routes/workflows/copilot/narrativeState.ts
@@ -7,15 +7,17 @@ import {
WorkflowCopilotBlockProgressUpdate,
WorkflowCopilotDesignEndUpdate,
WorkflowCopilotDesignStartUpdate,
+ WorkflowCopilotNarrationUpdate,
WorkflowCopilotStreamErrorUpdate,
WorkflowCopilotStreamResponseUpdate,
+ WorkflowCopilotToolCallUpdate,
+ WorkflowCopilotToolResultUpdate,
WorkflowCopilotTurnStartUpdate,
WorkflowCopilotWorkflowDraftUpdate,
} from "./workflowCopilotTypes";
// Discriminated union of every event the reducer below consumes. The bubble
-// only renders state derived from these payloads — it does not subscribe to
-// tool_call / tool_result / processing_update / narration / condensing.
+// derives all of its rendering from these payloads.
export type NarrativeEvent =
| WorkflowCopilotTurnStartUpdate
| WorkflowCopilotDesignStartUpdate
@@ -23,13 +25,17 @@ export type NarrativeEvent =
| WorkflowCopilotWorkflowDraftUpdate
| WorkflowCopilotBlockProgressUpdate
| WorkflowCopilotStreamResponseUpdate
- | WorkflowCopilotStreamErrorUpdate;
+ | WorkflowCopilotStreamErrorUpdate
+ | WorkflowCopilotNarrationUpdate
+ | WorkflowCopilotToolCallUpdate
+ | WorkflowCopilotToolResultUpdate;
// Block lifecycle states as observed via block_progress. The bubble groups
// failed-style states (failed, terminated, timed_out, canceled) under one
// chip and treats `skipped` as a separate neutral state.
export type BlockUIState =
| "queued"
+ | "drafted"
| "running"
| "completed"
| "failed"
@@ -41,6 +47,29 @@ export interface BlockState {
blockType: string;
state: BlockUIState;
lastSeenIteration: number;
+ // Tool calls and results emitted while this block was running are
+ // appended here so the expanded card shows what the agent did.
+ activity: ActivityEntry[];
+ // ISO timestamps captured the first time the block was seen running and
+ // the first time it landed in a terminal state. Drives the per-block
+ // ``done · 0:14``-style elapsed pill in the card.
+ startedAt: string | null;
+ endedAt: string | null;
+}
+
+export interface ActivityEntry {
+ kind: "tool_call" | "tool_result" | "narration";
+ // Free-text label rendered as a one-line summary in the card body.
+ text: string;
+ // Iteration of the agent loop that emitted the event. Used to dedupe
+ // re-sent payloads and to align tool_result with its tool_call.
+ iteration: number;
+ // Tool name when kind is tool_call/tool_result.
+ toolName?: string;
+ // Result success when kind is tool_result.
+ success?: boolean;
+ // Stable per-event id used as React key.
+ id: string;
}
export interface TurnNarrativeState {
@@ -58,6 +87,17 @@ export interface TurnNarrativeState {
terminal: "response" | "error" | null;
terminalMessage: string | null;
narrativeSummary: string | null;
+ // Block count of the canonical workflow at turn entry. Drives the edit-
+ // vs-build chip derivation; the snap-back source is captured client-side
+ // at submit so unsaved local canvas edits survive.
+ priorBlockCount: number | null;
+ // ISO timestamps from turn_start and the terminal frame. Drive the convo
+ // aggregate pill's elapsed display across all turns.
+ startedAt: string | null;
+ endedAt: string | null;
+ // Activity events fired BEFORE any block started running this turn
+ // (design phase + pre-execution tool calls), rendered inside the Design card.
+ designActivity: ActivityEntry[];
}
export const EMPTY_NARRATIVE: TurnNarrativeState = Object.freeze({
@@ -71,14 +111,117 @@ export const EMPTY_NARRATIVE: TurnNarrativeState = Object.freeze({
terminal: null,
terminalMessage: null,
narrativeSummary: null,
+ priorBlockCount: null,
+ startedAt: null,
+ endedAt: null,
+ designActivity: [],
}) as TurnNarrativeState;
+// Caps to keep long-running narrations from unbounded growth (and to keep
+// the rendered card from becoming a wall of text).
+const MAX_ACTIVITY_ENTRIES = 30;
+const MAX_DESIGN_ACTIVITY_ENTRIES = 50;
+
+// Some BE paths emit naive ISO datetimes (no timezone offset), e.g. the
+// chat-history endpoint serializing SQLAlchemy created_at columns. JS
+// Date.parse interprets those as local time, producing a multi-hour
+// drift versus timestamps that ARE timezone-aware (narrative_payload
+// startedAt/endedAt). Normalize to UTC when the offset is absent.
+export function parseUtcIsoMs(iso: string | null | undefined): number | null {
+ if (!iso) return null;
+ const hasTz = /Z$|[+-]\d{2}:?\d{2}$/.test(iso);
+ const ms = Date.parse(hasTz ? iso : `${iso}+00:00`);
+ return Number.isFinite(ms) ? ms : null;
+}
+
+// Tool names we never surface in the user-facing activity log. Internal
+// observation/maintenance tools are not interesting context for the user.
+const ACTIVITY_TOOL_DENYLIST = new Set([
+ "list_credentials",
+ "get_run_results",
+ "get_browser_screenshot",
+]);
+
+function buildActivityFromToolCall(
+ event: WorkflowCopilotToolCallUpdate,
+): ActivityEntry | null {
+ if (ACTIVITY_TOOL_DENYLIST.has(event.tool_name)) {
+ return null;
+ }
+ return {
+ kind: "tool_call",
+ text: `Calling ${event.tool_name}…`,
+ iteration: event.iteration,
+ toolName: event.tool_name,
+ id: `tc-${event.tool_call_id}`,
+ };
+}
+
+function buildActivityFromToolResult(
+ event: WorkflowCopilotToolResultUpdate,
+): ActivityEntry | null {
+ if (ACTIVITY_TOOL_DENYLIST.has(event.tool_name)) {
+ return null;
+ }
+ return {
+ kind: "tool_result",
+ text: event.summary || event.tool_name,
+ iteration: event.iteration,
+ toolName: event.tool_name,
+ success: event.success,
+ id: `tr-${event.tool_call_id}`,
+ };
+}
+
+function buildActivityFromNarration(
+ event: WorkflowCopilotNarrationUpdate,
+): ActivityEntry {
+ return {
+ kind: "narration",
+ text: event.narration,
+ iteration: event.iteration,
+ id: `n-${event.iteration}-${event.timestamp}`,
+ };
+}
+
+function appendCapped<T>(arr: T[], entry: T, cap: number): T[] {
+ const next = [...arr, entry];
+ return next.length > cap ? next.slice(next.length - cap) : next;
+}
+
+function appendActivity(
+ blocks: BlockState[],
+ designActivity: ActivityEntry[],
+ entry: ActivityEntry,
+): { blocks: BlockState[]; designActivity: ActivityEntry[] } {
+ const activeIdx = blocks.findIndex((b) => b.state === "running");
+ if (activeIdx === -1) {
+ return {
+ blocks,
+ designActivity: appendCapped(
+ designActivity,
+ entry,
+ MAX_DESIGN_ACTIVITY_ENTRIES,
+ ),
+ };
+ }
+ const nextBlocks = blocks.slice();
+ const active = nextBlocks[activeIdx]!;
+ nextBlocks[activeIdx] = {
+ ...active,
+ activity: appendCapped(active.activity, entry, MAX_ACTIVITY_ENTRIES),
+ };
+ return { blocks: nextBlocks, designActivity };
+}
+
export function mapBlockStatus(raw: string): BlockUIState {
switch (raw) {
case "running":
return "running";
case "completed":
return "completed";
+ case "drafted":
+ return "drafted";
case "failed":
case "terminated":
case "timed_out":
@@ -103,6 +246,8 @@ export function applyNarrativeEvent(
turnId: event.turn_id,
turnIndex: event.turn_index,
mode: event.mode || "unknown",
+ priorBlockCount: event.prior_block_count ?? null,
+ startedAt: event.timestamp ?? null,
};
case "design_start":
@@ -111,7 +256,31 @@ export function applyNarrativeEvent(
case "design_end":
return { ...prev, designEnded: true };
- case "workflow_draft":
+ case "workflow_draft": {
+ // Bubble shows the summary fields; canvas mid-turn rendering of
+ // ``event.workflow`` is wired in WorkflowCopilotChat.tsx. Seed
+ // ``blocks`` from block_labels so each drafted block renders its own
+ // card even on draft-only turns (where no block_progress fires).
+ // Existing entries from prior block_progress events take precedence;
+ // new labels join as ``drafted`` until block_progress upgrades them.
+ const labelToExisting = new Map(prev.blocks.map((b) => [b.label, b]));
+ const nextBlocks: BlockState[] = event.block_labels.map((label) => {
+ const existing = labelToExisting.get(label);
+ if (existing) return existing;
+ return {
+ workflowRunBlockId: "",
+ label,
+ blockType: "task",
+ state: "drafted",
+ lastSeenIteration: 0,
+ activity: [],
+ startedAt: null,
+ endedAt: null,
+ };
+ });
+ // Preserve any prior block whose label was dropped from the draft (rare
+ // — happens if the agent renames a block mid-turn). Drop those that no
+ // longer exist; they no longer participate in the proposal.
return {
...prev,
draft: {
@@ -119,50 +288,136 @@ export function applyNarrativeEvent(
blockLabels: event.block_labels,
summary: event.summary,
},
+ blocks: nextBlocks,
};
+ }
case "block_progress": {
const incomingState = mapBlockStatus(event.status);
// Key on workflow_run_block_id, not block_label, so loop iterations
// (e.g. a for_loop body) render as distinct rows.
- const existing = prev.blocks.findIndex(
+ let existing = prev.blocks.findIndex(
(b) => b.workflowRunBlockId === event.workflow_run_block_id,
);
- const nextEntry: BlockState = {
+ // A drafted placeholder seeded by workflow_draft has no run-block id
+ // yet; upgrade it in place on its first block_progress rather than
+ // spawning a duplicate row.
+ if (existing < 0) {
+ existing = prev.blocks.findIndex(
+ (b) =>
+ b.workflowRunBlockId === "" &&
+ b.state === "drafted" &&
+ b.label === event.block_label,
+ );
+ }
+ const eventTs = event.timestamp ?? null;
+ const previousBlock = existing >= 0 ? prev.blocks[existing]! : null;
+ const startedAt =
+ previousBlock?.startedAt ??
+ (incomingState === "running" ? eventTs : null);
+ const isTerminal =
+ incomingState === "completed" ||
+ incomingState === "failed" ||
+ incomingState === "skipped";
+ // Clear endedAt on retry-back-to-running so the elapsed pill doesn't
+ // show stale "DONE · 2:00" while the block is active again. On each
+ // terminal event take the latest wall clock so a retry-then-succeed
+ // sequence reflects the final completion time, not the first failure.
+ const endedAt = isTerminal ? eventTs : null;
+ const baseEntry: BlockState = {
workflowRunBlockId: event.workflow_run_block_id,
label: event.block_label,
blockType: event.block_type,
state: incomingState,
lastSeenIteration: event.iteration,
+ activity: previousBlock?.activity ?? [],
+ startedAt,
+ endedAt,
};
if (existing >= 0) {
const nextBlocks = prev.blocks.slice();
- nextBlocks[existing] = nextEntry;
+ nextBlocks[existing] = baseEntry;
return { ...prev, blocks: nextBlocks };
}
- return { ...prev, blocks: [...prev.blocks, nextEntry] };
+ return { ...prev, blocks: [...prev.blocks, baseEntry] };
+ }
+
+ case "tool_call": {
+ const entry = buildActivityFromToolCall(event);
+ if (!entry) return prev;
+ const { blocks, designActivity } = appendActivity(
+ prev.blocks,
+ prev.designActivity,
+ entry,
+ );
+ return { ...prev, blocks, designActivity };
}
- case "response":
- // Close the design phase on terminal regardless of whether design_end
- // arrived — a refusal turn can emit design_start via the first tool
- // call and then exit without persisting a workflow.
+ case "tool_result": {
+ const entry = buildActivityFromToolResult(event);
+ if (!entry) return prev;
+ const { blocks, designActivity } = appendActivity(
+ prev.blocks,
+ prev.designActivity,
+ entry,
+ );
+ return { ...prev, blocks, designActivity };
+ }
+
+ case "narration": {
+ const entry = buildActivityFromNarration(event);
+ const { blocks, designActivity } = appendActivity(
+ prev.blocks,
+ prev.designActivity,
+ entry,
+ );
+ return { ...prev, blocks, designActivity };
+ }
+
+ case "response": {
+ // Close the design phase on terminal even when DESIGN_END never
+ // arrived (a refusal turn can emit DESIGN_START via first
+ // tool_called and then exit without persisting a workflow).
+ // Some block_progress emissions only fire `running` without a
+ // terminal status; resolve any still-running block to `completed`
+ // so the chat doesn't show a stuck spinner after the turn is done.
+ const terminalTs = event.response_time ?? null;
+ const blocks = prev.blocks.map((b) =>
+ b.state === "running"
+ ? { ...b, state: "completed" as BlockUIState, endedAt: terminalTs }
+ : b,
+ );
return {
...prev,
designEnded: true,
terminal: "response",
terminalMessage: event.message,
narrativeSummary: event.narrative_summary ?? event.message,
+ endedAt: terminalTs ?? prev.endedAt,
+ blocks,
};
+ }
- case "error":
+ case "error": {
+ // Same sweep as the response case: any block stuck in `running` at
+ // terminal gets resolved so the chat doesn't show a stuck spinner.
+ // On an error terminal we mark them `failed` rather than `completed`.
+ const wallClock = prev.endedAt ?? new Date().toISOString();
+ const blocks = prev.blocks.map((b) =>
+ b.state === "running"
+ ? { ...b, state: "failed" as BlockUIState, endedAt: wallClock }
+ : b,
+ );
return {
...prev,
designEnded: true,
terminal: "error",
terminalMessage: event.error,
narrativeSummary: event.narrative_summary ?? null,
+ endedAt: wallClock,
+ blocks,
};
+ }
default:
// Exhaustiveness guard — any new NarrativeEvent variant added to the
@@ -170,3 +425,176 @@ export function applyNarrativeEvent(
return prev;
}
}
+
+function normalizeActivityEntries(raw: unknown): ActivityEntry[] {
+ if (!Array.isArray(raw)) return [];
+ const out: ActivityEntry[] = [];
+ for (const item of raw) {
+ if (!item || typeof item !== "object") continue;
+ const o = item as Record<string, unknown>;
+ const kind = o.kind;
+ if (
+ kind !== "tool_call" &&
+ kind !== "tool_result" &&
+ kind !== "narration"
+ ) {
+ continue;
+ }
+ if (typeof o.id !== "string" || typeof o.text !== "string") continue;
+ out.push({
+ kind,
+ text: o.text,
+ iteration: typeof o.iteration === "number" ? o.iteration : 0,
+ toolName: typeof o.toolName === "string" ? o.toolName : undefined,
+ success: typeof o.success === "boolean" ? o.success : undefined,
+ id: o.id,
+ });
+ }
+ return out;
+}
+
+export function hydrateNarrativeFromPayload(
+ payload: Record<string, unknown> | null | undefined,
+): TurnNarrativeState | undefined {
+ if (!payload || typeof payload !== "object") return undefined;
+ const turnId = typeof payload.turnId === "string" ? payload.turnId : null;
+ // turnIndex can be null on recovered route-error turns where the helper
+ // building the payload had no chat-message scope; default to 0 so the
+ // turn still hydrates and joins the convo-aggregate accounting.
+ const turnIndex =
+ typeof payload.turnIndex === "number" ? payload.turnIndex : 0;
+ if (turnId === null) return undefined;
+
+ const mode = typeof payload.mode === "string" ? payload.mode : "unknown";
+ const draftRaw = payload.draft;
+ const draft =
+ draftRaw && typeof draftRaw === "object"
+ ? {
+ blockCount:
+ typeof (draftRaw as Record<string, unknown>).blockCount === "number"
+ ? ((draftRaw as Record<string, unknown>).blockCount as number)
+ : 0,
+ blockLabels: Array.isArray(
+ (draftRaw as Record<string, unknown>).blockLabels,
+ )
+ ? ((draftRaw as Record<string, unknown>).blockLabels as string[])
+ : [],
+ summary:
+ typeof (draftRaw as Record<string, unknown>).summary === "string"
+ ? ((draftRaw as Record<string, unknown>).summary as string)
+ : null,
+ }
+ : null;
+
+ const blocksRaw = Array.isArray(payload.blocks) ? payload.blocks : [];
+ const blocks: BlockState[] = blocksRaw.map((b) => {
+ const obj = b as Record<string, unknown>;
+ return {
+ workflowRunBlockId:
+ typeof obj.workflowRunBlockId === "string"
+ ? obj.workflowRunBlockId
+ : "",
+ label: typeof obj.label === "string" ? obj.label : "",
+ blockType: typeof obj.blockType === "string" ? obj.blockType : "task",
+ state: ((): BlockState["state"] => {
+ const s = obj.state;
+ if (
+ s === "queued" ||
+ s === "drafted" ||
+ s === "running" ||
+ s === "completed" ||
+ s === "failed" ||
+ s === "skipped"
+ )
+ return s;
+ return "queued";
+ })(),
+ lastSeenIteration:
+ typeof obj.lastSeenIteration === "number" ? obj.lastSeenIteration : 0,
+ activity: normalizeActivityEntries(obj.activity),
+ startedAt: typeof obj.startedAt === "string" ? obj.startedAt : null,
+ endedAt: typeof obj.endedAt === "string" ? obj.endedAt : null,
+ };
+ });
+
+ const terminal = ((): TurnNarrativeState["terminal"] => {
+ const t = payload.terminal;
+ if (t === "response" || t === "error") return t;
+ return null;
+ })();
+
+ // Hydrated payloads sometimes record a block as `running` when the BE
+ // dropped its terminal `block_progress`. If the turn itself is terminal,
+ // sweep any still-running block to a sensible final state so the UI
+ // doesn't show a stuck spinner after the chat is loaded from history.
+ const endedAtIso =
+ typeof payload.endedAt === "string" ? (payload.endedAt as string) : null;
+ const sweptBlocks: BlockState[] = terminal
+ ? blocks.map((b) =>
+ b.state === "running"
+ ? {
+ ...b,
+ state: terminal === "error" ? "failed" : "completed",
+ endedAt: b.endedAt ?? endedAtIso,
+ }
+ : b,
+ )
+ : blocks;
+
+ const priorBlockCount =
+ typeof payload.priorBlockCount === "number"
+ ? (payload.priorBlockCount as number)
+ : null;
+
+ return {
+ ...EMPTY_NARRATIVE,
+ turnId,
+ turnIndex,
+ mode: mode as TurnNarrativeState["mode"],
+ designStarted: true,
+ designEnded: true,
+ draft,
+ blocks: sweptBlocks,
+ designActivity: normalizeActivityEntries(payload.designActivity),
+ terminal,
+ terminalMessage:
+ typeof payload.terminalMessage === "string"
+ ? (payload.terminalMessage as string)
+ : null,
+ narrativeSummary:
+ typeof payload.narrativeSummary === "string"
+ ? (payload.narrativeSummary as string)
+ : null,
+ priorBlockCount,
+ startedAt:
+ typeof payload.startedAt === "string"
+ ? (payload.startedAt as string)
+ : null,
+ endedAt:
+ typeof payload.endedAt === "string" ? (payload.endedAt as string) : null,
+ };
+}
+
+// Chip mode should reflect what the turn ACTUALLY did, not the pre-turn
+// intent classifier's guess. Re-derive from observed state so a
+// classifier-said-"unknown" turn that built shows "build", and a
+// classifier-said-"draft_only" turn that only asked a clarification
+// shows "clarify".
+export function effectiveMode(turn: TurnNarrativeState): string {
+ const blockCount = turn.draft?.blockCount ?? turn.blocks.length;
+ if (blockCount > 0) {
+ const priorBlocks = turn.priorBlockCount ?? 0;
+ return priorBlocks > 0 ? "edit" : "build";
+ }
+ if (turn.terminal !== null) {
+ if (
+ turn.mode === "docs_answer" ||
+ turn.mode === "diagnose" ||
+ turn.mode === "refuse"
+ ) {
+ return turn.mode;
+ }
+ return "clarify";
+ }
+ return turn.mode;
+}
diff --git a/skyvern-frontend/src/routes/workflows/copilot/workflowCopilotTypes.ts b/skyvern-frontend/src/routes/workflows/copilot/workflowCopilotTypes.ts
index 86d284857..6af6c1ecd 100644
--- a/skyvern-frontend/src/routes/workflows/copilot/workflowCopilotTypes.ts
+++ b/skyvern-frontend/src/routes/workflows/copilot/workflowCopilotTypes.ts
@@ -47,6 +47,7 @@ export interface WorkflowCopilotChatHistoryMessage {
sender: WorkflowCopilotChatSender;
content: string;
created_at: string;
+ narrative_payload?: Record<string, unknown> | null;
}
export interface WorkflowCopilotChatHistoryResponse {
@@ -114,6 +115,10 @@ export interface WorkflowCopilotTurnStartUpdate {
turn_index: number;
mode: string;
timestamp: string;
+ // Block count of the canonical workflow at turn entry. Drives the FE's
+ // edit-vs-build chip; the snap-back source is captured client-side at
+ // submit time so unsaved local canvas edits survive.
+ prior_block_count?: number | null;
}
export interface WorkflowCopilotDesignStartUpdate {
@@ -135,6 +140,7 @@ export interface WorkflowCopilotWorkflowDraftUpdate {
block_labels: string[];
summary: string | null;
timestamp: string;
+ workflow?: WorkflowApiResponse | null;
}
export interface WorkflowCopilotToolCallUpdate {
diff --git a/skyvern-frontend/src/routes/workflows/editor/Workspace.tsx b/skyvern-frontend/src/routes/workflows/editor/Workspace.tsx
index 8b6c19440..f0146acd4 100644
--- a/skyvern-frontend/src/routes/workflows/editor/Workspace.tsx
+++ b/skyvern-frontend/src/routes/workflows/editor/Workspace.tsx
@@ -87,6 +87,7 @@ import {
} from "@/store/WorkflowPanelStore";
import { useWorkflowHasChangesStore } from "@/store/WorkflowHasChangesStore";
import { useWorkflowParametersStore } from "@/store/WorkflowParametersStore";
+import { useWorkflowTitleStore } from "@/store/WorkflowTitleStore";
import { getCode, getOrderedBlockLabels } from "@/routes/workflows/utils";
import { DebuggerBlockRuns } from "@/routes/workflows/debugger/DebuggerBlockRuns";
import { copyText } from "@/util/copyText";
@@ -149,6 +150,22 @@ const Constants = {
// How long to poll before recording one rate-limit attempt (60s)
const POLL_ATTEMPT_THRESHOLD_MS = 60_000;
+// Marker class for the copilot's gold-ring block-highlight flash. Kept off
+// React Flow's `.selected` so a normal editor node click (which sets
+// `selected` to open the sidebar) doesn't trigger the flash. Must match the
+// selector in reactFlowOverrideStyles.css.
+const COPILOT_BLOCK_HIGHLIGHT_CLASS = "sk-copilot-block-highlight";
+
+function setBlockHighlightClass(node: AppNode, on: boolean): AppNode {
+ const tokens = (node.className ?? "")
+ .split(/\s+/)
+ .filter((token) => token && token !== COPILOT_BLOCK_HIGHLIGHT_CLASS);
+ if (on) tokens.push(COPILOT_BLOCK_HIGHLIGHT_CLASS);
+ const next = tokens.join(" ") || undefined;
+ if ((node.className ?? undefined) === next) return node;
+ return { ...node, className: next };
+}
+
type Props = Pick<FlowRendererProps, "initialTitle" | "workflow"> & {
initialNodes: Array<AppNode>;
initialEdges: Array<Edge>;
@@ -1275,6 +1292,12 @@ function Workspace({
const initialParameters = getInitialParameters(workflowData);
useWorkflowParametersStore.getState().setParameters(initialParameters);
+ // Sync title so snap-back on Reject reverts the editor's title bar
+ // alongside the canvas blocks.
+ if (typeof workflowData.title === "string") {
+ useWorkflowTitleStore.getState().setTitle(workflowData.title);
+ }
+
if (options?.persisted) {
// Atomic accept: server wrote a new version; treat as clean baseline and refresh cached workflow.
workflowChangesStore.setHasChanges(false);
@@ -2042,6 +2065,22 @@ function Workspace({
isLiveBrowserReady={copilotLiveBrowserReady}
initialMessage={initialCopilotMessage ?? undefined}
onInitialMessageConsumed={handleInitialCopilotMessageConsumed}
+ onBlockSelect={(blockLabel) => {
+ const matches = (node: AppNode) =>
+ (node.data as { label?: string } | undefined)?.label === blockLabel;
+ setNodes((prev) =>
+ prev.map((node) => setBlockHighlightClass(node, matches(node))),
+ );
+ // Auto-clear so the gold-ring flash animation re-triggers on the
+ // next select instead of the highlight sticking.
+ setTimeout(() => {
+ setNodes((prev) =>
+ prev.map((node) =>
+ matches(node) ? setBlockHighlightClass(node, false) : node,
+ ),
+ );
+ }, 1500);
+ }}
onReviewWorkflow={async (pendingWorkflow, clearPending) => {
const saveData = workflowChangesStore.getSaveData?.();
if (!saveData) return;
diff --git a/skyvern-frontend/src/routes/workflows/editor/reactFlowOverrideStyles.css b/skyvern-frontend/src/routes/workflows/editor/reactFlowOverrideStyles.css
index a2689b896..678b64fa6 100644
--- a/skyvern-frontend/src/routes/workflows/editor/reactFlowOverrideStyles.css
+++ b/skyvern-frontend/src/routes/workflows/editor/reactFlowOverrideStyles.css
@@ -14,6 +14,32 @@
@apply bg-slate-elevation3;
}
+@keyframes skBlockHighlightFlash {
+ 0%,
+ 60% {
+ box-shadow:
+ 0 0 0 2px var(--skyvern-gold, #facc15),
+ 0 0 24px rgba(234, 179, 8, 0.45);
+ }
+ 100% {
+ box-shadow: none;
+ }
+}
+
+/* Class set by Workspace's onBlockSelect (COPILOT_BLOCK_HIGHLIGHT_CLASS).
+ Deliberately not `.selected` — that flag also tracks the editor's sidebar
+ selection, so keying off it flashed on every normal node click. */
+.react-flow__node.sk-copilot-block-highlight
+ > div
+ > .rounded-lg.transition-shadow,
+.react-flow__node.sk-copilot-block-highlight
+ > div
+ > div
+ > .rounded-lg.transition-shadow {
+ animation: skBlockHighlightFlash 1.4s ease-out forwards;
+ border-radius: 8px;
+}
+
/* Smooth transitions for node position and size changes */
.react-flow__node {
transition: transform 0.2s ease-out;
diff --git a/skyvern/forge/sdk/copilot/tools.py b/skyvern/forge/sdk/copilot/tools.py
index 17581be56..134a3435f 100644
--- a/skyvern/forge/sdk/copilot/tools.py
+++ b/skyvern/forge/sdk/copilot/tools.py
@@ -156,7 +156,7 @@ RUN_BLOCKS_SAFETY_CEILING_SECONDS = 1200 # 20 min
# Per-tool-call budget for active block runs — caps a single tool invocation
# below the session-level wall clock (``enforcement.TOTAL_TIMEOUT_SECONDS``,
-# 600 s) so a long chain cannot consume the whole budget without giving the
+# 900 s) so a long chain cannot consume the whole budget without giving the
# copilot a chance to issue a smaller chain. Quiet-block runs keep the longer
# ``RUN_BLOCKS_SAFETY_CEILING_SECONDS`` above.
PER_TOOL_CALL_BUDGET_SECONDS = 240
@@ -703,23 +703,102 @@ def _per_tool_budget_problem_rerun_signal(
agent_steering = (
"The prior PER_TOOL_BUDGET run's get_run_results showed navigation "
f"block(s) [{labels}] were canceled or failed while applying page state. "
- "Do NOT rerun those block label(s) unchanged with run_blocks_and_collect_debug. "
+ f"Do NOT rerun those block label(s) unchanged with {tool_name}. "
"Update the workflow to split or replace the oversized navigation block first, "
- "prefer a code or validation block for DOM/page-state verification, or run only "
- "newly-created smaller block labels that apply one missing constraint at a time."
+ "use live-page inspection evidence to decide what state is actually missing, "
+ "or run only newly-created smaller block labels that apply one missing constraint at a time."
+ )
+ user_facing = (
+ "The previous run hit the per-step time budget before I could finish. "
+ "I'll continue from the verified browser state instead of retrying blindly."
)
- user_facing = "The previous run hit the per-step time budget. I need a smaller scope before I can rerun."
return CopilotToolBlockerSignal(
blocker_kind="tool_error",
agent_steering_text=agent_steering,
user_facing_reason=user_facing,
recovery_hint="retry_with_different_tool",
- cleared_by_tools=frozenset({"update_workflow", "update_and_run_blocks"}),
+ cleared_by_tools=PAGE_INSPECTION_TOOLS
+ | frozenset({"get_run_results", "update_workflow", "update_and_run_blocks"}),
internal_reason_code="tool_error_per_tool_budget_rerun",
blocked_tool=tool_name,
)
+def _workflow_yaml_ordered_labels(workflow_yaml: str | None) -> list[str]:
+ blocks = _parse_workflow_blocks(workflow_yaml)
+ if not blocks:
+ return []
+ labels: list[str] = []
+ for block in blocks:
+ if not isinstance(block, dict):
+ continue
+ label = _block_label_from_yaml(block)
+ if label:
+ labels.append(label)
+ return labels
+
+
+def _post_budget_upstream_replay_signal(
+ ctx: AgentContext, arguments: dict[str, Any] | None, tool_name: str
+) -> CopilotToolBlockerSignal | None:
+ problem_labels = _per_tool_budget_problem_label_set(ctx)
+ if not problem_labels:
+ return None
+
+ evidence = getattr(ctx, "composition_page_evidence", None)
+ if not isinstance(evidence, dict) or evidence.get("observed_after_workflow_run") is not True:
+ return None
+
+ requested_labels = _requested_block_label_set(arguments)
+ if not requested_labels:
+ return None
+
+ workflow_yaml = arguments.get("workflow_yaml") if isinstance(arguments, dict) else None
+ ordered_labels = _workflow_yaml_ordered_labels(workflow_yaml if isinstance(workflow_yaml, str) else None)
+ if not ordered_labels:
+ ordered_labels = _current_workflow_block_labels(ctx)
+ if not ordered_labels:
+ return None
+
+ first_problem_index = min(
+ (ordered_labels.index(label) for label in problem_labels if label in ordered_labels),
+ default=None,
+ )
+ if first_problem_index is None:
+ return None
+
+ upstream_requested = [label for label in ordered_labels[:first_problem_index] if label in requested_labels]
+ if not upstream_requested:
+ return None
+
+ upstream = ", ".join(upstream_requested)
+ frontier = ", ".join(sorted(problem_labels))
+ agent_steering = (
+ "The prior PER_TOOL_BUDGET run advanced the live browser, and you already inspected that "
+ "post-run page state. Do NOT restart upstream label(s) "
+ f"[{upstream}] before the budgeted frontier [{frontier}]. "
+ "Answer from the observed page if it contains the requested result/no-result evidence. "
+ "If more workflow testing is still required, preserve the verified upstream blocks and run only "
+ "new or modified smaller labels at/after the missing frontier."
+ )
+ user_facing = (
+ "The previous run already reached a later browser state. I'll continue from that evidence "
+ "instead of restarting earlier steps."
+ )
+ return CopilotToolBlockerSignal(
+ blocker_kind="tool_error",
+ agent_steering_text=agent_steering,
+ user_facing_reason=user_facing,
+ recovery_hint="retry_with_different_tool",
+ cleared_by_tools=PAGE_INSPECTION_TOOLS
+ | frozenset({"get_run_results", "update_workflow", "update_and_run_blocks"}),
+ preserves_workflow_draft=True,
+ renders_final_reply=False,
+ internal_reason_code="tool_error_post_budget_upstream_replay",
+ blocked_tool=tool_name,
+ )
+
+
_RECONCILIATION_REQUIRES_INPUT_USER_FACING = (
"The previous run was canceled. Tell me whether to retry, keep the draft as-is, or adjust the workflow first."
)
@@ -906,6 +985,8 @@ async def _attach_failed_block_screenshots(
BLOCK_RUNNING_TOOLS = frozenset({"run_blocks_and_collect_debug", "update_and_run_blocks"})
WORKFLOW_MUTATION_TOOLS = frozenset({"update_workflow", "update_and_run_blocks"})
ANSWER_ONLY_CONTEXT_TOOLS = frozenset({"get_run_results"})
+PAGE_INSPECTION_TOOLS = frozenset({"inspect_page_for_composition", "evaluate", "get_browser_screenshot"})
+PAGE_SCHEMA_CONTEXT_TOOLS = frozenset({"inspect_page_for_composition"})
_CURRENT_PAGE_INSPECTION_TARGETS = frozenset({"", "current", "current_page", "__current_page__"})
@@ -977,6 +1058,42 @@ def _late_block_running_call_signal(ctx: AgentContext, tool_name: str) -> Copilo
)
+def _mark_page_inspected(ctx: AgentContext) -> None:
+ ctx.post_budget_page_inspection_required = False
+ ctx.post_budget_page_inspection_url = None
+ ctx.post_budget_page_inspection_run_id = None
+
+
+def _post_budget_page_inspection_signal(ctx: AgentContext, tool_name: str) -> CopilotToolBlockerSignal | None:
+ if getattr(ctx, "post_budget_page_inspection_required", False) is not True:
+ return None
+
+ url = getattr(ctx, "post_budget_page_inspection_url", None)
+ run_id = getattr(ctx, "post_budget_page_inspection_run_id", None)
+ url_text = f" at {url}" if isinstance(url, str) and url else ""
+ run_text = f" for run {run_id}" if isinstance(run_id, str) and run_id else ""
+ agent_steering = (
+ f"The prior PER_TOOL_BUDGET run{run_text} advanced the live browser{url_text}. "
+ "Before another block-running tool, inspect the current browser page with "
+ 'inspect_page_for_composition(target_url="current_page"), evaluate, or get_browser_screenshot. '
+ "If the observed page evidence already contains the requested result or a no-results state, "
+ "answer from that evidence instead of rerunning the search. If evidence shows a missing page-state "
+ "change, then run only the smaller missing block after that inspection."
+ )
+ user_facing = "I need to inspect the current page state before running more steps."
+ return CopilotToolBlockerSignal(
+ blocker_kind="tool_error",
+ agent_steering_text=agent_steering,
+ user_facing_reason=user_facing,
+ recovery_hint="retry_with_different_tool",
+ cleared_by_tools=PAGE_INSPECTION_TOOLS,
+ preserves_workflow_draft=True,
+ renders_final_reply=False,
+ internal_reason_code="tool_error_post_budget_page_inspection_required",
+ blocked_tool=tool_name,
+ )
+
+
def _tool_loop_error(ctx: AgentContext, tool_name: str, arguments: dict[str, Any] | None = None) -> str | None:
detected = detect_failed_tool_step_loop_for_ctx(ctx, tool_name, arguments or {})
if detected is not None:
@@ -1020,10 +1137,17 @@ def _tool_loop_error(ctx: AgentContext, tool_name: str, arguments: dict[str, Any
_pending_reconciliation_no_input_signal(pending_run_id=pending_run_id, blocked_tool=tool_name),
)
- if tool_name == "run_blocks_and_collect_debug":
- budget_signal = _per_tool_budget_problem_rerun_signal(ctx, arguments, tool_name)
- if budget_signal is not None:
- return _emit_tool_blocker_signal(ctx, budget_signal)
+ inspection_signal = _post_budget_page_inspection_signal(ctx, tool_name)
+ if inspection_signal is not None:
+ return _emit_tool_blocker_signal(ctx, inspection_signal)
+
+ budget_signal = _per_tool_budget_problem_rerun_signal(ctx, arguments, tool_name)
+ if budget_signal is not None:
+ return _emit_tool_blocker_signal(ctx, budget_signal)
+
+ upstream_replay_signal = _post_budget_upstream_replay_signal(ctx, arguments, tool_name)
+ if upstream_replay_signal is not None:
+ return _emit_tool_blocker_signal(ctx, upstream_replay_signal)
streak_raw = getattr(ctx, "repeated_action_fingerprint_streak_count", 0)
streak = streak_raw if isinstance(streak_raw, int) else 0
@@ -1261,6 +1385,9 @@ def _turn_intent_tool_error(ctx: AgentContext, tool_name: str) -> CopilotToolBlo
blocks_update = tool_name in WORKFLOW_MUTATION_TOOLS and not authority.may_update_workflow
blocks_run = tool_name in BLOCK_RUNNING_TOOLS and not authority.may_run_blocks
+ blocks_page_inspection = tool_name in PAGE_SCHEMA_CONTEXT_TOOLS and (
+ intent.mode in NO_MUTATION_TURN_INTENT_MODES or not authority.may_update_workflow
+ )
# Two paths grant read access to ANSWER_ONLY_CONTEXT_TOOLS, both excluded for DOCS_ANSWER/REFUSE/CLARIFY:
# (1) authority.may_read_run_context — classifier-derived (DIAGNOSE turns)
# (2) pending_reconciliation_run_id — within-turn override anchored to the run-blocks watchdog
@@ -1273,10 +1400,19 @@ def _turn_intent_tool_error(ctx: AgentContext, tool_name: str) -> CopilotToolBlo
if isinstance(pending_run_id, str) and pending_run_id:
blocks_context_read = False
within_turn_read_override = True
+ else:
+ same_turn_run_id = getattr(ctx, "last_successful_run_blocks_workflow_run_id", None) or getattr(
+ ctx,
+ "last_run_blocks_workflow_run_id",
+ None,
+ )
+ if isinstance(same_turn_run_id, str) and same_turn_run_id:
+ blocks_context_read = False
+ within_turn_read_override = True
if blocks_run and not blocks_update and _request_policy_allows_update_and_skip_run(ctx, tool_name):
return None
- if not blocks_update and not blocks_run and not blocks_context_read:
+ if not blocks_update and not blocks_run and not blocks_context_read and not blocks_page_inspection:
if within_turn_read_override:
LOG.info(
"copilot authority gate allowed tool via within-turn read override",
@@ -1295,6 +1431,8 @@ def _turn_intent_tool_error(ctx: AgentContext, tool_name: str) -> CopilotToolBlo
reason_code = "turn_intent_no_mutation_run_blocked"
elif blocks_update:
reason_code = "turn_intent_update_blocked"
+ elif blocks_page_inspection:
+ reason_code = "turn_intent_page_inspection_blocked"
elif blocks_context_read:
reason_code = "turn_intent_context_read_blocked"
else:
@@ -1712,7 +1850,7 @@ _TEMPLATE_BUILTIN_ROOTS = (
_BLOCK_METADATA_STOPWORDS = frozenset({"and", "for", "the", "with"})
-def _block_type_name(block: Any) -> str:
+def _block_type_name(block: object) -> str:
"""Lowercase string name of a block's type, for both YAML and runtime blocks."""
bt = getattr(block, "block_type", None)
if bt is None:
@@ -1721,9 +1859,9 @@ def _block_type_name(block: Any) -> str:
return str(name).lower()
-def _blocks_by_label(workflow_definition: Any) -> dict[str, Any]:
+def _blocks_by_label(workflow_definition: object | None) -> dict[str, object]:
blocks = getattr(workflow_definition, "blocks", None) if workflow_definition else None
- by_label: dict[str, Any] = {}
+ by_label: dict[str, object] = {}
if not blocks:
return by_label
for block in blocks:
@@ -1733,6 +1871,44 @@ def _blocks_by_label(workflow_definition: Any) -> dict[str, Any]:
return by_label
+def _workflow_definition_block_labels(workflow_definition: object | None) -> list[str]:
+ blocks = getattr(workflow_definition, "blocks", None) if workflow_definition else None
+ labels: list[str] = []
+ if not blocks:
+ return labels
+ for block in blocks:
+ label = getattr(block, "label", None)
+ if isinstance(label, str) and label:
+ labels.append(label)
+ return labels
+
+
+def _current_workflow_block_labels(ctx: object) -> list[str]:
+ workflow = getattr(ctx, "last_workflow", None)
+ labels = _workflow_definition_block_labels(getattr(workflow, "workflow_definition", None))
+ if labels:
+ return labels
+ workflow_yaml = getattr(ctx, "last_workflow_yaml", None)
+ if not isinstance(workflow_yaml, str):
+ return []
+ blocks = _parse_workflow_blocks(workflow_yaml)
+ if not blocks:
+ return []
+ yaml_labels: list[str] = []
+ for block in blocks:
+ if isinstance(block, dict):
+ label = _block_label_from_yaml(block)
+ if label:
+ yaml_labels.append(label)
+ return yaml_labels
+
+
+def _unverified_current_workflow_labels(ctx: object) -> list[str]:
+ labels = _current_workflow_block_labels(ctx)
+ verified = set(getattr(ctx, "verified_prefix_labels", []) or [])
+ return [label for label in labels if label not in verified]
+
+
# Minimum length to apply the trailing-``s`` plural strip; below this we
# leave the token alone so words like ``is``/``us``/``has`` aren't mangled.
_MIN_STEMMABLE_TOKEN_LEN = 5
@@ -1946,8 +2122,8 @@ def _stale_block_metadata_message(items: list[dict[str, Any]]) -> str:
def _find_invalidated_labels(
- old_definition: Any,
- new_definition: Any,
+ old_definition: object | None,
+ new_definition: object | None,
requested_labels: list[str],
) -> set[str]:
"""Return the set of requested labels whose behavior is invalidated.
@@ -1984,7 +2160,7 @@ def _earliest_invalidated(requested_labels: list[str], invalidated: set[str]) ->
def _nearest_upstream_state_establisher(
- requested_labels: list[str], target_label: str, new_definition: Any
+ requested_labels: list[str], target_label: str, new_definition: object | None
) -> str | None:
by_label = _blocks_by_label(new_definition)
try:
@@ -2000,7 +2176,28 @@ def _nearest_upstream_state_establisher(
return None
-def _serialized_frontier_block_configs(frontier_labels: list[str], new_definition: Any) -> list[str]:
+def _block_can_start_browser_run(block: object) -> bool:
+ if _block_type_name(block) == BlockType.GOTO_URL.value:
+ return True
+ return _valid_runtime_anchor_url(getattr(block, "url", None)) is not None
+
+
+def _nearest_upstream_runnable_anchor(
+ workflow_labels: list[str], target_label: str, new_definition: object | None
+) -> str | None:
+ by_label = _blocks_by_label(new_definition)
+ try:
+ idx = workflow_labels.index(target_label)
+ except ValueError:
+ return None
+ for candidate in reversed(workflow_labels[:idx]):
+ block = by_label.get(candidate)
+ if block is not None and _block_can_start_browser_run(block):
+ return candidate
+ return workflow_labels[0] if workflow_labels[:idx] else None
+
+
+def _serialized_frontier_block_configs(frontier_labels: list[str], new_definition: object | None) -> list[str]:
by_label = _blocks_by_label(new_definition)
serialized_configs: list[str] = []
for label in frontier_labels:
@@ -2014,7 +2211,7 @@ def _serialized_frontier_block_configs(frontier_labels: list[str], new_definitio
return serialized_configs
-def _workflow_parameter_keys(definition: Any) -> set[str]:
+def _workflow_parameter_keys(definition: object | None) -> set[str]:
parameters = getattr(definition, "parameters", None) if definition else None
keys: set[str] = set()
if not parameters:
@@ -2031,7 +2228,7 @@ _CREDENTIAL_REAL_VALUE_SUFFIXES = ("_real_username", "_real_password")
def _classify_frontier_jinja_refs(
frontier_labels: list[str],
- new_definition: Any,
+ new_definition: object | None,
serialized_configs: list[str] | None = None,
) -> tuple[set[str], set[str], set[str]]:
"""Single pass over frontier blocks; returns ``(suffix_form_refs, block_form_refs, unknown_roots)``."""
@@ -2069,7 +2266,7 @@ def _classify_frontier_jinja_refs(
def _referenced_output_labels(
frontier_labels: list[str],
- new_definition: Any,
+ new_definition: object | None,
serialized_configs: list[str] | None = None,
) -> set[str]:
suffix_refs, block_form_refs, _ = _classify_frontier_jinja_refs(frontier_labels, new_definition, serialized_configs)
@@ -2078,7 +2275,7 @@ def _referenced_output_labels(
def _block_form_output_labels(
frontier_labels: list[str],
- new_definition: Any,
+ new_definition: object | None,
serialized_configs: list[str] | None = None,
) -> set[str]:
_, block_form_refs, _ = _classify_frontier_jinja_refs(frontier_labels, new_definition, serialized_configs)
@@ -2087,7 +2284,7 @@ def _block_form_output_labels(
def _unknown_jinja_roots(
frontier_labels: list[str],
- new_definition: Any,
+ new_definition: object | None,
serialized_configs: list[str] | None = None,
) -> set[str]:
_, _, unknown_roots = _classify_frontier_jinja_refs(frontier_labels, new_definition, serialized_configs)
@@ -2114,7 +2311,7 @@ def _summarize_action_trace(action_trace: list[dict[str, Any]] | None) -> list[s
return summary
-async def _get_prior_workflow_definition(ctx: AgentContext) -> Any:
+async def _get_prior_workflow_definition(ctx: AgentContext) -> object | None:
"""Hybrid: prefer ctx.last_workflow, fall back to DB fetch on cold start."""
last_workflow = getattr(ctx, "last_workflow", None)
if last_workflow is not None:
@@ -2239,26 +2436,27 @@ def _workflow_requires_canonical_persist(prior: Workflow | None, new: Workflow)
def _plan_frontier(
- ctx: Any,
+ ctx: AgentContext,
requested_labels: list[str],
- old_definition: Any,
- new_definition: Any,
+ old_definition: object | None,
+ new_definition: object | None,
) -> tuple[list[str], dict[str, Any], str | None]:
"""Plan the frontier execution.
Returns ``(labels_to_execute, block_outputs_to_seed, frontier_start_label)``.
Falls back to the full requested list on any ambiguity. When there is no
- workflow change (plain run path) the frontier is the first requested label
- and we seed any verified outputs referenced by the suffix.
+ workflow change (plain run path) the frontier is the first requested label,
+ and we seed verified outputs referenced by the suffix plus prior
+ browser-state outputs needed to start a downstream frontier.
"""
if not requested_labels:
return requested_labels, {}, None
if new_definition is None:
return requested_labels, {}, requested_labels[0]
- verified_outputs: dict[str, Any] = dict(getattr(ctx, "verified_block_outputs", {}) or {})
- verified_prefix: list[str] = list(getattr(ctx, "verified_prefix_labels", []) or [])
+ verified_outputs: dict[str, Any] = dict(ctx.verified_block_outputs or {})
+ verified_prefix: list[str] = list(ctx.verified_prefix_labels or [])
verified_prefix_set = set(verified_prefix)
# No old definition (cold start or parse failure) OR no diff signal → plain path.
@@ -2274,9 +2472,29 @@ def _plan_frontier(
earliest = _earliest_invalidated(requested_labels, invalidated)
if earliest is None:
- # No invalidation at all — unchanged request. Use first requested as frontier.
- frontier = requested_labels[0]
- return _seed_for_frontier(requested_labels, frontier, verified_outputs, new_definition)
+ # No invalidation at all — unchanged request. Continue from the
+ # first unverified requested label so a model may keep passing the
+ # complete chain while the tool advances the browser in small
+ # verified frontiers.
+ next_frontier = _first_unverified_requested_label(requested_labels, verified_prefix_set)
+ if next_frontier is not None:
+ return _seed_for_frontier(requested_labels, next_frontier, verified_outputs, new_definition)
+
+ # If the model accidentally asks to rerun an already-verified prefix,
+ # keep the browser moving forward instead of spending another tool call
+ # on work the current session has already covered.
+ workflow_labels = _workflow_definition_block_labels(new_definition)
+ next_workflow_frontier = _first_unverified_requested_label(workflow_labels, verified_prefix_set)
+ if next_workflow_frontier is not None:
+ frontier_idx = workflow_labels.index(next_workflow_frontier)
+ return _seed_for_frontier(
+ workflow_labels[: frontier_idx + 1],
+ next_workflow_frontier,
+ verified_outputs,
+ new_definition,
+ )
+
+ return _seed_for_frontier(requested_labels, requested_labels[0], verified_outputs, new_definition)
# Ensure the prefix before the earliest invalidated label is all in the
# verified prefix from a successful prior run. Otherwise we have no
@@ -2292,6 +2510,18 @@ def _plan_frontier(
# Case A — append-after-success. The earliest invalidated label is a
# new block that didn't exist in the prior definition, so the verified
# prefix represents the browser state just before it. Start there.
+ workflow_labels = _workflow_definition_block_labels(new_definition)
+ if earliest in workflow_labels:
+ workflow_prefix = workflow_labels[: workflow_labels.index(earliest)]
+ if not all(label in verified_prefix_set for label in workflow_prefix):
+ anchor = _nearest_upstream_runnable_anchor(workflow_labels, earliest, new_definition)
+ if anchor is not None:
+ return _seed_for_frontier(
+ workflow_labels[workflow_labels.index(anchor) : workflow_labels.index(earliest) + 1],
+ anchor,
+ verified_outputs,
+ new_definition,
+ )
return _seed_for_frontier(requested_labels, earliest, verified_outputs, new_definition)
# Edit-in-place. We lack a browser-anchor signal, so we cannot safely
@@ -2305,18 +2535,29 @@ def _plan_frontier(
return _seed_for_frontier(requested_labels, anchor, verified_outputs, new_definition)
+def _first_unverified_requested_label(requested_labels: list[str], verified_prefix_set: set[str]) -> str | None:
+ for label in requested_labels:
+ if label not in verified_prefix_set:
+ return label
+ return None
+
+
def _seed_for_frontier(
requested_labels: list[str],
frontier: str,
verified_outputs: dict[str, Any],
- new_definition: Any,
+ new_definition: object | None,
) -> tuple[list[str], dict[str, Any], str]:
try:
idx = requested_labels.index(frontier)
except ValueError:
return requested_labels, {}, requested_labels[0]
labels_to_execute = requested_labels[idx:]
- prefix_labels = requested_labels[:idx]
+ workflow_labels = _workflow_definition_block_labels(new_definition)
+ if frontier in workflow_labels:
+ prefix_labels = workflow_labels[: workflow_labels.index(frontier)]
+ else:
+ prefix_labels = requested_labels[:idx]
if not prefix_labels:
return labels_to_execute, {}, frontier
serialized_configs = _serialized_frontier_block_configs(labels_to_execute, new_definition)
@@ -2337,9 +2578,81 @@ def _seed_for_frontier(
seed[label] = verified_outputs[label]
if unknown_roots:
return requested_labels, {}, requested_labels[0]
+ by_label = _blocks_by_label(new_definition)
+ for label in prefix_labels:
+ block = by_label.get(label)
+ if block is None or _block_type_name(block) not in _BLOCK_TYPES_STATE_ESTABLISHER:
+ continue
+ if label in verified_outputs:
+ seed.setdefault(label, verified_outputs[label])
return labels_to_execute, seed, frontier
+_MAX_INCREMENTAL_PAGE_FRONTIER_LABELS = 2
+_PAGE_CHANGING_FRONTIER_BLOCK_TYPES: frozenset[str] = frozenset(
+ {
+ BlockType.ACTION.value,
+ BlockType.FILE_DOWNLOAD.value,
+ BlockType.FILE_UPLOAD.value,
+ BlockType.LOGIN.value,
+ BlockType.NAVIGATION.value,
+ }
+)
+
+
+def _frontier_block_type_names(labels: list[str], workflow_definition: object | None) -> list[str]:
+ by_label = _blocks_by_label(workflow_definition)
+ type_names: list[str] = []
+ for label in labels:
+ block = by_label.get(label)
+ if block is None:
+ continue
+ type_name = _block_type_name(block)
+ if type_name:
+ type_names.append(type_name)
+ return type_names
+
+
+def _frontier_has_several_page_changing_stages(labels: list[str], workflow_definition: object | None) -> bool:
+ type_names = _frontier_block_type_names(labels, workflow_definition)
+ if len(type_names) <= _MAX_INCREMENTAL_PAGE_FRONTIER_LABELS:
+ return False
+ page_changing_count = sum(1 for type_name in type_names if type_name in _PAGE_CHANGING_FRONTIER_BLOCK_TYPES)
+ return page_changing_count >= 2 or (page_changing_count >= 1 and len(type_names) >= 4)
+
+
+def _frontier_includes_required_runtime_anchor(block_labels: list[str], labels_to_execute: list[str]) -> bool:
+ if not block_labels or len(labels_to_execute) <= len(block_labels):
+ return False
+ return labels_to_execute[-len(block_labels) :] == block_labels
+
+
+def _frontier_run_size_error(
+ copilot_ctx: object,
+ block_labels: list[str],
+ labels_to_execute: list[str],
+ workflow_definition: object | None,
+) -> str | None:
+ if len(labels_to_execute) <= _MAX_INCREMENTAL_PAGE_FRONTIER_LABELS:
+ return None
+ if _frontier_includes_required_runtime_anchor(block_labels, labels_to_execute):
+ return None
+ if getattr(copilot_ctx, "build_phase", None) not in (BuildPhase.COMPOSING, BuildPhase.TESTING):
+ return None
+ if not _frontier_has_several_page_changing_stages(labels_to_execute, workflow_definition):
+ return None
+
+ suggested = labels_to_execute[:_MAX_INCREMENTAL_PAGE_FRONTIER_LABELS]
+ remaining = labels_to_execute[_MAX_INCREMENTAL_PAGE_FRONTIER_LABELS:]
+ return (
+ "Workflow validation failed: this browser test frontier is too long for a multi-stage "
+ "page-changing workflow. Keep the same complete workflow YAML, but shrink only the "
+ f"block_labels argument to the next 1-2 unverified labels: {suggested!r}. "
+ f"Do not remove later blocks from the YAML; test them after this frontier succeeds. "
+ f"Deferred labels: {remaining!r}. Requested labels: {block_labels!r}."
+ )
+
+
# Watchdog exit reasons. ``success`` means the run reached a trustworthy
# terminal status inside the poll loop OR after the post-drain reconcile.
# The three non-success reasons share the reconcile path but produce distinct
@@ -2472,7 +2785,11 @@ async def _watchdog_error_message(
f"Run ID: {workflow_run_id}.\n"
f"Next step: call get_run_results with this workflow_run_id to inspect what "
f"the cancelled run actually completed (the in-flight block was cancelled "
- f"mid-execution and may have left partial side effects). Then call "
+ f"mid-execution and may have left partial side effects). If the result "
+ f"includes a current_url, inspect that current page before any further "
+ f'block-running call. Use inspect_page_for_composition(target_url="current_page"), '
+ f"evaluate, or get_browser_screenshot to decide whether the answer is already "
+ f"visible or which page-state change is still missing. Only then call "
f"update_and_run_blocks with a smaller chain — the first 1-2 unverified "
f"blocks. Verified-prefix state is preserved, so the next call only re-runs "
f"from the new frontier. Do NOT retry the same chain unchanged — a longer "
@@ -2532,6 +2849,21 @@ def _workflow_with_runtime_block_goal_context(workflow: Workflow, ctx: CopilotCo
return wrap_workflow_block_goals(workflow, block_goal_main_goal)
+def _valid_runtime_anchor_url(value: object) -> str | None:
+ if not isinstance(value, str):
+ return None
+ url = value.strip()
+ if not url or url in {"about:blank", ":"}:
+ return None
+ try:
+ parsed = urlparse(url)
+ except ValueError:
+ return None
+ if parsed.scheme not in {"http", "https"} or not parsed.netloc:
+ return None
+ return url
+
+
async def _run_blocks_and_collect_debug(
params: dict[str, Any],
ctx: CopilotContext,
@@ -2821,6 +3153,7 @@ async def _run_blocks_and_collect_debug(
user_failure_reason = _watchdog_user_failure_reason(
exit_reason, workflow_run.workflow_run_id, budget_seconds, run
)
+ current_url, page_title = await _fallback_page_info(ctx)
result: dict[str, Any] = {
"ok": False,
"error": error_msg,
@@ -2828,6 +3161,8 @@ async def _run_blocks_and_collect_debug(
"workflow_run_id": workflow_run.workflow_run_id,
"overall_status": run.status if run is not None else None,
"failure_reason": user_failure_reason,
+ "current_url": current_url,
+ "page_title": page_title,
},
}
if exit_reason == "per_tool_budget":
@@ -2977,6 +3312,9 @@ async def _run_blocks_and_collect_debug(
existing_prefix.append(label)
existing_set.add(label)
ctx.verified_prefix_labels = existing_prefix
+ verified_current_url = _valid_runtime_anchor_url(current_url)
+ if verified_current_url is not None:
+ ctx.verified_prefix_current_url = verified_current_url
return build_run_blocks_response(run_ok, result_data)
@@ -2994,6 +3332,12 @@ async def _get_run_results(params: dict[str, Any], ctx: AgentContext) -> dict[st
),
}
workflow_run_id = pending_run_id
+ if not workflow_run_id:
+ same_turn_run_id = getattr(ctx, "last_successful_run_blocks_workflow_run_id", None)
+ if not isinstance(same_turn_run_id, str) or not same_turn_run_id:
+ same_turn_run_id = getattr(ctx, "last_run_blocks_workflow_run_id", None)
+ if isinstance(same_turn_run_id, str) and same_turn_run_id:
+ workflow_run_id = same_turn_run_id
if not workflow_run_id:
# Include every final state so the agent can inspect failures via the
@@ -3052,6 +3396,10 @@ async def _get_run_results(params: dict[str, Any], ctx: AgentContext) -> dict[st
"overall_status": run.status,
"blocks": results,
}
+ current_url, page_title = await _fallback_page_info(ctx)
+ if current_url:
+ result_data["current_url"] = current_url
+ result_data["page_title"] = page_title
if getattr(run, "failure_reason", None):
result_data["failure_reason"] = run.failure_reason
@@ -3221,29 +3569,36 @@ def _normalize_evaluate_page_schema(observed_data: object) -> dict[str, Any]:
}
-def _record_browser_observation_evidence(
+def _record_composition_page_observation(
ctx: AgentContext,
*,
source_tool: str,
- current_url: str,
- page_title: str = "",
+ url: str,
+ title: str = "",
observed_data: object | None = None,
) -> None:
- if not current_url:
+ if not url:
return
existing = ctx.composition_page_evidence
if isinstance(existing, dict) and existing.get("source_tool") == "inspect_page_for_composition":
return
+
evidence: dict[str, Any] = {
- "inspected_url": current_url,
- "current_url": current_url,
- "page_title": page_title,
+ "inspected_url": url,
+ "current_url": url,
+ "page_title": title[:240],
"forms": [],
+ "navigation_targets": [],
"result_containers": [],
"anti_bot_indicators": [],
+ "evidence_confidence": 0.0,
"source_tool": source_tool,
"observed_after_workflow_run": False,
}
+ if isinstance(observed_data, dict):
+ observed_title = observed_data.get("title")
+ if isinstance(observed_title, str) and observed_title and not evidence["page_title"]:
+ evidence["page_title"] = observed_title[:240]
if source_tool == "get_browser_screenshot":
evidence.update(
{
@@ -3576,19 +3931,15 @@ async def _screenshot_post_hook(
ctx: AgentContext,
) -> dict[str, Any]:
if result.get("ok") and result.get("data"):
+ _mark_page_inspected(ctx)
data = result["data"]
url, title = await _resolve_url_title(raw, ctx)
+ _record_composition_page_observation(ctx, source_tool="get_browser_screenshot", url=url, title=title)
result["data"] = {
"screenshot_base64": data.get("data", ""),
"url": url,
"title": title,
}
- _record_browser_observation_evidence(
- ctx,
- source_tool="get_browser_screenshot",
- current_url=url,
- page_title=title,
- )
return result
@@ -3630,15 +3981,21 @@ async def _evaluate_post_hook(
ctx: AgentContext,
) -> dict[str, Any]:
if result.get("ok") and result.get("data"):
+ _mark_page_inspected(ctx)
result["data"].pop("sdk_equivalent", None)
if "url" not in result["data"]:
url, _ = await _resolve_url_title(raw, ctx)
if url:
result["data"]["url"] = url
- _record_browser_observation_evidence(
+ url = str(result["data"].get("url") or "")
+ title = str(result["data"].get("title") or "")
+ if not title:
+ _, title = await _resolve_url_title(raw, ctx)
+ _record_composition_page_observation(
ctx,
source_tool="evaluate",
- current_url=str(result["data"].get("url") or ""),
+ url=url,
+ title=title,
observed_data=result["data"],
)
return result
@@ -3904,9 +4261,21 @@ def _analyze_run_blocks(result: dict[str, Any]) -> tuple[str | None, bool, list[
# Collect texts for scanning and data-block stats in one pass
texts_to_scan: list[str] = []
+ error = result.get("error")
+ if isinstance(error, str):
+ texts_to_scan.append(error)
html = data.get("visible_elements_html")
if isinstance(html, str):
texts_to_scan.append(html)
+ failure_reason = data.get("failure_reason")
+ if isinstance(failure_reason, str):
+ texts_to_scan.append(failure_reason)
+ page_title = data.get("page_title")
+ if isinstance(page_title, str):
+ texts_to_scan.append(page_title)
+ action_trace_summary = data.get("action_trace_summary")
+ if isinstance(action_trace_summary, list):
+ texts_to_scan.extend(str(item) for item in action_trace_summary if isinstance(item, str))
has_data_blocks = False
any_data_output = False
@@ -3938,6 +4307,22 @@ def _analyze_run_blocks(result: dict[str, Any]) -> tuple[str | None, bool, list[
return anti_bot_match, empty_data_blocks, categories
+def _composition_anti_bot_reason(copilot_ctx: object) -> str | None:
+ evidence = getattr(copilot_ctx, "composition_page_evidence", None)
+ if not isinstance(evidence, dict):
+ return None
+ indicators = evidence.get("anti_bot_indicators")
+ challenge_controls = evidence.get("challenge_controls")
+ normalized_indicators = (
+ [str(item) for item in indicators if isinstance(item, str)] if isinstance(indicators, list) else []
+ )
+ control_count = len(challenge_controls) if isinstance(challenge_controls, list) else 0
+ if not normalized_indicators and control_count == 0:
+ return None
+ details = ", ".join(normalized_indicators[:4]) or f"{control_count} challenge control(s)"
+ return f"Observed anti-bot challenge evidence before the run: {details}"
+
+
# Generic failure-reason template emitted by the shared agent when the
# browser-side scraper catches ScrapingFailed / NoElementFound. Matching on
# the template (not the shared classifier) lets the copilot notice a repeated
@@ -3990,11 +4375,17 @@ def _detect_non_retriable_nav_error(result: dict[str, Any]) -> str | None:
def _record_run_blocks_result(copilot_ctx: Any, result: dict[str, Any]) -> None:
run_ok = bool(result.get("ok", False))
+ data = result.get("data")
+ run_id = data.get("workflow_run_id") if isinstance(data, dict) else None
+ copilot_ctx.last_run_blocks_workflow_run_id = run_id if isinstance(run_id, str) else None
+ copilot_ctx.last_successful_run_blocks_workflow_run_id = run_id if run_ok and isinstance(run_id, str) else None
# Watchdog cancels normally count as ok=False; only a coincident total
# timeout softens to ``None`` to keep the unvalidated WIP rescue open.
cancelled_by_watchdog = result.get(_INTERNAL_RUN_CANCELLED_BY_WATCHDOG_KEY) is True
timeout_latched = bool(copilot_ctx.copilot_total_timeout_exceeded)
copilot_ctx.last_test_ok = None if (cancelled_by_watchdog and timeout_latched) else run_ok
+ copilot_ctx.last_full_workflow_test_ok = False
+ copilot_ctx.last_unverified_block_labels = _unverified_current_workflow_labels(copilot_ctx)
copilot_ctx.last_test_failure_reason = None
copilot_ctx.last_test_suspicious_success = False
copilot_ctx.suspicious_success_nudge_count = 0
@@ -4004,6 +4395,8 @@ def _record_run_blocks_result(copilot_ctx: Any, result: dict[str, Any]) -> None:
copilot_ctx.last_test_non_retriable_nav_error = None
anti_bot_match, empty_data_blocks, failure_categories = _analyze_run_blocks(result)
+ if not anti_bot_match:
+ anti_bot_match = _composition_anti_bot_reason(copilot_ctx)
if anti_bot_match:
copilot_ctx.last_test_anti_bot = anti_bot_match
if failure_categories:
@@ -4013,6 +4406,13 @@ def _record_run_blocks_result(copilot_ctx: Any, result: dict[str, Any]) -> None:
if isinstance(top_category, str):
copilot_ctx.last_failure_category_top = top_category
+ if copilot_ctx.last_failure_category_top == PER_TOOL_BUDGET_FAILURE_CATEGORY and isinstance(data, dict):
+ current_url = _valid_runtime_anchor_url(data.get("current_url"))
+ if current_url is not None:
+ copilot_ctx.post_budget_page_inspection_required = True
+ copilot_ctx.post_budget_page_inspection_url = current_url
+ copilot_ctx.post_budget_page_inspection_run_id = run_id if isinstance(run_id, str) else None
+
# A fresh budget trip on a different chain should get the dedicated split
# nudge again rather than falling through to the generic failed-test path,
# so reset the cap when the latest run is not itself a budget trip.
@@ -4026,6 +4426,7 @@ def _record_run_blocks_result(copilot_ctx: Any, result: dict[str, Any]) -> None:
data["failure_categories"] = failure_categories
if run_ok:
+ _mark_page_inspected(copilot_ctx)
if empty_data_blocks:
copilot_ctx.last_test_ok = None
copilot_ctx.last_test_suspicious_success = True
@@ -4047,8 +4448,17 @@ def _record_run_blocks_result(copilot_ctx: Any, result: dict[str, Any]) -> None:
# Real success: clear the signature latch so a subsequent bad URL in
# the same session can re-fire the stop nudge.
copilot_ctx.non_retriable_nav_error_last_emitted_signature = None
- copilot_ctx.last_good_workflow = copilot_ctx.last_workflow
- copilot_ctx.last_good_workflow_yaml = copilot_ctx.last_workflow_yaml
+ unverified = _unverified_current_workflow_labels(copilot_ctx)
+ copilot_ctx.last_unverified_block_labels = unverified
+ if not unverified:
+ copilot_ctx.last_full_workflow_test_ok = True
+ copilot_ctx.last_good_workflow = copilot_ctx.last_workflow
+ copilot_ctx.last_good_workflow_yaml = copilot_ctx.last_workflow_yaml
+ else:
+ copilot_ctx.last_test_failure_reason = (
+ "The last run verified only the current browser frontier; unverified workflow blocks remain: "
+ + ", ".join(unverified[:8])
+ )
update_repeated_failure_state(copilot_ctx, result)
return
@@ -4121,11 +4531,10 @@ async def update_workflow_tool(
reusable domain value the user supplies, not the page widget or action used
to enter it.
- Use browser inspection while building to fill knowledge gaps about page
- controls, result layout, and current URLs. Only refine URL params when they
- are grounded in observed DOM/link/form state or observed URL deltas.
- Browser inspection is build-time context; add durable workflow blocks only
- for the reusable actions/checks the workflow actually needs.
+ Use browser inspection and run evidence to fill knowledge gaps while
+ building or editing the workflow. Do not invent URL params, form fields,
+ result affordances, or page structure from memory; ground workflow blocks
+ in observed MCP evidence or information the user supplied.
"""
copilot_ctx = ctx.context
arguments = {"workflow_yaml": workflow_yaml}
@@ -4193,20 +4602,12 @@ async def list_credentials_tool(
return json.dumps(sanitized)
-async def _frontier_plan_for_current_workflow(
- ctx: AgentContext, block_labels: list[str]
-) -> tuple[list[str], dict[str, Any], str | None]:
- """Plan execution for the plain (no YAML update) path."""
- prior_definition = await _get_prior_workflow_definition(ctx)
- return _plan_frontier(ctx, block_labels, prior_definition, prior_definition)
-
-
def _run_blocks_span_data(
block_labels: list[str],
labels_to_execute: list[str],
frontier_start_label: str | None,
seeded_outputs: dict[str, Any],
- ctx: Any,
+ ctx: object,
) -> dict[str, Any]:
return {
"requested_block_labels": block_labels,
@@ -4218,6 +4619,27 @@ def _run_blocks_span_data(
}
+def _frontier_run_size_result(
+ error: str,
+ block_labels: list[str],
+ labels_to_execute: list[str],
+) -> dict[str, Any]:
+ return {
+ "ok": False,
+ "error": error,
+ "data": {
+ "workflow_run_id": None,
+ "overall_status": "skipped",
+ "workflow_run_skipped": True,
+ "requested_block_labels": list(block_labels),
+ "executed_block_labels": [],
+ "planned_block_labels": list(labels_to_execute),
+ "suggested_block_labels": list(labels_to_execute[:_MAX_INCREMENTAL_PAGE_FRONTIER_LABELS]),
+ "deferred_block_labels": list(labels_to_execute[_MAX_INCREMENTAL_PAGE_FRONTIER_LABELS:]),
+ },
+ }
+
+
@function_tool(
name_override="run_blocks_and_collect_debug",
timeout=RUN_BLOCKS_SAFETY_CEILING_SECONDS,
@@ -4250,11 +4672,10 @@ async def run_blocks_tool(
the inline value via `parameters`; stop and follow the CREDENTIAL
HANDLING refusal rule in the system prompt.
- When a prior `goto_url` used URL params for dynamic page state, the
- blocks you run must include live-page verification before extraction. If
- the visible state is uncertain or only partially applied, inspect it
- through a `code` or `validation` block, or apply missing state through a
- `navigation` block, instead of retrying guessed URL params.
+ Use browser inspection and run evidence to fill knowledge gaps before
+ changing the workflow. If visible state is uncertain, inspect the live
+ page and then compose the next normal workflow action from observed
+ evidence instead of retrying guessed URL params or page structure.
"""
copilot_ctx = ctx.context
arguments = {"block_labels": block_labels, "parameters": parameters or {}}
@@ -4266,9 +4687,20 @@ async def run_blocks_tool(
if loop_error:
return _diagnosis_repair_tool_error(copilot_ctx, "run_blocks_and_collect_debug", loop_error)
- labels_to_execute, block_outputs_to_seed, frontier_start_label = await _frontier_plan_for_current_workflow(
- copilot_ctx, block_labels
+ prior_definition = await _get_prior_workflow_definition(copilot_ctx)
+ labels_to_execute, block_outputs_to_seed, frontier_start_label = _plan_frontier(
+ copilot_ctx, block_labels, prior_definition, prior_definition
)
+ frontier_error = _frontier_run_size_error(copilot_ctx, block_labels, labels_to_execute, prior_definition)
+ if frontier_error:
+ result = _frontier_run_size_result(frontier_error, block_labels, labels_to_execute)
+ record_tool_step_result_for_ctx(copilot_ctx, "run_blocks_and_collect_debug", arguments, result)
+ _record_diagnosis_repair_contract(
+ copilot_ctx,
+ source_tool="run_blocks_and_collect_debug",
+ result=result,
+ )
+ return json.dumps(result)
with copilot_span(
"run_blocks",
@@ -4347,6 +4779,9 @@ async def update_and_run_blocks_tool(
"""Update the workflow YAML and immediately run the specified blocks in one step.
Use this instead of calling update_workflow and run_blocks_and_collect_debug separately.
The workflow must validate successfully before blocks are run.
+ `block_labels` may be a tested frontier subset of the full workflow YAML;
+ save the complete reusable workflow, then run only the next 1-2 unverified
+ blocks when a long form/search/result chain can be verified incrementally.
Top-level workflow parameter keys appear in the run-input UI. When you
add runtime inputs in `workflow_definition.parameters`, name keys for the
@@ -4491,6 +4926,20 @@ async def update_and_run_blocks_tool(
labels_to_execute, block_outputs_to_seed, frontier_start_label = _plan_frontier(
copilot_ctx, block_labels, prior_definition, new_definition
)
+ frontier_error = _frontier_run_size_error(copilot_ctx, block_labels, labels_to_execute, new_definition)
+ if frontier_error:
+ result = _frontier_run_size_result(frontier_error, block_labels, labels_to_execute)
+ data = result.get("data")
+ if isinstance(data, dict):
+ data["workflow_updated"] = True
+ record_tool_step_result_for_ctx(copilot_ctx, "update_and_run_blocks", arguments, result)
+ _record_diagnosis_repair_contract(
+ copilot_ctx,
+ source_tool="update_and_run_blocks",
+ result=result,
+ workflow_updated=True,
+ )
+ return json.dumps(result)
with copilot_span(
"run_blocks",
@@ -4531,6 +4980,8 @@ async def update_and_run_blocks_tool(
_DISCOVERY_PER_CHAT_BUDGET = 3
_DISCOVERY_PER_TURN_BUDGET = 1
+_COMPOSITION_INSPECTION_PER_CHAT_BUDGET = 6
+_COMPOSITION_INSPECTION_PER_TURN_BUDGET = 4
_DISCOVERY_WALL_CLOCK_SECONDS = 60.0
_DISCOVERY_STEP_CAP = 8
_DISCOVERY_EVIDENCE_TRAIL_MAX = 8
@@ -5030,6 +5481,29 @@ async def _inspect_page_for_composition_impl(
record_tool_step_result_for_ctx(copilot_ctx, "inspect_page_for_composition", arguments, result)
return result
+ if copilot_ctx.page_inspection_calls_this_turn >= _COMPOSITION_INSPECTION_PER_TURN_BUDGET:
+ result = {
+ "ok": False,
+ "data": None,
+ "error": (
+ "inspect_page_for_composition reached the page-inspection budget for this turn. "
+ "Compose from existing evidence or ask for clarification if inspection still cannot determine "
+ "required page inputs."
+ ),
+ }
+ record_tool_step_result_for_ctx(copilot_ctx, "inspect_page_for_composition", arguments, result)
+ return result
+
+ cumulative = copilot_ctx.prior_page_inspection_calls_made + copilot_ctx.page_inspection_calls_this_turn
+ if cumulative >= _COMPOSITION_INSPECTION_PER_CHAT_BUDGET:
+ result = {
+ "ok": False,
+ "data": None,
+ "error": "inspect_page_for_composition has reached the page-inspection budget for this chat. Compose from existing evidence or ask for clarification.",
+ }
+ record_tool_step_result_for_ctx(copilot_ctx, "inspect_page_for_composition", arguments, result)
+ return result
+
use_current_page = (target_url or "").strip().lower() in _CURRENT_PAGE_INSPECTION_TARGETS
entry_url: str
kind: str
@@ -5113,7 +5587,9 @@ async def _inspect_page_for_composition_impl(
"observed_after_workflow_run": True,
}
+ copilot_ctx.page_inspection_calls_this_turn += 1
copilot_ctx.composition_page_evidence = evidence
+ _mark_page_inspected(copilot_ctx)
result = {"ok": True, "data": evidence}
record_tool_step_result_for_ctx(copilot_ctx, "inspect_page_for_composition", arguments, result)
return result
@@ -5218,7 +5694,25 @@ async def _discovery_walk(
title_score = _discovery_title_score(page_title, intent_tokens)
- if intent_tokens and title_score >= 2:
+ best_score = 0
+ best_href: str | None = None
+ best_anchor: dict[str, str] | None = None
+ for anchor in anchors:
+ score = _discovery_anchor_score(
+ anchor.get("text", ""),
+ anchor.get("title", ""),
+ anchor.get("href", ""),
+ intent_tokens,
+ )
+ if score > best_score:
+ resolved = _discovery_resolve_href(current_url, anchor.get("href", ""))
+ if resolved is None:
+ continue
+ best_score = score
+ best_href = resolved
+ best_anchor = anchor
+
+ if intent_tokens and title_score >= 2 and (form_fields or best_score <= title_score):
confidence = min(1.0, title_score / max(1, len(intent_tokens)))
return _discovery_build_result(
candidate_url=current_url,
@@ -5247,24 +5741,6 @@ async def _discovery_walk(
failure_reason=None,
)
- best_score = 0
- best_href: str | None = None
- best_anchor: dict[str, str] | None = None
- for anchor in anchors:
- score = _discovery_anchor_score(
- anchor.get("text", ""),
- anchor.get("title", ""),
- anchor.get("href", ""),
- intent_tokens,
- )
- if score > best_score:
- resolved = _discovery_resolve_href(current_url, anchor.get("href", ""))
- if resolved is None:
- continue
- best_score = score
- best_href = resolved
- best_anchor = anchor
-
if best_score == 0 or best_href is None:
return _discovery_build_result(
candidate_url=None,
@@ -5447,18 +5923,21 @@ async def inspect_page_for_composition_tool(
"""Inspect a known page before composing form/search workflow blocks.
Use this after the entrypoint URL is known and before authoring blocks that
- fill fields, submit searches, filter results, or expand result rows. Pass
- target_url="current_page" after partial workflow runs to inspect the live
- browser page without navigating away. It returns observed page evidence:
- current URL, title, navigation targets, form fields with labels and selectors,
- submit/search controls, result containers, anti-bot indicators, and bounded
- visual challenge evidence when DOM evidence shows challenge state. Do NOT
- paste the evidence into workflow YAML; use it to ground concise block prompts.
- If a block run changes pages, inspect the reached page before authoring
- downstream form/search/result blocks. If the evidence shows required fields
- or controls that the user did not supply enough information for, ASK_QUESTION
- with that observed missing input. If evidence is sufficient, compose and run
- workflow blocks from the observed fields.
+ fill fields, submit searches, filter results, or expand result rows. It
+ can also inspect the current browser page after a run by passing
+ target_url="current_page"; use that after partial/budgeted runs so you do
+ not replay a search that already advanced the page.
+
+ Returns observed page evidence: current URL, title, navigation targets, form
+ fields with labels and selectors, submit/search controls, result containers,
+ compact visible text excerpts, anti-bot indicators, and bounded visual
+ challenge evidence when DOM evidence shows challenge state. Do NOT paste the
+ evidence into workflow YAML; use it to ground concise block prompts. If a
+ block run changes pages, inspect the reached page before authoring downstream
+ form/search/result blocks. If the
+ evidence shows required fields or controls that the user did not supply
+ enough information for, ASK_QUESTION with that observed missing input. If
+ evidence is sufficient, compose and run workflow blocks from the observed fields.
If challenge_state.gates_submit_controls is true, treat challenge resolution
as a prerequisite for submit/search; do not click a submit control while the
latest inspected evidence says it is disabled.
diff --git a/tests/unit/test_copilot_agent_helpers.py b/tests/unit/test_copilot_agent_helpers.py
index 49c00f5f4..cb840bffc 100644
--- a/tests/unit/test_copilot_agent_helpers.py
+++ b/tests/unit/test_copilot_agent_helpers.py
@@ -13,6 +13,7 @@ import yaml
from skyvern.forge.sdk.api.llm.exceptions import LLMProviderError
from skyvern.forge.sdk.copilot import agent as agent_module
+from skyvern.forge.sdk.copilot.build_phase import BuildPhase
from skyvern.forge.sdk.copilot.config import CopilotConfig
from skyvern.forge.sdk.copilot.enforcement import (
CopilotNonRetriableNavError,
@@ -301,6 +302,17 @@ class TestVerifiedWorkflowOrNone:
)
assert _verified_workflow_or_none(ctx) == (wf, "foo: bar")
+ def test_zeros_when_only_frontier_tested_successfully(self) -> None:
+ from skyvern.forge.sdk.copilot.agent import _verified_workflow_or_none
+
+ ctx = _ctx(
+ last_workflow=self._wf(),
+ last_workflow_yaml="foo: bar",
+ last_test_ok=True,
+ last_full_workflow_test_ok=False,
+ )
+ assert _verified_workflow_or_none(ctx) == (None, None)
+
def test_zeros_when_test_failed(self) -> None:
from skyvern.forge.sdk.copilot.agent import _verified_workflow_or_none
@@ -791,7 +803,12 @@ class TestTranslateToAgentResultGating:
lambda **kwargs: new_wf,
)
- ctx = _ctx(last_workflow=old_wf, last_workflow_yaml="old: yaml", last_test_ok=True)
+ ctx = _ctx(
+ last_workflow=old_wf,
+ last_workflow_yaml="old: yaml",
+ last_test_ok=True,
+ last_full_workflow_test_ok=True,
+ )
result = _fake_run_result(
{
"type": "REPLACE_WORKFLOW",
@@ -842,7 +859,13 @@ workflow_definition:
next_block_label: null
navigation_goal: Search example.com for sample beta.
"""
- ctx = _ctx(workflow_yaml=prior_yaml, last_workflow_yaml=prior_yaml, last_workflow=object(), last_test_ok=True)
+ ctx = _ctx(
+ workflow_yaml=prior_yaml,
+ last_workflow_yaml=prior_yaml,
+ last_workflow=object(),
+ last_test_ok=True,
+ last_full_workflow_test_ok=True,
+ )
result = _fake_run_result(
{"type": "REPLACE_WORKFLOW", "user_response": "Here you go.", "workflow_yaml": submitted_yaml}
)
@@ -857,6 +880,43 @@ workflow_definition:
assert agent_result.updated_workflow is None
assert agent_result.workflow_yaml is None
+ def test_inline_replace_workflow_rejects_page_dependent_blocks_without_inspection(self, monkeypatch) -> None:
+ process_mock = MagicMock(return_value=SimpleNamespace(name="new"))
+ monkeypatch.setattr("skyvern.forge.sdk.copilot.tools._process_workflow_yaml", process_mock)
+
+ submitted_yaml = """
+title: Lookup example
+workflow_definition:
+ parameters: []
+ blocks:
+ - block_type: goto_url
+ label: open_lookup
+ url: https://example.com/lookup
+ - block_type: navigation
+ label: search_lookup
+ navigation_goal: Enter the person name into the search field and click Search.
+"""
+ ctx = _ctx(
+ workflow_yaml="",
+ build_phase=BuildPhase.COMPOSING,
+ turn_intent=TurnIntent(mode=TurnIntentMode.BUILD),
+ composition_page_evidence=None,
+ )
+ result = _fake_run_result(
+ {"type": "REPLACE_WORKFLOW", "user_response": "Here you go.", "workflow_yaml": submitted_yaml}
+ )
+
+ agent_result = asyncio.run(
+ agent_module._translate_to_agent_result(
+ result, ctx, global_llm_context=None, chat_request=_chat_request(), organization_id="org-1"
+ )
+ )
+
+ process_mock.assert_not_called()
+ assert "inspect_page_for_composition" in agent_result.user_response
+ assert agent_result.updated_workflow is None
+ assert agent_result.workflow_yaml is None
+
def test_inline_replace_with_invalid_yaml_keeps_prior_pass(self, monkeypatch) -> None:
# _process_workflow_yaml raising on a malformed REPLACE must leave
# ctx untouched — no spurious last_test_ok reset, no workflow swap —
@@ -1168,6 +1228,7 @@ workflow_definition:
last_workflow=wf,
last_workflow_yaml="title: drafted",
last_test_ok=True,
+ last_full_workflow_test_ok=True,
last_update_block_count=8,
)
result = _fake_run_result(
@@ -1235,6 +1296,7 @@ workflow_definition:
last_workflow=wf,
last_workflow_yaml="title: drafted",
last_test_ok=True,
+ last_full_workflow_test_ok=True,
last_update_block_count=2,
)
result = _fake_run_result(
@@ -1472,7 +1534,12 @@ workflow_definition:
# A verified-but-non-terminal workflow built this turn must not surface
# alongside the question; the clear flag also nulls any stale prior ghost.
verified_wf = SimpleNamespace(name="verified-partial")
- ctx = _ctx(last_workflow=verified_wf, last_workflow_yaml="verified: yaml", last_test_ok=True)
+ ctx = _ctx(
+ last_workflow=verified_wf,
+ last_workflow_yaml="verified: yaml",
+ last_test_ok=True,
+ last_full_workflow_test_ok=True,
+ )
result = _fake_run_result({"type": "ASK_QUESTION", "user_response": "Need credentials before I can continue."})
agent_result = asyncio.run(
agent_module._translate_to_agent_result(
@@ -1503,7 +1570,12 @@ workflow_definition:
# Differential: a REPLY turn surfaces the verified workflow and leaves
# any prior persisted proposal untouched.
verified_wf = SimpleNamespace(name="final")
- ctx = _ctx(last_workflow=verified_wf, last_workflow_yaml="final: yaml", last_test_ok=True)
+ ctx = _ctx(
+ last_workflow=verified_wf,
+ last_workflow_yaml="final: yaml",
+ last_test_ok=True,
+ last_full_workflow_test_ok=True,
+ )
result = _fake_run_result({"type": "REPLY", "user_response": "Here you go."})
agent_result = asyncio.run(
agent_module._translate_to_agent_result(
diff --git a/tests/unit/test_copilot_blocker_lifecycle.py b/tests/unit/test_copilot_blocker_lifecycle.py
index a6bf1ae49..8a89d5a86 100644
--- a/tests/unit/test_copilot_blocker_lifecycle.py
+++ b/tests/unit/test_copilot_blocker_lifecycle.py
@@ -58,6 +58,14 @@ def test_loop_blocker_clears_on_progress_tool_success() -> None:
assert ctx.blocker_signal is None
+def test_loop_blocker_stays_sticky_on_metadata_only_success() -> None:
+ ctx = _ctx()
+ signal = _signal(kind="loop_detected", cleared_by=frozenset(), reason="loop_detected_generic")
+ ctx.blocker_signal = signal
+ record_tool_step_result_for_ctx(ctx, "list_credentials", None, {"ok": True})
+ assert ctx.blocker_signal is signal
+
+
def test_terminal_tool_error_stays_sticky_on_any_success() -> None:
ctx = _ctx()
signal = _signal(kind="tool_error", cleared_by=frozenset(), reason="tool_error_repeated_action_abort")
@@ -90,6 +98,61 @@ def test_per_tool_budget_blocker_clears_on_update_and_run_blocks_success() -> No
assert ctx.blocker_signal is None
+def test_per_tool_budget_blocker_clears_on_live_page_evidence_success() -> None:
+ from skyvern.forge.sdk.copilot.tools import _per_tool_budget_problem_rerun_signal, _tool_loop_error
+
+ ctx = _ctx()
+ ctx.per_tool_budget_problem_block_labels = ["heavy_navigation"]
+ signal = _per_tool_budget_problem_rerun_signal(ctx, None, "update_and_run_blocks")
+ assert signal is not None
+ assert "evaluate" in signal.cleared_by_tools
+ ctx.blocker_signal = signal
+
+ record_tool_step_result_for_ctx(ctx, "evaluate", {"script": "document.body.innerText"}, {"ok": True})
+
+ assert ctx.blocker_signal is None
+ assert ctx.per_tool_budget_problem_block_labels == ["heavy_navigation"]
+ rerun_msg = _tool_loop_error(ctx, "update_and_run_blocks", {"block_labels": ["heavy_navigation"]})
+ assert rerun_msg is not None
+ assert ctx.blocker_signal is not None
+ assert ctx.blocker_signal.internal_reason_code == "tool_error_per_tool_budget_rerun"
+
+
+def test_per_tool_budget_blocker_clears_on_run_results_read_success() -> None:
+ from skyvern.forge.sdk.copilot.tools import _per_tool_budget_problem_rerun_signal
+
+ ctx = _ctx()
+ ctx.per_tool_budget_problem_block_labels = ["heavy_navigation"]
+ signal = _per_tool_budget_problem_rerun_signal(ctx, None, "update_and_run_blocks")
+ assert signal is not None
+ assert "get_run_results" in signal.cleared_by_tools
+ ctx.blocker_signal = signal
+
+ record_tool_step_result_for_ctx(ctx, "get_run_results", {"workflow_run_id": "wr_1"}, {"ok": True})
+
+ assert ctx.blocker_signal is None
+ assert ctx.per_tool_budget_problem_block_labels == ["heavy_navigation"]
+
+
+def test_per_tool_budget_blocker_stays_on_failed_inspection() -> None:
+ from skyvern.forge.sdk.copilot.tools import _per_tool_budget_problem_rerun_signal
+
+ ctx = _ctx()
+ ctx.per_tool_budget_problem_block_labels = ["heavy_navigation"]
+ signal = _per_tool_budget_problem_rerun_signal(ctx, None, "update_and_run_blocks")
+ assert signal is not None
+ ctx.blocker_signal = signal
+
+ record_tool_step_result_for_ctx(
+ ctx,
+ "inspect_page_for_composition",
+ {"target_url": "current_page"},
+ {"ok": False, "error": "inspection budget reached"},
+ )
+
+ assert ctx.blocker_signal is signal
+
+
def test_reconciliation_canceled_status_replaces_no_input_signal_with_requires_input() -> None:
"""When the reconciliation read resolves the pending run as canceled, the
'I'll check what happened' blocker is replaced with one that asks the
@@ -177,3 +240,52 @@ def test_reconciliation_signal_steering_text_does_not_leak_through_user_facing_c
# If a future refactor pipes steering text into the renderer, this fails.
with pytest.raises(ValueError):
assert_clean_user_facing_text(ctx.blocker_signal.agent_steering_text)
+
+
+def test_reconciliation_requires_input_clears_after_direct_browser_progress() -> None:
+ from skyvern.forge.sdk.copilot.tools import _maybe_clear_reconciliation_flag
+ from skyvern.forge.sdk.workflow.models.workflow import WorkflowRunStatus
+
+ ctx = _ctx()
+ ctx.pending_reconciliation_run_id = "wr_pending"
+ result = {
+ "ok": True,
+ "data": {
+ "workflow_run_id": "wr_pending",
+ "overall_status": WorkflowRunStatus.canceled.value,
+ },
+ }
+ _maybe_clear_reconciliation_flag(ctx, result)
+
+ assert ctx.pending_reconciliation_requires_user_input is True
+ assert ctx.blocker_signal is not None
+ assert ctx.blocker_signal.internal_reason_code == "tool_error_pending_reconciliation_requires_input"
+
+ record_tool_step_result_for_ctx(ctx, "type_text", {"selector": "#id-first_name"}, {"ok": True})
+
+ assert ctx.pending_reconciliation_requires_user_input is False
+ assert ctx.pending_reconciliation_run_id is None
+ assert ctx.blocker_signal is None
+
+
+def test_reconciliation_requires_input_does_not_clear_after_metadata_only_success() -> None:
+ from skyvern.forge.sdk.copilot.tools import _maybe_clear_reconciliation_flag
+ from skyvern.forge.sdk.workflow.models.workflow import WorkflowRunStatus
+
+ ctx = _ctx()
+ ctx.pending_reconciliation_run_id = "wr_pending"
+ result = {
+ "ok": True,
+ "data": {
+ "workflow_run_id": "wr_pending",
+ "overall_status": WorkflowRunStatus.canceled.value,
+ },
+ }
+ _maybe_clear_reconciliation_flag(ctx, result)
+
+ record_tool_step_result_for_ctx(ctx, "list_credentials", {}, {"ok": True})
+
+ assert ctx.pending_reconciliation_requires_user_input is True
+ assert ctx.pending_reconciliation_run_id == "wr_pending"
+ assert ctx.blocker_signal is not None
+ assert ctx.blocker_signal.internal_reason_code == "tool_error_pending_reconciliation_requires_input"
diff --git a/tests/unit/test_copilot_discovery.py b/tests/unit/test_copilot_discovery.py
index f59e6d431..b2ab17636 100644
--- a/tests/unit/test_copilot_discovery.py
+++ b/tests/unit/test_copilot_discovery.py
@@ -11,10 +11,12 @@ from skyvern.forge.sdk.copilot.tools import _discovery_walk, _inspect_page_for_c
class _Ctx:
- def __init__(self, server: Any) -> None:
+ def __init__(self, server: object) -> None:
self.discovery_mcp_server = server
self.discovery_started_monotonic = None
self.discovery_step_count = 0
+ self.prior_page_inspection_calls_made = 0
+ self.page_inspection_calls_this_turn = 0
class _FailingNavigateServer:
@@ -214,7 +216,7 @@ async def test_inspect_current_page_uses_existing_browser_page(monkeypatch: pyte
ctx.last_run_blocks_workflow_run_id = "wr_123" # type: ignore[attr-defined]
ctx.composition_page_evidence = None # type: ignore[attr-defined]
- async def fake_fallback_page_info(_ctx: Any) -> tuple[str, str]:
+ async def fake_fallback_page_info(_ctx: object) -> tuple[str, str]:
return "https://www.example.com/results", "Results"
monkeypatch.setattr(tools_module, "_fallback_page_info", fake_fallback_page_info)
diff --git a/tests/unit/test_copilot_enforcement_pruning.py b/tests/unit/test_copilot_enforcement_pruning.py
index 8e65d37eb..01cb5ddf3 100644
--- a/tests/unit/test_copilot_enforcement_pruning.py
+++ b/tests/unit/test_copilot_enforcement_pruning.py
@@ -293,15 +293,13 @@ def test_analyze_text_prompt_all_null_is_empty() -> None:
# ---------------------------------------------------------------------------
-def _fresh_ctx_for_record() -> Any:
+def _fresh_ctx_for_record() -> SimpleNamespace:
"""SimpleNamespace shaped for _record_run_blocks_result + update_repeated_failure_state.
Uses getattr-with-default-compatible defaults so the function under test
populates the interesting fields without tripping AttributeError on the
downstream update_repeated_failure_state call.
"""
- from types import SimpleNamespace
-
return SimpleNamespace(
last_test_ok=True,
last_test_failure_reason=None,
@@ -312,11 +310,16 @@ def _fresh_ctx_for_record() -> Any:
null_data_streak_count=0,
failed_test_nudge_count=0,
last_failed_workflow_yaml=None,
+ last_good_workflow=None,
+ last_good_workflow_yaml=None,
non_retriable_nav_error_last_emitted_signature=None,
workflow_yaml=None,
last_workflow=None,
+ last_workflow_yaml=None,
last_frontier_start_label=None,
last_executed_block_labels=[],
+ last_full_workflow_test_ok=False,
+ last_unverified_block_labels=[],
last_failure_signature=None,
last_frontier_fingerprint=None,
repeated_failure_streak_count=0,
@@ -341,6 +344,64 @@ def test_record_run_blocks_result_flips_last_test_ok_on_empty_extraction_envelop
assert ctx.last_test_failure_reason is not None
+def test_record_run_blocks_result_does_not_promote_partial_frontier_to_full_workflow() -> None:
+ from types import SimpleNamespace
+
+ ctx = _fresh_ctx_for_record()
+ ctx.last_workflow = SimpleNamespace(
+ workflow_definition=SimpleNamespace(blocks=[SimpleNamespace(label="open"), SimpleNamespace(label="extract")])
+ )
+ ctx.last_workflow_yaml = "workflow: yaml"
+ ctx.verified_prefix_labels = ["open"]
+
+ result = {
+ "ok": True,
+ "data": {
+ "workflow_run_id": "wr_partial",
+ "requested_block_labels": ["open"],
+ "executed_block_labels": ["open"],
+ "blocks": [{"label": "open", "status": "completed"}],
+ },
+ }
+
+ _record_run_blocks_result(ctx, result)
+
+ assert ctx.last_test_ok is True
+ assert ctx.last_full_workflow_test_ok is False
+ assert ctx.last_unverified_block_labels == ["extract"]
+ assert ctx.last_good_workflow is None
+ assert "unverified workflow blocks remain" in (ctx.last_test_failure_reason or "")
+
+
+def test_record_run_blocks_result_promotes_when_verified_prefix_covers_workflow() -> None:
+ from types import SimpleNamespace
+
+ ctx = _fresh_ctx_for_record()
+ ctx.last_workflow = SimpleNamespace(
+ workflow_definition=SimpleNamespace(blocks=[SimpleNamespace(label="open"), SimpleNamespace(label="extract")])
+ )
+ ctx.last_workflow_yaml = "workflow: yaml"
+ ctx.verified_prefix_labels = ["open", "extract"]
+
+ result = {
+ "ok": True,
+ "data": {
+ "workflow_run_id": "wr_full",
+ "requested_block_labels": ["extract"],
+ "executed_block_labels": ["extract"],
+ "blocks": [{"label": "extract", "status": "completed", "extracted_data": {"value": "ok"}}],
+ },
+ }
+
+ _record_run_blocks_result(ctx, result)
+
+ assert ctx.last_test_ok is True
+ assert ctx.last_full_workflow_test_ok is True
+ assert ctx.last_unverified_block_labels == []
+ assert ctx.last_good_workflow is ctx.last_workflow
+ assert ctx.last_good_workflow_yaml == ctx.last_workflow_yaml
+
+
def test_record_run_blocks_result_keeps_failure_when_watchdog_cancel_without_timeout() -> None:
"""Stagnation/ceiling cancels mid-session must still set last_test_ok=False
so the failed-test nudge can fire — only a coincident total timeout softens
diff --git a/tests/unit/test_copilot_frontier.py b/tests/unit/test_copilot_frontier.py
index f1e67c072..ac842a461 100644
--- a/tests/unit/test_copilot_frontier.py
+++ b/tests/unit/test_copilot_frontier.py
@@ -25,6 +25,7 @@ from skyvern.forge.sdk.copilot.output_utils import (
)
from skyvern.forge.sdk.copilot.tools import (
_find_invalidated_labels,
+ _frontier_run_size_error,
_plan_frontier,
_referenced_output_labels,
)
@@ -44,6 +45,8 @@ class _FakeBlock:
self.block_type = _BT(block_type)
self._config = config or {}
+ for key, value in self._config.items():
+ setattr(self, key, value)
def model_dump(self, mode: str = "json", exclude_none: bool = True) -> dict[str, Any]:
return {
@@ -73,11 +76,11 @@ class _FakeStream:
async def is_disconnected(self) -> bool:
return False
- async def send(self, event: Any) -> None:
+ async def send(self, event: object) -> None:
return None
-def _make_ctx(**kwargs: Any) -> CopilotContext:
+def _make_ctx(**kwargs: object) -> CopilotContext:
defaults: dict[str, Any] = dict(
organization_id="org",
workflow_id="wf_id",
@@ -136,6 +139,190 @@ def test_plan_frontier_append_after_success_runs_only_appended() -> None:
assert frontier == "c"
+def test_plan_frontier_append_walks_back_when_workflow_prefix_is_not_verified() -> None:
+ old = _FakeDefinition(
+ [
+ _FakeBlock("open", "goto_url", {"url": "https://example.com/search"}),
+ _FakeBlock("set_search", "navigation", {"prompt": "Fill search fields"}),
+ ]
+ )
+ new = _FakeDefinition(
+ [
+ _FakeBlock("open", "goto_url", {"url": "https://example.com/search"}),
+ _FakeBlock("set_search", "navigation", {"prompt": "Fill updated search fields"}),
+ _FakeBlock("submit_search", "navigation", {"prompt": "Click Search"}),
+ ]
+ )
+ ctx = _make_ctx()
+ ctx.verified_prefix_labels = ["open"]
+ ctx.verified_block_outputs = {"open": "opened"}
+
+ labels, seed, frontier = _plan_frontier(ctx, ["submit_search"], old, new)
+
+ assert labels == ["open", "set_search", "submit_search"]
+ assert seed == {}
+ assert frontier == "open"
+
+
+def test_plan_frontier_unchanged_workflow_continues_from_first_unverified_label() -> None:
+ definition = _FakeDefinition(
+ [
+ _FakeBlock("open", "goto_url"),
+ _FakeBlock("set_search", "navigation"),
+ _FakeBlock("submit_search", "navigation"),
+ _FakeBlock("extract", "extraction"),
+ ]
+ )
+ ctx = _make_ctx()
+ ctx.verified_prefix_labels = ["open", "set_search"]
+
+ labels, seed, frontier = _plan_frontier(
+ ctx,
+ ["open", "set_search", "submit_search", "extract"],
+ definition,
+ definition,
+ )
+
+ assert labels == ["submit_search", "extract"]
+ assert seed == {}
+ assert frontier == "submit_search"
+
+
+def test_plan_frontier_verified_only_request_advances_to_next_unverified_workflow_label() -> None:
+ definition = _FakeDefinition(
+ [
+ _FakeBlock("open", "goto_url"),
+ _FakeBlock("set_search", "navigation"),
+ _FakeBlock("submit_search", "navigation"),
+ _FakeBlock("extract", "extraction"),
+ ]
+ )
+ ctx = _make_ctx()
+ ctx.verified_prefix_labels = ["open", "set_search"]
+
+ labels, seed, frontier = _plan_frontier(
+ ctx,
+ ["open", "set_search"],
+ definition,
+ definition,
+ )
+
+ assert labels == ["submit_search"]
+ assert seed == {}
+ assert frontier == "submit_search"
+
+
+def test_plan_frontier_suffix_only_request_seeds_prior_browser_state_outputs() -> None:
+ definition = _FakeDefinition(
+ [
+ _FakeBlock("open", "goto_url"),
+ _FakeBlock("search", "navigation"),
+ _FakeBlock("expand", "navigation"),
+ _FakeBlock("extract", "extraction"),
+ ]
+ )
+ ctx = _make_ctx()
+ ctx.verified_prefix_labels = ["open", "search"]
+ ctx.verified_block_outputs = {
+ "open": {"current_url": "https://example.com/search"},
+ "search": {"current_url": "https://example.com/search/results"},
+ }
+
+ labels, seed, frontier = _plan_frontier(ctx, ["expand"], definition, definition)
+
+ assert labels == ["expand"]
+ assert seed == {
+ "open": {"current_url": "https://example.com/search"},
+ "search": {"current_url": "https://example.com/search/results"},
+ }
+ assert frontier == "expand"
+
+
+def test_frontier_run_size_error_limits_long_page_changing_frontier() -> None:
+ definition = _FakeDefinition(
+ [
+ _FakeBlock("open", "goto_url"),
+ _FakeBlock("set_search", "navigation"),
+ _FakeBlock("submit_search", "navigation"),
+ _FakeBlock("expand_results", "navigation"),
+ _FakeBlock("extract", "extraction"),
+ ]
+ )
+ ctx = _make_ctx()
+
+ error = _frontier_run_size_error(
+ ctx,
+ ["open", "set_search", "submit_search", "expand_results", "extract"],
+ ["open", "set_search", "submit_search", "expand_results", "extract"],
+ definition,
+ )
+
+ assert error is not None
+ assert "Keep the same complete workflow YAML" in error
+ assert "['open', 'set_search']" in error
+ assert "Do not remove later blocks" in error
+
+
+def test_frontier_run_size_error_allows_tool_expanded_runtime_anchor() -> None:
+ definition = _FakeDefinition(
+ [
+ _FakeBlock("open", "goto_url"),
+ _FakeBlock("set_search", "navigation"),
+ _FakeBlock("submit_search", "navigation"),
+ ]
+ )
+ ctx = _make_ctx()
+
+ assert (
+ _frontier_run_size_error(
+ ctx,
+ ["submit_search"],
+ ["open", "set_search", "submit_search"],
+ definition,
+ )
+ is None
+ )
+
+
+def test_frontier_run_size_error_allows_small_or_single_action_frontiers() -> None:
+ single_action_definition = _FakeDefinition(
+ [
+ _FakeBlock("open", "goto_url"),
+ _FakeBlock("search", "navigation"),
+ _FakeBlock("extract", "extraction"),
+ ]
+ )
+ long_read_definition = _FakeDefinition(
+ [
+ _FakeBlock("open", "goto_url"),
+ _FakeBlock("extract_a", "extraction"),
+ _FakeBlock("extract_b", "extraction"),
+ _FakeBlock("extract_c", "extraction"),
+ ]
+ )
+ ctx = _make_ctx()
+
+ assert _frontier_run_size_error(ctx, ["open", "search"], ["open", "search"], single_action_definition) is None
+ assert (
+ _frontier_run_size_error(
+ ctx,
+ ["open", "search", "extract"],
+ ["open", "search", "extract"],
+ single_action_definition,
+ )
+ is None
+ )
+ assert (
+ _frontier_run_size_error(
+ ctx,
+ ["open", "extract_a", "extract_b", "extract_c"],
+ ["open", "extract_a", "extract_b", "extract_c"],
+ long_read_definition,
+ )
+ is None
+ )
+
+
def test_plan_frontier_edit_walks_back_to_upstream_navigation_anchor() -> None:
# Editing a non-rerunnable block with an upstream navigation: walk back to nav.
old = _FakeDefinition([_FakeBlock("nav", "navigation"), _FakeBlock("click", "action", {"selector": "#a"})])
@@ -196,7 +383,7 @@ def test_plan_frontier_cold_start_no_old_definition_uses_first_requested() -> No
def test_plan_frontier_ambiguous_diff_falls_back_on_exception(monkeypatch: pytest.MonkeyPatch) -> None:
from skyvern.forge.sdk.copilot import tools
- def _blow_up(*args: Any, **kwargs: Any) -> set[str]:
+ def _blow_up(*args: object, **kwargs: object) -> set[str]:
raise RuntimeError("parse failure in diff")
monkeypatch.setattr(tools, "_find_invalidated_labels", _blow_up)
@@ -324,7 +511,10 @@ def test_plan_frontier_append_seeds_output_parameter_jinja_ref() -> None:
)
assert labels == ["summarize_article"]
- assert seed == {"extract_article_info": {"extracted_information": {"abstract": "Prior output"}}}
+ assert seed == {
+ "open_page": "nav_ok",
+ "extract_article_info": {"extracted_information": {"abstract": "Prior output"}},
+ }
assert frontier == "summarize_article"
@@ -671,7 +861,7 @@ def test_plan_frontier_append_only_with_workflow_param_does_not_fall_back() -> N
labels, seed, frontier = _plan_frontier(ctx, ["open_page", "search"], old, new)
assert labels == ["search"]
- assert seed == {}
+ assert seed == {"open_page": "nav_ok"}
assert frontier == "search"
diff --git a/tests/unit/test_copilot_page_evidence_policy.py b/tests/unit/test_copilot_page_evidence_policy.py
index 35914ed08..498d4da3e 100644
--- a/tests/unit/test_copilot_page_evidence_policy.py
+++ b/tests/unit/test_copilot_page_evidence_policy.py
@@ -3,7 +3,14 @@
from __future__ import annotations
from skyvern.forge.prompts import prompt_engine
-from skyvern.forge.sdk.copilot.tools import update_and_run_blocks_tool, update_workflow_tool
+from skyvern.forge.sdk.copilot.config import DEFAULT_MAX_TURNS
+from skyvern.forge.sdk.copilot.tools import (
+ _COMPOSITION_INSPECTION_PER_CHAT_BUDGET,
+ _COMPOSITION_INSPECTION_PER_TURN_BUDGET,
+ run_blocks_tool,
+ update_and_run_blocks_tool,
+ update_workflow_tool,
+)
_AGENT_TEMPLATE_DEFAULTS = dict(
workflow_knowledge_base="test kb",
@@ -17,6 +24,15 @@ def _render_agent_prompt() -> str:
return prompt_engine.load_prompt("workflow-copilot-agent", **_AGENT_TEMPLATE_DEFAULTS)
+def test_prompt_requires_evidence_grounded_form_and_result_composition() -> None:
+ rendered = _render_agent_prompt()
+
+ assert "grounded in observed evidence" in rendered
+ assert "not one guessed site model" in rendered
+ assert "Do not pre-author row/detail expansion from the user's words alone" in rendered
+ assert "the expansion step also needs result-page evidence" in rendered
+
+
def test_agent_prompt_frames_inspection_as_build_time_context_not_workflow_shape_policy() -> None:
rendered = _render_agent_prompt()
@@ -24,14 +40,59 @@ def test_agent_prompt_frames_inspection_as_build_time_context_not_workflow_shape
assert "fill knowledge gaps while building, editing, or debugging a workflow" in rendered
assert "not to add defensive verification blocks for every website shape" in rendered
assert "Do not invent website-specific paths, query parameters, form fields" in rendered
+ assert (
+ "Add `validation` blocks only when the reusable workflow's task actually includes a durable check" in rendered
+ )
+ assert "before each action" in rendered
assert "GOTO_URL STATE SHORTCUT POLICY" not in rendered
assert "Before extraction on stateful search/result tasks" not in rendered
+def test_agent_prompt_accounts_for_observed_challenges_without_blind_waits() -> None:
+ rendered = _render_agent_prompt()
+
+ assert "anti-bot or challenge controls" in rendered
+ assert "Use `get_browser_screenshot` when DOM evidence identifies a challenge" in rendered
+ assert "Prefer explicit challenge handling available to Skyvern over blind waits" in rendered
+ assert "report the observed blocker instead of retrying the same flow" in rendered
+
+
+def test_agent_prompt_continues_from_observed_state_after_budgeted_runs() -> None:
+ rendered = _render_agent_prompt()
+
+ assert "live browser page that advanced beyond the workflow's entrypoint" in rendered
+ assert "Do not turn the observed current page into a new workflow entrypoint" in rendered
+ assert "Preserve unchanged upstream labels and text" in rendered
+ assert "run only the missing downstream labels" in rendered
+
+
+def test_agent_prompt_requires_result_page_evidence_before_expansion_blocks() -> None:
+ rendered = _render_agent_prompt()
+
+ assert "Do not pre-author row/detail expansion from the user's words alone" in rendered
+ assert "Do not author or run an expansion block before you have reached or inspected the results page" in rendered
+ assert "Do not author downstream row expansion or extraction that depends on a future page state" in rendered
+ assert "add and run the expansion block before adding extraction" in rendered
+ assert "if the requested details are already visible" in rendered
+ assert "omit the expansion block and proceed to extraction from the visible results" in rendered
+
+
def test_tool_descriptions_ground_composition_without_prescribing_extra_workflow_blocks() -> None:
- for tool in (update_workflow_tool, update_and_run_blocks_tool):
+ for tool in (update_workflow_tool, run_blocks_tool, update_and_run_blocks_tool):
desc = tool.description # type: ignore[attr-defined]
assert "browser inspection" in desc
- assert "build-time context" in desc
+ assert "fill knowledge gaps" in desc
+ assert "observed" in desc
+ assert "evidence" in desc
assert "validation` or `navigation` block" not in desc
assert "verify every requested constraint" not in desc
+
+
+def test_inspection_budget_allows_multi_page_authoring_evidence_but_remains_bounded() -> None:
+ assert _COMPOSITION_INSPECTION_PER_TURN_BUDGET >= 3
+ assert _COMPOSITION_INSPECTION_PER_CHAT_BUDGET >= _COMPOSITION_INSPECTION_PER_TURN_BUDGET
+ assert _COMPOSITION_INSPECTION_PER_CHAT_BUDGET <= 6
+
+
+def test_default_loop_budget_allows_inspect_build_run_answer_trajectory() -> None:
+ assert DEFAULT_MAX_TURNS >= 35
diff --git a/tests/unit/test_copilot_per_tool_budget.py b/tests/unit/test_copilot_per_tool_budget.py
index 83f299751..911e7b81c 100644
--- a/tests/unit/test_copilot_per_tool_budget.py
+++ b/tests/unit/test_copilot_per_tool_budget.py
@@ -23,6 +23,7 @@ import pytest
from skyvern.forge.sdk.copilot.context import CopilotContext
from skyvern.forge.sdk.copilot.enforcement import (
MAX_PER_TOOL_BUDGET_NUDGES,
+ POST_ANTI_BOT_FAILED_TEST_NUDGE,
POST_FAILED_TEST_NUDGE,
POST_PER_TOOL_BUDGET_NUDGE,
REPEATED_FRONTIER_STREAK_ESCALATE_AT,
@@ -35,6 +36,7 @@ from skyvern.forge.sdk.copilot.failure_tracking import (
)
from skyvern.forge.sdk.copilot.tools import (
WatchdogExitReason,
+ _mark_page_inspected,
_mark_pending_reconciliation_run,
_maybe_clear_reconciliation_flag,
_record_per_tool_budget_problem_blocks_from_results,
@@ -80,8 +82,63 @@ def _budget_trip_result(workflow_run_id: str = "wr_1") -> dict:
def test_record_sets_top_category_on_per_tool_budget_result() -> None:
ctx = _fresh_context()
- _record_run_blocks_result(ctx, _budget_trip_result())
+ _record_run_blocks_result(ctx, _budget_trip_result("wr_budget"))
assert ctx.last_failure_category_top == PER_TOOL_BUDGET_FAILURE_CATEGORY
+ assert ctx.last_run_blocks_workflow_run_id == "wr_budget"
+ assert ctx.last_successful_run_blocks_workflow_run_id is None
+
+
+def test_record_per_tool_budget_with_current_url_requires_page_inspection() -> None:
+ ctx = _fresh_context()
+ result = _budget_trip_result("wr_budget")
+ result["data"]["current_url"] = "https://example.com/results"
+
+ _record_run_blocks_result(ctx, result)
+
+ assert ctx.post_budget_page_inspection_required is True
+ assert ctx.post_budget_page_inspection_url == "https://example.com/results"
+ assert ctx.post_budget_page_inspection_run_id == "wr_budget"
+
+
+def test_record_preserves_pre_run_anti_bot_evidence_on_budget_trip() -> None:
+ ctx = _fresh_context()
+ ctx.composition_page_evidence = {
+ "anti_bot_indicators": ["challenges.cloudflare.com", "cf-turnstile"],
+ "challenge_controls": [{"selector": "#turnstile-widget"}],
+ }
+
+ _record_run_blocks_result(ctx, _budget_trip_result("wr_budget"))
+
+ assert ctx.last_failure_category_top == PER_TOOL_BUDGET_FAILURE_CATEGORY
+ assert ctx.last_test_anti_bot is not None
+ assert "cf-turnstile" in ctx.last_test_anti_bot
+
+
+def test_block_running_after_budget_current_url_requires_inspection_first() -> None:
+ ctx = _fresh_context()
+ ctx.post_budget_page_inspection_required = True
+ ctx.post_budget_page_inspection_url = "https://example.com/results"
+ ctx.post_budget_page_inspection_run_id = "wr_budget"
+
+ msg = _tool_loop_error(ctx, "update_and_run_blocks", {"block_labels": ["extract_results"]})
+
+ assert msg is not None
+ assert "inspect_page_for_composition" in msg
+ assert "current_page" in msg
+ assert "answer from that evidence" in msg
+
+
+def test_page_inspection_clears_post_budget_run_guard() -> None:
+ ctx = _fresh_context()
+ ctx.post_budget_page_inspection_required = True
+ ctx.post_budget_page_inspection_url = "https://example.com/results"
+ ctx.post_budget_page_inspection_run_id = "wr_budget"
+
+ _mark_page_inspected(ctx)
+
+ assert ctx.post_budget_page_inspection_required is False
+ assert ctx.post_budget_page_inspection_url is None
+ assert ctx.post_budget_page_inspection_run_id is None
def test_record_uses_policy_failure_reason_not_llm_tool_instruction() -> None:
@@ -172,6 +229,21 @@ def test_check_enforcement_emits_budget_nudge_before_failed_test() -> None:
assert ctx.per_tool_budget_nudge_count == 1
+def test_check_enforcement_emits_anti_bot_nudge_before_budget_when_challenge_observed() -> None:
+ ctx = _fresh_context()
+ ctx.update_workflow_called = True
+ ctx.test_after_update_done = True
+ ctx.last_test_ok = False
+ ctx.last_failure_category_top = PER_TOOL_BUDGET_FAILURE_CATEGORY
+ ctx.last_test_anti_bot = "Observed anti-bot challenge evidence before the run: cf-turnstile"
+
+ nudge = _check_enforcement(ctx)
+
+ assert nudge == POST_ANTI_BOT_FAILED_TEST_NUDGE
+ assert ctx.failed_test_nudge_count == 1
+ assert ctx.per_tool_budget_nudge_count == 0
+
+
def test_check_enforcement_emits_budget_nudge_before_repeated_frontier_warn() -> None:
"""The budget trip is structural (chain too long) and must not be silently
consumed by the repeated-frontier escalation, even when both signals fire
@@ -419,7 +491,23 @@ def test_tool_loop_error_blocks_rerun_of_problem_navigation_label() -> None:
assert msg is not None
assert "apply_filters" in msg
assert "Do NOT rerun" in msg
- assert "code or validation" in msg
+ assert "live-page inspection evidence" in msg
+
+
+def test_tool_loop_error_blocks_update_and_run_rerun_of_problem_navigation_label() -> None:
+ ctx = _fresh_context()
+ ctx.per_tool_budget_problem_block_labels = ["apply_filters"]
+
+ msg = _tool_loop_error(
+ ctx,
+ "update_and_run_blocks",
+ {"workflow_yaml": "title: wf", "block_labels": ["apply_filters"], "parameters": {}},
+ )
+
+ assert msg is not None
+ assert "apply_filters" in msg
+ assert ctx.blocker_signal is not None
+ assert ctx.blocker_signal.internal_reason_code == "tool_error_per_tool_budget_rerun"
def test_tool_loop_error_treats_missing_labels_as_rerun_all() -> None:
@@ -446,6 +534,85 @@ def test_tool_loop_error_allows_new_smaller_label_after_budget_problem() -> None
)
+def test_tool_loop_error_blocks_upstream_replay_after_post_budget_page_evidence() -> None:
+ ctx = _fresh_context()
+ ctx.per_tool_budget_problem_block_labels = ["apply_filters"]
+ ctx.composition_page_evidence = {
+ "current_url": "https://example.com/results",
+ "workflow_run_id": "wr_budget",
+ "observed_after_workflow_run": True,
+ }
+ workflow_yaml = """
+workflow_definition:
+ blocks:
+ - label: open_site
+ block_type: goto_url
+ url: https://example.com
+ - label: open_search
+ block_type: navigation
+ goal: Open search
+ - label: apply_filters
+ block_type: navigation
+ goal: Apply filters
+"""
+
+ msg = _tool_loop_error(
+ ctx,
+ "update_and_run_blocks",
+ {
+ "workflow_yaml": workflow_yaml,
+ "block_labels": ["open_search"],
+ "parameters": {},
+ },
+ )
+
+ assert msg is not None
+ assert "Do NOT restart upstream" in msg
+ assert "open_search" in msg
+ assert "apply_filters" in msg
+ assert ctx.blocker_signal is not None
+ assert ctx.blocker_signal.internal_reason_code == "tool_error_post_budget_upstream_replay"
+
+
+def test_tool_loop_error_allows_downstream_recovery_after_post_budget_page_evidence() -> None:
+ ctx = _fresh_context()
+ ctx.per_tool_budget_problem_block_labels = ["apply_filters"]
+ ctx.composition_page_evidence = {
+ "current_url": "https://example.com/results",
+ "workflow_run_id": "wr_budget",
+ "observed_after_workflow_run": True,
+ }
+ workflow_yaml = """
+workflow_definition:
+ blocks:
+ - label: open_site
+ block_type: goto_url
+ url: https://example.com
+ - label: open_search
+ block_type: navigation
+ goal: Open search
+ - label: apply_filters
+ block_type: navigation
+ goal: Apply filters
+ - label: expand_results
+ block_type: navigation
+ goal: Expand results
+"""
+
+ assert (
+ _tool_loop_error(
+ ctx,
+ "update_and_run_blocks",
+ {
+ "workflow_yaml": workflow_yaml,
+ "block_labels": ["expand_results"],
+ "parameters": {},
+ },
+ )
+ is None
+ )
+
+
def test_successful_workflow_update_keeps_problem_label_while_still_navigation() -> None:
ctx = _fresh_context()
ctx.workflow_yaml = "updated yaml"
diff --git a/tests/unit/test_copilot_turn_intent_tool_gate.py b/tests/unit/test_copilot_turn_intent_tool_gate.py
index 820ceb92c..d1e74f653 100644
--- a/tests/unit/test_copilot_turn_intent_tool_gate.py
+++ b/tests/unit/test_copilot_turn_intent_tool_gate.py
@@ -33,6 +33,8 @@ def _ctx(
request_policy: RequestPolicy | None = None,
*,
pending_reconciliation_run_id: str | None = None,
+ last_run_blocks_workflow_run_id: str | None = None,
+ last_successful_run_blocks_workflow_run_id: str | None = None,
tool_activity: list[dict] | None = None,
) -> CopilotContext:
ctx = CopilotContext(
@@ -47,6 +49,10 @@ def _ctx(
)
if pending_reconciliation_run_id is not None:
ctx.pending_reconciliation_run_id = pending_reconciliation_run_id
+ if last_run_blocks_workflow_run_id is not None:
+ ctx.last_run_blocks_workflow_run_id = last_run_blocks_workflow_run_id
+ if last_successful_run_blocks_workflow_run_id is not None:
+ ctx.last_successful_run_blocks_workflow_run_id = last_successful_run_blocks_workflow_run_id
if tool_activity is not None:
ctx.tool_activity = tool_activity
return ctx
@@ -75,6 +81,8 @@ def _assert_signal(
[
(TurnIntentMode.DOCS_ANSWER, "update_workflow", "turn_intent_no_mutation_update_blocked"),
(TurnIntentMode.DIAGNOSE, "run_blocks_and_collect_debug", "turn_intent_no_mutation_run_blocked"),
+ (TurnIntentMode.DOCS_ANSWER, "inspect_page_for_composition", "turn_intent_page_inspection_blocked"),
+ (TurnIntentMode.CLARIFY, "inspect_page_for_composition", "turn_intent_page_inspection_blocked"),
(TurnIntentMode.CLARIFY, "update_and_run_blocks", "turn_intent_no_mutation_run_blocked"),
(TurnIntentMode.REFUSE, "update_and_run_blocks", "turn_intent_no_mutation_run_blocked"),
],
@@ -106,6 +114,15 @@ def test_turn_intent_gate_allows_draft_update_without_run_authority() -> None:
assert _turn_intent_tool_error(_ctx(intent), "update_workflow") is None
+def test_turn_intent_gate_allows_build_page_inspection_with_update_authority() -> None:
+ intent = TurnIntent(
+ mode=TurnIntentMode.BUILD,
+ authority=TurnIntentAuthority(may_update_workflow=True, may_run_blocks=False),
+ )
+
+ assert _turn_intent_tool_error(_ctx(intent), "inspect_page_for_composition") is None
+
+
def test_turn_intent_gate_blocks_draft_only_run_tools() -> None:
intent = TurnIntent(
mode=TurnIntentMode.DRAFT_ONLY,
@@ -405,6 +422,28 @@ def test_within_turn_override_pending_reconciliation_allows_read() -> None:
assert _turn_intent_tool_error(ctx, "get_run_results") is None
+def test_within_turn_override_successful_run_blocks_allows_read() -> None:
+ intent = TurnIntent(
+ mode=TurnIntentMode.BUILD,
+ authority=TurnIntentAuthority(may_update_workflow=True, may_run_blocks=True),
+ )
+
+ ctx = _ctx(intent, last_successful_run_blocks_workflow_run_id="wr_completed_this_turn")
+
+ assert _turn_intent_tool_error(ctx, "get_run_results") is None
+
+
+def test_within_turn_override_failed_run_blocks_allows_read() -> None:
+ intent = TurnIntent(
+ mode=TurnIntentMode.BUILD,
+ authority=TurnIntentAuthority(may_update_workflow=True, may_run_blocks=True),
+ )
+
+ ctx = _ctx(intent, last_run_blocks_workflow_run_id="wr_failed_this_turn")
+
+ assert _turn_intent_tool_error(ctx, "get_run_results") is None
+
+
def test_within_turn_override_excluded_for_docs_answer() -> None:
intent = TurnIntent(
mode=TurnIntentMode.DOCS_ANSWER,
@@ -439,6 +478,46 @@ def test_tool_activity_is_not_a_substitute_for_pending_reconciliation_run_id() -
assert _turn_intent_tool_error(ctx, "get_run_results") is not None
+async def test_get_run_results_defaults_to_successful_same_turn_run() -> None:
+ ctx = _ctx(
+ TurnIntent(mode=TurnIntentMode.BUILD, authority=TurnIntentAuthority()),
+ last_successful_run_blocks_workflow_run_id="wr_completed_this_turn",
+ )
+ run = SimpleNamespace(workflow_run_id="wr_completed_this_turn", workflow_permanent_id="wfp-1", status="completed")
+
+ with patch("skyvern.forge.sdk.copilot.tools.app") as mock_app:
+ mock_app.DATABASE.workflow_runs.get_workflow_run = AsyncMock(return_value=run)
+ mock_app.DATABASE.observer.get_workflow_run_blocks = AsyncMock(return_value=[])
+ mock_app.WORKFLOW_SERVICE.get_workflow_runs_for_workflow_permanent_id = AsyncMock()
+
+ result = await _get_run_results({}, ctx)
+
+ assert result["ok"] is True
+ assert result["data"]["workflow_run_id"] == "wr_completed_this_turn"
+ mock_app.WORKFLOW_SERVICE.get_workflow_runs_for_workflow_permanent_id.assert_not_called()
+
+
+async def test_get_run_results_defaults_to_latest_same_turn_run_when_no_success() -> None:
+ ctx = _ctx(
+ TurnIntent(mode=TurnIntentMode.BUILD, authority=TurnIntentAuthority()),
+ last_run_blocks_workflow_run_id="wr_failed_this_turn",
+ )
+ run = SimpleNamespace(workflow_run_id="wr_failed_this_turn", workflow_permanent_id="wfp-1", status="canceled")
+
+ with patch("skyvern.forge.sdk.copilot.tools.app") as mock_app:
+ mock_app.DATABASE.workflow_runs.get_workflow_run = AsyncMock(return_value=run)
+ mock_app.DATABASE.observer.get_workflow_run_blocks = AsyncMock(return_value=[])
+ mock_app.WORKFLOW_SERVICE.get_workflow_runs_for_workflow_permanent_id = AsyncMock()
+
+ result = await _get_run_results({}, ctx)
+
+ assert result["ok"] is True
+ assert result["data"]["workflow_run_id"] == "wr_failed_this_turn"
+ mock_app.WORKFLOW_SERVICE.get_workflow_runs_for_workflow_permanent_id.assert_not_called()
+
+
def test_recovery_diagnose_keeps_get_run_results_in_native_tools() -> None:
intent = TurnIntent(
mode=TurnIntentMode.DIAGNOSE,