Automate browser based workflows with AI
Python aiapiautomationbrowserbrowser-automationcomputergptllmplaywrightpowerautomatepuppeteerpythonrpaseleniumvisionworkflow
feat(SKY-9329): surface workflow-run sub-events as mid-tool copilot narrations (#5741)
Andrew Neilsonde3c731110b9
diff --git a/skyvern-frontend/src/routes/workflows/copilot/WorkflowCopilotChat.tsx b/skyvern-frontend/src/routes/workflows/copilot/WorkflowCopilotChat.tsxindex 70dad35dd..451622284 100644--- a/skyvern-frontend/src/routes/workflows/copilot/WorkflowCopilotChat.tsx+++ b/skyvern-frontend/src/routes/workflows/copilot/WorkflowCopilotChat.tsx@@ -26,6 +26,7 @@ import {WorkflowCopilotToolResultUpdate,WorkflowCopilotCondensingUpdate,WorkflowCopilotNarrationUpdate,+ WorkflowCopilotBlockProgressUpdate,WorkflowCopilotChatSender,WorkflowCopilotChatRequest,WorkflowCopilotClearProposedWorkflowRequest,@@ -33,6 +34,7 @@ import {} from "./workflowCopilotTypes";import {ToolActivity,+ applyBlockProgress,applyToolCall,applyToolResult,getActivityDotClass,@@ -52,7 +54,8 @@ type WorkflowCopilotSsePayload =| WorkflowCopilotToolCallUpdate| WorkflowCopilotToolResultUpdate| WorkflowCopilotCondensingUpdate- | WorkflowCopilotNarrationUpdate;+ | WorkflowCopilotNarrationUpdate+ | WorkflowCopilotBlockProgressUpdate;const TOOL_DISPLAY_NAMES: Record<string, string> = {update_workflow: "Updating workflow",@@ -790,6 +793,9 @@ export function WorkflowCopilotChat({setLatestNarration(payload.narration);}return false;+ case "block_progress":+ setToolActivity((prev) => applyBlockProgress(prev, payload));+ return false;case "response":handleResponse(payload);return true;diff --git a/skyvern-frontend/src/routes/workflows/copilot/toolActivity.test.ts b/skyvern-frontend/src/routes/workflows/copilot/toolActivity.test.tsindex fcaf0be88..c4739cdd2 100644--- a/skyvern-frontend/src/routes/workflows/copilot/toolActivity.test.ts+++ b/skyvern-frontend/src/routes/workflows/copilot/toolActivity.test.ts@@ -1,7 +1,13 @@import { describe, expect, it } from "vitest";-import { ToolActivity, applyToolCall, applyToolResult } from "./toolActivity";import {+ ToolActivity,+ applyBlockProgress,+ applyToolCall,+ applyToolResult,+} from "./toolActivity";+import {+ WorkflowCopilotBlockProgressUpdate,WorkflowCopilotToolCallUpdate,WorkflowCopilotToolResultUpdate,} from "./workflowCopilotTypes";@@ -335,3 +341,140 @@ describe("applyToolCall", () => {expect(next[0]!).toBe(prior);});});++const block = (+ overrides: Partial<WorkflowCopilotBlockProgressUpdate> &+ Pick<+ WorkflowCopilotBlockProgressUpdate,+ "workflow_run_block_id" | "status"+ >,+): WorkflowCopilotBlockProgressUpdate => ({+ type: "block_progress",+ block_label: `label_${overrides.workflow_run_block_id}`,+ block_type: "navigation",+ iteration: 0,+ timestamp: "2026-04-30T07:00:00Z",+ ...overrides,+});++describe("applyBlockProgress", () => {+ it("appends a running entry on first sighting", () => {+ const next = applyBlockProgress(+ [],+ block({+ workflow_run_block_id: "wrb_1",+ status: "running",+ block_label: "step_navigate",+ }),+ );+ expect(next).toHaveLength(1);+ expect(next[0]!).toMatchObject({+ tool_name: "Block step_navigate",+ tool_call_id: "block:wrb_1",+ status: "running",+ summary: "running",+ });+ });++ it("updates the same row by workflow_run_block_id when status changes", () => {+ const prev = applyBlockProgress(+ [],+ block({+ workflow_run_block_id: "wrb_1",+ status: "running",+ block_label: "step_navigate",+ }),+ );+ const next = applyBlockProgress(+ prev,+ block({+ workflow_run_block_id: "wrb_1",+ status: "completed",+ block_label: "step_navigate",+ }),+ );+ expect(next).toHaveLength(1);+ expect(next[0]!).toMatchObject({+ tool_call_id: "block:wrb_1",+ status: "success",+ summary: "completed",+ });+ });++ it("treats two blocks with the same label as separate rows when ids differ", () => {+ let state: ToolActivity[] = [];+ state = applyBlockProgress(+ state,+ block({+ workflow_run_block_id: "wrb_1",+ status: "running",+ block_label: "iterate_url",+ }),+ );+ state = applyBlockProgress(+ state,+ block({+ workflow_run_block_id: "wrb_2",+ status: "running",+ block_label: "iterate_url",+ }),+ );+ expect(state).toHaveLength(2);+ expect(state[0]!.tool_call_id).toBe("block:wrb_1");+ expect(state[1]!.tool_call_id).toBe("block:wrb_2");+ });++ it("maps failed/terminated/timed_out/canceled to error status", () => {+ for (const status of [+ "failed",+ "terminated",+ "timed_out",+ "canceled",+ ] as const) {+ const next = applyBlockProgress(+ [],+ block({ workflow_run_block_id: `wrb_${status}`, status }),+ );+ expect(next[0]!.status).toBe("error");+ expect(next[0]!.summary).toBe(status);+ }+ });++ it("maps skipped to success status (benign-completed)", () => {+ const next = applyBlockProgress(+ [],+ block({ workflow_run_block_id: "wrb_1", status: "skipped" }),+ );+ expect(next[0]!.status).toBe("success");+ });++ it("ignores unknown status values without mutating the list", () => {+ const prev: ToolActivity[] = [+ { tool_name: "x", tool_call_id: "x", status: "running" },+ ];+ const next = applyBlockProgress(+ prev,+ block({ workflow_run_block_id: "wrb_1", status: "weird_state" }),+ );+ expect(next).toBe(prev);+ });++ it("does not collide with regular tool_call rows that have different tool_call_ids", () => {+ let state: ToolActivity[] = [];+ state = applyToolCall(+ state,+ call({ tool_call_id: "c1", tool_name: "update_and_run_blocks" }),+ );+ state = applyBlockProgress(+ state,+ block({+ workflow_run_block_id: "wrb_1",+ status: "running",+ block_label: "step_navigate",+ }),+ );+ expect(state).toHaveLength(2);+ expect(state[0]!.tool_call_id).toBe("c1");+ expect(state[1]!.tool_call_id).toBe("block:wrb_1");+ });+});diff --git a/skyvern-frontend/src/routes/workflows/copilot/toolActivity.ts b/skyvern-frontend/src/routes/workflows/copilot/toolActivity.tsindex f4bdc037f..27c7a02cd 100644--- a/skyvern-frontend/src/routes/workflows/copilot/toolActivity.ts+++ b/skyvern-frontend/src/routes/workflows/copilot/toolActivity.ts@@ -1,4 +1,5 @@import {+ WorkflowCopilotBlockProgressUpdate,WorkflowCopilotToolCallUpdate,WorkflowCopilotToolResultUpdate,} from "./workflowCopilotTypes";@@ -124,3 +125,59 @@ export function applyToolResult(return item;});}++// Same status taxonomy as the backend BlockStatus enum.+const BLOCK_FAILED_STATUSES = new Set([+ "failed",+ "terminated",+ "timed_out",+ "canceled",+]);+const BLOCK_COMPLETED_STATUSES = new Set(["completed", "skipped"]);++function blockStatusToActivityStatus(+ status: string,+): "running" | "success" | "error" | null {+ if (status === "running") return "running";+ if (BLOCK_COMPLETED_STATUSES.has(status)) return "success";+ if (BLOCK_FAILED_STATUSES.has(status)) return "error";+ return null;+}++// Per-block lifecycle update from inside long-running tool calls. Keyed by+// `workflow_run_block_id` so duplicate labels in the same run never collide.+export function applyBlockProgress(+ prev: ToolActivity[],+ payload: WorkflowCopilotBlockProgressUpdate,+): ToolActivity[] {+ const nextStatus = blockStatusToActivityStatus(payload.status);+ if (nextStatus === null) return prev;++ const tool_call_id = `block:${payload.workflow_run_block_id}`;+ const tool_name = `Block ${payload.block_label}`;+ const summary = payload.status;++ const idx = prev.findIndex((item) => item.tool_call_id === tool_call_id);+ if (idx === -1) {+ return [+ ...prev,+ {+ tool_name,+ tool_call_id,+ status: nextStatus,+ summary,+ },+ ];+ }++ return prev.map((item, i) =>+ i === idx+ ? {+ ...item,+ tool_name,+ status: nextStatus,+ summary,+ }+ : item,+ );+}diff --git a/skyvern-frontend/src/routes/workflows/copilot/workflowCopilotTypes.ts b/skyvern-frontend/src/routes/workflows/copilot/workflowCopilotTypes.tsindex dd2545926..b3abca5b2 100644--- a/skyvern-frontend/src/routes/workflows/copilot/workflowCopilotTypes.ts+++ b/skyvern-frontend/src/routes/workflows/copilot/workflowCopilotTypes.ts@@ -68,7 +68,8 @@ export type WorkflowCopilotStreamMessageType =| "tool_call"| "tool_result"| "condensing"- | "narration";+ | "narration"+ | "block_progress";export interface WorkflowCopilotProcessingUpdate {type: "processing_update";@@ -119,6 +120,16 @@ export interface WorkflowCopilotNarrationUpdate {timestamp: string;}+export interface WorkflowCopilotBlockProgressUpdate {+ type: "block_progress";+ workflow_run_block_id: string;+ block_label: string;+ block_type: string;+ status: string;+ iteration: number;+ timestamp: string;+}+export interface WorkflowYAMLConversionRequest {workflow_definition_yaml: string;workflow_id: string;diff --git a/skyvern/forge/sdk/copilot/narration.py b/skyvern/forge/sdk/copilot/narration.pyindex e3a0800cd..0068bfe04 100644--- a/skyvern/forge/sdk/copilot/narration.py+++ b/skyvern/forge/sdk/copilot/narration.py@@ -18,16 +18,18 @@ import asyncioimport reimport timefrom collections import deque+from collections.abc import Awaitable, Callablefrom dataclasses import dataclass, fieldfrom datetime import datetime, timezonefrom enum import StrEnum-from typing import TYPE_CHECKING, Any+from typing import TYPE_CHECKING, Any, NamedTuplefrom urllib.parse import urlparseimport structlogfrom skyvern.forge import appfrom skyvern.forge.sdk.schemas.workflow_copilot import (+ WorkflowCopilotBlockProgressUpdate,WorkflowCopilotNarrationUpdate,WorkflowCopilotStreamMessageType,)@@ -57,7 +59,11 @@ class TransitionKind(StrEnum):# Ordered by ascending priority: higher-priority transitions overwrite a# lower-priority pending one within the min-gap window.TOOL_STARTED = "tool_started"+ TOOL_IN_PROGRESS = "tool_in_progress"+ BLOCK_STARTED = "block_started"+ BLOCK_COMPLETED = "block_completed"NEW_TOOL_CLUSTER = "new_tool_cluster"+ BLOCK_FAILED = "block_failed"ENFORCEMENT_RETRY = "enforcement_retry"NAVIGATION_COMPLETED = "navigation_completed"TEST_COMPLETED = "test_completed"@@ -83,6 +89,9 @@ class NarratorState:"""Cadence + buffer state carried across stream_to_sse iterations."""last_emitted_at: float | None = None+ # Advances on every narrator task launch (success or failure) so a flaky+ # narrator path can't be re-fired every poll tick.+ last_attempted_at: float | None = Nonepending_activity: deque[_ToolActivityEntry] = field(default_factory=lambda: deque(maxlen=MAX_TOOL_ACTIVITY_BUFFER))in_flight_task: asyncio.Task[None] | None = Nonepending_transition: TransitionKind | None = None@@ -91,6 +100,7 @@ class NarratorState:# tool_output so post-tool transitions describe the finished action, not# the in-flight one.pending_tool_name: str | None = None+ current_iteration: int = 0def record_tool(self,@@ -170,7 +180,8 @@ def should_emit(state: NarratorState, now: float) -> bool:return Falseif state.in_flight_task is not None and not state.in_flight_task.done():return False- if state.last_emitted_at is not None and (now - state.last_emitted_at) < MIN_NARRATION_GAP_SECONDS:+ last_event = max(state.last_emitted_at or 0.0, state.last_attempted_at or 0.0)+ if last_event > 0.0 and (now - last_event) < MIN_NARRATION_GAP_SECONDS:return Falsereturn True@@ -189,11 +200,9 @@ def schedule_narration(transition = state.pending_transitionassert transition is not None # guaranteed by should_emitstate.pending_transition = None- # last_emitted_at is advanced only after a narration is actually delivered- # (see _narration_task_body). Advancing here would silence the next 10s of- # valid transitions when a narration fails, times out, or is leak-dropped- # -- a bad trade since the in_flight_task slot already prevents concurrent- # emissions during the LLM call.+ # Bound failure-path retries to the same gap window successes use; without+ # this, a flaky narrator re-fires every poll tick.+ state.last_attempted_at = now# Copy the deque at schedule time so the background task sees a stable# view while streaming_adapter keeps appending.@@ -422,12 +431,19 @@ _USER_FACING_TOOL_LABELS: dict[str, str] = {"get_block_schema": "looking up workflow block options","validate_block": "checking workflow block configuration","get_run_results": "checking results of a prior run",+ "block_started": "starting a step in the workflow",+ "block_completed": "completing a step in the workflow",+ "block_failed": "a step in the workflow failed",}_TRANSITION_LABELS: dict[TransitionKind, str] = {TransitionKind.TOOL_STARTED: "just started a new action",+ TransitionKind.TOOL_IN_PROGRESS: "still working through the requested task",+ TransitionKind.BLOCK_STARTED: "starting another step in the workflow",+ TransitionKind.BLOCK_COMPLETED: "just finished a step in the workflow",TransitionKind.NEW_TOOL_CLUSTER: "starting a different kind of work",+ TransitionKind.BLOCK_FAILED: "a step in the workflow failed",TransitionKind.ENFORCEMENT_RETRY: "course-correcting after a check",TransitionKind.NAVIGATION_COMPLETED: "just finished loading a page",TransitionKind.TEST_COMPLETED: "just finished a test of the workflow",@@ -586,3 +602,179 @@ _IDENTIFIER_LEAK_PATTERNS = (def _narration_leaks_identifier(narration: str) -> bool:return any(pattern.search(narration) for pattern in _IDENTIFIER_LEAK_PATTERNS)+++# `skipped` is benign-completed, not a failure.+_BLOCK_STATUS_TO_TRANSITION: dict[str, TransitionKind] = {+ "running": TransitionKind.BLOCK_STARTED,+ "completed": TransitionKind.BLOCK_COMPLETED,+ "skipped": TransitionKind.BLOCK_COMPLETED,+ "failed": TransitionKind.BLOCK_FAILED,+ "terminated": TransitionKind.BLOCK_FAILED,+ "timed_out": TransitionKind.BLOCK_FAILED,+ "canceled": TransitionKind.BLOCK_FAILED,+}++_BLOCK_TRANSITION_TO_SYNTHETIC_TOOL: dict[TransitionKind, str] = {+ TransitionKind.BLOCK_STARTED: "block_started",+ TransitionKind.BLOCK_COMPLETED: "block_completed",+ TransitionKind.BLOCK_FAILED: "block_failed",+}+++@dataclass(frozen=True)+class BlockProgressEvent:+ """One block status change detected by record_block_transitions."""++ block_id: str+ block_label: str+ block_type: str+ status: str+ kind: TransitionKind+++def record_block_transitions(+ state: NarratorState,+ snapshot: list[tuple[str, str, str, str]],+ seen_state: dict[str, str],+ iteration: int,+) -> list[BlockProgressEvent]:+ """Record transitions for status changes since the last snapshot; returns the new events for further fan-out."""+ new_events: list[BlockProgressEvent] = []+ for block_id, block_label, block_type, status in snapshot:+ if not block_id:+ continue+ prior = seen_state.get(block_id)+ if prior == status:+ continue+ seen_state[block_id] = status+ kind = _BLOCK_STATUS_TO_TRANSITION.get(status)+ if kind is None:+ continue+ synthetic_tool = _BLOCK_TRANSITION_TO_SYNTHETIC_TOOL.get(kind)+ if synthetic_tool is None:+ # Defensive: a new TransitionKind added to the status map without+ # a matching synthetic-tool entry would otherwise KeyError here.+ continue+ state.record_tool(+ tool_name=synthetic_tool,+ summary=f"workflow step {status}",+ success=(kind == TransitionKind.BLOCK_COMPLETED),+ iteration=iteration,+ )+ state.record_transition(kind)+ new_events.append(+ BlockProgressEvent(+ block_id=block_id,+ block_label=block_label,+ block_type=block_type,+ status=status,+ kind=kind,+ )+ )+ return new_events+++# Returns objects exposing workflow_run_block_id and status; helper reads only those two fields.+FetchBlockStatusesCallable = Callable[[], Awaitable[list[Any]]]+++class NarratorPollTickResult(NamedTuple):+ """Updated bookkeeping the polling loop must thread into its next call."""++ prior_block_ts: datetime | None+ prior_step_ts: datetime | None+ last_block_fetch_monotonic: float+++async def narrator_poll_tick(+ state: NarratorState,+ *,+ current_block_ts: datetime | None,+ current_step_ts: datetime | None,+ prior_block_ts: datetime | None,+ prior_step_ts: datetime | None,+ last_block_fetch_monotonic: float,+ seen_block_states: dict[str, str],+ fetch_block_statuses: FetchBlockStatusesCallable,+ stream: EventSourceStream,+) -> NarratorPollTickResult:+ """Per-tick narrator bookkeeping; returns updated (prior_block_ts, prior_step_ts, last_block_fetch_monotonic).++ `prior_block_ts` advances only on a successful fetch so rate-limited and failed ticks retry on the next call.+ """+ now = time.monotonic()+ block_changed = current_block_ts != prior_block_ts+ step_changed = current_step_ts != prior_step_ts+ gate_open = (now - last_block_fetch_monotonic) >= MIN_NARRATION_GAP_SECONDS++ next_prior_block_ts = prior_block_ts+ next_last_fetch = last_block_fetch_monotonic+ block_transition_recorded = False++ if block_changed and gate_open:+ next_last_fetch = now+ try:+ blocks = await fetch_block_statuses()+ except Exception:+ LOG.debug("copilot narrator block-status fetch failed", exc_info=True)+ blocks = None++ if blocks is not None:+ snapshot: list[tuple[str, str, str, str]] = []+ for block in blocks:+ block_id = getattr(block, "workflow_run_block_id", None)+ if not block_id:+ continue+ raw_status = getattr(block, "status", None)+ if raw_status is None:+ continue+ status = raw_status.value if hasattr(raw_status, "value") else str(raw_status)+ if not status:+ continue+ block_label = getattr(block, "label", None) or ""+ raw_block_type = getattr(block, "block_type", None)+ if raw_block_type is None:+ block_type = ""+ elif hasattr(raw_block_type, "value"):+ block_type = raw_block_type.value+ elif hasattr(raw_block_type, "name"):+ block_type = raw_block_type.name+ else:+ block_type = str(raw_block_type)+ snapshot.append((block_id, block_label, block_type, status))+ # Repository returns DESC by created_at; reverse for chronological order.+ snapshot.reverse()+ new_events = record_block_transitions(state, snapshot, seen_block_states, state.current_iteration)+ block_transition_recorded = bool(new_events)+ next_prior_block_ts = current_block_ts+ for event in new_events:+ if not event.block_label:+ # Without a label the FE has nothing readable to render; skip+ # rather than ship empty bullets.+ continue+ try:+ await stream.send(+ WorkflowCopilotBlockProgressUpdate(+ type=WorkflowCopilotStreamMessageType.BLOCK_PROGRESS,+ workflow_run_block_id=event.block_id,+ block_label=event.block_label,+ block_type=event.block_type,+ status=event.status,+ iteration=state.current_iteration,+ timestamp=datetime.now(timezone.utc),+ )+ )+ except Exception:+ LOG.debug("copilot block_progress send failed", exc_info=True)++ if not block_transition_recorded and step_changed:+ state.record_transition(TransitionKind.TOOL_IN_PROGRESS)++ schedule_narration(state, stream, state.current_iteration)++ return NarratorPollTickResult(+ prior_block_ts=next_prior_block_ts,+ prior_step_ts=current_step_ts,+ last_block_fetch_monotonic=next_last_fetch,+ )diff --git a/skyvern/forge/sdk/copilot/streaming_adapter.py b/skyvern/forge/sdk/copilot/streaming_adapter.pyindex ae1f58a09..d998ec1d9 100644--- a/skyvern/forge/sdk/copilot/streaming_adapter.py+++ b/skyvern/forge/sdk/copilot/streaming_adapter.py@@ -130,6 +130,7 @@ async def stream_to_sse(# than waiting for tool_output of a long tool.if narrator_enabled:narrator_state.pending_tool_name = tool_name+ narrator_state.current_iteration = iterationnarrator_state.record_transition(TransitionKind.TOOL_STARTED)schedule_narration(narrator_state, stream, iteration)@@ -179,6 +180,7 @@ async def stream_to_sse()for transition in detect_transitions(ctx_before, ctx_after, tool_name, prior_tool_name):narrator_state.record_transition(transition)+ narrator_state.current_iteration = iterationschedule_narration(narrator_state, stream, iteration)else:_update_enforcement_from_tool(ctx, tool_name, parsed)diff --git a/skyvern/forge/sdk/copilot/tools.py b/skyvern/forge/sdk/copilot/tools.pyindex 726ba37ab..31ac42f9b 100644--- a/skyvern/forge/sdk/copilot/tools.py+++ b/skyvern/forge/sdk/copilot/tools.py@@ -30,6 +30,9 @@ from skyvern.forge.sdk.copilot.failure_tracking import ()from skyvern.forge.sdk.copilot.loop_detection import detect_tool_loopfrom skyvern.forge.sdk.copilot.mcp_adapter import SchemaOverlay+from skyvern.forge.sdk.copilot.narration import NarratorState+from skyvern.forge.sdk.copilot.narration import handler_available as narration_handler_available+from skyvern.forge.sdk.copilot.narration import narrator_poll_tickfrom skyvern.forge.sdk.copilot.output_utils import (build_run_blocks_response,iter_failure_reasons,@@ -1172,12 +1175,42 @@ async def _run_blocks_and_collect_debug(# one. Safety ceiling still applies.stagnation_enabled = not _any_quiet_block_requested(ctx, labels_to_execute)+ # Mid-tool narrator bridge: feed block-status changes and step-level+ # heartbeats into NarratorState so the narration ticker keeps emitting+ # while a long workflow run is in flight.+ narrator_state: NarratorState | None = getattr(ctx, "narrator_state", None)+ narrator_enabled = narrator_state is not None and narration_handler_available()+ seen_block_states: dict[str, str] = {}+ prior_block_ts: datetime | None = initial_block_ts+ prior_step_ts: datetime | None = initial_step_ts+ last_block_fetch_monotonic = 0.0+try:while True:await asyncio.sleep(RUN_BLOCKS_POLL_INTERVAL_SECONDS)run, step_ts, block_ts = await _read_progress_sources(ctx, workflow_run.workflow_run_id)+ if narrator_enabled:+ assert narrator_state is not None # narrator_enabled implies non-None+ tick_result = await narrator_poll_tick(+ narrator_state,+ current_block_ts=block_ts,+ current_step_ts=step_ts,+ prior_block_ts=prior_block_ts,+ prior_step_ts=prior_step_ts,+ last_block_fetch_monotonic=last_block_fetch_monotonic,+ seen_block_states=seen_block_states,+ fetch_block_statuses=lambda: app.DATABASE.observer.get_workflow_run_blocks(+ workflow_run_id=workflow_run.workflow_run_id,+ organization_id=ctx.organization_id,+ ),+ stream=ctx.stream,+ )+ prior_block_ts = tick_result.prior_block_ts+ prior_step_ts = tick_result.prior_step_ts+ last_block_fetch_monotonic = tick_result.last_block_fetch_monotonic+if run and WorkflowRunStatus(run.status).is_final():final_status = run.statusexit_reason = "success"diff --git a/skyvern/forge/sdk/schemas/workflow_copilot.py b/skyvern/forge/sdk/schemas/workflow_copilot.pyindex 036c22fe0..89abd067b 100644--- a/skyvern/forge/sdk/schemas/workflow_copilot.py+++ b/skyvern/forge/sdk/schemas/workflow_copilot.py@@ -93,6 +93,7 @@ class WorkflowCopilotStreamMessageType(StrEnum):TOOL_RESULT = "tool_result"CONDENSING = "condensing"NARRATION = "narration"+ BLOCK_PROGRESS = "block_progress"class WorkflowCopilotProcessingUpdate(BaseModel):@@ -172,6 +173,21 @@ class WorkflowCopilotNarrationUpdate(BaseModel):timestamp: datetime = Field(..., description="Server timestamp")+class WorkflowCopilotBlockProgressUpdate(BaseModel):+ # Per-block lifecycle event from inside long-running tool calls.+ type: WorkflowCopilotStreamMessageType = Field(+ WorkflowCopilotStreamMessageType.BLOCK_PROGRESS, description="Message type"+ )+ workflow_run_block_id: str = Field(..., description="Stable per-block id; used as the row key in the activity pane")+ block_label: str = Field(..., description="Workflow block label (e.g. 'enter_name')")+ block_type: str = Field(..., description="Workflow block type (e.g. 'navigation', 'extraction')")+ status: str = Field(+ ..., description="BlockStatus value: running, completed, failed, terminated, timed_out, canceled, skipped"+ )+ iteration: int = Field(..., description="Agent loop iteration number this block belongs to")+ timestamp: datetime = Field(..., description="Server timestamp")++class WorkflowYAMLConversionRequest(BaseModel):workflow_definition_yaml: str = Field(..., description="Workflow definition YAML to convert to blocks")workflow_id: str = Field(..., description="Workflow ID")diff --git a/tests/unit/test_copilot_narration.py b/tests/unit/test_copilot_narration.pyindex cde455a01..36ec60674 100644--- a/tests/unit/test_copilot_narration.py+++ b/tests/unit/test_copilot_narration.py@@ -9,6 +9,7 @@ failure semantics -- the narrator must never be able to crash the agent run.from __future__ import annotationsimport asyncio+import timefrom types import SimpleNamespacefrom typing import Any@@ -25,6 +26,8 @@ from skyvern.forge.sdk.copilot.narration import (_sanitize_narration,cancel_in_flight,detect_transitions,+ narrator_poll_tick,+ record_block_transitions,schedule_narration,should_emit,snapshot_ctx,@@ -657,3 +660,549 @@ async def test_cancel_in_flight_returns_fast() -> None:await cancel_in_flight(state)elapsed = loop.time() - t0assert elapsed < 0.1, f"cancel_in_flight took {elapsed:.3f}s, expected <0.1s"+++# ---------------------------------------------------------------------------+# record_block_transitions+# ---------------------------------------------------------------------------+++def _snap(*entries: tuple[str, str]) -> list[tuple[str, str, str, str]]:+ """Test helper: lift (block_id, status) pairs into the (id, label, type, status) shape narrator_poll_tick produces."""+ return [(block_id, f"label_{block_id}", "navigation", status) for block_id, status in entries]+++def test_record_block_transitions_records_completed_on_running_to_completed() -> None:+ state = NarratorState()+ seen: dict[str, str] = {"b1": "running"}+ events = record_block_transitions(state, _snap(("b1", "completed")), seen, iteration=3)+ assert len(events) == 1+ assert events[0].kind == TransitionKind.BLOCK_COMPLETED+ assert events[0].block_label == "label_b1"+ assert state.pending_transition == TransitionKind.BLOCK_COMPLETED+ assert seen == {"b1": "completed"}+++def test_record_block_transitions_no_change_records_nothing() -> None:+ state = NarratorState()+ seen: dict[str, str] = {"b1": "running"}+ events = record_block_transitions(state, _snap(("b1", "running")), seen, iteration=0)+ assert events == []+ assert state.pending_transition is None+++def test_record_block_transitions_failed_terminated_timed_out_canceled_all_map_to_block_failed() -> None:+ for status in ("failed", "terminated", "timed_out", "canceled"):+ state = NarratorState()+ seen: dict[str, str] = {}+ events = record_block_transitions(state, _snap(("b1", status)), seen, iteration=0)+ assert len(events) == 1, f"status={status!r} should record"+ assert events[0].kind == TransitionKind.BLOCK_FAILED, f"status={status!r}"+ assert state.pending_transition == TransitionKind.BLOCK_FAILED, f"status={status!r}"+++def test_record_block_transitions_skipped_maps_to_block_completed() -> None:+ state = NarratorState()+ events = record_block_transitions(state, _snap(("b1", "skipped")), {}, iteration=0)+ assert len(events) == 1+ assert events[0].kind == TransitionKind.BLOCK_COMPLETED+ assert state.pending_transition == TransitionKind.BLOCK_COMPLETED+++def test_record_block_transitions_running_records_block_started() -> None:+ state = NarratorState()+ events = record_block_transitions(state, _snap(("b1", "running")), {}, iteration=0)+ assert len(events) == 1+ assert events[0].kind == TransitionKind.BLOCK_STARTED+ assert state.pending_transition == TransitionKind.BLOCK_STARTED+++def test_record_block_transitions_advances_seen_state_for_subsequent_calls() -> None:+ state = NarratorState()+ seen: dict[str, str] = {}+ record_block_transitions(state, _snap(("b1", "running")), seen, iteration=0)+ assert seen == {"b1": "running"}+ state.pending_transition = None+ events = record_block_transitions(state, _snap(("b1", "running")), seen, iteration=0)+ assert events == []+ assert state.pending_transition is None+ record_block_transitions(state, _snap(("b1", "completed")), seen, iteration=0)+ assert seen == {"b1": "completed"}+ assert state.pending_transition == TransitionKind.BLOCK_COMPLETED+++def test_record_block_transitions_returns_empty_when_nothing_changed() -> None:+ state = NarratorState()+ seen = {"b1": "completed"}+ assert record_block_transitions(state, _snap(("b1", "completed")), seen, iteration=0) == []+++def test_record_block_transitions_records_synthetic_activity_entry() -> None:+ state = NarratorState()+ record_block_transitions(state, _snap(("b1", "completed")), {}, iteration=4)+ assert len(state.pending_activity) == 1+ entry = state.pending_activity[0]+ assert entry.tool_name == "block_completed"+ assert entry.iteration == 4+ assert entry.success is True+++def test_record_block_transitions_skips_blocks_with_empty_id() -> None:+ state = NarratorState()+ seen: dict[str, str] = {}+ events = record_block_transitions(state, _snap(("", "completed")), seen, iteration=0)+ assert events == []+ assert seen == {}+++def test_record_block_transitions_skips_unknown_status() -> None:+ state = NarratorState()+ seen: dict[str, str] = {}+ events = record_block_transitions(state, _snap(("b1", "weird_state")), seen, iteration=0)+ assert events == []+ # seen still advances so we don't keep retrying an unknown status+ assert seen == {"b1": "weird_state"}+++# ---------------------------------------------------------------------------+# Transition priority (block kinds)+# ---------------------------------------------------------------------------+++def test_block_failed_priority_higher_than_block_completed() -> None:+ state = NarratorState()+ state.record_transition(TransitionKind.BLOCK_COMPLETED)+ state.record_transition(TransitionKind.BLOCK_FAILED)+ assert state.pending_transition == TransitionKind.BLOCK_FAILED+++def test_tool_in_progress_priority_above_tool_started_below_block_started() -> None:+ state = NarratorState()+ state.record_transition(TransitionKind.TOOL_STARTED)+ state.record_transition(TransitionKind.TOOL_IN_PROGRESS)+ assert state.pending_transition == TransitionKind.TOOL_IN_PROGRESS++ state2 = NarratorState()+ state2.record_transition(TransitionKind.TOOL_IN_PROGRESS)+ state2.record_transition(TransitionKind.BLOCK_STARTED)+ assert state2.pending_transition == TransitionKind.BLOCK_STARTED+++# ---------------------------------------------------------------------------+# should_emit attempt-bounded gate+# ---------------------------------------------------------------------------+++def test_should_emit_blocked_within_attempt_window_after_failure() -> None:+ # last_emitted_at is None (no successful delivery) but last_attempted_at+ # was set when a doomed narrator task was launched. The gate must still+ # block until MIN_NARRATION_GAP_SECONDS elapses, otherwise the polling+ # loop would re-fire the doomed narrator every 5s tick.+ state = NarratorState(+ last_emitted_at=None,+ last_attempted_at=100.0,+ pending_transition=TransitionKind.BLOCK_COMPLETED,+ )+ assert should_emit(state, now=100.0 + 1.0) is False+ assert should_emit(state, now=100.0 + MIN_NARRATION_GAP_SECONDS - 0.01) is False+ assert should_emit(state, now=100.0 + MIN_NARRATION_GAP_SECONDS + 0.01) is True+++def test_should_emit_uses_max_of_emitted_and_attempted_clocks() -> None:+ state = NarratorState(+ last_emitted_at=200.0,+ last_attempted_at=210.0,+ pending_transition=TransitionKind.BLOCK_COMPLETED,+ )+ # Window measured from 210 (later attempt), not 200 (older success).+ assert should_emit(state, now=210.0 + MIN_NARRATION_GAP_SECONDS - 0.5) is False+ assert should_emit(state, now=210.0 + MIN_NARRATION_GAP_SECONDS + 0.5) is True+++# ---------------------------------------------------------------------------+# narrator_poll_tick+# ---------------------------------------------------------------------------+++class _StubBlock:+ def __init__(self, block_id: str, status: str, label: str | None = None, block_type: str = "navigation") -> None:+ self.workflow_run_block_id = block_id+ self.status = status+ self.label = label if label is not None else f"label_{block_id}"+ self.block_type = block_type+++class _StubStream:+ def __init__(self) -> None:+ self.sent: list[Any] = []++ async def send(self, payload: Any) -> None:+ self.sent.append(payload)++ async def is_disconnected(self) -> bool:+ return False+++def _ts(seconds: float) -> Any:+ """Cheap unique timestamp marker for the helper -- equality is all that matters."""+ from datetime import datetime as _dt+ from datetime import timezone as _tz++ return _dt.fromtimestamp(seconds, tz=_tz.utc)+++async def test_poll_tick_block_ts_change_triggers_fetch_and_records_transition() -> None:+ state = NarratorState()+ stream = _StubStream()+ seen: dict[str, str] = {}+ fetch_calls = 0++ async def fetch() -> list[_StubBlock]:+ nonlocal fetch_calls+ fetch_calls += 1+ # Repository returns DESC; helper reverses internally.+ return [_StubBlock("b1", "completed"), _StubBlock("b0", "running")]++ new_block_ts, new_step_ts, new_last_fetch = await narrator_poll_tick(+ state,+ current_block_ts=_ts(2.0),+ current_step_ts=_ts(1.0),+ prior_block_ts=_ts(1.0),+ prior_step_ts=_ts(1.0),+ last_block_fetch_monotonic=0.0,+ seen_block_states=seen,+ fetch_block_statuses=fetch,+ stream=stream, # type: ignore[arg-type]+ )++ assert fetch_calls == 1+ assert seen == {"b0": "running", "b1": "completed"}+ # Activity buffer captures one synthetic entry per state transition. The+ # snapshot saw b0 (running) and b1 (completed), so two entries land.+ tool_names = [entry.tool_name for entry in state.pending_activity]+ assert "block_started" in tool_names+ assert "block_completed" in tool_names+ # schedule_narration was reached -- last_attempted_at advanced because+ # the gate was open (no prior emission, no in-flight task).+ assert state.last_attempted_at is not None+ assert new_block_ts == _ts(2.0)+ assert new_step_ts == _ts(1.0)+ assert new_last_fetch > 0.0+ # Drain the spawned narrator task so it doesn't outlive the test.+ if state.in_flight_task is not None:+ state.in_flight_task.cancel()+ try:+ await state.in_flight_task+ except (asyncio.CancelledError, Exception):+ pass+++async def test_poll_tick_step_ts_change_alone_records_tool_in_progress() -> None:+ # Pre-populate last_attempted_at so the gate is closed and the+ # TOOL_IN_PROGRESS transition stays in pending_transition for inspection+ # rather than being drained by schedule_narration.+ state = NarratorState(last_attempted_at=time.monotonic())+ stream = _StubStream()+ seen: dict[str, str] = {}+ fetch_calls = 0++ async def fetch() -> list[_StubBlock]:+ nonlocal fetch_calls+ fetch_calls += 1+ return []++ same_block_ts = _ts(1.0)+ await narrator_poll_tick(+ state,+ current_block_ts=same_block_ts,+ current_step_ts=_ts(2.0),+ prior_block_ts=same_block_ts,+ prior_step_ts=_ts(1.0),+ last_block_fetch_monotonic=0.0,+ seen_block_states=seen,+ fetch_block_statuses=fetch,+ stream=stream, # type: ignore[arg-type]+ )++ assert fetch_calls == 0 # block_ts didn't change+ assert state.pending_transition == TransitionKind.TOOL_IN_PROGRESS+++async def test_poll_tick_no_change_still_calls_schedule_narration() -> None:+ """Pending transitions latched while the gate was closed must drain on+ subsequent ticks even when no fresh block/step signal arrives."""+ state = NarratorState(pending_transition=TransitionKind.BLOCK_COMPLETED)+ stream = _StubStream()++ async def fetch() -> list[_StubBlock]:+ raise AssertionError("fetch should not be called when block_ts is unchanged")++ same_ts = _ts(1.0)+ await narrator_poll_tick(+ state,+ current_block_ts=same_ts,+ current_step_ts=same_ts,+ prior_block_ts=same_ts,+ prior_step_ts=same_ts,+ last_block_fetch_monotonic=0.0,+ seen_block_states={},+ fetch_block_statuses=fetch,+ stream=stream, # type: ignore[arg-type]+ )++ # schedule_narration was invoked. With no in-flight task, no last_emitted+ # clock, and a pending transition, it should have launched a task --+ # detected by last_attempted_at advancing.+ assert state.last_attempted_at is not None+ assert state.in_flight_task is not None+ state.in_flight_task.cancel()+ try:+ await state.in_flight_task+ except (asyncio.CancelledError, Exception):+ pass+++async def test_poll_tick_rate_limited_block_change_retries_on_next_tick() -> None:+ """A block_ts change inside the rate-limit window must not advance+ prior_block_ts -- the next tick must still see the diff."""+ state = NarratorState()+ stream = _StubStream()+ seen: dict[str, str] = {}+ fetch_calls = 0++ async def fetch() -> list[_StubBlock]:+ nonlocal fetch_calls+ fetch_calls += 1+ return [_StubBlock("b1", "completed")]++ fresh_now = time.monotonic()+ next_block_ts, _, next_last_fetch = await narrator_poll_tick(+ state,+ current_block_ts=_ts(2.0),+ current_step_ts=_ts(1.0),+ prior_block_ts=_ts(1.0),+ prior_step_ts=_ts(1.0),+ # Last fetch a moment ago -- gate closed.+ last_block_fetch_monotonic=fresh_now,+ seen_block_states=seen,+ fetch_block_statuses=fetch,+ stream=stream, # type: ignore[arg-type]+ )++ assert fetch_calls == 0+ # prior_block_ts must NOT have advanced -- the diff is still alive.+ assert next_block_ts == _ts(1.0)+ assert next_last_fetch == fresh_now+++async def test_poll_tick_fetch_exception_retries_on_next_tick() -> None:+ """A fetch raising must not advance prior_block_ts."""+ state = NarratorState()+ stream = _StubStream()+ seen: dict[str, str] = {}+ fetch_calls = 0++ async def fetch() -> list[_StubBlock]:+ nonlocal fetch_calls+ fetch_calls += 1+ raise RuntimeError("db transient failure")++ next_block_ts, _, next_last_fetch = await narrator_poll_tick(+ state,+ current_block_ts=_ts(2.0),+ current_step_ts=_ts(1.0),+ prior_block_ts=_ts(1.0),+ prior_step_ts=_ts(1.0),+ last_block_fetch_monotonic=0.0,+ seen_block_states=seen,+ fetch_block_statuses=fetch,+ stream=stream, # type: ignore[arg-type]+ )++ assert fetch_calls == 1+ # prior_block_ts unchanged (still 1.0) so the next tick retries.+ assert next_block_ts == _ts(1.0)+ # Rate-limit clock still advances so we don't hammer the DB on errors.+ assert next_last_fetch > 0.0+ # No transition recorded (snapshot unavailable, no step diff).+ assert state.pending_transition is None+++async def test_poll_tick_first_tick_with_zero_initial_fetch_marker_does_not_raise() -> None:+ """`last_block_fetch_monotonic` is initialized to 0.0 (not None) so the+ first tick can compute now - 0.0 without TypeError."""+ state = NarratorState()+ stream = _StubStream()++ async def fetch() -> list[_StubBlock]:+ return [_StubBlock("b1", "running")]++ new_block_ts, new_step_ts, new_last_fetch = await narrator_poll_tick(+ state,+ current_block_ts=_ts(2.0),+ current_step_ts=_ts(1.0),+ prior_block_ts=_ts(1.0),+ prior_step_ts=_ts(1.0),+ last_block_fetch_monotonic=0.0,+ seen_block_states={},+ fetch_block_statuses=fetch,+ stream=stream, # type: ignore[arg-type]+ )++ assert new_block_ts == _ts(2.0)+ assert new_last_fetch > 0.0+++async def test_poll_tick_uses_state_current_iteration_for_synthetic_entries() -> None:+ state = NarratorState(current_iteration=7)+ stream = _StubStream()+ seen: dict[str, str] = {}++ async def fetch() -> list[_StubBlock]:+ return [_StubBlock("b1", "completed")]++ await narrator_poll_tick(+ state,+ current_block_ts=_ts(2.0),+ current_step_ts=_ts(1.0),+ prior_block_ts=_ts(1.0),+ prior_step_ts=_ts(1.0),+ last_block_fetch_monotonic=0.0,+ seen_block_states=seen,+ fetch_block_statuses=fetch,+ stream=stream, # type: ignore[arg-type]+ )++ assert state.pending_activity[-1].iteration == 7+ # Drain the spawned narrator task so it doesn't outlive the test.+ if state.in_flight_task is not None:+ state.in_flight_task.cancel()+ try:+ await state.in_flight_task+ except (asyncio.CancelledError, Exception):+ pass+++# ---------------------------------------------------------------------------+# narrator_poll_tick block_progress SSE emissions+# ---------------------------------------------------------------------------+++async def test_poll_tick_emits_block_progress_for_each_new_transition() -> None:+ from skyvern.forge.sdk.schemas.workflow_copilot import (+ WorkflowCopilotBlockProgressUpdate,+ WorkflowCopilotStreamMessageType,+ )++ state = NarratorState()+ stream = _StubStream()+ seen: dict[str, str] = {}++ async def fetch() -> list[_StubBlock]:+ # DESC by created_at; helper reverses for chronological order.+ return [+ _StubBlock("b1", "completed", label="step_extract", block_type="extraction"),+ _StubBlock("b0", "running", label="step_navigate", block_type="navigation"),+ ]++ await narrator_poll_tick(+ state,+ current_block_ts=_ts(2.0),+ current_step_ts=_ts(1.0),+ prior_block_ts=_ts(1.0),+ prior_step_ts=_ts(1.0),+ last_block_fetch_monotonic=0.0,+ seen_block_states=seen,+ fetch_block_statuses=fetch,+ stream=stream, # type: ignore[arg-type]+ )++ progress_payloads = [p for p in stream.sent if isinstance(p, WorkflowCopilotBlockProgressUpdate)]+ assert len(progress_payloads) == 2+ # Chronological order (running step_navigate first, completed step_extract second).+ assert progress_payloads[0].block_label == "step_navigate"+ assert progress_payloads[0].status == "running"+ assert progress_payloads[0].block_type == "navigation"+ assert progress_payloads[0].type == WorkflowCopilotStreamMessageType.BLOCK_PROGRESS+ assert progress_payloads[0].workflow_run_block_id == "b0"+ assert progress_payloads[1].block_label == "step_extract"+ assert progress_payloads[1].status == "completed"+ assert progress_payloads[1].block_type == "extraction"+ assert progress_payloads[1].workflow_run_block_id == "b1"+ # Drain the narrator task spawned by schedule_narration.+ if state.in_flight_task is not None:+ state.in_flight_task.cancel()+ try:+ await state.in_flight_task+ except (asyncio.CancelledError, Exception):+ pass+++async def test_poll_tick_does_not_emit_block_progress_for_unchanged_blocks() -> None:+ from skyvern.forge.sdk.schemas.workflow_copilot import WorkflowCopilotBlockProgressUpdate++ state = NarratorState()+ stream = _StubStream()+ seen: dict[str, str] = {"b1": "completed"}++ async def fetch() -> list[_StubBlock]:+ return [_StubBlock("b1", "completed", label="step_extract", block_type="extraction")]++ await narrator_poll_tick(+ state,+ current_block_ts=_ts(2.0),+ current_step_ts=_ts(1.0),+ prior_block_ts=_ts(1.0),+ prior_step_ts=_ts(1.0),+ last_block_fetch_monotonic=0.0,+ seen_block_states=seen,+ fetch_block_statuses=fetch,+ stream=stream, # type: ignore[arg-type]+ )++ assert [p for p in stream.sent if isinstance(p, WorkflowCopilotBlockProgressUpdate)] == []+++async def test_poll_tick_skips_block_progress_when_label_blank() -> None:+ from skyvern.forge.sdk.schemas.workflow_copilot import WorkflowCopilotBlockProgressUpdate++ state = NarratorState()+ stream = _StubStream()+ seen: dict[str, str] = {}++ async def fetch() -> list[_StubBlock]:+ # Block with empty label -- nothing readable to show in the FE bullet.+ return [_StubBlock("b1", "completed", label="", block_type="extraction")]++ await narrator_poll_tick(+ state,+ current_block_ts=_ts(2.0),+ current_step_ts=_ts(1.0),+ prior_block_ts=_ts(1.0),+ prior_step_ts=_ts(1.0),+ last_block_fetch_monotonic=0.0,+ seen_block_states=seen,+ fetch_block_statuses=fetch,+ stream=stream, # type: ignore[arg-type]+ )++ assert [p for p in stream.sent if isinstance(p, WorkflowCopilotBlockProgressUpdate)] == []+ # Internal state still updates (transition recorded for narrator) -- this only suppresses the FE bullet.+ assert seen == {"b1": "completed"}+ # Drain narrator task.+ if state.in_flight_task is not None:+ state.in_flight_task.cancel()+ try:+ await state.in_flight_task+ except (asyncio.CancelledError, Exception):+ pass