Automate browser based workflows with AI
Python aiapiautomationbrowserbrowser-automationcomputergptllmplaywrightpowerautomatepuppeteerpythonrpaseleniumvisionworkflow
feat(SKY-9672): detect archived artifacts and surface archive status to frontend (#6075)
LawyZheng9eaec2a7d31e
diff --git a/skyvern-frontend/src/api/types.ts b/skyvern-frontend/src/api/types.tsindex a0c77c61f..f6cc53e76 100644--- a/skyvern-frontend/src/api/types.ts+++ b/skyvern-frontend/src/api/types.ts@@ -89,6 +89,7 @@ export type ArtifactApiResponse = {artifact_type: ArtifactType;uri: string;signed_url?: string | null;+ archived?: boolean;organization_id: string;};@@ -162,6 +163,7 @@ export type TaskApiResponse = {extracted_information: Record<string, unknown> | string | null;screenshot_url: string | null;recording_url: string | null;+ recording_archived?: boolean;failure_reason: string | null;failure_category: Array<FailureCategory> | null;webhook_failure_reason: string | null;@@ -584,6 +586,7 @@ export type WorkflowRunStatusApiResponse = {screenshot_urls: Array<string> | null;recording_url: string | null;recording_urls: Array<string> | null;+ recording_archived?: boolean;outputs: Record<string, unknown> | null;failure_reason: string | null;failure_category: Array<FailureCategory> | null;@@ -617,6 +620,7 @@ export type WorkflowRunStatusApiResponseWithWorkflow = {screenshot_urls: Array<string> | null;recording_url: string | null;recording_urls: Array<string> | null;+ recording_archived?: boolean;outputs: Record<string, unknown> | null;failure_reason: string | null;failure_category: Array<FailureCategory> | null;diff --git a/skyvern-frontend/src/routes/tasks/detail/ActionScreenshot.tsx b/skyvern-frontend/src/routes/tasks/detail/ActionScreenshot.tsxindex d50bd94bb..33ef3601a 100644--- a/skyvern-frontend/src/routes/tasks/detail/ActionScreenshot.tsx+++ b/skyvern-frontend/src/routes/tasks/detail/ActionScreenshot.tsx@@ -104,6 +104,15 @@ function ActionScreenshot({ artifactId, stepId, index, taskStatus }: Props) {);}+ if (screenshot.archived) {+ return (+ <div className="flex h-full items-center justify-center bg-slate-elevation1 text-muted-foreground">+ This screenshot has been archived. To request restoration, please+ contact [email protected]+ </div>+ );+ }+return (<figure className="mx-auto flex max-w-full flex-col items-center gap-2 overflow-hidden rounded"><ZoomableImage src={getImageURL(screenshot)} alt="llm-screenshot" />diff --git a/skyvern-frontend/src/routes/tasks/detail/Artifact.tsx b/skyvern-frontend/src/routes/tasks/detail/Artifact.tsxindex 6367d3f18..942f579e5 100644--- a/skyvern-frontend/src/routes/tasks/detail/Artifact.tsx+++ b/skyvern-frontend/src/routes/tasks/detail/Artifact.tsx@@ -53,6 +53,11 @@ type Props = {};function Artifact({ type, artifacts }: Props) {+ const total = artifacts.length;+ const archivedCount = artifacts.filter((a) => a.archived).length;+ const allArchived = total > 0 && archivedCount === total;+ const partiallyArchived = archivedCount > 0 && archivedCount < total;+function fetchArtifact(artifact: ArtifactApiResponse) {if (artifact.signed_url) {return axios.get(artifact.signed_url).then((response) => response.data);@@ -75,29 +80,48 @@ function Artifact({ type, artifacts }: Props) {return {queryKey: ["artifact", artifact.artifact_id],queryFn: () => fetchArtifact(artifact),+ enabled: !artifact.archived,};}) ?? [],});+ if (allArchived) {+ return (+ <div className="p-4 text-muted-foreground">+ This data has been archived. To request restoration, please contact+ </div>+ );+ }+if (results.some((result) => result.isLoading)) {return <Skeleton className="h-48 w-full" />;}return (- <CodeEditor- language={type === "text" ? undefined : type}- className="w-full"- value={- results.some((result) => result.isError)- ? JSON.stringify(results.find((result) => result.isError)?.error)- : results- .map((result) => getFormattedResult(type, result.data))- .join(",\n")- }- minHeight="96px"- maxHeight="500px"- readOnly- />+ <div className="flex flex-col gap-2">+ {partiallyArchived && (+ <div className="text-sm text-muted-foreground">+ {archivedCount} of {total} items archived and not shown. Contact+ [email protected] to request restoration.+ </div>+ )}+ <CodeEditor+ language={type === "text" ? undefined : type}+ className="w-full"+ value={+ results.some((result) => result.isError)+ ? JSON.stringify(results.find((result) => result.isError)?.error)+ : results+ .filter((_, i) => !artifacts[i]?.archived)+ .map((result) => getFormattedResult(type, result.data))+ .join(",\n")+ }+ minHeight="96px"+ maxHeight="500px"+ readOnly+ />+ </div>);}diff --git a/skyvern-frontend/src/routes/tasks/detail/StepArtifacts.tsx b/skyvern-frontend/src/routes/tasks/detail/StepArtifacts.tsxindex 6865d9289..e2f48a9ec 100644--- a/skyvern-frontend/src/routes/tasks/detail/StepArtifacts.tsx+++ b/skyvern-frontend/src/routes/tasks/detail/StepArtifacts.tsx@@ -21,6 +21,67 @@ import { apiPathPrefix } from "@/util/env";const enable_log_artifacts =import.meta.env.VITE_ENABLE_LOG_ARTIFACTS === "true";+type ScreenshotsTabContentProps = {+ screenshots: Array<ArtifactApiResponse> | undefined;+ isFetching: boolean;+ gridCols: string;+ skeletonCount: number;+};++function ScreenshotsTabContent({+ screenshots,+ isFetching,+ gridCols,+ skeletonCount,+}: ScreenshotsTabContentProps) {+ if (!screenshots || screenshots.length === 0) {+ if (isFetching) {+ return (+ <div className={`grid ${gridCols} gap-4 p-4`}>+ {Array.from({ length: skeletonCount }).map((_, i) => (+ <Skeleton key={i} className="h-full w-full" />+ ))}+ </div>+ );+ }+ return <div>No screenshots found</div>;+ }++ const total = screenshots.length;+ const archivedCount = screenshots.filter((a) => a.archived).length;+ const visible = screenshots.filter((a) => !a.archived);++ if (archivedCount === total) {+ return (+ <div className="p-4 text-muted-foreground">+ These screenshots have been archived. To request restoration, please+ contact [email protected]+ </div>+ );+ }++ return (+ <div className="flex flex-col gap-2 p-4">+ {archivedCount > 0 && (+ <div className="text-sm text-muted-foreground">+ {archivedCount} of {total} screenshots archived and not shown. Contact+ [email protected] to request restoration.+ </div>+ )}+ <div className={`grid ${gridCols} gap-4`}>+ {visible.map((artifact, index) => (+ <ZoomableImage+ key={index}+ src={getImageURL(artifact)}+ className="h-full w-full object-cover"+ alt="action-screenshot"+ />+ ))}+ </div>+ </div>+ );+}+type Props = {id: string;stepProps: StepApiResponse;@@ -152,48 +213,20 @@ function StepArtifacts({ id, stepProps }: Props) {</div></TabsContent><TabsContent value="screenshot_llm">- {llmScreenshots && llmScreenshots.length > 0 ? (- <div className="grid grid-cols-2 gap-4 p-4">- {llmScreenshots.map((artifact, index) => (- <ZoomableImage- key={index}- src={getImageURL(artifact)}- className="h-full w-full object-cover"- alt="action-screenshot"- />- ))}- </div>- ) : isFetching ? (- <div className="grid grid-cols-2 gap-4 p-4">- <Skeleton className="h-full w-full" />- <Skeleton className="h-full w-full" />- <Skeleton className="h-full w-full" />- </div>- ) : (- <div>No screenshots found</div>- )}+ <ScreenshotsTabContent+ screenshots={llmScreenshots}+ isFetching={isFetching}+ gridCols="grid-cols-2"+ skeletonCount={3}+ /></TabsContent><TabsContent value="screenshot_action">- {actionScreenshots && actionScreenshots.length > 0 ? (- <div className="grid grid-cols-2 gap-4 p-4">- {actionScreenshots.map((artifact, index) => (- <ZoomableImage- key={index}- src={getImageURL(artifact)}- className="h-full w-full object-cover"- alt="action-screenshot"- />- ))}- </div>- ) : isFetching ? (- <div className="grid grid-cols-3 gap-4 p-4">- <Skeleton className="h-full w-full" />- <Skeleton className="h-full w-full" />- <Skeleton className="h-full w-full" />- </div>- ) : (- <div>No screenshots found</div>- )}+ <ScreenshotsTabContent+ screenshots={actionScreenshots}+ isFetching={isFetching}+ gridCols="grid-cols-3"+ skeletonCount={3}+ /></TabsContent><TabsContent value="element_tree_trimmed">{visibleElementsTreeInPrompt ? (diff --git a/skyvern-frontend/src/routes/tasks/detail/TaskRecording.tsx b/skyvern-frontend/src/routes/tasks/detail/TaskRecording.tsxindex fd0240cb8..e69d0e3e5 100644--- a/skyvern-frontend/src/routes/tasks/detail/TaskRecording.tsx+++ b/skyvern-frontend/src/routes/tasks/detail/TaskRecording.tsx@@ -11,17 +11,20 @@ function TaskRecording() {const credentialGetter = useCredentialGetter();const {- data: recordingURL,+ data: recordingData,isLoading: taskIsLoading,isError: taskIsError,- } = useQuery<string | null>({+ } = useQuery<{ url: string | null; archived: boolean }>({queryKey: ["task", taskId, "recordingURL"],queryFn: async () => {const client = await getClient(credentialGetter);const task: TaskApiResponse = await client.get(`/tasks/${taskId}`).then((response) => response.data);- return getRecordingURL(task);+ return {+ url: getRecordingURL(task),+ archived: task.recording_archived ?? false,+ };},refetchOnMount: true,});@@ -38,11 +41,21 @@ function TaskRecording() {return <div>Error loading recording</div>;}- return recordingURL ? (- <video width={800} height={450} src={recordingURL} controls />- ) : (- <div>No recording available for this task</div>- );+ if (recordingData?.url) {+ return <video width={800} height={450} src={recordingData.url} controls />;+ }++ if (recordingData?.archived) {+ return (+ <div className="text-muted-foreground">+ This recording has been archived. To request restoration, please contact+ {/* TODO: add a "Request Restore" button */}+ </div>+ );+ }++ return <div>No recording available for this task</div>;}export { TaskRecording };diff --git a/skyvern-frontend/src/routes/workflows/workflowRun/WorkflowRunRecording.tsx b/skyvern-frontend/src/routes/workflows/workflowRun/WorkflowRunRecording.tsxindex ad8ba6be6..d6955906c 100644--- a/skyvern-frontend/src/routes/workflows/workflowRun/WorkflowRunRecording.tsx+++ b/skyvern-frontend/src/routes/workflows/workflowRun/WorkflowRunRecording.tsx@@ -22,6 +22,15 @@ function WorkflowRunRecording() {const recordingUrls = rawUrls.map(resolveUrl);if (!workflowRun || recordingUrls.length === 0) {+ if (workflowRun?.recording_archived) {+ return (+ <div className="text-muted-foreground">+ This recording has been archived. To request restoration, please+ contact [email protected]+ {/* TODO: add a "Request Restore" button */}+ </div>+ );+ }return <div>No recording available for this workflow</div>;}diff --git a/skyvern/forge/agent.py b/skyvern/forge/agent.pyindex 38c9434e6..1fdd34426 100644--- a/skyvern/forge/agent.py+++ b/skyvern/forge/agent.py@@ -4270,6 +4270,7 @@ class ForgeAgent:screenshot_url = Nonerecording_url = None+ recording_archived = Falsebrowser_console_log_url: str | None = Nonelatest_action_screenshot_urls: list[str] | None = Nonedownloaded_files: list[FileInfo] | None = None@@ -4286,6 +4287,7 @@ class ForgeAgent:# Get recording url from browser session first,# if not found, get the recording url from the first step+ recording_artifact = Noneif task.browser_session_id:try:async with asyncio.timeout(GET_DOWNLOADED_FILES_TIMEOUT):@@ -4310,7 +4312,9 @@ class ForgeAgent:organization_id=task.organization_id,)if recording_artifact:- recording_url = await app.ARTIFACT_MANAGER.get_share_link(recording_artifact)+ recording_archived = await app.ARTIFACT_MANAGER.is_recording_archived(recording_artifact)+ if not recording_archived:+ recording_url = await app.ARTIFACT_MANAGER.get_share_link(recording_artifact)# get the artifact of the last TASK_RESPONSE_ACTION_SCREENSHOT_COUNT screenshots and get the screenshot_urllatest_action_screenshot_artifacts = await app.DATABASE.artifacts.get_latest_n_artifacts(@@ -4368,6 +4372,7 @@ class ForgeAgent:action_screenshot_urls=latest_action_screenshot_urls,screenshot_url=screenshot_url,recording_url=recording_url,+ recording_archived=recording_archived,browser_console_log_url=browser_console_log_url,downloaded_files=downloaded_files,failure_reason=failure_reason,diff --git a/skyvern/forge/sdk/artifact/manager.py b/skyvern/forge/sdk/artifact/manager.pyindex b295b37f2..219b555db 100644--- a/skyvern/forge/sdk/artifact/manager.py+++ b/skyvern/forge/sdk/artifact/manager.py@@ -5,7 +5,7 @@ import timeimport zipfilefrom collections import defaultdictfrom dataclasses import dataclass, field-from datetime import UTC, datetime+from datetime import UTC, datetime, timedeltafrom urllib.parse import urlencodeimport structlog@@ -29,6 +29,13 @@ from skyvern.forge.sdk.schemas.workflow_runs import WorkflowRunBlockLOG = structlog.get_logger(__name__)+ARCHIVE_AGE_THRESHOLD = timedelta(days=90)+++def _ensure_aware_utc(value: datetime) -> datetime:+ return value if value.tzinfo is not None else value.replace(tzinfo=UTC)++_SCREENSHOT_PREFIX_MAP: dict[ArtifactType, str] = {ArtifactType.SCREENSHOT_LLM: "screenshot_llm",ArtifactType.SCREENSHOT_ACTION: "screenshot_action",@@ -1146,6 +1153,44 @@ class ArtifactManager:return result+ async def mark_archived_artifacts(self, artifacts: list[Artifact]) -> None:+ """Set ``archived = True`` on artifacts whose S3 objects are in GLACIER or DEEP_ARCHIVE.++ Skips artifacts newer than ARCHIVE_AGE_THRESHOLD (90 days) to avoid unnecessary+ head_object calls. Deduplicates by URI so bundle members sharing the same ZIP+ only trigger one check.+ """+ now = datetime.now(UTC)+ candidates: list[Artifact] = [+ a for a in artifacts if (now - _ensure_aware_utc(a.created_at)) > ARCHIVE_AGE_THRESHOLD+ ]+ if not candidates:+ return++ unique_uris = list({a.uri for a in candidates})+ try:+ archived_map = await app.STORAGE.check_archived_uris(unique_uris)+ except Exception:+ LOG.warning("check_archived_uris failed; skipping archived marking", exc_info=True)+ return++ for artifact in candidates:+ if archived_map.get(artifact.uri, False):+ artifact.archived = True++ async def is_recording_archived(self, artifact: Artifact | None) -> bool:+ if artifact is None:+ return False+ now = datetime.now(UTC)+ if (now - _ensure_aware_utc(artifact.created_at)) <= ARCHIVE_AGE_THRESHOLD:+ return False+ try:+ archived_map = await app.STORAGE.check_archived_uris([artifact.uri])+ except Exception:+ LOG.warning("is_recording_archived failed; assuming not archived", exc_info=True)+ return False+ return archived_map.get(artifact.uri, False)+# ---------------------------------------------------------------------------# Step-archive accumulation helpers# ---------------------------------------------------------------------------diff --git a/skyvern/forge/sdk/artifact/models.py b/skyvern/forge/sdk/artifact/models.pyindex d594084ae..1f6327cfb 100644--- a/skyvern/forge/sdk/artifact/models.py+++ b/skyvern/forge/sdk/artifact/models.py@@ -97,6 +97,7 @@ class Artifact(BaseModel):observer_thought_id: str | None = Noneai_suggestion_id: str | None = Nonesigned_url: str | None = None+ archived: bool = Falseorganization_id: strdef __getitem__(self, key: str) -> Any:diff --git a/skyvern/forge/sdk/artifact/storage/base.py b/skyvern/forge/sdk/artifact/storage/base.pyindex 8ef68115b..4dd7a8620 100644--- a/skyvern/forge/sdk/artifact/storage/base.py+++ b/skyvern/forge/sdk/artifact/storage/base.py@@ -152,6 +152,14 @@ class BaseStorage(ABC):async def retrieve_artifact(self, artifact: Artifact) -> bytes | None:pass+ async def check_archived_uris(self, uris: list[str]) -> dict[str, bool]:+ """Check whether each URI points to an archived (non-retrievable) S3 object.++ Returns a mapping of URI -> True if the object is in GLACIER or DEEP_ARCHIVE.+ Default implementation returns False for all URIs (local/Azure storage is never archived).+ """+ return {uri: False for uri in uris}+@abstractmethodasync def get_share_link(self, artifact: Artifact) -> str | None:passdiff --git a/skyvern/forge/sdk/artifact/storage/s3.py b/skyvern/forge/sdk/artifact/storage/s3.pyindex 8c63e8b1f..876ef61f9 100644--- a/skyvern/forge/sdk/artifact/storage/s3.py+++ b/skyvern/forge/sdk/artifact/storage/s3.py@@ -9,6 +9,7 @@ from typing import BinaryIOimport structlogimport zstandard as zstd+from botocore.exceptions import ClientErrorfrom skyvern.config import settingsfrom skyvern.constants import BROWSER_DOWNLOADING_SUFFIX, DOWNLOAD_FILE_PREFIX@@ -182,6 +183,27 @@ class S3Storage(BaseStorage):return Nonereturn data+ async def check_archived_uris(self, uris: list[str]) -> dict[str, bool]:+ if not uris:+ return {}++ async def _check(uri: str) -> tuple[str, bool]:+ async with self._head_object_semaphore:+ try:+ info = await self.async_client.get_object_info(uri)+ except ClientError as exc:+ LOG.warning(+ "head_object failed; assuming not archived",+ uri=uri,+ error_code=exc.response.get("Error", {}).get("Code"),+ )+ return uri, False+ sc = info.get("StorageClass", S3StorageClass.STANDARD)+ return uri, sc in (S3StorageClass.GLACIER, S3StorageClass.DEEP_ARCHIVE)++ pairs = await asyncio.gather(*[_check(uri) for uri in uris])+ return dict(pairs)+async def get_share_link(self, artifact: Artifact) -> str | None:share_urls = await self.async_client.create_presigned_urls([artifact.uri])return share_urls[0] if share_urls else Nonediff --git a/skyvern/forge/sdk/routes/agent_protocol.py b/skyvern/forge/sdk/routes/agent_protocol.pyindex 350d9ba64..fd9b2c8bc 100644--- a/skyvern/forge/sdk/routes/agent_protocol.py+++ b/skyvern/forge/sdk/routes/agent_protocol.py@@ -1495,6 +1495,7 @@ async def get_artifact()signed_url = await app.ARTIFACT_MANAGER.get_share_link(artifact)artifact.signed_url = signed_url+ await app.ARTIFACT_MANAGER.mark_archived_artifacts([artifact])return artifact@@ -1805,6 +1806,7 @@ async def get_run_artifacts(signed_urls = await app.ARTIFACT_MANAGER.get_share_links_with_bundle_support(artifacts_list)for i, artifact in enumerate(artifacts_list):artifact.signed_url = signed_urls[i]+ await app.ARTIFACT_MANAGER.mark_archived_artifacts(artifacts_list)return ORJSONResponse([artifact.model_dump() for artifact in artifacts_list])@@ -2529,6 +2531,7 @@ async def get_artifacts(signed_urls = await app.ARTIFACT_MANAGER.get_share_links_with_bundle_support(artifacts)for i, artifact in enumerate(artifacts):artifact.signed_url = signed_urls[i]+ await app.ARTIFACT_MANAGER.mark_archived_artifacts(artifacts)return ORJSONResponse([artifact.model_dump() for artifact in artifacts])@@ -2566,6 +2569,7 @@ async def get_step_artifacts(signed_urls = await app.ARTIFACT_MANAGER.get_share_links_with_bundle_support(artifacts)for i, artifact in enumerate(artifacts):artifact.signed_url = signed_urls[i]+ await app.ARTIFACT_MANAGER.mark_archived_artifacts(artifacts)return ORJSONResponse([artifact.model_dump() for artifact in artifacts])diff --git a/skyvern/forge/sdk/schemas/tasks.py b/skyvern/forge/sdk/schemas/tasks.pyindex 3e7d62dbe..80b71635d 100644--- a/skyvern/forge/sdk/schemas/tasks.py+++ b/skyvern/forge/sdk/schemas/tasks.py@@ -346,6 +346,7 @@ class Task(TaskBase):action_screenshot_urls: list[str] | None = None,screenshot_url: str | None = None,recording_url: str | None = None,+ recording_archived: bool = False,browser_console_log_url: str | None = None,downloaded_files: list[FileInfo] | None = None,failure_reason: str | None = None,@@ -367,6 +368,7 @@ class Task(TaskBase):action_screenshot_urls=action_screenshot_urls,screenshot_url=screenshot_url,recording_url=recording_url,+ recording_archived=recording_archived,browser_console_log_url=browser_console_log_url,downloaded_files=downloaded_files,downloaded_file_urls=[file.url for file in downloaded_files] if downloaded_files else None,@@ -389,6 +391,7 @@ class TaskResponse(BaseModel):action_screenshot_urls: list[str] | None = Nonescreenshot_url: str | None = Nonerecording_url: str | None = None+ recording_archived: bool = Falsebrowser_console_log_url: str | None = Nonedownloaded_files: list[FileInfo] | None = Nonedownloaded_file_urls: list[str] | None = Nonediff --git a/skyvern/forge/sdk/workflow/models/workflow.py b/skyvern/forge/sdk/workflow/models/workflow.pyindex 51099cfae..a01587d63 100644--- a/skyvern/forge/sdk/workflow/models/workflow.py+++ b/skyvern/forge/sdk/workflow/models/workflow.py@@ -302,6 +302,7 @@ class WorkflowRunResponseBase(BaseModel):screenshot_urls: list[str] | None = Nonerecording_url: str | None = Nonerecording_urls: list[str] | None = None+ recording_archived: bool = Falsedownloaded_files: list[FileInfo] | None = Nonedownloaded_file_urls: list[str] | None = Noneoutputs: dict[str, Any] | None = Nonediff --git a/skyvern/forge/sdk/workflow/service.py b/skyvern/forge/sdk/workflow/service.pyindex 0e4eeb822..4ca45b48b 100644--- a/skyvern/forge/sdk/workflow/service.py+++ b/skyvern/forge/sdk/workflow/service.py@@ -5018,9 +5018,13 @@ class WorkflowService:workflow_run: WorkflowRun,task_v2: Any | None,organization_id: str | None,- ) -> list[str]:- """Fetch recording URLs, preferring browser-session recordings with artifact-store fallback."""+ ) -> tuple[list[str], bool]:+ """Fetch recording URLs, preferring browser-session recordings with artifact-store fallback.++ Returns (recording_urls, recording_archived).+ """recording_urls: list[str] = []+ recording_archived = Falseif workflow_run.browser_session_id:if workflow_run.started_at is None:LOG.warning(@@ -5049,10 +5053,12 @@ class WorkflowService:organization_id=workflow_run.organization_id,)if recording_artifacts:- urls = await app.ARTIFACT_MANAGER.get_share_links_with_bundle_support(recording_artifacts)- recording_urls = [u for u in urls if u is not None]+ recording_archived = await app.ARTIFACT_MANAGER.is_recording_archived(recording_artifacts[0])+ if not recording_archived:+ urls = await app.ARTIFACT_MANAGER.get_share_links_with_bundle_support(recording_artifacts)+ recording_urls = [u for u in urls if u is not None]- return recording_urls+ return recording_urls, recording_archivedasync def _fetch_downloaded_files(self,@@ -5140,7 +5146,7 @@ class WorkflowService:(screenshot_urls_raw,output_parameter_tuples,- recording_urls,+ (recording_urls, recording_archived),(downloaded_files, downloaded_file_urls),) = await asyncio.gather(self.get_recent_workflow_screenshot_urls(@@ -5238,6 +5244,7 @@ class WorkflowService:screenshot_urls=screenshot_urls,recording_url=recording_url,recording_urls=recording_urls or None, # omit field when empty+ recording_archived=recording_archived,downloaded_files=downloaded_files,downloaded_file_urls=downloaded_file_urls,outputs=outputs,diff --git a/skyvern/schemas/runs.py b/skyvern/schemas/runs.pyindex 714f1d8db..54860de83 100644--- a/skyvern/schemas/runs.py+++ b/skyvern/schemas/runs.py@@ -332,6 +332,10 @@ class BaseRunResponse(BaseModel):)downloaded_files: list[FileInfo] | None = Field(default=None, description="List of files downloaded during the run")recording_url: str | None = Field(default=None, description="URL to the recording of the run")+ recording_archived: bool = Field(+ default=False,+ description="True when the recording exists but has been archived to cold storage and is not currently accessible.",+ )screenshot_urls: list[str] | None = Field(default=None,description="List of last n screenshot URLs in reverse chronological order - the first one the list is the latest screenshot.",diff --git a/skyvern/services/run_service.py b/skyvern/services/run_service.pyindex 0dde3e122..c732ca4b3 100644--- a/skyvern/services/run_service.py+++ b/skyvern/services/run_service.py@@ -55,6 +55,7 @@ async def get_run_response(run_id: str, organization_id: str | None = None) -> Rmodified_at=task_v1_response.modified_at,app_url=f"{settings.SKYVERN_APP_URL.rstrip('/')}/tasks/{task_v1_response.task_id}",recording_url=task_v1_response.recording_url,+ recording_archived=task_v1_response.recording_archived,screenshot_urls=task_v1_response.action_screenshot_urls,downloaded_files=task_v1_response.downloaded_files,run_request=TaskRunRequest(diff --git a/skyvern/services/task_v2_service.py b/skyvern/services/task_v2_service.pyindex 74f65d8ae..4fe2124fa 100644--- a/skyvern/services/task_v2_service.py+++ b/skyvern/services/task_v2_service.py@@ -2036,6 +2036,7 @@ async def build_task_v2_run_response(task_v2: TaskV2) -> TaskRunResponse:created_at=task_v2.created_at,modified_at=task_v2.modified_at,recording_url=workflow_run_resp.recording_url if workflow_run_resp else None,+ recording_archived=workflow_run_resp.recording_archived if workflow_run_resp else False,screenshot_urls=workflow_run_resp.screenshot_urls if workflow_run_resp else None,downloaded_files=workflow_run_resp.downloaded_files if workflow_run_resp else None,app_url=app_url,diff --git a/skyvern/services/webhook_service.py b/skyvern/services/webhook_service.pyindex 14cc16ae7..cc51fb68b 100644--- a/skyvern/services/webhook_service.py+++ b/skyvern/services/webhook_service.py@@ -424,6 +424,7 @@ async def _build_workflow_payload(output=status_response.outputs,downloaded_files=status_response.downloaded_files,recording_url=status_response.recording_url,+ recording_archived=status_response.recording_archived,screenshot_urls=status_response.screenshot_urls,failure_reason=status_response.failure_reason,app_url=app_url,diff --git a/skyvern/services/workflow_service.py b/skyvern/services/workflow_service.pyindex 58ca6d0b6..6d808c1d8 100644--- a/skyvern/services/workflow_service.py+++ b/skyvern/services/workflow_service.py@@ -142,6 +142,7 @@ async def get_workflow_run_response(output=workflow_run_resp.outputs,downloaded_files=workflow_run_resp.downloaded_files,recording_url=workflow_run_resp.recording_url,+ recording_archived=workflow_run_resp.recording_archived,screenshot_urls=workflow_run_resp.screenshot_urls,failure_reason=workflow_run_resp.failure_reason,queued_at=workflow_run.queued_at,diff --git a/tests/unit/test_artifact_archive_detection.py b/tests/unit/test_artifact_archive_detection.pynew file mode 100644index 000000000..ee823a46c--- /dev/null+++ b/tests/unit/test_artifact_archive_detection.py@@ -0,0 +1,291 @@+"""Tests for artifact archive detection (SKY-9672).++Artifacts older than 90 days in S3 DEEP_ARCHIVE or GLACIER should be marked+as ``archived = True`` so the frontend can display an appropriate message+instead of a generic "unavailable" state.+"""++from __future__ import annotations++import asyncio+from datetime import UTC, datetime, timedelta+from unittest.mock import AsyncMock, patch++import pytest+from botocore.exceptions import ClientError++from skyvern.forge.sdk.artifact.manager import ARCHIVE_AGE_THRESHOLD, ArtifactManager+from skyvern.forge.sdk.artifact.models import Artifact, ArtifactType+from skyvern.forge.sdk.artifact.storage.s3 import S3Storage+++def _make_s3_storage() -> S3Storage:+ storage = S3Storage.__new__(S3Storage)+ storage.async_client = AsyncMock()+ storage._head_object_semaphore = asyncio.Semaphore(8)+ return storage+++def _make_artifact(+ artifact_id: str = "art_1",+ uri: str = "s3://skyvern-artifacts/production/org/recording.webm",+ created_at: datetime | None = None,+ artifact_type: ArtifactType = ArtifactType.RECORDING,+ bundle_key: str | None = None,+) -> Artifact:+ now = datetime.now(UTC)+ return Artifact(+ artifact_id=artifact_id,+ artifact_type=artifact_type,+ uri=uri,+ bundle_key=bundle_key,+ organization_id="o_test",+ created_at=created_at or now,+ modified_at=created_at or now,+ )+++# ---------------------------------------------------------------------------+# S3Storage.check_archived_uris+# ---------------------------------------------------------------------------+++class TestCheckArchivedUris:+ @pytest.mark.asyncio+ async def test_deep_archive_detected(self) -> None:+ storage = _make_s3_storage()+ storage.async_client.get_object_info = AsyncMock(return_value={"StorageClass": "DEEP_ARCHIVE"})++ result = await storage.check_archived_uris(["s3://bucket/key"])+ assert result == {"s3://bucket/key": True}++ @pytest.mark.asyncio+ async def test_glacier_detected(self) -> None:+ storage = _make_s3_storage()+ storage.async_client.get_object_info = AsyncMock(return_value={"StorageClass": "GLACIER"})++ result = await storage.check_archived_uris(["s3://bucket/key"])+ assert result == {"s3://bucket/key": True}++ @pytest.mark.asyncio+ async def test_glacier_ir_not_archived(self) -> None:+ storage = _make_s3_storage()+ storage.async_client.get_object_info = AsyncMock(return_value={"StorageClass": "GLACIER_IR"})++ result = await storage.check_archived_uris(["s3://bucket/key"])+ assert result == {"s3://bucket/key": False}++ @pytest.mark.asyncio+ async def test_standard_not_archived(self) -> None:+ storage = _make_s3_storage()+ storage.async_client.get_object_info = AsyncMock(return_value={"StorageClass": "STANDARD"})++ result = await storage.check_archived_uris(["s3://bucket/key"])+ assert result == {"s3://bucket/key": False}++ @pytest.mark.asyncio+ async def test_missing_storage_class_defaults_to_standard(self) -> None:+ storage = _make_s3_storage()+ storage.async_client.get_object_info = AsyncMock(return_value={})++ result = await storage.check_archived_uris(["s3://bucket/key"])+ assert result == {"s3://bucket/key": False}++ @pytest.mark.asyncio+ async def test_head_object_client_error_defaults_to_not_archived(self) -> None:+ storage = _make_s3_storage()+ storage.async_client.get_object_info = AsyncMock(+ side_effect=ClientError({"Error": {"Code": "NoSuchKey", "Message": "missing"}}, "HeadObject")+ )++ result = await storage.check_archived_uris(["s3://bucket/key"])+ assert result == {"s3://bucket/key": False}++ @pytest.mark.asyncio+ async def test_unexpected_error_propagates(self) -> None:+ storage = _make_s3_storage()+ storage.async_client.get_object_info = AsyncMock(side_effect=RuntimeError("boom"))++ with pytest.raises(RuntimeError):+ await storage.check_archived_uris(["s3://bucket/key"])++ @pytest.mark.asyncio+ async def test_multiple_uris(self) -> None:+ storage = _make_s3_storage()++ async def _head(uri: str) -> dict:+ if "old" in uri:+ return {"StorageClass": "DEEP_ARCHIVE"}+ return {"StorageClass": "STANDARD"}++ storage.async_client.get_object_info = AsyncMock(side_effect=_head)++ result = await storage.check_archived_uris(["s3://bucket/old.webm", "s3://bucket/new.webm"])+ assert result == {"s3://bucket/old.webm": True, "s3://bucket/new.webm": False}++ @pytest.mark.asyncio+ async def test_empty_input_short_circuits(self) -> None:+ storage = _make_s3_storage()+ result = await storage.check_archived_uris([])+ assert result == {}+ storage.async_client.get_object_info.assert_not_called()+++# ---------------------------------------------------------------------------+# ArtifactManager.mark_archived_artifacts+# ---------------------------------------------------------------------------+++class TestMarkArchivedArtifacts:+ @pytest.mark.asyncio+ async def test_recent_artifacts_skipped(self) -> None:+ """Artifacts younger than ARCHIVE_AGE_THRESHOLD should not trigger head_object."""+ recent = _make_artifact(created_at=datetime.now(UTC) - timedelta(days=30))+ mock_storage = AsyncMock()+ mock_storage.check_archived_uris = AsyncMock(return_value={})++ manager = ArtifactManager.__new__(ArtifactManager)+ with patch("skyvern.forge.sdk.artifact.manager.app") as mock_app:+ mock_app.STORAGE = mock_storage+ await manager.mark_archived_artifacts([recent])++ mock_storage.check_archived_uris.assert_not_called()+ assert recent.archived is False++ @pytest.mark.asyncio+ async def test_old_archived_artifact_marked(self) -> None:+ old = _make_artifact(created_at=datetime.now(UTC) - timedelta(days=100))+ mock_storage = AsyncMock()+ mock_storage.check_archived_uris = AsyncMock(return_value={old.uri: True})++ manager = ArtifactManager.__new__(ArtifactManager)+ with patch("skyvern.forge.sdk.artifact.manager.app") as mock_app:+ mock_app.STORAGE = mock_storage+ await manager.mark_archived_artifacts([old])++ assert old.archived is True++ @pytest.mark.asyncio+ async def test_old_non_archived_artifact_not_marked(self) -> None:+ old = _make_artifact(created_at=datetime.now(UTC) - timedelta(days=100))+ mock_storage = AsyncMock()+ mock_storage.check_archived_uris = AsyncMock(return_value={old.uri: False})++ manager = ArtifactManager.__new__(ArtifactManager)+ with patch("skyvern.forge.sdk.artifact.manager.app") as mock_app:+ mock_app.STORAGE = mock_storage+ await manager.mark_archived_artifacts([old])++ assert old.archived is False++ @pytest.mark.asyncio+ async def test_uri_dedup_for_bundle_members(self) -> None:+ """Bundle members sharing the same URI should only trigger one head_object."""+ shared_uri = "s3://bucket/archive.zip"+ old_date = datetime.now(UTC) - timedelta(days=100)+ a1 = _make_artifact(artifact_id="a1", uri=shared_uri, created_at=old_date, bundle_key="file1.json")+ a2 = _make_artifact(artifact_id="a2", uri=shared_uri, created_at=old_date, bundle_key="file2.json")++ mock_storage = AsyncMock()+ mock_storage.check_archived_uris = AsyncMock(return_value={shared_uri: True})++ manager = ArtifactManager.__new__(ArtifactManager)+ with patch("skyvern.forge.sdk.artifact.manager.app") as mock_app:+ mock_app.STORAGE = mock_storage+ await manager.mark_archived_artifacts([a1, a2])++ # Only called once with one unique URI+ mock_storage.check_archived_uris.assert_called_once_with([shared_uri])+ assert a1.archived is True+ assert a2.archived is True++ @pytest.mark.asyncio+ async def test_mixed_recent_and_old(self) -> None:+ recent = _make_artifact(artifact_id="recent", created_at=datetime.now(UTC) - timedelta(days=10))+ old = _make_artifact(artifact_id="old", created_at=datetime.now(UTC) - timedelta(days=100))++ mock_storage = AsyncMock()+ mock_storage.check_archived_uris = AsyncMock(return_value={old.uri: True})++ manager = ArtifactManager.__new__(ArtifactManager)+ with patch("skyvern.forge.sdk.artifact.manager.app") as mock_app:+ mock_app.STORAGE = mock_storage+ await manager.mark_archived_artifacts([recent, old])++ assert recent.archived is False+ assert old.archived is True++ @pytest.mark.asyncio+ async def test_empty_list(self) -> None:+ manager = ArtifactManager.__new__(ArtifactManager)+ await manager.mark_archived_artifacts([])++ @pytest.mark.asyncio+ async def test_naive_db_timestamps_normalized(self) -> None:+ naive_old = datetime.utcnow() - timedelta(days=100)+ old = _make_artifact(created_at=naive_old)+ mock_storage = AsyncMock()+ mock_storage.check_archived_uris = AsyncMock(return_value={old.uri: True})++ manager = ArtifactManager.__new__(ArtifactManager)+ with patch("skyvern.forge.sdk.artifact.manager.app") as mock_app:+ mock_app.STORAGE = mock_storage+ await manager.mark_archived_artifacts([old])++ assert old.archived is True+++# ---------------------------------------------------------------------------+# ArtifactManager.is_recording_archived+# ---------------------------------------------------------------------------+++class TestIsRecordingArchived:+ @pytest.mark.asyncio+ async def test_none_artifact_returns_false(self) -> None:+ manager = ArtifactManager.__new__(ArtifactManager)+ result = await manager.is_recording_archived(None)+ assert result is False++ @pytest.mark.asyncio+ async def test_recent_recording_returns_false(self) -> None:+ recent = _make_artifact(created_at=datetime.now(UTC) - timedelta(days=30))+ manager = ArtifactManager.__new__(ArtifactManager)+ result = await manager.is_recording_archived(recent)+ assert result is False++ @pytest.mark.asyncio+ async def test_old_archived_recording_returns_true(self) -> None:+ old = _make_artifact(created_at=datetime.now(UTC) - timedelta(days=100))+ mock_storage = AsyncMock()+ mock_storage.check_archived_uris = AsyncMock(return_value={old.uri: True})++ manager = ArtifactManager.__new__(ArtifactManager)+ with patch("skyvern.forge.sdk.artifact.manager.app") as mock_app:+ mock_app.STORAGE = mock_storage+ result = await manager.is_recording_archived(old)++ assert result is True++ @pytest.mark.asyncio+ async def test_naive_datetime_age_screen(self) -> None:+ naive_old = datetime.utcnow() - timedelta(days=100)+ old = _make_artifact(created_at=naive_old)+ mock_storage = AsyncMock()+ mock_storage.check_archived_uris = AsyncMock(return_value={old.uri: True})++ manager = ArtifactManager.__new__(ArtifactManager)+ with patch("skyvern.forge.sdk.artifact.manager.app") as mock_app:+ mock_app.STORAGE = mock_storage+ result = await manager.is_recording_archived(old)++ assert result is True+++# ---------------------------------------------------------------------------+# ARCHIVE_AGE_THRESHOLD constant+# ---------------------------------------------------------------------------+++def test_archive_age_threshold_is_90_days() -> None:+ assert ARCHIVE_AGE_THRESHOLD == timedelta(days=90)