Skip to content

Automate browser based workflows with AI

Surface run-level tags: chips + filter on run lists, and analytics picker keys (#7412)

Aaron Perez765f0244f00a
diff --git a/docs/api-reference/openapi.json b/docs/api-reference/openapi.json
index 02179fc75..752e1da80 100644
--- a/docs/api-reference/openapi.json
+++ b/docs/api-reference/openapi.json
@@ -2499,6 +2499,59 @@
"x-fern-sdk-method-name": "batch_get_run_tags_post"
}
},
+ "/v1/run-tag-suggestions": {
+ "get": {
+ "tags": [
+ "Tags"
+ ],
+ "summary": "List run tag suggestions",
+ "description": "List distinct (key, value) pairs ever set on a run for the organization, sourced from the run-tag event log rather than the tag-key/tag-value registry. Surfaces reserved 'skyvern.*' system keys (which are never registered) so pickers can offer them alongside user-defined tags.",
+ "operationId": "get_run_tag_suggestions_v1_run_tag_suggestions_get",
+ "parameters": [
+ {
+ "name": "x-api-key",
+ "in": "header",
+ "required": false,
+ "schema": {
+ "anyOf": [
+ {
+ "type": "string"
+ },
+ {
+ "type": "null"
+ }
+ ],
+ "description": "Skyvern API key for authentication. API key can be found at https://app.skyvern.com/settings.",
+ "title": "X-Api-Key"
+ },
+ "description": "Skyvern API key for authentication. API key can be found at https://app.skyvern.com/settings."
+ }
+ ],
+ "responses": {
+ "200": {
+ "description": "Successfully retrieved run tag suggestions",
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/RunTagSuggestionsResponse"
+ }
+ }
+ }
+ },
+ "422": {
+ "description": "Validation Error",
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/HTTPValidationError"
+ }
+ }
+ }
+ }
+ },
+ "x-fern-sdk-method-name": "get_run_tag_suggestions"
+ }
+ },
"/v1/artifacts/{artifact_id}/content": {
"get": {
"tags": [
@@ -2931,6 +2984,53 @@
},
"description": "Case-insensitive substring search (min 3 chars for trigram index)."
},
+ {
+ "name": "run_type",
+ "in": "query",
+ "required": false,
+ "schema": {
+ "anyOf": [
+ {
+ "type": "array",
+ "items": {
+ "$ref": "#/components/schemas/RunType"
+ }
+ },
+ {
+ "type": "null"
+ }
+ ],
+ "title": "Run Type"
+ }
+ },
+ {
+ "name": "tags",
+ "in": "query",
+ "required": false,
+ "schema": {
+ "anyOf": [
+ {
+ "type": "array",
+ "items": {
+ "type": "string"
+ },
+ "maxItems": 20
+ },
+ {
+ "type": "null"
+ }
+ ],
+ "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.",
+ "examples": [
+ "env:prod",
+ "production",
+ "env:*",
+ "customer:acme,env:prod"
+ ],
+ "title": "Tags"
+ },
+ "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": "x-api-key",
"in": "header",
@@ -6371,6 +6471,34 @@
},
"description": "Only include runs created strictly before this UTC timestamp (ISO 8601)."
},
+ {
+ "name": "tags",
+ "in": "query",
+ "required": false,
+ "schema": {
+ "anyOf": [
+ {
+ "type": "array",
+ "items": {
+ "type": "string"
+ },
+ "maxItems": 20
+ },
+ {
+ "type": "null"
+ }
+ ],
+ "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.",
+ "examples": [
+ "env:prod",
+ "production",
+ "env:*",
+ "customer:acme,env:prod"
+ ],
+ "title": "Tags"
+ },
+ "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": "x-api-key",
"in": "header",
@@ -9260,7 +9388,8 @@
"google_sheets_read",
"google_sheets_write",
"pdf_fill",
- "split_pdf"
+ "split_pdf",
+ "email_inbox"
],
"title": "BlockType"
},
@@ -9915,7 +10044,7 @@
"type": "number",
"title": "Timeout",
"description": "Timeout in milliseconds",
- "default": 10000
+ "default": 5000
}
},
"type": "object",
@@ -12009,47 +12138,416 @@
"type": "null"
}
],
- "title": "Next Block Label",
- "description": "Optional pointer to the label of the next block. When omitted, it will default to sequential order. See [[s-4bnl]]."
+ "title": "Next Block Label",
+ "description": "Optional pointer to the label of the next block. When omitted, it will default to sequential order. See [[s-4bnl]]."
+ },
+ "continue_on_failure": {
+ "type": "boolean",
+ "title": "Continue On Failure",
+ "default": false
+ },
+ "model": {
+ "anyOf": [
+ {
+ "additionalProperties": true,
+ "type": "object"
+ },
+ {
+ "type": "null"
+ }
+ ],
+ "title": "Model"
+ },
+ "ignore_workflow_system_prompt": {
+ "type": "boolean",
+ "title": "Ignore Workflow System Prompt",
+ "default": false
+ },
+ "next_loop_on_failure": {
+ "type": "boolean",
+ "title": "Next Loop On Failure",
+ "default": false
+ },
+ "url": {
+ "type": "string",
+ "title": "Url"
+ }
+ },
+ "type": "object",
+ "required": [
+ "label",
+ "url"
+ ],
+ "title": "DownloadToS3BlockYAML"
+ },
+ "EmailInboxBlock": {
+ "properties": {
+ "label": {
+ "type": "string",
+ "title": "Label",
+ "description": "Author-facing identifier for a block; unique within a workflow."
+ },
+ "next_block_label": {
+ "anyOf": [
+ {
+ "type": "string"
+ },
+ {
+ "type": "null"
+ }
+ ],
+ "title": "Next Block Label",
+ "description": "Optional pointer to the next block label when constructing a DAG. Defaults to sequential order when omitted."
+ },
+ "block_type": {
+ "type": "string",
+ "const": "email_inbox",
+ "title": "Block Type",
+ "default": "email_inbox"
+ },
+ "output_parameter": {
+ "$ref": "#/components/schemas/OutputParameter"
+ },
+ "continue_on_failure": {
+ "type": "boolean",
+ "title": "Continue On Failure",
+ "default": false
+ },
+ "model": {
+ "anyOf": [
+ {
+ "additionalProperties": true,
+ "type": "object"
+ },
+ {
+ "type": "null"
+ }
+ ],
+ "title": "Model"
+ },
+ "disable_cache": {
+ "type": "boolean",
+ "title": "Disable Cache",
+ "default": false
+ },
+ "ignore_workflow_system_prompt": {
+ "type": "boolean",
+ "title": "Ignore Workflow System Prompt",
+ "default": false
+ },
+ "next_loop_on_failure": {
+ "type": "boolean",
+ "title": "Next Loop On Failure",
+ "default": false
+ },
+ "email_client": {
+ "type": "string",
+ "enum": [
+ "gmail",
+ "outlook"
+ ],
+ "title": "Email Client"
+ },
+ "credential_id": {
+ "anyOf": [
+ {
+ "type": "string"
+ },
+ {
+ "type": "null"
+ }
+ ],
+ "title": "Credential Id"
+ },
+ "folder": {
+ "anyOf": [
+ {
+ "type": "string"
+ },
+ {
+ "type": "null"
+ }
+ ],
+ "title": "Folder"
+ },
+ "prompt": {
+ "anyOf": [
+ {
+ "type": "string"
+ },
+ {
+ "type": "null"
+ }
+ ],
+ "title": "Prompt"
+ },
+ "sender": {
+ "anyOf": [
+ {
+ "type": "string"
+ },
+ {
+ "type": "null"
+ }
+ ],
+ "title": "Sender"
+ },
+ "subject": {
+ "anyOf": [
+ {
+ "type": "string"
+ },
+ {
+ "type": "null"
+ }
+ ],
+ "title": "Subject"
+ },
+ "newer_than_days": {
+ "anyOf": [
+ {
+ "type": "integer"
+ },
+ {
+ "type": "null"
+ }
+ ],
+ "title": "Newer Than Days"
+ },
+ "max_results": {
+ "type": "integer",
+ "title": "Max Results",
+ "default": 25
+ },
+ "include_body": {
+ "type": "boolean",
+ "title": "Include Body",
+ "default": true
+ },
+ "parameters": {
+ "items": {
+ "oneOf": [
+ {
+ "$ref": "#/components/schemas/WorkflowParameter"
+ },
+ {
+ "$ref": "#/components/schemas/ContextParameter"
+ },
+ {
+ "$ref": "#/components/schemas/AWSSecretParameter"
+ },
+ {
+ "$ref": "#/components/schemas/AzureSecretParameter"
+ },
+ {
+ "$ref": "#/components/schemas/BitwardenLoginCredentialParameter"
+ },
+ {
+ "$ref": "#/components/schemas/BitwardenSensitiveInformationParameter"
+ },
+ {
+ "$ref": "#/components/schemas/BitwardenCreditCardDataParameter"
+ },
+ {
+ "$ref": "#/components/schemas/OnePasswordCredentialParameter"
+ },
+ {
+ "$ref": "#/components/schemas/AzureVaultCredentialParameter"
+ },
+ {
+ "$ref": "#/components/schemas/OutputParameter"
+ },
+ {
+ "$ref": "#/components/schemas/CredentialParameter"
+ }
+ ],
+ "discriminator": {
+ "propertyName": "parameter_type",
+ "mapping": {
+ "aws_secret": "#/components/schemas/AWSSecretParameter",
+ "azure_secret": "#/components/schemas/AzureSecretParameter",
+ "azure_vault_credential": "#/components/schemas/AzureVaultCredentialParameter",
+ "bitwarden_credit_card_data": "#/components/schemas/BitwardenCreditCardDataParameter",
+ "bitwarden_login_credential": "#/components/schemas/BitwardenLoginCredentialParameter",
+ "bitwarden_sensitive_information": "#/components/schemas/BitwardenSensitiveInformationParameter",
+ "context": "#/components/schemas/ContextParameter",
+ "credential": "#/components/schemas/CredentialParameter",
+ "onepassword": "#/components/schemas/OnePasswordCredentialParameter",
+ "output": "#/components/schemas/OutputParameter",
+ "workflow": "#/components/schemas/WorkflowParameter"
+ }
+ }
+ },
+ "type": "array",
+ "title": "Parameters",
+ "default": []
+ }
+ },
+ "type": "object",
+ "required": [
+ "label",
+ "output_parameter",
+ "email_client"
+ ],
+ "title": "EmailInboxBlock"
+ },
+ "EmailInboxBlockYAML": {
+ "properties": {
+ "block_type": {
+ "type": "string",
+ "const": "email_inbox",
+ "title": "Block Type",
+ "default": "email_inbox"
+ },
+ "label": {
+ "type": "string",
+ "title": "Label",
+ "description": "Author-facing identifier; must be unique per workflow."
+ },
+ "next_block_label": {
+ "anyOf": [
+ {
+ "type": "string"
+ },
+ {
+ "type": "null"
+ }
+ ],
+ "title": "Next Block Label",
+ "description": "Optional pointer to the label of the next block. When omitted, it will default to sequential order. See [[s-4bnl]]."
+ },
+ "continue_on_failure": {
+ "type": "boolean",
+ "title": "Continue On Failure",
+ "default": false
+ },
+ "model": {
+ "anyOf": [
+ {
+ "additionalProperties": true,
+ "type": "object"
+ },
+ {
+ "type": "null"
+ }
+ ],
+ "title": "Model"
+ },
+ "ignore_workflow_system_prompt": {
+ "type": "boolean",
+ "title": "Ignore Workflow System Prompt",
+ "default": false
+ },
+ "next_loop_on_failure": {
+ "type": "boolean",
+ "title": "Next Loop On Failure",
+ "default": false
+ },
+ "email_client": {
+ "type": "string",
+ "enum": [
+ "gmail",
+ "outlook"
+ ],
+ "title": "Email Client"
+ },
+ "credential_id": {
+ "anyOf": [
+ {
+ "type": "string"
+ },
+ {
+ "type": "null"
+ }
+ ],
+ "title": "Credential Id"
+ },
+ "folder": {
+ "anyOf": [
+ {
+ "type": "string"
+ },
+ {
+ "type": "null"
+ }
+ ],
+ "title": "Folder"
+ },
+ "prompt": {
+ "anyOf": [
+ {
+ "type": "string"
+ },
+ {
+ "type": "null"
+ }
+ ],
+ "title": "Prompt"
+ },
+ "sender": {
+ "anyOf": [
+ {
+ "type": "string"
+ },
+ {
+ "type": "null"
+ }
+ ],
+ "title": "Sender"
},
- "continue_on_failure": {
- "type": "boolean",
- "title": "Continue On Failure",
- "default": false
+ "subject": {
+ "anyOf": [
+ {
+ "type": "string"
+ },
+ {
+ "type": "null"
+ }
+ ],
+ "title": "Subject"
},
- "model": {
+ "newer_than_days": {
"anyOf": [
{
- "additionalProperties": true,
- "type": "object"
+ "type": "integer"
},
{
"type": "null"
}
],
- "title": "Model"
+ "title": "Newer Than Days"
},
- "ignore_workflow_system_prompt": {
- "type": "boolean",
- "title": "Ignore Workflow System Prompt",
- "default": false
+ "max_results": {
+ "type": "integer",
+ "title": "Max Results",
+ "default": 25
},
- "next_loop_on_failure": {
+ "include_body": {
"type": "boolean",
- "title": "Next Loop On Failure",
- "default": false
+ "title": "Include Body",
+ "default": true
},
- "url": {
- "type": "string",
- "title": "Url"
+ "parameter_keys": {
+ "anyOf": [
+ {
+ "items": {
+ "type": "string"
+ },
+ "type": "array"
+ },
+ {
+ "type": "null"
+ }
+ ],
+ "title": "Parameter Keys"
}
},
"type": "object",
"required": [
"label",
- "url"
+ "email_client"
],
- "title": "DownloadToS3BlockYAML"
+ "title": "EmailInboxBlockYAML"
},
"Extensions": {
"type": "string",
@@ -13398,7 +13896,8 @@
"enum": [
"s3",
"azure",
- "google_drive"
+ "google_drive",
+ "sftp"
],
"title": "FileStorageType"
},
@@ -13578,6 +14077,106 @@
],
"title": "Google Drive Folder Id"
},
+ "sftp_host": {
+ "anyOf": [
+ {
+ "type": "string"
+ },
+ {
+ "type": "null"
+ }
+ ],
+ "title": "Sftp Host"
+ },
+ "sftp_port": {
+ "anyOf": [
+ {
+ "type": "integer"
+ },
+ {
+ "type": "null"
+ }
+ ],
+ "title": "Sftp Port"
+ },
+ "sftp_username": {
+ "anyOf": [
+ {
+ "type": "string"
+ },
+ {
+ "type": "null"
+ }
+ ],
+ "title": "Sftp Username"
+ },
+ "sftp_password": {
+ "anyOf": [
+ {
+ "type": "string"
+ },
+ {
+ "type": "null"
+ }
+ ],
+ "title": "Sftp Password"
+ },
+ "sftp_private_key": {
+ "anyOf": [
+ {
+ "type": "string"
+ },
+ {
+ "type": "null"
+ }
+ ],
+ "title": "Sftp Private Key"
+ },
+ "sftp_private_key_passphrase": {
+ "anyOf": [
+ {
+ "type": "string"
+ },
+ {
+ "type": "null"
+ }
+ ],
+ "title": "Sftp Private Key Passphrase"
+ },
+ "sftp_remote_path": {
+ "anyOf": [
+ {
+ "type": "string"
+ },
+ {
+ "type": "null"
+ }
+ ],
+ "title": "Sftp Remote Path"
+ },
+ "sftp_host_key": {
+ "anyOf": [
+ {
+ "type": "string"
+ },
+ {
+ "type": "null"
+ }
+ ],
+ "title": "Sftp Host Key"
+ },
+ "prompt": {
+ "anyOf": [
+ {
+ "type": "string"
+ },
+ {
+ "type": "null"
+ }
+ ],
+ "title": "Prompt",
+ "description": "Optional natural-language control over which downloaded files are uploaded; empty means upload all."
+ },
"path": {
"anyOf": [
{
@@ -13769,6 +14368,106 @@
],
"title": "Google Drive Folder Id"
},
+ "sftp_host": {
+ "anyOf": [
+ {
+ "type": "string"
+ },
+ {
+ "type": "null"
+ }
+ ],
+ "title": "Sftp Host"
+ },
+ "sftp_port": {
+ "anyOf": [
+ {
+ "type": "integer"
+ },
+ {
+ "type": "null"
+ }
+ ],
+ "title": "Sftp Port"
+ },
+ "sftp_username": {
+ "anyOf": [
+ {
+ "type": "string"
+ },
+ {
+ "type": "null"
+ }
+ ],
+ "title": "Sftp Username"
+ },
+ "sftp_password": {
+ "anyOf": [
+ {
+ "type": "string"
+ },
+ {
+ "type": "null"
+ }
+ ],
+ "title": "Sftp Password"
+ },
+ "sftp_private_key": {
+ "anyOf": [
+ {
+ "type": "string"
+ },
+ {
+ "type": "null"
+ }
+ ],
+ "title": "Sftp Private Key"
+ },
+ "sftp_private_key_passphrase": {
+ "anyOf": [
+ {
+ "type": "string"
+ },
+ {
+ "type": "null"
+ }
+ ],
+ "title": "Sftp Private Key Passphrase"
+ },
+ "sftp_remote_path": {
+ "anyOf": [
+ {
+ "type": "string"
+ },
+ {
+ "type": "null"
+ }
+ ],
+ "title": "Sftp Remote Path"
+ },
+ "sftp_host_key": {
+ "anyOf": [
+ {
+ "type": "string"
+ },
+ {
+ "type": "null"
+ }
+ ],
+ "title": "Sftp Host Key"
+ },
+ "prompt": {
+ "anyOf": [
+ {
+ "type": "string"
+ },
+ {
+ "type": "null"
+ }
+ ],
+ "title": "Prompt",
+ "description": "Optional natural-language control over which downloaded files are uploaded; empty means upload all."
+ },
"path": {
"anyOf": [
{
@@ -14047,6 +14746,9 @@
{
"$ref": "#/components/schemas/GoogleSheetsReadBlock"
},
+ {
+ "$ref": "#/components/schemas/EmailInboxBlock"
+ },
{
"$ref": "#/components/schemas/GoogleSheetsWriteBlock"
},
@@ -14064,6 +14766,7 @@
"code": "#/components/schemas/CodeBlock",
"conditional": "#/components/schemas/ConditionalBlock",
"download_to_s3": "#/components/schemas/DownloadToS3Block",
+ "email_inbox": "#/components/schemas/EmailInboxBlock",
"extraction": "#/components/schemas/ExtractionBlock",
"file_download": "#/components/schemas/FileDownloadBlock",
"file_upload": "#/components/schemas/FileUploadBlock",
@@ -14335,6 +15038,9 @@
{
"$ref": "#/components/schemas/GoogleSheetsReadBlockYAML"
},
+ {
+ "$ref": "#/components/schemas/EmailInboxBlockYAML"
+ },
{
"$ref": "#/components/schemas/GoogleSheetsWriteBlockYAML"
}
@@ -16110,7 +16816,7 @@
"type": "number",
"title": "Timeout",
"description": "Timeout in milliseconds",
- "default": 10000
+ "default": 5000
}
},
"type": "object",
@@ -19057,6 +19763,40 @@
],
"title": "RunTagHistoryResponse"
},
+ "RunTagSuggestionsResponse": {
+ "properties": {
+ "keys": {
+ "items": {
+ "type": "string"
+ },
+ "type": "array",
+ "title": "Keys",
+ "description": "Distinct grouped tag keys seen on runs."
+ },
+ "values_by_key": {
+ "additionalProperties": {
+ "items": {
+ "type": "string"
+ },
+ "type": "array"
+ },
+ "type": "object",
+ "title": "Values By Key",
+ "description": "Values seen for each grouped key."
+ },
+ "labels": {
+ "items": {
+ "type": "string"
+ },
+ "type": "array",
+ "title": "Labels",
+ "description": "Distinct standalone (keyless) labels seen on runs."
+ }
+ },
+ "type": "object",
+ "title": "RunTagSuggestionsResponse",
+ "description": "Response for ``GET /v1/run-tag-suggestions``: distinct (key, value) pairs\never set on a run for the org, sourced from the event log rather than the\ntag-key/tag-value registry so reserved ``skyvern.*`` system keys (never\nregistered) reach the pickers too."
+ },
"RunTagsBatchRequest": {
"properties": {
"workflow_run_ids": {
@@ -19114,6 +19854,19 @@
"title": "RunTagsResponse",
"description": "Current tags for a workflow run."
},
+ "RunType": {
+ "type": "string",
+ "enum": [
+ "task_v1",
+ "task_v2",
+ "workflow_run",
+ "openai_cua",
+ "anthropic_cua",
+ "ui_tars",
+ "yutori_navigator"
+ ],
+ "title": "RunType"
+ },
"RunWebhookReplayResponse": {
"properties": {
"run_id": {
@@ -19515,7 +20268,7 @@
"type": "number",
"title": "Timeout",
"description": "Timeout in milliseconds",
- "default": 10000
+ "default": 5000
}
},
"type": "object",
@@ -23236,7 +23989,7 @@
"type": "number",
"title": "Timeout",
"description": "Timeout in milliseconds",
- "default": 10000
+ "default": 5000
}
},
"type": "object",
@@ -24651,6 +25404,9 @@
{
"$ref": "#/components/schemas/GoogleSheetsReadBlock"
},
+ {
+ "$ref": "#/components/schemas/EmailInboxBlock"
+ },
{
"$ref": "#/components/schemas/GoogleSheetsWriteBlock"
},
@@ -24668,6 +25424,7 @@
"code": "#/components/schemas/CodeBlock",
"conditional": "#/components/schemas/ConditionalBlock",
"download_to_s3": "#/components/schemas/DownloadToS3Block",
+ "email_inbox": "#/components/schemas/EmailInboxBlock",
"extraction": "#/components/schemas/ExtractionBlock",
"file_download": "#/components/schemas/FileDownloadBlock",
"file_upload": "#/components/schemas/FileUploadBlock",
@@ -24867,6 +25624,9 @@
{
"$ref": "#/components/schemas/GoogleSheetsReadBlockYAML"
},
+ {
+ "$ref": "#/components/schemas/EmailInboxBlockYAML"
+ },
{
"$ref": "#/components/schemas/GoogleSheetsWriteBlockYAML"
}
@@ -25655,6 +26415,9 @@
{
"$ref": "#/components/schemas/GoogleSheetsReadBlock"
},
+ {
+ "$ref": "#/components/schemas/EmailInboxBlock"
+ },
{
"$ref": "#/components/schemas/GoogleSheetsWriteBlock"
},
@@ -25672,6 +26435,7 @@
"code": "#/components/schemas/CodeBlock",
"conditional": "#/components/schemas/ConditionalBlock",
"download_to_s3": "#/components/schemas/DownloadToS3Block",
+ "email_inbox": "#/components/schemas/EmailInboxBlock",
"extraction": "#/components/schemas/ExtractionBlock",
"file_download": "#/components/schemas/FileDownloadBlock",
"file_upload": "#/components/schemas/FileUploadBlock",
@@ -25900,6 +26664,9 @@
{
"$ref": "#/components/schemas/GoogleSheetsReadBlockYAML"
},
+ {
+ "$ref": "#/components/schemas/EmailInboxBlockYAML"
+ },
{
"$ref": "#/components/schemas/GoogleSheetsWriteBlockYAML"
}
@@ -25911,6 +26678,7 @@
"code": "#/components/schemas/CodeBlockYAML",
"conditional": "#/components/schemas/ConditionalBlockYAML",
"download_to_s3": "#/components/schemas/DownloadToS3BlockYAML",
+ "email_inbox": "#/components/schemas/EmailInboxBlockYAML",
"extraction": "#/components/schemas/ExtractionBlockYAML",
"file_download": "#/components/schemas/FileDownloadBlockYAML",
"file_upload": "#/components/schemas/FileUploadBlockYAML",
diff --git a/skyvern-frontend/src/hooks/useRunsQuery.ts b/skyvern-frontend/src/hooks/useRunsQuery.ts
index 6c84ae0a6..37ae6829b 100644
--- a/skyvern-frontend/src/hooks/useRunsQuery.ts
+++ b/skyvern-frontend/src/hooks/useRunsQuery.ts
@@ -20,6 +20,7 @@ type Props = {
statusFilters?: Array<Status>;
runTypeFilters?: Array<TaskRunType>;
search?: string;
+ tags?: string;
} & UseQueryOptions;
function useRunsQuery({
@@ -28,6 +29,7 @@ function useRunsQuery({
statusFilters,
runTypeFilters,
search,
+ tags,
...queryOptions
}: Props) {
const credentialGetter = useCredentialGetter();
@@ -35,7 +37,7 @@ function useRunsQuery({
const activeOrgQueryKeyScope = getActiveOrgQueryKeyScope(activeOrgId);
return useQuery<Array<TaskRunListItem>>({
queryKey: getOrgScopedQueryKey(
- ["runs", { statusFilters, runTypeFilters }, page, pageSize, search],
+ ["runs", { statusFilters, runTypeFilters, tags }, page, pageSize, search],
activeOrgQueryKeyScope,
),
queryFn: async ({ signal }) => {
@@ -56,6 +58,9 @@ function useRunsQuery({
if (search) {
params.append("search_key", search);
}
+ if (tags) {
+ params.append("tags", tags);
+ }
return client.get("/runs", { params, signal }).then((res) => res.data);
},
...queryOptions,
diff --git a/skyvern-frontend/src/routes/history/RunHistory.runTags.test.tsx b/skyvern-frontend/src/routes/history/RunHistory.runTags.test.tsx
new file mode 100644
index 000000000..350263c1c
--- /dev/null
+++ b/skyvern-frontend/src/routes/history/RunHistory.runTags.test.tsx
@@ -0,0 +1,219 @@
+// @vitest-environment jsdom
+
+import type { ReactNode } from "react";
+import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
+import {
+ cleanup,
+ fireEvent,
+ render,
+ screen,
+ within,
+} from "@testing-library/react";
+import { MemoryRouter, useLocation } from "react-router-dom";
+import { afterEach, describe, expect, it, vi } from "vitest";
+import { TaskRunType, type TaskRunListItem } from "@/api/types";
+
+// cmdk (used by TagFilterControl) needs ResizeObserver + scrollIntoView, which
+// jsdom lacks.
+class MockResizeObserver {
+ observe() {}
+ unobserve() {}
+ disconnect() {}
+}
+(globalThis as { ResizeObserver: unknown }).ResizeObserver = MockResizeObserver;
+Element.prototype.scrollIntoView = () => {};
+
+const run: TaskRunListItem = {
+ task_run_id: "tr_1",
+ task_run_type: TaskRunType.WorkflowRun,
+ run_id: "wr_1",
+ title: "My Run",
+ status: "completed",
+ started_at: "2026-07-08T00:00:00Z",
+ finished_at: "2026-07-08T00:01:00Z",
+ created_at: "2026-07-08T00:00:00Z",
+ workflow_permanent_id: "wpid_1",
+ workflow_deleted: false,
+ script_run: false,
+ trigger_type: null,
+ searchable_text: null,
+};
+
+vi.mock("use-debounce", () => ({
+ useDebounce: <T,>(value: T): [T] => [value],
+}));
+
+vi.mock("posthog-js/react", () => ({
+ useFeatureFlagVariantKey: () => undefined,
+ useFeatureFlagEnabled: () => false,
+}));
+
+const runsQueryCalls: Array<Record<string, unknown>> = [];
+
+vi.mock("@/hooks/useRunsQuery", () => ({
+ useRunsQuery: (props: Record<string, unknown>) => {
+ runsQueryCalls.push(props);
+ return { data: [run], isFetching: false };
+ },
+}));
+
+vi.mock("@/hooks/useCredentialGetter", () => ({
+ useCredentialGetter: () => vi.fn(),
+}));
+
+const flagState = vi.hoisted(() => ({ taggingEnabled: true as boolean }));
+
+vi.mock("@/hooks/useFeatureFlag", () => ({
+ useFeatureFlag: () => flagState.taggingEnabled,
+}));
+
+vi.mock("@/routes/workflows/hooks/useGlobalWorkflowsQuery", () => ({
+ useGlobalWorkflowsQuery: () => ({ data: [] }),
+}));
+
+vi.mock("@/store/onboarding/useOnboardingState", () => ({
+ useOnboardingStateOptional: () => null,
+}));
+
+vi.mock("@/components/StatusFilterDropdown", () => ({
+ StatusFilterDropdown: () => <div data-testid="status-filter" />,
+}));
+
+vi.mock("@/components/onboarding/OnboardingEmptyState", () => ({
+ OnboardingEmptyState: () => <div data-testid="onboarding-empty" />,
+}));
+
+vi.mock("@/components/TableSearchInput", () => ({
+ TableSearchInput: () => <input aria-label="search-runs" readOnly />,
+}));
+
+vi.mock("@/api/AxiosClient", () => ({
+ getClient: vi.fn(async () => ({
+ get: vi.fn(async () => ({
+ data: { parameters: {}, extra_http_headers: null },
+ })),
+ })),
+}));
+
+vi.mock("@/routes/tasks/hooks/useRunTagsBatchQuery", () => ({
+ useRunTagsBatchQuery: () => ({
+ data: { wr_1: [{ key: "skyvern.platform", value: "platform_a" }] },
+ isPending: false,
+ }),
+}));
+
+vi.mock("@/routes/workflows/hooks/useTagKeysQuery", () => ({
+ useTagKeysQuery: () => ({ data: [] }),
+}));
+
+vi.mock("@/routes/workflows/hooks/useTagValuesQuery", () => ({
+ useTagValuesQuery: () => ({ data: new Map() }),
+}));
+
+vi.mock("@/routes/tasks/hooks/useRunTagSuggestionsQuery", () => ({
+ useRunTagSuggestionsQuery: () => ({
+ data: {
+ keys: ["skyvern.platform"],
+ valuesByKey: new Map([["skyvern.platform", ["platform_a"]]]),
+ labels: ["adhoc"],
+ },
+ }),
+}));
+
+vi.mock("@/routes/workflows/components/tagging/TagChipList", () => ({
+ TagChipList: ({
+ tags,
+ }: {
+ tags: Array<{ key: string | null; value: string }>;
+ }) => (
+ <span data-testid="tag-chip-list">
+ {tags.map((tag) => `${tag.key ?? "label"}:${tag.value}`).join(",")}
+ </span>
+ ),
+}));
+
+import { RunHistory } from "./RunHistory";
+
+function wrapper({ children }: { children: ReactNode }) {
+ const queryClient = new QueryClient({
+ defaultOptions: { queries: { retry: false } },
+ });
+ return (
+ <QueryClientProvider client={queryClient}>
+ <MemoryRouter initialEntries={["/history"]}>{children}</MemoryRouter>
+ </QueryClientProvider>
+ );
+}
+
+function LocationProbe() {
+ const location = useLocation();
+ return <output data-testid="qs">{location.search}</output>;
+}
+
+afterEach(() => {
+ runsQueryCalls.length = 0;
+ flagState.taggingEnabled = true;
+ vi.clearAllMocks();
+ cleanup();
+});
+
+describe("RunHistory run tags", () => {
+ it("renders a run-tag chip on the all-runs list", () => {
+ const { container } = render(<RunHistory />, { wrapper });
+
+ expect(
+ within(container).getByTestId("tag-chip-list").textContent,
+ ).toContain("platform_a");
+ });
+});
+
+describe("RunHistory tag filter control", () => {
+ it("drops a stale ?tags= param when tagging is disabled", () => {
+ flagState.taggingEnabled = false;
+
+ function disabledWrapper({ children }: { children: ReactNode }) {
+ const queryClient = new QueryClient({
+ defaultOptions: { queries: { retry: false } },
+ });
+ return (
+ <QueryClientProvider client={queryClient}>
+ <MemoryRouter initialEntries={["/history?tags=adhoc"]}>
+ {children}
+ </MemoryRouter>
+ </QueryClientProvider>
+ );
+ }
+
+ render(<RunHistory />, { wrapper: disabledWrapper });
+
+ const lastCall = runsQueryCalls[runsQueryCalls.length - 1];
+ expect(lastCall?.tags).toBeUndefined();
+ });
+
+ it("filters by a standalone label", () => {
+ const { container } = render(
+ <>
+ <RunHistory />
+ <LocationProbe />
+ </>,
+ { wrapper },
+ );
+
+ // TagFilterControl's popover content renders through a Radix portal
+ // (appended to document.body), so it can't be queried via `within(container)`.
+ fireEvent.click(screen.getByRole("button", { name: /tags/i }));
+ fireEvent.change(screen.getByPlaceholderText(/filter by/i), {
+ target: { value: "adhoc" },
+ });
+ fireEvent.click(screen.getByText(/^adhoc$/));
+
+ const urlParams = new URLSearchParams(
+ container.querySelector('[data-testid="qs"]')?.textContent ?? "",
+ );
+ expect(urlParams.get("tags")).toBe("adhoc");
+ expect(urlParams.get("page")).toBe("1");
+
+ const lastCall = runsQueryCalls[runsQueryCalls.length - 1];
+ expect(lastCall?.tags).toBe("adhoc");
+ });
+});
diff --git a/skyvern-frontend/src/routes/history/RunHistory.test.tsx b/skyvern-frontend/src/routes/history/RunHistory.test.tsx
index 87cb5efac..32cfa10ec 100644
--- a/skyvern-frontend/src/routes/history/RunHistory.test.tsx
+++ b/skyvern-frontend/src/routes/history/RunHistory.test.tsx
@@ -59,6 +59,22 @@ vi.mock("@/hooks/useCredentialGetter", () => ({
useCredentialGetter: () => vi.fn(),
}));
+vi.mock("@/hooks/useFeatureFlag", () => ({
+ useFeatureFlag: () => true,
+}));
+
+vi.mock("@/routes/tasks/hooks/useRunTagsBatchQuery", () => ({
+ useRunTagsBatchQuery: () => ({ data: {} }),
+}));
+
+vi.mock("@/routes/workflows/hooks/useTagKeysQuery", () => ({
+ useTagKeysQuery: () => ({ data: [] }),
+}));
+
+vi.mock("@/routes/workflows/hooks/useTagValuesQuery", () => ({
+ useTagValuesQuery: () => ({ data: new Map() }),
+}));
+
vi.mock("@/routes/workflows/hooks/useGlobalWorkflowsQuery", () => ({
useGlobalWorkflowsQuery: () => ({ data: [] }),
}));
diff --git a/skyvern-frontend/src/routes/history/RunHistory.tsx b/skyvern-frontend/src/routes/history/RunHistory.tsx
index f4ed9c120..4d1ad0c6c 100644
--- a/skyvern-frontend/src/routes/history/RunHistory.tsx
+++ b/skyvern-frontend/src/routes/history/RunHistory.tsx
@@ -59,6 +59,7 @@ import React, { useMemo, useState } from "react";
import { useNavigate, useSearchParams } from "react-router-dom";
import { getClient } from "@/api/AxiosClient";
import { useCredentialGetter } from "@/hooks/useCredentialGetter";
+import { useFeatureFlag } from "@/hooks/useFeatureFlag";
import { useDebounce } from "use-debounce";
import { Button } from "@/components/ui/button";
import {
@@ -77,6 +78,14 @@ import { useOnboardingStateOptional } from "@/store/onboarding/useOnboardingStat
import { OnboardingEmptyState } from "@/components/onboarding/OnboardingEmptyState";
import { useFeatureFlagVariantKey } from "posthog-js/react";
import { EXPERIMENT, isABVariant } from "@/util/onboarding/experimentConfig";
+import { useRunTagsBatchQuery } from "@/routes/tasks/hooks/useRunTagsBatchQuery";
+import { useRunTagSuggestionsQuery } from "@/routes/tasks/hooks/useRunTagSuggestionsQuery";
+import { useTagKeysQuery } from "@/routes/workflows/hooks/useTagKeysQuery";
+import { useTagValuesQuery } from "@/routes/workflows/hooks/useTagValuesQuery";
+import { TagChipList } from "@/routes/workflows/components/tagging/TagChipList";
+import { TagFilterControl } from "@/routes/workflows/components/tagging/TagFilterControl";
+import { useRunTagFilterParam } from "@/routes/workflows/hooks/useRunTagFilterParam";
+import { WORKFLOW_TAGGING_FLAG } from "@/util/featureFlags";
const statusValues = new Set<string>(Object.values(Status));
function isKnownStatus(value: string): value is Status {
@@ -183,6 +192,13 @@ function RunHistory() {
() => runTypeGroups.flatMap((group) => runTypeGroupToRunTypes[group]),
[runTypeGroups],
);
+ const { tagTerms, tagsParam, writeTagsParam } = useRunTagFilterParam(
+ searchParams,
+ setSearchParams,
+ );
+ const taggingEnabled = useFeatureFlag(WORKFLOW_TAGGING_FLAG) !== false;
+ // A stale ?tags= URL param would 403 the request when tagging is disabled.
+ const effectiveTagsParam = taggingEnabled ? tagsParam : undefined;
const [search, setSearch] = useState("");
const [debouncedSearch] = useDebounce(search, 500);
@@ -202,6 +218,7 @@ function RunHistory() {
statusFilters,
runTypeFilters,
search: effectiveSearch,
+ tags: effectiveTagsParam,
});
const navigate = useNavigate();
const studioEnabled = useWorkflowStudioEnabled();
@@ -212,6 +229,7 @@ function RunHistory() {
statusFilters,
runTypeFilters,
search: effectiveSearch,
+ tags: effectiveTagsParam,
enabled: rawRuns?.length === itemsPerPage,
});
@@ -242,6 +260,35 @@ function RunHistory() {
const isNextDisabled =
isFetching || !nextPageRuns || nextPageRuns.length === 0;
+ const runIds = useMemo(() => (runs ?? []).map((r) => r.run_id), [runs]);
+ const { data: runTagsMap = {} } = useRunTagsBatchQuery(runIds, {
+ enabled: taggingEnabled,
+ });
+ const { data: tagKeys = [] } = useTagKeysQuery({ enabled: taggingEnabled });
+ const tagDescriptions = useMemo(
+ () =>
+ new Map(
+ tagKeys.map((tagKey): [string, string | null] => [
+ tagKey.key,
+ tagKey.description,
+ ]),
+ ),
+ [tagKeys],
+ );
+ const { data: tagColors } = useTagValuesQuery({ enabled: taggingEnabled });
+ const { data: runTagSuggestions } = useRunTagSuggestionsQuery({
+ enabled: taggingEnabled,
+ });
+ const tagFilterKeys = useMemo(
+ () =>
+ (runTagSuggestions?.keys ?? []).map((key) => ({
+ key,
+ description: null,
+ workflow_count: 0,
+ })),
+ [runTagSuggestions?.keys],
+ );
+
const { matchesParameter } = useKeywordSearch(debouncedSearch);
const { expandedRows, toggleExpanded: toggleParametersExpanded } =
useParameterExpansion();
@@ -320,6 +367,7 @@ function RunHistory() {
const isExpanded = isWorkflowRun && expandedRows.has(run.run_id);
const navPath = getRunNavigationPath(run, studioEnabled);
const triggerType = inferTriggerType(run);
+ const runTags = runTagsMap[run.run_id];
const titleContent =
triggerType || run.script_run || run.workflow_deleted ? (
@@ -364,7 +412,17 @@ function RunHistory() {
className="max-w-0 truncate"
title={run.title ?? undefined}
>
- {titleContent}
+ <div className="flex min-w-0 flex-col gap-1">
+ {titleContent}
+ {taggingEnabled && runTags && runTags.length > 0 ? (
+ <TagChipList
+ tags={runTags}
+ descriptions={tagDescriptions}
+ colors={tagColors}
+ maxVisible={2}
+ />
+ ) : null}
+ </div>
</TableCell>
<TableCell>
{isKnownStatus(run.status) ? (
@@ -445,6 +503,7 @@ function RunHistory() {
const hasActiveFilters =
statusFilters.length > 0 ||
runTypeGroups.length > 0 ||
+ tagTerms.length > 0 ||
!!textSearch ||
!!workflowPermanentIdFilter;
const showOnboardingEmpty =
@@ -529,6 +588,16 @@ function RunHistory() {
setSearchParams(params, { replace: true });
}}
/>
+ {taggingEnabled ? (
+ <TagFilterControl
+ tagKeys={tagFilterKeys}
+ labelSuggestions={runTagSuggestions?.labels}
+ valueSuggestionsByKey={runTagSuggestions?.valuesByKey}
+ value={tagTerms}
+ onChange={writeTagsParam}
+ colors={tagColors}
+ />
+ ) : null}
<StatusFilterDropdown
values={statusFilters}
onChange={(filters) => {
diff --git a/skyvern-frontend/src/routes/tasks/hooks/useRunTagSuggestionsQuery.ts b/skyvern-frontend/src/routes/tasks/hooks/useRunTagSuggestionsQuery.ts
new file mode 100644
index 000000000..491799e86
--- /dev/null
+++ b/skyvern-frontend/src/routes/tasks/hooks/useRunTagSuggestionsQuery.ts
@@ -0,0 +1,51 @@
+import { getClient } from "@/api/AxiosClient";
+import { useCredentialGetter } from "@/hooks/useCredentialGetter";
+import { useQuery } from "@tanstack/react-query";
+import {
+ getActiveOrgQueryKeyScope,
+ getOrgScopedQueryKey,
+ useActiveOrgId,
+} from "@/store/ActiveOrgContext";
+
+interface RunTagSuggestionsResponse {
+ keys: Array<string>;
+ values_by_key: Record<string, Array<string>>;
+ labels: Array<string>;
+}
+
+type RunTagSuggestions = {
+ keys: Array<string>;
+ valuesByKey: Map<string, Array<string>>;
+ labels: Array<string>;
+};
+
+// Mirrors useTagValuesQuery's Map-in-`select` approach so the transform is
+// memoized and the returned Map reference is stable across renders.
+function useRunTagSuggestionsQuery({
+ enabled = true,
+}: { enabled?: boolean } = {}) {
+ const credentialGetter = useCredentialGetter();
+ const activeOrgId = useActiveOrgId();
+ const activeOrgQueryKeyScope = getActiveOrgQueryKeyScope(activeOrgId);
+
+ return useQuery<RunTagSuggestionsResponse, Error, RunTagSuggestions>({
+ queryKey: getOrgScopedQueryKey(
+ ["run-tag-suggestions"],
+ activeOrgQueryKeyScope,
+ ),
+ enabled,
+ queryFn: async () => {
+ const client = await getClient(credentialGetter);
+ return client
+ .get<RunTagSuggestionsResponse>("/run-tag-suggestions")
+ .then((response) => response.data);
+ },
+ select: (data) => ({
+ keys: data.keys,
+ valuesByKey: new Map(Object.entries(data.values_by_key)),
+ labels: data.labels,
+ }),
+ });
+}
+
+export { useRunTagSuggestionsQuery };
diff --git a/skyvern-frontend/src/routes/workflows/WorkflowPage.runTags.test.tsx b/skyvern-frontend/src/routes/workflows/WorkflowPage.runTags.test.tsx
new file mode 100644
index 000000000..2ae87a582
--- /dev/null
+++ b/skyvern-frontend/src/routes/workflows/WorkflowPage.runTags.test.tsx
@@ -0,0 +1,252 @@
+// @vitest-environment jsdom
+import {
+ cleanup,
+ fireEvent,
+ render,
+ screen,
+ within,
+} from "@testing-library/react";
+import { afterEach, describe, expect, it, vi } from "vitest";
+import { MemoryRouter, Route, Routes, useLocation } from "react-router-dom";
+
+import CloudContext from "@/store/CloudContext";
+import { PageSlotsProvider } from "@/store/PageSlots";
+import { Status, type WorkflowRunApiResponse } from "@/api/types";
+import { WorkflowPage } from "./WorkflowPage";
+
+// cmdk (used by TagFilterControl) needs ResizeObserver + scrollIntoView, which
+// jsdom lacks.
+class MockResizeObserver {
+ observe() {}
+ unobserve() {}
+ disconnect() {}
+}
+(globalThis as { ResizeObserver: unknown }).ResizeObserver = MockResizeObserver;
+Element.prototype.scrollIntoView = () => {};
+
+const workflowRun: WorkflowRunApiResponse = {
+ created_at: "2026-07-08T00:00:00Z",
+ failure_reason: null,
+ started_at: "2026-07-08T00:00:00Z",
+ finished_at: "2026-07-08T00:01:00Z",
+ modified_at: "2026-07-08T00:01:00Z",
+ proxy_location: null,
+ script_run: false,
+ status: Status.Completed,
+ title: "My Run",
+ trigger_type: null,
+ webhook_callback_url: "",
+ workflow_id: "wf_1",
+ workflow_permanent_id: "wpid_abc123",
+ workflow_run_id: "wr_1",
+ workflow_title: "Test Workflow",
+};
+
+vi.mock("posthog-js/react", () => ({
+ useFeatureFlagEnabled: () => false,
+ useFeatureFlagVariantKey: () => undefined,
+}));
+
+const flagState = vi.hoisted(() => ({ taggingEnabled: true as boolean }));
+
+vi.mock("@/hooks/useFeatureFlag", () => ({
+ useFeatureFlag: () => flagState.taggingEnabled,
+}));
+
+vi.mock("use-debounce", () => ({
+ useDebounce: <T,>(value: T): [T] => [value],
+}));
+
+vi.mock("@/api/AxiosClient", () => ({
+ getClient: vi.fn(),
+}));
+
+vi.mock("@/hooks/useCredentialGetter", () => ({
+ useCredentialGetter: () => vi.fn(),
+}));
+
+vi.mock("@/util/env", () => ({
+ useNewRunsUrl: false,
+}));
+
+vi.mock("@/components/StatusFilterDropdown", () => ({
+ StatusFilterDropdown: () => <div data-testid="status-filter" />,
+}));
+
+vi.mock("@/components/TableSearchInput", () => ({
+ TableSearchInput: () => <input aria-label="Search runs by input" />,
+}));
+
+vi.mock("./WorkflowActions", () => ({
+ WorkflowActions: () => <div data-testid="workflow-actions" />,
+}));
+
+vi.mock("./workflowRun/RunParametersDialog", () => ({
+ RunParametersDialog: () => null,
+}));
+
+vi.mock("./hooks/useWorkflowQuery", () => ({
+ useWorkflowQuery: () => ({
+ data: {
+ title: "Test Workflow",
+ workflow_definition: { parameters: [] },
+ },
+ isLoading: false,
+ }),
+}));
+
+const workflowRunsQueryCalls: Array<Record<string, unknown>> = [];
+
+vi.mock("./hooks/useWorkflowRunsQuery", () => ({
+ useWorkflowRunsQuery: (props: Record<string, unknown>) => {
+ workflowRunsQueryCalls.push(props);
+ return {
+ data: [workflowRun],
+ isLoading: false,
+ };
+ },
+}));
+
+vi.mock("./hooks/useWorkflowTagsBatchQuery", () => ({
+ useWorkflowTagsBatchQuery: () => ({ data: {} }),
+}));
+
+vi.mock("./hooks/useTagKeysQuery", () => ({
+ useTagKeysQuery: () => ({ data: [] }),
+}));
+
+vi.mock("./hooks/useTagValuesQuery", () => ({
+ useTagValuesQuery: () => ({ data: new Map() }),
+}));
+
+vi.mock("@/routes/tasks/hooks/useRunTagsBatchQuery", () => ({
+ useRunTagsBatchQuery: () => ({
+ data: { wr_1: [{ key: "skyvern.status", value: "completed" }] },
+ isPending: false,
+ }),
+}));
+
+vi.mock("@/routes/tasks/hooks/useRunTagSuggestionsQuery", () => ({
+ useRunTagSuggestionsQuery: () => ({
+ data: {
+ keys: ["skyvern.platform"],
+ valuesByKey: new Map([["skyvern.platform", ["platform_a"]]]),
+ labels: ["adhoc"],
+ },
+ }),
+}));
+
+vi.mock("./components/tagging/TagChipList", () => ({
+ TagChipList: ({
+ tags,
+ }: {
+ tags: Array<{ key: string | null; value: string }>;
+ }) => (
+ <span data-testid="tag-chip-list">
+ {tags.map((tag) => `${tag.key ?? "label"}:${tag.value}`).join(",")}
+ </span>
+ ),
+}));
+
+vi.mock("./hooks/useKeywordSearch", () => ({
+ useKeywordSearch: () => ({
+ matchesParameter: () => false,
+ }),
+}));
+
+vi.mock("./hooks/useParameterExpansion", () => ({
+ useParameterExpansion: () => ({
+ expandedRows: new Set<string>(),
+ toggleExpanded: vi.fn(),
+ }),
+}));
+
+vi.mock("@/store/onboarding/useOnboardingState", () => ({
+ useOnboardingState: () => ({
+ state: null,
+ isLoading: false,
+ updateState: vi.fn(),
+ isNewUser: false,
+ abVariant: null,
+ }),
+ useOnboardingStateOptional: () => ({
+ state: null,
+ isLoading: false,
+ updateState: vi.fn(),
+ isNewUser: false,
+ abVariant: null,
+ }),
+}));
+
+afterEach(() => {
+ workflowRunsQueryCalls.length = 0;
+ flagState.taggingEnabled = true;
+ cleanup();
+ vi.clearAllMocks();
+});
+
+function LocationProbe() {
+ const location = useLocation();
+ return <output data-testid="qs">{location.search}</output>;
+}
+
+function renderWorkflowPage(initialEntry = "/workflows/wpid_abc123") {
+ return render(
+ <CloudContext.Provider value={true}>
+ <PageSlotsProvider value={{}}>
+ <MemoryRouter initialEntries={[initialEntry]}>
+ <Routes>
+ <Route
+ path="/workflows/:workflowPermanentId"
+ element={
+ <>
+ <WorkflowPage />
+ <LocationProbe />
+ </>
+ }
+ />
+ </Routes>
+ </MemoryRouter>
+ </PageSlotsProvider>
+ </CloudContext.Provider>,
+ );
+}
+
+describe("WorkflowPage run tags", () => {
+ it("renders a run-tag chip on the agent runs list row", () => {
+ const { container } = renderWorkflowPage();
+
+ expect(
+ within(container).getByTestId("tag-chip-list").textContent,
+ ).toContain("completed");
+ });
+});
+
+describe("WorkflowPage tag filter control", () => {
+ it("drops a stale ?tags= param when tagging is disabled", () => {
+ flagState.taggingEnabled = false;
+
+ renderWorkflowPage("/workflows/wpid_abc123?tags=env:prod");
+
+ const lastCall = workflowRunsQueryCalls[workflowRunsQueryCalls.length - 1];
+ expect(lastCall?.tags).toBeUndefined();
+ });
+
+ it("filters by any value in a run-tag group", () => {
+ const { container } = renderWorkflowPage();
+
+ // TagFilterControl's popover content renders through a Radix portal
+ // (appended to document.body), so it can't be queried via `within(container)`.
+ fireEvent.click(screen.getByRole("button", { name: /tags/i }));
+ fireEvent.click(screen.getByText("skyvern.platform"));
+
+ const urlParams = new URLSearchParams(
+ container.querySelector('[data-testid="qs"]')?.textContent ?? "",
+ );
+ expect(urlParams.get("tags")).toBe("skyvern.platform:*");
+ expect(urlParams.get("page")).toBe("1");
+
+ const lastCall = workflowRunsQueryCalls[workflowRunsQueryCalls.length - 1];
+ expect(lastCall?.tags).toBe("skyvern.platform:*");
+ });
+});
diff --git a/skyvern-frontend/src/routes/workflows/WorkflowPage.test.tsx b/skyvern-frontend/src/routes/workflows/WorkflowPage.test.tsx
index bf1cfce1b..a1eaad3a2 100644
--- a/skyvern-frontend/src/routes/workflows/WorkflowPage.test.tsx
+++ b/skyvern-frontend/src/routes/workflows/WorkflowPage.test.tsx
@@ -69,6 +69,16 @@ vi.mock("./hooks/useWorkflowTagsBatchQuery", () => ({
useWorkflowTagsBatchQuery: () => ({ data: {} }),
}));
+vi.mock("@/routes/tasks/hooks/useRunTagsBatchQuery", () => ({
+ useRunTagsBatchQuery: () => ({ data: {} }),
+}));
+
+vi.mock("@/routes/tasks/hooks/useRunTagSuggestionsQuery", () => ({
+ useRunTagSuggestionsQuery: () => ({
+ data: { keys: [], valuesByKey: new Map(), labels: [] },
+ }),
+}));
+
vi.mock("./hooks/useTagKeysQuery", () => ({
useTagKeysQuery: () => ({ data: [] }),
}));
diff --git a/skyvern-frontend/src/routes/workflows/WorkflowPage.tsx b/skyvern-frontend/src/routes/workflows/WorkflowPage.tsx
index 1a05646c1..31e7d541f 100644
--- a/skyvern-frontend/src/routes/workflows/WorkflowPage.tsx
+++ b/skyvern-frontend/src/routes/workflows/WorkflowPage.tsx
@@ -57,6 +57,8 @@ import { useTagKeysQuery } from "./hooks/useTagKeysQuery";
import { useTagValuesQuery } from "./hooks/useTagValuesQuery";
import { useWorkflowTagsBatchQuery } from "./hooks/useWorkflowTagsBatchQuery";
import { TagChipList } from "./components/tagging/TagChipList";
+import { TagFilterControl } from "./components/tagging/TagFilterControl";
+import { useRunTagFilterParam } from "./hooks/useRunTagFilterParam";
import { WorkflowActions } from "./WorkflowActions";
import { useDebounce } from "use-debounce";
import {
@@ -87,6 +89,8 @@ import { useOnboardingStateOptional } from "@/store/onboarding/useOnboardingStat
import { OnboardingEmptyState } from "@/components/onboarding/OnboardingEmptyState";
import { usePageSlots } from "@/store/PageSlots";
import { resolveRunWindow } from "./resolveRunWindow";
+import { useRunTagsBatchQuery } from "@/routes/tasks/hooks/useRunTagsBatchQuery";
+import { useRunTagSuggestionsQuery } from "@/routes/tasks/hooks/useRunTagSuggestionsQuery";
function WorkflowPage() {
const { workflowPermanentId } = useParams();
@@ -118,6 +122,14 @@ function WorkflowPage() {
const { expandedRows, toggleExpanded: toggleParametersExpanded } =
useParameterExpansion();
+ const { tagTerms, tagsParam, writeTagsParam } = useRunTagFilterParam(
+ searchParams,
+ setSearchParams,
+ );
+
+ // undefined (OSS / pre-load) shows tagging; only an explicit cloud `false` hides it.
+ const taggingEnabled = useFeatureFlag(WORKFLOW_TAGGING_FLAG) !== false;
+
const { data: workflowRuns, isLoading } = useWorkflowRunsQuery({
workflowPermanentId,
statusFilters,
@@ -126,6 +138,8 @@ function WorkflowPage() {
search: debouncedSearch,
createdAtStart: runWindow.createdAtStart,
createdAtEnd: runWindow.createdAtEnd,
+ // A stale ?tags= URL param would 403 the request when tagging is disabled.
+ tags: taggingEnabled ? tagsParam : undefined,
refetchOnMount: "always",
});
@@ -141,8 +155,6 @@ function WorkflowPage() {
workflowPermanentId,
});
- // undefined (OSS / pre-load) shows tagging; only an explicit cloud `false` hides it.
- const taggingEnabled = useFeatureFlag(WORKFLOW_TAGGING_FLAG) !== false;
const { data: workflowTagsMap = {} } = useWorkflowTagsBatchQuery(
workflowPermanentId ? [workflowPermanentId] : [],
{ enabled: taggingEnabled },
@@ -162,6 +174,25 @@ function WorkflowPage() {
[tagKeys],
);
const { data: tagColors } = useTagValuesQuery({ enabled: taggingEnabled });
+ const runIds = useMemo(
+ () => (workflowRuns ?? []).map((r) => r.workflow_run_id),
+ [workflowRuns],
+ );
+ const { data: runTagsMap = {} } = useRunTagsBatchQuery(runIds, {
+ enabled: taggingEnabled,
+ });
+ const { data: runTagSuggestions } = useRunTagSuggestionsQuery({
+ enabled: taggingEnabled,
+ });
+ const tagFilterKeys = useMemo(
+ () =>
+ (runTagSuggestions?.keys ?? []).map((key) => ({
+ key,
+ description: null,
+ workflow_count: 0,
+ })),
+ [runTagSuggestions?.keys],
+ );
const {
workflowAnalyticsPanel: WorkflowAnalyticsPanel,
@@ -253,6 +284,7 @@ function WorkflowPage() {
{!isLoading &&
workflowRuns?.length === 0 &&
statusFilters.length === 0 &&
+ tagTerms.length === 0 &&
!debouncedSearch &&
isNewUser &&
onboardingState?.first_run_at === null &&
@@ -296,6 +328,16 @@ function WorkflowPage() {
{WorkflowRunsFilterControls ? (
<WorkflowRunsFilterControls />
) : null}
+ {taggingEnabled ? (
+ <TagFilterControl
+ tagKeys={tagFilterKeys}
+ labelSuggestions={runTagSuggestions?.labels}
+ valueSuggestionsByKey={runTagSuggestions?.valuesByKey}
+ value={tagTerms}
+ onChange={writeTagsParam}
+ colors={tagColors}
+ />
+ ) : null}
<StatusFilterDropdown
values={statusFilters}
onChange={setStatusFilters}
@@ -340,6 +382,8 @@ function WorkflowPage() {
workflowRun.workflow_run_id,
);
+ const runTags = runTagsMap[workflowRun.workflow_run_id];
+
return (
<React.Fragment key={workflowRun.workflow_run_id}>
{/* Main run row */}
@@ -365,7 +409,17 @@ function WorkflowPage() {
className="cursor-pointer"
>
<TableCell className="font-mono text-xs text-muted-foreground">
- {workflowRunId}
+ <div className="flex flex-col gap-1">
+ {workflowRunId}
+ {taggingEnabled && runTags?.length ? (
+ <TagChipList
+ tags={runTags}
+ descriptions={tagDescriptions}
+ colors={tagColors}
+ maxVisible={2}
+ />
+ ) : null}
+ </div>
</TableCell>
<TableCell>
<StatusBadge status={workflowRun.status} />
diff --git a/skyvern-frontend/src/routes/workflows/hooks/useRunTagFilterParam.test.tsx b/skyvern-frontend/src/routes/workflows/hooks/useRunTagFilterParam.test.tsx
new file mode 100644
index 000000000..e394b3fbf
--- /dev/null
+++ b/skyvern-frontend/src/routes/workflows/hooks/useRunTagFilterParam.test.tsx
@@ -0,0 +1,53 @@
+// @vitest-environment jsdom
+
+import { act, renderHook } from "@testing-library/react";
+import type { SetURLSearchParams } from "react-router-dom";
+import { describe, expect, it, vi } from "vitest";
+
+import { useRunTagFilterParam } from "./useRunTagFilterParam";
+
+describe("useRunTagFilterParam", () => {
+ it("parses repeated params and writes or clears one canonical filter", () => {
+ const searchParams = new URLSearchParams(
+ "tags=env%3Aprod&tags=standalone%2Cinvalid%3A&page=4&status=completed",
+ );
+ const setSearchParams: SetURLSearchParams = vi.fn();
+ const { result } = renderHook(() =>
+ useRunTagFilterParam(searchParams, setSearchParams),
+ );
+
+ expect(result.current.tagTerms).toEqual([
+ { key: "env", value: "prod" },
+ { key: null, value: "standalone" },
+ ]);
+ expect(result.current.tagsParam).toBe("standalone,env:prod");
+
+ act(() => {
+ result.current.writeTagsParam([
+ { key: "team", value: "qa" },
+ { key: null, value: "urgent" },
+ ]);
+ });
+
+ const firstCall = vi.mocked(setSearchParams).mock.calls[0];
+ expect(firstCall).toBeDefined();
+ const writtenParams = firstCall?.[0];
+ const options = firstCall?.[1];
+ expect(writtenParams).toBeInstanceOf(URLSearchParams);
+ expect((writtenParams as URLSearchParams).getAll("tags")).toEqual([
+ "urgent,team:qa",
+ ]);
+ expect((writtenParams as URLSearchParams).get("page")).toBe("1");
+ expect((writtenParams as URLSearchParams).get("status")).toBe("completed");
+ expect(options).toEqual({ replace: true });
+
+ act(() => {
+ result.current.writeTagsParam([]);
+ });
+
+ const clearedParams = vi.mocked(setSearchParams).mock.calls[1]?.[0];
+ expect((clearedParams as URLSearchParams).has("tags")).toBe(false);
+ expect((clearedParams as URLSearchParams).get("page")).toBe("1");
+ expect((clearedParams as URLSearchParams).get("status")).toBe("completed");
+ });
+});
diff --git a/skyvern-frontend/src/routes/workflows/hooks/useRunTagFilterParam.ts b/skyvern-frontend/src/routes/workflows/hooks/useRunTagFilterParam.ts
new file mode 100644
index 000000000..481b10e04
--- /dev/null
+++ b/skyvern-frontend/src/routes/workflows/hooks/useRunTagFilterParam.ts
@@ -0,0 +1,37 @@
+import { useMemo } from "react";
+import type { SetURLSearchParams } from "react-router-dom";
+
+import {
+ parseTagFilter,
+ serializeTagFilter,
+ type TagFilterTerm,
+} from "../types/tagTypes";
+
+function useRunTagFilterParam(
+ searchParams: URLSearchParams,
+ setSearchParams: SetURLSearchParams,
+) {
+ const tagTerms = useMemo(
+ () => parseTagFilter(searchParams.getAll("tags").join(",")),
+ [searchParams],
+ );
+ const tagsParam = useMemo(
+ () => serializeTagFilter(tagTerms) || undefined,
+ [tagTerms],
+ );
+
+ function writeTagsParam(terms: Array<TagFilterTerm>) {
+ const params = new URLSearchParams(searchParams);
+ if (terms.length === 0) {
+ params.delete("tags");
+ } else {
+ params.set("tags", serializeTagFilter(terms));
+ }
+ params.set("page", "1");
+ setSearchParams(params, { replace: true });
+ }
+
+ return { tagTerms, tagsParam, writeTagsParam };
+}
+
+export { useRunTagFilterParam };
diff --git a/skyvern-frontend/src/routes/workflows/hooks/useWorkflowRunsQuery.test.tsx b/skyvern-frontend/src/routes/workflows/hooks/useWorkflowRunsQuery.test.tsx
new file mode 100644
index 000000000..b20227265
--- /dev/null
+++ b/skyvern-frontend/src/routes/workflows/hooks/useWorkflowRunsQuery.test.tsx
@@ -0,0 +1,79 @@
+// @vitest-environment jsdom
+
+import type { ReactNode } from "react";
+import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
+import { renderHook, waitFor } from "@testing-library/react";
+import { afterEach, describe, expect, it, vi } from "vitest";
+
+const { mockGet, mockGetClient } = vi.hoisted(() => ({
+ mockGet: vi.fn(),
+ mockGetClient: vi.fn(),
+}));
+
+vi.mock("@/api/AxiosClient", () => ({
+ getClient: mockGetClient,
+}));
+vi.mock("@/hooks/useCredentialGetter", () => ({
+ useCredentialGetter: () => null,
+}));
+vi.mock("./useGlobalWorkflowsQuery", () => ({
+ useGlobalWorkflowsQuery: () => ({ data: [] }),
+}));
+
+import { useWorkflowRunsQuery } from "./useWorkflowRunsQuery";
+
+function wrapper({ children }: { children: ReactNode }) {
+ const queryClient = new QueryClient({
+ defaultOptions: { queries: { retry: false } },
+ });
+ return (
+ <QueryClientProvider client={queryClient}>{children}</QueryClientProvider>
+ );
+}
+
+afterEach(() => {
+ vi.clearAllMocks();
+});
+
+describe("useWorkflowRunsQuery", () => {
+ it("keeps the legacy route when no run-tag filter is active", async () => {
+ mockGet.mockResolvedValue({ data: [] });
+ mockGetClient.mockResolvedValue({ get: mockGet });
+
+ renderHook(
+ () =>
+ useWorkflowRunsQuery({
+ workflowPermanentId: "wpid_1",
+ page: 1,
+ }),
+ { wrapper },
+ );
+
+ await waitFor(() => expect(mockGet).toHaveBeenCalled());
+ expect(mockGetClient).toHaveBeenCalledWith(null);
+ });
+
+ it("keeps the legacy route (child runs visible) when filtering by run tags", async () => {
+ mockGet.mockResolvedValue({ data: [] });
+ mockGetClient.mockResolvedValue({ get: mockGet });
+
+ renderHook(
+ () =>
+ useWorkflowRunsQuery({
+ workflowPermanentId: "wpid_1",
+ page: 1,
+ tags: "env:prod",
+ }),
+ { wrapper },
+ );
+
+ await waitFor(() => expect(mockGet).toHaveBeenCalled());
+ expect(mockGetClient).toHaveBeenCalledWith(null);
+ expect(mockGet).toHaveBeenCalledWith(
+ "/workflows/wpid_1/runs",
+ expect.anything(),
+ );
+ const params = mockGet.mock.calls[0]?.[1].params as URLSearchParams;
+ expect(params.get("tags")).toBe("env:prod");
+ });
+});
diff --git a/skyvern-frontend/src/routes/workflows/hooks/useWorkflowRunsQuery.ts b/skyvern-frontend/src/routes/workflows/hooks/useWorkflowRunsQuery.ts
index f190a1034..c22b261d4 100644
--- a/skyvern-frontend/src/routes/workflows/hooks/useWorkflowRunsQuery.ts
+++ b/skyvern-frontend/src/routes/workflows/hooks/useWorkflowRunsQuery.ts
@@ -25,6 +25,7 @@ type Props = {
enabled?: boolean;
createdAtStart?: string;
createdAtEnd?: string;
+ tags?: string;
} & UseQueryOptions;
function useWorkflowRunsQuery({
@@ -36,6 +37,7 @@ function useWorkflowRunsQuery({
enabled,
createdAtStart,
createdAtEnd,
+ tags,
...queryOptions
}: Props) {
const { data: globalWorkflows } = useGlobalWorkflowsQuery();
@@ -47,7 +49,7 @@ function useWorkflowRunsQuery({
queryKey: getOrgScopedQueryKey(
[
"workflowRuns",
- { statusFilters },
+ { statusFilters, tags },
workflowPermanentId,
page,
pageSize,
@@ -58,6 +60,8 @@ function useWorkflowRunsQuery({
activeOrgQueryKeyScope,
),
queryFn: async ({ signal }) => {
+ // The default legacy route supports ?tags= and keeps child workflow
+ // runs visible; the /v1 route excludes them, so don't switch on filter.
const client = await getClient(credentialGetter);
const params = new URLSearchParams();
const isGlobalWorkflow = globalWorkflows?.some(
@@ -84,6 +88,9 @@ function useWorkflowRunsQuery({
if (createdAtEnd) {
params.append("created_at_end", createdAtEnd);
}
+ if (tags) {
+ params.append("tags", tags);
+ }
return client
.get(`/workflows/${workflowPermanentId}/runs`, {
diff --git a/skyvern/forge/sdk/db/repositories/tags.py b/skyvern/forge/sdk/db/repositories/tags.py
index 245d480cb..05df43b3e 100644
--- a/skyvern/forge/sdk/db/repositories/tags.py
+++ b/skyvern/forge/sdk/db/repositories/tags.py
@@ -7,7 +7,7 @@ from datetime import datetime, timezone
from typing import Any
import structlog
-from sqlalchemy import Exists, and_, exists, func, select, text, update
+from sqlalchemy import Exists, and_, exists, func, or_, select, text, update
from sqlalchemy.dialects import postgresql, sqlite
from sqlalchemy.ext.asyncio import AsyncSession
@@ -39,6 +39,11 @@ MAX_SYSTEM_TAGS_PER_WORKFLOW = RUN_METADATA_MAX_KEYS
MAX_SYSTEM_TAGS_PER_RUN = RUN_METADATA_MAX_KEYS
SYSTEM_TAG_CALLER_ID = "system"
+# Cap on distinct values surfaced per grouped key in get_run_tag_suggestions, so a
+# single high-cardinality key (one distinct value per run) can't fill the whole limit
+# and starve keys that sort after it. Standalone labels (key is None) stay uncapped.
+SUGGESTIONS_VALUES_PER_KEY = 3
+
class TagCountLimitExceeded(ValueError):
"""Raised when an apply would push a workflow over MAX_TAGS_PER_WORKFLOW."""
@@ -792,6 +797,46 @@ class TagsRepository(BaseRepository):
result = await session.execute(stmt)
return list(result.scalars().all())
+ @db_operation("get_run_tag_suggestions")
+ async def get_run_tag_suggestions(
+ self,
+ organization_id: str,
+ limit: int = 1000,
+ key_prefix: str | None = None,
+ ) -> list[tuple[str | None, str | None]]:
+ """Distinct (key, value) pairs from active run-tag SET events for the org,
+ including reserved ``skyvern.*`` system keys (the registry-backed
+ ``list_tag_keys``/``list_tag_values`` never see these, so this is their only
+ surfacing path for pickers). Each grouped key contributes at most
+ ``SUGGESTIONS_VALUES_PER_KEY`` values so no single high-cardinality key can
+ consume the whole ``limit`` and starve keys that sort after it. When
+ ``key_prefix`` is provided, filtering happens before ranking and limiting."""
+ async with self.Session() as session:
+ distinct_pairs_stmt = (
+ select(WorkflowRunTagEventModel.key, WorkflowRunTagEventModel.value)
+ .where(WorkflowRunTagEventModel.organization_id == organization_id)
+ .where(WorkflowRunTagEventModel.superseded_at.is_(None))
+ .where(WorkflowRunTagEventModel.event_type == TagEventType.SET.value)
+ )
+ if key_prefix is not None:
+ distinct_pairs_stmt = distinct_pairs_stmt.where(WorkflowRunTagEventModel.key.startswith(key_prefix))
+ distinct_pairs = distinct_pairs_stmt.distinct().subquery()
+ ranked = select(
+ distinct_pairs.c.key,
+ distinct_pairs.c.value,
+ func.row_number()
+ .over(partition_by=distinct_pairs.c.key, order_by=distinct_pairs.c.value.asc())
+ .label("rn"),
+ ).subquery()
+ stmt = (
+ select(ranked.c.key, ranked.c.value)
+ .where(or_(ranked.c.key.is_(None), ranked.c.rn <= SUGGESTIONS_VALUES_PER_KEY))
+ .order_by(ranked.c.key.asc(), ranked.c.value.asc())
+ .limit(limit)
+ )
+ result = await session.execute(stmt)
+ return [(key, value) for key, value in result]
+
@db_operation("recolor_tag_value")
async def recolor_tag_value(
self,
diff --git a/skyvern/forge/sdk/db/repositories/workflow_runs.py b/skyvern/forge/sdk/db/repositories/workflow_runs.py
index 43a9f8b98..659894b81 100644
--- a/skyvern/forge/sdk/db/repositories/workflow_runs.py
+++ b/skyvern/forge/sdk/db/repositories/workflow_runs.py
@@ -1,5 +1,6 @@
from __future__ import annotations
+from collections.abc import Sequence
from datetime import datetime, timedelta
from typing import TYPE_CHECKING, Any, Callable
from typing import cast as typing_cast
@@ -29,6 +30,7 @@ from skyvern.forge.sdk.db.base_repository import BaseRepository
from skyvern.forge.sdk.db.datetime_utils import naive_utc_now, to_naive_utc
from skyvern.forge.sdk.db.enums import WorkflowRunTriggerType
from skyvern.forge.sdk.db.exceptions import NotFoundError
+from skyvern.forge.sdk.db.tag_filters import run_tag_run_id_subqueries
if TYPE_CHECKING:
from skyvern.forge.sdk.db.base_alchemy_db import _SessionFactory
@@ -584,8 +586,10 @@ class WorkflowRunsRepository(BaseRepository):
status: list[str] | None = None,
search_key: str | None = None,
run_type: list[str] | None = None,
+ run_tags: Sequence[tuple[str | None, str | None]] | 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)
# 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.
@@ -633,6 +637,9 @@ class WorkflowRunsRepository(BaseRepository):
if run_type:
query = query.filter(TaskRunModel.task_run_type.in_(run_type))
+ for subquery in run_tag_subqueries:
+ query = query.filter(TaskRunModel.run_id.in_(subquery))
+
if search_key:
query = query.filter(
or_(
@@ -700,6 +707,8 @@ 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))
+ for subquery in run_tag_subqueries:
+ fallback_query = fallback_query.filter(WorkflowRunModel.workflow_run_id.in_(subquery))
fallback_query = fallback_query.order_by(WorkflowRunModel.created_at.desc()).limit(query_limit)
fallback_result = await session.execute(fallback_query)
rows.extend(dict(row) for row in fallback_result.mappings().all())
@@ -1200,6 +1209,7 @@ class WorkflowRunsRepository(BaseRepository):
exclude_child_runs: bool = False,
created_at_start: datetime | None = None,
created_at_end: datetime | None = None,
+ run_tags: Sequence[tuple[str | None, str | None]] | None = None,
) -> list[WorkflowRun]:
"""
Get runs for a workflow, with optional `search_key` on run ID, parameter key/description/value,
@@ -1224,6 +1234,8 @@ class WorkflowRunsRepository(BaseRepository):
query = query.filter(WorkflowRunModel.created_at >= created_at_start)
if created_at_end is not None:
query = query.filter(WorkflowRunModel.created_at < created_at_end)
+ for subquery in run_tag_run_id_subqueries(run_tags, organization_id):
+ query = query.filter(WorkflowRunModel.workflow_run_id.in_(subquery))
query = query.order_by(WorkflowRunModel.created_at.desc()).limit(page_size).offset(db_page * page_size)
workflow_runs_and_titles_tuples = (await session.execute(query)).all()
workflow_runs = [
diff --git a/skyvern/forge/sdk/routes/agent_protocol.py b/skyvern/forge/sdk/routes/agent_protocol.py
index 287427473..82cee8814 100644
--- a/skyvern/forge/sdk/routes/agent_protocol.py
+++ b/skyvern/forge/sdk/routes/agent_protocol.py
@@ -3,6 +3,7 @@ import json
import random
import time
import unicodedata
+from collections.abc import Sequence
from datetime import datetime
from enum import Enum
from typing import Annotated, Any
@@ -158,6 +159,7 @@ from skyvern.schemas.tags import (
RunTagsBatchRequest,
RunTagsBatchResponse,
RunTagsResponse,
+ RunTagSuggestionsResponse,
TagApplyRequest,
TagHistoryItem,
TagHistoryResponse,
@@ -2618,6 +2620,44 @@ async def batch_get_run_tags_post(
return _build_run_batch_response(run_ids, tag_map)
+@legacy_base_router.get(
+ "/run-tag-suggestions", response_model=RunTagSuggestionsResponse, tags=["agent"], include_in_schema=False
+)
+@legacy_base_router.get("/run-tag-suggestions/", response_model=RunTagSuggestionsResponse, include_in_schema=False)
+@base_router.get(
+ "/run-tag-suggestions",
+ response_model=RunTagSuggestionsResponse,
+ tags=["Tags"],
+ openapi_extra={"x-fern-sdk-method-name": "get_run_tag_suggestions"},
+ description="List distinct (key, value) pairs ever set on a run for the organization, sourced from the "
+ "run-tag event log rather than the tag-key/tag-value registry. Surfaces reserved 'skyvern.*' system keys "
+ "(which are never registered) so pickers can offer them alongside user-defined tags.",
+ summary="List run tag suggestions",
+ responses={200: {"description": "Successfully retrieved run tag suggestions"}},
+)
+@base_router.get("/run-tag-suggestions/", response_model=RunTagSuggestionsResponse, include_in_schema=False)
+async def get_run_tag_suggestions(
+ current_org: Organization = Depends(org_auth_service.get_current_org),
+ _tagging_gate: None = Depends(require_workflow_tagging),
+) -> RunTagSuggestionsResponse:
+ organization_id = current_org.organization_id
+ pairs = await app.DATABASE.tags.get_run_tag_suggestions(organization_id=organization_id)
+ keys: list[str] = []
+ values_by_key: dict[str, list[str]] = {}
+ labels: list[str] = []
+ for key, value in pairs:
+ if value is None:
+ continue
+ if key is None:
+ labels.append(value)
+ continue
+ if key not in values_by_key:
+ keys.append(key)
+ values_by_key[key] = []
+ values_by_key[key].append(value)
+ return RunTagSuggestionsResponse(keys=keys, values_by_key=values_by_key, labels=labels)
+
+
@legacy_base_router.post(
"/utilities/curl-to-http",
tags=["Utilities"],
@@ -3856,6 +3896,63 @@ async def get_runs(
return ORJSONResponse([run.model_dump() for run in runs])
+def _parse_tag_filter_terms(tags: list[str] | None) -> list[tuple[str | None, str | None]]:
+ """Parse a repeated/comma-separated ``tags`` query param into (key, value) filter terms.
+
+ Shared by ``get_runs_v2``, ``get_workflow_runs_by_id``, and ``get_workflows``. Each term is a
+ label (``production`` -> ``(None, "production")``), a group wildcard (``env:*`` -> ``("env", None)``),
+ or an exact group:label (``env:prod`` -> ``("env", "prod")``); malformed terms raise a 400.
+ """
+ # A lone empty value (?tags= with nothing else) is a no-op for backward
+ # compat; any blank segment alongside real ones — comma (env:prod,) or
+ # repeated (tags=env:prod&tags=) — is malformed, so both encodings 400 alike.
+ tag_groups = tags or []
+ if tag_groups == [""]:
+ tag_groups = []
+ # Split on the FIRST colon: no colon -> value-only (None, value); value `*` ->
+ # group-only (key, None); else exact (key, value), whose value may contain colons.
+ invalid_term_detail = "expected 'label', 'key:*', or 'key:value'"
+ parsed_tags: list[tuple[str | None, str | None]] = []
+ for raw_group in tag_groups:
+ for raw_term in raw_group.split(","):
+ term = raw_term.strip()
+ if not term:
+ raise HTTPException(
+ status_code=http_status.HTTP_400_BAD_REQUEST,
+ detail="Invalid tag filter; empty term.",
+ )
+ tag_key, sep, tag_value = term.partition(":")
+ if not sep:
+ parsed_tags.append((None, term))
+ continue
+ tag_key, tag_value = tag_key.strip(), tag_value.strip()
+ if not tag_key:
+ raise HTTPException(
+ status_code=http_status.HTTP_400_BAD_REQUEST,
+ detail=f"Invalid tag filter '{term}'; {invalid_term_detail}.",
+ )
+ if tag_value == "*":
+ parsed_tags.append((tag_key, None))
+ elif not tag_value:
+ raise HTTPException(
+ status_code=http_status.HTTP_400_BAD_REQUEST,
+ detail=f"Invalid tag filter '{term}'; {invalid_term_detail}.",
+ )
+ else:
+ parsed_tags.append((tag_key, tag_value))
+ return parsed_tags
+
+
+async def _parse_and_gate_tag_filter_terms(
+ tags: list[str] | None,
+ current_org: Organization,
+) -> list[tuple[str | None, str | None]]:
+ parsed_tags = _parse_tag_filter_terms(tags)
+ if parsed_tags:
+ await require_workflow_tagging(current_org)
+ return parsed_tags
+
+
# NOTE: v2 returns TaskRunListItem from the unified task_runs table,
# replacing the v1 response type (list[WorkflowRun | Task]) which
# merged two separate queries. The v1 endpoint is preserved for
@@ -3886,6 +3983,21 @@ async def get_runs_v2(
examples=["login_url", "wr_abc123"],
),
run_type: Annotated[list[RunType] | None, Query()] = None,
+ tags: Annotated[
+ list[str] | None,
+ Query(
+ max_length=20,
+ 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."
+ ),
+ examples=["env:prod", "production", "env:*", "customer:acme,env:prod"],
+ ),
+ ] = None,
) -> Response:
analytics.capture("skyvern-oss-agent-runs-v2-get")
if search_key and (page - 1) * page_size >= MAX_SEARCH_FETCH_LIMIT:
@@ -3894,6 +4006,8 @@ async def get_runs_v2(
detail=f"Search pagination is limited to the first {MAX_SEARCH_FETCH_LIMIT} matches. Use a narrower search.",
)
+ run_tags = await _parse_and_gate_tag_filter_terms(tags, current_org)
+
rows = await app.DATABASE.workflow_runs.get_all_runs_v2(
current_org.organization_id,
page=page,
@@ -3901,6 +4015,7 @@ async def get_runs_v2(
status=[s.value for s in status] if status else None,
search_key=search_key,
run_type=[r.value for r in run_type] if run_type else None,
+ run_tags=run_tags or None,
)
items = [TaskRunListItem.model_validate(row) for row in rows]
return ORJSONResponse([item.model_dump(mode="json") for item in items])
@@ -4246,6 +4361,7 @@ async def _get_workflow_runs_by_id(
exclude_child_runs: bool,
created_at_start: datetime | None = None,
created_at_end: datetime | None = None,
+ run_tags: Sequence[tuple[str | None, str | None]] | None = None,
) -> list[WorkflowRun]:
analytics.capture("skyvern-oss-agent-workflow-runs-get")
return await app.WORKFLOW_SERVICE.get_workflow_runs_for_workflow_permanent_id(
@@ -4259,6 +4375,7 @@ async def _get_workflow_runs_by_id(
exclude_child_runs=exclude_child_runs,
created_at_start=created_at_start,
created_at_end=created_at_end,
+ run_tags=run_tags,
)
@@ -4311,14 +4428,31 @@ async def get_workflow_runs_by_id(
datetime | None,
Query(description="Only include runs created strictly before this UTC timestamp (ISO 8601)."),
] = None,
+ tags: Annotated[
+ list[str] | None,
+ Query(
+ max_length=20,
+ 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."
+ ),
+ examples=["env:prod", "production", "env:*", "customer:acme,env:prod"],
+ ),
+ ] = None,
current_org: Organization = Depends(org_auth_service.get_current_org),
) -> list[WorkflowRun]:
"""
List runs for a specific workflow permanent id.
The public API excludes child workflow runs so workflow histories only show top-level runs.
- All filters (**status**, **search_key**, **error_code**) are combined with AND logic.
+ All filters (**status**, **search_key**, **error_code**, **tags**) are combined with AND logic.
"""
+ run_tags = await _parse_and_gate_tag_filter_terms(tags, current_org)
+
return await _get_workflow_runs_by_id(
workflow_id=workflow_id,
organization_id=current_org.organization_id,
@@ -4330,6 +4464,7 @@ async def get_workflow_runs_by_id(
created_at_start=created_at_start,
created_at_end=created_at_end,
exclude_child_runs=True,
+ run_tags=run_tags or None,
)
@@ -4382,13 +4517,31 @@ async def get_workflow_runs_by_id_legacy(
datetime | None,
Query(description="Only include runs created strictly before this UTC timestamp (ISO 8601)."),
] = None,
+ tags: Annotated[
+ list[str] | None,
+ Query(
+ max_length=20,
+ 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."
+ ),
+ examples=["env:prod", "production", "env:*", "customer:acme,env:prod"],
+ ),
+ ] = None,
current_org: Organization = Depends(org_auth_service.get_current_org),
) -> list[WorkflowRun]:
"""
List runs for a specific workflow permanent id using legacy endpoint behavior.
- Legacy callers keep seeing child workflow runs to avoid changing existing API behavior.
+ Legacy callers keep seeing child workflow runs to avoid changing existing API behavior,
+ including when a ``tags`` filter is active (child runs matching the filter stay visible).
"""
+ run_tags = await _parse_and_gate_tag_filter_terms(tags, current_org)
+
return await _get_workflow_runs_by_id(
workflow_id=workflow_id,
organization_id=current_org.organization_id,
@@ -4400,6 +4553,7 @@ async def get_workflow_runs_by_id_legacy(
created_at_start=created_at_start,
created_at_end=created_at_end,
exclude_child_runs=False,
+ run_tags=run_tags or None,
)
@@ -4619,49 +4773,7 @@ async def get_workflows(
# Default to published and draft if no status filter provided
effective_statuses = status if status else [WorkflowStatus.published, WorkflowStatus.draft]
- # A lone empty value (?tags= with nothing else) is a no-op for backward
- # compat; any blank segment alongside real ones — comma (env:prod,) or
- # repeated (tags=env:prod&tags=) — is malformed, so both encodings 400 alike.
- tag_groups = tags or []
- if tag_groups == [""]:
- tag_groups = []
- # Split on the FIRST colon: no colon -> value-only (None, value); value `*` ->
- # group-only (key, None); else exact (key, value), whose value may contain colons.
- invalid_term_detail = "expected 'label', 'key:*', or 'key:value'"
- workflow_tags: list[tuple[str | None, str | None]] = []
- for raw_group in tag_groups:
- for raw_term in raw_group.split(","):
- term = raw_term.strip()
- if not term:
- raise HTTPException(
- status_code=http_status.HTTP_400_BAD_REQUEST,
- detail="Invalid tag filter; empty term.",
- )
- tag_key, sep, tag_value = term.partition(":")
- if not sep:
- workflow_tags.append((None, term))
- continue
- tag_key, tag_value = tag_key.strip(), tag_value.strip()
- if not tag_key:
- raise HTTPException(
- status_code=http_status.HTTP_400_BAD_REQUEST,
- detail=f"Invalid tag filter '{term}'; {invalid_term_detail}.",
- )
- if tag_value == "*":
- workflow_tags.append((tag_key, None))
- elif not tag_value:
- raise HTTPException(
- status_code=http_status.HTTP_400_BAD_REQUEST,
- detail=f"Invalid tag filter '{term}'; {invalid_term_detail}.",
- )
- else:
- workflow_tags.append((tag_key, tag_value))
-
- if workflow_tags and not await app.AGENT_FUNCTION.is_workflow_tagging_enabled(current_org.organization_id):
- raise HTTPException(
- status_code=http_status.HTTP_403_FORBIDDEN,
- detail="Workflow tagging is not enabled for this organization.",
- )
+ workflow_tags = await _parse_and_gate_tag_filter_terms(tags, current_org)
if template and workflow_tags:
# Templates are global; tags are org-scoped, so the two can't combine.
diff --git a/skyvern/forge/sdk/workflow/service.py b/skyvern/forge/sdk/workflow/service.py
index 8e85bc44b..7a5d5b3cf 100644
--- a/skyvern/forge/sdk/workflow/service.py
+++ b/skyvern/forge/sdk/workflow/service.py
@@ -5827,6 +5827,7 @@ class WorkflowService:
exclude_child_runs: bool = False,
created_at_start: datetime | None = None,
created_at_end: datetime | None = None,
+ run_tags: Sequence[tuple[str | None, str | None]] | None = None,
) -> list[WorkflowRun]:
return await app.DATABASE.workflow_runs.get_workflow_runs_for_workflow_permanent_id(
workflow_permanent_id=workflow_permanent_id,
@@ -5839,6 +5840,7 @@ class WorkflowService:
exclude_child_runs=exclude_child_runs,
created_at_start=created_at_start,
created_at_end=created_at_end,
+ run_tags=run_tags,
)
async def get_workflow_runs_for_browser_session(
diff --git a/skyvern/schemas/tags.py b/skyvern/schemas/tags.py
index 5a6ec1879..ef42c8f95 100644
--- a/skyvern/schemas/tags.py
+++ b/skyvern/schemas/tags.py
@@ -368,3 +368,17 @@ class RunTagsBatchResponse(BaseModel):
Runs outside the caller's org are silently absent (no leakage)."""
run_tags: dict[str, list[TagItem]]
+
+
+class RunTagSuggestionsResponse(BaseModel):
+ """Response for ``GET /v1/run-tag-suggestions``: distinct (key, value) pairs
+ ever set on a run for the org, sourced from the event log rather than the
+ tag-key/tag-value registry so reserved ``skyvern.*`` system keys (never
+ registered) reach the pickers too."""
+
+ keys: list[str] = Field(default_factory=list, description="Distinct grouped tag keys seen on runs.")
+ values_by_key: dict[str, list[str]] = Field(
+ default_factory=dict,
+ description="Values seen for each grouped key.",
+ )
+ labels: list[str] = Field(default_factory=list, description="Distinct standalone (keyless) labels seen on runs.")
diff --git a/tests/unit/test_runs_list_run_tag_filter.py b/tests/unit/test_runs_list_run_tag_filter.py
new file mode 100644
index 000000000..bf39aaf0b
--- /dev/null
+++ b/tests/unit/test_runs_list_run_tag_filter.py
@@ -0,0 +1,503 @@
+"""Tag-filter tests for the GET /runs ?tags= filter (mirrors test_workflows_list_tag_filter.py).
+
+Two layers:
+- Repository tests run against in-memory SQLite so `run_tag_run_id_subqueries` executes
+ against real rows in both the main `task_runs` branch and the `search_key` fallback
+ branch that queries `WorkflowRunModel` directly.
+- Route tests mount the real FastAPI router with a mocked DATABASE/AGENT_FUNCTION so the
+ `?tags=` registration, the shared `_parse_tag_filter_terms` wiring, and the
+ `is_workflow_tagging_enabled` 403 guard are exercised end to end.
+"""
+
+from __future__ import annotations
+
+from datetime import datetime, timezone
+from unittest.mock import AsyncMock, MagicMock
+
+import pytest
+import pytest_asyncio
+from fastapi import FastAPI
+from fastapi.testclient import TestClient
+from sqlalchemy.ext.asyncio import AsyncEngine
+
+from skyvern.forge.sdk.db.base_alchemy_db import BaseAlchemyDB
+from skyvern.forge.sdk.db.models import TaskRunModel, WorkflowModel, WorkflowRunModel, WorkflowRunTagEventModel
+from skyvern.forge.sdk.db.repositories.tags import TagsRepository
+from skyvern.forge.sdk.db.repositories.workflow_runs import WorkflowRunsRepository
+from skyvern.forge.sdk.schemas.organizations import Organization
+from skyvern.forge.sdk.services import org_auth_service
+from skyvern.forge.sdk.workflow.models.tags import TagEventType, TagSource
+from skyvern.schemas.run_enums import RunType
+
+ORG_ID = "o_test"
+
+
+@pytest_asyncio.fixture
+async def engine(sqlite_engine: AsyncEngine) -> AsyncEngine:
+ return sqlite_engine
+
+
+@pytest_asyncio.fixture
+async def repo(engine: AsyncEngine) -> WorkflowRunsRepository:
+ db = BaseAlchemyDB(engine)
+ return WorkflowRunsRepository(db.Session, debug_enabled=False)
+
+
+@pytest_asyncio.fixture
+async def tags_repo(engine: AsyncEngine) -> TagsRepository:
+ db = BaseAlchemyDB(engine)
+ return TagsRepository(db.Session, debug_enabled=False)
+
+
+async def _insert_task_run(
+ repo: WorkflowRunsRepository,
+ *,
+ run_id: str,
+ task_run_type: str = RunType.workflow_run.value,
+ organization_id: str = ORG_ID,
+ status: str = "completed",
+) -> None:
+ async with repo.Session() as session:
+ session.add(
+ TaskRunModel(
+ task_run_id=f"tskrun_{run_id}",
+ organization_id=organization_id,
+ task_run_type=task_run_type,
+ run_id=run_id,
+ status=status,
+ )
+ )
+ await session.commit()
+
+
+async def _insert_workflow_run(
+ repo: WorkflowRunsRepository,
+ *,
+ workflow_run_id: str,
+ organization_id: str = ORG_ID,
+ status: str = "completed",
+) -> None:
+ async with repo.Session() as session:
+ session.add(
+ WorkflowRunModel(
+ workflow_run_id=workflow_run_id,
+ workflow_id=f"wf_{workflow_run_id}",
+ workflow_permanent_id=f"wpid_{workflow_run_id}",
+ organization_id=organization_id,
+ status=status,
+ )
+ )
+ await session.commit()
+
+
+async def _set_run_tag(
+ repo: WorkflowRunsRepository,
+ *,
+ workflow_run_id: str,
+ key: str,
+ value: str,
+ organization_id: str = ORG_ID,
+) -> None:
+ async with repo.Session() as session:
+ session.add(
+ WorkflowRunTagEventModel(
+ workflow_run_id=workflow_run_id,
+ organization_id=organization_id,
+ key=key,
+ value=value,
+ event_type=TagEventType.SET.value,
+ set_at=datetime.now(timezone.utc),
+ set_by="user_test",
+ source=TagSource.SYSTEM.value,
+ )
+ )
+ await session.commit()
+
+
+async def _insert_workflow(
+ repo: WorkflowRunsRepository,
+ *,
+ workflow_id: str,
+ workflow_permanent_id: str,
+ organization_id: str = ORG_ID,
+) -> None:
+ async with repo.Session() as session:
+ session.add(
+ WorkflowModel(
+ workflow_id=workflow_id,
+ workflow_permanent_id=workflow_permanent_id,
+ organization_id=organization_id,
+ title="Test Workflow",
+ workflow_definition={"blocks": [], "parameters": []},
+ status="published",
+ version=1,
+ )
+ )
+ await session.commit()
+
+
+async def _insert_workflow_run_for_workflow(
+ repo: WorkflowRunsRepository,
+ *,
+ workflow_run_id: str,
+ workflow_id: str,
+ workflow_permanent_id: str,
+ organization_id: str = ORG_ID,
+ status: str = "completed",
+) -> None:
+ async with repo.Session() as session:
+ session.add(
+ WorkflowRunModel(
+ workflow_run_id=workflow_run_id,
+ workflow_id=workflow_id,
+ workflow_permanent_id=workflow_permanent_id,
+ organization_id=organization_id,
+ status=status,
+ )
+ )
+ await session.commit()
+
+
+async def test_get_all_runs_v2_filters_by_run_tag(repo: WorkflowRunsRepository) -> None:
+ await _insert_task_run(repo, run_id="wr_tagged")
+ await _insert_task_run(repo, run_id="wr_untagged")
+ await _set_run_tag(repo, workflow_run_id="wr_tagged", key="skyvern.platform", value="platform_a")
+
+ rows = await repo.get_all_runs_v2(organization_id=ORG_ID, run_tags=[("skyvern.platform", "platform_a")])
+ ids = {row["run_id"] for row in rows}
+
+ assert "wr_tagged" in ids
+ assert "wr_untagged" not in ids
+
+
+async def test_get_all_runs_v2_run_tag_filter_excludes_plain_task_runs(repo: WorkflowRunsRepository) -> None:
+ # task_runs is polymorphic: task_run_type distinguishes a plain task run from a
+ # workflow run, but both share the same run_id column that the tag filter joins on.
+ # Run tags are only ever written keyed by an actual workflow_run_id, so a plain task
+ # run's run_id can never appear in the tag-event subquery: tag-filtered pages are
+ # workflow-run-only by construction.
+ await _insert_task_run(repo, run_id="tsk_plain", task_run_type=RunType.task_v1.value)
+ await _insert_task_run(repo, run_id="wr_tagged", task_run_type=RunType.workflow_run.value)
+ await _set_run_tag(repo, workflow_run_id="wr_tagged", key="skyvern.platform", value="platform_a")
+
+ rows = await repo.get_all_runs_v2(organization_id=ORG_ID, run_tags=[("skyvern.platform", "platform_a")])
+ ids = {row["run_id"] for row in rows}
+
+ assert ids == {"wr_tagged"}
+
+
+async def test_get_all_runs_v2_run_tag_filter_applies_to_search_key_fallback(repo: WorkflowRunsRepository) -> None:
+ # Both workflow runs below have no task_runs row, forcing the search_key path into
+ # the WorkflowRunModel fallback branch, where the run-tag filter must also apply.
+ await _insert_workflow_run(repo, workflow_run_id="wr_search_tagged")
+ await _insert_workflow_run(repo, workflow_run_id="wr_search_untagged")
+ await _set_run_tag(repo, workflow_run_id="wr_search_tagged", key="skyvern.platform", value="platform_a")
+
+ rows = await repo.get_all_runs_v2(
+ organization_id=ORG_ID,
+ search_key="wr_search",
+ run_tags=[("skyvern.platform", "platform_a")],
+ )
+ ids = {row["run_id"] for row in rows}
+
+ assert ids == {"wr_search_tagged"}
+
+
+async def test_get_workflow_runs_by_id_filters_by_run_tag(repo: WorkflowRunsRepository) -> None:
+ workflow_id = "wf_shared"
+ workflow_permanent_id = "wpid_shared"
+ await _insert_workflow(repo, workflow_id=workflow_id, workflow_permanent_id=workflow_permanent_id)
+ await _insert_workflow_run_for_workflow(
+ repo,
+ workflow_run_id="wr_agent_tagged",
+ workflow_id=workflow_id,
+ workflow_permanent_id=workflow_permanent_id,
+ )
+ await _insert_workflow_run_for_workflow(
+ repo,
+ workflow_run_id="wr_agent_untagged",
+ workflow_id=workflow_id,
+ workflow_permanent_id=workflow_permanent_id,
+ )
+ await _set_run_tag(repo, workflow_run_id="wr_agent_tagged", key="skyvern.platform", value="platform_a")
+
+ runs = await repo.get_workflow_runs_for_workflow_permanent_id(
+ workflow_permanent_id=workflow_permanent_id,
+ organization_id=ORG_ID,
+ run_tags=[("skyvern.platform", "platform_a")],
+ )
+ ids = {run.workflow_run_id for run in runs}
+
+ assert ids == {"wr_agent_tagged"}
+
+
+def _make_org(org_id: str = ORG_ID) -> Organization:
+ now = datetime.now(timezone.utc)
+ return Organization(
+ organization_id=org_id,
+ organization_name="Test Org",
+ created_at=now,
+ modified_at=now,
+ )
+
+
+async def test_parse_and_gate_tag_filter_terms_only_gates_nonempty_filters(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ from skyvern.forge.sdk.routes import agent_protocol as ap
+
+ gate = AsyncMock()
+ monkeypatch.setattr(ap, "require_workflow_tagging", gate)
+ organization = _make_org()
+
+ assert await ap._parse_and_gate_tag_filter_terms(None, organization) == []
+ gate.assert_not_awaited()
+
+ assert await ap._parse_and_gate_tag_filter_terms(["env:prod"], organization) == [("env", "prod")]
+ gate.assert_awaited_once_with(organization)
+
+
+def route_client(monkeypatch: pytest.MonkeyPatch) -> TestClient:
+ from skyvern.forge.sdk.routes.routers import base_router
+
+ captured: dict[str, object] = {}
+
+ async def _get_all_runs_v2(*args: object, **kwargs: object) -> list[dict[str, object]]:
+ captured["run_tags"] = kwargs.get("run_tags")
+ return []
+
+ workflow_runs_mock = MagicMock()
+ workflow_runs_mock.get_all_runs_v2 = AsyncMock(side_effect=_get_all_runs_v2)
+
+ app_mock = MagicMock()
+ app_mock.DATABASE.workflow_runs = workflow_runs_mock
+ app_mock.AGENT_FUNCTION.is_workflow_tagging_enabled = AsyncMock(return_value=True)
+
+ test_app = FastAPI()
+ test_app.include_router(base_router, prefix="/v1")
+ test_app.dependency_overrides[org_auth_service.get_current_org] = lambda: _make_org()
+
+ from skyvern.forge.sdk.routes import agent_protocol as ap
+
+ monkeypatch.setattr(ap, "app", app_mock)
+
+ client = TestClient(test_app)
+ client.captured = captured # type: ignore[attr-defined]
+ client.app_mock = app_mock # type: ignore[attr-defined]
+ return client
+
+
+def test_route_no_tags_param_passes_none_run_tags(route_client: TestClient) -> None:
+ resp = route_client.get("/v1/runs")
+ assert resp.status_code == 200, resp.text
+ assert route_client.captured["run_tags"] is None # type: ignore[attr-defined]
+
+
+def test_route_tags_param_passes_parsed_run_tags(route_client: TestClient) -> None:
+ resp = route_client.get("/v1/runs", params=[("tags", "skyvern.platform:platform_a")])
+ assert resp.status_code == 200, resp.text
+ assert route_client.captured["run_tags"] == [("skyvern.platform", "platform_a")] # type: ignore[attr-defined]
+
+
+def test_route_tags_enforces_workflow_tagging_gate(route_client: TestClient) -> None:
+ route_client.app_mock.AGENT_FUNCTION.is_workflow_tagging_enabled = AsyncMock(return_value=False) # type: ignore[attr-defined]
+ resp = route_client.get("/v1/runs", params=[("tags", "skyvern.platform:platform_a")])
+ assert resp.status_code == 403, resp.text
+
+
+def agent_runs_route_client(monkeypatch: pytest.MonkeyPatch) -> TestClient:
+ from skyvern.forge.sdk.routes.routers import base_router, legacy_base_router
+
+ captured: dict[str, object] = {}
+
+ async def _get_workflow_runs_for_workflow_permanent_id(*args: object, **kwargs: object) -> list[object]:
+ captured["run_tags"] = kwargs.get("run_tags")
+ captured["exclude_child_runs"] = kwargs.get("exclude_child_runs")
+ return []
+
+ workflow_service_mock = MagicMock()
+ workflow_service_mock.get_workflow_runs_for_workflow_permanent_id = AsyncMock(
+ side_effect=_get_workflow_runs_for_workflow_permanent_id
+ )
+
+ app_mock = MagicMock()
+ app_mock.WORKFLOW_SERVICE = workflow_service_mock
+ app_mock.AGENT_FUNCTION.is_workflow_tagging_enabled = AsyncMock(return_value=True)
+
+ test_app = FastAPI()
+ test_app.include_router(base_router, prefix="/v1")
+ test_app.include_router(legacy_base_router, prefix="/api/v1")
+ test_app.dependency_overrides[org_auth_service.get_current_org] = lambda: _make_org()
+
+ from skyvern.forge.sdk.routes import agent_protocol as ap
+
+ monkeypatch.setattr(ap, "app", app_mock)
+
+ client = TestClient(test_app)
+ client.captured = captured # type: ignore[attr-defined]
+ client.app_mock = app_mock # type: ignore[attr-defined]
+ return client
+
+
+def test_agent_runs_route_no_tags_param_passes_none_run_tags(agent_runs_route_client: TestClient) -> None:
+ resp = agent_runs_route_client.get("/v1/workflows/wpid_test/runs")
+ assert resp.status_code == 200, resp.text
+ assert agent_runs_route_client.captured["run_tags"] is None # type: ignore[attr-defined]
+
+
+def test_agent_runs_route_tags_param_passes_parsed_run_tags(agent_runs_route_client: TestClient) -> None:
+ resp = agent_runs_route_client.get("/v1/workflows/wpid_test/runs", params=[("tags", "skyvern.platform:platform_a")])
+ assert resp.status_code == 200, resp.text
+ assert agent_runs_route_client.captured["run_tags"] == [("skyvern.platform", "platform_a")] # type: ignore[attr-defined]
+
+
+def test_agent_runs_route_tags_enforces_workflow_tagging_gate(agent_runs_route_client: TestClient) -> None:
+ agent_runs_route_client.app_mock.AGENT_FUNCTION.is_workflow_tagging_enabled = AsyncMock(return_value=False) # type: ignore[attr-defined]
+ resp = agent_runs_route_client.get("/v1/workflows/wpid_test/runs", params=[("tags", "skyvern.platform:platform_a")])
+ assert resp.status_code == 403, resp.text
+
+
+def test_agent_runs_legacy_route_tags_filter_keeps_child_runs(agent_runs_route_client: TestClient) -> None:
+ resp = agent_runs_route_client.get(
+ "/api/v1/workflows/wpid_test/runs", params=[("tags", "skyvern.platform:platform_a")]
+ )
+ assert resp.status_code == 200, resp.text
+ assert agent_runs_route_client.captured["run_tags"] == [("skyvern.platform", "platform_a")] # type: ignore[attr-defined]
+ assert agent_runs_route_client.captured["exclude_child_runs"] is False # type: ignore[attr-defined]
+
+
+def test_agent_runs_legacy_route_tags_enforces_workflow_tagging_gate(agent_runs_route_client: TestClient) -> None:
+ agent_runs_route_client.app_mock.AGENT_FUNCTION.is_workflow_tagging_enabled = AsyncMock(return_value=False) # type: ignore[attr-defined]
+ resp = agent_runs_route_client.get(
+ "/api/v1/workflows/wpid_test/runs", params=[("tags", "skyvern.platform:platform_a")]
+ )
+ assert resp.status_code == 403, resp.text
+
+
+async def test_get_run_tag_suggestions_includes_system_keys(
+ repo: WorkflowRunsRepository, tags_repo: TagsRepository
+) -> None:
+ await _insert_workflow_run(repo, workflow_run_id="wr_suggestions")
+ await _set_run_tag(repo, workflow_run_id="wr_suggestions", key="skyvern.platform", value="platform_a")
+
+ pairs = await tags_repo.get_run_tag_suggestions(ORG_ID)
+
+ assert ("skyvern.platform", "platform_a") in pairs
+
+
+async def test_get_run_tag_suggestions_filters_prefix_before_limit(
+ repo: WorkflowRunsRepository, tags_repo: TagsRepository
+) -> None:
+ await _insert_workflow_run(repo, workflow_run_id="wr_prefix")
+ await _set_run_tag(repo, workflow_run_id="wr_prefix", key="custom_a", value="value_a")
+ await _set_run_tag(repo, workflow_run_id="wr_prefix", key="custom_b", value="value_b")
+ await _set_run_tag(repo, workflow_run_id="wr_prefix", key="skyvern.platform", value="platform_a")
+
+ pairs = await tags_repo.get_run_tag_suggestions(ORG_ID, limit=1, key_prefix="skyvern.")
+
+ assert pairs == [("skyvern.platform", "platform_a")]
+
+
+async def test_get_run_tag_suggestions_caps_values_per_key(
+ repo: WorkflowRunsRepository, tags_repo: TagsRepository
+) -> None:
+ for i in range(6):
+ await _insert_workflow_run(repo, workflow_run_id=f"wr_hc_{i}")
+ await _set_run_tag(repo, workflow_run_id=f"wr_hc_{i}", key="skyvern.high_card", value=f"v{i}")
+ await _set_run_tag(repo, workflow_run_id="wr_hc_0", key="team", value="alpha")
+ await _set_run_tag(repo, workflow_run_id="wr_hc_1", key="urgent", value="yes")
+
+ pairs = await tags_repo.get_run_tag_suggestions(ORG_ID, limit=5)
+
+ keys = {key for key, _ in pairs}
+ assert "team" in keys
+ assert "urgent" in keys
+ high_card_values = [value for key, value in pairs if key == "skyvern.high_card"]
+ assert len(high_card_values) == 3
+
+
+def run_tag_suggestions_route_client(monkeypatch: pytest.MonkeyPatch) -> TestClient:
+ from skyvern.forge.sdk.routes.routers import base_router
+
+ tags_mock = MagicMock()
+ tags_mock.get_run_tag_suggestions = AsyncMock(return_value=[])
+
+ app_mock = MagicMock()
+ app_mock.DATABASE.tags = tags_mock
+ app_mock.AGENT_FUNCTION.is_workflow_tagging_enabled = AsyncMock(return_value=True)
+
+ test_app = FastAPI()
+ test_app.include_router(base_router, prefix="/v1")
+ test_app.dependency_overrides[org_auth_service.get_current_org] = lambda: _make_org()
+
+ from skyvern.forge.sdk.routes import agent_protocol as ap
+
+ monkeypatch.setattr(ap, "app", app_mock)
+
+ client = TestClient(test_app)
+ client.app_mock = app_mock # type: ignore[attr-defined]
+ client.tags_mock = tags_mock # type: ignore[attr-defined]
+ return client
+
+
+def test_run_tag_suggestions_route_partitions_pairs_into_keys_values_and_labels(
+ run_tag_suggestions_route_client: TestClient,
+) -> None:
+ run_tag_suggestions_route_client.tags_mock.get_run_tag_suggestions = AsyncMock( # type: ignore[attr-defined]
+ return_value=[
+ ("skyvern.platform", "platform_a"),
+ ("skyvern.platform", "platform_b"),
+ ("env", "prod"),
+ (None, "my-label"),
+ ]
+ )
+
+ resp = run_tag_suggestions_route_client.get("/v1/run-tag-suggestions")
+
+ assert resp.status_code == 200, resp.text
+ body = resp.json()
+ assert body["keys"] == ["skyvern.platform", "env"]
+ assert body["values_by_key"] == {
+ "skyvern.platform": ["platform_a", "platform_b"],
+ "env": ["prod"],
+ }
+ assert body["labels"] == ["my-label"]
+
+
+def test_run_tag_suggestions_route_skips_pairs_with_null_value(
+ run_tag_suggestions_route_client: TestClient,
+) -> None:
+ run_tag_suggestions_route_client.tags_mock.get_run_tag_suggestions = AsyncMock( # type: ignore[attr-defined]
+ return_value=[("env", None), ("env", "prod")]
+ )
+
+ resp = run_tag_suggestions_route_client.get("/v1/run-tag-suggestions")
+
+ assert resp.status_code == 200, resp.text
+ body = resp.json()
+ assert body["keys"] == ["env"]
+ assert body["values_by_key"] == {"env": ["prod"]}
+ assert body["labels"] == []
+
+
+def test_run_tag_suggestions_route_enforces_workflow_tagging_gate(
+ run_tag_suggestions_route_client: TestClient,
+) -> None:
+ run_tag_suggestions_route_client.app_mock.AGENT_FUNCTION.is_workflow_tagging_enabled = AsyncMock( # type: ignore[attr-defined]
+ return_value=False
+ )
+
+ resp = run_tag_suggestions_route_client.get("/v1/run-tag-suggestions")
+
+ assert resp.status_code == 403, resp.text
diff --git a/tests/unit/test_runs_v2_route.py b/tests/unit/test_runs_v2_route.py
index 9b0b02323..ecfe16943 100644
--- a/tests/unit/test_runs_v2_route.py
+++ b/tests/unit/test_runs_v2_route.py
@@ -65,6 +65,7 @@ async def test_get_runs_v2_serializes_mapping_rows_from_database(monkeypatch: py
status=None,
search_key="abc",
run_type=["workflow_run", "task_v1"],
+ run_tags=None,
)
assert orjson.loads(response.body) == [
{
@@ -147,6 +148,7 @@ async def test_get_workflow_runs_by_id_child_filter_depends_on_route(
exclude_child_runs=expected_exclude_child_runs,
created_at_start=None,
created_at_end=None,
+ run_tags=None,
)