Automate browser based workflows with AI
Python aiapiautomationbrowserbrowser-automationcomputergptllmplaywrightpowerautomatepuppeteerpythonrpaseleniumvisionworkflow
Refresh static artifact URLs on demand: screenshots, viewers, download links (#7484)
Aaron Pereza551a5236f81
diff --git a/skyvern-frontend/src/api/artifactUrls.test.ts b/skyvern-frontend/src/api/artifactUrls.test.tsindex 2cee65694..5f8e0fd56 100644--- a/skyvern-frontend/src/api/artifactUrls.test.ts+++ b/skyvern-frontend/src/api/artifactUrls.test.ts@@ -1,11 +1,30 @@-import { describe, expect, test } from "vitest";+import { describe, expect, test, vi } from "vitest";import {artifactIdFromContentUrl,expiryFromSignedUrl,+ freshArtifactUrl,+ getWithMintRetry,refreshDelayMs,} from "./artifactUrls";+const { axiosGetMock, clientGetMock, getClientMock } = vi.hoisted(() => {+ const clientGetMock = vi.fn();+ return {+ axiosGetMock: vi.fn(),+ clientGetMock,+ getClientMock: vi.fn().mockResolvedValue({ get: clientGetMock }),+ };+});++vi.mock("axios", () => ({+ default: { get: axiosGetMock },+}));++vi.mock("@/api/AxiosClient", () => ({+ getClient: getClientMock,+}));+describe("artifactIdFromContentUrl", () => {test("extracts the artifact id from a signed content URL", () => {expect(@@ -60,6 +79,69 @@ describe("expiryFromSignedUrl", () => {});});+describe("freshArtifactUrl", () => {+ test("mints a fresh URL for artifact content URLs", async () => {+ clientGetMock.mockResolvedValueOnce({+ data: { artifact_id: "a_1", signed_url: "https://fresh", expires_at: 2 },+ });+ await expect(+ freshArtifactUrl(+ null,+ "https://api.skyvern.com/v1/artifacts/a_1/content?expiry=1&kid=k&sig=s",+ ),+ ).resolves.toBe("https://fresh");+ expect(clientGetMock).toHaveBeenCalledWith("/artifacts/a_1/signed-url");+ // The signed-url route only exists on the `/v1` router (not `/api/v1`).+ expect(getClientMock).toHaveBeenCalledWith(null, "sans-api-v1");+ });++ test("returns non-artifact URLs unchanged without minting", async () => {+ clientGetMock.mockClear();+ const presigned = "https://bucket.s3.amazonaws.com/f.pdf?X-Amz-Signature=x";+ await expect(freshArtifactUrl(null, presigned)).resolves.toBe(presigned);+ expect(clientGetMock).not.toHaveBeenCalled();+ });++ test("falls back to the original URL when minting fails", async () => {+ clientGetMock.mockRejectedValueOnce(new Error("boom"));+ const url =+ "https://api.skyvern.com/v1/artifacts/a_1/content?expiry=1&kid=k&sig=s";+ await expect(freshArtifactUrl(null, url)).resolves.toBe(url);+ });+});++describe("getWithMintRetry", () => {+ test("returns the first fetch when it succeeds", async () => {+ axiosGetMock.mockResolvedValueOnce({ data: "body" });+ await expect(getWithMintRetry("https://u1", "a_1", null)).resolves.toBe(+ "body",+ );+ expect(axiosGetMock).toHaveBeenCalledTimes(1);+ });++ test("retries once on a freshly minted URL when the fetch fails", async () => {+ axiosGetMock.mockRejectedValueOnce(new Error("403"));+ clientGetMock.mockResolvedValueOnce({+ data: { artifact_id: "a_1", signed_url: "https://fresh", expires_at: 2 },+ });+ axiosGetMock.mockResolvedValueOnce({ data: "fresh-body" });++ await expect(getWithMintRetry("https://u1", "a_1", null)).resolves.toBe(+ "fresh-body",+ );+ expect(axiosGetMock).toHaveBeenLastCalledWith("https://fresh");+ });++ test("surfaces the original error when minting fails", async () => {+ const original = new Error("original 403");+ axiosGetMock.mockRejectedValueOnce(original);+ clientGetMock.mockRejectedValueOnce(new Error("mint failed"));+ await expect(getWithMintRetry("https://u1", "a_1", null)).rejects.toBe(+ original,+ );+ });+});+describe("refreshDelayMs", () => {test("schedules the refresh margin before expiry", () => {// expires 300s from now, margin 60s -> refresh in 240sdiff --git a/skyvern-frontend/src/api/artifactUrls.ts b/skyvern-frontend/src/api/artifactUrls.tsindex f8ab7a22f..499166ce9 100644--- a/skyvern-frontend/src/api/artifactUrls.ts+++ b/skyvern-frontend/src/api/artifactUrls.ts@@ -1,4 +1,6 @@-import { AxiosInstance } from "axios";+import axios from "axios";++import { CredentialGetter, getClient } from "@/api/AxiosClient";export type ArtifactSignedUrlApiResponse = {artifact_id: string;@@ -65,11 +67,61 @@ export function refreshDelayMs(/** Mint a fresh short-lived content URL for the artifact (SKY-12541). */export async function mintSignedArtifactUrl(- client: AxiosInstance,+ credentialGetter: CredentialGetter | null,artifactId: string,): Promise<ArtifactSignedUrlApiResponse> {+ // The signed-url route is registered on the `/v1` router only; the default+ // client's `/api/v1` base 404s.+ const client = await getClient(credentialGetter, "sans-api-v1");const response = await client.get<ArtifactSignedUrlApiResponse>(`/artifacts/${artifactId}/signed-url`,);return response.data;}++/**+ * Freshly minted URL for a Skyvern content URL, at the point of use. Returns+ * the input unchanged for non-artifact URLs or when minting fails (the caller+ * falls back to whatever validity the original URL still has).+ */+export async function freshArtifactUrl(+ credentialGetter: CredentialGetter | null,+ url: string,+): Promise<string> {+ const artifactId = artifactIdFromContentUrl(url);+ if (!artifactId) {+ return url;+ }+ try {+ const minted = await mintSignedArtifactUrl(credentialGetter, artifactId);+ return minted.signed_url;+ } catch {+ return url;+ }+}++/**+ * GET `url`, retrying once on a freshly minted URL when the fetch fails.+ * Deliberately retries on any failure, not just 403: expiry surfaces as an+ * opaque error on cross-origin fetches, and the mint only runs on the error+ * path.+ */+export async function getWithMintRetry(+ url: string,+ artifactId: string,+ credentialGetter: CredentialGetter | null,+): Promise<unknown> {+ try {+ const response = await axios.get(url);+ return response.data;+ } catch (initialError) {+ let minted: ArtifactSignedUrlApiResponse;+ try {+ minted = await mintSignedArtifactUrl(credentialGetter, artifactId);+ } catch {+ throw initialError;+ }+ const response = await axios.get(minted.signed_url);+ return response.data;+ }+}diff --git a/skyvern-frontend/src/components/ArtifactDownloadLink.test.tsx b/skyvern-frontend/src/components/ArtifactDownloadLink.test.tsxnew file mode 100644index 000000000..631339f4f--- /dev/null+++ b/skyvern-frontend/src/components/ArtifactDownloadLink.test.tsx@@ -0,0 +1,62 @@+// @vitest-environment jsdom++import { fireEvent, render, waitFor } from "@testing-library/react";+import { describe, expect, it, vi } from "vitest";++import { ArtifactDownloadLink } from "./ArtifactDownloadLink";++const { freshMock } = vi.hoisted(() => ({+ freshMock: vi.fn(),+}));++vi.mock("@/api/artifactUrls", async (importOriginal) => ({+ ...(await importOriginal<typeof import("@/api/artifactUrls")>()),+ freshArtifactUrl: freshMock,+}));++vi.mock("@/hooks/useCredentialGetter", () => ({+ useCredentialGetter: () => null,+}));++const ARTIFACT_URL =+ "https://api.skyvern.com/v1/artifacts/a_dl/content?expiry=1&kid=k&sig=s";+const MINTED_URL =+ "https://api.skyvern.com/v1/artifacts/a_dl/content?expiry=2&kid=k&sig=fresh";++describe("ArtifactDownloadLink", () => {+ it("opens the tab synchronously in the click gesture, then assigns the minted URL", async () => {+ freshMock.mockResolvedValue(MINTED_URL);+ const fakeTab = { location: { href: "" }, opener: {} } as unknown as Window;+ const openSpy = vi.spyOn(window, "open").mockReturnValue(fakeTab);++ const { container } = render(+ <ArtifactDownloadLink href={ARTIFACT_URL} target="_blank">+ file.pdf+ </ArtifactDownloadLink>,+ );+ const anchor = container.querySelector("a")!;+ const notPrevented = fireEvent.click(anchor);++ expect(notPrevented).toBe(false);+ // Opened before the mint resolves, or popup blockers kill it.+ expect(openSpy).toHaveBeenCalledWith("", "_blank");+ expect(fakeTab.opener).toBeNull();+ expect(freshMock).toHaveBeenCalledWith(null, ARTIFACT_URL);+ await waitFor(() => {+ expect(fakeTab.location.href).toBe(MINTED_URL);+ });+ openSpy.mockRestore();+ });++ it("keeps native behavior for modified clicks", () => {+ freshMock.mockClear();+ const { container } = render(+ <ArtifactDownloadLink href={ARTIFACT_URL}>file.pdf</ArtifactDownloadLink>,+ );+ const anchor = container.querySelector("a")!;+ const notPrevented = fireEvent.click(anchor, { metaKey: true });++ expect(notPrevented).toBe(true);+ expect(freshMock).not.toHaveBeenCalled();+ });+});diff --git a/skyvern-frontend/src/components/ArtifactDownloadLink.tsx b/skyvern-frontend/src/components/ArtifactDownloadLink.tsxnew file mode 100644index 000000000..0b95d33e4--- /dev/null+++ b/skyvern-frontend/src/components/ArtifactDownloadLink.tsx@@ -0,0 +1,60 @@+import { freshArtifactUrl } from "@/api/artifactUrls";+import { useCredentialGetter } from "@/hooks/useCredentialGetter";++type Props = Omit<React.ComponentPropsWithoutRef<"a">, "href"> & {+ href: string;+};++/**+ * Anchor for artifact content URLs that mints a fresh short-lived URL at+ * click time (SKY-12541), so links keep working after the embedded URL+ * expires. Non-artifact hrefs (storage presigned URLs) navigate natively.+ */+function ArtifactDownloadLink({+ href,+ onClick,+ children,+ ...anchorProps+}: Props) {+ const credentialGetter = useCredentialGetter();++ const handleClick = (event: React.MouseEvent<HTMLAnchorElement>) => {+ onClick?.(event);+ // Modified clicks (new-tab, download-as) keep native anchor semantics.+ if (+ event.defaultPrevented ||+ event.button !== 0 ||+ event.metaKey ||+ event.ctrlKey ||+ event.shiftKey ||+ event.altKey+ ) {+ return;+ }+ event.preventDefault();+ // The tab must be opened synchronously inside the click gesture — opening+ // it after the awaited mint trips popup blockers (Safari/Firefox). The+ // minted URL is assigned to the already-open tab; if the open was still+ // blocked, fall back to same-tab navigation.+ const newTab =+ anchorProps.target === "_blank" ? window.open("", "_blank") : null;+ if (newTab) {+ newTab.opener = null;+ }+ void freshArtifactUrl(credentialGetter, href).then((url) => {+ if (newTab) {+ newTab.location.href = url;+ } else {+ window.location.assign(url);+ }+ });+ };++ return (+ <a href={href} onClick={handleClick} {...anchorProps}>+ {children}+ </a>+ );+}++export { ArtifactDownloadLink };diff --git a/skyvern-frontend/src/components/ArtifactImage.tsx b/skyvern-frontend/src/components/ArtifactImage.tsxnew file mode 100644index 000000000..6a3807783--- /dev/null+++ b/skyvern-frontend/src/components/ArtifactImage.tsx@@ -0,0 +1,18 @@+import { ArtifactApiResponse } from "@/api/types";+import { ZoomableImage } from "@/components/ZoomableImage";+import { useArtifactImageSrc } from "@/hooks/useArtifactImageSrc";++type Props = Omit<+ React.ComponentProps<typeof ZoomableImage>,+ "src" | "onError"+> & {+ artifact: ArtifactApiResponse;+};++/** ZoomableImage for an artifact; re-mints its URL once on load error (SKY-12541). */+function ArtifactImage({ artifact, ...imageProps }: Props) {+ const { src, onImageError } = useArtifactImageSrc(artifact);+ return <ZoomableImage src={src} onError={onImageError} {...imageProps} />;+}++export { ArtifactImage };diff --git a/skyvern-frontend/src/components/ArtifactVideo.test.tsx b/skyvern-frontend/src/components/ArtifactVideo.test.tsxindex 3968ef8f1..1a622649a 100644--- a/skyvern-frontend/src/components/ArtifactVideo.test.tsx+++ b/skyvern-frontend/src/components/ArtifactVideo.test.tsx@@ -44,7 +44,7 @@ describe("ArtifactVideo", () => {await waitFor(() => {expect(video.getAttribute("src")).toBe(MINTED_URL);});- expect(mintMock).toHaveBeenCalledWith(expect.anything(), "a_rec");+ expect(mintMock).toHaveBeenCalledWith(null, "a_rec");fireEvent.error(video);expect(mintMock).toHaveBeenCalledTimes(1);diff --git a/skyvern-frontend/src/components/ArtifactVideo.tsx b/skyvern-frontend/src/components/ArtifactVideo.tsxindex aa4d2b996..4d6723360 100644--- a/skyvern-frontend/src/components/ArtifactVideo.tsx+++ b/skyvern-frontend/src/components/ArtifactVideo.tsx@@ -1,6 +1,5 @@import { useCallback, useEffect, useRef, useState } from "react";-import { getClient } from "@/api/AxiosClient";import {artifactIdFromContentUrl,expiryFromSignedUrl,@@ -52,8 +51,7 @@ function ArtifactVideo({};}try {- const client = await getClient(credentialGetter);- const minted = await mintSignedArtifactUrl(client, artifactId);+ const minted = await mintSignedArtifactUrl(credentialGetter, artifactId);setUrl(minted.signed_url);} catch {// Leave the current URL in place; the on-error backstop (or the nextdiff --git a/skyvern-frontend/src/hooks/useArtifactImageSrc.test.tsx b/skyvern-frontend/src/hooks/useArtifactImageSrc.test.tsxnew file mode 100644index 000000000..779f73b44--- /dev/null+++ b/skyvern-frontend/src/hooks/useArtifactImageSrc.test.tsx@@ -0,0 +1,107 @@+// @vitest-environment jsdom++import { act, fireEvent, render, waitFor } from "@testing-library/react";+import { describe, expect, it, vi } from "vitest";++import { ArtifactApiResponse } from "@/api/types";+import { useArtifactImageSrc } from "./useArtifactImageSrc";++const { mintMock } = vi.hoisted(() => ({+ mintMock: vi.fn(),+}));++vi.mock("@/api/AxiosClient", () => ({+ getClient: vi.fn().mockResolvedValue({}),+}));++vi.mock("@/api/artifactUrls", async (importOriginal) => ({+ ...(await importOriginal<typeof import("@/api/artifactUrls")>()),+ mintSignedArtifactUrl: mintMock,+}));++vi.mock("@/hooks/useCredentialGetter", () => ({+ useCredentialGetter: () => null,+}));++const SIGNED_URL =+ "https://api.skyvern.com/v1/artifacts/a_img/content?expiry=1&kid=k&sig=s";+const MINTED_URL =+ "https://api.skyvern.com/v1/artifacts/a_img/content?expiry=2&kid=k&sig=fresh";++const artifact = {+ artifact_id: "a_img",+ artifact_type: "screenshot_action",+ uri: "s3://bucket/a_img.png",+ signed_url: SIGNED_URL,+} as ArtifactApiResponse;++function Probe({+ probeArtifact = artifact,+}: {+ probeArtifact?: ArtifactApiResponse;+}) {+ const { src, onImageError, imageFailed } = useArtifactImageSrc(probeArtifact);+ if (imageFailed) {+ return <div data-testid="failed">failed</div>;+ }+ return <img src={src} onError={onImageError} alt="probe" />;+}++describe("useArtifactImageSrc", () => {+ it("re-mints once on image error, then fails permanently", async () => {+ mintMock.mockResolvedValue({+ artifact_id: "a_img",+ signed_url: MINTED_URL,+ expires_at: 2,+ });++ const { container, queryByTestId } = render(<Probe />);+ const img = () => container.querySelector("img")!;+ expect(img().getAttribute("src")).toBe(SIGNED_URL);++ fireEvent.error(img());+ await waitFor(() => {+ expect(img().getAttribute("src")).toBe(MINTED_URL);+ });+ expect(mintMock).toHaveBeenCalledWith(null, "a_img");+ expect(queryByTestId("failed")).toBeNull();++ fireEvent.error(img());+ await waitFor(() => {+ expect(queryByTestId("failed")).not.toBeNull();+ });+ expect(mintMock).toHaveBeenCalledTimes(1);+ });++ it("ignores a mint that resolves after the artifact changed", async () => {+ let resolveMint!: (value: unknown) => void;+ mintMock.mockReset();+ mintMock.mockReturnValueOnce(+ new Promise((resolve) => {+ resolveMint = resolve;+ }),+ );++ const otherArtifact = {+ ...artifact,+ artifact_id: "a_other",+ signed_url:+ "https://api.skyvern.com/v1/artifacts/a_other/content?expiry=1&kid=k&sig=s",+ } as ArtifactApiResponse;++ const { container, rerender } = render(<Probe />);+ const img = () => container.querySelector("img")!;+ fireEvent.error(img());++ rerender(<Probe probeArtifact={otherArtifact} />);+ await act(async () => {+ resolveMint({+ artifact_id: "a_img",+ signed_url: MINTED_URL,+ expires_at: 2,+ });+ });++ expect(img().getAttribute("src")).toBe(otherArtifact.signed_url);+ });+});diff --git a/skyvern-frontend/src/hooks/useArtifactImageSrc.ts b/skyvern-frontend/src/hooks/useArtifactImageSrc.tsnew file mode 100644index 000000000..13b429dcc--- /dev/null+++ b/skyvern-frontend/src/hooks/useArtifactImageSrc.ts@@ -0,0 +1,50 @@+import { useCallback, useEffect, useRef, useState } from "react";++import { mintSignedArtifactUrl } from "@/api/artifactUrls";+import { ArtifactApiResponse } from "@/api/types";+import { useCredentialGetter } from "@/hooks/useCredentialGetter";+import { getImageURL } from "@/routes/tasks/detail/artifactUtils";++/**+ * Image source for an artifact that survives signed-URL expiry (SKY-12541):+ * on image error, mint a fresh short-lived URL once and retry before giving+ * up. `imageFailed` only turns true after the minted retry also fails.+ */+function useArtifactImageSrc(artifact: ArtifactApiResponse | undefined) {+ const credentialGetter = useCredentialGetter();+ const [mintedUrl, setMintedUrl] = useState<string | null>(null);+ const [imageFailed, setImageFailed] = useState(false);++ const artifactId = artifact?.artifact_id;+ const baseSrc = artifact ? getImageURL(artifact) : undefined;+ const currentArtifactIdRef = useRef(artifactId);++ useEffect(() => {+ currentArtifactIdRef.current = artifactId;+ setMintedUrl(null);+ setImageFailed(false);+ }, [artifactId, baseSrc]);++ const onImageError = useCallback(() => {+ if (!artifactId || mintedUrl) {+ setImageFailed(true);+ return;+ }+ mintSignedArtifactUrl(credentialGetter, artifactId)+ .then((minted) => {+ // Ignore mints that resolve after the rendered artifact changed.+ if (currentArtifactIdRef.current === artifactId) {+ setMintedUrl(minted.signed_url);+ }+ })+ .catch(() => {+ if (currentArtifactIdRef.current === artifactId) {+ setImageFailed(true);+ }+ });+ }, [artifactId, mintedUrl, credentialGetter]);++ return { src: mintedUrl ?? baseSrc, onImageError, imageFailed };+}++export { useArtifactImageSrc };diff --git a/skyvern-frontend/src/routes/browserSessions/BrowserSessionDownloads.tsx b/skyvern-frontend/src/routes/browserSessions/BrowserSessionDownloads.tsxindex 82e1bee9d..27fc29300 100644--- a/skyvern-frontend/src/routes/browserSessions/BrowserSessionDownloads.tsx+++ b/skyvern-frontend/src/routes/browserSessions/BrowserSessionDownloads.tsx@@ -3,6 +3,8 @@ import { useQuery } from "@tanstack/react-query";import { useParams } from "react-router-dom";import { getClient } from "@/api/AxiosClient";+import { freshArtifactUrl } from "@/api/artifactUrls";+import { ArtifactDownloadLink } from "@/components/ArtifactDownloadLink";import { useCredentialGetter } from "@/hooks/useCredentialGetter";import { type BrowserSession } from "@/routes/workflows/types/browserSessionTypes";@@ -138,7 +140,7 @@ function BrowserSessionDownloads() {{file.url && (<div className="flex w-full gap-1.5">{previewable ? (- <a+ <ArtifactDownloadLinkhref={file.url}target="_blank"rel="noopener noreferrer"@@ -147,7 +149,7 @@ function BrowserSessionDownloads() {><EyeOpenIcon className="size-3" />Preview- </a>+ </ArtifactDownloadLink>) : (<buttondisabled@@ -159,7 +161,11 @@ function BrowserSessionDownloads() {</button>)}<button- onClick={() => downloadFile(file.url, filename)}+ onClick={() =>+ void freshArtifactUrl(credentialGetter, file.url).then(+ (url) => downloadFile(url, filename),+ )+ }className="flex flex-1 items-center justify-center gap-1 rounded border px-2 py-1 text-xs hover:bg-muted"title={`Download ${filename}`}>diff --git a/skyvern-frontend/src/routes/tasks/detail/ActionScreenshot.tsx b/skyvern-frontend/src/routes/tasks/detail/ActionScreenshot.tsxindex 33ef3601a..a0d141c60 100644--- a/skyvern-frontend/src/routes/tasks/detail/ActionScreenshot.tsx+++ b/skyvern-frontend/src/routes/tasks/detail/ActionScreenshot.tsx@@ -1,9 +1,8 @@import { getClient } from "@/api/AxiosClient";import { ArtifactApiResponse, ArtifactType, Status } from "@/api/types";-import { ZoomableImage } from "@/components/ZoomableImage";+import { ArtifactImage } from "@/components/ArtifactImage";import { useCredentialGetter } from "@/hooks/useCredentialGetter";import { useQuery } from "@tanstack/react-query";-import { getImageURL } from "./artifactUtils";import { ReloadIcon } from "@radix-ui/react-icons";import { statusIsNotFinalized } from "../types";import { apiPathPrefix } from "@/util/env";@@ -115,7 +114,7 @@ function ActionScreenshot({ artifactId, stepId, index, taskStatus }: Props) {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" />+ <ArtifactImage artifact={screenshot} alt="llm-screenshot" /></figure>);}diff --git a/skyvern-frontend/src/routes/tasks/detail/Artifact.tsx b/skyvern-frontend/src/routes/tasks/detail/Artifact.tsxindex 942f579e5..dd9402cf7 100644--- a/skyvern-frontend/src/routes/tasks/detail/Artifact.tsx+++ b/skyvern-frontend/src/routes/tasks/detail/Artifact.tsx@@ -1,9 +1,10 @@import { artifactApiClient } from "@/api/AxiosClient";+import { getWithMintRetry } from "@/api/artifactUrls";import { ArtifactApiResponse } from "@/api/types";import { Skeleton } from "@/components/ui/skeleton";+import { useCredentialGetter } from "@/hooks/useCredentialGetter";import { CodeEditor } from "@/routes/workflows/components/CodeEditor";import { useQueries } from "@tanstack/react-query";-import axios from "axios";// https://stackoverflow.com/a/60338028function format(html: string) {@@ -53,6 +54,7 @@ type Props = {};function Artifact({ type, artifacts }: Props) {+ const credentialGetter = useCredentialGetter();const total = artifacts.length;const archivedCount = artifacts.filter((a) => a.archived).length;const allArchived = total > 0 && archivedCount === total;@@ -60,7 +62,11 @@ function Artifact({ type, artifacts }: Props) {function fetchArtifact(artifact: ArtifactApiResponse) {if (artifact.signed_url) {- return axios.get(artifact.signed_url).then((response) => response.data);+ return getWithMintRetry(+ artifact.signed_url,+ artifact.artifact_id,+ credentialGetter,+ );}if (artifact.uri.startsWith("file://")) {const endpoint = getEndpoint(type);diff --git a/skyvern-frontend/src/routes/tasks/detail/StepArtifacts.tsx b/skyvern-frontend/src/routes/tasks/detail/StepArtifacts.tsxindex e2f48a9ec..000f7c435 100644--- a/skyvern-frontend/src/routes/tasks/detail/StepArtifacts.tsx+++ b/skyvern-frontend/src/routes/tasks/detail/StepArtifacts.tsx@@ -9,9 +9,8 @@ import { Label } from "@/components/ui/label";import { useQuery } from "@tanstack/react-query";import { useSearchParams } from "react-router-dom";import { Tabs, TabsContent, TabsList, TabsTrigger } from "@/components/ui/tabs";-import { ZoomableImage } from "@/components/ZoomableImage";+import { ArtifactImage } from "@/components/ArtifactImage";import { Skeleton } from "@/components/ui/skeleton";-import { getImageURL } from "./artifactUtils";import { Input } from "@/components/ui/input";import { basicLocalTimeFormat, basicTimeFormat } from "@/util/timeFormat";import { useCredentialGetter } from "@/hooks/useCredentialGetter";@@ -70,9 +69,9 @@ function ScreenshotsTabContent({)}<div className={`grid ${gridCols} gap-4`}>{visible.map((artifact, index) => (- <ZoomableImage+ <ArtifactImagekey={index}- src={getImageURL(artifact)}+ artifact={artifact}className="h-full w-full object-cover"alt="action-screenshot"/>diff --git a/skyvern-frontend/src/routes/workflows/WorkflowRun.tsx b/skyvern-frontend/src/routes/workflows/WorkflowRun.tsxindex d3fd1403d..c72cda03e 100644--- a/skyvern-frontend/src/routes/workflows/WorkflowRun.tsx+++ b/skyvern-frontend/src/routes/workflows/WorkflowRun.tsx@@ -56,6 +56,7 @@ import {findActiveItem,parseActiveIterationParam,} from "./workflowRun/workflowTimelineUtils";+import { ArtifactDownloadLink } from "@/components/ArtifactDownloadLink";import { pickDownloadedFileFilename } from "./workflowRun/blockDownloadedFiles";import { isBlockItem } from "./types/workflowRunTypes";import { Label } from "@/components/ui/label";@@ -765,12 +766,12 @@ function WorkflowRun() {return (<div key={url} title={url} className="flex gap-2"><FileIcon className="size-6" />- <a+ <ArtifactDownloadLinkhref={url}className="underline underline-offset-4"><span>{filename}</span>- </a>+ </ArtifactDownloadLink></div>);})diff --git a/skyvern-frontend/src/routes/workflows/studio/runview/HeroScreenshot.tsx b/skyvern-frontend/src/routes/workflows/studio/runview/HeroScreenshot.tsxindex 3c069027c..8fa17d64e 100644--- a/skyvern-frontend/src/routes/workflows/studio/runview/HeroScreenshot.tsx+++ b/skyvern-frontend/src/routes/workflows/studio/runview/HeroScreenshot.tsx@@ -4,8 +4,8 @@ import { useQuery } from "@tanstack/react-query";import { getClient } from "@/api/AxiosClient";import { ArtifactApiResponse, ArtifactType } from "@/api/types";+import { useArtifactImageSrc } from "@/hooks/useArtifactImageSrc";import { useCredentialGetter } from "@/hooks/useCredentialGetter";-import { getImageURL } from "@/routes/tasks/detail/artifactUtils";import { apiPathPrefix } from "@/util/env";import { selectBlockScreenshot } from "../../workflowRun/blockScreenshot";@@ -148,6 +148,7 @@ export function HeroScreenshot({}const screenshotId = screenshot?.artifact_id ?? null;+ const { src, onImageError } = useArtifactImageSrc(screenshot);const isLoading =loadingArtifact || loadingStep || loadingBlock || loadingThought;@@ -207,9 +208,10 @@ export function HeroScreenshot({}}><img- src={getImageURL(screenshot)}+ src={src}alt="screenshot"className={zoom.image}+ onError={onImageError}/></div>);diff --git a/skyvern-frontend/src/routes/workflows/studio/runview/RunOutputsSection.tsx b/skyvern-frontend/src/routes/workflows/studio/runview/RunOutputsSection.tsxindex 403a3f290..7d09364ca 100644--- a/skyvern-frontend/src/routes/workflows/studio/runview/RunOutputsSection.tsx+++ b/skyvern-frontend/src/routes/workflows/studio/runview/RunOutputsSection.tsx@@ -4,6 +4,7 @@ import {FileIcon,} from "@radix-ui/react-icons";+import { ArtifactDownloadLink } from "@/components/ArtifactDownloadLink";import { SummarizeOutput } from "@/components/SummarizeOutput";import { OverviewCodeBlock } from "./OverviewCodeBlock";@@ -257,7 +258,7 @@ export function RunOutputsSection({</span><div className="flex flex-col gap-1">{files.map((file) => (- <a+ <ArtifactDownloadLinkkey={file.url}href={file.url}title={file.url}@@ -267,7 +268,7 @@ export function RunOutputsSection({<FileIcon className="size-4 shrink-0 text-muted-foreground" /><span className="min-w-0 flex-1 truncate">{file.filename}</span><DownloadIcon className="size-4 shrink-0 text-muted-foreground transition-colors group-hover:text-foreground" />- </a>+ </ArtifactDownloadLink>))}</div></div>diff --git a/skyvern-frontend/src/routes/workflows/workflowRun/ObserverThoughtScreenshot.tsx b/skyvern-frontend/src/routes/workflows/workflowRun/ObserverThoughtScreenshot.tsxindex d9b59db2f..25fa07626 100644--- a/skyvern-frontend/src/routes/workflows/workflowRun/ObserverThoughtScreenshot.tsx+++ b/skyvern-frontend/src/routes/workflows/workflowRun/ObserverThoughtScreenshot.tsx@@ -1,7 +1,7 @@-import { useEffect, useState } from "react";import { getClient } from "@/api/AxiosClient";import { ArtifactApiResponse, ArtifactType, Status } from "@/api/types";import { ZoomableImage } from "@/components/ZoomableImage";+import { useArtifactImageSrc } from "@/hooks/useArtifactImageSrc";import { useCredentialGetter } from "@/hooks/useCredentialGetter";import { useQuery } from "@tanstack/react-query";import {@@ -9,7 +9,6 @@ import {StreamStatusPanel,} from "@/routes/streaming/StreamDiagnostics";import { statusIsNotFinalized } from "@/routes/tasks/types";-import { getImageURL } from "@/routes/tasks/detail/artifactUtils";import { apiPathPrefix } from "@/util/env";type Props = {@@ -19,7 +18,6 @@ type Props = {function ObserverThoughtScreenshot({ observerThoughtId, taskStatus }: Props) {const credentialGetter = useCredentialGetter();- const [imageFailed, setImageFailed] = useState(false);const { data: artifacts, isLoading } = useQuery<Array<ArtifactApiResponse>>({queryKey: ["observerThought", observerThoughtId, "artifacts"],@@ -47,10 +45,7 @@ function ObserverThoughtScreenshot({ observerThoughtId, taskStatus }: Props) {// use the last screenshot as the llmScreenshots are in reverse orderconst screenshot = llmScreenshots?.[llmScreenshots.length - 1];-- useEffect(() => {- setImageFailed(false);- }, [observerThoughtId, screenshot?.signed_url]);+ const { src, onImageError, imageFailed } = useArtifactImageSrc(screenshot);if (isLoading) {return (@@ -110,11 +105,7 @@ function ObserverThoughtScreenshot({ observerThoughtId, taskStatus }: Props) {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"- onError={() => setImageFailed(true)}- />+ <ZoomableImage src={src} alt="llm-screenshot" onError={onImageError} /></figure>);}diff --git a/skyvern-frontend/src/routes/workflows/workflowRun/WorkflowRunBlockDetail.tsx b/skyvern-frontend/src/routes/workflows/workflowRun/WorkflowRunBlockDetail.tsxindex 3407a6080..586783c78 100644--- a/skyvern-frontend/src/routes/workflows/workflowRun/WorkflowRunBlockDetail.tsx+++ b/skyvern-frontend/src/routes/workflows/workflowRun/WorkflowRunBlockDetail.tsx@@ -1,6 +1,7 @@import type { ActionsApiResponse } from "@/api/types";import { useMemo } from "react";import { FileIcon } from "@radix-ui/react-icons";+import { ArtifactDownloadLink } from "@/components/ArtifactDownloadLink";import { useWorkflowRunWithWorkflowQuery } from "../hooks/useWorkflowRunWithWorkflowQuery";import {isAction,@@ -97,12 +98,12 @@ function BlockDownloadedFiles({className="flex items-center gap-2 text-sm"><FileIcon className="size-4 shrink-0 text-muted-foreground" />- <a+ <ArtifactDownloadLinkhref={file.url}className="truncate underline underline-offset-4">{file.filename}- </a>+ </ArtifactDownloadLink></div>))}</div>diff --git a/skyvern-frontend/src/routes/workflows/workflowRun/WorkflowRunBlockScreenshot.tsx b/skyvern-frontend/src/routes/workflows/workflowRun/WorkflowRunBlockScreenshot.tsxindex d63f04e98..4436afc72 100644--- a/skyvern-frontend/src/routes/workflows/workflowRun/WorkflowRunBlockScreenshot.tsx+++ b/skyvern-frontend/src/routes/workflows/workflowRun/WorkflowRunBlockScreenshot.tsx@@ -1,7 +1,7 @@-import { useEffect, useState } from "react";import { getClient } from "@/api/AxiosClient";import { ArtifactApiResponse, Status } from "@/api/types";import { ZoomableImage } from "@/components/ZoomableImage";+import { useArtifactImageSrc } from "@/hooks/useArtifactImageSrc";import { useCredentialGetter } from "@/hooks/useCredentialGetter";import { useQuery } from "@tanstack/react-query";import {@@ -9,7 +9,6 @@ import {StreamStatusPanel,} from "@/routes/streaming/StreamDiagnostics";import { statusIsNotFinalized } from "@/routes/tasks/types";-import { getImageURL } from "@/routes/tasks/detail/artifactUtils";import { apiPathPrefix } from "@/util/env";import { isBlockScreenshot, selectBlockScreenshot } from "./blockScreenshot";@@ -25,7 +24,6 @@ function WorkflowRunBlockScreenshot({runStatus,}: Props) {const credentialGetter = useCredentialGetter();- const [imageFailed, setImageFailed] = useState(false);const { data: artifacts, isLoading } = useQuery<Array<ArtifactApiResponse>>({queryKey: ["workflowRunBlock", workflowRunBlockId, "artifacts"],@@ -50,10 +48,7 @@ function WorkflowRunBlockScreenshot({});const screenshot = selectBlockScreenshot(artifacts, blockType);-- useEffect(() => {- setImageFailed(false);- }, [workflowRunBlockId, screenshot?.signed_url]);+ const { src, onImageError, imageFailed } = useArtifactImageSrc(screenshot);if (isLoading) {return (@@ -112,11 +107,7 @@ function WorkflowRunBlockScreenshot({return (<figure className="mx-auto flex max-w-full flex-col items-center gap-2 overflow-hidden rounded">- <ZoomableImage- src={getImageURL(screenshot)}- alt="block screenshot"- onError={() => setImageFailed(true)}- />+ <ZoomableImage src={src} alt="block screenshot" onError={onImageError} /></figure>);}diff --git a/skyvern-frontend/src/routes/workflows/workflowRun/WorkflowRunOutput.tsx b/skyvern-frontend/src/routes/workflows/workflowRun/WorkflowRunOutput.tsxindex 4c750addc..1bcc9205e 100644--- a/skyvern-frontend/src/routes/workflows/workflowRun/WorkflowRunOutput.tsx+++ b/skyvern-frontend/src/routes/workflows/workflowRun/WorkflowRunOutput.tsx@@ -1,6 +1,7 @@import { FileIcon } from "@radix-ui/react-icons";import { useEffect, useMemo, useRef, useState } from "react";import { useSearchParams } from "react-router-dom";+import { ArtifactDownloadLink } from "@/components/ArtifactDownloadLink";import { Button } from "@/components/ui/button";import { CodeEditor } from "../components/CodeEditor";import { useWorkflowRunWithWorkflowQuery } from "../hooks/useWorkflowRunWithWorkflowQuery";@@ -363,9 +364,12 @@ function WorkflowRunOutput() {return (<div key={url} title={url} className="flex gap-2"><FileIcon className="size-6" />- <a href={url} className="underline underline-offset-4">+ <ArtifactDownloadLink+ href={url}+ className="underline underline-offset-4"+ ><span>{filename}</span>- </a>+ </ArtifactDownloadLink></div>);})