Automate browser based workflows with AI
Python aiapiautomationbrowserbrowser-automationcomputergptllmplaywrightpowerautomatepuppeteerpythonrpaseleniumvisionworkflow
fix(SKY-10474): make Copilot activity results product-safe (#6337)
Andrew Neilson98fba7773c6e
diff --git a/skyvern-frontend/src/routes/workflows/copilot/NarrativeView.test.ts b/skyvern-frontend/src/routes/workflows/copilot/NarrativeView.test.tsindex ce0e80426..5a5b59330 100644--- a/skyvern-frontend/src/routes/workflows/copilot/NarrativeView.test.ts+++ b/skyvern-frontend/src/routes/workflows/copilot/NarrativeView.test.ts@@ -12,6 +12,7 @@ import {WorkflowCopilotDesignStartUpdate,WorkflowCopilotStreamErrorUpdate,WorkflowCopilotStreamResponseUpdate,+ WorkflowCopilotToolCallUpdate,WorkflowCopilotTurnStartUpdate,WorkflowCopilotWorkflowDraftUpdate,} from "./workflowCopilotTypes";@@ -60,6 +61,18 @@ const blockProgress = (...overrides,});+const toolCall = (+ overrides: Partial<WorkflowCopilotToolCallUpdate> = {},+): WorkflowCopilotToolCallUpdate => ({+ type: "tool_call",+ tool_name: "update_and_run_blocks",+ display_label: "Testing workflow",+ tool_input: {},+ iteration: 0,+ tool_call_id: "call-1",+ ...overrides,+});+const response = (overrides: Partial<WorkflowCopilotStreamResponseUpdate> = {},): WorkflowCopilotStreamResponseUpdate => ({@@ -320,6 +333,21 @@ describe("applyNarrativeEvent — block_progress", () => {});});+describe("applyNarrativeEvent — activity", () => {+ it("renders product-safe labels for internal tool calls", () => {+ const s = applyNarrativeEvent(EMPTY_NARRATIVE, toolCall());++ expect(s.designActivity).toHaveLength(1);+ expect(s.designActivity[0]).toMatchObject({+ kind: "tool_call",+ toolName: "update_and_run_blocks",+ displayLabel: "Testing workflow",+ text: "Testing workflow…",+ });+ expect(s.designActivity[0]?.text).not.toContain("update_and_run_blocks");+ });+});+describe("applyNarrativeEvent — terminal", () => {it("response closes designEnded and uses narrative_summary when present", () => {let s = applyNarrativeEvent(EMPTY_NARRATIVE, designStart());diff --git a/skyvern-frontend/src/routes/workflows/copilot/NarrativeView.tsx b/skyvern-frontend/src/routes/workflows/copilot/NarrativeView.tsxindex 6b1b93225..7c51db1d7 100644--- a/skyvern-frontend/src/routes/workflows/copilot/NarrativeView.tsx+++ b/skyvern-frontend/src/routes/workflows/copilot/NarrativeView.tsx@@ -6,6 +6,7 @@ import {TurnNarrativeState,effectiveMode,parseUtcIsoMs,+ toolActivityDisplayLabel,} from "./narrativeState";interface BlockPalette {@@ -173,9 +174,11 @@ function ActivityRow({ entry }: { entry: ActivityEntry }) {);}if (entry.kind === "tool_call") {+ const label =+ entry.displayLabel ?? toolActivityDisplayLabel(entry.toolName);return (<FSubRow glyph="▸" glyphClass="text-slate-400">- <span className="font-mono text-slate-200">{entry.toolName}</span>+ <span className="text-slate-200">{label}</span><span className="text-slate-500"> · calling…</span></FSubRow>);diff --git a/skyvern-frontend/src/routes/workflows/copilot/narrativeState.ts b/skyvern-frontend/src/routes/workflows/copilot/narrativeState.tsindex 926f078af..a7d3f2e57 100644--- a/skyvern-frontend/src/routes/workflows/copilot/narrativeState.ts+++ b/skyvern-frontend/src/routes/workflows/copilot/narrativeState.ts@@ -67,6 +67,8 @@ export interface ActivityEntry {iteration: number;// Tool name when kind is tool_call/tool_result.toolName?: string;+ // Product-safe label for rendering tool activity to users.+ displayLabel?: string;// Result success when kind is tool_result.success?: boolean;// Stable per-event id used as React key.@@ -145,17 +147,41 @@ const ACTIVITY_TOOL_DENYLIST = new Set(["get_browser_screenshot",]);+// Mirror of the backend _TOOL_ACTIVITY_DISPLAY_LABELS in narration.py.+const ACTIVITY_TOOL_DISPLAY_LABELS: Record<string, string> = {+ update_workflow: "Updating workflow",+ update_and_run_blocks: "Testing workflow",+ run_blocks_and_collect_debug: "Testing workflow",+ evaluate: "Inspecting page",+ click: "Interacting with page",+ type_text: "Entering text",+ scroll: "Interacting with page",+ select_option: "Selecting option",+ press_key: "Interacting with page",+ navigate_browser: "Opening page",+ get_block_schema: "Checking workflow block options",+ inspect_current_workflow: "Inspecting workflow",+};++export function toolActivityDisplayLabel(toolName?: string | null): string {+ if (!toolName) return "Working";+ return ACTIVITY_TOOL_DISPLAY_LABELS[toolName] ?? "Working";+}+function buildActivityFromToolCall(event: WorkflowCopilotToolCallUpdate,): ActivityEntry | null {if (ACTIVITY_TOOL_DENYLIST.has(event.tool_name)) {return null;}+ const displayLabel =+ event.display_label ?? toolActivityDisplayLabel(event.tool_name);return {kind: "tool_call",- text: `Calling ${event.tool_name}…`,+ text: `${displayLabel}…`,iteration: event.iteration,toolName: event.tool_name,+ displayLabel,id: `tc-${event.tool_call_id}`,};}@@ -166,11 +192,13 @@ function buildActivityFromToolResult(if (ACTIVITY_TOOL_DENYLIST.has(event.tool_name)) {return null;}+ const displayLabel = toolActivityDisplayLabel(event.tool_name);return {kind: "tool_result",- text: event.summary || event.tool_name,+ text: event.summary || displayLabel,iteration: event.iteration,toolName: event.tool_name,+ displayLabel,success: event.success,id: `tr-${event.tool_call_id}`,};@@ -464,6 +492,8 @@ function normalizeActivityEntries(raw: unknown): ActivityEntry[] {text: o.text,iteration: typeof o.iteration === "number" ? o.iteration : 0,toolName: typeof o.toolName === "string" ? o.toolName : undefined,+ displayLabel:+ typeof o.displayLabel === "string" ? o.displayLabel : undefined,success: typeof o.success === "boolean" ? o.success : undefined,id: o.id,});diff --git a/skyvern-frontend/src/routes/workflows/copilot/workflowCopilotTypes.ts b/skyvern-frontend/src/routes/workflows/copilot/workflowCopilotTypes.tsindex 802864479..0e4383d6b 100644--- a/skyvern-frontend/src/routes/workflows/copilot/workflowCopilotTypes.ts+++ b/skyvern-frontend/src/routes/workflows/copilot/workflowCopilotTypes.ts@@ -149,6 +149,7 @@ export interface WorkflowCopilotWorkflowDraftUpdate {export interface WorkflowCopilotToolCallUpdate {type: "tool_call";tool_name: string;+ display_label?: string | null;tool_input: Record<string, unknown>;iteration: number;tool_call_id: string;diff --git a/skyvern/forge/sdk/copilot/blocker_signal.py b/skyvern/forge/sdk/copilot/blocker_signal.pyindex 2be227420..16259082f 100644--- a/skyvern/forge/sdk/copilot/blocker_signal.py+++ b/skyvern/forge/sdk/copilot/blocker_signal.py@@ -117,6 +117,8 @@ def to_trace_data(signal: CopilotToolBlockerSignal) -> dict[str, Any]:class _BlockerSignalCtx(Protocol):blocker_signal: CopilotToolBlockerSignal | None+ latest_tool_blocker_signal: CopilotToolBlockerSignal | None+ tool_blocker_signals: list[CopilotToolBlockerSignal]_LOOP_PROGRESS_TOOL_SUCCESS_REASON_CODES = frozenset(@@ -165,6 +167,16 @@ def clear_blocker_signal_for_reason_codes(ctx: _BlockerSignalCtx, internal_reasodef stash_blocker_signal(ctx: _BlockerSignalCtx, signal: CopilotToolBlockerSignal) -> str:"""First-wins stash + observability log; returns the LLM-visible payload."""+ ctx.latest_tool_blocker_signal = signal+ # Keep the defensive guard for tests and partial context shims even though+ # real Copilot contexts type this field as a list.+ history = getattr(ctx, "tool_blocker_signals", None)+ if not isinstance(history, list):+ history = []+ ctx.tool_blocker_signals = history+ history.append(signal)+ if len(history) > 20:+ del history[:-20]existing = getattr(ctx, "blocker_signal", None)stashed = not isinstance(existing, CopilotToolBlockerSignal)if stashed:diff --git a/skyvern/forge/sdk/copilot/context.py b/skyvern/forge/sdk/copilot/context.pyindex ff7845168..e2fadacc4 100644--- a/skyvern/forge/sdk/copilot/context.py+++ b/skyvern/forge/sdk/copilot/context.py@@ -33,6 +33,7 @@ class NarrativeActivityEntry(TypedDict):text: striteration: inttoolName: NotRequired[str]+ displayLabel: NotRequired[str]success: NotRequired[bool]id: str@@ -67,6 +68,7 @@ class TurnNarrativePayload(TypedDict):if TYPE_CHECKING:+ from skyvern.forge.sdk.copilot.blocker_signal import CopilotToolBlockerSignalfrom skyvern.forge.sdk.copilot.diagnosis_repair_contract import DiagnosisRepairContractfrom skyvern.forge.sdk.copilot.narration import NarratorStatefrom skyvern.forge.sdk.copilot.request_policy import RequestPolicy@@ -320,6 +322,8 @@ class CopilotContext(AgentContext):# Tool trackingconsecutive_tool_tracker: list[str] = field(default_factory=list)tool_activity: list[dict[str, Any]] = field(default_factory=list)+ latest_tool_blocker_signal: CopilotToolBlockerSignal | None = None+ tool_blocker_signals: list[CopilotToolBlockerSignal] = field(default_factory=list)# ``None`` until usage is observed; ``0`` only when a provider explicitly# reported zero. Distinct values let cost grading flag missing telemetry.diff --git a/skyvern/forge/sdk/copilot/narration.py b/skyvern/forge/sdk/copilot/narration.pyindex 5cc2f97b9..15b4e7a59 100644--- a/skyvern/forge/sdk/copilot/narration.py+++ b/skyvern/forge/sdk/copilot/narration.py@@ -66,15 +66,38 @@ MAX_DESIGN_ACTIVITY_ENTRIES = 50# Mirror of the FE ACTIVITY_TOOL_DENYLIST in narrativeState.ts.ACTIVITY_TOOL_DENYLIST = frozenset({"list_credentials", "get_run_results", "get_browser_screenshot"})+_TOOL_ACTIVITY_DISPLAY_LABELS = {+ # Mirror of the FE ACTIVITY_TOOL_DISPLAY_LABELS in narrativeState.ts.+ "update_workflow": "Updating workflow",+ "update_and_run_blocks": "Testing workflow",+ "run_blocks_and_collect_debug": "Testing workflow",+ "evaluate": "Inspecting page",+ "click": "Interacting with page",+ "type_text": "Entering text",+ "scroll": "Interacting with page",+ "select_option": "Selecting option",+ "press_key": "Interacting with page",+ "navigate_browser": "Opening page",+ "get_block_schema": "Checking workflow block options",+ "inspect_current_workflow": "Inspecting workflow",+}+++def tool_activity_display_label(tool_name: str) -> str:+ """Return a product-safe label for user-visible activity rows."""+ return _TOOL_ACTIVITY_DISPLAY_LABELS.get(tool_name, "Working")+def build_tool_call_activity(tool_name: str, iteration: int, tool_call_id: str) -> NarrativeActivityEntry | None:if tool_name in ACTIVITY_TOOL_DENYLIST:return None+ display_label = tool_activity_display_label(tool_name)return {"kind": "tool_call",- "text": f"Calling {tool_name}…",+ "text": f"{display_label}…","iteration": iteration,"toolName": tool_name,+ "displayLabel": display_label,"id": f"tc-{tool_call_id}",}@@ -84,11 +107,13 @@ def build_tool_result_activity() -> NarrativeActivityEntry | None:if tool_name in ACTIVITY_TOOL_DENYLIST:return None+ display_label = tool_activity_display_label(tool_name)return {"kind": "tool_result",- "text": summary or tool_name,+ "text": summary or display_label,"iteration": iteration,"toolName": tool_name,+ "displayLabel": display_label,"success": success,"id": f"tr-{tool_call_id}",}diff --git a/skyvern/forge/sdk/copilot/output_utils.py b/skyvern/forge/sdk/copilot/output_utils.pyindex 802b56280..fafa166b8 100644--- a/skyvern/forge/sdk/copilot/output_utils.py+++ b/skyvern/forge/sdk/copilot/output_utils.py@@ -6,10 +6,11 @@ import base64import binasciiimport jsonimport re-from collections.abc import Iterator+from collections.abc import Iterable, Iteratorfrom typing import TYPE_CHECKING, Anyfrom skyvern.forge.sdk.agents.context import sanitize_agent_tool_result_for_llm as sanitize_generic_tool_result_for_llm+from skyvern.forge.sdk.copilot.blocker_signal import CopilotToolBlockerSignal, assert_clean_user_facing_textfrom skyvern.forge.sdk.copilot.context import COPILOT_RESPONSE_TYPESfrom skyvern.forge.sdk.copilot.loop_detection import LOOP_DETECTED_MARKERfrom skyvern.schemas.workflows import BlockType@@ -306,6 +307,9 @@ def iter_failure_reasons(result: dict[str, Any]) -> Iterator[str]:_UNKNOWN_ERROR_SENTINEL = "Unknown error"+_PER_TOOL_BUDGET_FAILURE_CATEGORY = "PER_TOOL_BUDGET"+_USER_FACING_SUMMARY_KEYS: tuple[str, ...] = ("user_facing_summary", "user_facing_reason")+_STRUCTURED_UNSAFE_FALLBACK = "Couldn't complete that step."def _extract_failure_message(result: dict[str, Any]) -> str:@@ -318,6 +322,101 @@ def _extract_failure_message(result: dict[str, Any]) -> str:return next(iter_failure_reasons(result), _UNKNOWN_ERROR_SENTINEL)+def _result_data(result: dict[str, Any]) -> dict[str, Any]:+ data = result.get("data")+ return data if isinstance(data, dict) else {}+++def _clean_structured_user_facing_text(value: Any, *, blocked_tool: str | None = None) -> str | None:+ if not isinstance(value, str):+ return None+ cleaned = " ".join(value.split())+ if not cleaned:+ return None+ try:+ assert_clean_user_facing_text(cleaned, blocked_tool=blocked_tool)+ except ValueError:+ return None+ return cleaned+++def _blocker_signal_matches_result(signal: CopilotToolBlockerSignal, result: dict[str, Any]) -> bool:+ error = result.get("error")+ if not isinstance(error, str) or not error:+ return False+ steering = signal.agent_steering_text+ return error == steering or steering in error+++def _failure_categories(result: dict[str, Any]) -> list[Any]:+ data = _result_data(result)+ categories = data.get("failure_categories")+ return categories if isinstance(categories, list) else []+++def _has_failure_category(result: dict[str, Any], category: str) -> bool:+ for item in _failure_categories(result):+ if isinstance(item, dict) and item.get("category") == category:+ return True+ return False+++def _iter_blocker_signals(+ blocker_signal: CopilotToolBlockerSignal | Iterable[CopilotToolBlockerSignal] | None,+) -> Iterator[CopilotToolBlockerSignal]:+ if isinstance(blocker_signal, CopilotToolBlockerSignal):+ yield blocker_signal+ return+ if blocker_signal is None:+ return+ for signal in blocker_signal:+ if isinstance(signal, CopilotToolBlockerSignal):+ yield signal+++def _structured_failure_summary_for_user(+ result: dict[str, Any],+ *,+ blocker_signal: CopilotToolBlockerSignal | Iterable[CopilotToolBlockerSignal] | None = None,+ blocked_tool: str | None = None,+) -> str | None:+ if result.get("ok", False):+ return None++ for signal in _iter_blocker_signals(blocker_signal):+ if _blocker_signal_matches_result(signal, result):+ return (+ _clean_structured_user_facing_text(+ signal.user_facing_reason,+ blocked_tool=signal.blocked_tool or blocked_tool,+ )+ or _STRUCTURED_UNSAFE_FALLBACK+ )++ data = _result_data(result)+ saw_structured_summary = False+ for container in (result, data):+ for key in _USER_FACING_SUMMARY_KEYS:+ raw_value = container.get(key)+ if isinstance(raw_value, str) and raw_value.strip():+ saw_structured_summary = True+ summary = _clean_structured_user_facing_text(raw_value, blocked_tool=blocked_tool)+ if summary is not None:+ return summary+ if saw_structured_summary:+ return _STRUCTURED_UNSAFE_FALLBACK++ if _has_failure_category(result, _PER_TOOL_BUDGET_FAILURE_CATEGORY):+ # An explicit but empty failure_reason still means the structured+ # watchdog path fired; use the generic safe copy rather than raw error+ # fallback.+ return _clean_structured_user_facing_text(data.get("failure_reason"), blocked_tool=blocked_tool) or (+ _STRUCTURED_UNSAFE_FALLBACK if isinstance(data.get("failure_reason"), str) else None+ )++ return None++_HEADERS_BLOB_RE = re.compile(r"\s*headers:\s*\{[^{}]*\}\s*", re.IGNORECASE)_LARGE_DICT_BLOB_RE = re.compile(r"\{[^{}]{40,}\}")@@ -429,10 +528,19 @@ def build_run_blocks_response(run_ok: bool, result_data: dict[str, Any]) -> dictreturn response-def summarize_tool_result_detail(result: dict[str, Any], max_chars: int = 800) -> str | None:+def summarize_tool_result_detail(+ result: dict[str, Any],+ max_chars: int = 800,+ *,+ tool_name: str | None = None,+ blocker_signal: CopilotToolBlockerSignal | Iterable[CopilotToolBlockerSignal] | None = None,+) -> str | None:"""Tooltip-grade failure detail (longer cap than ``summarize_tool_result``); None on success."""if result.get("ok", False):return None+ structured = _structured_failure_summary_for_user(result, blocker_signal=blocker_signal, blocked_tool=tool_name)+ if structured is not None:+ return structuredreturn _sanitize_failure_text(_extract_failure_message(result), max_chars=max_chars)@@ -451,7 +559,7 @@ _USE_TOOL_NAME_RE = re.compile(r"use the ['\"]?[a-z_][a-z0-9_]*['\"]? tool", re._USER_FACING_LOOP_MESSAGE = "The agent got stuck retrying the same step — moving on."_USER_FACING_JINJA_MESSAGE = "A workflow parameter could not be filled in."-_USER_FACING_GENERIC_FAILURE = "Couldn't complete that step."+_USER_FACING_GENERIC_FAILURE = _STRUCTURED_UNSAFE_FALLBACK_USER_FACING_EMPTY_SUCCESS_TOOLS: frozenset[str] = frozenset({"click", "type_text", "evaluate", "select_option"})@@ -471,13 +579,21 @@ def _translate_failure_for_user(error_text: str) -> str:return f"Failed: {_sanitize_failure_text(error_text)}"-def format_tool_result_for_user(tool_name: str, result: dict[str, Any]) -> str:+def format_tool_result_for_user(+ tool_name: str,+ result: dict[str, Any],+ *,+ blocker_signal: CopilotToolBlockerSignal | Iterable[CopilotToolBlockerSignal] | None = None,+) -> str:"""SSE-bound counterpart to summarize_tool_result; do not mix the two.summarize_tool_result is parsed by context.merge_turn_summary for stateextraction — rewriting it would corrupt agent state."""if not result.get("ok", False):+ structured = _structured_failure_summary_for_user(result, blocker_signal=blocker_signal, blocked_tool=tool_name)+ if structured is not None:+ return structuredreturn _translate_failure_for_user(_extract_failure_message(result))if tool_name in _USER_FACING_EMPTY_SUCCESS_TOOLS:return ""diff --git a/skyvern/forge/sdk/copilot/runtime.py b/skyvern/forge/sdk/copilot/runtime.pyindex 6201f4261..1b05aaa85 100644--- a/skyvern/forge/sdk/copilot/runtime.py+++ b/skyvern/forge/sdk/copilot/runtime.py@@ -197,6 +197,11 @@ class AgentContext:# turn end and overrides the AgentResult with a deterministic# product-language reply. See blocker_signal.py for the contract.blocker_signal: CopilotToolBlockerSignal | None = None+ # Most recently emitted blocker signal for the current tool output. Unlike+ # blocker_signal, this is last-wins so the activity-log projection can+ # render the current tool result from structured product text.+ latest_tool_blocker_signal: CopilotToolBlockerSignal | None = None+ tool_blocker_signals: list[CopilotToolBlockerSignal] = field(default_factory=list)def mcp_to_copilot(mcp_result: dict[str, Any]) -> dict[str, Any]:diff --git a/skyvern/forge/sdk/copilot/streaming_adapter.py b/skyvern/forge/sdk/copilot/streaming_adapter.pyindex 8ddf7c011..ffa10d974 100644--- a/skyvern/forge/sdk/copilot/streaming_adapter.py+++ b/skyvern/forge/sdk/copilot/streaming_adapter.py@@ -23,6 +23,7 @@ from skyvern.forge.sdk.copilot.narration import (resolve_narrator_handler,schedule_narration,snapshot_ctx,+ tool_activity_display_label,)from skyvern.forge.sdk.copilot.output_utils import format_tool_result_for_user, summarize_tool_result_detailfrom skyvern.forge.sdk.schemas.workflow_copilot import (@@ -152,6 +153,7 @@ async def stream_to_sse(WorkflowCopilotToolCallUpdate(type=WorkflowCopilotStreamMessageType.TOOL_CALL,tool_name=tool_name,+ display_label=tool_activity_display_label(tool_name),tool_input=_sanitize_input(tool_input),iteration=iteration,tool_call_id=call_id,@@ -176,9 +178,10 @@ async def stream_to_sse(output = getattr(event.item, "output", None)parsed = parse_tool_output(output)- summary = format_tool_result_for_user(tool_name, parsed)+ blocker_signals = _tool_blocker_signal_candidates(ctx)+ summary = format_tool_result_for_user(tool_name, parsed, blocker_signal=blocker_signals)success = parsed.get("ok", True)- detail = summarize_tool_result_detail(parsed)+ detail = summarize_tool_result_detail(parsed, tool_name=tool_name, blocker_signal=blocker_signals)narrator_state.record_activity(build_tool_result_activity(tool_name, summary, success, iteration, call_id))@@ -223,6 +226,9 @@ async def stream_to_sse(except CopilotUnrecoverableToolError:result.cancel()raise+ # Keep latest_tool_blocker_signal scoped to the tool result+ # that immediately follows the blocker-producing tool call.+ ctx.latest_tool_blocker_signal = Noneiteration += 1except asyncio.CancelledError:# Real cancellation (server shutdown, upstream abort). Propagate so@@ -242,6 +248,28 @@ def _get_raw_field(raw: Any, key: str) -> Any:return getattr(raw, key, None)+def _tool_blocker_signal_candidates(ctx: Any) -> list[Any]:+ candidates: list[Any] = []+ latest = getattr(ctx, "latest_tool_blocker_signal", None)+ if latest is not None:+ candidates.append(latest)+ history = getattr(ctx, "tool_blocker_signals", None)+ if isinstance(history, list):+ candidates.extend(reversed(history))+ sticky = getattr(ctx, "blocker_signal", None)+ if sticky is not None:+ candidates.append(sticky)+ deduped: list[Any] = []+ seen_ids: set[int] = set()+ for candidate in candidates:+ candidate_id = id(candidate)+ if candidate_id in seen_ids:+ continue+ seen_ids.add(candidate_id)+ deduped.append(candidate)+ return deduped++def _extract_text_content(item: Any) -> str | None:"""Extract text from a dict or object with type='text', returning None otherwise."""if isinstance(item, dict):diff --git a/skyvern/forge/sdk/copilot/tools.py b/skyvern/forge/sdk/copilot/tools.pyindex ec25d8910..c43d17a6c 100644--- a/skyvern/forge/sdk/copilot/tools.py+++ b/skyvern/forge/sdk/copilot/tools.py@@ -3264,6 +3264,22 @@ def _watchdog_user_failure_reason(return f"{body} Run ID: {workflow_run_id}. Outcome is uncertain."+def _watchdog_user_facing_summary(+ exit_reason: WatchdogExitReason,+ budget_seconds: int,+ run: WorkflowRun | None,+) -> str:+ if exit_reason == "stagnation":+ return f"The run stopped after no observable progress for {RUN_BLOCKS_STAGNATION_WINDOW_SECONDS}s."+ if exit_reason == "per_tool_budget":+ return f"The run exceeded the {budget_seconds}s per-tool-call budget while still making progress."+ if exit_reason == "ceiling":+ return f"The run exceeded the {budget_seconds}s absolute ceiling while still showing progress."+ if run is not None:+ return f"The run ended before recording a trustworthy terminal status. Last observed status: {run.status}."+ return "The run ended before recording a trustworthy terminal status."++def _workflow_with_runtime_block_goal_context(workflow: Workflow, ctx: CopilotContext) -> Workflow:block_goal_main_goal = ctx.block_goal_main_goal or ctx.user_message or ""if not block_goal_main_goal:@@ -3815,6 +3831,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)+ user_facing_summary = _watchdog_user_facing_summary(exit_reason, budget_seconds, run)current_url, page_title = await _fallback_page_info(ctx)result: dict[str, Any] = {"ok": False,@@ -3825,6 +3842,11 @@ async def _run_blocks_and_collect_debug("failure_reason": user_failure_reason,"current_url": current_url,"page_title": page_title,+ "control_signal": {+ "kind": f"watchdog_{exit_reason}",+ "user_facing_summary": user_facing_summary,+ },+ "user_facing_summary": user_facing_summary,},}if exit_reason == "per_tool_budget":@@ -5989,6 +6011,9 @@ async def update_and_run_blocks_tool(coverage_error = _pre_run_workflow_coverage_error(copilot_ctx)if coverage_error:+ user_facing_summary = (+ "Workflow draft saved; I still need to add the remaining requested actions before testing it."+ )result = {"ok": False,"error": coverage_error,@@ -5996,6 +6021,11 @@ async def update_and_run_blocks_tool("block_count": copilot_ctx.last_update_block_count,"workflow_updated": True,"workflow_run_skipped": True,+ "control_signal": {+ "kind": "intermediate_success",+ "user_facing_summary": user_facing_summary,+ },+ "user_facing_summary": user_facing_summary,},}record_tool_step_result_for_ctx(copilot_ctx, "update_and_run_blocks", arguments, result)diff --git a/skyvern/forge/sdk/schemas/workflow_copilot.py b/skyvern/forge/sdk/schemas/workflow_copilot.pyindex 2fa7303af..bcb8e6906 100644--- a/skyvern/forge/sdk/schemas/workflow_copilot.py+++ b/skyvern/forge/sdk/schemas/workflow_copilot.py@@ -192,6 +192,10 @@ class WorkflowCopilotToolCallUpdate(BaseModel):WorkflowCopilotStreamMessageType.TOOL_CALL, description="Message type")tool_name: str = Field(..., description="Name of the tool being called")+ display_label: str | None = Field(+ None,+ description="Product-safe label for rendering the tool call in user-visible activity surfaces",+ )tool_input: dict = Field(default_factory=dict, description="Sanitized tool input (no secrets)")iteration: int = Field(..., description="Agent loop iteration number")tool_call_id: str = Field(..., description="Unique ID for this tool invocation")diff --git a/tests/unit/test_copilot_blocker_signal.py b/tests/unit/test_copilot_blocker_signal.pyindex 6b3de24d1..a36ca1f67 100644--- a/tests/unit/test_copilot_blocker_signal.py+++ b/tests/unit/test_copilot_blocker_signal.py@@ -93,6 +93,11 @@ def test_assert_clean_passes_normal_product_language() -> None:class _Ctx:blocker_signal: CopilotToolBlockerSignal | None = None+ latest_tool_blocker_signal: CopilotToolBlockerSignal | None = None+ tool_blocker_signals: list[CopilotToolBlockerSignal]++ def __init__(self) -> None:+ self.tool_blocker_signals = []def test_maybe_clear_on_tool_success_clears_when_in_cleared_by_tools() -> None:@@ -237,11 +242,15 @@ def test_stash_blocker_signal_first_wins_returns_llm_payload() -> None:payload = stash_blocker_signal(ctx, first)assert payload == first.agent_steering_textassert ctx.blocker_signal is first+ assert ctx.latest_tool_blocker_signal is first+ assert ctx.tool_blocker_signals == [first]second = _make(internal_reason_code="second")payload2 = stash_blocker_signal(ctx, second)assert payload2 == second.agent_steering_text # LLM payload is the current signal'sassert ctx.blocker_signal is first # stash is sticky+ assert ctx.latest_tool_blocker_signal is second+ assert ctx.tool_blocker_signals == [first, second]def test_agent_context_and_copilot_context_blocker_signal_defaults_match() -> None:@@ -273,3 +282,8 @@ def test_agent_context_and_copilot_context_blocker_signal_defaults_match() -> Noassert agent_ctx.blocker_signal is Noneassert copilot_ctx.blocker_signal is Noneassert agent_ctx.blocker_signal == copilot_ctx.blocker_signal+ assert agent_ctx.latest_tool_blocker_signal is None+ assert copilot_ctx.latest_tool_blocker_signal is None+ assert agent_ctx.latest_tool_blocker_signal == copilot_ctx.latest_tool_blocker_signal+ assert agent_ctx.tool_blocker_signals == []+ assert copilot_ctx.tool_blocker_signals == []diff --git a/tests/unit/test_copilot_narrative_activity.py b/tests/unit/test_copilot_narrative_activity.pyindex 76c1c9f39..eb70e8f6b 100644--- a/tests/unit/test_copilot_narrative_activity.py+++ b/tests/unit/test_copilot_narrative_activity.py@@ -38,9 +38,10 @@ def test_tool_call_activity_shape_and_denylist() -> None:entry = build_tool_call_activity("update_workflow", 3, "abc")assert entry == {"kind": "tool_call",- "text": "Calling update_workflow…",+ "text": "Updating workflow…","iteration": 3,"toolName": "update_workflow",+ "displayLabel": "Updating workflow","id": "tc-abc",}assert "success" not in entry@@ -54,10 +55,11 @@ def test_tool_result_activity_shape_falls_back_to_tool_name_and_denylist() -> No"text": "Updated 2 blocks","iteration": 4,"toolName": "update_workflow",+ "displayLabel": "Updating workflow","success": True,"id": "tr-abc",}- assert build_tool_result_activity("update_workflow", "", False, 4, "abc")["text"] == "update_workflow"+ assert build_tool_result_activity("update_workflow", "", False, 4, "abc")["text"] == "Updating workflow"assert build_tool_result_activity("get_browser_screenshot", "s", True, 0, "x") is Noneassert build_tool_result_activity("get_run_results", "s", True, 0, "x") is None@@ -142,6 +144,7 @@ def test_build_narrative_payload_serializes_block_and_design_activity() -> None:"text": "ran step_1","iteration": 1,"toolName": "run_blocks_and_collect_debug",+ "displayLabel": "Testing workflow","success": True,"id": "tr-c1",}diff --git a/tests/unit/test_copilot_output_utils.py b/tests/unit/test_copilot_output_utils.pyindex b18da23ec..bd0574d6a 100644--- a/tests/unit/test_copilot_output_utils.py+++ b/tests/unit/test_copilot_output_utils.py@@ -11,6 +11,7 @@ from skyvern.forge.sdk.copilot.output_utils import (parse_final_response,sanitize_tool_result_for_llm,summarize_tool_result,+ summarize_tool_result_detail,truncate_output,)@@ -434,6 +435,80 @@ class TestFormatToolResultForUser:def _format(tool_name: str, result: dict) -> str:return format_tool_result_for_user(tool_name, result)+ def test_blocker_signal_overrides_activity_summary_and_detail(self) -> None:+ from skyvern.forge.sdk.copilot.blocker_signal import CopilotToolBlockerSignal++ signal = CopilotToolBlockerSignal(+ blocker_kind="tool_error",+ agent_steering_text=(+ "Less than 90 seconds remain in this Copilot turn. "+ "Do NOT start another block-running tool call; reply from gathered progress."+ ),+ user_facing_reason="I'm running out of time on this turn. I'll wrap up with what I have so far.",+ recovery_hint="stop",+ renders_final_reply=False,+ internal_reason_code="tool_error_late_block_running",+ blocked_tool="update_and_run_blocks",+ )+ result = {"ok": False, "error": signal.agent_steering_text}++ summary = format_tool_result_for_user("update_and_run_blocks", result, blocker_signal=signal)+ detail = summarize_tool_result_detail(result, blocker_signal=signal)++ assert summary == signal.user_facing_reason+ assert detail == signal.user_facing_reason+ assert "Do NOT" not in summary+ assert "Do NOT" not in detail+ assert "update_and_run_blocks" not in summary+ assert "tool_error_late_block_running" not in summary+ agent_summary = summarize_tool_result("update_and_run_blocks", result)+ assert "Do NOT start another block-running tool call" in agent_summary++ def test_watchdog_control_signal_summary_overrides_raw_detail(self) -> None:+ result = {+ "ok": False,+ "error": (+ "The run has not made progress. Run ID: wr_stalled. Outcome is uncertain. "+ "Do NOT re-invoke block-running tools without first calling get_run_results."+ ),+ "data": {+ "failure_reason": (+ "The run stopped after no observable progress for 120s. Run ID: wr_stalled. Outcome is uncertain."+ ),+ "control_signal": {+ "kind": "watchdog_stagnation",+ "user_facing_summary": "The run stopped after no observable progress for 120s.",+ },+ "user_facing_summary": "The run stopped after no observable progress for 120s.",+ },+ }++ summary = self._format("run_blocks_and_collect_debug", result)+ detail = summarize_tool_result_detail(result, tool_name="run_blocks_and_collect_debug")++ assert summary == "The run stopped after no observable progress for 120s."+ assert detail == summary+ assert "wr_stalled" not in summary+ assert "get_run_results" not in detail+ assert "Do NOT" not in detail++ def test_unsafe_structured_summary_falls_back_for_summary_and_detail(self) -> None:+ result = {+ "ok": False,+ "error": "STOP - do NOT respond to the user yet.",+ "data": {+ "user_facing_summary": "The update_and_run_blocks tool could not continue.",+ },+ }++ summary = self._format("update_and_run_blocks", result)+ detail = summarize_tool_result_detail(result, tool_name="update_and_run_blocks")++ assert summary == "Couldn't complete that step."+ assert detail == "Couldn't complete that step."+ assert "update_and_run_blocks" not in summary+ assert "STOP" not in detail+def test_loop_detected_failure_drops_use_a_different_tool_tail(self) -> None:summary = self._format("click",diff --git a/tests/unit/test_copilot_streaming_adapter.py b/tests/unit/test_copilot_streaming_adapter.pyindex d2d769ae4..25fd07f4e 100644--- a/tests/unit/test_copilot_streaming_adapter.py+++ b/tests/unit/test_copilot_streaming_adapter.py@@ -1,6 +1,7 @@from __future__ import annotationsimport asyncio+import jsonfrom types import SimpleNamespacefrom typing import Anyfrom unittest.mock import AsyncMock, MagicMock@@ -122,6 +123,48 @@ async def test_stream_to_sse_keeps_running_after_client_disconnect() -> None:stream.send.assert_not_called()+async def test_tool_call_sse_uses_product_safe_activity_label() -> None:+ from agents.items import RunItem+ from agents.stream_events import RunItemStreamEvent++ from skyvern.forge.sdk.schemas.workflow_copilot import WorkflowCopilotStreamMessageType++ call_item = MagicMock(spec=RunItem)+ call_item.raw_item = {"call_id": "c1", "name": "update_and_run_blocks", "arguments": "{}"}+ tool_call_event = RunItemStreamEvent(name="tool_called", item=call_item)++ result = MagicMock()+ result.stream_events = lambda: _stream_events_from(tool_call_event)+ result.cancel = MagicMock()++ sent: list[Any] = []++ async def _send(payload: Any) -> bool:+ sent.append(payload)+ return True++ stream = MagicMock()+ stream.is_disconnected = AsyncMock(return_value=False)+ stream.send = _send+ ctx = SimpleNamespace()++ await stream_to_sse(result, stream, ctx)++ tool_calls = [p for p in sent if getattr(p, "type", None) == WorkflowCopilotStreamMessageType.TOOL_CALL]+ assert len(tool_calls) == 1+ assert tool_calls[0].tool_name == "update_and_run_blocks"+ assert tool_calls[0].display_label == "Testing workflow"++ activity = ctx.narrator_state.design_activity+ assert len(activity) == 1+ assert activity[0]["kind"] == "tool_call"+ assert activity[0]["toolName"] == "update_and_run_blocks"+ assert activity[0]["displayLabel"] == "Testing workflow"+ assert activity[0]["text"] == "Testing workflow…"+ assert "update_and_run_blocks" not in activity[0]["text"]++@pytest.mark.asyncioasync def test_stream_to_sse_propagates_cancelled_error() -> None:"""A generic asyncio.CancelledError must propagate up from stream_to_sse so@@ -293,6 +336,66 @@ async def test_tool_result_sse_summary_translates_loop_detected_failure() -> Nonassert "LOOP DETECTED" in agent_summary+async def test_tool_result_sse_uses_latest_blocker_signal_for_activity_surface() -> None:+ from agents.items import RunItem+ from agents.stream_events import RunItemStreamEvent++ from skyvern.forge.sdk.copilot.blocker_signal import CopilotToolBlockerSignal+ from skyvern.forge.sdk.schemas.workflow_copilot import WorkflowCopilotStreamMessageType++ signal = CopilotToolBlockerSignal(+ blocker_kind="tool_error",+ agent_steering_text=(+ "Less than 90 seconds remain in this Copilot turn. "+ "Do NOT start another block-running tool call; reply from gathered progress."+ ),+ user_facing_reason="I'm running out of time on this turn. I'll wrap up with what I have so far.",+ recovery_hint="stop",+ renders_final_reply=False,+ internal_reason_code="tool_error_late_block_running",+ blocked_tool="update_and_run_blocks",+ )++ call_item = MagicMock(spec=RunItem)+ call_item.raw_item = {"call_id": "c1", "name": "update_and_run_blocks", "arguments": "{}"}+ tool_call_event = RunItemStreamEvent(name="tool_called", item=call_item)++ out_item = MagicMock(spec=RunItem)+ out_item.raw_item = {"call_id": "c1", "name": "update_and_run_blocks"}+ out_item.output = [{"type": "text", "text": json.dumps({"ok": False, "error": signal.agent_steering_text})}]+ tool_output_event = RunItemStreamEvent(name="tool_output", item=out_item)++ result = MagicMock()+ result.stream_events = lambda: _stream_events_from(tool_call_event, tool_output_event)+ result.cancel = MagicMock()++ sent: list[Any] = []++ async def _send(payload: Any) -> bool:+ sent.append(payload)+ return True++ stream = MagicMock()+ stream.is_disconnected = AsyncMock(return_value=False)+ stream.send = _send+ ctx = SimpleNamespace(latest_tool_blocker_signal=signal, tool_blocker_signals=[signal])++ await stream_to_sse(result, stream, ctx)++ tool_results = [p for p in sent if getattr(p, "type", None) == WorkflowCopilotStreamMessageType.TOOL_RESULT]+ assert len(tool_results) == 1+ assert tool_results[0].summary == signal.user_facing_reason+ assert tool_results[0].detail == signal.user_facing_reason+ assert "Do NOT" not in tool_results[0].summary++ activity = ctx.narrator_state.design_activity+ assert len(activity) == 2+ assert activity[-1]["kind"] == "tool_result"+ assert activity[-1]["text"] == signal.user_facing_reason+ assert "Do NOT" not in activity[-1]["text"]++@pytest.mark.asyncioasync def test_stream_to_sse_raises_and_cancels_on_repeated_unrecoverable_tool_error() -> None:from agents.items import RunItem