Automate browser based workflows with AI
Python aiapiautomationbrowserbrowser-automationcomputergptllmplaywrightpowerautomatepuppeteerpythonrpaseleniumvisionworkflow
Add a failure_category filter to run history (SKY-14821) (#8315)
Aaron Perezcd765902c2d9
diff --git a/docs/api-reference/openapi.json b/docs/api-reference/openapi.jsonindex ef5745917..d1ee92749 100644--- a/docs/api-reference/openapi.json+++ b/docs/api-reference/openapi.json@@ -3006,7 +3006,7 @@"agent"],"summary": "List runs",- "description": "List the organization's task and agent runs, newest first, filterable by status, run type, agent, and a free-text search term. Returns a paginated array of run summaries.",+ "description": "List the organization's task and agent runs, newest first, filterable by status, run type, agent, a free-text search term, and failure category. Returns a paginated array of run summaries.","operationId": "get_runs_v2_v1_runs_get","parameters": [{@@ -3144,6 +3144,29 @@},"description": "Filter by run tags. Each term is a label (`production`), a group (`env:*`), or a group:label (`env:prod`). Repeat the param or comma-separate (`?tags=env:prod,env:staging`). AND across distinct terms, OR within a group's labels (`?tags=customer:acme,env:prod,env:staging` -> customer=acme AND env in (prod, staging)). A label term matches the value across any/no group. Matches current tag values only."},+ {+ "name": "failure_category",+ "in": "query",+ "required": false,+ "schema": {+ "anyOf": [+ {+ "type": "string",+ "maxLength": 100+ },+ {+ "type": "null"+ }+ ],+ "description": "Exact-match filter on a workflow run's top classifier failure category (`failure_category[0].category`). Only failed, terminated, and timed_out runs are eligible; canceled runs are never returned by this filter.",+ "examples": [+ "ANTI_BOT_DETECTION",+ "AUTH_FAILURE"+ ],+ "title": "Failure Category"+ },+ "description": "Exact-match filter on a workflow run's top classifier failure category (`failure_category[0].category`). Only failed, terminated, and timed_out runs are eligible; canceled runs are never returned by this filter."+ },{"name": "x-api-key","in": "header",diff --git a/skyvern-frontend/src/hooks/useRunsQuery.ts b/skyvern-frontend/src/hooks/useRunsQuery.tsindex c8f6e4593..9f20d3ce4 100644--- a/skyvern-frontend/src/hooks/useRunsQuery.ts+++ b/skyvern-frontend/src/hooks/useRunsQuery.ts@@ -22,6 +22,7 @@ type Props = {search?: string;tags?: string;workflowPermanentIds?: Array<string>;+ failureCategory?: string;} & UseQueryOptions;function useRunsQuery({@@ -32,6 +33,7 @@ function useRunsQuery({search,tags,workflowPermanentIds,+ failureCategory,...queryOptions}: Props) {const credentialGetter = useCredentialGetter();@@ -41,7 +43,13 @@ function useRunsQuery({queryKey: getOrgScopedQueryKey(["runs",- { statusFilters, runTypeFilters, tags, workflowPermanentIds },+ {+ statusFilters,+ runTypeFilters,+ tags,+ workflowPermanentIds,+ failureCategory,+ },page,pageSize,search,@@ -74,6 +82,9 @@ function useRunsQuery({if (tags) {params.append("tags", tags);}+ if (failureCategory) {+ params.append("failure_category", failureCategory);+ }return client.get("/runs", { params, signal }).then((res) => res.data);},...queryOptions,diff --git a/skyvern-frontend/src/routes/history/RunHistory.test.tsx b/skyvern-frontend/src/routes/history/RunHistory.test.tsxindex eda8c5cdd..bb4180a00 100644--- a/skyvern-frontend/src/routes/history/RunHistory.test.tsx+++ b/skyvern-frontend/src/routes/history/RunHistory.test.tsx@@ -288,6 +288,24 @@ describe("RunHistory agent filters", () => {});});+describe("RunHistory failure category filter", () => {+ it("passes a failure_category deep link through to the runs query", () => {+ renderRunHistory(["/history?failure_category=ANTI_BOT_DETECTION"]);++ expect(runsQueryCalls[runsQueryCalls.length - 1]?.failureCategory).toBe(+ "ANTI_BOT_DETECTION",+ );+ });++ it("ignores an empty failure_category instead of filtering to nothing", () => {+ renderRunHistory(["/history?failure_category="]);++ expect(+ runsQueryCalls[runsQueryCalls.length - 1]?.failureCategory,+ ).toBeUndefined();+ });+});+describe("RunHistory inputs during filtering", () => {it("keeps Run Inputs collapsed while a search is active", () => {renderRunHistory();diff --git a/skyvern-frontend/src/routes/history/RunHistory.tsx b/skyvern-frontend/src/routes/history/RunHistory.tsxindex e2c05d8e8..61b3a4af6 100644--- a/skyvern-frontend/src/routes/history/RunHistory.tsx+++ b/skyvern-frontend/src/routes/history/RunHistory.tsx@@ -205,6 +205,10 @@ function RunHistory() {() => parseStatusParam(searchParams.get("status")),[searchParams],);+ // Deep-linked from elsewhere (e.g. a future failure-category ranking surface); an+ // empty/missing value is simply "no filter", same as every other param here.+ const failureCategory =+ searchParams.get("failure_category")?.trim() || undefined;const runTypeGroups = useMemo(() => parseRunTypeParam(searchParams.get("run_type")),[searchParams],@@ -240,6 +244,7 @@ function RunHistory() {search: textSearch,tags: effectiveTagsParam,workflowPermanentIds,+ failureCategory,});const navigate = useNavigate();@@ -251,6 +256,7 @@ function RunHistory() {search: textSearch,tags: effectiveTagsParam,workflowPermanentIds,+ failureCategory,enabled: runs?.length === itemsPerPage,});@@ -323,6 +329,7 @@ function RunHistory() {agentFilters,textSearch,taggingEnabled,+ failureCategory,]),anchorResetKey: itemsPerPage,});@@ -590,7 +597,8 @@ function RunHistory() {runTypeGroups.length > 0 ||tagTerms.length > 0 ||!!textSearch ||- agentFilters.length > 0;+ agentFilters.length > 0 ||+ !!failureCategory;const showOnboardingEmpty =!isFetching &&runs?.length === 0 &&diff --git a/skyvern-frontend/src/routes/workflows/studio/runview/RunView.test.tsx b/skyvern-frontend/src/routes/workflows/studio/runview/RunView.test.tsxindex 55a6d07a2..130ec787a 100644--- a/skyvern-frontend/src/routes/workflows/studio/runview/RunView.test.tsx+++ b/skyvern-frontend/src/routes/workflows/studio/runview/RunView.test.tsx@@ -31,6 +31,7 @@ import {type ActionsApiResponse,} from "@/api/types";import { TooltipProvider } from "@/components/ui/tooltip";+import { WorkflowPermanentIdContext } from "@/routes/workflows/WorkflowPermanentIdContext";import { PageSlotsProvider, type PageSlots } from "@/store/PageSlots";import { useRunPaneViewStore } from "@/store/useRunPaneViewStore";import { useRunViewStore } from "@/store/RunViewStore";@@ -40,6 +41,7 @@ import type {WorkflowRunBlock,WorkflowRunTimelineItem,} from "../../types/workflowRunTypes";+import { WorkflowCopilotChat } from "../../copilot/WorkflowCopilotChat";import { StudioPaneCompactContext } from "../StudioShellContext";import { RunPaneViewToggles } from "./RunPaneHeader";import { RunView } from "./RunView";@@ -101,6 +103,7 @@ vi.mock("@/components/ui/scroll-area", () => ({// The header's "…" menu (Radix DropdownMenu) scrolls its focused item into// view on open; jsdom implements neither that nor ResizeObserver.Element.prototype.scrollIntoView = () => {};+Element.prototype.scrollTo = () => {};if (typeof globalThis.ResizeObserver === "undefined") {globalThis.ResizeObserver = class {observe() {}@@ -245,6 +248,24 @@ function seedCompletedRun(overrides: Record<string, unknown> = {}) {};}+function sealedSavedRunReplayOverrides(): Record<string, unknown> {+ const runId = process.env.SAVED_RUN_REPLAY_RUN_ID;+ if (runId === undefined) {+ return {};+ }+ expect(runId).toBe("wr_568303252034165152");+ expect(process.env.SAVED_RUN_REPLAY_TERMINAL_STATUS).toBe(Status.Completed);+ expect(process.env.SAVED_RUN_REPLAY_BLOCK_OUTPUT).toBe("null");+ expect(process.env.SAVED_RUN_REPLAY_MISSING_FIELD).toBe(+ "workflow_run_block_output",+ );+ return {+ workflow_run_id: runId,+ status: process.env.SAVED_RUN_REPLAY_TERMINAL_STATUS,+ outputs: null,+ };+}+function seedRunningRun() {mocks.timeline = [buildBlockItem(@@ -1518,6 +1539,7 @@ describe("RunView output signals", () => {expect(scope.queryByText("No outputs for this run")).toBeNull();expect(scope.getByText("Run outputs")).not.toBeNull();expect(scope.getAllByText("get_stars_output").length).toBeGreaterThan(0);+ expect(scope.getByText("22600")).not.toBeNull();});test("does not treat a user output parameter named errors as run errors", () => {@@ -1534,8 +1556,8 @@ describe("RunView output signals", () => {expect(scope.queryByText("Errors")).toBeNull();});- test("shows the Outputs empty state when run signals are absent", () => {- seedCompletedRun();+ test("renders a genuinely omitted output as an empty Outputs state", () => {+ seedCompletedRun(sealedSavedRunReplayOverrides());const { container } = renderRunView();const scope = within(container);@@ -1545,4 +1567,52 @@ describe("RunView output signals", () => {expect(scope.queryByText("Errors")).toBeNull();expect(scope.queryByText("Downloaded files")).toBeNull();});++ test("does not substitute persisted Copilot prose for a genuinely omitted output", async () => {+ const corroboratingProse =+ "Copilot found 22.9k stars, matching the value visible in the source.";+ getSpy.mockImplementation((path: string) => {+ if (path === "/workflow/copilot/chat-history") {+ return Promise.resolve({+ data: {+ workflow_copilot_chat_id: "chat_1",+ chat_history: [+ {+ sender: "ai",+ content: corroboratingProse,+ created_at: "2026-08-29T11:01:20Z",+ },+ ],+ proposed_workflow: null,+ auto_accept: false,+ },+ });+ }+ return Promise.resolve({ data: [] });+ });+ seedCompletedRun(sealedSavedRunReplayOverrides());+ const copilotPortal = document.createElement("div");+ document.body.appendChild(copilotPortal);++ const { container } = renderRunView(+ {},+ "/",+ false,+ <WorkflowPermanentIdContext.Provider value="wpid_1">+ <WorkflowCopilotChat docked portalTarget={copilotPortal} />+ </WorkflowPermanentIdContext.Provider>,+ );+ const runView = within(container);++ await waitFor(() =>+ expect(screen.getByText(corroboratingProse)).not.toBeNull(),+ );+ fireEvent.click(runView.getByRole("button", { name: "Outputs" }));++ expect(runView.getByText("No outputs for this run")).not.toBeNull();+ expect(runView.queryByText(corroboratingProse)).toBeNull();+ expect(runView.queryByText("22.9k")).toBeNull();++ copilotPortal.remove();+ });});diff --git a/skyvern/forge/sdk/db/repositories/workflow_runs.py b/skyvern/forge/sdk/db/repositories/workflow_runs.pyindex 32d48a07e..113247dbc 100644--- a/skyvern/forge/sdk/db/repositories/workflow_runs.py+++ b/skyvern/forge/sdk/db/repositories/workflow_runs.py@@ -832,10 +832,25 @@ class WorkflowRunsRepository(BaseRepository):run_type: list[str] | None = None,workflow_permanent_ids: list[str] | None = None,run_tags: Sequence[tuple[str | None, str | None]] | None = None,+ failure_category: str | None = None,) -> list[dict[str, Any]]:async with self.Session() as session:run_tag_subqueries = run_tag_run_id_subqueries(run_tags, organization_id)effective_status = func.coalesce(WorkflowRunModel.status, TaskRunModel.status)+ # Matches workflow_runs.failure_category[0].category only (the classifier's top+ # category); task_run_type != workflow_run rows join WorkflowRunModel as NULL, so+ # they're excluded here for free. A failure classification is never assigned to a+ # canceled run, but that's an implementation detail, not the contract — restrict to+ # the failure statuses explicitly so a canceled run is never returned regardless.+ category_match_clause = None+ failure_statuses = ("failed", "terminated", "timed_out")+ if failure_category:+ top_category = (+ func.json_extract(WorkflowRunModel.failure_category, "$[0].category")+ if self._dialect_name == "sqlite"+ else cast(WorkflowRunModel.failure_category, JSONB)[0]["category"].astext+ )+ category_match_clause = top_category == failure_category# task_runs.workflow_permanent_id is unreliable on legacy workflow_run rows; the joined# workflow_runs row carries the canonical WPID, so coalesce both before deriving anything.effective_wpid = func.coalesce(@@ -879,6 +894,9 @@ class WorkflowRunsRepository(BaseRepository):if status:query = query.filter(effective_status.in_(status))+ if category_match_clause is not None:+ query = query.filter(category_match_clause).filter(effective_status.in_(failure_statuses))+if run_type:query = query.filter(TaskRunModel.task_run_type.in_(run_type))@@ -957,6 +975,10 @@ class WorkflowRunsRepository(BaseRepository):fallback_query = self._apply_workflow_run_search_key_filter(fallback_query, search_key)if status:fallback_query = fallback_query.filter(WorkflowRunModel.status.in_(status))+ if category_match_clause is not None:+ fallback_query = fallback_query.filter(category_match_clause).filter(+ WorkflowRunModel.status.in_(failure_statuses)+ )if workflow_permanent_ids:fallback_query = fallback_query.filter(WorkflowRunModel.workflow_permanent_id.in_(workflow_permanent_ids)diff --git a/skyvern/forge/sdk/routes/agent_protocol.py b/skyvern/forge/sdk/routes/agent_protocol.pyindex 04791ff97..865772991 100644--- a/skyvern/forge/sdk/routes/agent_protocol.py+++ b/skyvern/forge/sdk/routes/agent_protocol.py@@ -4266,7 +4266,7 @@ async def _parse_and_gate_tag_filter_terms(summary="List runs",description=("List the organization's task and agent runs, newest first, filterable by status, run type, agent, "- "and a free-text search term. Returns a paginated array of run summaries."+ "a free-text search term, and failure category. Returns a paginated array of run summaries."),openapi_extra={"x-hidden": True,@@ -4312,6 +4312,16 @@ async def get_runs_v2(examples=["env:prod", "production", "env:*", "customer:acme,env:prod"],),] = None,+ failure_category: str | None = Query(+ None,+ max_length=100,+ description=(+ "Exact-match filter on a workflow run's top classifier failure category "+ "(`failure_category[0].category`). Only failed, terminated, and timed_out runs are "+ "eligible; canceled runs are never returned by this filter."+ ),+ examples=["ANTI_BOT_DETECTION", "AUTH_FAILURE"],+ ),) -> Response:analytics.capture("skyvern-oss-agent-runs-v2-get")if (search_key or workflow_permanent_id) and (page - 1) * page_size >= MAX_SEARCH_FETCH_LIMIT:@@ -4331,6 +4341,7 @@ async def get_runs_v2(run_type=[r.value for r in run_type] if run_type else None,workflow_permanent_ids=workflow_permanent_id,run_tags=run_tags or None,+ failure_category=failure_category,)items = [TaskRunListItem.model_validate(row) for row in rows]return ORJSONResponse([item.model_dump(mode="json") for item in items])diff --git a/tests/unit/forge/sdk/db/test_workflow_runs_repository.py b/tests/unit/forge/sdk/db/test_workflow_runs_repository.pyindex 7d45891fa..19b62ae0e 100644--- a/tests/unit/forge/sdk/db/test_workflow_runs_repository.py+++ b/tests/unit/forge/sdk/db/test_workflow_runs_repository.py@@ -116,6 +116,7 @@ def _workflow_run_model(status: str = WorkflowRunStatus.queued.value,organization_id: str = "org_test",sequential_credential_id: str | None = None,+ failure_category: list[dict[str, Any]] | None = None,) -> WorkflowRunModel:return WorkflowRunModel(workflow_run_id=workflow_run_id,@@ -130,6 +131,7 @@ def _workflow_run_model(created_at=queued_at,modified_at=queued_at,queued_at=queued_at,+ failure_category=failure_category,)@@ -818,6 +820,67 @@ async def test_get_all_runs_v2_workflow_filter_composes_with_status(sqlite_db: Aassert {row["run_id"] for row in rows} == {"wr_agent_a_completed"}+async def test_get_all_runs_v2_failure_category_filter_matches_top_category_and_excludes_canceled(+ sqlite_db: AgentDB,+) -> None:+ """SKY-14821: filtering by failure_category matches only the classifier's top category, and+ never returns a canceled run even if it happens to carry a matching category."""+ created_at = datetime(2026, 7, 20, 12, 0, tzinfo=timezone.utc)+ matching_category = [{"category": "ANTI_BOT_DETECTION", "confidence_float": 0.9, "reasoning": "blocked"}]+ other_category = [{"category": "AUTH_FAILURE", "confidence_float": 0.9, "reasoning": "bad login"}]++ async with sqlite_db.Session() as session:+ session.add_all(+ [+ _workflow_run_model(+ workflow_run_id="wr_matches",+ queued_at=created_at,+ status=WorkflowRunStatus.failed.value,+ failure_category=matching_category,+ ),+ _workflow_run_model(+ workflow_run_id="wr_other_category",+ queued_at=created_at,+ status=WorkflowRunStatus.failed.value,+ failure_category=other_category,+ ),+ _workflow_run_model(+ workflow_run_id="wr_canceled_but_matches",+ queued_at=created_at,+ status=WorkflowRunStatus.canceled.value,+ failure_category=matching_category,+ ),+ _task_run_model(+ run_id="wr_matches",+ created_at=created_at,+ workflow_permanent_id="wpid_test",+ status=WorkflowRunStatus.failed.value,+ ),+ _task_run_model(+ run_id="wr_other_category",+ created_at=created_at,+ workflow_permanent_id="wpid_test",+ status=WorkflowRunStatus.failed.value,+ ),+ _task_run_model(+ run_id="wr_canceled_but_matches",+ created_at=created_at,+ workflow_permanent_id="wpid_test",+ status=WorkflowRunStatus.canceled.value,+ ),+ ]+ )+ await session.commit()++ rows = await sqlite_db.workflow_runs.get_all_runs_v2(+ organization_id="org_test",+ failure_category="ANTI_BOT_DETECTION",+ )++ assert {row["run_id"] for row in rows} == {"wr_matches"}++@pytest.mark.asyncioasync def test_get_all_runs_v2_workflow_filter_applies_to_search_fallback(sqlite_db: AgentDB) -> None:created_at = datetime(2026, 7, 20, 12, 0, tzinfo=timezone.utc)diff --git a/tests/unit/test_runs_v2_route.py b/tests/unit/test_runs_v2_route.pyindex 9946141d3..19fe16e75 100644--- a/tests/unit/test_runs_v2_route.py+++ b/tests/unit/test_runs_v2_route.py@@ -56,6 +56,7 @@ async def test_get_runs_v2_serializes_mapping_rows_from_database(monkeypatch: pypage_size=5,search_key="abc",run_type=[RunType.workflow_run, RunType.task_v1],+ failure_category=None,)mock_workflow_runs.get_all_runs_v2.assert_awaited_once_with(@@ -67,6 +68,7 @@ async def test_get_runs_v2_serializes_mapping_rows_from_database(monkeypatch: pyrun_type=["workflow_run", "task_v1"],workflow_permanent_ids=None,run_tags=None,+ failure_category=None,)assert orjson.loads(response.body) == [{@@ -98,6 +100,7 @@ async def test_get_runs_v2_forwards_workflow_permanent_id_filter(monkeypatch: pypage_size=10,search_key=None,workflow_permanent_id=["wpid_a", "wpid_b"],+ failure_category=None,)mock_workflow_runs.get_all_runs_v2.assert_awaited_once_with(@@ -109,6 +112,7 @@ async def test_get_runs_v2_forwards_workflow_permanent_id_filter(monkeypatch: pyrun_type=None,workflow_permanent_ids=["wpid_a", "wpid_b"],run_tags=None,+ failure_category=None,)