Skip to content

Automate browser based workflows with AI

Let a download filename keep the site's own name with {{ original_filename }} (SKY-17905) (#8852)

Aaron Perezc93e21107a89
diff --git a/docs/api-reference/openapi.json b/docs/api-reference/openapi.json
index cd8e09d99..2d8cdb225 100644
--- a/docs/api-reference/openapi.json
+++ b/docs/api-reference/openapi.json
@@ -14337,7 +14337,7 @@
}
],
"title": "Download Suffix",
- "description": "Suffix or complete filename for the downloaded file"
+ "description": "Complete filename for the downloaded file. Supports {{ original_filename }}, which keeps the name the site gave the file, so {{ original_filename }} alone preserves it and prefix_{{ original_filename }} prefixes it. The source extension is used unless the configured filename includes an extension, which overrides it. {{ original_filename }} must be a standalone interpolation without filters or other transformations."
},
"download_timeout": {
"anyOf": [
diff --git a/docs/cloud/building-agents/configure-blocks.mdx b/docs/cloud/building-agents/configure-blocks.mdx
index 79e48907a..3a5871aaf 100644
--- a/docs/cloud/building-agents/configure-blocks.mdx
+++ b/docs/cloud/building-agents/configure-blocks.mdx
@@ -432,7 +432,7 @@ Additional fields in **Advanced Settings:**
| Field | Type | Description |
|-------|------|-------------|
-| **File Name** | text | Custom filename for the download |
+| **File Name** | text | Custom filename for the download. Replaces the site's filename, keeping the extension. Reference `{{ original_filename }}` to keep the site's name instead — `{{ fund }}_{{ original_filename }}` prefixes it, which separates documents that several pages name identically. |
*Plus [common browser fields](#common-fields).*
diff --git a/docs/developers/browser-automations/work-with-files.mdx b/docs/developers/browser-automations/work-with-files.mdx
index b3cd3acbf..c50721f26 100644
--- a/docs/developers/browser-automations/work-with-files.mdx
+++ b/docs/developers/browser-automations/work-with-files.mdx
@@ -74,7 +74,7 @@ await browser.close();
|-----------|------|----------|-------------|
| `prompt` | `str` / `string` | Yes | Describe what to download. The agent navigates the page to find and click the download link. |
| `url` | `str` / `string` | No | URL to navigate to before downloading. Defaults to the current page URL. |
-| `download_suffix` | `str` / `string` | No | Filename hint prepended to the saved file (e.g., `"invoice"` → `invoice.pdf`). **Not a validator**; mismatched extensions don't fail the run. Omit this to get a system-generated filename like `download-<timestamp>-<random>.pdf`. |
+| `download_suffix` | `str` / `string` | No | Filename hint prepended to the saved file (e.g., `"invoice"` → `invoice.pdf`). Supports `{{ original_filename }}` to keep the site's own name (e.g., `"fund-a_{{ original_filename }}"` → `fund-a_Q4 Report.pdf`). **Not a validator**; mismatched extensions don't fail the run. Omit this to get a system-generated filename like `download-<timestamp>-<random>.pdf`. |
| `download_timeout` | `float` / `number` | No | Soft hint (seconds) for how long to wait for a download to start. Not a hard cap; the overall `timeout` below governs failure. |
| `max_steps_per_run` | `int` / `number` | No | Cap AI steps for the download navigation. |
| `timeout` | `float` / `number` | No | Total timeout in seconds (default: 1800). |
@@ -151,6 +151,16 @@ for (const file of result.downloadedFiles ?? []) {
**Set `download_suffix`** to get a predictable filename (e.g., `"invoice-q4"` → `invoice-q4.pdf`). Without it, files are saved with a system-generated name like `download-<timestamp>-<random>.pdf`. It does **not** validate or filter by extension.
+**Keep the site's filename with `{{ original_filename }}`.** When a portal serves documents whose names you need to preserve, reference `{{ original_filename }}` in `download_suffix` and Skyvern substitutes the name the site gave the file. Use it alone to keep that name as-is, or combine it with other parameters to disambiguate files that would otherwise collide:
+
+```
+download_suffix = "{{ fund }}_{{ original_filename }}" # Fund%20A_Q4 Report.pdf
+download_suffix = "{{ original_filename }}_archived" # Q4 Report_archived.pdf
+```
+
+The source extension is used unless the configured filename includes an extension, which overrides it. Files that still collide get a `_1`, `_2` counter as usual.
+Use `{{ original_filename }}` as a standalone interpolation without filters or other transformations; Skyvern substitutes the site's name after the download response is available.
+
**Raise the overall `timeout`** for large files. `download_timeout` is a soft hint; `timeout` is what actually fails the run.
**Verify with checksums.** The `checksum` field contains a SHA-256 hash. Compare it against expected values to verify file integrity.
diff --git a/docs/sdk-reference/browser-automation/agent-download-files.mdx b/docs/sdk-reference/browser-automation/agent-download-files.mdx
index 46b038f09..6ca0cf947 100644
--- a/docs/sdk-reference/browser-automation/agent-download-files.mdx
+++ b/docs/sdk-reference/browser-automation/agent-download-files.mdx
@@ -26,7 +26,7 @@ const result = await page.agent.downloadFiles("Download the latest invoice PDF",
|-----------|------|----------|-------------|
| `prompt` | `str` / `string` | Yes | What to download. |
| `url` | `str` / `string` | No | URL to navigate to. Defaults to current page URL. |
-| `download_suffix` / `downloadSuffix` | `str` / `string` | No | Expected file extension. |
+| `download_suffix` / `downloadSuffix` | `str` / `string` | No | Filename for the saved file, keeping the source extension. Supports `{{ original_filename }}` to keep the site's own name. |
| `download_timeout` / `downloadTimeout` | `float` / `number` | No | Download timeout in seconds. |
| `max_steps_per_run` / `maxStepsPerRun` | `int` / `number` | No | Max AI steps. |
| `timeout` | `float` / `number` | No | Max wait time in seconds. Default: `1800`. |
diff --git a/docs/sdk-reference/helpers/download-files.mdx b/docs/sdk-reference/helpers/download-files.mdx
index 163f385e0..84332b48b 100644
--- a/docs/sdk-reference/helpers/download-files.mdx
+++ b/docs/sdk-reference/helpers/download-files.mdx
@@ -51,7 +51,7 @@ for (const f of result.downloaded_files ?? []) {
| `browser_profile_id` | `str` | No | `None` | Load a browser profile. |
| `proxy_location` | `ProxyLocation` | No | `None` | Route through a geographic proxy. |
| `webhook_url` | `str` | No | `None` | URL to receive a POST when the download finishes. |
-| `download_suffix` | `str` | No | `None` | Expected file extension to wait for (e.g., `".pdf"`). |
+| `download_suffix` | `str` | No | `None` | Filename for the saved file, keeping the source extension. Supports `{{ original_filename }}` to keep the site's own name (e.g., `"fund-a_{{ original_filename }}"`). |
| `download_timeout` | `float` | No | `None` | Max time to wait for the download in seconds. |
| `max_steps_per_run` | `int` | No | `None` | Cap AI steps. |
| `extra_http_headers` | `dict[str, str]` | No | `None` | Additional HTTP headers. |
diff --git a/fern/openapi/skyvern_openapi.json b/fern/openapi/skyvern_openapi.json
index 224ca94e2..b2b0152ac 100644
--- a/fern/openapi/skyvern_openapi.json
+++ b/fern/openapi/skyvern_openapi.json
@@ -14242,7 +14242,7 @@
}
],
"title": "Download Suffix",
- "description": "Suffix or complete filename for the downloaded file"
+ "description": "Complete filename for the downloaded file. Supports {{ original_filename }}, which keeps the name the site gave the file, so {{ original_filename }} alone preserves it and prefix_{{ original_filename }} prefixes it. The source extension is used unless the configured filename includes an extension, which overrides it. {{ original_filename }} must be a standalone interpolation without filters or other transformations."
},
"download_timeout": {
"anyOf": [
diff --git a/skyvern-frontend/src/routes/workflows/editor/helpContent.ts b/skyvern-frontend/src/routes/workflows/editor/helpContent.ts
index c6a05a590..076365645 100644
--- a/skyvern-frontend/src/routes/workflows/editor/helpContent.ts
+++ b/skyvern-frontend/src/routes/workflows/editor/helpContent.ts
@@ -14,7 +14,7 @@ export const baseHelpTooltipContent = {
completeOnDownload:
"Allow Skyvern to auto-complete the block when it downloads a file.",
fileSuffix:
- "The complete filename (without extension) for downloaded files. This replaces the entire filename instead of being appended to a random name.",
+ "The complete filename (without extension) for downloaded files. This replaces the entire filename instead of being appended to a random name. Use {{ original_filename }} to keep the name the site gave the file, e.g. {{ fund }}_{{ original_filename }} to prefix it.",
errorCodeMapping:
"Knowing about why a block terminated can be important, specify error messages here.",
totpVerificationUrl:
@@ -39,7 +39,8 @@ export const basePlaceholderContent = {
dataExtractionGoal: "What data do you need to extract?",
maxRetries: "Default: 3",
maxStepsOverride: "Default: 10",
- downloadSuffix: "Enter the complete filename (without extension)",
+ downloadSuffix:
+ "Enter the complete filename (without extension), or prefix the site's own name with {{ original_filename }}",
totpVerificationUrl: "Provide your 2FA endpoint",
totpIdentifier: "Add an ID that links your TOTP to the block",
};
diff --git a/skyvern-frontend/src/routes/workflows/editor/panels/BlockConfigForm/FileDownloadBlockForm.test.tsx b/skyvern-frontend/src/routes/workflows/editor/panels/BlockConfigForm/FileDownloadBlockForm.test.tsx
index f4f02e688..6efe4143a 100644
--- a/skyvern-frontend/src/routes/workflows/editor/panels/BlockConfigForm/FileDownloadBlockForm.test.tsx
+++ b/skyvern-frontend/src/routes/workflows/editor/panels/BlockConfigForm/FileDownloadBlockForm.test.tsx
@@ -11,6 +11,7 @@ import type { ReactNode } from "react";
import { afterEach, beforeEach, describe, expect, test, vi } from "vitest";
import { RunEngine } from "@/api/types";
+import { placeholders } from "../../helpContent";
import type { FileDownloadNode } from "../../nodes/FileDownloadNode/types";
import type * as WorkflowEditorUtilsModule from "../../workflowEditorUtils";
import type {
@@ -661,7 +662,7 @@ describe("FileDownloadBlockForm (SKY-9361)", () => {
render(<FileDownloadBlockForm blockId="d1" />);
const suffixInput = screen.getByTestId(
- "wbi-ph-Enter the complete filename (without extension)",
+ `wbi-ph-${placeholders["download"]["downloadSuffix"]}`,
);
fireEvent.change(suffixInput, { target: { value: "invoice-2024" } });
diff --git a/skyvern/forge/agent.py b/skyvern/forge/agent.py
index 7ff1f3442..0379c27b6 100644
--- a/skyvern/forge/agent.py
+++ b/skyvern/forge/agent.py
@@ -1685,8 +1685,8 @@ class ForgeAgent:
with open(os.path.join(workflow_download_directory, local_file_name), "wb") as f:
f.write(file_data)
- file_extension = Path(local_file_name).suffix
- if file_extension == BROWSER_DOWNLOADING_SUFFIX:
+ local_basename = Path(local_file_name).name
+ if Path(local_basename).suffix == BROWSER_DOWNLOADING_SUFFIX:
LOG.warning(
"Detecting incompleted download file, skip the rename",
file=local_file_name,
@@ -1695,6 +1695,8 @@ class ForgeAgent:
)
continue
+ applied_download = context.download_suffix_applied_files.get(local_basename) if context else None
+ file_extension = Path(applied_download[0] if applied_download else local_basename).suffix
if not file_extension:
file_extension = recover_download_extension(
os.path.join(workflow_download_directory, local_file_name), download_suffix
@@ -1712,13 +1714,17 @@ class ForgeAgent:
# local_file_name is a bare basename for session (s3/gs) files but an absolute path for
# run-dir files; compare on basenames so a file already named by download_suffix is not
# treated as its own collision and bumped to ``<name>_1``.
- local_basename = Path(local_file_name).name
existing_names = {
Path(f).name
for f in list_files_in_directory(workflow_download_directory)
if Path(f).name != local_basename
}
- desired_name = download_filename_from_suffix(download_suffix, file_extension, existing_names)
+ desired_name = download_filename_from_suffix(
+ download_suffix,
+ file_extension,
+ existing_names,
+ original_filename=applied_download[0] if applied_download else local_basename,
+ )
# finalize_* keys avoid the forge_log processor, which overwrites bare task_id/
# workflow_run_id with the ambient context's values; under a stale/shared context those
# would otherwise mask the task actually being finalized (the divergence to diagnose).
@@ -3498,6 +3504,8 @@ class ForgeAgent:
context.task_id = task.task_id
context.navigation_goal = task.navigation_goal
context.navigation_payload = task.navigation_payload
+ if download_baseline_files is None:
+ context.download_suffix_applied_files = {}
context.download_suffix = task_block.download_suffix if task_block else None
# do not need to do complete verification when it's a CUA task
diff --git a/skyvern/forge/sdk/api/files.py b/skyvern/forge/sdk/api/files.py
index 3edaa253c..0a93e3e21 100644
--- a/skyvern/forge/sdk/api/files.py
+++ b/skyvern/forge/sdk/api/files.py
@@ -66,6 +66,8 @@ LOG = structlog.get_logger()
# Ids are generated from a 64-bit int, so a real one never exceeds 20 digits.
_UPLOADED_FILE_ID_PATTERN = re.compile(rf"^{UPLOADED_FILE_PREFIX}_[0-9]{{1,20}}$")
+_ORIGINAL_FILENAME_MARKER = "__skyvern_original_filename__"
+_ORIGINAL_FILENAME_TEMPLATE_RE = re.compile(r"\{\{\s*original_filename\s*\}\}")
_LOCAL_DOWNLOAD_ROOTS: set[str] = {os.path.realpath(os.path.join(settings.ARTIFACT_STORAGE_PATH, "downloads"))}
@@ -1396,8 +1398,13 @@ def recover_download_extension(file_path: str | Path, download_suffix: str | Non
Returns "" when ``download_suffix`` already carries its own extension, so the final
``download_suffix + extension`` name is not doubled (e.g. invoice.pdf + .pdf).
"""
- if download_suffix and Path(download_suffix).suffix:
- return ""
+ if download_suffix:
+ suffix_for_extension = _ORIGINAL_FILENAME_TEMPLATE_RE.sub(_ORIGINAL_FILENAME_MARKER, download_suffix)
+ if _ORIGINAL_FILENAME_MARKER in suffix_for_extension:
+ # Dots before the site-name placeholder are part of the prefix, not an explicit extension.
+ suffix_for_extension = suffix_for_extension.rsplit(_ORIGINAL_FILENAME_MARKER, 1)[1]
+ if Path(suffix_for_extension).suffix:
+ return ""
return guess_extension_from_file(file_path)
diff --git a/skyvern/forge/sdk/core/skyvern_context.py b/skyvern/forge/sdk/core/skyvern_context.py
index b389de994..1559c6fcf 100644
--- a/skyvern/forge/sdk/core/skyvern_context.py
+++ b/skyvern/forge/sdk/core/skyvern_context.py
@@ -700,6 +700,8 @@ class SkyvernContext:
navigation_payload: dict[str, Any] | list | str | None = None
complete_criterion_is_untrusted: bool = False
download_suffix: str | None = None
+ # Keep source names with exact CDP targets; finalization must not infer provenance from affixes.
+ download_suffix_applied_files: dict[str, tuple[str, str]] = field(default_factory=dict, repr=False)
totp_codes: dict[str, str | None] = field(default_factory=dict)
seed_generated_totp_values: dict[str, set[str]] = field(default_factory=dict, repr=False)
multi_field_totp: dict[str, MultiFieldTotpAttempt] = field(default_factory=dict)
diff --git a/skyvern/forge/sdk/workflow/models/block.py b/skyvern/forge/sdk/workflow/models/block.py
index a9ae3e919..b37c62640 100644
--- a/skyvern/forge/sdk/workflow/models/block.py
+++ b/skyvern/forge/sdk/workflow/models/block.py
@@ -336,7 +336,7 @@ from skyvern.utils.secret_redaction import (
redact_secrets_from_text,
)
from skyvern.utils.strings import generate_random_string
-from skyvern.utils.templating import get_available_keys, get_missing_variables
+from skyvern.utils.templating import get_available_keys, get_missing_variables, reject_jinja_transformations_on_variable
from skyvern.utils.token_counter import count_tokens, decode_tokens, encode_tokens
from skyvern.utils.url_validators import (
prepend_scheme_and_validate_url,
@@ -351,7 +351,12 @@ from skyvern.webeye.browser_engine import is_any_engine_error
from skyvern.webeye.browser_factory import rebind_download_dir
from skyvern.webeye.browser_object_predicates import is_page_like
from skyvern.webeye.browser_state import BrowserState, get_browser_state_diagnostic
-from skyvern.webeye.cdp_download_interceptor import normalize_download_filename, settle_browser_downloads_for_context
+from skyvern.webeye.cdp_download_interceptor import (
+ ORIGINAL_FILENAME_MARKER,
+ ORIGINAL_FILENAME_TEMPLATE_VARIABLE,
+ normalize_download_filename,
+ settle_browser_downloads_for_context,
+)
from skyvern.webeye.navigation import (
default_navigation_settle,
driver_nav_error_code,
@@ -949,6 +954,7 @@ class Block(BaseModel, abc.ABC):
env: SandboxedEnvironment | None = None,
skip_missing_variable_preflight: bool = False,
page_derived_capture: PageDerivedCapture | None = None,
+ extra_template_data: dict[str, Any] | None = None,
) -> str:
if field not in type(self).model_fields:
raise ValueError(f"{type(self).__name__} has no field named {field!r}")
@@ -964,6 +970,7 @@ class Block(BaseModel, abc.ABC):
env=env,
skip_missing_variable_preflight=skip_missing_variable_preflight,
page_derived_capture=page_derived_capture,
+ extra_template_data=extra_template_data,
)
except Exception as exc:
if field not in ("totp_identifier", "totp_verification_url"):
@@ -1411,6 +1418,7 @@ class Block(BaseModel, abc.ABC):
env: SandboxedEnvironment | None = None,
skip_missing_variable_preflight: bool = False,
page_derived_capture: PageDerivedCapture | None = None,
+ extra_template_data: dict[str, Any] | None = None,
) -> str:
"""
Format a template string using the workflow run context.
@@ -1430,6 +1438,10 @@ class Block(BaseModel, abc.ABC):
template_data = self._build_block_parameter_template_data(
workflow_run_context, force_include_secrets=force_include_secrets
)
+ if extra_template_data:
+ # A field-specific binding only fills a gap: a workflow that already has a parameter
+ # under the same key keeps rendering its own value.
+ template_data = {**extra_template_data, **template_data}
# A caller whose environment decides for itself what an absent binding means renders instead of
# failing here, so `| default(...)` still reaches an undefined the preflight would reject.
@@ -2130,8 +2142,17 @@ class BaseTaskBlock(Block):
)
if self.download_suffix:
+ if ORIGINAL_FILENAME_TEMPLATE_VARIABLE not in workflow_run_context.values:
+ reject_jinja_transformations_on_variable(
+ self.download_suffix,
+ ORIGINAL_FILENAME_TEMPLATE_VARIABLE,
+ jinja_sandbox_env,
+ )
self.download_suffix = self.render_templatable_field(
- "download_suffix", self.download_suffix, workflow_run_context
+ "download_suffix",
+ self.download_suffix,
+ workflow_run_context,
+ extra_template_data={ORIGINAL_FILENAME_TEMPLATE_VARIABLE: ORIGINAL_FILENAME_MARKER},
)
# encode the suffix to prevent invalid path style
self.download_suffix = quote(string=self.download_suffix, safe="")
diff --git a/skyvern/library/skyvern_browser_page_agent.py b/skyvern/library/skyvern_browser_page_agent.py
index e9568ecb2..40ba97b92 100644
--- a/skyvern/library/skyvern_browser_page_agent.py
+++ b/skyvern/library/skyvern_browser_page_agent.py
@@ -305,7 +305,8 @@ class SkyvernBrowserPageAgent:
Args:
prompt: Instructions for navigating to and downloading the file.
url: URL to navigate to for file download. If not provided, uses the current page URL.
- download_suffix: Suffix or complete filename for the downloaded file.
+ download_suffix: Complete filename for the downloaded file. Supports
+ {{ original_filename }} to keep the name the site gave the file.
download_timeout: Timeout in seconds for the download operation.
max_steps_per_run: Maximum number of steps to execute.
webhook_url: URL to receive webhook notifications about download progress.
diff --git a/skyvern/schemas/run_blocks.py b/skyvern/schemas/run_blocks.py
index 5db82ffdb..776e3c491 100644
--- a/skyvern/schemas/run_blocks.py
+++ b/skyvern/schemas/run_blocks.py
@@ -118,6 +118,15 @@ class LoginRequest(BaseRunBlockRequest):
class DownloadFilesRequest(BaseRunBlockRequest):
navigation_goal: str = Field(..., description="Instructions for navigating to and downloading the file")
- download_suffix: str | None = Field(default=None, description="Suffix or complete filename for the downloaded file")
+ download_suffix: str | None = Field(
+ default=None,
+ description=(
+ "Complete filename for the downloaded file. Supports {{ original_filename }}, which keeps the name the "
+ "site gave the file, so {{ original_filename }} alone preserves it and prefix_{{ original_filename }} "
+ "prefixes it. The source extension is used unless the configured filename includes an extension, which "
+ "overrides it. {{ original_filename }} must be a standalone interpolation without filters or other "
+ "transformations."
+ ),
+ )
download_timeout: float | None = Field(default=None, description="Timeout in seconds for the download operation")
max_steps_per_run: int | None = Field(default=None, description="Maximum number of steps to execute")
diff --git a/skyvern/services/script_service.py b/skyvern/services/script_service.py
index 2129ccf19..e4af6973f 100644
--- a/skyvern/services/script_service.py
+++ b/skyvern/services/script_service.py
@@ -11,6 +11,7 @@ from dataclasses import dataclass
from datetime import datetime, timezone
from pathlib import Path
from typing import Any, AsyncGenerator, Callable, Sequence, cast
+from urllib.parse import quote
import libcst as cst
import structlog
@@ -119,10 +120,15 @@ from skyvern.schemas.steps import AgentStepOutput
from skyvern.schemas.workflows import BlockResult, BlockStatus, BlockType, FileDownloadTarget, FileStorageType, FileType
from skyvern.utils.css_selector import build_action_summaries_with_timing
from skyvern.utils.script_file_paths import SCRIPT_FILE_PATH_ERROR, normalize_script_file_path
+from skyvern.utils.templating import reject_jinja_transformations_on_variable
from skyvern.utils.url_validators import validate_fetch_url
from skyvern.webeye.actions.action_types import ActionType
from skyvern.webeye.actions.actions import Action, DecisiveAction, reasoning_is_turn_scoped
-from skyvern.webeye.cdp_download_interceptor import download_filename_from_suffix
+from skyvern.webeye.cdp_download_interceptor import (
+ ORIGINAL_FILENAME_MARKER,
+ ORIGINAL_FILENAME_TEMPLATE_VARIABLE,
+ download_filename_from_suffix,
+)
from skyvern.webeye.scraper.scraped_page import ElementTreeFormat
LOG = structlog.get_logger()
@@ -2512,6 +2518,40 @@ async def download(
)
navigation_prompt = _render_template_with_label(navigation_prompt, cache_key)
context = skyvern_context.ensure_context()
+ context.download_suffix_applied_files.clear()
+ if download_suffix:
+ workflow_values = (
+ app.WORKFLOW_CONTEXT_MANAGER.get_workflow_run_context(context.workflow_run_id).values
+ if context.workflow_run_id
+ else {}
+ )
+ script_parameters = context.script_run_parameters
+ if not (
+ isinstance(workflow_values, dict)
+ and ORIGINAL_FILENAME_TEMPLATE_VARIABLE in workflow_values
+ or isinstance(script_parameters, dict)
+ and ORIGINAL_FILENAME_TEMPLATE_VARIABLE in script_parameters
+ ):
+ reject_jinja_transformations_on_variable(
+ download_suffix,
+ ORIGINAL_FILENAME_TEMPLATE_VARIABLE,
+ jinja_sandbox_env,
+ )
+ cached_download_suffix = (
+ quote(
+ _render_template_with_label(
+ download_suffix,
+ cache_key,
+ extra_template_data={ORIGINAL_FILENAME_TEMPLATE_VARIABLE: ORIGINAL_FILENAME_MARKER},
+ ),
+ safe="",
+ )
+ if download_suffix
+ else None
+ )
+ previous_download_suffix = context.download_suffix
+ # Cached downloads use the CDP target-path hook too, so stamp the suffix before the click for provenance.
+ context.download_suffix = cached_download_suffix
file_download_block: FileDownloadBlock | None = None
storage_type: FileStorageType | None = None
destination_delivery_started = False
@@ -2745,30 +2785,36 @@ async def download(
# Rename runs BEFORE S3 upload so that remote storage receives the
# correctly-named file and subsequent blocks get the right URLs.
# This matches the agent path ordering in agent.py.
- if download_suffix and local_download_dir.exists():
+ if cached_download_suffix and local_download_dir.exists():
local_files_after = current_attempt_local_files(local_download_dir)
files_to_rename = [file_path for file_path in newly_downloaded_files if file_path in local_files_after]
newly_downloaded_files = []
for file_path in files_to_rename:
- file_extension = Path(file_path).suffix
+ local_basename = Path(file_path).name
# Skip incomplete downloads
- if file_extension == BROWSER_DOWNLOADING_SUFFIX:
+ if Path(local_basename).suffix == BROWSER_DOWNLOADING_SUFFIX:
continue
+ applied_download = context.download_suffix_applied_files.get(local_basename)
+ file_extension = Path(applied_download[0] if applied_download else local_basename).suffix
if not file_extension:
- file_extension = recover_download_extension(file_path, download_suffix)
+ file_extension = recover_download_extension(file_path, cached_download_suffix)
if file_extension:
LOG.info(
"Recovered missing download file extension from file content",
file=file_path,
extension=file_extension,
)
- local_basename = Path(file_path).name
existing_names = {
Path(f).name
for f in list_files_in_directory(local_download_dir)
if Path(f).name != local_basename
}
- desired_name = download_filename_from_suffix(download_suffix, file_extension, existing_names)
+ desired_name = download_filename_from_suffix(
+ cached_download_suffix,
+ file_extension,
+ existing_names,
+ original_filename=applied_download[0] if applied_download else local_basename,
+ )
# context suffix fields are omitted: cached-script mode bakes the suffix into the
# generated script (no per-step contextvar stamping), so there is no task_block-vs-
# context divergence to attribute; task_id/block_label give per-download attribution.
@@ -2781,7 +2827,7 @@ async def download(
finalize_task_id=task_id,
block_label=cache_key,
pre_rename_filename_fp=diagnostic_fingerprint(local_basename),
- passed_download_suffix_fp=diagnostic_fingerprint(download_suffix),
+ passed_download_suffix_fp=diagnostic_fingerprint(cached_download_suffix),
desired_name_fp=diagnostic_fingerprint(desired_name),
will_rename=local_basename != desired_name,
)
@@ -2911,7 +2957,7 @@ async def download(
url=url,
max_steps=max_steps,
complete_on_download=complete_on_download,
- download_suffix=download_suffix,
+ download_suffix=cached_download_suffix,
error=e,
workflow_run_block_id=workflow_run_block_id,
error_code_mapping=error_code_mapping,
@@ -2967,6 +3013,7 @@ async def download(
raise
finally:
context.prompt = None
+ context.download_suffix = previous_download_suffix
_clear_cached_block_overrides(cache_key)
else:
block_validation_output = await _validate_and_get_output_parameter(label)
@@ -3525,7 +3572,9 @@ async def run_script(
LOG.warning("Failed to clean up script browser resources", script_id=script_id, exc_info=True)
-def _render_template_with_label(template: str, label: str | None = None) -> str:
+def _render_template_with_label(
+ template: str, label: str | None = None, *, extra_template_data: dict[str, Any] | None = None
+) -> str:
template_data = {}
context = skyvern_context.current()
if context and context.workflow_run_id:
@@ -3563,6 +3612,8 @@ def _render_template_with_label(template: str, label: str | None = None) -> str:
template_data["current_date"] = datetime.now(timezone.utc).strftime(CURRENT_DATE_FORMAT)
if "browser_session_id" not in template_data:
template_data["browser_session_id"] = workflow_run_context.browser_session_id or ""
+ if extra_template_data:
+ template_data = {**extra_template_data, **template_data}
return render_template(template, data=template_data)
diff --git a/skyvern/utils/templating.py b/skyvern/utils/templating.py
index bae0f4366..3e4e6c294 100644
--- a/skyvern/utils/templating.py
+++ b/skyvern/utils/templating.py
@@ -115,6 +115,26 @@ def get_missing_variables(template_source: str, template_data: dict) -> set[str]
return missing_vars
+def reject_jinja_transformations_on_variable(
+ template_source: str,
+ variable_name: str,
+ env: SandboxedEnvironment | None = None,
+) -> None:
+ """Require a delayed placeholder to be emitted as a standalone interpolation."""
+ ast = (env or SandboxedEnvironment()).parse(template_source)
+ direct_interpolations = {
+ id(expression)
+ for output in ast.find_all(nodes.Output)
+ for expression in output.nodes
+ if isinstance(expression, nodes.Name) and expression.name == variable_name
+ }
+ if any(
+ variable.name == variable_name and id(variable) not in direct_interpolations
+ for variable in ast.find_all(nodes.Name)
+ ):
+ raise ValueError(f"The {variable_name} placeholder must be used without Jinja transformations")
+
+
MAX_AVAILABLE_KEYS = 200
MAX_AVAILABLE_KEY_LENGTH = 128
MAX_AVAILABLE_PATH_LENGTH = 512
diff --git a/skyvern/webeye/actions/handler.py b/skyvern/webeye/actions/handler.py
index 19c30c7ac..cedbac4bc 100644
--- a/skyvern/webeye/actions/handler.py
+++ b/skyvern/webeye/actions/handler.py
@@ -1267,7 +1267,9 @@ def _download_target_path(download_dir: Path, suggested_filename: str | None) ->
# Name the file by the block-configured download_suffix so the watcher syncs the
# request-based name instead of the site's suggested name.
existing = {p.name for p in download_dir.iterdir()} if download_dir.exists() else set()
- target_name = download_filename_from_suffix(download_suffix, suffix, existing)
+ target_name = download_filename_from_suffix(download_suffix, suffix, existing, original_filename=filename)
+ if context:
+ context.download_suffix_applied_files[target_name] = (filename, download_suffix)
LOG.info(
"download_suffix_target_named",
context_task_id=context.task_id if context else None,
diff --git a/skyvern/webeye/cdp_download_interceptor.py b/skyvern/webeye/cdp_download_interceptor.py
index e1b63e70e..e8f2c14bf 100644
--- a/skyvern/webeye/cdp_download_interceptor.py
+++ b/skyvern/webeye/cdp_download_interceptor.py
@@ -270,6 +270,15 @@ DOWNLOAD_EXTENSION_BY_MIME_TYPE = {
_FILENAME_PATH_SEPARATOR_RE = re.compile(r"[\\/]+")
_FILENAME_CONTROL_CHAR_RE = re.compile(r"[\x00-\x1f\x7f]")
_WINDOWS_DRIVE_RE = re.compile(r"^[A-Za-z]:[\\/]")
+
+# The variable a download filename template uses to keep the site's own name, e.g.
+# "{{ fund }}_{{ original_filename }}". It renders to a marker rather than to the name itself,
+# because the name only exists once the download lands; the marker is substituted at rename time.
+# Built from unreserved characters so the percent-encoding the renderer applies leaves it intact.
+ORIGINAL_FILENAME_TEMPLATE_VARIABLE = "original_filename"
+ORIGINAL_FILENAME_MARKER = "__skyvern_original_filename__"
+_ORIGINAL_FILENAME_JINJA_RE = re.compile(r"\{\{\s*" + ORIGINAL_FILENAME_TEMPLATE_VARIABLE + r"\s*\}\}")
+_MAX_DOWNLOAD_FILENAME_BYTES = 255
_DATA_URL_TOKEN = r"[!#$%&'*+.^_`|~A-Za-z0-9-]+"
_DATA_URL_MEDIA_TYPE_RE = re.compile(rf"^{_DATA_URL_TOKEN}/{_DATA_URL_TOKEN}$")
_DATA_URL_PARAMETER_NAME_RE = re.compile(rf"^{_DATA_URL_TOKEN}$")
@@ -657,22 +666,101 @@ def _validated_download_basename(filename: str, content_type: str = "") -> str:
return normalize_download_filename(decoded_filename, content_type)
-def download_filename_from_suffix(download_suffix: str, source_extension: str, existing_names: set[str]) -> str:
- """Filename for a download whose block configured ``download_suffix``"""
- existing_names = {Path(n).name for n in existing_names} # contract: dedup on basenames, never full paths
- name = Path(download_suffix).name # defensive: never let a suffix escape the dir
+def _marked_download_suffix(download_suffix: str) -> str:
+ """``download_suffix`` with every ``original_filename`` reference reduced to the marker.
+
+ The renderer normally produces the marker, but the cached-script path bakes the author's
+ filename template into generated code as a literal and never renders it, so the raw
+ ``{{ original_filename }}`` spelling has to resolve here too.
+ """
+ return _ORIGINAL_FILENAME_JINJA_RE.sub(ORIGINAL_FILENAME_MARKER, download_suffix)
+
+
+def _download_suffix_stem_and_extension(download_suffix: str, source_extension: str) -> tuple[str, str]:
+ name = Path(_marked_download_suffix(download_suffix)).name # defensive: never let a suffix escape the dir
+ if ORIGINAL_FILENAME_MARKER in name:
+ suffix_after_marker = name.rsplit(ORIGINAL_FILENAME_MARKER, 1)[1]
+ suffix_ext = Path(suffix_after_marker).suffix
+ if suffix_ext:
+ return name[: -len(suffix_ext)], suffix_ext
+ return name, source_extension or ""
suffix_ext = Path(name).suffix
if suffix_ext:
- stem, ext = name[: -len(suffix_ext)], suffix_ext
- else:
- stem, ext = name, source_extension or ""
- stem = stem or "download"
- candidate = f"{stem}{ext}"
+ return name[: -len(suffix_ext)], suffix_ext
+ return name, source_extension or ""
+
+
+def _basename_stem(filename: str) -> str:
+ name = Path(filename).name
+ extension = Path(name).suffix
+ return name[: -len(extension)] if extension else name
+
+
+def original_filename_stem(original_filename: str | None) -> str:
+ """``original_filename`` reduced to a stem safe to substitute into a download name.
+
+ The site chooses this name, so it goes through the same sanitization as a server-provided
+ filename; its extension is dropped because the final name's extension is resolved separately.
+ Truncated because a site-controlled basename can exceed the filesystem's 255-byte component limit.
+ """
+ stem = _basename_stem(normalize_download_filename(Path(original_filename or "").name))
+ return _truncate_utf8_to_bytes(stem, _MAX_DOWNLOAD_FILENAME_BYTES).strip(" .")
+
+
+def _truncate_utf8_to_bytes(value: str, max_bytes: int) -> str:
+ return value.encode("utf-8")[:max_bytes].decode("utf-8", errors="ignore")
+
+
+def append_download_extension_if_missing(filename: str, extension: str) -> str:
+ """Preserve a recovered source extension when a download-time name has none."""
+ if not extension or Path(filename).suffix.lower() == extension.lower():
+ return filename
+ return f"{filename}{extension}"
+
+
+def _unique_download_filename(stem: str, extension: str, existing_names: set[str]) -> str:
+ existing_names = {file_api.sanitize_filename(Path(name).name) for name in existing_names}
+ stem = file_api.sanitize_filename(stem).strip(" .") or "download"
+ extension = file_api.sanitize_filename(extension)
counter = 1
- while candidate in existing_names:
- candidate = f"{stem}_{counter}{ext}"
+ while True:
+ counter_suffix = "" if counter == 1 else f"_{counter - 1}"
+ bounded_extension = _truncate_utf8_to_bytes(
+ extension, _MAX_DOWNLOAD_FILENAME_BYTES - len(counter_suffix.encode("utf-8"))
+ )
+ bounded_stem = _truncate_utf8_to_bytes(
+ stem,
+ _MAX_DOWNLOAD_FILENAME_BYTES - len(counter_suffix.encode("utf-8")) - len(bounded_extension.encode("utf-8")),
+ ).strip(" .")
+ candidate = file_api.sanitize_filename(f"{bounded_stem}{counter_suffix}{bounded_extension}")
+ if candidate not in existing_names:
+ return candidate
counter += 1
- return candidate
+
+
+def unique_download_filename(filename: str, source_extension: str, existing_names: set[str]) -> str:
+ """Ensure a final download-time name and recovered extension do not overwrite a file."""
+ candidate = append_download_extension_if_missing(Path(filename).name, source_extension)
+ extension = (
+ candidate[-len(source_extension) :]
+ if source_extension and candidate.lower().endswith(source_extension.lower())
+ else ""
+ )
+ stem = candidate[: -len(extension)] if extension else candidate
+ return _unique_download_filename(stem, extension, existing_names)
+
+
+def download_filename_from_suffix(
+ download_suffix: str,
+ source_extension: str,
+ existing_names: set[str],
+ original_filename: str | None = None,
+) -> str:
+ """Filename for a download whose block configured ``download_suffix``"""
+ stem, ext = _download_suffix_stem_and_extension(download_suffix, source_extension)
+ if ORIGINAL_FILENAME_MARKER in stem:
+ stem = stem.replace(ORIGINAL_FILENAME_MARKER, original_filename_stem(original_filename))
+ return _unique_download_filename(stem, ext, existing_names)
def is_download_response(headers: dict[str, str], status_code: int, resource_type: str = "") -> bool:
diff --git a/tests/unit/test_agent_cleanup_download_suffix.py b/tests/unit/test_agent_cleanup_download_suffix.py
index a16bdce70..33cb8bba6 100644
--- a/tests/unit/test_agent_cleanup_download_suffix.py
+++ b/tests/unit/test_agent_cleanup_download_suffix.py
@@ -17,7 +17,9 @@ from skyvern.forge.sdk.artifact.storage.base import get_download_retry_started_a
from skyvern.forge.sdk.core.skyvern_context import SkyvernContext
from skyvern.forge.sdk.models import StepStatus
from skyvern.schemas.runs import RunEngine
+from skyvern.webeye.actions.handler import _download_target_path
from skyvern.webeye.actions.models import DetailedAgentStepOutput
+from skyvern.webeye.cdp_download_interceptor import ORIGINAL_FILENAME_MARKER
from tests.unit._fingerprint_expectations import expected_fingerprint
@@ -72,6 +74,60 @@ async def test_finalize_downloaded_files_renames_with_download_suffix(tmp_path)
rename_mock.assert_called_once_with(os.path.join(download_dir, "uuid-file.zip"), "req-123.zip")
+async def test_finalize_recovers_extension_from_original_name_with_dotted_prefix(tmp_path) -> None:
+ agent = ForgeAgent()
+ download_dir = tmp_path / "downloads"
+ download_dir.mkdir()
+ suffix = f"Acme.L.P._{ORIGINAL_FILENAME_MARKER}"
+ target_name = "Acme.L.P._export"
+ (download_dir / target_name).write_bytes(b"workbook")
+ context = SkyvernContext(download_suffix=suffix)
+ context.download_suffix_applied_files[target_name] = ("export", suffix)
+
+ with (
+ patch("skyvern.forge.agent.get_path_for_workflow_download_directory", return_value=download_dir),
+ patch("skyvern.forge.agent.skyvern_context.current", return_value=context),
+ patch("skyvern.forge.agent.recover_download_extension", return_value=".xlsx") as recover_extension,
+ ):
+ await agent._finalize_downloaded_files_for_task(
+ _make_task(),
+ organization_id="org-1",
+ download_suffix=suffix,
+ list_files_before=[],
+ randomize_if_missing=False,
+ )
+
+ recover_extension.assert_called_once_with(str(download_dir / target_name), suffix)
+ assert (download_dir / f"{target_name}.xlsx").exists()
+
+
+async def test_finalize_preserves_explicit_suffix_extension(tmp_path) -> None:
+ agent = ForgeAgent()
+ download_dir = tmp_path / "downloads"
+ download_dir.mkdir()
+ target_name = "custom.txt"
+ (download_dir / target_name).write_bytes(b"report")
+ context = SkyvernContext(download_suffix=target_name)
+ context.download_suffix_applied_files[target_name] = ("report.pdf", target_name)
+
+ with (
+ patch("skyvern.forge.agent.get_path_for_workflow_download_directory", return_value=download_dir),
+ patch("skyvern.forge.agent.skyvern_context.current", return_value=context),
+ ):
+ await agent._finalize_downloaded_files_for_task(
+ _make_task(),
+ organization_id="org-1",
+ download_suffix=target_name,
+ list_files_before=[],
+ randomize_if_missing=False,
+ )
+
+ assert (download_dir / target_name).exists()
+ assert not (download_dir / "custom.txt.pdf").exists()
+
+
@pytest.mark.asyncio
async def test_finalize_excludes_incomplete_file_created_during_discovery(tmp_path) -> None:
agent = ForgeAgent()
@@ -119,7 +175,12 @@ async def test_finalize_skips_rename_for_session_file_already_named_by_suffix(tm
patch("skyvern.forge.agent.get_path_for_workflow_download_directory", return_value=download_dir),
patch("skyvern.forge.agent.get_aws_client", return_value=aws_client),
patch("skyvern.forge.agent.rename_file", rename_mock),
- patch("skyvern.forge.agent.skyvern_context.current", return_value=None),
+ patch(
+ "skyvern.forge.agent.skyvern_context.current",
+ return_value=SkyvernContext(
+ download_suffix="req-123", download_suffix_applied_files={"req-123.pdf": ("site.pdf", "req-123")}
+ ),
+ ),
patch("skyvern.forge.agent.app") as mock_app,
):
mock_app.STORAGE.list_downloaded_files_in_browser_session = AsyncMock(
@@ -188,7 +249,12 @@ async def test_finalize_skips_rename_for_local_file_already_named_by_suffix(tmp_
with (
patch("skyvern.forge.agent.get_path_for_workflow_download_directory", return_value=download_dir),
patch("skyvern.forge.agent.rename_file", rename_mock),
- patch("skyvern.forge.agent.skyvern_context.current", return_value=None),
+ patch(
+ "skyvern.forge.agent.skyvern_context.current",
+ return_value=SkyvernContext(
+ download_suffix="req-123", download_suffix_applied_files={"req-123.pdf": ("site.pdf", "req-123")}
+ ),
+ ),
):
await agent._finalize_downloaded_files_for_task(
task,
@@ -203,6 +269,101 @@ async def test_finalize_skips_rename_for_local_file_already_named_by_suffix(tmp_
assert not (download_dir / "req-123_1.pdf").exists()
+async def test_finalize_appends_recovered_extension_to_already_named_file(tmp_path) -> None:
+ agent = ForgeAgent()
+ task = _make_task()
+ download_dir = tmp_path / "downloads"
+ download_dir.mkdir()
+ rename_mock = MagicMock()
+ file_path = str(download_dir / "ACME_export")
+
+ with (
+ patch("skyvern.forge.agent.get_path_for_workflow_download_directory", return_value=download_dir),
+ patch("skyvern.forge.agent.list_files_in_directory", return_value=[file_path]),
+ patch("skyvern.forge.agent.recover_download_extension", return_value=".xlsx"),
+ patch("skyvern.forge.agent.rename_file", rename_mock),
+ patch(
+ "skyvern.forge.agent.skyvern_context.current",
+ return_value=SkyvernContext(
+ download_suffix=f"ACME_{ORIGINAL_FILENAME_MARKER}",
+ download_suffix_applied_files={"ACME_export": ("export", f"ACME_{ORIGINAL_FILENAME_MARKER}")},
+ ),
+ ),
+ ):
+ await agent._finalize_downloaded_files_for_task(
+ task,
+ organization_id=task.organization_id,
+ download_suffix=f"ACME_{ORIGINAL_FILENAME_MARKER}",
+ list_files_before=[],
+ randomize_if_missing=False,
+ )
+
+ rename_mock.assert_called_once_with(file_path, "ACME_export.xlsx")
+
+
+async def test_finalize_prefixes_site_name_that_matches_template_affixes(tmp_path) -> None:
+ agent = ForgeAgent()
+ task = _make_task()
+ download_dir = tmp_path / "downloads"
+ download_dir.mkdir()
+ file_path = str(download_dir / "ACME_report.pdf")
+ rename_mock = MagicMock()
+
+ with (
+ patch("skyvern.forge.agent.get_path_for_workflow_download_directory", return_value=download_dir),
+ patch("skyvern.forge.agent.list_files_in_directory", return_value=[file_path]),
+ patch("skyvern.forge.agent.rename_file", rename_mock),
+ patch(
+ "skyvern.forge.agent.skyvern_context.current",
+ return_value=SkyvernContext(download_suffix=f"ACME_{ORIGINAL_FILENAME_MARKER}"),
+ ),
+ ):
+ await agent._finalize_downloaded_files_for_task(
+ task,
+ organization_id=task.organization_id,
+ download_suffix=f"ACME_{ORIGINAL_FILENAME_MARKER}",
+ list_files_before=[],
+ randomize_if_missing=False,
+ )
+
+ rename_mock.assert_called_once_with(file_path, "ACME_ACME_report.pdf")
+
+
+async def test_finalize_recovered_extension_dedupes_before_rename(tmp_path) -> None:
+ agent = ForgeAgent()
+ task = _make_task()
+ download_dir = tmp_path / "downloads"
+ download_dir.mkdir()
+ extensionless_path = str(download_dir / "ACME_export")
+ existing_path = str(download_dir / "ACME_export.xlsx")
+ (download_dir / "ACME_export").write_bytes(b"new")
+ (download_dir / "ACME_export.xlsx").write_bytes(b"existing")
+ context = SkyvernContext(
+ download_suffix=f"ACME_{ORIGINAL_FILENAME_MARKER}",
+ download_suffix_applied_files={"ACME_export": ("export", f"ACME_{ORIGINAL_FILENAME_MARKER}")},
+ )
+
+ with (
+ patch("skyvern.forge.agent.get_path_for_workflow_download_directory", return_value=download_dir),
+ patch("skyvern.forge.agent.list_files_in_directory", return_value=[extensionless_path, existing_path]),
+ patch("skyvern.forge.agent.recover_download_extension", return_value=".xlsx"),
+ patch("skyvern.forge.agent.skyvern_context.current", return_value=context),
+ ):
+ await agent._finalize_downloaded_files_for_task(
+ task,
+ organization_id=task.organization_id,
+ download_suffix=f"ACME_{ORIGINAL_FILENAME_MARKER}",
+ list_files_before=[existing_path],
+ randomize_if_missing=False,
+ )
+
+ assert (download_dir / "ACME_export_1.xlsx").read_bytes() == b"new"
+ assert (download_dir / "ACME_export.xlsx").read_bytes() == b"existing"
+
+
@pytest.mark.asyncio
async def test_cleanup_task_finalizes_downloads_before_saving(tmp_path) -> None:
agent = ForgeAgent()
@@ -475,15 +636,16 @@ async def test_execute_step_reuses_initial_download_baseline_across_recursive_st
task_block = MagicMock()
task_block.complete_on_download = False
task_block.download_timeout = None
- task_block.download_suffix = "req-123"
+ task_block.download_suffix = f"Fund_{ORIGINAL_FILENAME_MARKER}"
browser_state = MagicMock()
browser_state.get_working_page = AsyncMock(return_value=None)
+ context = SkyvernContext(task_id=task.task_id, download_suffix=task_block.download_suffix)
async def agent_step_side_effect(*args, **kwargs):
current_step = args[1]
if current_step.step_id == "step-1":
- (download_dir / "uuid-file.zip").write_text("dummy")
+ _download_target_path(download_dir, "report.pdf").write_text("dummy")
step1.status = "completed"
return step1, DetailedAgentStepOutput(
scraped_page=None,
@@ -520,8 +682,8 @@ async def test_execute_step_reuses_initial_download_baseline_across_recursive_st
with (
patch("skyvern.forge.agent.analytics.capture"),
- patch("skyvern.forge.agent.skyvern_context.ensure_context", return_value=MagicMock()),
- patch("skyvern.forge.agent.skyvern_context.current", return_value=None),
+ patch("skyvern.forge.agent.skyvern_context.ensure_context", return_value=context),
+ patch("skyvern.forge.agent.skyvern_context.current", return_value=context),
patch("skyvern.forge.agent.get_path_for_workflow_download_directory", return_value=download_dir),
patch("skyvern.forge.agent.list_downloading_files_in_directory", return_value=[]),
patch.object(
@@ -562,8 +724,8 @@ async def test_execute_step_reuses_initial_download_baseline_across_recursive_st
engine=RunEngine.skyvern_v1,
)
- assert (download_dir / "req-123.zip").exists()
- assert not (download_dir / "uuid-file.zip").exists()
+ assert (download_dir / "Fund_report.pdf").exists()
+ assert not (download_dir / "Fund_Fund_report.pdf").exists()
@pytest.mark.asyncio
diff --git a/tests/unit/test_cached_download_s3_upload.py b/tests/unit/test_cached_download_s3_upload.py
index 185ce5328..474098ec8 100644
--- a/tests/unit/test_cached_download_s3_upload.py
+++ b/tests/unit/test_cached_download_s3_upload.py
@@ -63,6 +63,7 @@ def mock_context():
ctx.browser_session_id = None
ctx.run_id = ctx.workflow_run_id
ctx.prompt = None
+ ctx.download_suffix_applied_files = {}
return ctx
@@ -103,7 +104,13 @@ def setup(mock_context, tmp_path):
new_callable=AsyncMock,
return_value=("wrb_1", "tsk_1", "stp_1"),
),
- patch(f"{MODULE}._render_template_with_label", side_effect=lambda p, _: p),
+ patch(
+ f"{MODULE}._render_template_with_label",
+ side_effect=lambda p, _, extra_template_data=None: p.replace(
+ "{{ original_filename }}",
+ extra_template_data["original_filename"] if extra_template_data else "{{ original_filename }}",
+ ),
+ ),
patch(f"{MODULE}.skyvern_context.ensure_context", return_value=mock_context),
patch(f"{MODULE}._prepare_cached_block_inputs", new_callable=AsyncMock),
patch(f"{MODULE}._run_cached_function", new=run_cached_mock),
@@ -128,6 +135,7 @@ def setup(mock_context, tmp_path):
"update_block": update_block_mock,
"rename": rename,
"run_cached": run_cached_mock,
+ "context": mock_context,
"wait_downloads": wait_downloads_mock,
"get_download_dir": get_download_dir_mock,
}
@@ -165,6 +173,35 @@ def test_render_template_with_label_injects_workflow_run_id():
assert rendered == "exports/wr_cached_run"
+def test_render_template_with_label_uses_workflow_parameter_over_extra_binding():
+ context = SimpleNamespace(workflow_run_id="wr_cached_run", script_run_parameters={}, loop_metadata=None)
+ workflow_run_context = SimpleNamespace(
+ values={"original_filename": "custom.pdf"},
+ secrets={},
+ workflow_title="Cached workflow",
+ workflow_id="wf_cached",
+ workflow_permanent_id="wpid_cached",
+ workflow_run_id="wr_cached_run",
+ browser_session_id=None,
+ )
+ mock_app = MagicMock()
+ mock_app.WORKFLOW_CONTEXT_MANAGER.get_workflow_run_context.return_value = workflow_run_context
+
+ with (
+ patch(f"{MODULE}.app", mock_app),
+ patch(f"{MODULE}.skyvern_context.current", return_value=context),
+ ):
+ from skyvern.services.script_service import _render_template_with_label
+ from skyvern.webeye.cdp_download_interceptor import ORIGINAL_FILENAME_MARKER
+
+ rendered = _render_template_with_label(
+ "ACME_{{ original_filename }}",
+ extra_template_data={"original_filename": ORIGINAL_FILENAME_MARKER},
+ )
+
+ assert rendered == "ACME_custom.pdf"
+
+
@pytest.mark.asyncio
async def test_cached_download_calls_save_downloaded_files(setup, tmp_path):
"""save_downloaded_files must be called so get_downloaded_files can find the file."""
@@ -591,6 +628,243 @@ async def test_cached_download_rename_emits_finalize_lineage(setup, tmp_path):
_cleanup(refs)
+async def test_cached_download_renders_filename_template_before_substituting_site_name(setup, tmp_path):
+ download_dir = tmp_path / "downloads"
+ abs_path = str(download_dir / "Q4 Report.pdf")
+ rename_mock = MagicMock()
+ refs = setup(
+ get_side_effect=[[], ["Q4 Report.pdf"]],
+ list_files_side_effect=[[], [abs_path], [abs_path], [abs_path]],
+ rename_mock=rename_mock,
+ )
+ try:
+ from skyvern.services.script_service import download
+
+ with patch(
+ f"{MODULE}._render_template_with_label",
+ side_effect=lambda value, _, extra_template_data=None: value.replace("{{ fund }}", "Fund A").replace(
+ "{{ original_filename }}",
+ extra_template_data["original_filename"] if extra_template_data else "{{ original_filename }}",
+ ),
+ ):
+ await download(
+ prompt="Download invoice",
+ download_suffix="{{ fund }}_{{ original_filename }}",
+ label="test_block",
+ )
+
+ rename_mock.assert_called_once_with(abs_path, "Fund%20A_Q4 Report.pdf")
+ finally:
+ _cleanup(refs)
+
+
+async def test_cached_download_applies_suffix_at_download_time_and_preserves_original_name(setup, tmp_path):
+ download_dir = tmp_path / "downloads"
+ expected_name = "Fund_Q4 Report.pdf"
+ abs_path = str(download_dir / expected_name)
+ refs = setup(
+ get_side_effect=[[], [expected_name]],
+ list_files_side_effect=[[], [abs_path], [abs_path], [abs_path]],
+ )
+ refs["context"].download_suffix = None
+ saved_targets = []
+ try:
+ from skyvern.services.script_service import download
+ from skyvern.webeye.actions.handler import _download_target_path
+
+ async def save_download(_cached_fn):
+ target = _download_target_path(download_dir, "Q4 Report.pdf")
+ saved_targets.append(target)
+ target.touch()
+
+ refs["run_cached"].side_effect = save_download
+ with patch(f"{MODULE}.skyvern_context.current", return_value=refs["context"]):
+ await download(
+ prompt="Download invoice",
+ download_suffix="Fund_{{ original_filename }}",
+ label="test_block",
+ )
+
+ assert [target.name for target in saved_targets] == [expected_name]
+ assert refs["context"].download_suffix_applied_files[expected_name][0] == "Q4 Report.pdf"
+ assert refs["context"].download_suffix is None
+ refs["rename"].assert_not_called()
+ finally:
+ _cleanup(refs)
+
+
+async def test_cached_download_rejects_transformations_on_original_filename(setup):
+ refs = setup(list_files_side_effect=[[], []])
+ try:
+ from skyvern.services.script_service import download
+
+ with pytest.raises(ValueError, match="must be used without Jinja transformations"):
+ await download(
+ prompt="Download invoice",
+ download_suffix="{{ original_filename | upper }}",
+ label="test_block",
+ )
+
+ refs["run_cached"].assert_not_awaited()
+ finally:
+ _cleanup(refs)
+
+
+async def test_cached_download_allows_filters_on_workflow_owned_original_filename(setup):
+ refs = setup(get_side_effect=[[]], list_files_side_effect=[[], []])
+ refs["app"].WORKFLOW_CONTEXT_MANAGER.get_workflow_run_context.return_value.values = {
+ "original_filename": "custom.pdf"
+ }
+ refs["run_cached"].side_effect = RuntimeError("cached function failed")
+ try:
+ from skyvern.services.script_service import download
+
+ with patch(
+ f"{MODULE}._render_template_with_label",
+ side_effect=lambda value, *_args, **_kwargs: (
+ "CUSTOM.PDF" if value == "{{ original_filename | upper }}" else value
+ ),
+ ):
+ await download(
+ prompt="Download invoice",
+ download_suffix="{{ original_filename | upper }}",
+ label="test_block",
+ )
+
+ assert refs["fallback"].await_args.kwargs["download_suffix"] == "CUSTOM.PDF"
+ finally:
+ _cleanup(refs)
+
+
+async def test_cached_download_passes_rendered_suffix_to_ai_fallback(setup):
+ refs = setup(get_side_effect=[[]], list_files_side_effect=[[], []])
+ refs["context"].download_suffix = "ambient_suffix"
+ refs["run_cached"].side_effect = RuntimeError("cached function failed")
+ try:
+ from skyvern.services.script_service import download
+ from skyvern.webeye.cdp_download_interceptor import ORIGINAL_FILENAME_MARKER
+
+ await download(
+ prompt="Download invoice",
+ download_suffix="Fund_{{ original_filename }}",
+ label="test_block",
+ )
+
+ refs["fallback"].assert_awaited_once()
+ assert refs["fallback"].await_args.kwargs["download_suffix"] == f"Fund_{ORIGINAL_FILENAME_MARKER}"
+ assert refs["context"].download_suffix == "ambient_suffix"
+ finally:
+ _cleanup(refs)
+
+
+async def test_cached_download_recovers_extension_with_dotted_prefix(setup, tmp_path):
+ download_dir = tmp_path / "downloads"
+ target_name = "Acme.L.P._export"
+ abs_path = str(download_dir / target_name)
+ rename_mock = MagicMock()
+ refs = setup(
+ get_side_effect=[[], [f"{target_name}.xlsx"]],
+ list_files_side_effect=[[], [abs_path], [abs_path], [abs_path]],
+ rename_mock=rename_mock,
+ )
+ try:
+ from skyvern.services.script_service import download
+ from skyvern.webeye.cdp_download_interceptor import ORIGINAL_FILENAME_MARKER
+
+ async def mark_cdp_target(_cached_fn):
+ refs["context"].download_suffix_applied_files[target_name] = (
+ "export",
+ f"Acme.L.P._{ORIGINAL_FILENAME_MARKER}",
+ )
+
+ refs["run_cached"].side_effect = mark_cdp_target
+ with patch(f"{MODULE}.recover_download_extension", return_value=".xlsx") as recover_extension:
+ await download(
+ prompt="Download invoice",
+ download_suffix="Acme.L.P._{{ original_filename }}",
+ label="test_block",
+ )
+
+ recover_extension.assert_called_once_with(abs_path, f"Acme.L.P._{ORIGINAL_FILENAME_MARKER}")
+ rename_mock.assert_called_once_with(abs_path, f"{target_name}.xlsx")
+ finally:
+ _cleanup(refs)
+
+
+async def test_cached_download_preserves_explicit_suffix_extension(setup, tmp_path):
+ download_dir = tmp_path / "downloads"
+ target_name = "custom.txt"
+ abs_path = str(download_dir / target_name)
+ rename_mock = MagicMock()
+ refs = setup(
+ get_side_effect=[[], [target_name]],
+ list_files_side_effect=[[], [abs_path], [abs_path], [abs_path]],
+ rename_mock=rename_mock,
+ )
+ try:
+ from skyvern.services.script_service import download
+
+ async def mark_cdp_target(_cached_fn):
+ refs["context"].download_suffix_applied_files[target_name] = ("report.pdf", target_name)
+
+ refs["run_cached"].side_effect = mark_cdp_target
+ await download(
+ prompt="Download invoice",
+ download_suffix=target_name,
+ label="test_block",
+ )
+
+ rename_mock.assert_not_called()
+ finally:
+ _cleanup(refs)
+
+
+async def test_cached_download_dedupes_recovered_extension_for_already_named_file(setup, tmp_path):
+ download_dir = tmp_path / "downloads"
+ abs_path = str(download_dir / "ACME_export")
+ existing_path = str(download_dir / "ACME_export.xlsx")
+ rename_mock = MagicMock()
+ refs = setup(
+ get_side_effect=[[], ["ACME_export.xlsx"]],
+ list_files_side_effect=[
+ [existing_path],
+ [existing_path, abs_path],
+ [existing_path, abs_path],
+ [existing_path, abs_path],
+ ],
+ rename_mock=rename_mock,
+ )
+ try:
+ from skyvern.services.script_service import download
+ from skyvern.webeye.cdp_download_interceptor import _marked_download_suffix
+
+ async def mark_cdp_target(_cached_fn):
+ refs["context"].download_suffix_applied_files["ACME_export"] = (
+ "export",
+ _marked_download_suffix("ACME_{{ original_filename }}"),
+ )
+
+ refs["run_cached"].side_effect = mark_cdp_target
+ with patch(f"{MODULE}.recover_download_extension", return_value=".xlsx"):
+ await download(
+ prompt="Download invoice",
+ download_suffix="ACME_{{ original_filename }}",
+ label="test_block",
+ )
+
+ rename_mock.assert_called_once_with(abs_path, "ACME_export_1.xlsx")
+ finally:
+ _cleanup(refs)
+
+
@pytest.mark.asyncio
async def test_verification_raises_when_no_new_file(setup):
"""When no new file appears on local filesystem, the poll loop should exhaust
diff --git a/tests/unit/test_download_suffix_lineage.py b/tests/unit/test_download_suffix_lineage.py
index e013cac09..6533e0a80 100644
--- a/tests/unit/test_download_suffix_lineage.py
+++ b/tests/unit/test_download_suffix_lineage.py
@@ -37,6 +37,7 @@ from tests.unit._fingerprint_expectations import (
from tests.unit.fake_workflow_run_context import FakeWorkflowRunContext
SUFFIX_TEMPLATE = "AllDataExport_UsageDetail_{{current_value.account_number}}"
+PREFIX_TEMPLATE = "{{current_value.account_number}}_{{ original_filename }}"
# Synthetic, obviously-fake account numbers (never real customer values).
ACCOUNTS = ["ACCT_AAA_1001", "ACCT_BBB_2002", "ACCT_CCC_3003"]
SITE_FILENAME = "detail_report.csv"
@@ -215,6 +216,36 @@ def test_render_boundary_emits_lineage_per_iteration_and_leaves_template_untouch
assert block.download_suffix == SUFFIX_TEMPLATE
+ "suffix",
+ [
+ "{{ original_filename | upper }}",
+ "{{ original_filename | replace('Q', 'R') }}",
+ "{{ original_filename.upper() }}",
+ "{{ original_filename.replace('_', '-') }}",
+ "{{ original_filename[:4] }}",
+ "{{ 'prefix_' ~ original_filename }}",
+ ],
+)
+def test_render_boundary_rejects_transformations_on_original_filename(suffix: str) -> None:
+ block = _make_download_block()
+ block.download_suffix = suffix
+
+ with pytest.raises(ValueError, match="must be used without Jinja transformations"):
+ block.format_potential_template_parameters(_loop_context(block.label, 0, ACCOUNTS[0]))
+
+
+def test_render_boundary_allows_filters_on_workflow_owned_original_filename() -> None:
+ block = _make_download_block()
+ block.download_suffix = "{{ original_filename | upper }}"
+ context = _loop_context(block.label, 0, ACCOUNTS[0])
+ context.values["original_filename"] = "custom.pdf"
+
+ block.format_potential_template_parameters(context)
+
+ assert block.download_suffix == "CUSTOM.PDF"
+
+
# --------------------------------------------------------------------------------------------------
# 4-case reproduction harness (real render/copy + real finalize + real contextvar naming)
# --------------------------------------------------------------------------------------------------
@@ -259,6 +290,44 @@ async def test_harness_case1_finalize_names_per_iteration_no_freeze(tmp_path: Pa
assert len({r["passed_download_suffix_fp"] for r in records}) == len(ACCOUNTS)
+async def test_original_filename_prefix_distinguishes_identically_named_site_files(tmp_path: Path) -> None:
+ """SKY-17905: a portal serving every document under one name, prefixed per loop iteration.
+
+ Drives the same real render + real finalize as case1, so it covers the whole chain the prefix
+ has to survive: the Jinja render, the percent-encoding after it, and the rename. Finalizing a
+ second time over the same baseline must not prefix an already-prefixed file.
+ """
+ agent = ForgeAgent()
+ block = _make_download_block()
+ block.download_suffix = PREFIX_TEMPLATE
+ download_dir = tmp_path / "downloads"
+ download_dir.mkdir()
+
+ for index, account in enumerate(ACCOUNTS):
+ ctx = _loop_context(block.label, index, account)
+ copy = block.model_copy(deep=True)
+ copy.format_potential_template_parameters(ctx)
+ before = sorted(str(p) for p in download_dir.iterdir())
+ download_context = SkyvernContext(download_suffix=copy.download_suffix)
+ with skyvern_context.scoped(download_context):
+ target = _download_target_path(download_dir, SITE_FILENAME)
+ target.write_text(f"bytes-{account}") # every account exports this name
+ with patch("skyvern.forge.agent.get_path_for_workflow_download_directory", return_value=download_dir):
+ with skyvern_context.scoped(download_context):
+ for _ in range(2): # the second pass must be a no-op, not a second prefix
+ await agent._finalize_downloaded_files_for_task(
+ _make_task(task_id=f"task-{index}"),
+ organization_id="org-harness",
+ download_suffix=copy.download_suffix,
+ list_files_before=before,
+ randomize_if_missing=False,
+ )
+
+ names = {p.name for p in download_dir.iterdir()}
+ assert names == {f"{account}_detail_report.csv" for account in ACCOUNTS}, names
+
+
@pytest.mark.asyncio
async def test_harness_case2_frozen_contextvar_reproduces_freeze_on_atsave_path(tmp_path: Path) -> None:
"""At-save naming via a contextvar that was stamped at iteration 0 and never re-stamped.
diff --git a/tests/unit/webeye/test_download_target_path.py b/tests/unit/webeye/test_download_target_path.py
index 161ba57de..5324aa173 100644
--- a/tests/unit/webeye/test_download_target_path.py
+++ b/tests/unit/webeye/test_download_target_path.py
@@ -1,11 +1,17 @@
from __future__ import annotations
from pathlib import Path
+from unittest.mock import patch
+from skyvern.forge.sdk.api.files import recover_download_extension
from skyvern.forge.sdk.core import skyvern_context
from skyvern.forge.sdk.core.skyvern_context import SkyvernContext
from skyvern.webeye.actions.handler import _download_target_path
-from skyvern.webeye.cdp_download_interceptor import download_filename_from_suffix
+from skyvern.webeye.cdp_download_interceptor import (
+ ORIGINAL_FILENAME_MARKER,
+ download_filename_from_suffix,
+ unique_download_filename,
+)
_SITE_UUID = "0faafbe5-fc0e-4cb6-9947-332fe1405073.pdf"
@@ -49,3 +55,150 @@ def test_download_target_path_dedupes_same_suffix_in_dir(tmp_path: Path) -> None
with skyvern_context.scoped(SkyvernContext(download_suffix="REQ-1")):
target = _download_target_path(tmp_path, "site-uuid.pdf")
assert target.name == "REQ-1_1.pdf"
+
+
+def test_original_filename_marker_prefixes_the_site_name() -> None:
+ assert (
+ download_filename_from_suffix(
+ f"Fund-A_{ORIGINAL_FILENAME_MARKER}", ".pdf", set(), original_filename="Q4 Report.pdf"
+ )
+ == "Fund-A_Q4 Report.pdf"
+ )
+
+
+def test_original_filename_marker_keeps_source_extension_after_dotted_prefix() -> None:
+ assert (
+ download_filename_from_suffix(
+ f"Acme Capital L.P._{ORIGINAL_FILENAME_MARKER}",
+ ".pdf",
+ set(),
+ original_filename="Q4 Report.pdf",
+ )
+ == "Acme Capital L.P._Q4 Report.pdf"
+ )
+
+
+def test_original_filename_marker_alone_keeps_the_site_name() -> None:
+ assert (
+ download_filename_from_suffix(ORIGINAL_FILENAME_MARKER, ".pdf", set(), original_filename="Q4 Report.pdf")
+ == "Q4 Report.pdf"
+ )
+
+
+def test_original_filename_marker_uses_the_source_extension_when_the_site_name_has_none() -> None:
+ assert (
+ download_filename_from_suffix(f"ACME_{ORIGINAL_FILENAME_MARKER}", ".xlsx", set(), original_filename="export")
+ == "ACME_export.xlsx"
+ )
+
+
+def test_original_filename_marker_as_suffix_does_not_lose_the_extension() -> None:
+ assert (
+ download_filename_from_suffix(
+ f"{ORIGINAL_FILENAME_MARKER}_archived", ".pdf", set(), original_filename="report.pdf"
+ )
+ == "report_archived.pdf"
+ )
+
+
+def test_original_filename_marker_sanitizes_a_traversing_site_name() -> None:
+ # The site picks this name, and a Windows-style traversal survives Path().name on POSIX.
+ assert (
+ download_filename_from_suffix(
+ f"ACME_{ORIGINAL_FILENAME_MARKER}", ".pdf", set(), original_filename="..\\..\\secret.pdf"
+ )
+ == "ACME_secret.pdf"
+ )
+
+
+def test_original_filename_marker_falls_back_when_the_site_names_nothing() -> None:
+ assert (
+ download_filename_from_suffix(ORIGINAL_FILENAME_MARKER, ".pdf", set(), original_filename=None) == "download.pdf"
+ )
+
+
+def test_original_filename_marker_bounds_a_site_name_the_filesystem_would_reject() -> None:
+ # The site controls this part of the name; a basename over ~255 bytes fails the rename outright.
+ name = download_filename_from_suffix(
+ f"ACME_{ORIGINAL_FILENAME_MARKER}", ".pdf", set(), original_filename="z" * 400 + ".pdf"
+ )
+ assert len(name.encode()) <= 255
+ assert name.startswith("ACME_z") and name.endswith(".pdf")
+
+
+def test_original_filename_marker_bounds_multibyte_stem_with_prefix_and_extension() -> None:
+ name = download_filename_from_suffix(
+ f"ACME_{ORIGINAL_FILENAME_MARKER}", ".pdf", set(), original_filename="界" * 150 + ".pdf"
+ )
+ assert len(name.encode("utf-8")) <= 255
+ assert name.startswith("ACME_界") and name.endswith(".pdf")
+
+
+def test_original_filename_marker_collisions_are_deduped() -> None:
+ assert (
+ download_filename_from_suffix(
+ f"ACME_{ORIGINAL_FILENAME_MARKER}", ".pdf", {"ACME_report.pdf"}, original_filename="report.pdf"
+ )
+ == "ACME_report_1.pdf"
+ )
+
+
+def test_original_filename_marker_dedupes_after_filename_sanitization() -> None:
+ assert (
+ download_filename_from_suffix(
+ f"ACME_{ORIGINAL_FILENAME_MARKER}", ".pdf", {"ACME_a#.pdf"}, original_filename="a.pdf"
+ )
+ == "ACME_a_1.pdf"
+ )
+
+
+def test_raw_jinja_original_filename_resolves_for_an_unrendered_suffix() -> None:
+ # Cached-script mode bakes the author's template into generated code as an unrendered literal.
+ assert (
+ download_filename_from_suffix("ACME_{{ original_filename }}", ".pdf", set(), original_filename="report.pdf")
+ == "ACME_report.pdf"
+ )
+
+
+def test_already_named_file_keeps_recovered_extension() -> None:
+ from skyvern.webeye.cdp_download_interceptor import append_download_extension_if_missing
+
+ assert append_download_extension_if_missing("ACME_export", ".xlsx") == "ACME_export.xlsx"
+ assert append_download_extension_if_missing("ACME_export.xlsx", ".xlsx") == "ACME_export.xlsx"
+ assert unique_download_filename("ACME_export", ".xlsx", set()) == "ACME_export.xlsx"
+ assert unique_download_filename("ACME_export", ".xlsx", {"ACME_export.xlsx"}) == "ACME_export_1.xlsx"
+
+
+def test_suffix_dedup_keeps_a_numeric_template_suffix() -> None:
+ suffix = f"{ORIGINAL_FILENAME_MARKER}_2024"
+ assert (
+ download_filename_from_suffix(suffix, ".pdf", {"Q4 Report_2024.pdf"}, original_filename="Q4 Report.pdf")
+ == "Q4 Report_2024_1.pdf"
+ )
+
+
+def test_recover_extension_ignores_dotted_template_prefix_before_original_filename(tmp_path: Path) -> None:
+ with patch("skyvern.forge.sdk.api.files.guess_extension_from_file", return_value=".xlsx"):
+ assert (
+ recover_download_extension(tmp_path / "extensionless", f"Acme Capital L.P._{ORIGINAL_FILENAME_MARKER}")
+ == ".xlsx"
+ )
+
+
+def test_download_target_path_prefixes_the_site_name(tmp_path: Path) -> None:
+ context = SkyvernContext(download_suffix=f"ACME_{ORIGINAL_FILENAME_MARKER}")
+ with skyvern_context.scoped(context):
+ target = _download_target_path(tmp_path, "Q4 Report.pdf")
+ assert target.name == "ACME_Q4 Report.pdf"
+ assert target.parent == tmp_path
+ assert context.download_suffix_applied_files == {target.name: ("Q4 Report.pdf", f"ACME_{ORIGINAL_FILENAME_MARKER}")}
+
+
+def test_download_target_path_does_not_infer_prior_naming_from_site_affixes(tmp_path: Path) -> None:
+ context = SkyvernContext(download_suffix=f"ACME_{ORIGINAL_FILENAME_MARKER}")
+ with skyvern_context.scoped(context):
+ target = _download_target_path(tmp_path, "ACME_report.pdf")
+ assert target.name == "ACME_ACME_report.pdf"
+ assert context.download_suffix_applied_files == {
+ target.name: ("ACME_report.pdf", f"ACME_{ORIGINAL_FILENAME_MARKER}")
+ }