Skip to content

:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.

fix(desktop): open artifact links from agent messages in the app (#79524)

Shy Alter2d4c17c4c580
diff --git a/products/desktop/packages/agent/src/adapters/local-tools/tools/upload-artifact.test.ts b/products/desktop/packages/agent/src/adapters/local-tools/tools/upload-artifact.test.ts
index 8d54a95fdbf3..d7d7e5c69f9e 100644
--- a/products/desktop/packages/agent/src/adapters/local-tools/tools/upload-artifact.test.ts
+++ b/products/desktop/packages/agent/src/adapters/local-tools/tools/upload-artifact.test.ts
@@ -6,6 +6,8 @@ import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
const prepareTaskArtifactUploads = vi.fn();
const finalizeTaskArtifactUploads = vi.fn();
const uploadTaskArtifacts = vi.fn();
+const STABLE_DOWNLOAD_URL =
+ "https://app.example/api/projects/2/tasks/task-1/runs/run-1/artifacts/artifact-1/download/";
vi.mock("../../../signed-commit-artefacts", () => ({
createSandboxPosthogClient: () => ({
@@ -30,10 +32,10 @@ describe("uploadArtifactTool", () => {
prepareTaskArtifactUploads.mockResolvedValue([
{
id: "artifact-1",
- name: "report.csv",
+ name: "report [final].csv",
type: "output",
size: 7,
- storage_path: "tasks/artifacts/report.csv",
+ storage_path: "tasks/artifacts/report-final.csv",
expires_in: 300,
presigned_post: {
url: "https://storage.example/upload",
@@ -44,12 +46,12 @@ describe("uploadArtifactTool", () => {
finalizeTaskArtifactUploads.mockResolvedValue([
{
id: "artifact-1",
- name: "report.csv",
+ name: "report [final].csv",
type: "output",
size: 7,
- storage_path: "tasks/artifacts/report.csv",
+ storage_path: "tasks/artifacts/report-final.csv",
uploaded_at: "2026-01-01T00:00:00Z",
- url: "https://storage.example/download/report.csv",
+ url: STABLE_DOWNLOAD_URL,
},
]);
uploadTaskArtifacts.mockResolvedValue([
@@ -60,7 +62,7 @@ describe("uploadArtifactTool", () => {
size: 7,
storage_path: "tasks/artifacts/report.csv",
uploaded_at: "2026-01-01T00:00:00Z",
- url: "https://app.example/download/artifact-1",
+ url: STABLE_DOWNLOAD_URL,
},
]);
});
@@ -75,13 +77,17 @@ describe("uploadArtifactTool", () => {
const result = await uploadArtifactTool.handler(
{ cwd, taskId: "task-1", taskRunId: "run-1" },
- { path: "report.csv", contentType: "text/csv" },
+ {
+ path: "report.csv",
+ name: "report [final].csv",
+ contentType: "text/csv",
+ },
);
expect(result.isError).toBeUndefined();
expect(prepareTaskArtifactUploads).toHaveBeenCalledWith("task-1", "run-1", [
{
- name: "report.csv",
+ name: "report [final].csv",
type: "output",
source: "agent_output",
size: 7,
@@ -100,12 +106,12 @@ describe("uploadArtifactTool", () => {
id: "artifact-1",
type: "output",
source: "agent_output",
- storage_path: "tasks/artifacts/report.csv",
+ storage_path: "tasks/artifacts/report-final.csv",
}),
],
);
expect(result.content[0]?.text).toContain(
- "https://storage.example/download/report.csv",
+ String.raw`[report \[final\].csv](<${STABLE_DOWNLOAD_URL}>)`,
);
});
@@ -130,8 +136,34 @@ describe("uploadArtifactTool", () => {
}),
]);
expect(result.content[0]?.text).toContain(
- "https://app.example/download/artifact-1",
+ `[report.csv](<${STABLE_DOWNLOAD_URL}>)`,
+ );
+ });
+
+ it("removes credentials from a legacy presigned artifact reference", async () => {
+ await writeFile(path.join(cwd, "report.csv"), "a,b\n1,2");
+ finalizeTaskArtifactUploads.mockResolvedValueOnce([
+ {
+ id: "artifact-1",
+ name: "report.csv",
+ type: "output",
+ size: 7,
+ storage_path: "tasks/artifacts/report-final.csv",
+ uploaded_at: "2026-01-01T00:00:00Z",
+ url: "https://storage.example/tasks/artifacts/report.csv?X-Amz-Signature=secret",
+ },
+ ]);
+
+ const result = await uploadArtifactTool.handler(
+ { cwd, taskId: "task-1", taskRunId: "run-1" },
+ { path: "report.csv", contentType: "text/csv" },
+ );
+
+ expect(result.content[0]?.text).toContain(
+ "[report.csv](<https://storage.example/tasks/artifacts/report.csv>)",
);
+ expect(result.content[0]?.text).not.toContain("X-Amz-Signature");
+ expect(result.content[0]?.text).not.toContain("secret");
});
it("surfaces the failure instead of falling back above the inline size limit", async () => {
diff --git a/products/desktop/packages/agent/src/adapters/local-tools/tools/upload-artifact.ts b/products/desktop/packages/agent/src/adapters/local-tools/tools/upload-artifact.ts
index c5971464bbcf..bf2cadd4cae8 100644
--- a/products/desktop/packages/agent/src/adapters/local-tools/tools/upload-artifact.ts
+++ b/products/desktop/packages/agent/src/adapters/local-tools/tools/upload-artifact.ts
@@ -103,7 +103,10 @@ export const uploadArtifactTool = defineLocalTool({
}
const { name } = upload;
- const linkText = downloadUrl ? ` Download URL: ${downloadUrl}` : "";
+ const referenceUrl = getArtifactReferenceUrl(downloadUrl);
+ const linkText = referenceUrl
+ ? ` Reference it as a markdown link: [${escapeMarkdownLinkLabel(name)}](<${referenceUrl}>)`
+ : "";
return {
content: [
@@ -223,6 +226,28 @@ function readDownloadUrl(artifact: TaskRunArtifact): string | undefined {
return (artifact as { url?: string }).url;
}
+function getArtifactReferenceUrl(
+ downloadUrl: string | undefined,
+): string | null {
+ if (!downloadUrl) return null;
+
+ try {
+ const referenceUrl = new URL(downloadUrl);
+ // Legacy backends return bearer credentials in the query string; stable API URLs do not.
+ referenceUrl.search = "";
+ referenceUrl.hash = "";
+ referenceUrl.username = "";
+ referenceUrl.password = "";
+ return referenceUrl.toString();
+ } catch {
+ return null;
+ }
+}
+
+function escapeMarkdownLinkLabel(label: string): string {
+ return label.replace(/([\\[\]])/g, "\\$1");
+}
+
function errorResult(message: string): LocalToolResult {
return { content: [{ type: "text", text: message }], isError: true };
}
diff --git a/products/desktop/packages/ui/src/features/canvas/components/TaskArtifactsList.tsx b/products/desktop/packages/ui/src/features/canvas/components/TaskArtifactsList.tsx
index e7ea51313f26..ee5bff7d912e 100644
--- a/products/desktop/packages/ui/src/features/canvas/components/TaskArtifactsList.tsx
+++ b/products/desktop/packages/ui/src/features/canvas/components/TaskArtifactsList.tsx
@@ -8,11 +8,6 @@ import {
} from "@phosphor-icons/react";
import type { ResourceComment } from "@posthog/api-client/posthog-client";
import type { ThreadTimelineRow } from "@posthog/core/canvas/threadTimeline";
-import {
- SESSION_SERVICE,
- type SessionService,
-} from "@posthog/core/sessions/sessionService";
-import { useService } from "@posthog/di/react";
import {
Badge,
Button,
@@ -40,9 +35,9 @@ import { usePrComments } from "@posthog/ui/features/pr-review/usePrComments";
import { usePrReviewThreads } from "@posthog/ui/features/pr-review/usePrReviewThreads";
import { buildCommentThreads } from "@posthog/ui/features/sessions/components/commentViewTypes";
import { useCommentsForTargetsQuery } from "@posthog/ui/features/sessions/components/useComments";
+import { useArtifactDownload } from "@posthog/ui/features/sessions/useArtifactDownload";
import { useCommentsEnabled } from "@posthog/ui/features/sessions/useCommentsEnabled";
import { FileIcon } from "@posthog/ui/primitives/FileIcon";
-import { toast } from "@posthog/ui/primitives/toast";
import { openExternalUrl } from "@posthog/ui/shell/openExternal";
import { formatFileSize } from "@posthog/ui/utils/formatFileSize";
import { type ReactNode, useMemo, useState } from "react";
@@ -239,9 +234,8 @@ function FileRow({
/** Supplied by the pane's single comments query so each row doesn't fetch. */
commentCount: number;
}) {
- const sessionService = useService<SessionService>(SESSION_SERVICE);
const openArtifactTab = usePanelLayoutStore((state) => state.openArtifactTab);
- const [downloading, setDownloading] = useState(false);
+ const { download, downloadingId } = useArtifactDownload();
const canOpen = !!runId && !!artifactId;
const sizeLabel = formatFileSize(size);
const onOpen = canOpen
@@ -254,31 +248,13 @@ function FileRow({
}
: undefined;
const onDownload = canOpen
- ? async () => {
- setDownloading(true);
- try {
- const url = await sessionService.getCloudAttachmentPreviewUrl(
- taskId,
- runId as string,
- artifactId as string,
- );
- if (!url) {
- toast.error("This file is no longer available");
- return;
- }
- const response = await fetch(url);
- if (!response.ok) throw new Error("Artifact download failed");
- const objectUrl = URL.createObjectURL(await response.blob());
- const anchor = document.createElement("a");
- anchor.href = objectUrl;
- anchor.download = name;
- anchor.click();
- URL.revokeObjectURL(objectUrl);
- } catch {
- toast.error("Couldn't download file");
- } finally {
- setDownloading(false);
- }
+ ? () => {
+ void download({
+ taskId,
+ runId: runId as string,
+ artifactId: artifactId as string,
+ name,
+ });
}
: undefined;
return (
@@ -299,7 +275,7 @@ function FileRow({
onOpen={onOpen}
fileActions={
onDownload
- ? { onDownload: () => void onDownload(), downloading }
+ ? { onDownload, downloading: downloadingId === artifactId }
: undefined
}
/>
diff --git a/products/desktop/packages/ui/src/features/editor/components/ArtifactRefChip.stories.tsx b/products/desktop/packages/ui/src/features/editor/components/ArtifactRefChip.stories.tsx
new file mode 100644
index 000000000000..f46c38085122
--- /dev/null
+++ b/products/desktop/packages/ui/src/features/editor/components/ArtifactRefChip.stories.tsx
@@ -0,0 +1,57 @@
+import { ArtifactChipShell } from "@posthog/ui/features/editor/components/ArtifactRefChip";
+import type { Meta, StoryObj } from "@storybook/react-vite";
+
+const meta = {
+ title: "Editor/ArtifactRefChip",
+ component: ArtifactChipShell,
+} satisfies Meta<typeof ArtifactChipShell>;
+
+export default meta;
+type Story = StoryObj<typeof meta>;
+
+/** How an artifact reference reads mid-sentence in an agent message. */
+export const InAMessage: Story = {
+ render: () => (
+ <p className="max-w-lg text-[13px] leading-[1.9]">
+ I've put the findings in{" "}
+ <ArtifactChipShell
+ label="report.md"
+ name="report.md"
+ sizeLabel="12 KB"
+ onOpen={() => {}}
+ onDownload={() => {}}
+ />{" "}
+ — open it to read the breakdown, or download it to share.
+ </p>
+ ),
+};
+
+export const States: Story = {
+ render: () => (
+ <div className="flex max-w-lg flex-col items-start gap-3 text-[13px]">
+ <ArtifactChipShell
+ label="report.md"
+ name="report.md"
+ sizeLabel="12 KB"
+ onOpen={() => {}}
+ onDownload={() => {}}
+ />
+ <ArtifactChipShell
+ label="quarterly-revenue-breakdown-by-region-and-plan.csv"
+ name="quarterly-revenue-breakdown-by-region-and-plan.csv"
+ sizeLabel="1.4 MB"
+ onOpen={() => {}}
+ onDownload={() => {}}
+ />
+ <ArtifactChipShell
+ label="report.md"
+ name="report.md"
+ sizeLabel="12 KB"
+ onOpen={() => {}}
+ onDownload={() => {}}
+ downloading
+ />
+ <ArtifactChipShell label="report.md" name="report.md" disabled />
+ </div>
+ ),
+};
diff --git a/products/desktop/packages/ui/src/features/editor/components/ArtifactRefChip.test.tsx b/products/desktop/packages/ui/src/features/editor/components/ArtifactRefChip.test.tsx
new file mode 100644
index 000000000000..c8a24d42dffd
--- /dev/null
+++ b/products/desktop/packages/ui/src/features/editor/components/ArtifactRefChip.test.tsx
@@ -0,0 +1,169 @@
+import type { TaskRunArtifact } from "@posthog/shared";
+import { MarkdownRenderer } from "@posthog/ui/features/editor/components/MarkdownRenderer";
+import { ChatMarkdown } from "@posthog/ui/features/sessions/components/chat-thread/ChatMarkdown";
+import { SessionTaskIdProvider } from "@posthog/ui/features/sessions/useSessionTaskId";
+import { render, screen, waitFor } from "@testing-library/react";
+import userEvent from "@testing-library/user-event";
+import { beforeEach, describe, expect, it, vi } from "vitest";
+
+const TASK_ID = "3f1c2b6a-1111-4222-8333-444455556666";
+const RUN_ID = "9a8b7c6d-5555-4666-8777-888899990000";
+const ARTIFACT_ID = "1a2b3c4d-2222-4333-8444-555566667777";
+const STORAGE_PATH = `posthog-tasks/artifacts/team_2/task_${TASK_ID}/run_${RUN_ID}/1a2b3c4d_report.md`;
+const LEGACY_LINK = `https://bucket.s3.amazonaws.com/${STORAGE_PATH}?X-Amz-Signature=abc`;
+const STABLE_LINK = `https://app.posthog.com/api/projects/2/tasks/${TASK_ID}/runs/${RUN_ID}/artifacts/${ARTIFACT_ID}/download/`;
+
+const manifest = vi.hoisted(() => ({
+ data: undefined as TaskRunArtifact[] | undefined,
+ isLoading: false,
+}));
+const openArtifactTab = vi.hoisted(() => vi.fn());
+const download = vi.hoisted(() => vi.fn());
+
+vi.mock("@posthog/ui/features/sessions/useRunArtifacts", () => ({
+ useRunArtifacts: () => manifest,
+}));
+
+vi.mock("@posthog/ui/features/sessions/useArtifactDownload", () => ({
+ useArtifactDownload: () => ({ download, downloadingId: null }),
+}));
+
+vi.mock("@posthog/ui/features/panels/panelLayoutStore", () => ({
+ usePanelLayoutStore: (selector: (state: unknown) => unknown) =>
+ selector({ openArtifactTab }),
+}));
+
+// Agent replies render through two markdown surfaces — the app-wide renderer and
+// the chat thread's own. A link has to become a chip in both.
+const SURFACES = [
+ ["MarkdownRenderer", MarkdownRenderer],
+ ["ChatMarkdown", ChatMarkdown],
+] as const;
+
+let renderSurface: (typeof SURFACES)[number][1] = MarkdownRenderer;
+
+function renderMessage(content: string, taskId: string | undefined = TASK_ID) {
+ const Surface = renderSurface;
+ return render(
+ <SessionTaskIdProvider taskId={taskId}>
+ <Surface content={content} />
+ </SessionTaskIdProvider>,
+ );
+}
+
+describe.each(SURFACES)("artifact links in messages (%s)", (_name, Surface) => {
+ beforeEach(() => {
+ renderSurface = Surface;
+ vi.clearAllMocks();
+ manifest.isLoading = false;
+ manifest.data = [
+ {
+ id: ARTIFACT_ID,
+ name: "report.md",
+ type: "output",
+ size: 2048,
+ storage_path: STORAGE_PATH,
+ },
+ ];
+ });
+
+ it.each([
+ ["legacy storage", LEGACY_LINK],
+ ["stable download", STABLE_LINK],
+ ])(
+ "opens a %s link in a tab instead of leaving the app",
+ async (_kind, link) => {
+ renderMessage(`Here it is: [report.md](${link})`);
+
+ await userEvent.click(
+ await screen.findByRole("button", { name: "Open report.md" }),
+ );
+
+ expect(openArtifactTab).toHaveBeenCalledWith(TASK_ID, {
+ runId: RUN_ID,
+ artifactId: ARTIFACT_ID,
+ name: "report.md",
+ });
+ expect(screen.queryByRole("link")).toBeNull();
+ },
+ );
+
+ it("downloads from the divided half without opening a tab", async () => {
+ renderMessage(`Here it is: [report.md](${LEGACY_LINK})`);
+
+ await userEvent.click(
+ await screen.findByRole("button", { name: "Download report.md" }),
+ );
+
+ expect(download).toHaveBeenCalledWith({
+ taskId: TASK_ID,
+ runId: RUN_ID,
+ artifactId: ARTIFACT_ID,
+ name: "report.md",
+ });
+ expect(openArtifactTab).not.toHaveBeenCalled();
+ });
+
+ it("holds an inert chip while the manifest is still loading", async () => {
+ manifest.data = undefined;
+ manifest.isLoading = true;
+ renderMessage(`Here it is: [report.md](${LEGACY_LINK})`);
+
+ expect(screen.queryByRole("link")).toBeNull();
+ expect(
+ await screen.findByRole("button", { name: "Open report.md" }),
+ ).toBeDisabled();
+ });
+
+ it.each([
+ ["legacy storage", LEGACY_LINK],
+ ["stable download", STABLE_LINK],
+ ])("labels a bare %s url with the manifest filename", async (_kind, link) => {
+ renderMessage(`Here it is: ${link}`);
+
+ const chip = await screen.findByRole("button", { name: "Open report.md" });
+ expect(chip).toHaveTextContent("report.md");
+ expect(chip).not.toHaveTextContent("https://");
+ });
+
+ it("keeps a stable link when the artifact is no longer in the manifest", async () => {
+ manifest.data = [];
+ renderMessage(`Here it is: [report.md](${STABLE_LINK})`);
+
+ await waitFor(() => {
+ expect(screen.getByRole("link")).toHaveAttribute("href", STABLE_LINK);
+ });
+ expect(screen.queryByRole("button", { name: "Open report.md" })).toBeNull();
+ });
+
+ it.each([
+ [
+ "the link belongs to another task",
+ () => {},
+ "other-task-id" as string | undefined,
+ ],
+ [
+ "the artifact is no longer in the manifest",
+ () => {
+ manifest.data = [];
+ },
+ TASK_ID as string | undefined,
+ ],
+ [
+ "the manifest never loads because nobody is signed in",
+ () => {
+ manifest.data = undefined;
+ manifest.isLoading = false;
+ },
+ TASK_ID as string | undefined,
+ ],
+ ])("keeps the plain link when %s", async (_label, mutate, taskId) => {
+ mutate();
+ renderMessage(`Here it is: [report.md](${LEGACY_LINK})`, taskId);
+
+ await waitFor(() => {
+ expect(screen.getByRole("link")).toHaveAttribute("href", LEGACY_LINK);
+ });
+ expect(screen.queryByRole("button", { name: "Open report.md" })).toBeNull();
+ });
+});
diff --git a/products/desktop/packages/ui/src/features/editor/components/ArtifactRefChip.tsx b/products/desktop/packages/ui/src/features/editor/components/ArtifactRefChip.tsx
new file mode 100644
index 000000000000..686a04d33666
--- /dev/null
+++ b/products/desktop/packages/ui/src/features/editor/components/ArtifactRefChip.tsx
@@ -0,0 +1,152 @@
+import { DownloadSimpleIcon } from "@phosphor-icons/react";
+import { usePanelLayoutStore } from "@posthog/ui/features/panels/panelLayoutStore";
+import { useArtifactDownload } from "@posthog/ui/features/sessions/useArtifactDownload";
+import { useRunArtifacts } from "@posthog/ui/features/sessions/useRunArtifacts";
+import { useSessionTaskId } from "@posthog/ui/features/sessions/useSessionTaskId";
+import { FileIcon } from "@posthog/ui/primitives/FileIcon";
+import { Tooltip } from "@posthog/ui/primitives/Tooltip";
+import type { ArtifactLinkTarget } from "@posthog/ui/utils/artifactLinks";
+import { findArtifactForLink } from "@posthog/ui/utils/artifactLinks";
+import { formatFileSize } from "@posthog/ui/utils/formatFileSize";
+import type { ReactNode } from "react";
+
+/**
+ * An artifact reference inside a message: a chip that opens the file in an
+ * artifact tab, with a divided download half for saving it to disk. Supports
+ * stable API links and storage URLs from older messages.
+ *
+ * Renders `fallback` whenever it cannot prove which artifact the link means:
+ * another task, a dismissed artifact, or an ambiguous legacy id prefix.
+ */
+export function ArtifactRefChip({
+ target,
+ href,
+ children,
+ fallback,
+}: {
+ target: ArtifactLinkTarget;
+ href: string;
+ children: ReactNode;
+ fallback: ReactNode;
+}) {
+ const sessionTaskId = useSessionTaskId();
+ // The link carries its own task id, but a message can quote a link from
+ // anywhere. Only a link belonging to the task being viewed is opened in
+ // place — the artifact tab is scoped to this task, and its API calls are
+ // authorized against it.
+ const belongsToSession = sessionTaskId === target.taskId;
+
+ // isLoading rather than isPending: a query that is disabled (signed out) is
+ // pending forever, and a chip that never resolves is worse than a link.
+ const {
+ data: artifacts,
+ isFetching,
+ isLoading,
+ } = useRunArtifacts(target.taskId, target.runId, {
+ enabled: belongsToSession,
+ staleTime: 0,
+ });
+ const artifact = artifacts ? findArtifactForLink(artifacts, target) : null;
+
+ const openArtifactTab = usePanelLayoutStore((state) => state.openArtifactTab);
+ const markdownLabel =
+ typeof children === "string" && children !== href ? children : undefined;
+ const fallbackName =
+ target.kind === "legacy-storage" ? target.fileName : markdownLabel;
+ const displayName = artifact?.name ?? fallbackName;
+ // A bare legacy URL includes the filename, while a stable URL gets its name
+ // from the manifest after the refresh completes.
+ const label =
+ typeof children === "string" && children === href
+ ? (displayName ?? children)
+ : children;
+ const { download, downloadingId } = useArtifactDownload();
+
+ if (!belongsToSession) return <>{fallback}</>;
+ // Resolving: hold the chip's shape so the line doesn't reflow once the
+ // manifest lands, but keep it inert until there is something to open.
+ if (isLoading || (isFetching && !artifact)) {
+ return <ArtifactChipShell label={label} name={displayName} disabled />;
+ }
+ const artifactId = artifact?.id;
+ if (!artifactId) return <>{fallback}</>;
+
+ const name = artifact.name;
+ const sizeLabel = formatFileSize(artifact.size);
+
+ return (
+ <ArtifactChipShell
+ label={label}
+ name={name}
+ sizeLabel={sizeLabel}
+ onOpen={() =>
+ openArtifactTab(target.taskId, {
+ runId: target.runId,
+ artifactId,
+ name,
+ })
+ }
+ onDownload={() => {
+ void download({
+ taskId: target.taskId,
+ runId: target.runId,
+ artifactId,
+ name,
+ });
+ }}
+ downloading={downloadingId === artifactId}
+ />
+ );
+}
+
+/** Presentation only, exported for stories. */
+export function ArtifactChipShell({
+ label,
+ name,
+ sizeLabel,
+ onOpen,
+ onDownload,
+ downloading,
+ disabled,
+}: {
+ label: ReactNode;
+ name?: string;
+ sizeLabel?: string | null;
+ onOpen?: () => void;
+ onDownload?: () => void;
+ downloading?: boolean;
+ disabled?: boolean;
+}) {
+ return (
+ // A span, not a button: this renders inside a paragraph, so the two halves
+ // have to be siblings rather than a button nested in a button.
+ <span className="mx-0.5 inline-flex max-w-full cursor-default items-stretch overflow-hidden rounded-md border border-border bg-muted align-middle text-[0.95em] leading-normal">
+ <button
+ type="button"
+ onClick={onOpen}
+ disabled={disabled || !onOpen}
+ aria-label={name ? `Open ${name}` : undefined}
+ className="flex min-w-0 items-center gap-1 px-1.5 py-0.5 text-left transition-colors enabled:cursor-pointer enabled:hover:bg-gray-3"
+ >
+ {typeof name === "string" && <FileIcon filename={name} size={12} />}
+ <span className="min-w-0 truncate">{label}</span>
+ {sizeLabel && (
+ <span className="shrink-0 text-muted-foreground">{sizeLabel}</span>
+ )}
+ </button>
+ {onDownload && (
+ <Tooltip content={downloading ? "Downloading…" : "Download"}>
+ <button
+ type="button"
+ onClick={onDownload}
+ disabled={downloading}
+ aria-label={name ? `Download ${name}` : "Download"}
+ className="flex shrink-0 items-center self-stretch border-border border-l px-1.5 text-muted-foreground transition-colors enabled:cursor-pointer enabled:hover:bg-gray-3 enabled:hover:text-foreground disabled:opacity-60"
+ >
+ <DownloadSimpleIcon size={12} />
+ </button>
+ </Tooltip>
+ )}
+ </span>
+ );
+}
diff --git a/products/desktop/packages/ui/src/features/editor/components/MarkdownRenderer.tsx b/products/desktop/packages/ui/src/features/editor/components/MarkdownRenderer.tsx
index a5fd7ff14b75..ebd830c2ed01 100644
--- a/products/desktop/packages/ui/src/features/editor/components/MarkdownRenderer.tsx
+++ b/products/desktop/packages/ui/src/features/editor/components/MarkdownRenderer.tsx
@@ -1,10 +1,12 @@
import { isPostHogCodeDeeplink } from "@posthog/shared";
+import { ArtifactRefChip } from "@posthog/ui/features/editor/components/ArtifactRefChip";
import { GithubRefChip } from "@posthog/ui/features/editor/components/GithubRefChip";
import { parseGithubIssueUrl } from "@posthog/ui/features/message-editor/githubIssueUrl";
import { CodeBlock } from "@posthog/ui/primitives/CodeBlock";
import { Divider } from "@posthog/ui/primitives/Divider";
import { HighlightedCode } from "@posthog/ui/primitives/HighlightedCode";
import { List, ListItem } from "@posthog/ui/primitives/List";
+import { parseArtifactLink } from "@posthog/ui/utils/artifactLinks";
import { handleShareLinkClick } from "@posthog/ui/utils/shareLinks";
import { Blockquote, Checkbox, Code, Kbd, Text } from "@radix-ui/themes";
import { memo, useMemo } from "react";
@@ -38,6 +40,53 @@ const HeadingText = ({ children }: { children: React.ReactNode }) => (
</Text>
);
+/** A link that leaves the app, with the trailing external-link glyph. */
+function ExternalMarkdownLink({
+ href,
+ children,
+}: {
+ href: string | undefined;
+ children: React.ReactNode;
+}) {
+ const isDeeplink = isPostHogCodeDeeplink(href);
+ return (
+ <a
+ href={href}
+ onClick={(event) => {
+ if (handleShareLinkClick(href, event)) return;
+ if (!isDeeplink || !href) return;
+ event.preventDefault();
+ openExternalUrl(href);
+ }}
+ target="_blank"
+ rel="noopener noreferrer"
+ className="markdown-link inline-flex items-center gap-[2px]"
+ >
+ {children}
+ <svg
+ width="10"
+ height="10"
+ viewBox="0 0 12 12"
+ fill="none"
+ // Radix accent vars don't reach portalled surfaces (quill dialogs);
+ // without the fallback the glyph draws invisibly, leaving a blank
+ // icon-sized gap after the link.
+ stroke="var(--accent-11, currentColor)"
+ strokeWidth="1.5"
+ strokeLinecap="round"
+ strokeLinejoin="round"
+ aria-label="external link icon"
+ role="img"
+ className="ml-1 shrink-0"
+ >
+ <path d="M4.5 1.5H2.25C1.836 1.5 1.5 1.836 1.5 2.25V9.75C1.5 10.164 1.836 10.5 2.25 10.5H9.75C10.164 10.5 10.5 10.164 10.5 9.75V7.5" />
+ <path d="M7.5 1.5H10.5V4.5" />
+ <path d="M5.25 6.75L10.5 1.5" />
+ </svg>
+ </a>
+ );
+}
+
export const baseComponents: Components = {
h1: ({ children }) => <HeadingText>{children}</HeadingText>,
h2: ({ children }) => <HeadingText>{children}</HeadingText>,
@@ -75,6 +124,20 @@ export const baseComponents: Components = {
<del className="text-(--gray-9) line-through">{children}</del>
),
a: ({ href, children }) => {
+ const artifactTarget = parseArtifactLink(href);
+ if (artifactTarget && href) {
+ return (
+ <ArtifactRefChip
+ target={artifactTarget}
+ href={href}
+ fallback={
+ <ExternalMarkdownLink href={href}>{children}</ExternalMarkdownLink>
+ }
+ >
+ {children}
+ </ArtifactRefChip>
+ );
+ }
const githubRef = href ? parseGithubIssueUrl(href) : null;
if (githubRef) {
const isAutoLink = typeof children === "string" && children === href;
@@ -87,43 +150,7 @@ export const baseComponents: Components = {
</GithubRefChip>
);
}
- const isDeeplink = isPostHogCodeDeeplink(href);
- return (
- <a
- href={href}
- onClick={(event) => {
- if (handleShareLinkClick(href, event)) return;
- if (!isDeeplink || !href) return;
- event.preventDefault();
- openExternalUrl(href);
- }}
- target="_blank"
- rel="noopener noreferrer"
- className="markdown-link inline-flex items-center gap-[2px]"
- >
- {children}
- <svg
- width="10"
- height="10"
- viewBox="0 0 12 12"
- fill="none"
- // Radix accent vars don't reach portalled surfaces (quill dialogs);
- // without the fallback the glyph draws invisibly, leaving a blank
- // icon-sized gap after the link.
- stroke="var(--accent-11, currentColor)"
- strokeWidth="1.5"
- strokeLinecap="round"
- strokeLinejoin="round"
- aria-label="external link icon"
- role="img"
- className="ml-1 shrink-0"
- >
- <path d="M4.5 1.5H2.25C1.836 1.5 1.5 1.836 1.5 2.25V9.75C1.5 10.164 1.836 10.5 2.25 10.5H9.75C10.164 10.5 10.5 10.164 10.5 9.75V7.5" />
- <path d="M7.5 1.5H10.5V4.5" />
- <path d="M5.25 6.75L10.5 1.5" />
- </svg>
- </a>
- );
+ return <ExternalMarkdownLink href={href}>{children}</ExternalMarkdownLink>;
},
kbd: ({ children }) => <Kbd>{children}</Kbd>,
ul: ({ children }) => (
diff --git a/products/desktop/packages/ui/src/features/sessions/components/CloudArtifactDownloads.test.tsx b/products/desktop/packages/ui/src/features/sessions/components/CloudArtifactDownloads.test.tsx
index 062b397a314d..2c80d9d4c081 100644
--- a/products/desktop/packages/ui/src/features/sessions/components/CloudArtifactDownloads.test.tsx
+++ b/products/desktop/packages/ui/src/features/sessions/components/CloudArtifactDownloads.test.tsx
@@ -143,6 +143,47 @@ describe("CloudArtifactDownloads", () => {
);
});
+ it("disables every download while a shared request is in progress", async () => {
+ if (!fetchedArtifacts) throw new Error("artifact fixture must be loaded");
+ const artifacts = fetchedArtifacts;
+ artifacts.push({
+ id: "output-2",
+ name: "summary.txt",
+ type: "output",
+ size: 100,
+ storage_path: "tasks/run-1/summary.txt",
+ });
+ let finishPreviewRequest: (url: null) => void = () => undefined;
+ getCloudAttachmentPreviewUrl.mockReturnValue(
+ new Promise<null>((resolve) => {
+ finishPreviewRequest = resolve;
+ }),
+ );
+
+ try {
+ render(
+ <Theme>
+ <CloudArtifactDownloads taskId="task-1" task={task} />
+ </Theme>,
+ );
+
+ const downloadButtons = screen.getAllByRole("button", {
+ name: "Download",
+ });
+ fireEvent.click(downloadButtons[0]);
+
+ await waitFor(() =>
+ expect(downloadButtons[1]).toHaveAttribute("aria-disabled", "true"),
+ );
+ finishPreviewRequest(null);
+ await waitFor(() =>
+ expect(downloadButtons[1]).toHaveAttribute("aria-disabled", "false"),
+ );
+ } finally {
+ artifacts.pop();
+ }
+ });
+
it("opens an artifact preview in a new tab", () => {
renderDownloads();
diff --git a/products/desktop/packages/ui/src/features/sessions/components/CloudArtifactDownloads.tsx b/products/desktop/packages/ui/src/features/sessions/components/CloudArtifactDownloads.tsx
index ca671edadb82..72a520fe0de6 100644
--- a/products/desktop/packages/ui/src/features/sessions/components/CloudArtifactDownloads.tsx
+++ b/products/desktop/packages/ui/src/features/sessions/components/CloudArtifactDownloads.tsx
@@ -36,12 +36,13 @@ import {
useArtifactFilesCollapsed,
useSessionViewActions,
} from "@posthog/ui/features/sessions/sessionViewStore";
+import { useArtifactDownload } from "@posthog/ui/features/sessions/useArtifactDownload";
import { FileIcon } from "@posthog/ui/primitives/FileIcon";
import { RelativeTimestamp } from "@posthog/ui/primitives/RelativeTimestamp";
import { toast } from "@posthog/ui/primitives/toast";
import { formatFileSize } from "@posthog/ui/utils/formatFileSize";
import { useMutation, useQuery } from "@tanstack/react-query";
-import { useCallback, useEffect, useMemo, useRef, useState } from "react";
+import { useEffect, useMemo, useRef, useState } from "react";
import { createArtifactUploadTracker } from "./countArtifactUploads";
type ArtifactGroup = RunArtifactVersions<TaskRunArtifact>;
@@ -81,7 +82,7 @@ export function CloudArtifactDownloads({
const collapsed = useArtifactFilesCollapsed(taskId);
const { setArtifactFilesCollapsed } = useSessionViewActions();
const authIdentity = useAuthStateValue(getAuthIdentity);
- const [downloadingId, setDownloadingId] = useState<string | null>(null);
+ const { download, downloadingId } = useArtifactDownload();
const [selectedVersionByName, setSelectedVersionByName] = useState<
Record<string, string>
>({});
@@ -172,37 +173,6 @@ export function CloudArtifactDownloads({
onError: () => toast.error("Couldn't update this file"),
});
- const downloadArtifact = useCallback(
- async (artifact: TaskRunArtifact): Promise<void> => {
- if (!taskId || !runId || !artifact.id) return;
- setDownloadingId(artifact.id);
- try {
- const url = await sessionService.getCloudAttachmentPreviewUrl(
- taskId,
- runId,
- artifact.id,
- );
- if (!url) {
- toast.error("This file is no longer available");
- return;
- }
- const response = await fetch(url);
- if (!response.ok) throw new Error("Artifact download failed");
- const objectUrl = URL.createObjectURL(await response.blob());
- const anchor = document.createElement("a");
- anchor.href = objectUrl;
- anchor.download = artifact.name;
- anchor.click();
- URL.revokeObjectURL(objectUrl);
- } catch {
- toast.error("Couldn't download file");
- } finally {
- setDownloadingId(null);
- }
- },
- [runId, sessionService, taskId],
- );
-
if (!runId || groups.length === 0) return null;
const renderRow = (group: ArtifactGroup) => {
@@ -290,8 +260,16 @@ export function CloudArtifactDownloads({
<Button
size="sm"
variant="outline"
- disabled={!canDownload || downloadingId === selected.id}
- onClick={() => void downloadArtifact(selected)}
+ disabled={!canDownload || downloadingId !== null}
+ onClick={() => {
+ if (!taskId || !selected.id) return;
+ void download({
+ taskId,
+ runId,
+ artifactId: selected.id,
+ name: selected.name,
+ });
+ }}
>
<DownloadSimple size={14} />
{downloadingId === selected.id ? "Opening..." : "Download"}
diff --git a/products/desktop/packages/ui/src/features/sessions/components/chat-thread/ChatMarkdown.tsx b/products/desktop/packages/ui/src/features/sessions/components/chat-thread/ChatMarkdown.tsx
index c1429bb7160c..9b877fd5c1e6 100644
--- a/products/desktop/packages/ui/src/features/sessions/components/chat-thread/ChatMarkdown.tsx
+++ b/products/desktop/packages/ui/src/features/sessions/components/chat-thread/ChatMarkdown.tsx
@@ -10,6 +10,7 @@ import {
TableRow,
Text,
} from "@posthog/quill";
+import { ArtifactRefChip } from "@posthog/ui/features/editor/components/ArtifactRefChip";
import {
markOpenLinkDestination,
parseOpenFence,
@@ -23,6 +24,7 @@ import {
} from "@posthog/ui/features/sessions/components/session-update/fileLinkChips";
import { HighlightedCode } from "@posthog/ui/primitives/HighlightedCode";
import { useCopy } from "@posthog/ui/primitives/useCopy";
+import { parseArtifactLink } from "@posthog/ui/utils/artifactLinks";
import { IconButton } from "@radix-ui/themes";
import { memo, type ReactNode, useMemo } from "react";
import Markdown, { type Components } from "react-markdown";
@@ -81,7 +83,7 @@ const components: Components = {
</output>
);
}
- return (
+ const link = (
<a
href={href}
target="_blank"
@@ -91,6 +93,13 @@ const components: Components = {
{children}
</a>
);
+ const artifactTarget = parseArtifactLink(href);
+ if (!artifactTarget || !href) return link;
+ return (
+ <ArtifactRefChip target={artifactTarget} href={href} fallback={link}>
+ {children}
+ </ArtifactRefChip>
+ );
},
img: ({ alt }) => (
<Text className="text-muted-foreground text-sm">
diff --git a/products/desktop/packages/ui/src/features/sessions/useArtifactDownload.ts b/products/desktop/packages/ui/src/features/sessions/useArtifactDownload.ts
new file mode 100644
index 000000000000..38fcb1edc792
--- /dev/null
+++ b/products/desktop/packages/ui/src/features/sessions/useArtifactDownload.ts
@@ -0,0 +1,63 @@
+import {
+ SESSION_SERVICE,
+ type SessionService,
+} from "@posthog/core/sessions/sessionService";
+import { useService } from "@posthog/di/react";
+import { toast } from "@posthog/ui/primitives/toast";
+import { useCallback, useState } from "react";
+
+export interface ArtifactDownloadRef {
+ taskId: string;
+ runId: string;
+ artifactId: string;
+ name: string;
+}
+
+export interface ArtifactDownload {
+ download: (ref: ArtifactDownloadRef) => Promise<void>;
+ /** Artifact id currently being fetched. Shared lists must disable every download until it clears. */
+ downloadingId: string | null;
+}
+
+/**
+ * Save a task-run artifact to disk. The link an artifact was rendered from is
+ * presigned and short-lived, so every download mints a fresh URL through the
+ * API instead of reusing it.
+ */
+export function useArtifactDownload(): ArtifactDownload {
+ const sessionService = useService<SessionService>(SESSION_SERVICE);
+ const [downloadingId, setDownloadingId] = useState<string | null>(null);
+
+ const download = useCallback(
+ async (ref: ArtifactDownloadRef) => {
+ if (downloadingId !== null) return;
+ setDownloadingId(ref.artifactId);
+ try {
+ const url = await sessionService.getCloudAttachmentPreviewUrl(
+ ref.taskId,
+ ref.runId,
+ ref.artifactId,
+ );
+ if (!url) {
+ toast.error("This file is no longer available");
+ return;
+ }
+ const response = await fetch(url);
+ if (!response.ok) throw new Error("Artifact download failed");
+ const objectUrl = URL.createObjectURL(await response.blob());
+ const anchor = document.createElement("a");
+ anchor.href = objectUrl;
+ anchor.download = ref.name;
+ anchor.click();
+ URL.revokeObjectURL(objectUrl);
+ } catch {
+ toast.error("Couldn't download file");
+ } finally {
+ setDownloadingId(null);
+ }
+ },
+ [downloadingId, sessionService],
+ );
+
+ return { download, downloadingId };
+}
diff --git a/products/desktop/packages/ui/src/features/sessions/useRunArtifacts.ts b/products/desktop/packages/ui/src/features/sessions/useRunArtifacts.ts
new file mode 100644
index 000000000000..6bb9f401d62c
--- /dev/null
+++ b/products/desktop/packages/ui/src/features/sessions/useRunArtifacts.ts
@@ -0,0 +1,37 @@
+import {
+ SESSION_SERVICE,
+ type SessionService,
+} from "@posthog/core/sessions/sessionService";
+import { useService } from "@posthog/di/react";
+import type { TaskRunArtifact } from "@posthog/shared";
+import {
+ getAuthIdentity,
+ useAuthStateValue,
+} from "@posthog/ui/features/auth/store";
+import { type UseQueryResult, useQuery } from "@tanstack/react-query";
+
+/**
+ * A run's artifact manifest. The query key is shared across every caller, so a
+ * message referencing several artifacts — or a message rendered next to the
+ * Files list — costs one fetch rather than one per reference.
+ */
+export function useRunArtifacts(
+ taskId: string | undefined,
+ runId: string | undefined,
+ options?: { enabled?: boolean; staleTime?: number },
+): UseQueryResult<TaskRunArtifact[]> {
+ const sessionService = useService<SessionService>(SESSION_SERVICE);
+ const authIdentity = useAuthStateValue(getAuthIdentity);
+ return useQuery({
+ queryKey: ["cloudRunArtifacts", authIdentity, taskId, runId],
+ queryFn: () =>
+ sessionService.getCloudRunArtifacts(taskId ?? "", runId ?? ""),
+ enabled:
+ authIdentity !== null &&
+ taskId !== undefined &&
+ runId !== undefined &&
+ (options?.enabled ?? true),
+ retry: false,
+ staleTime: options?.staleTime ?? Infinity,
+ });
+}
diff --git a/products/desktop/packages/ui/src/utils/artifactLinks.test.ts b/products/desktop/packages/ui/src/utils/artifactLinks.test.ts
new file mode 100644
index 000000000000..f2c3d590c7ca
--- /dev/null
+++ b/products/desktop/packages/ui/src/utils/artifactLinks.test.ts
@@ -0,0 +1,117 @@
+import {
+ findArtifactForLink,
+ parseArtifactLink,
+} from "@posthog/ui/utils/artifactLinks";
+import { describe, expect, it } from "vitest";
+
+const TASK_ID = "3f1c2b6a-1111-4222-8333-444455556666";
+const RUN_ID = "9a8b7c6d-5555-4666-8777-888899990000";
+const ARTIFACT_ID = "1a2b3c4d-2222-4333-8444-555566667777";
+const KEY = `posthog-tasks/artifacts/team_2/task_${TASK_ID}/run_${RUN_ID}/1a2b3c4d_report.md`;
+const STABLE_LINK = `https://app.posthog.com/api/projects/2/tasks/${TASK_ID}/runs/${RUN_ID}/artifacts/${ARTIFACT_ID}/download/`;
+
+describe("parseArtifactLink", () => {
+ it.each([
+ [
+ "presigned url",
+ `https://bucket.s3.amazonaws.com/${KEY}?X-Amz-Signature=abc`,
+ ],
+ [
+ "path-style url with the bucket in the path",
+ `https://s3.eu-west-1.amazonaws.com/ph-bucket/${KEY}`,
+ ],
+ [
+ "percent-encoded path",
+ `https://bucket.s3.amazonaws.com/${KEY.replace("report.md", "report%20final.md")}`,
+ ],
+ ])("reads task, run, and artifact prefix from a %s", (_label, href) => {
+ expect(parseArtifactLink(href)).toMatchObject({
+ kind: "legacy-storage",
+ taskId: TASK_ID,
+ runId: RUN_ID,
+ artifactIdPrefix: "1a2b3c4d",
+ });
+ });
+
+ it("reads the full artifact id from a stable download url", () => {
+ expect(parseArtifactLink(STABLE_LINK)).toEqual({
+ kind: "stable",
+ taskId: TASK_ID,
+ runId: RUN_ID,
+ artifactId: ARTIFACT_ID,
+ });
+ });
+
+ it.each([
+ ["a non-artifact url", "https://posthog.com/docs"],
+ ["a github link", "https://github.com/PostHog/posthog/issues/1"],
+ [
+ "an artifacts path missing the run segment",
+ `https://bucket.s3.amazonaws.com/artifacts/team_2/task_${TASK_ID}/1a2b3c4d_report.md`,
+ ],
+ [
+ "an object name without an id prefix",
+ `https://bucket.s3.amazonaws.com/artifacts/team_2/task_${TASK_ID}/run_${RUN_ID}/report.md`,
+ ],
+ [
+ "a non-http scheme",
+ `posthog-code://artifacts/team_2/task_${TASK_ID}/run_${RUN_ID}/1a2b3c4d_report.md`,
+ ],
+ [
+ "a stable route missing the artifact id",
+ `https://app.posthog.com/api/projects/2/tasks/${TASK_ID}/runs/${RUN_ID}/artifacts/download/`,
+ ],
+ [
+ "a different task API route",
+ `https://app.posthog.com/api/projects/2/tasks/${TASK_ID}/runs/${RUN_ID}/artifacts/${ARTIFACT_ID}/presign/`,
+ ],
+ ["an unparseable href", "not a url"],
+ ])("returns null for %s", (_label, href) => {
+ expect(parseArtifactLink(href)).toBeNull();
+ });
+});
+
+describe("findArtifactForLink", () => {
+ const target = parseArtifactLink(`https://bucket.s3.amazonaws.com/${KEY}`);
+ if (target?.kind !== "legacy-storage") {
+ throw new Error("fixture link must parse as legacy storage");
+ }
+
+ it("matches a stable link by the full artifact id", () => {
+ const stableTarget = parseArtifactLink(STABLE_LINK);
+ if (!stableTarget) throw new Error("stable fixture link must parse");
+ const artifacts = [
+ { id: "1a2b3c4d-9999-4222-8333-444455556666" },
+ { id: ARTIFACT_ID },
+ ];
+
+ expect(findArtifactForLink(artifacts, stableTarget)).toBe(artifacts[1]);
+ });
+
+ it("matches on the exact storage path", () => {
+ const artifacts = [
+ { id: "0000ffff-1111-4222-8333-444455556666", storage_path: "other/key" },
+ { id: "1a2b3c4d-1111-4222-8333-444455556666", storage_path: KEY },
+ ];
+ expect(findArtifactForLink(artifacts, target)?.storage_path).toBe(KEY);
+ });
+
+ it("falls back to the id prefix when the manifest has no storage path", () => {
+ const artifacts = [{ id: "1A2B3C4D-1111-4222-8333-444455556666" }];
+ expect(findArtifactForLink(artifacts, target)).toBe(artifacts[0]);
+ });
+
+ it("refuses an ambiguous id prefix rather than opening the wrong file", () => {
+ const artifacts = [
+ { id: "1a2b3c4d-1111-4222-8333-444455556666" },
+ { id: "1a2b3c4d-9999-4222-8333-444455556666" },
+ ];
+ expect(findArtifactForLink(artifacts, target)).toBeNull();
+ });
+
+ it("returns null when the artifact is gone from the manifest", () => {
+ expect(
+ findArtifactForLink([{ id: "abcd0000", storage_path: "x" }], target),
+ ).toBeNull();
+ });
+});
diff --git a/products/desktop/packages/ui/src/utils/artifactLinks.ts b/products/desktop/packages/ui/src/utils/artifactLinks.ts
new file mode 100644
index 000000000000..36327e2ffa07
--- /dev/null
+++ b/products/desktop/packages/ui/src/utils/artifactLinks.ts
@@ -0,0 +1,133 @@
+/**
+ * Recognizing task-artifact links inside agent messages.
+ *
+ * New uploads use an authenticated PostHog download URL containing the task,
+ * run, and full artifact id. Existing messages can instead contain a presigned
+ * or unsigned object-storage URL. Both forms need to open the artifact tab
+ * rather than leave the app, so the parser retains the legacy storage-key path
+ * alongside the stable API path.
+ */
+
+const ID_SEGMENT_RE = /^[0-9a-fA-F-]{8,}$/;
+const TEAM_SEGMENT_RE = /^team_\d+$/;
+const TASK_SEGMENT_RE = /^task_([0-9a-fA-F-]{8,})$/;
+const RUN_SEGMENT_RE = /^run_([0-9a-fA-F-]{8,})$/;
+const OBJECT_SEGMENT_RE = /^([0-9a-fA-F]{8})_(.+)$/;
+
+export type ArtifactLinkTarget =
+ | {
+ kind: "stable";
+ taskId: string;
+ runId: string;
+ artifactId: string;
+ }
+ | {
+ kind: "legacy-storage";
+ taskId: string;
+ runId: string;
+ /** First 8 characters of the artifact id, the only part the key carries. */
+ artifactIdPrefix: string;
+ /** Storage-safe filename from the key; the display label may differ. */
+ fileName: string;
+ };
+
+function decodeSegment(segment: string): string {
+ try {
+ return decodeURIComponent(segment);
+ } catch {
+ return segment;
+ }
+}
+
+/** Parse a stable API or legacy storage URL into an in-app artifact target. */
+export function parseArtifactLink(
+ href: string | undefined,
+): ArtifactLinkTarget | null {
+ if (!href) return null;
+
+ let url: URL;
+ try {
+ url = new URL(href);
+ } catch {
+ return null;
+ }
+ if (url.protocol !== "https:" && url.protocol !== "http:") return null;
+
+ const segments = url.pathname.split("/").filter(Boolean).map(decodeSegment);
+ for (let index = 0; index + 9 < segments.length; index++) {
+ if (
+ segments[index] !== "api" ||
+ segments[index + 1] !== "projects" ||
+ segments[index + 3] !== "tasks" ||
+ segments[index + 5] !== "runs" ||
+ segments[index + 7] !== "artifacts" ||
+ segments[index + 9] !== "download" ||
+ index + 10 !== segments.length
+ ) {
+ continue;
+ }
+
+ const taskId = segments[index + 4];
+ const runId = segments[index + 6];
+ const artifactId = segments[index + 8];
+ if (
+ !ID_SEGMENT_RE.test(taskId) ||
+ !ID_SEGMENT_RE.test(runId) ||
+ !ID_SEGMENT_RE.test(artifactId)
+ ) {
+ continue;
+ }
+
+ return { kind: "stable", taskId, runId, artifactId };
+ }
+
+ // The storage folder prefix varies by deployment, and path-style S3 URLs
+ // carry the bucket as a leading segment, so locate the marker dynamically.
+ for (let index = 0; index + 4 < segments.length; index++) {
+ if (segments[index] !== "artifacts") continue;
+ if (!TEAM_SEGMENT_RE.test(segments[index + 1])) continue;
+
+ const task = TASK_SEGMENT_RE.exec(segments[index + 2]);
+ const run = RUN_SEGMENT_RE.exec(segments[index + 3]);
+ const object = OBJECT_SEGMENT_RE.exec(segments[index + 4]);
+ if (!task || !run || !object) continue;
+
+ return {
+ kind: "legacy-storage",
+ taskId: task[1],
+ runId: run[1],
+ artifactIdPrefix: object[1].toLowerCase(),
+ fileName: object[2],
+ };
+ }
+
+ return null;
+}
+
+/** Match stable links by full id and legacy links by storage key or id prefix. */
+export function findArtifactForLink<
+ T extends { id?: string; storage_path?: string },
+>(artifacts: readonly T[], target: ArtifactLinkTarget): T | null {
+ if (target.kind === "stable") {
+ return (
+ artifacts.find(
+ (artifact) =>
+ artifact.id?.toLowerCase() === target.artifactId.toLowerCase(),
+ ) ?? null
+ );
+ }
+
+ const keySuffix = `/${target.artifactIdPrefix}_${target.fileName}`;
+ const byPath = artifacts.find((artifact) =>
+ artifact.storage_path?.endsWith(keySuffix),
+ );
+ if (byPath) return byPath;
+
+ const matchingIds = artifacts.filter((artifact) =>
+ artifact.id?.toLowerCase().startsWith(target.artifactIdPrefix),
+ );
+ // An 8-character prefix is not a guarantee of uniqueness. Two matches mean we
+ // cannot tell which file the link meant, and opening the wrong one is worse
+ // than leaving the link alone.
+ return matchingIds.length === 1 ? matchingIds[0] : null;
+}