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.

feat(desktop): edit text artifacts and overhaul the artifact pane (#79723)

Shy Alter31f2a9084504
diff --git a/products/desktop/docs/cloud-task-artifacts.md b/products/desktop/docs/cloud-task-artifacts.md
index 0af8971d7df8..27bcfc757e84 100644
--- a/products/desktop/docs/cloud-task-artifacts.md
+++ b/products/desktop/docs/cloud-task-artifacts.md
@@ -12,6 +12,8 @@ The desktop app runs scripts embedded in HTML artifacts inside an isolated previ
## Versions and dismissal
-Uploading a file under a name the run already has does not add a second file. Every upload stays on the manifest as its own entry, and clients group entries by name into one file with a version history: the newest upload is what the app shows, and the earlier ones sit behind a version picker on the row. That is how an agent revises a deliverable — upload it again under the same name.
+Uploading a file under a name the run already has does not add a second file. Every upload stays on the manifest as its own entry, and clients group entries by name into one file with a version history: the newest upload is what the app shows, and the earlier ones sit behind a version picker on the row. An agent revises a deliverable by reading the current latest version, then uploading its revision under the same name.
+
+Users can edit the latest Markdown, HTML, and plain-text version in the app. Saving appends another `output` entry under the same name. It never overwrites the version the user opened, and a confirmation appears if another version arrived during the edit.
A user can dismiss a file they don't want to see. `POST .../runs/<run_id>/artifacts/dismiss/` takes `artifact_ids` and a `dismissed` boolean, and stamps `dismissed_at` on each named manifest entry. Nothing is deleted from object storage, and clients only hide a file once every version of it is dismissed, so dismissing the current version cannot resurface the one it replaced. Passing `dismissed: false` restores the file.
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 bf2cadd4cae8..b943b14ffc8c 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
@@ -17,8 +17,8 @@ export const uploadArtifactTool = defineLocalTool({
"Deliver a file you created to the user as a downloadable task artifact. " +
"Call this for every non-code deliverable (reports, images, archives, data files, and similar output) " +
"before your final response. The file must be inside the session workspace. Repository changes belong in git and should not be uploaded. " +
- "To revise a file you already delivered, upload it again under the same name: the app shows the newest version " +
- "and keeps the earlier ones available. " +
+ "To revise a file you already delivered, read its current latest version first because the user may have edited it, " +
+ "then upload your revision under the same name. The app shows the newest version and keeps the earlier ones available. " +
"On success the result includes a download URL for the uploaded file, which you can reference in your final response.",
schema: {
path: z
diff --git a/products/desktop/packages/api-client/src/posthog-client.ts b/products/desktop/packages/api-client/src/posthog-client.ts
index e19463353303..0edc0c33e57b 100644
--- a/products/desktop/packages/api-client/src/posthog-client.ts
+++ b/products/desktop/packages/api-client/src/posthog-client.ts
@@ -677,7 +677,7 @@ export class FolderInstructionsConflictError extends Error {
export interface TaskArtifactUploadRequest {
name: string;
- type: "user_attachment" | "skill_bundle";
+ type: "output" | "user_attachment" | "skill_bundle";
size: number;
content_type?: string;
source?: string;
@@ -706,6 +706,8 @@ export interface FinalizedTaskArtifactUpload {
metadata?: TaskArtifactUploadRequest["metadata"];
storage_path: string;
uploaded_at?: string;
+ uploaded_by?: "agent" | "user";
+ uploaded_by_user_id?: number;
}
export interface CloudRunOptions {
diff --git a/products/desktop/packages/api-client/src/task-normalization.test.ts b/products/desktop/packages/api-client/src/task-normalization.test.ts
index 7c041052534a..928b641a9da3 100644
--- a/products/desktop/packages/api-client/src/task-normalization.test.ts
+++ b/products/desktop/packages/api-client/src/task-normalization.test.ts
@@ -28,6 +28,8 @@ describe("task response normalization", () => {
type: "legacy_type",
storage_path: "tasks/result.txt",
uploaded_at: "2026-07-21T00:00:00Z",
+ uploaded_by: "user",
+ uploaded_by_user_id: 42,
},
],
created_at: "2026-07-21T00:00:00Z",
@@ -57,6 +59,8 @@ describe("task response normalization", () => {
type: "artifact",
storage_path: "tasks/result.txt",
uploaded_at: "2026-07-21T00:00:00Z",
+ uploaded_by: "user",
+ uploaded_by_user_id: 42,
},
],
created_at: "2026-07-21T00:00:00Z",
diff --git a/products/desktop/packages/api-client/src/task-normalization.ts b/products/desktop/packages/api-client/src/task-normalization.ts
index b223b4c3cfde..83917c1c857c 100644
--- a/products/desktop/packages/api-client/src/task-normalization.ts
+++ b/products/desktop/packages/api-client/src/task-normalization.ts
@@ -10,6 +10,9 @@ import type { Schemas } from "./generated";
export type TaskRunArtifactDTO = Schemas.TaskRunArtifactResponse & {
metadata?: unknown;
+ uploaded_by?: "agent" | "user";
+ uploaded_by_user_id?: number;
+ dismissed_at?: string | null;
};
type TaskRunResponseDTO = Partial<
@@ -128,6 +131,12 @@ export function normalizeTaskRunArtifact(
...(artifact.uploaded_at === undefined
? {}
: { uploaded_at: artifact.uploaded_at }),
+ ...(artifact.uploaded_by === undefined
+ ? {}
+ : { uploaded_by: artifact.uploaded_by }),
+ ...(artifact.uploaded_by_user_id === undefined
+ ? {}
+ : { uploaded_by_user_id: artifact.uploaded_by_user_id }),
...(artifact.dismissed_at === undefined
? {}
: { dismissed_at: artifact.dismissed_at }),
diff --git a/products/desktop/packages/core/src/canvas/runArtifactSchemas.test.ts b/products/desktop/packages/core/src/canvas/runArtifactSchemas.test.ts
index 0441e2b80eb5..cb81f4ce1ca6 100644
--- a/products/desktop/packages/core/src/canvas/runArtifactSchemas.test.ts
+++ b/products/desktop/packages/core/src/canvas/runArtifactSchemas.test.ts
@@ -36,6 +36,8 @@ describe("parseRunArtifacts", () => {
size: 16861,
content_type: "text/markdown",
uploaded_at: "2026-07-27T08:27:26.896719+00:00",
+ uploaded_by: "user" as const,
+ uploaded_by_user_id: 42,
};
expect(parseRunArtifacts([artifact], OUTPUT_ARTIFACT_TYPES)).toEqual([
artifact,
diff --git a/products/desktop/packages/core/src/canvas/runArtifactSchemas.ts b/products/desktop/packages/core/src/canvas/runArtifactSchemas.ts
index 37230862b2a4..268808243ffe 100644
--- a/products/desktop/packages/core/src/canvas/runArtifactSchemas.ts
+++ b/products/desktop/packages/core/src/canvas/runArtifactSchemas.ts
@@ -8,6 +8,8 @@ export const runArtifactSchema = z.object({
content_type: z.string().optional(),
storage_path: z.string().optional(),
uploaded_at: z.string().optional(),
+ uploaded_by: z.enum(["agent", "user"]).optional(),
+ uploaded_by_user_id: z.number().int().optional(),
dismissed_at: z.string().nullish(),
});
export type RunArtifact = z.infer<typeof runArtifactSchema>;
diff --git a/products/desktop/packages/core/src/sessions/cloudArtifactIdentifiers.ts b/products/desktop/packages/core/src/sessions/cloudArtifactIdentifiers.ts
index 69b1f9011657..7961638a82ef 100644
--- a/products/desktop/packages/core/src/sessions/cloudArtifactIdentifiers.ts
+++ b/products/desktop/packages/core/src/sessions/cloudArtifactIdentifiers.ts
@@ -5,7 +5,7 @@ import type {
export interface CloudArtifactUploadRequest {
name: string;
- type: "user_attachment" | "skill_bundle";
+ type: "output" | "user_attachment" | "skill_bundle";
size: number;
content_type?: string;
source?: string;
diff --git a/products/desktop/packages/core/src/sessions/cloudArtifactService.test.ts b/products/desktop/packages/core/src/sessions/cloudArtifactService.test.ts
index d76644491c46..7a5fab6e30d9 100644
--- a/products/desktop/packages/core/src/sessions/cloudArtifactService.test.ts
+++ b/products/desktop/packages/core/src/sessions/cloudArtifactService.test.ts
@@ -134,6 +134,66 @@ describe("CloudArtifactService", () => {
fetchMock.mockRestore();
});
+ it("appends edited text as an output artifact with the same name and content type", async () => {
+ const fetchMock = vi
+ .spyOn(globalThis, "fetch")
+ .mockResolvedValue({ ok: true } as Response);
+ const service = new CloudArtifactService(
+ vi.fn(),
+ bundleLocalSkill,
+ passthroughDeps,
+ );
+ const client = makeClient();
+ (
+ client.prepareTaskRunArtifactUploads as ReturnType<typeof vi.fn>
+ ).mockResolvedValue([
+ {
+ id: "prep-1",
+ name: "report.md",
+ type: "output",
+ size: 16,
+ content_type: "text/markdown",
+ presigned_post: { url: "https://s3/upload", fields: { key: "k" } },
+ },
+ ]);
+ (
+ client.finalizeTaskRunArtifactUploads as ReturnType<typeof vi.fn>
+ ).mockResolvedValue([{ id: "artifact-2" }]);
+
+ const id = await service.uploadRunOutput(
+ client,
+ "task-1",
+ "run-1",
+ "report.md",
+ "# Edited by user",
+ "text/markdown",
+ );
+
+ expect(id).toBe("artifact-2");
+ expect(client.prepareTaskRunArtifactUploads).toHaveBeenCalledWith(
+ "task-1",
+ "run-1",
+ [
+ {
+ name: "report.md",
+ type: "output",
+ size: 16,
+ content_type: "text/markdown",
+ },
+ ],
+ );
+ expect(fetchMock).toHaveBeenCalledWith(
+ "https://s3/upload",
+ expect.objectContaining({ method: "POST", body: expect.any(FormData) }),
+ );
+ expect(client.finalizeTaskRunArtifactUploads).toHaveBeenCalledWith(
+ "task-1",
+ "run-1",
+ [expect.objectContaining({ id: "prep-1", name: "report.md" })],
+ );
+ fetchMock.mockRestore();
+ });
+
it("uploads local skill bundles as skill bundle artifacts", async () => {
const fetchMock = vi
.spyOn(globalThis, "fetch")
diff --git a/products/desktop/packages/core/src/sessions/cloudArtifactService.ts b/products/desktop/packages/core/src/sessions/cloudArtifactService.ts
index 8769c7f30557..ea619df5679a 100644
--- a/products/desktop/packages/core/src/sessions/cloudArtifactService.ts
+++ b/products/desktop/packages/core/src/sessions/cloudArtifactService.ts
@@ -158,6 +158,43 @@ export class CloudArtifactService {
return finalizedArtifacts.map((artifact) => artifact.id);
}
+ async uploadRunOutput(
+ client: CloudArtifactClient,
+ taskId: string,
+ runId: string,
+ name: string,
+ content: string,
+ contentType?: string,
+ ): Promise<string> {
+ const bytes = new TextEncoder().encode(content);
+ const attachment: LoadedCloudAttachment = {
+ filePath: name,
+ bytes,
+ upload: {
+ name,
+ type: "output",
+ size: bytes.byteLength,
+ ...(contentType ? { content_type: contentType } : {}),
+ },
+ };
+ const preparedArtifacts = await client.prepareTaskRunArtifactUploads(
+ taskId,
+ runId,
+ [attachment.upload],
+ );
+ await this.uploadPreparedArtifacts([attachment], preparedArtifacts);
+ const finalizedArtifacts = await client.finalizeTaskRunArtifactUploads(
+ taskId,
+ runId,
+ preparedArtifacts,
+ );
+ const finalizedArtifact = finalizedArtifacts[0];
+ if (!finalizedArtifact) {
+ throw new Error("Artifact upload was not finalized");
+ }
+ return finalizedArtifact.id;
+ }
+
async uploadRunAttachments(
client: CloudArtifactClient,
taskId: string,
diff --git a/products/desktop/packages/core/src/sessions/sessionService.ts b/products/desktop/packages/core/src/sessions/sessionService.ts
index b79333c7e49d..c52c3c8dd8a7 100644
--- a/products/desktop/packages/core/src/sessions/sessionService.ts
+++ b/products/desktop/packages/core/src/sessions/sessionService.ts
@@ -309,6 +309,14 @@ export interface SessionServiceHelpers {
combineQueuedCloudPrompts: (...args: any[]) => any;
getCloudPromptTransport: (...args: any[]) => any;
resolveLocalSkillCommandPrompt?: (prompt: string) => Promise<string | null>;
+ uploadRunOutput: (
+ client: CloudArtifactClient,
+ taskId: string,
+ runId: string,
+ name: string,
+ content: string,
+ contentType?: string,
+ ) => Promise<string>;
uploadRunAttachments: (
client: CloudArtifactClient,
taskId: string,
@@ -7578,6 +7586,28 @@ export class SessionService {
);
}
+ async uploadCloudRunArtifactVersion(
+ taskId: string,
+ runId: string,
+ name: string,
+ content: string,
+ contentType?: string,
+ ): Promise<string> {
+ const authStatus = await this.getAuthCredentialsStatus();
+ if (authStatus.kind !== "ready") {
+ throw new Error("Not signed in to PostHog");
+ }
+
+ return this.d.h.uploadRunOutput(
+ authStatus.auth.client,
+ taskId,
+ runId,
+ name,
+ content,
+ contentType,
+ );
+ }
+
async setCloudRunArtifactsDismissed(
taskId: string,
runId: string,
diff --git a/products/desktop/packages/shared/src/domain-types.ts b/products/desktop/packages/shared/src/domain-types.ts
index 8d7d09f6bbe4..99406cb3f849 100644
--- a/products/desktop/packages/shared/src/domain-types.ts
+++ b/products/desktop/packages/shared/src/domain-types.ts
@@ -259,6 +259,8 @@ export interface TaskRunArtifact {
metadata?: TaskRunArtifactMetadata;
storage_path?: string;
uploaded_at?: string;
+ uploaded_by?: "agent" | "user";
+ uploaded_by_user_id?: number;
dismissed_at?: string | null;
}
diff --git a/products/desktop/packages/ui/src/features/canvas/components/TaskArtifactsList.test.tsx b/products/desktop/packages/ui/src/features/canvas/components/TaskArtifactsList.test.tsx
index fb6fdaf92691..970326552f36 100644
--- a/products/desktop/packages/ui/src/features/canvas/components/TaskArtifactsList.test.tsx
+++ b/products/desktop/packages/ui/src/features/canvas/components/TaskArtifactsList.test.tsx
@@ -14,6 +14,8 @@ const mocks = vi.hoisted(() => ({
openExternalUrl: vi.fn(),
getCloudAttachmentPreviewUrl: vi.fn(),
commentsError: false,
+ sessionEvents: [] as unknown[],
+ taskRunsRefreshKeys: [] as number[],
}));
vi.mock("@posthog/ui/features/sessions/useCommentsEnabled", () => ({
@@ -33,8 +35,19 @@ vi.mock("@posthog/ui/shell/openExternal", () => ({
openExternalUrl: (url: string) => mocks.openExternalUrl(url),
}));
+vi.mock("@posthog/ui/features/auth/useMeQuery", () => ({
+ useMeQuery: () => ({ data: { id: 42, first_name: "Sam" } }),
+}));
vi.mock("@posthog/ui/features/canvas/hooks/useTaskRuns", () => ({
- useTaskRuns: () => ({ runs: mocks.runs, isLoading: false }),
+ useTaskRuns: (_taskId: string | undefined, refreshKey = 0) => {
+ mocks.taskRunsRefreshKeys.push(refreshKey);
+ return { runs: mocks.runs, isLoading: false };
+ },
+}));
+
+vi.mock("@posthog/ui/features/sessions/sessionStore", () => ({
+ useSessionSelector: (_taskId: string, select: (s: unknown) => unknown) =>
+ select({ events: mocks.sessionEvents }),
}));
vi.mock("@posthog/ui/features/panels/panelLayoutStore", () => ({
usePanelLayoutStore: () => mocks.openArtifactTab,
@@ -121,6 +134,8 @@ function outputFile(
describe("TaskArtifactsList", () => {
beforeEach(() => {
mocks.commentsError = false;
+ mocks.sessionEvents = [];
+ mocks.taskRunsRefreshKeys = [];
mocks.runs = [run("run-1", { prNumber: 1 }), run("run-2", { prNumber: 2 })];
mocks.openArtifactTab.mockReset();
mocks.openExternalUrl.mockReset();
@@ -184,10 +199,10 @@ describe("TaskArtifactsList", () => {
render(<TaskArtifactsList task={task} timeline={[]} />);
- const row = screen.getByText("report.md").closest("button");
+ const row = screen.getByText("report.md").closest("[data-artifact-card]");
expect(row).not.toBeNull();
expect(within(row as HTMLElement).getByText("2")).toBeTruthy();
- expect(within(row as HTMLElement).getByText("File · 17 KB")).toBeTruthy();
+ expect(within(row as HTMLElement).getByText("Agent · 17 KB")).toBeTruthy();
});
it("keeps artifacts visible when comment counts fail", () => {
@@ -199,7 +214,7 @@ describe("TaskArtifactsList", () => {
render(<TaskArtifactsList task={task} timeline={[]} />);
expect(screen.getByText("report.md")).toBeInTheDocument();
- expect(screen.getByText("File · 17 KB")).toBeInTheDocument();
+ expect(screen.getByText("Agent · 17 KB")).toBeInTheDocument();
});
// The threads themselves live in the Comments tab now, so the pane must not
@@ -302,7 +317,7 @@ describe("TaskArtifactsList", () => {
});
// Agents revise a deliverable and upload it again under the same name.
- it("keeps only the newest upload of a repeatedly revised file", () => {
+ it("shows the newest upload with earlier versions behind a picker", () => {
mocks.runs = [
run("run-1", {
artifacts: [
@@ -324,7 +339,69 @@ describe("TaskArtifactsList", () => {
render(<TaskArtifactsList task={task} timeline={[]} />);
expect(screen.getAllByText("report.md")).toHaveLength(1);
- expect(screen.getByText("File · 2 KB")).toBeInTheDocument();
+ expect(screen.getByText(/ · 2 KB$/)).toBeInTheDocument();
+ expect(
+ screen.getByLabelText("Choose a version of report.md"),
+ ).toHaveTextContent("v2");
+
+ fireEvent.click(screen.getByLabelText("Choose a version of report.md"));
+ fireEvent.click(screen.getByText(/^v1 · Agent ·/));
+ fireEvent.click(screen.getByText("report.md"));
+
+ expect(mocks.openArtifactTab).toHaveBeenCalledWith("task-1", {
+ runId: "run-1",
+ artifactId: "a",
+ name: "report.md",
+ });
+ });
+
+ it("names the current user on a version they edited", () => {
+ mocks.runs = [
+ run("run-1", {
+ artifacts: [
+ outputFile({
+ id: "a",
+ uploaded_at: "2026-07-27T08:00:00+00:00",
+ uploaded_by: "user",
+ uploaded_by_user_id: 42,
+ }),
+ ],
+ }),
+ ];
+
+ render(<TaskArtifactsList task={task} timeline={[]} />);
+
+ expect(screen.getByText(/^Sam · /)).toBeInTheDocument();
+ });
+
+ it("defaults to the newest undismissed version", () => {
+ mocks.runs = [
+ run("run-1", {
+ artifacts: [
+ outputFile({
+ id: "a",
+ size: 1_000,
+ uploaded_at: "2026-07-27T08:00:00+00:00",
+ }),
+ outputFile({
+ id: "b",
+ size: 2_000,
+ uploaded_at: "2026-07-27T09:00:00+00:00",
+ dismissed_at: "2026-07-27T10:00:00+00:00",
+ }),
+ ],
+ }),
+ ];
+
+ render(<TaskArtifactsList task={task} timeline={[]} />);
+
+ expect(screen.getByText(/ · 1 KB$/)).toBeInTheDocument();
+ fireEvent.click(screen.getByText("report.md"));
+ expect(mocks.openArtifactTab).toHaveBeenCalledWith("task-1", {
+ runId: "run-1",
+ artifactId: "a",
+ name: "report.md",
+ });
});
// A file dismissed in the chat's Files box has to go from this pane too, but
@@ -367,6 +444,40 @@ describe("TaskArtifactsList", () => {
expect(screen.queryByText("report.md") !== null).toBe(visible);
});
+ // The runs query must re-key the moment an agent upload completes, so a
+ // fresh file doesn't wait out the 30-second poll before appearing.
+ it("refreshes the runs query when an artifact upload completes", () => {
+ mocks.sessionEvents = ["tool_call", "tool_call_update"].map(
+ (sessionUpdate, index) => ({
+ type: "acp_message",
+ ts: index,
+ message: {
+ jsonrpc: "2.0",
+ method: "session/update",
+ params: {
+ update: {
+ sessionUpdate,
+ toolCallId: "c1",
+ ...(sessionUpdate === "tool_call_update"
+ ? { status: "completed" }
+ : {
+ _meta: {
+ posthog: {
+ toolName: "mcp__posthog-code-tools__upload_artifact",
+ },
+ },
+ }),
+ },
+ },
+ },
+ }),
+ );
+
+ render(<TaskArtifactsList task={task} timeline={[]} />);
+
+ expect(mocks.taskRunsRefreshKeys.at(-1)).toBe(1);
+ });
+
it.each([
{ name: "a plan", type: "plan" as const },
{ name: "a user attachment", type: "user_attachment" as const },
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 ee5bff7d912e..9df3e126330b 100644
--- a/products/desktop/packages/ui/src/features/canvas/components/TaskArtifactsList.tsx
+++ b/products/desktop/packages/ui/src/features/canvas/components/TaskArtifactsList.tsx
@@ -1,16 +1,24 @@
import {
ArrowSquareOutIcon,
+ CaretDownIcon,
ChatCircleIcon,
DownloadSimpleIcon,
- EyeIcon,
PackageIcon,
SlackLogoIcon,
} from "@phosphor-icons/react";
import type { ResourceComment } from "@posthog/api-client/posthog-client";
+import {
+ type RunArtifactVersions,
+ runArtifactVersionKey,
+} from "@posthog/core/canvas/runArtifactSchemas";
import type { ThreadTimelineRow } from "@posthog/core/canvas/threadTimeline";
import {
Badge,
Button,
+ DropdownMenu,
+ DropdownMenuContent,
+ DropdownMenuItem,
+ DropdownMenuTrigger,
Empty,
EmptyDescription,
EmptyHeader,
@@ -20,11 +28,14 @@ import {
TooltipContent,
TooltipTrigger,
} from "@posthog/quill";
+import { formatRelativeTimeLong } from "@posthog/shared";
import type { Task, TaskThreadMessage } from "@posthog/shared/domain-types";
+import { useMeQuery } from "@posthog/ui/features/auth/useMeQuery";
import { iconForTemplate } from "@posthog/ui/features/canvas/components/canvasTemplateIcon";
import {
buildRows,
commentTargets,
+ type RunFile,
} from "@posthog/ui/features/canvas/components/taskArtifactRows";
import { useTaskRuns } from "@posthog/ui/features/canvas/hooks/useTaskRuns";
import { canvasArtifactOpenHandler } from "@posthog/ui/features/canvas/utils/canvasArtifactNavigation";
@@ -34,109 +45,108 @@ import { usePanelLayoutStore } from "@posthog/ui/features/panels/panelLayoutStor
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 { useCompletedArtifactUploads } from "@posthog/ui/features/sessions/components/countArtifactUploads";
import { useCommentsForTargetsQuery } from "@posthog/ui/features/sessions/components/useComments";
+import { useSessionSelector } from "@posthog/ui/features/sessions/sessionStore";
import { useArtifactDownload } from "@posthog/ui/features/sessions/useArtifactDownload";
import { useCommentsEnabled } from "@posthog/ui/features/sessions/useCommentsEnabled";
import { FileIcon } from "@posthog/ui/primitives/FileIcon";
import { openExternalUrl } from "@posthog/ui/shell/openExternal";
import { formatFileSize } from "@posthog/ui/utils/formatFileSize";
-import { type ReactNode, useMemo, useState } from "react";
+import { type MouseEvent, type ReactNode, useMemo, useState } from "react";
const EMPTY_COMMENTS: ResourceComment[] = [];
-function ArtifactListRow({
+interface CurrentUser {
+ id?: number;
+ first_name?: string | null;
+}
+
+function CommentCountBadge({ count }: { count: number }) {
+ if (count === 0) return null;
+ return (
+ <Badge>
+ <ChatCircleIcon />
+ {count}
+ </Badge>
+ );
+}
+
+/**
+ * One artifact card. The whole card is the open control - a `role="button"`
+ * div rather than a `<button>`, because the version picker and the trailing
+ * actions are real buttons and HTML forbids nesting those (see NestedButton
+ * for the same call). Inner controls stop propagation so they don't open it.
+ */
+function ArtifactCard({
icon,
title,
- detail,
- external,
+ meta,
onOpen,
- onOpenExternal,
- fileActions,
onHoverStart,
+ actions,
}: {
icon: ReactNode;
title: string;
- detail?: ReactNode;
- external?: boolean;
+ meta?: ReactNode;
onOpen?: () => void;
- /** Renders a trailing button that leaves the app instead of opening the
- * artifact in place. Absent when there is nowhere safe to send the user. */
- onOpenExternal?: () => void;
- fileActions?: {
- onDownload: () => void;
- downloading: boolean;
- };
onHoverStart?: () => void;
+ /** Always-visible trailing cluster: comment badge, download, open externally. */
+ actions?: ReactNode;
}) {
return (
- // overflow-hidden so each half's hover fill is clipped to the row's radius.
- <div className="flex w-full items-center overflow-hidden rounded-md border border-border bg-muted text-[13px]">
- <button
- type="button"
- onClick={onOpen}
- disabled={!onOpen}
- onPointerEnter={onHoverStart}
- onFocus={onHoverStart}
- className="flex min-w-0 flex-1 items-center gap-2 px-2.5 py-2 text-left transition-colors enabled:hover:bg-gray-3"
- >
- {icon}
- <span className="min-w-0 flex-1 truncate font-medium">{title}</span>
- {detail && (
- <span className="shrink-0 text-muted-foreground">{detail}</span>
- )}
- {external && (
- <ArrowSquareOutIcon size={12} className="shrink-0 text-gray-9" />
- )}
- </button>
- {onOpenExternal && (
- <button
- type="button"
- onClick={onOpenExternal}
- aria-label={`Open ${title} externally`}
- className="flex shrink-0 items-center self-stretch border-border border-l px-2 text-muted-foreground transition-colors hover:bg-gray-3 hover:text-foreground"
+ // biome-ignore lint/a11y/useSemanticElements: nested real buttons forbid a <button> card
+ <div
+ data-artifact-card
+ role="button"
+ tabIndex={onOpen ? 0 : undefined}
+ aria-disabled={onOpen ? undefined : true}
+ aria-label={`View ${title}`}
+ className={`flex w-full items-center gap-2.5 rounded-lg border border-border bg-muted py-2 pr-1.5 pl-2 text-[13px] transition-colors ${
+ onOpen ? "cursor-pointer hover:border-gray-6 hover:bg-gray-3" : ""
+ }`}
+ onClick={onOpen}
+ onKeyDown={(event) => {
+ // Only the card itself: inner controls' key presses bubble up here.
+ if (event.target !== event.currentTarget) return;
+ if (onOpen && (event.key === "Enter" || event.key === " ")) {
+ event.preventDefault();
+ onOpen();
+ }
+ }}
+ onPointerEnter={onHoverStart}
+ onFocus={onHoverStart}
+ >
+ <div className="relative flex size-9 shrink-0 items-center justify-center overflow-hidden rounded-md bg-gray-4">
+ {/* The icon again, blown up and blurred: the tile tints itself with
+ the icon's own colors, so new icons never need a color mapping. */}
+ <div
+ aria-hidden
+ className="absolute inset-0 flex scale-[2.4] items-center justify-center opacity-40 blur-[9px] saturate-[1.8] dark:opacity-70"
>
- <ArrowSquareOutIcon size={12} />
- </button>
- )}
- {fileActions && onOpen && (
- <div className="flex shrink-0 items-center gap-0.5 border-border border-l px-1">
- <Tooltip>
- <TooltipTrigger
- render={
- <Button
- variant="default"
- size="icon-sm"
- aria-label={`View ${title}`}
- onClick={onOpen}
- />
- }
- >
- <EyeIcon size={14} />
- </TooltipTrigger>
- <TooltipContent>View</TooltipContent>
- </Tooltip>
- <Tooltip>
- <TooltipTrigger
- render={
- <Button
- variant="default"
- size="icon-sm"
- aria-label={`Download ${title}`}
- disabled={fileActions.downloading}
- onClick={fileActions.onDownload}
- />
- }
- >
- <DownloadSimpleIcon size={14} />
- </TooltipTrigger>
- <TooltipContent>Download</TooltipContent>
- </Tooltip>
+ {icon}
</div>
+ <div className="relative flex items-center justify-center">{icon}</div>
+ </div>
+ <div className="min-w-0 flex-1">
+ <div className="truncate font-medium">{title}</div>
+ {meta && (
+ <div className="flex items-center gap-1 whitespace-nowrap text-[12px] text-muted-foreground">
+ {meta}
+ </div>
+ )}
+ </div>
+ {actions && (
+ <div className="flex shrink-0 items-center gap-1">{actions}</div>
)}
</div>
);
}
+function stopCardOpen(event: MouseEvent) {
+ event.stopPropagation();
+}
+
function PrRow({
url,
openInPlaceTaskId,
@@ -150,31 +160,18 @@ function PrRow({
const comments = usePrComments(countsWanted ? safeUrl : null);
const threads = usePrReviewThreads(countsWanted ? safeUrl : null);
- const commentCount =
+ const prCommentCount =
(comments.data?.length ?? 0) +
(threads.data ?? []).reduce(
(sum, thread) => sum + thread.comments.length,
0,
);
- const detailParts = [
- stateLabel,
- comments.data || threads.data
- ? `${commentCount} ${commentCount === 1 ? "comment" : "comments"}`
- : null,
- ].filter(Boolean);
return (
- <ArtifactListRow
- icon={
- <Icon
- size={14}
- weight="bold"
- className="shrink-0"
- style={{ color: iconColor }}
- />
- }
+ <ArtifactCard
+ icon={<Icon size={16} weight="bold" style={{ color: iconColor }} />}
title={title}
- detail={detailParts.join(" · ") || null}
+ meta={stateLabel}
onHoverStart={() => setCountsWanted(true)}
onOpen={
safeUrl
@@ -184,7 +181,24 @@ function PrRow({
: openExternalUrl(safeUrl)
: undefined
}
- onOpenExternal={safeUrl ? () => openExternalUrl(safeUrl) : undefined}
+ actions={
+ <>
+ <CommentCountBadge count={prCommentCount} />
+ {safeUrl && (
+ <Button
+ variant="default"
+ size="icon-sm"
+ aria-label={`Open ${title} externally`}
+ onClick={(event) => {
+ stopCardOpen(event);
+ openExternalUrl(safeUrl);
+ }}
+ >
+ <ArrowSquareOutIcon size={14} />
+ </Button>
+ )}
+ </>
+ }
/>
);
}
@@ -200,50 +214,90 @@ function CanvasRow({
}) {
const open = canvasArtifactOpenHandler(url);
return (
- <ArtifactListRow
- icon={iconForTemplate("", { size: 14, className: "text-violet-9" })}
+ <ArtifactCard
+ icon={iconForTemplate("", { size: 16, className: "text-amber-11" })}
title={name}
- detail={
- commentCount > 0 ? (
- <Badge>
- <ChatCircleIcon />
- {commentCount}
- </Badge>
- ) : (
- "Canvas"
- )
- }
+ meta="Canvas"
onOpen={open}
+ actions={<CommentCountBadge count={commentCount} />}
/>
);
}
+function wasEditedByCurrentUser(
+ artifact: RunFile,
+ currentUserId: number | undefined,
+): boolean {
+ return (
+ artifact.uploaded_by === "user" &&
+ currentUserId !== undefined &&
+ artifact.uploaded_by_user_id === currentUserId
+ );
+}
+
+/** Who a version came from, named rather than described. */
+function uploaderLabel(
+ artifact: RunFile,
+ currentUser: CurrentUser | undefined,
+): string {
+ if (artifact.uploaded_by !== "user") return "Agent";
+ if (wasEditedByCurrentUser(artifact, currentUser?.id)) {
+ return currentUser?.first_name?.trim() || "You";
+ }
+ return "Teammate";
+}
+
+/** Compact one-based version label: v1 is oldest, v{total} is newest. */
+function versionShortLabel(index: number, total: number): string {
+ return `v${total - index}`;
+}
+
+function fileVersionMenuLabel(
+ artifact: RunFile,
+ index: number,
+ total: number,
+ currentUser: CurrentUser | undefined,
+): string {
+ return [
+ versionShortLabel(index, total),
+ uploaderLabel(artifact, currentUser),
+ artifact.uploaded_at ? formatRelativeTimeLong(artifact.uploaded_at) : null,
+ ]
+ .filter(Boolean)
+ .join(" · ");
+}
+
function FileRow({
taskId,
- runId,
- artifactId,
- name,
- size,
+ group,
commentCount,
+ currentUser,
}: {
taskId: string;
- runId: string | null;
- artifactId: string | null;
- name: string;
- size: number | undefined;
+ group: RunArtifactVersions<RunFile>;
/** Supplied by the pane's single comments query so each row doesn't fetch. */
commentCount: number;
+ currentUser: CurrentUser | undefined;
}) {
const openArtifactTab = usePanelLayoutStore((state) => state.openArtifactTab);
const { download, downloadingId } = useArtifactDownload();
- const canOpen = !!runId && !!artifactId;
- const sizeLabel = formatFileSize(size);
+ const [selectedKey, setSelectedKey] = useState<string | null>(null);
+ const pickedIndex = group.versions.findIndex(
+ (version) => runArtifactVersionKey(version) === selectedKey,
+ );
+ const newestVisibleIndex = group.versions.findIndex(
+ (version) => !version.dismissed_at,
+ );
+ const selectedIndex =
+ pickedIndex >= 0 ? pickedIndex : Math.max(newestVisibleIndex, 0);
+ const selected = group.versions[selectedIndex] ?? group.latest;
+ const canOpen = !!selected.id;
const onOpen = canOpen
? () => {
openArtifactTab(taskId, {
- runId: runId as string,
- artifactId: artifactId as string,
- name,
+ runId: selected.runId,
+ artifactId: selected.id as string,
+ name: group.name,
});
}
: undefined;
@@ -251,32 +305,95 @@ function FileRow({
? () => {
void download({
taskId,
- runId: runId as string,
- artifactId: artifactId as string,
- name,
+ runId: selected.runId,
+ artifactId: selected.id as string,
+ name: group.name,
});
}
: undefined;
+ const metaText = [
+ uploaderLabel(selected, currentUser),
+ selected.uploaded_at ? formatRelativeTimeLong(selected.uploaded_at) : null,
+ formatFileSize(selected.size),
+ ]
+ .filter(Boolean)
+ .join(" · ");
+
return (
- <ArtifactListRow
- icon={<FileIcon filename={name} size={14} />}
- title={name}
- detail={
- <div className="flex items-center gap-1.5">
- <span>{sizeLabel ? `File · ${sizeLabel}` : "File"}</span>
- {commentCount > 0 && (
- <Badge>
- <ChatCircleIcon />
- {commentCount}
- </Badge>
+ <ArtifactCard
+ icon={<FileIcon filename={group.name} size={18} />}
+ title={group.name}
+ meta={
+ <>
+ {metaText && <span className="truncate">{metaText}</span>}
+ {group.versions.length > 1 && (
+ <>
+ {metaText && <span>·</span>}
+ <DropdownMenu>
+ <DropdownMenuTrigger
+ render={
+ <button
+ type="button"
+ aria-label={`Choose a version of ${group.name}`}
+ onClick={stopCardOpen}
+ className="flex shrink-0 cursor-pointer items-center gap-0.5 text-foreground"
+ >
+ {versionShortLabel(selectedIndex, group.versions.length)}
+ <CaretDownIcon size={10} />
+ </button>
+ }
+ />
+ {/* w-max: the default popup width tracks the anchor, and this
+ trigger is a couple of characters wide, so version labels
+ would be cut off. */}
+ <DropdownMenuContent align="start" className="w-max">
+ {group.versions.map((version, index) => (
+ <DropdownMenuItem
+ key={runArtifactVersionKey(version)}
+ onClick={() =>
+ setSelectedKey(runArtifactVersionKey(version))
+ }
+ >
+ {fileVersionMenuLabel(
+ version,
+ index,
+ group.versions.length,
+ currentUser,
+ )}
+ </DropdownMenuItem>
+ ))}
+ </DropdownMenuContent>
+ </DropdownMenu>
+ </>
)}
- </div>
+ </>
}
onOpen={onOpen}
- fileActions={
- onDownload
- ? { onDownload, downloading: downloadingId === artifactId }
- : undefined
+ actions={
+ <>
+ <CommentCountBadge count={commentCount} />
+ {onDownload && (
+ <Tooltip>
+ <TooltipTrigger
+ render={
+ <Button
+ variant="default"
+ size="icon-sm"
+ aria-label={`Download ${group.name}`}
+ disabled={downloadingId === selected.id}
+ onClick={(event) => {
+ stopCardOpen(event);
+ onDownload();
+ }}
+ />
+ }
+ >
+ <DownloadSimpleIcon size={14} />
+ </TooltipTrigger>
+ <TooltipContent>Download</TooltipContent>
+ </Tooltip>
+ )}
+ </>
}
/>
);
@@ -294,7 +411,12 @@ export function TaskArtifactsList({
canOpenInPlace?: boolean;
}) {
const commentsEnabled = useCommentsEnabled();
- const { runs } = useTaskRuns(task.id);
+ // A finished upload_artifact tool call re-keys the runs query, so a file
+ // the agent just delivered shows up now rather than on the next poll.
+ const events = useSessionSelector(task.id, (session) => session?.events);
+ const completedUploads = useCompletedArtifactUploads(events ?? []);
+ const { runs } = useTaskRuns(task.id, completedUploads);
+ const { data: currentUser } = useMeQuery();
const rows = useMemo(
() => buildRows(task, timeline, runs),
[task, timeline, runs],
@@ -359,22 +481,32 @@ export function TaskArtifactsList({
<FileRow
key={row.key}
taskId={task.id}
- runId={row.runId}
- artifactId={row.artifactId}
- name={row.name}
- size={row.size}
+ group={row.group}
commentCount={
row.artifactId ? (openCountByItem.get(row.artifactId) ?? 0) : 0
}
+ currentUser={currentUser}
/>
) : (
- <ArtifactListRow
+ <ArtifactCard
key={row.key}
- icon={<SlackLogoIcon size={14} className="shrink-0 text-gray-11" />}
+ icon={<SlackLogoIcon size={16} className="text-gray-11" />}
title="Slack thread"
- detail="External"
- external
+ meta="External"
onOpen={() => openExternalUrl(row.url)}
+ actions={
+ <Button
+ variant="default"
+ size="icon-sm"
+ aria-label="Open Slack thread externally"
+ onClick={(event) => {
+ stopCardOpen(event);
+ openExternalUrl(row.url);
+ }}
+ >
+ <ArrowSquareOutIcon size={14} />
+ </Button>
+ }
/>
),
)}
diff --git a/products/desktop/packages/ui/src/features/canvas/components/taskArtifactRows.ts b/products/desktop/packages/ui/src/features/canvas/components/taskArtifactRows.ts
index 3b02240eb972..26c667a47a68 100644
--- a/products/desktop/packages/ui/src/features/canvas/components/taskArtifactRows.ts
+++ b/products/desktop/packages/ui/src/features/canvas/components/taskArtifactRows.ts
@@ -1,7 +1,9 @@
import {
+ groupRunArtifactVersions,
OUTPUT_ARTIFACT_TYPES,
parseRunArtifacts,
type RunArtifact,
+ type RunArtifactVersions,
} from "@posthog/core/canvas/runArtifactSchemas";
import type { ThreadTimelineRow } from "@posthog/core/canvas/threadTimeline";
import {
@@ -16,6 +18,8 @@ import type {
} from "@posthog/shared/domain-types";
import { parseHttpsUrl, parseShareLink } from "@posthog/ui/utils/posthogLinks";
+export type RunFile = RunArtifact & { runId: string };
+
export type ArtifactRow =
| { kind: "pr"; key: string; url: string }
| {
@@ -33,6 +37,7 @@ export type ArtifactRow =
name: string;
runId: string | null;
size: number | undefined;
+ group: RunArtifactVersions<RunFile>;
}
| { kind: "slack"; key: string; url: string };
@@ -164,36 +169,25 @@ export function buildRows(
const allRuns =
runs.length > 0 ? runs : task.latest_run ? [task.latest_run] : [];
- // Re-uploading a file replaces it rather than adding a second one: agents
- // revise a deliverable and upload it again under the same name, so keeping
- // every copy would bury the current one under its own drafts.
- const newestByName = new Map<string, { file: RunArtifact; runId: string }>();
- const undismissedNames = new Set<string>();
+ const files: RunFile[] = [];
for (const run of allRuns) {
for (const outputPr of readPrUrls(run.output)) {
addPr(outputPr, `output-pr:${outputPr}`);
}
- for (const file of readRunOutputs(run)) {
- if (!file.name) continue;
- if (!file.dismissed_at) undismissedNames.add(file.name);
- const previous = newestByName.get(file.name);
- const isNewer =
- !previous ||
- (file.uploaded_at ?? "") >= (previous.file.uploaded_at ?? "");
- if (isNewer) newestByName.set(file.name, { file, runId: run.id });
- }
+ files.push(
+ ...readRunOutputs(run).map((file) => ({ ...file, runId: run.id })),
+ );
}
- for (const [name, { file, runId }] of newestByName) {
- // A file goes only when every version of it is dismissed, so dismissing the
- // one on show cannot resurface the copy it replaced.
- if (!undismissedNames.has(name)) continue;
+ for (const group of groupRunArtifactVersions(files)) {
+ if (group.dismissed) continue;
rows.push({
kind: "file",
- key: `file:${file.id ?? file.storage_path ?? name}`,
- artifactId: file.id ?? null,
- name,
- runId,
- size: file.size,
+ key: `file:${group.name}`,
+ artifactId: group.latest.id ?? null,
+ name: group.name,
+ runId: group.latest.runId,
+ size: group.latest.size,
+ group,
});
}
diff --git a/products/desktop/packages/ui/src/features/canvas/hooks/useTaskRuns.ts b/products/desktop/packages/ui/src/features/canvas/hooks/useTaskRuns.ts
index 400bb9fc5bde..4b71b2682324 100644
--- a/products/desktop/packages/ui/src/features/canvas/hooks/useTaskRuns.ts
+++ b/products/desktop/packages/ui/src/features/canvas/hooks/useTaskRuns.ts
@@ -1,20 +1,35 @@
import type { TaskRun } from "@posthog/shared/domain-types";
import { useAuthenticatedQuery } from "@posthog/ui/hooks/useAuthenticatedQuery";
+import { useCallback } from "react";
const TASK_RUNS_POLL_INTERVAL_MS = 30_000;
-/** Every run of a task — for gathering artifacts across all runs, not just the latest. */
-export function useTaskRuns(taskId: string | undefined): {
+/**
+ * Every run of a task — for gathering artifacts across all runs, not just the
+ * latest. The server never pushes manifest changes, so `refreshKey` lets
+ * callers force a fresh fetch the moment they see one land (for example a
+ * completed `upload_artifact` tool call) instead of waiting out the poll.
+ */
+export function useTaskRuns(
+ taskId: string | undefined,
+ refreshKey = 0,
+): {
runs: TaskRun[];
isLoading: boolean;
+ refreshRuns: () => Promise<TaskRun[]>;
} {
const query = useAuthenticatedQuery<TaskRun[]>(
- ["task-runs", taskId ?? "none"],
+ ["task-runs", taskId ?? "none", refreshKey],
(client) => client.listTaskRuns(taskId as string),
{
enabled: !!taskId,
refetchInterval: TASK_RUNS_POLL_INTERVAL_MS,
},
);
- return { runs: query.data ?? [], isLoading: query.isLoading };
+ const refreshRuns = useCallback(async (): Promise<TaskRun[]> => {
+ const result = await query.refetch();
+ if (result.error) throw result.error;
+ return result.data ?? [];
+ }, [query.refetch]);
+ return { runs: query.data ?? [], isLoading: query.isLoading, refreshRuns };
}
diff --git a/products/desktop/packages/ui/src/features/code-editor/components/CodeMirrorEditor.tsx b/products/desktop/packages/ui/src/features/code-editor/components/CodeMirrorEditor.tsx
index d57daa283eda..78db08643f39 100644
--- a/products/desktop/packages/ui/src/features/code-editor/components/CodeMirrorEditor.tsx
+++ b/products/desktop/packages/ui/src/features/code-editor/components/CodeMirrorEditor.tsx
@@ -53,6 +53,7 @@ interface CodeMirrorEditorProps {
enrichment?: SerializedEnrichment | null;
/** Fires on every selection (or doc) change with the current selection. */
onSelectionChange?: (selection: EditorSelection) => void;
+ onContentChange?: (content: string) => void;
/** Highlight the active selection as full lines (code-review style). */
highlightSelectedLines?: boolean;
}
@@ -64,6 +65,7 @@ export function CodeMirrorEditor({
readOnly = false,
enrichment,
onSelectionChange,
+ onContentChange,
highlightSelectedLines = false,
}: CodeMirrorEditorProps) {
const enrichmentEnabled = enrichment !== undefined;
@@ -78,9 +80,16 @@ export function CodeMirrorEditor({
useEffect(() => {
onSelectionChangeRef.current = onSelectionChange;
}, [onSelectionChange]);
+ const onContentChangeRef = useRef(onContentChange);
+ useEffect(() => {
+ onContentChangeRef.current = onContentChange;
+ }, [onContentChange]);
const selectionExtension = useMemo(
() =>
EditorView.updateListener.of((update) => {
+ if (update.docChanged) {
+ onContentChangeRef.current?.(update.state.doc.toString());
+ }
const cb = onSelectionChangeRef.current;
if (!cb) return;
const changed = update.selectionSet || update.docChanged;
diff --git a/products/desktop/packages/ui/src/features/code-editor/components/DocumentPreviewHeader.tsx b/products/desktop/packages/ui/src/features/code-editor/components/DocumentPreviewHeader.tsx
index dfd7408e6d2a..1657f7dbf6c7 100644
--- a/products/desktop/packages/ui/src/features/code-editor/components/DocumentPreviewHeader.tsx
+++ b/products/desktop/packages/ui/src/features/code-editor/components/DocumentPreviewHeader.tsx
@@ -5,53 +5,77 @@ import {
TooltipContent,
TooltipTrigger,
} from "@posthog/quill";
-import { type ReactNode, useState } from "react";
+import { type ReactElement, type ReactNode, useState } from "react";
+
+interface DocumentPreviewHeaderProps {
+ label: string;
+ /** Version stepper rendered beside the label (see ArtifactVersionNav). */
+ versionNav?: ReactNode;
+ content: string;
+ getContent?: () => string;
+ showRendered: boolean;
+ onToggleRendered?: () => void;
+ actions?: ReactNode;
+ canEdit?: boolean;
+ editing?: boolean;
+ saving?: boolean;
+ onEdit?: () => void;
+ onCancel?: () => void;
+ onSave?: () => void;
+}
export function DocumentPreviewHeader({
label,
+ versionNav,
content,
+ getContent,
showRendered,
onToggleRendered,
actions,
-}: {
- label: string;
- content: string;
- showRendered: boolean;
- onToggleRendered: () => void;
- actions?: ReactNode;
-}) {
+ canEdit = false,
+ editing = false,
+ saving = false,
+ onEdit,
+ onCancel,
+ onSave,
+}: DocumentPreviewHeaderProps): ReactElement {
const [copied, setCopied] = useState(false);
- const handleCopySource = () => {
- navigator.clipboard.writeText(content);
+ const handleCopySource = (): void => {
+ void navigator.clipboard.writeText(getContent?.() ?? content);
setCopied(true);
setTimeout(() => setCopied(false), 2000);
};
return (
- <div className="flex shrink-0 items-center justify-between border-b border-b-(--gray-6) px-3 py-2">
- <span className="font-[var(--code-font-family)] text-[13px] text-muted-foreground">
- {label}
- </span>
- <div className="flex items-center gap-1">
+ <div className="flex h-10 shrink-0 items-center justify-between gap-2 border-b border-b-(--gray-6) px-3">
+ <div className="flex min-w-0 items-center gap-2">
+ <span className="truncate font-[var(--code-font-family)] text-[13px] text-muted-foreground">
+ {label}
+ </span>
+ {versionNav}
+ </div>
+ <div className="flex shrink-0 items-center gap-1">
{actions}
- <Tooltip>
- <TooltipTrigger
- render={
- <Button
- size="icon"
- variant="default"
- onClick={onToggleRendered}
- aria-label={showRendered ? "View source" : "View preview"}
- >
- {showRendered ? <Code size={14} /> : <Eye size={14} />}
- </Button>
- }
- />
- <TooltipContent>
- {showRendered ? "View source" : "View preview"}
- </TooltipContent>
- </Tooltip>
+ {!editing && onToggleRendered && (
+ <Tooltip>
+ <TooltipTrigger
+ render={
+ <Button
+ size="icon"
+ variant="default"
+ onClick={onToggleRendered}
+ aria-label={showRendered ? "View source" : "View preview"}
+ >
+ {showRendered ? <Code size={14} /> : <Eye size={14} />}
+ </Button>
+ }
+ />
+ <TooltipContent>
+ {showRendered ? "View source" : "View preview"}
+ </TooltipContent>
+ </Tooltip>
+ )}
<Tooltip>
<TooltipTrigger
render={
@@ -67,6 +91,32 @@ export function DocumentPreviewHeader({
/>
<TooltipContent>{copied ? "Copied" : "Copy source"}</TooltipContent>
</Tooltip>
+ {editing ? (
+ <>
+ <Button
+ size="sm"
+ variant="outline"
+ disabled={saving}
+ onClick={onCancel}
+ >
+ Cancel
+ </Button>
+ <Button
+ size="sm"
+ variant="primary"
+ loading={saving}
+ onClick={onSave}
+ >
+ Save
+ </Button>
+ </>
+ ) : (
+ canEdit && (
+ <Button size="sm" variant="outline" onClick={onEdit}>
+ Edit
+ </Button>
+ )
+ )}
</div>
</div>
);
diff --git a/products/desktop/packages/ui/src/features/sessions/components/ArtifactDocumentCommentAction.tsx b/products/desktop/packages/ui/src/features/sessions/components/ArtifactDocumentCommentAction.tsx
index c2969fe192bb..39aaff73af81 100644
--- a/products/desktop/packages/ui/src/features/sessions/components/ArtifactDocumentCommentAction.tsx
+++ b/products/desktop/packages/ui/src/features/sessions/components/ArtifactDocumentCommentAction.tsx
@@ -5,6 +5,9 @@ import {
Popover,
PopoverContent,
PopoverTrigger,
+ Tooltip,
+ TooltipContent,
+ TooltipTrigger,
} from "@posthog/quill";
import { useOrgMembers } from "@posthog/ui/features/canvas/hooks/useOrgMembers";
import { useState } from "react";
@@ -27,14 +30,20 @@ export function ArtifactDocumentCommentAction({
return (
<Popover open={open} onOpenChange={setOpen}>
- <PopoverTrigger
- render={
- <Button size="sm" variant="outline">
- <ChatCircleIcon />
- Comment…
- </Button>
- }
- />
+ <Tooltip>
+ <TooltipTrigger
+ render={
+ <PopoverTrigger
+ render={
+ <Button size="icon" variant="default" aria-label="Comment…">
+ <ChatCircleIcon size={14} />
+ </Button>
+ }
+ />
+ }
+ />
+ <TooltipContent>Comment on this artifact</TooltipContent>
+ </Tooltip>
<PopoverContent align="end" sideOffset={6} className="w-96 p-2">
<CommentComposer
value={draft}
diff --git a/products/desktop/packages/ui/src/features/sessions/components/ArtifactEditView.tsx b/products/desktop/packages/ui/src/features/sessions/components/ArtifactEditView.tsx
new file mode 100644
index 000000000000..c932373f1c21
--- /dev/null
+++ b/products/desktop/packages/ui/src/features/sessions/components/ArtifactEditView.tsx
@@ -0,0 +1,97 @@
+import {
+ AlertDialog,
+ AlertDialogClose,
+ AlertDialogContent,
+ AlertDialogDescription,
+ AlertDialogFooter,
+ AlertDialogHeader,
+ AlertDialogTitle,
+ Button,
+} from "@posthog/quill";
+import type { ReactElement } from "react";
+import { CodeMirrorEditor } from "../../code-editor/components/CodeMirrorEditor";
+import { DocumentPreviewHeader } from "../../code-editor/components/DocumentPreviewHeader";
+import type { ArtifactEditConflict } from "./useArtifactEditing";
+
+export function ArtifactEditView({
+ name,
+ source,
+ editorPath,
+ showRendered,
+ saving,
+ conflict,
+ onConflictOpenChange,
+ getContent,
+ onContentChange,
+ onCancel,
+ onSave,
+ onForceSave,
+}: {
+ name: string;
+ source: string;
+ editorPath: string;
+ showRendered: boolean;
+ saving: boolean;
+ conflict: ArtifactEditConflict | null;
+ onConflictOpenChange: (open: boolean) => void;
+ getContent: () => string;
+ onContentChange: (content: string) => void;
+ onCancel: () => void;
+ onSave: () => void;
+ onForceSave: () => void;
+}): ReactElement {
+ return (
+ <div className="flex h-full flex-col overflow-hidden">
+ <DocumentPreviewHeader
+ label={name}
+ content={source}
+ getContent={getContent}
+ showRendered={showRendered}
+ editing
+ saving={saving}
+ onCancel={onCancel}
+ onSave={onSave}
+ />
+ <div className="min-h-0 min-w-0 flex-1 overflow-hidden">
+ <CodeMirrorEditor
+ content={source}
+ filePath={editorPath}
+ readOnly={false}
+ onContentChange={onContentChange}
+ />
+ </div>
+ <AlertDialog
+ open={conflict !== null}
+ onOpenChange={(open) => {
+ if (!saving) onConflictOpenChange(open);
+ }}
+ >
+ <AlertDialogContent>
+ <AlertDialogHeader>
+ <AlertDialogTitle>
+ {conflict === "dismissed"
+ ? "This file was dismissed"
+ : "A newer version is available"}
+ </AlertDialogTitle>
+ <AlertDialogDescription>
+ {conflict === "dismissed"
+ ? "Every version of this file was dismissed while you were editing. Save your changes to restore it as the latest version?"
+ : "A newer version of this file arrived while you were editing. Save yours as the latest anyway?"}
+ </AlertDialogDescription>
+ </AlertDialogHeader>
+ <AlertDialogFooter>
+ <AlertDialogClose
+ disabled={saving}
+ render={<Button variant="outline" disabled={saving} />}
+ >
+ Keep editing
+ </AlertDialogClose>
+ <Button variant="primary" loading={saving} onClick={onForceSave}>
+ {conflict === "dismissed" ? "Save and restore" : "Save as latest"}
+ </Button>
+ </AlertDialogFooter>
+ </AlertDialogContent>
+ </AlertDialog>
+ </div>
+ );
+}
diff --git a/products/desktop/packages/ui/src/features/sessions/components/ArtifactPreview.test.tsx b/products/desktop/packages/ui/src/features/sessions/components/ArtifactPreview.test.tsx
index fc2485284281..bde016c75a1c 100644
--- a/products/desktop/packages/ui/src/features/sessions/components/ArtifactPreview.test.tsx
+++ b/products/desktop/packages/ui/src/features/sessions/components/ArtifactPreview.test.tsx
@@ -36,7 +36,19 @@ const artifactComments = vi.hoisted(() => ({
const createComment = vi.hoisted(() => vi.fn());
const useQuery = vi.hoisted(() => vi.fn());
const commentsFlag = vi.hoisted(() => ({ enabled: true }));
+const taskRuns = vi.hoisted(() => ({
+ data: [] as unknown[],
+ isLoading: false,
+ refreshRuns: vi.fn(),
+}));
const orgMembersOptions = vi.hoisted(() => vi.fn());
+const artifactMocks = vi.hoisted(() => ({
+ getCloudRunArtifacts: vi.fn(),
+ getCloudAttachmentPreviewUrl: vi.fn(),
+ uploadCloudRunArtifactVersion: vi.fn(),
+ invalidateQueries: vi.fn(),
+ openArtifactTab: vi.fn(),
+}));
vi.mock("@posthog/ui/features/sessions/useCommentsEnabled", () => ({
useCommentsEnabled: () => commentsFlag.enabled,
@@ -47,7 +59,11 @@ vi.mock("@posthog/core/sessions/sessionService", () => ({
}));
vi.mock("@posthog/di/react", () => ({
- useService: () => ({}),
+ useService: () => ({
+ getCloudRunArtifacts: artifactMocks.getCloudRunArtifacts,
+ getCloudAttachmentPreviewUrl: artifactMocks.getCloudAttachmentPreviewUrl,
+ uploadCloudRunArtifactVersion: artifactMocks.uploadCloudRunArtifactVersion,
+ }),
useServiceOptional: () => null,
}));
@@ -60,6 +76,18 @@ vi.mock("@posthog/ui/features/auth/useCurrentUser", () => ({
AUTH_SCOPED_QUERY_META: { authScoped: true },
}));
+vi.mock("@posthog/ui/features/panels/panelLayoutStore", () => ({
+ usePanelLayoutStore: () => artifactMocks.openArtifactTab,
+}));
+
+vi.mock("@posthog/ui/features/canvas/hooks/useTaskRuns", () => ({
+ useTaskRuns: () => ({
+ runs: taskRuns.data,
+ isLoading: taskRuns.isLoading,
+ refreshRuns: taskRuns.refreshRuns,
+ }),
+}));
+
vi.mock("@posthog/ui/features/canvas/hooks/useOrgMembers", () => ({
useOrgMembers: (options: { enabled?: boolean }) => {
orgMembersOptions(options);
@@ -93,6 +121,26 @@ vi.mock("@posthog/ui/features/canvas/components/MentionComposer", () => ({
vi.mock("@tanstack/react-query", () => ({
useQuery,
+ useMutation: (options: {
+ mutationFn: (variables: unknown) => Promise<unknown>;
+ onSuccess?: (data: unknown) => Promise<void> | void;
+ onError?: (error: unknown) => void;
+ }) => ({
+ isPending: false,
+ mutateAsync: async (variables: unknown) => {
+ try {
+ const result = await options.mutationFn(variables);
+ await options.onSuccess?.(result);
+ return result;
+ } catch (error) {
+ options.onError?.(error);
+ throw error;
+ }
+ },
+ }),
+ useQueryClient: () => ({
+ invalidateQueries: artifactMocks.invalidateQueries,
+ }),
}));
vi.mock("./useComments", () => ({
@@ -105,11 +153,47 @@ vi.mock("./useComments", () => ({
}));
vi.mock("../../code-editor/components/CodeMirrorEditor", () => ({
- CodeMirrorEditor: ({ content }: { content: string }) => (
- <div data-testid="source-view">{content}</div>
- ),
+ CodeMirrorEditor: ({
+ content,
+ readOnly,
+ onContentChange,
+ }: {
+ content: string;
+ readOnly?: boolean;
+ onContentChange?: (content: string) => void;
+ }) =>
+ readOnly ? (
+ <div data-testid="source-view">{content}</div>
+ ) : (
+ <textarea
+ aria-label="Artifact source editor"
+ defaultValue={content}
+ onChange={(event) => onContentChange?.(event.target.value)}
+ />
+ ),
}));
+function editablePreview(
+ overrides: Record<string, unknown> = {},
+ artifacts?: Record<string, unknown>[],
+) {
+ const artifact = {
+ id: "artifact-1",
+ name: "report.md",
+ type: "output",
+ content_type: "text/markdown",
+ storage_path: "runs/1/report.md",
+ uploaded_at: "2026-08-07T10:00:00Z",
+ ...overrides,
+ };
+ return {
+ artifact,
+ artifacts: artifacts ?? [artifact],
+ preview: "# Report",
+ source: "# Report",
+ };
+}
+
function textComment(): ResourceComment {
return {
id: "comment-1",
@@ -143,6 +227,10 @@ describe("ArtifactPreview", () => {
});
artifactComments.data = [];
artifactComments.isError = false;
+ taskRuns.data = [];
+ taskRuns.isLoading = false;
+ taskRuns.refreshRuns.mockReset();
+ taskRuns.refreshRuns.mockImplementation(async () => taskRuns.data);
createComment.mockReset();
createComment.mockResolvedValue({ id: "created-comment" });
useQuery.mockReset();
@@ -151,6 +239,13 @@ describe("ArtifactPreview", () => {
isLoading: false,
isError: false,
});
+ artifactMocks.getCloudRunArtifacts.mockReset();
+ artifactMocks.getCloudAttachmentPreviewUrl.mockReset();
+ artifactMocks.uploadCloudRunArtifactVersion.mockReset();
+ artifactMocks.uploadCloudRunArtifactVersion.mockResolvedValue("artifact-2");
+ artifactMocks.invalidateQueries.mockReset();
+ artifactMocks.invalidateQueries.mockResolvedValue(undefined);
+ artifactMocks.openArtifactTab.mockReset();
vi.spyOn(URL, "createObjectURL").mockReturnValue("blob:preview");
vi.spyOn(URL, "revokeObjectURL").mockImplementation(() => undefined);
});
@@ -180,6 +275,36 @@ describe("ArtifactPreview", () => {
);
});
+ it("starts the manifest and preview URL requests together", async () => {
+ let resolveArtifacts: (artifacts: unknown[]) => void = () => undefined;
+ artifactMocks.getCloudRunArtifacts.mockReturnValue(
+ new Promise((resolve) => {
+ resolveArtifacts = resolve;
+ }),
+ );
+ artifactMocks.getCloudAttachmentPreviewUrl.mockResolvedValue(null);
+
+ render(
+ <ArtifactPreview
+ taskId="task-1"
+ runId="run-1"
+ artifactId="artifact-1"
+ name="report.html"
+ />,
+ );
+
+ const queryFn = useQuery.mock.calls[0]?.[0]
+ .queryFn as () => Promise<unknown>;
+ const result = queryFn();
+ expect(artifactMocks.getCloudAttachmentPreviewUrl).toHaveBeenCalledWith(
+ "task-1",
+ "run-1",
+ "artifact-1",
+ );
+ resolveArtifacts([]);
+ await expect(result).rejects.toThrow("Artifact is unavailable");
+ });
+
it("keeps the artifact visible when comments fail to load", () => {
artifactComments.isError = true;
useQuery.mockReturnValue({
@@ -798,6 +923,276 @@ describe("ArtifactPreview", () => {
expect(screen.queryByText("Tighten this summary")).toBeNull();
});
+ it.each([
+ ["text/markdown", "report.bin"],
+ ["text/html", "report.bin"],
+ ["text/plain", "report.bin"],
+ [undefined, "report.md"],
+ [undefined, "report.html"],
+ [undefined, "report.txt"],
+ ])(
+ "offers editing for the latest %s artifact named %s",
+ (contentType, fileName) => {
+ const data = editablePreview({
+ name: fileName,
+ content_type: contentType,
+ });
+ useQuery.mockReturnValue({ data, isLoading: false, isError: false });
+
+ render(
+ <ArtifactPreview
+ taskId="task-1"
+ runId="run-1"
+ artifactId="artifact-1"
+ name={fileName}
+ />,
+ );
+
+ expect(screen.getByRole("button", { name: "Edit" })).toBeInTheDocument();
+ },
+ );
+
+ it.each([
+ {
+ name: "a non-editable type",
+ artifact: { name: "report.json", content_type: "application/json" },
+ newerVersion: false,
+ },
+ {
+ name: "an unsupported extension fallback",
+ artifact: { name: "report.markdown", content_type: undefined },
+ newerVersion: false,
+ },
+ {
+ name: "an old version",
+ artifact: { name: "report.md", content_type: "text/markdown" },
+ newerVersion: true,
+ },
+ ])("does not offer editing for $name", ({ artifact, newerVersion }) => {
+ const data = editablePreview(artifact);
+ if (newerVersion) {
+ taskRuns.data = [
+ { id: "run-1", artifacts: data.artifacts },
+ {
+ id: "run-2",
+ artifacts: [
+ {
+ ...data.artifact,
+ id: "artifact-2",
+ storage_path: "runs/2/report-v2.md",
+ uploaded_at: "2026-08-07T11:00:00Z",
+ },
+ ],
+ },
+ ];
+ }
+ useQuery.mockReturnValue({ data, isLoading: false, isError: false });
+
+ render(
+ <ArtifactPreview
+ taskId="task-1"
+ runId="run-1"
+ artifactId="artifact-1"
+ name={data.artifact.name as string}
+ />,
+ );
+
+ expect(screen.queryByRole("button", { name: "Edit" })).toBeNull();
+ });
+
+ // The tab header steps through a file's versions in place, retargeting the
+ // preview fetch instead of opening more tabs.
+ it("steps between versions and follows focused comments", () => {
+ taskRuns.data = [
+ {
+ id: "run-1",
+ artifacts: [
+ {
+ id: "artifact-0",
+ name: "report.md",
+ type: "output",
+ storage_path: "runs/1/report-v1.md",
+ uploaded_at: "2026-08-06T10:00:00Z",
+ },
+ {
+ id: "artifact-1",
+ name: "report.md",
+ type: "output",
+ storage_path: "runs/1/report-v2.md",
+ uploaded_at: "2026-08-07T10:00:00Z",
+ },
+ ],
+ },
+ ];
+ useQuery.mockReturnValue({
+ data: editablePreview(),
+ isLoading: false,
+ isError: false,
+ });
+
+ render(
+ <ArtifactPreview
+ taskId="task-1"
+ runId="run-1"
+ artifactId="artifact-1"
+ name="report.md"
+ />,
+ );
+
+ expect(screen.getByText("v2/2")).toBeInTheDocument();
+ expect(
+ screen.getByRole("button", { name: "Newer version" }),
+ ).toHaveAttribute("aria-disabled", "true");
+
+ fireEvent.click(screen.getByRole("button", { name: "Older version" }));
+
+ expect(screen.getByText("v1/2")).toBeInTheDocument();
+ expect(
+ screen.getByRole("button", { name: "Older version" }),
+ ).toHaveAttribute("aria-disabled", "true");
+ let lastCall = useQuery.mock.calls.at(-1)?.[0] as {
+ queryKey: unknown[];
+ };
+ expect(lastCall.queryKey).toContain("artifact-0");
+
+ act(() => {
+ useCommentNavigationStore
+ .getState()
+ .requestCommentFocus(
+ "task-1",
+ { scope: "task_artifact", itemId: "artifact-1" },
+ "comment-1",
+ );
+ });
+
+ expect(screen.getByText("v2/2")).toBeInTheDocument();
+ lastCall = useQuery.mock.calls.at(-1)?.[0] as { queryKey: unknown[] };
+ expect(lastCall.queryKey).toContain("artifact-1");
+ });
+
+ it("saves edited source as a new output version under the same name", async () => {
+ const data = editablePreview();
+ taskRuns.data = [{ id: "run-1", artifacts: data.artifacts }];
+ useQuery.mockReturnValue({ data, isLoading: false, isError: false });
+
+ render(
+ <ArtifactPreview
+ taskId="task-1"
+ runId="run-1"
+ artifactId="artifact-1"
+ name="report.md"
+ />,
+ );
+
+ fireEvent.click(screen.getByRole("button", { name: "Edit" }));
+ fireEvent.change(screen.getByLabelText("Artifact source editor"), {
+ target: { value: "# Edited by user" },
+ });
+ fireEvent.click(screen.getByRole("button", { name: "Save" }));
+
+ await waitFor(() =>
+ expect(artifactMocks.uploadCloudRunArtifactVersion).toHaveBeenCalledWith(
+ "task-1",
+ "run-1",
+ "report.md",
+ "# Edited by user",
+ "text/markdown",
+ ),
+ );
+ expect(artifactMocks.invalidateQueries).toHaveBeenCalledWith({
+ queryKey: ["task-runs", "task-1"],
+ });
+ expect(artifactMocks.openArtifactTab).toHaveBeenCalledWith("task-1", {
+ runId: "run-1",
+ artifactId: "artifact-2",
+ name: "report.md",
+ });
+ });
+
+ it("asks before saving over a version that arrived during editing", async () => {
+ const data = editablePreview();
+ taskRuns.data = [{ id: "run-1", artifacts: data.artifacts }];
+ taskRuns.refreshRuns.mockResolvedValue([
+ { id: "run-1", artifacts: data.artifacts },
+ {
+ id: "run-2",
+ artifacts: [
+ {
+ ...data.artifact,
+ id: "artifact-2",
+ storage_path: "runs/2/report-v2.md",
+ uploaded_at: "2026-08-07T11:00:00Z",
+ },
+ ],
+ },
+ ]);
+ useQuery.mockReturnValue({ data, isLoading: false, isError: false });
+
+ render(
+ <ArtifactPreview
+ taskId="task-1"
+ runId="run-1"
+ artifactId="artifact-1"
+ name="report.md"
+ />,
+ );
+
+ fireEvent.click(screen.getByRole("button", { name: "Edit" }));
+ fireEvent.click(screen.getByRole("button", { name: "Save" }));
+
+ expect(
+ await screen.findByText(
+ "A newer version of this file arrived while you were editing. Save yours as the latest anyway?",
+ ),
+ ).toBeInTheDocument();
+ expect(artifactMocks.uploadCloudRunArtifactVersion).not.toHaveBeenCalled();
+
+ fireEvent.click(screen.getByRole("button", { name: "Save as latest" }));
+
+ await waitFor(() =>
+ expect(
+ artifactMocks.uploadCloudRunArtifactVersion,
+ ).toHaveBeenCalledOnce(),
+ );
+ });
+
+ it("explains that saving restores a file dismissed during editing", async () => {
+ const data = editablePreview();
+ taskRuns.data = [{ id: "run-1", artifacts: data.artifacts }];
+ taskRuns.refreshRuns.mockResolvedValue([
+ {
+ id: "run-1",
+ artifacts: data.artifacts.map((artifact) => ({
+ ...artifact,
+ dismissed_at: "2026-08-07T11:00:00Z",
+ })),
+ },
+ ]);
+ useQuery.mockReturnValue({ data, isLoading: false, isError: false });
+
+ render(
+ <ArtifactPreview
+ taskId="task-1"
+ runId="run-1"
+ artifactId="artifact-1"
+ name="report.md"
+ />,
+ );
+
+ fireEvent.click(screen.getByRole("button", { name: "Edit" }));
+ fireEvent.click(screen.getByRole("button", { name: "Save" }));
+
+ expect(
+ await screen.findByText(
+ "Every version of this file was dismissed while you were editing. Save your changes to restore it as the latest version?",
+ ),
+ ).toBeInTheDocument();
+ expect(
+ screen.getByRole("button", { name: "Save and restore" }),
+ ).toBeInTheDocument();
+ expect(artifactMocks.uploadCloudRunArtifactVersion).not.toHaveBeenCalled();
+ });
+
it("preserves authored styles and injects the inline-comment bridge", () => {
const document = artifactHtmlDocument(
'<!doctype html><html><head><style>.card{color:red}</style></head><body><div class="card" style="font-size:20px">Report</div></body></html>',
diff --git a/products/desktop/packages/ui/src/features/sessions/components/ArtifactPreview.tsx b/products/desktop/packages/ui/src/features/sessions/components/ArtifactPreview.tsx
index 7bcecee8f031..273b23b690d7 100644
--- a/products/desktop/packages/ui/src/features/sessions/components/ArtifactPreview.tsx
+++ b/products/desktop/packages/ui/src/features/sessions/components/ArtifactPreview.tsx
@@ -1,5 +1,10 @@
-import { CrosshairSimpleIcon, XIcon } from "@phosphor-icons/react";
+import { CaretLeftIcon, CaretRightIcon } from "@phosphor-icons/react";
import type { ResourceComment } from "@posthog/api-client/posthog-client";
+import {
+ groupRunArtifactVersions,
+ OUTPUT_ARTIFACT_TYPES,
+ parseRunArtifacts,
+} from "@posthog/core/canvas/runArtifactSchemas";
import {
type CommentAnchor,
type CommentTarget,
@@ -11,76 +16,69 @@ import {
} from "@posthog/core/sessions/sessionService";
import { useService } from "@posthog/di/react";
import { Button, Spinner } from "@posthog/quill";
-import { isAllowedImageMimeType } from "@posthog/shared";
+import type { TaskRun, TaskRunArtifact } from "@posthog/shared";
import {
getAuthIdentity,
useAuthStateValue,
} from "@posthog/ui/features/auth/store";
-import { AUTH_SCOPED_QUERY_META } from "@posthog/ui/features/auth/useCurrentUser";
import { useOrgMembers } from "@posthog/ui/features/canvas/hooks/useOrgMembers";
+import { useTaskRuns } from "@posthog/ui/features/canvas/hooks/useTaskRuns";
+import { usePanelLayoutStore } from "@posthog/ui/features/panels/panelLayoutStore";
import { useCommentNavigationStore } from "@posthog/ui/features/sessions/commentNavigationStore";
+import { useSessionSelector } from "@posthog/ui/features/sessions/sessionStore";
import { useCommentsEnabled } from "@posthog/ui/features/sessions/useCommentsEnabled";
-import { useQuery } from "@tanstack/react-query";
import {
- type ReactNode,
+ type ReactElement,
useCallback,
useEffect,
useMemo,
useRef,
useState,
} from "react";
-import { CodeMirrorEditor } from "../../code-editor/components/CodeMirrorEditor";
-import { DocumentPreviewHeader } from "../../code-editor/components/DocumentPreviewHeader";
-import { MarkdownDocumentPreview } from "../../code-editor/components/MarkdownDocumentPreview";
-import { AnnotatedArtifactHtml } from "./AnnotatedArtifactHtml";
-import { AnnotatedArtifactImage } from "./AnnotatedArtifactImage";
-import { ArtifactDocumentCommentAction } from "./ArtifactDocumentCommentAction";
-import { ArtifactTextAnnotations } from "./ArtifactTextAnnotations";
-import { artifactPreviewBlob } from "./artifactPreviewDocument";
+import { ArtifactEditView } from "./ArtifactEditView";
+import {
+ ArtifactPreviewContent,
+ ArtifactPreviewError,
+} from "./ArtifactPreviewContent";
import {
buildCommentThreads,
type CommentLocateRequest,
type HighlightResolution,
} from "./commentViewTypes";
+import { useCompletedArtifactUploads } from "./countArtifactUploads";
+import { useArtifactEditing } from "./useArtifactEditing";
+import {
+ editorFilePath,
+ useArtifactPreviewData,
+} from "./useArtifactPreviewData";
import { useCommentsQuery, useCreateComment } from "./useComments";
-const MARKDOWN_EXTENSIONS = new Set(["md", "mdx", "markdown"]);
-const HTML_EXTENSIONS = new Set(["html", "htm"]);
-/** SVG is excluded from the shared image allowlist because its scripts can run
- * when it comes from a data URL. An <img> renders SVG in a secure static mode
- * that never runs scripts, so the zoom-and-annotate surface is safe for it. */
-const SVG_MIME_TYPE = "image/svg+xml";
const EMPTY_COMMENTS: ResourceComment[] = [];
-type HtmlPreview = { kind: "html"; html: string };
-type PreviewData = string | Blob | HtmlPreview;
+type ArtifactVersion = TaskRunArtifact & { runId: string };
-function extension(filename: string): string {
- return filename.split(".").pop()?.toLowerCase() ?? "";
-}
-
-function ArtifactPreviewError() {
- return (
- <div className="flex h-full items-center justify-center text-muted-foreground">
- This artifact can’t be previewed.
- </div>
+function artifactVersionsFromRuns(
+ runs: TaskRun[],
+ name: string,
+): ArtifactVersion[] {
+ const files = runs.flatMap((run) =>
+ parseRunArtifacts(run.artifacts, OUTPUT_ARTIFACT_TYPES).flatMap((file) =>
+ file.name === name && file.id
+ ? [
+ {
+ ...file,
+ id: file.id,
+ name: file.name,
+ type: file.type as TaskRunArtifact["type"],
+ runId: run.id,
+ },
+ ]
+ : [],
+ ),
);
-}
-
-function GenericArtifactHeader({
- name,
- actions,
-}: {
- name: string;
- actions?: ReactNode;
-}) {
return (
- <header className="flex h-11 shrink-0 items-center justify-between border-border border-b px-3">
- <span className="truncate font-[var(--code-font-family)] text-[13px] text-muted-foreground">
- {name}
- </span>
- {actions}
- </header>
+ groupRunArtifactVersions(files).find((candidate) => candidate.name === name)
+ ?.versions ?? []
);
}
@@ -96,18 +94,47 @@ export function ArtifactPreview({
runId: string;
artifactId: string;
name: string;
-}) {
+}): ReactElement {
const commentsEnabled = useCommentsEnabled();
const sessionService = useService<SessionService>(SESSION_SERVICE);
+ const openArtifactTab = usePanelLayoutStore((state) => state.openArtifactTab);
const [showRendered, setShowRendered] = useState(true);
+ // Every version of this file across the task's runs, newest first - the
+ // same grouping the artifact list shows. Stepping through them swaps what
+ // this tab renders without opening more tabs. A finished upload_artifact
+ // tool call re-keys the runs query so a just-delivered version is steppable
+ // right away.
+ const events = useSessionSelector(taskId, (session) => session?.events);
+ const completedUploads = useCompletedArtifactUploads(events ?? []);
+ const {
+ runs,
+ isLoading: runsLoading,
+ refreshRuns,
+ } = useTaskRuns(taskId, completedUploads);
+ const versions = useMemo(
+ () => artifactVersionsFromRuns(runs, name),
+ [runs, name],
+ );
+ const refreshVersions = useCallback(async (): Promise<ArtifactVersion[]> => {
+ return artifactVersionsFromRuns(await refreshRuns(), name);
+ }, [name, refreshRuns]);
+ const [selectedVersionId, setSelectedVersionId] = useState<string | null>(
+ null,
+ );
+ const activeArtifactId = selectedVersionId ?? artifactId;
+ const versionIndex = versions.findIndex(
+ (version) => version.id === activeArtifactId,
+ );
+ const activeRunId =
+ versionIndex >= 0 ? (versions[versionIndex]?.runId ?? runId) : runId;
const markdownRootRef = useRef<HTMLDivElement>(null);
const markdownContainerRef = useRef<HTMLDivElement>(null);
const [imageError, setImageError] = useState(false);
const [imageCommenting, setImageCommenting] = useState(false);
const authIdentity = useAuthStateValue(getAuthIdentity);
const commentTarget = useMemo<CommentTarget>(
- () => ({ scope: "task_artifact", itemId: artifactId }),
- [artifactId],
+ () => ({ scope: "task_artifact", itemId: activeArtifactId }),
+ [activeArtifactId],
);
const commentsQuery = useCommentsQuery(commentTarget, taskId, {
enabled: commentsEnabled,
@@ -121,34 +148,39 @@ export function ArtifactPreview({
(state) => state.setCommentResolutions,
);
const focus = useCommentNavigationStore((state) => state.focusByTask[taskId]);
- const { data, isLoading, isError } = useQuery<PreviewData>({
- queryKey: ["artifactPreview", authIdentity, taskId, runId, artifactId],
- queryFn: async () => {
- const url = await sessionService.getCloudAttachmentPreviewUrl(
- taskId,
- runId,
- artifactId,
- );
- if (!url) throw new Error("Artifact is unavailable");
- const response = await fetch(url);
- if (!response.ok) throw new Error("Artifact preview failed");
- const blob = await response.blob();
- const fileExtension = extension(name);
- if (MARKDOWN_EXTENSIONS.has(fileExtension)) return blob.text();
- if (HTML_EXTENSIONS.has(fileExtension)) {
- return { kind: "html", html: await blob.text() };
- }
- return artifactPreviewBlob(blob, name);
- },
- enabled: authIdentity !== null,
- staleTime: Infinity,
- retry: false,
- meta: AUTH_SCOPED_QUERY_META,
+ useEffect(() => {
+ if (
+ !focus ||
+ focus.target.scope !== "task_artifact" ||
+ focus.target.itemId === activeArtifactId ||
+ !versions.some((version) => version.id === focus.target.itemId)
+ ) {
+ return;
+ }
+ setSelectedVersionId(focus.target.itemId);
+ }, [activeArtifactId, focus, versions]);
+ const { artifactResult, previewData, previewUrl, isLoading, isError } =
+ useArtifactPreviewData({
+ sessionService,
+ authIdentity,
+ taskId,
+ runId: activeRunId,
+ artifactId: activeArtifactId,
+ name,
+ });
+ const editing = useArtifactEditing({
+ sessionService,
+ artifactResult,
+ versions:
+ versions.length > 0 ? versions : (artifactResult?.artifacts ?? []),
+ versionsLoading: runsLoading,
+ refreshVersions,
+ taskId,
+ runId: activeRunId,
+ name,
+ authIdentity,
+ openArtifactTab,
});
- const previewUrl = useMemo(
- () => (data instanceof Blob ? URL.createObjectURL(data) : null),
- [data],
- );
const comments = commentsEnabled
? (commentsQuery.data ?? EMPTY_COMMENTS)
: EMPTY_COMMENTS;
@@ -165,14 +197,6 @@ export function ArtifactPreview({
() => threads.flatMap((thread) => (thread.resolved ? [] : [thread.root])),
[threads],
);
-
- useEffect(() => {
- return () => {
- if (previewUrl) URL.revokeObjectURL(previewUrl);
- };
- }, [previewUrl]);
-
- /** This artifact's share of the task's focus, if the focus is on it at all. */
const focusedThreadId =
focus && isSameCommentTarget(focus.target, commentTarget)
? focus.threadId
@@ -204,13 +228,11 @@ export function ArtifactPreview({
(id: string) => requestCommentFocus(taskId, commentTarget, id),
[requestCommentFocus, taskId, commentTarget],
);
-
const onResolutionsChange = useCallback(
(resolutions: Map<string, HighlightResolution>) =>
setCommentResolutions(commentTarget, resolutions),
[setCommentResolutions, commentTarget],
);
-
const createAnchoredComment = useCallback(
async (anchor: CommentAnchor, content: string, mentions: number[] = []) => {
const created = await createComment.mutateAsync({
@@ -223,6 +245,39 @@ export function ArtifactPreview({
[createComment, activateThread],
);
+ const versionNav =
+ versions.length > 1 && versionIndex >= 0 ? (
+ <div className="flex shrink-0 items-center gap-0.5">
+ <Button
+ size="icon"
+ variant="default"
+ aria-label="Older version"
+ disabled={versionIndex >= versions.length - 1}
+ onClick={() => {
+ const older = versions[versionIndex + 1];
+ if (older?.id) setSelectedVersionId(older.id);
+ }}
+ >
+ <CaretLeftIcon size={12} />
+ </Button>
+ <span className="text-[11px] text-muted-foreground tabular-nums">
+ v{versions.length - versionIndex}/{versions.length}
+ </span>
+ <Button
+ size="icon"
+ variant="default"
+ aria-label="Newer version"
+ disabled={versionIndex <= 0}
+ onClick={() => {
+ const newer = versions[versionIndex - 1];
+ if (newer?.id) setSelectedVersionId(newer.id);
+ }}
+ >
+ <CaretRightIcon size={12} />
+ </Button>
+ </div>
+ ) : null;
+
if (isLoading) {
return (
<div className="flex h-full items-center justify-center">
@@ -232,156 +287,57 @@ export function ArtifactPreview({
}
if (isError || imageError) return <ArtifactPreviewError />;
- if (typeof data === "string") {
- return (
- <div className="flex h-full flex-col overflow-hidden">
- <DocumentPreviewHeader
- label={name}
- content={data}
- showRendered={showRendered}
- onToggleRendered={() => setShowRendered((rendered) => !rendered)}
- actions={
- commentsEnabled ? (
- <ArtifactDocumentCommentAction
- target={commentTarget}
- taskId={taskId}
- />
- ) : undefined
- }
- />
- {commentLoadError}
- {showRendered ? (
- <div
- ref={markdownContainerRef}
- className="relative min-h-0 min-w-0 flex-1 overflow-auto"
- >
- <div ref={markdownRootRef}>
- <MarkdownDocumentPreview
- content={data}
- components={{ img: () => null }}
- />
- </div>
- {commentsEnabled && (
- <ArtifactTextAnnotations
- artifactName={name}
- rootRef={markdownRootRef}
- containerRef={markdownContainerRef}
- comments={annotationComments}
- activeThreadId={focusedThreadId}
- locateRequest={locateRequest}
- members={members}
- onActivateThread={activateThread}
- onCreate={createAnchoredComment}
- onResolutionsChange={onResolutionsChange}
- />
- )}
- </div>
- ) : (
- <div className="min-h-0 min-w-0 flex-1 overflow-hidden">
- <CodeMirrorEditor content={data} filePath={name} readOnly />
- </div>
- )}
- </div>
- );
- }
-
- if (data && !(data instanceof Blob) && data.kind === "html") {
- return (
- <div className="flex h-full flex-col overflow-hidden">
- <GenericArtifactHeader
- name={name}
- actions={
- commentsEnabled ? (
- <ArtifactDocumentCommentAction
- target={commentTarget}
- taskId={taskId}
- />
- ) : undefined
- }
- />
- {commentLoadError}
- <div className="min-h-0 min-w-0 flex-1">
- <AnnotatedArtifactHtml
- html={data.html}
- name={name}
- commentsEnabled={commentsEnabled}
- comments={annotationComments}
- activeThreadId={focusedThreadId}
- locateRequest={locateRequest}
- members={members}
- onActivateThread={activateThread}
- onCreate={createAnchoredComment}
- onResolutionsChange={onResolutionsChange}
- />
- </div>
- </div>
- );
- }
-
- if (!previewUrl || !data) return <ArtifactPreviewError />;
-
if (
- data instanceof Blob &&
- (isAllowedImageMimeType(data.type) || data.type === SVG_MIME_TYPE)
+ editing.isEditing &&
+ artifactResult?.source !== undefined &&
+ editing.editableKind
) {
- const imageActions = commentsEnabled ? (
- <div className="flex items-center gap-1">
- <ArtifactDocumentCommentAction target={commentTarget} taskId={taskId} />
- <Button
- size="sm"
- variant={imageCommenting ? "primary" : "outline"}
- onClick={() => setImageCommenting((commenting) => !commenting)}
- >
- {imageCommenting ? <XIcon /> : <CrosshairSimpleIcon />}
- {imageCommenting ? "Cancel" : "Pin comment…"}
- </Button>
- </div>
- ) : undefined;
return (
- <div className="flex h-full flex-col overflow-hidden">
- <GenericArtifactHeader name={name} actions={imageActions} />
- {commentLoadError}
- <div className="min-h-0 min-w-0 flex-1">
- <AnnotatedArtifactImage
- src={previewUrl}
- name={name}
- comments={annotationComments}
- activeThreadId={focusedThreadId}
- locateRequest={locateRequest}
- commenting={commentsEnabled && imageCommenting}
- members={members}
- onCommentingChange={setImageCommenting}
- onActivateThread={activateThread}
- onCreate={createAnchoredComment}
- onError={() => setImageError(true)}
- />
- </div>
- </div>
+ <ArtifactEditView
+ name={name}
+ source={artifactResult.source}
+ editorPath={editorFilePath(editing.editableKind, name)}
+ showRendered={showRendered}
+ saving={editing.saving}
+ conflict={editing.conflict}
+ onConflictOpenChange={editing.setConflictOpen}
+ getContent={editing.getDraftContent}
+ onContentChange={editing.setDraftContent}
+ onCancel={editing.cancelEditing}
+ onSave={() => void editing.saveDraft()}
+ onForceSave={() => void editing.forceSaveDraft()}
+ />
);
}
return (
- <div className="flex h-full flex-col overflow-hidden">
- <GenericArtifactHeader
- name={name}
- actions={
- commentsEnabled ? (
- <ArtifactDocumentCommentAction
- target={commentTarget}
- taskId={taskId}
- />
- ) : undefined
- }
- />
- {commentLoadError}
- <div className="min-h-0 min-w-0 flex-1">
- <iframe
- className="h-full w-full border-0 bg-white"
- sandbox=""
- src={previewUrl}
- title={`Preview of ${name}`}
- />
- </div>
- </div>
+ <ArtifactPreviewContent
+ name={name}
+ versionNav={versionNav}
+ taskId={taskId}
+ commentTarget={commentTarget}
+ commentsEnabled={commentsEnabled}
+ canEdit={editing.canEdit}
+ beginEditing={editing.beginEditing}
+ previewData={previewData}
+ previewUrl={previewUrl}
+ showRendered={showRendered}
+ setShowRendered={setShowRendered}
+ commentLoadError={commentLoadError}
+ markdownRootRef={markdownRootRef}
+ markdownContainerRef={markdownContainerRef}
+ annotationComments={annotationComments}
+ focusedThreadId={focusedThreadId}
+ locateRequest={locateRequest}
+ members={members}
+ activateThread={activateThread}
+ createAnchoredComment={createAnchoredComment}
+ onResolutionsChange={onResolutionsChange}
+ imageCommenting={imageCommenting}
+ setImageCommenting={setImageCommenting}
+ onImageError={() => setImageError(true)}
+ editableKind={editing.editableKind}
+ artifactResult={artifactResult}
+ />
);
}
diff --git a/products/desktop/packages/ui/src/features/sessions/components/ArtifactPreviewContent.tsx b/products/desktop/packages/ui/src/features/sessions/components/ArtifactPreviewContent.tsx
new file mode 100644
index 000000000000..189adeb0ebe8
--- /dev/null
+++ b/products/desktop/packages/ui/src/features/sessions/components/ArtifactPreviewContent.tsx
@@ -0,0 +1,335 @@
+import { CrosshairSimpleIcon, XIcon } from "@phosphor-icons/react";
+import type { ResourceComment } from "@posthog/api-client/posthog-client";
+import type {
+ CommentAnchor,
+ CommentTarget,
+} from "@posthog/core/comments/anchors";
+import {
+ Button,
+ Spinner,
+ Tooltip,
+ TooltipContent,
+ TooltipTrigger,
+} from "@posthog/quill";
+import { isAllowedImageMimeType } from "@posthog/shared";
+import type { UserBasic } from "@posthog/shared/domain-types";
+import type {
+ Dispatch,
+ ReactElement,
+ ReactNode,
+ RefObject,
+ SetStateAction,
+} from "react";
+import { CodeMirrorEditor } from "../../code-editor/components/CodeMirrorEditor";
+import { DocumentPreviewHeader } from "../../code-editor/components/DocumentPreviewHeader";
+import { MarkdownDocumentPreview } from "../../code-editor/components/MarkdownDocumentPreview";
+import { AnnotatedArtifactHtml } from "./AnnotatedArtifactHtml";
+import { AnnotatedArtifactImage } from "./AnnotatedArtifactImage";
+import { ArtifactDocumentCommentAction } from "./ArtifactDocumentCommentAction";
+import { ArtifactTextAnnotations } from "./ArtifactTextAnnotations";
+import type {
+ CommentLocateRequest,
+ HighlightResolution,
+} from "./commentViewTypes";
+import type {
+ ArtifactPreviewResult,
+ EditableArtifactKind,
+ PreviewData,
+} from "./useArtifactPreviewData";
+
+const SVG_MIME_TYPE = "image/svg+xml";
+
+export function ArtifactPreviewError(): ReactElement {
+ return (
+ <div className="flex h-full items-center justify-center text-muted-foreground">
+ This artifact can’t be previewed.
+ </div>
+ );
+}
+
+function GenericArtifactHeader({
+ name,
+ versionNav,
+ actions,
+}: {
+ name: string;
+ versionNav?: ReactNode;
+ actions?: ReactNode;
+}): ReactElement {
+ return (
+ <header className="flex h-10 shrink-0 items-center justify-between gap-2 border-border border-b px-3">
+ <div className="flex min-w-0 items-center gap-2">
+ <span className="truncate font-[var(--code-font-family)] text-[13px] text-muted-foreground">
+ {name}
+ </span>
+ {versionNav}
+ </div>
+ {actions}
+ </header>
+ );
+}
+
+export function ArtifactPreviewContent({
+ name,
+ versionNav,
+ taskId,
+ commentTarget,
+ commentsEnabled,
+ canEdit,
+ beginEditing,
+ previewData,
+ previewUrl,
+ showRendered,
+ setShowRendered,
+ commentLoadError,
+ markdownRootRef,
+ markdownContainerRef,
+ annotationComments,
+ focusedThreadId,
+ locateRequest,
+ members,
+ activateThread,
+ createAnchoredComment,
+ onResolutionsChange,
+ imageCommenting,
+ setImageCommenting,
+ onImageError,
+ editableKind,
+ artifactResult,
+}: {
+ name: string;
+ versionNav?: ReactNode;
+ taskId: string;
+ commentTarget: CommentTarget;
+ commentsEnabled: boolean;
+ canEdit: boolean;
+ beginEditing: () => void;
+ previewData: PreviewData | undefined;
+ previewUrl: string | null;
+ showRendered: boolean;
+ setShowRendered: Dispatch<SetStateAction<boolean>>;
+ commentLoadError: ReactNode;
+ markdownRootRef: RefObject<HTMLDivElement | null>;
+ markdownContainerRef: RefObject<HTMLDivElement | null>;
+ annotationComments: ResourceComment[];
+ focusedThreadId: string | null;
+ locateRequest: CommentLocateRequest | null;
+ members: UserBasic[];
+ activateThread: (id: string) => void;
+ createAnchoredComment: (
+ anchor: CommentAnchor,
+ content: string,
+ mentions?: number[],
+ ) => Promise<void>;
+ onResolutionsChange: (resolutions: Map<string, HighlightResolution>) => void;
+ imageCommenting: boolean;
+ setImageCommenting: Dispatch<SetStateAction<boolean>>;
+ onImageError: () => void;
+ editableKind: EditableArtifactKind | null;
+ artifactResult: ArtifactPreviewResult | undefined;
+}): ReactElement {
+ if (typeof previewData === "string") {
+ return (
+ <div className="flex h-full flex-col overflow-hidden">
+ <DocumentPreviewHeader
+ label={name}
+ versionNav={versionNav}
+ content={previewData}
+ getContent={() => previewData}
+ showRendered={showRendered}
+ onToggleRendered={() => setShowRendered((rendered) => !rendered)}
+ canEdit={canEdit}
+ onEdit={beginEditing}
+ actions={
+ commentsEnabled ? (
+ <ArtifactDocumentCommentAction
+ target={commentTarget}
+ taskId={taskId}
+ />
+ ) : undefined
+ }
+ />
+ {commentLoadError}
+ {showRendered ? (
+ <div
+ ref={markdownContainerRef}
+ className="relative min-h-0 min-w-0 flex-1 overflow-auto"
+ >
+ <div ref={markdownRootRef}>
+ <MarkdownDocumentPreview
+ content={previewData}
+ components={{ img: () => null }}
+ />
+ </div>
+ {commentsEnabled && (
+ <ArtifactTextAnnotations
+ artifactName={name}
+ rootRef={markdownRootRef}
+ containerRef={markdownContainerRef}
+ comments={annotationComments}
+ activeThreadId={focusedThreadId}
+ locateRequest={locateRequest}
+ members={members}
+ onActivateThread={activateThread}
+ onCreate={createAnchoredComment}
+ onResolutionsChange={onResolutionsChange}
+ />
+ )}
+ </div>
+ ) : (
+ <div className="min-h-0 min-w-0 flex-1 overflow-hidden">
+ <CodeMirrorEditor content={previewData} filePath={name} readOnly />
+ </div>
+ )}
+ </div>
+ );
+ }
+
+ if (
+ previewData &&
+ !(previewData instanceof Blob) &&
+ previewData.kind === "html"
+ ) {
+ return (
+ <div className="flex h-full flex-col overflow-hidden">
+ <DocumentPreviewHeader
+ label={name}
+ versionNav={versionNav}
+ content={previewData.html}
+ getContent={() => previewData.html}
+ showRendered
+ canEdit={canEdit}
+ onEdit={beginEditing}
+ actions={
+ commentsEnabled ? (
+ <ArtifactDocumentCommentAction
+ target={commentTarget}
+ taskId={taskId}
+ />
+ ) : undefined
+ }
+ />
+ {commentLoadError}
+ <div className="min-h-0 min-w-0 flex-1">
+ <AnnotatedArtifactHtml
+ html={previewData.html}
+ name={name}
+ commentsEnabled={commentsEnabled}
+ comments={annotationComments}
+ activeThreadId={focusedThreadId}
+ locateRequest={locateRequest}
+ members={members}
+ onActivateThread={activateThread}
+ onCreate={createAnchoredComment}
+ onResolutionsChange={onResolutionsChange}
+ />
+ </div>
+ </div>
+ );
+ }
+
+ if (!previewData) return <ArtifactPreviewError />;
+ if (previewData instanceof Blob && !previewUrl) {
+ return (
+ <div className="flex h-full items-center justify-center">
+ <Spinner />
+ </div>
+ );
+ }
+ if (!previewUrl) return <ArtifactPreviewError />;
+
+ if (
+ previewData instanceof Blob &&
+ (isAllowedImageMimeType(previewData.type) ||
+ previewData.type === SVG_MIME_TYPE)
+ ) {
+ const imageActions = commentsEnabled ? (
+ <div className="flex shrink-0 items-center gap-1">
+ <ArtifactDocumentCommentAction target={commentTarget} taskId={taskId} />
+ <Tooltip>
+ <TooltipTrigger
+ render={
+ <Button
+ size="icon"
+ variant={imageCommenting ? "primary" : "default"}
+ aria-label={imageCommenting ? "Cancel pinning" : "Pin comment…"}
+ onClick={() => setImageCommenting((commenting) => !commenting)}
+ />
+ }
+ >
+ {imageCommenting ? (
+ <XIcon size={14} />
+ ) : (
+ <CrosshairSimpleIcon size={14} />
+ )}
+ </TooltipTrigger>
+ <TooltipContent>
+ {imageCommenting
+ ? "Cancel pinning"
+ : "Pin a comment to a spot on the image"}
+ </TooltipContent>
+ </Tooltip>
+ </div>
+ ) : undefined;
+ return (
+ <div className="flex h-full flex-col overflow-hidden">
+ <GenericArtifactHeader
+ name={name}
+ versionNav={versionNav}
+ actions={imageActions}
+ />
+ {commentLoadError}
+ <div className="min-h-0 min-w-0 flex-1">
+ <AnnotatedArtifactImage
+ src={previewUrl}
+ name={name}
+ comments={annotationComments}
+ activeThreadId={focusedThreadId}
+ locateRequest={locateRequest}
+ commenting={commentsEnabled && imageCommenting}
+ members={members}
+ onCommentingChange={setImageCommenting}
+ onActivateThread={activateThread}
+ onCreate={createAnchoredComment}
+ onError={onImageError}
+ />
+ </div>
+ </div>
+ );
+ }
+
+ const documentActions = commentsEnabled ? (
+ <ArtifactDocumentCommentAction target={commentTarget} taskId={taskId} />
+ ) : undefined;
+ return (
+ <div className="flex h-full flex-col overflow-hidden">
+ {editableKind === "plain-text" && artifactResult?.source !== undefined ? (
+ <DocumentPreviewHeader
+ label={name}
+ versionNav={versionNav}
+ content={artifactResult.source}
+ getContent={() => artifactResult.source ?? ""}
+ showRendered
+ canEdit={canEdit}
+ onEdit={beginEditing}
+ actions={documentActions}
+ />
+ ) : (
+ <GenericArtifactHeader
+ name={name}
+ versionNav={versionNav}
+ actions={documentActions}
+ />
+ )}
+ {commentLoadError}
+ <div className="min-h-0 min-w-0 flex-1">
+ <iframe
+ className="h-full w-full border-0 bg-white"
+ sandbox=""
+ src={previewUrl}
+ title={`Preview of ${name}`}
+ />
+ </div>
+ </div>
+ );
+}
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 2c80d9d4c081..758b365ef918 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
@@ -7,6 +7,7 @@ const getCloudAttachmentPreviewUrl = vi.fn();
const setCloudRunArtifactsDismissed = vi.fn();
const openArtifactTab = vi.fn();
const refetch = vi.fn();
+const queryOptions = vi.fn();
let fetchedArtifacts: unknown[] | undefined = [];
let session: {
cloudArtifacts?: unknown[];
@@ -45,17 +46,25 @@ vi.mock("@posthog/ui/features/auth/store", () => ({
useAuthStateValue: () => "auth-1",
}));
+vi.mock("@posthog/ui/features/auth/useMeQuery", () => ({
+ useMeQuery: () => ({ data: { id: 42 } }),
+}));
+
vi.mock("@tanstack/react-query", () => ({
- useQuery: () => ({ data: fetchedArtifacts, refetch }),
+ useQuery: (options: unknown) => {
+ queryOptions(options);
+ return { data: fetchedArtifacts, refetch };
+ },
useMutation: ({
mutationFn,
onSuccess,
}: {
mutationFn: (variables: unknown) => Promise<unknown>;
- onSuccess: (result: unknown) => void;
+ onSuccess: (result: unknown) => Promise<void> | void;
}) => ({
isPending: false,
- mutate: (variables: unknown) => void mutationFn(variables).then(onSuccess),
+ mutate: (variables: unknown) =>
+ void mutationFn(variables).then((result) => onSuccess(result)),
}),
}));
@@ -99,6 +108,8 @@ describe("CloudArtifactDownloads", () => {
];
session = {};
refetch.mockReset();
+ refetch.mockResolvedValue({ data: undefined });
+ queryOptions.mockReset();
getCloudAttachmentPreviewUrl.mockReset();
setCloudRunArtifactsDismissed.mockReset();
openArtifactTab.mockReset();
@@ -127,6 +138,7 @@ describe("CloudArtifactDownloads", () => {
expect(screen.getByText("report.pdf")).toBeInTheDocument();
expect(screen.getByText("12 KB")).toBeInTheDocument();
expect(screen.queryByText("handoff.pack")).not.toBeInTheDocument();
+ expect(screen.queryByText("Edited by you")).not.toBeInTheDocument();
fireEvent.click(screen.getByText("Download"));
@@ -184,6 +196,31 @@ describe("CloudArtifactDownloads", () => {
}
});
+ it("labels versions edited by the current user", () => {
+ fetchedArtifacts = [
+ {
+ id: "output-1",
+ name: "report.md",
+ type: "output",
+ uploaded_at: "2026-07-27T08:00:00+00:00",
+ uploaded_by: "user",
+ uploaded_by_user_id: 42,
+ },
+ {
+ id: "output-2",
+ name: "report.md",
+ type: "output",
+ uploaded_at: "2026-07-27T09:00:00+00:00",
+ },
+ ];
+
+ renderDownloads();
+
+ expect(screen.queryByText("Edited by you")).not.toBeInTheDocument();
+ fireEvent.click(screen.getByLabelText("Choose a version of report.md"));
+ expect(screen.getByText(/Version 1 · Edited by you ·/)).toBeInTheDocument();
+ });
+
it("opens an artifact preview in a new tab", () => {
renderDownloads();
@@ -229,6 +266,36 @@ describe("CloudArtifactDownloads", () => {
});
});
+ it("defaults to the newest undismissed version", () => {
+ fetchedArtifacts = [
+ {
+ id: "output-1",
+ name: "report.pdf",
+ type: "output",
+ size: 1_000,
+ uploaded_at: "2026-07-27T08:00:00+00:00",
+ },
+ {
+ id: "output-2",
+ name: "report.pdf",
+ type: "output",
+ size: 2_000,
+ uploaded_at: "2026-07-27T09:00:00+00:00",
+ dismissed_at: "2026-07-27T10:00:00+00:00",
+ },
+ ];
+
+ renderDownloads();
+
+ expect(screen.getByText("1 KB")).toBeInTheDocument();
+ fireEvent.click(screen.getByText("report.pdf"));
+ expect(openArtifactTab).toHaveBeenCalledWith("task-1", {
+ runId: "run-1",
+ artifactId: "output-1",
+ name: "report.pdf",
+ });
+ });
+
// A manifest entry carries an id only once the upload is finalized, and a
// version the picker cannot switch to is worse than no picker at all.
it("switches to a version that has no id", () => {
@@ -259,6 +326,29 @@ describe("CloudArtifactDownloads", () => {
expect(screen.getByText("1 KB")).toBeInTheDocument();
});
+ it("disables dismissal until every version has an id", () => {
+ fetchedArtifacts = [
+ {
+ name: "report.pdf",
+ type: "output",
+ uploaded_at: "2026-07-27T09:00:00+00:00",
+ },
+ {
+ id: "output-1",
+ name: "report.pdf",
+ type: "output",
+ uploaded_at: "2026-07-27T08:00:00+00:00",
+ },
+ ];
+
+ renderDownloads();
+
+ const dismiss = screen.getByLabelText("Dismiss report.pdf");
+ expect(dismiss).toHaveAttribute("aria-disabled", "true");
+ fireEvent.click(dismiss);
+ expect(setCloudRunArtifactsDismissed).not.toHaveBeenCalled();
+ });
+
// Dismissing the row a user sees has to take the versions behind it too,
// otherwise the file reappears as its own older upload.
it("dismisses every version of a file", async () => {
@@ -281,6 +371,10 @@ describe("CloudArtifactDownloads", () => {
dismissed_at: "2026-07-27T10:00:00+00:00",
}));
setCloudRunArtifactsDismissed.mockResolvedValue(dismissedManifest);
+ refetch.mockImplementation(async () => {
+ fetchedArtifacts = dismissedManifest;
+ return { data: dismissedManifest };
+ });
renderDownloads();
@@ -377,7 +471,7 @@ describe("CloudArtifactDownloads", () => {
// Nothing pushes the run's manifest to this client, so without the tool call as a trigger a
// freshly delivered file waits for the backstop poll.
- it("rereads the manifest as soon as an upload finishes", () => {
+ it("changes the manifest query key as soon as an upload finishes", () => {
session = { cloudStatus: "in_progress", events: [] };
const { rerender } = renderDownloads();
@@ -401,7 +495,26 @@ describe("CloudArtifactDownloads", () => {
</Theme>,
);
- expect(refetch).toHaveBeenCalled();
+ expect(queryOptions).toHaveBeenLastCalledWith(
+ expect.objectContaining({
+ queryKey: ["cloudRunArtifacts", "auth-1", "task-1", "run-1", 1],
+ }),
+ );
+ expect(refetch).not.toHaveBeenCalled();
+ });
+
+ it.each([
+ { status: "in_progress", interval: 120_000 },
+ { status: "completed", interval: false },
+ { status: undefined, interval: false },
+ ])("uses the backstop poll for $status runs", ({ status, interval }) => {
+ session = { cloudStatus: status };
+
+ renderDownloads();
+
+ expect(queryOptions).toHaveBeenCalledWith(
+ expect.objectContaining({ refetchInterval: interval }),
+ );
});
// Collapse state lives in a module-scoped store that nothing here resets, so
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 72a520fe0de6..cc97100ad8ae 100644
--- a/products/desktop/packages/ui/src/features/sessions/components/CloudArtifactDownloads.tsx
+++ b/products/desktop/packages/ui/src/features/sessions/components/CloudArtifactDownloads.tsx
@@ -25,11 +25,12 @@ import {
Text,
} from "@posthog/quill";
import { formatRelativeTimeShort, type TaskRunArtifact } from "@posthog/shared";
-import { isTerminalStatus, type Task } from "@posthog/shared/domain-types";
+import type { Task } from "@posthog/shared/domain-types";
import {
getAuthIdentity,
useAuthStateValue,
} from "@posthog/ui/features/auth/store";
+import { useMeQuery } from "@posthog/ui/features/auth/useMeQuery";
import { usePanelLayoutStore } from "@posthog/ui/features/panels/panelLayoutStore";
import { useSessionSelector } from "@posthog/ui/features/sessions/sessionStore";
import {
@@ -42,8 +43,8 @@ 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 { useEffect, useMemo, useRef, useState } from "react";
-import { createArtifactUploadTracker } from "./countArtifactUploads";
+import { useMemo, useState } from "react";
+import { useCompletedArtifactUploads } from "./countArtifactUploads";
type ArtifactGroup = RunArtifactVersions<TaskRunArtifact>;
@@ -51,15 +52,30 @@ type ArtifactGroup = RunArtifactVersions<TaskRunArtifact>;
* The menu sits at the right edge of the thread, and its popup is capped at the space left
* there and clips what does not fit, so the age is the compact form rather than the row's.
*/
+function wasEditedByCurrentUser(
+ artifact: TaskRunArtifact,
+ currentUserId: number | undefined,
+): boolean {
+ return (
+ artifact.uploaded_by === "user" &&
+ currentUserId !== undefined &&
+ artifact.uploaded_by_user_id === currentUserId
+ );
+}
+
function versionMenuLabel(
artifact: TaskRunArtifact,
index: number,
total: number,
+ currentUserId: number | undefined,
): string {
- const label = runArtifactVersionLabel(index, total);
- return artifact.uploaded_at
- ? `${label} · ${formatRelativeTimeShort(artifact.uploaded_at)}`
- : label;
+ return [
+ runArtifactVersionLabel(index, total),
+ wasEditedByCurrentUser(artifact, currentUserId) ? "Edited by you" : null,
+ artifact.uploaded_at ? formatRelativeTimeShort(artifact.uploaded_at) : null,
+ ]
+ .filter(Boolean)
+ .join(" · ");
}
export function CloudArtifactDownloads({
@@ -83,6 +99,7 @@ export function CloudArtifactDownloads({
const { setArtifactFilesCollapsed } = useSessionViewActions();
const authIdentity = useAuthStateValue(getAuthIdentity);
const { download, downloadingId } = useArtifactDownload();
+ const { data: currentUser } = useMeQuery();
const [selectedVersionByName, setSelectedVersionByName] = useState<
Record<string, string>
>({});
@@ -91,34 +108,28 @@ export function CloudArtifactDownloads({
>({});
const [showDismissed, setShowDismissed] = useState(false);
const runId = task?.latest_run?.id;
- const isTerminal = isTerminalStatus(cloudStatus ?? task?.latest_run?.status);
+ const runStatus = cloudStatus ?? task?.latest_run?.status;
+ const isLive = runStatus === "queued" || runStatus === "in_progress";
+ const events = useSessionSelector(taskId, (session) => session?.events);
+ const completedUploads = useCompletedArtifactUploads(events ?? []);
const { data: fetchedArtifacts, refetch } = useQuery({
- queryKey: ["cloudRunArtifacts", authIdentity, taskId, runId],
+ queryKey: [
+ "cloudRunArtifacts",
+ authIdentity,
+ taskId,
+ runId,
+ completedUploads,
+ ],
queryFn: () =>
sessionService.getCloudRunArtifacts(taskId ?? "", runId ?? ""),
enabled:
authIdentity !== null && taskId !== undefined && runId !== undefined,
retry: false,
staleTime: 15_000,
- // Backstop only, for an upload whose tool call never reached this client.
- refetchInterval: isTerminal ? false : 30_000,
+ // Tool completion triggers an immediate refresh; this only covers missing tool events.
+ refetchInterval: isLive ? 120_000 : false,
});
- // The agent's own upload_artifact call is the earliest signal a new file exists,
- // so read the manifest the moment one finishes rather than on the next tick.
- const events = useSessionSelector(taskId, (session) => session?.events);
- const uploadTracker = useRef<ReturnType<
- typeof createArtifactUploadTracker
- > | null>(null);
- uploadTracker.current ??= createArtifactUploadTracker();
- const tracker = uploadTracker.current;
- const completedUploads = useMemo(
- () => tracker.update(events ?? []),
- [events, tracker],
- );
- useEffect(() => {
- if (completedUploads > 0) void refetch();
- }, [completedUploads, refetch]);
const groups = useMemo(
() =>
groupRunArtifactVersions(
@@ -127,13 +138,14 @@ export function CloudArtifactDownloads({
sessionArtifacts ??
task?.latest_run?.artifacts ??
[]
- )
- .filter((artifact) => artifact.type === "output")
- .map((artifact) =>
+ ).flatMap((artifact) => {
+ if (artifact.type !== "output") return [];
+ return [
artifact.id && artifact.id in dismissalOverrides
? { ...artifact, dismissed_at: dismissalOverrides[artifact.id] }
: artifact,
- ),
+ ];
+ }),
),
[
dismissalOverrides,
@@ -152,16 +164,23 @@ export function CloudArtifactDownloads({
}: {
group: ArtifactGroup;
dismissed: boolean;
- }) =>
- sessionService.setCloudRunArtifactsDismissed(
+ }) => {
+ const artifactIds = group.versions.flatMap((version) =>
+ version.id ? [version.id] : [],
+ );
+ if (artifactIds.length !== group.versions.length) {
+ throw new Error("Artifact versions are still uploading");
+ }
+ return sessionService.setCloudRunArtifactsDismissed(
taskId ?? "",
runId ?? "",
- group.versions.flatMap((version) => version.id ?? []),
+ artifactIds,
dismissed,
- ),
+ );
+ },
// Overlay just the dismissal stamps from the response, so the row updates at once without
// parking a whole-manifest snapshot over a source that keeps refreshing behind it.
- onSuccess: (manifest) =>
+ onSuccess: async (manifest) => {
setDismissalOverrides((current) => ({
...current,
...Object.fromEntries(
@@ -169,23 +188,29 @@ export function CloudArtifactDownloads({
entry.id ? [[entry.id, entry.dismissed_at ?? null]] : [],
),
),
- })),
+ }));
+ const refreshed = await refetch();
+ if (refreshed?.data) setDismissalOverrides({});
+ },
onError: () => toast.error("Couldn't update this file"),
});
if (!runId || groups.length === 0) return null;
const renderRow = (group: ArtifactGroup) => {
- const selectedIndex = Math.max(
- group.versions.findIndex(
- (version) =>
- runArtifactVersionKey(version) === selectedVersionByName[group.name],
- ),
- 0,
+ const pickedIndex = group.versions.findIndex(
+ (version) =>
+ runArtifactVersionKey(version) === selectedVersionByName[group.name],
);
+ const newestVisibleIndex = group.versions.findIndex(
+ (version) => !version.dismissed_at,
+ );
+ const selectedIndex =
+ pickedIndex >= 0 ? pickedIndex : Math.max(newestVisibleIndex, 0);
const selected = group.versions[selectedIndex] as TaskRunArtifact;
const size = formatFileSize(selected.size);
const canDownload = Boolean(selected.id);
+ const canChangeDismissal = group.versions.every((version) => version.id);
return (
<div
@@ -210,6 +235,11 @@ export function CloudArtifactDownloads({
{size !== null && (
<Text className="shrink-0 text-[12px] text-gray-10">{size}</Text>
)}
+ {wasEditedByCurrentUser(selected, currentUser?.id) && (
+ <Text className="shrink-0 text-[12px] text-gray-10">
+ Edited by you
+ </Text>
+ )}
<RelativeTimestamp timestamp={selected.uploaded_at} />
</button>
{group.versions.length > 1 && (
@@ -240,7 +270,12 @@ export function CloudArtifactDownloads({
}))
}
>
- {versionMenuLabel(version, index, group.versions.length)}
+ {versionMenuLabel(
+ version,
+ index,
+ group.versions.length,
+ currentUser?.id,
+ )}
</DropdownMenuItem>
))}
</DropdownMenuContent>
@@ -250,7 +285,7 @@ export function CloudArtifactDownloads({
<Button
size="sm"
variant="outline"
- disabled={dismissal.isPending}
+ disabled={dismissal.isPending || !canChangeDismissal}
onClick={() => dismissal.mutate({ group, dismissed: false })}
>
Restore
@@ -278,7 +313,7 @@ export function CloudArtifactDownloads({
size="icon-sm"
variant="outline"
aria-label={`Dismiss ${group.name}`}
- disabled={dismissal.isPending}
+ disabled={dismissal.isPending || !canChangeDismissal}
onClick={() => dismissal.mutate({ group, dismissed: true })}
>
<X size={14} />
diff --git a/products/desktop/packages/ui/src/features/sessions/components/countArtifactUploads.test.ts b/products/desktop/packages/ui/src/features/sessions/components/countArtifactUploads.test.ts
index c051a38a9302..16742e7b37bf 100644
--- a/products/desktop/packages/ui/src/features/sessions/components/countArtifactUploads.test.ts
+++ b/products/desktop/packages/ui/src/features/sessions/components/countArtifactUploads.test.ts
@@ -1,6 +1,9 @@
import type { AcpMessage } from "@posthog/shared";
import { describe, expect, it } from "vitest";
-import { createArtifactUploadTracker } from "./countArtifactUploads";
+import {
+ countCompletedArtifactUploads,
+ createArtifactUploadTracker,
+} from "./countArtifactUploads";
function toolCallEvent(
sessionUpdate: "tool_call" | "tool_call_update",
@@ -63,21 +66,20 @@ describe("createArtifactUploadTracker", () => {
});
it("counts each upload separately", () => {
- const tracker = createArtifactUploadTracker();
+ const events = [
+ toolCallEvent("tool_call", { toolCallId: "c1", toolName: UPLOAD }),
+ toolCallEvent("tool_call_update", {
+ toolCallId: "c1",
+ status: "completed",
+ }),
+ toolCallEvent("tool_call", { toolCallId: "c2", toolName: UPLOAD }),
+ toolCallEvent("tool_call_update", {
+ toolCallId: "c2",
+ status: "completed",
+ }),
+ ];
- expect(
- tracker.update([
- toolCallEvent("tool_call", { toolCallId: "c1", toolName: UPLOAD }),
- toolCallEvent("tool_call_update", {
- toolCallId: "c1",
- status: "completed",
- }),
- toolCallEvent("tool_call", { toolCallId: "c2", toolName: UPLOAD }),
- toolCallEvent("tool_call_update", {
- toolCallId: "c2",
- status: "completed",
- }),
- ]),
- ).toBe(2);
+ expect(createArtifactUploadTracker().update(events)).toBe(2);
+ expect(countCompletedArtifactUploads(events)).toBe(2);
});
});
diff --git a/products/desktop/packages/ui/src/features/sessions/components/countArtifactUploads.ts b/products/desktop/packages/ui/src/features/sessions/components/countArtifactUploads.ts
index c22547886e83..3cdc168dc59b 100644
--- a/products/desktop/packages/ui/src/features/sessions/components/countArtifactUploads.ts
+++ b/products/desktop/packages/ui/src/features/sessions/components/countArtifactUploads.ts
@@ -1,5 +1,10 @@
import { createAppendOnlyTracker } from "@posthog/core/sessions/appendOnlyTracker";
-import { isJsonRpcNotification, readMcpToolDescriptor } from "@posthog/shared";
+import {
+ type AcpMessage,
+ isJsonRpcNotification,
+ readMcpToolDescriptor,
+} from "@posthog/shared";
+import { useMemo, useRef } from "react";
const UPLOAD_ARTIFACT_TOOL = "upload_artifact";
@@ -60,3 +65,16 @@ export function createArtifactUploadTracker() {
getResult: (state) => state.completedCallIds.size,
});
}
+
+export function countCompletedArtifactUploads(events: AcpMessage[]): number {
+ return createArtifactUploadTracker().update(events);
+}
+
+export function useCompletedArtifactUploads(events: AcpMessage[]): number {
+ const trackerRef = useRef<ReturnType<
+ typeof createArtifactUploadTracker
+ > | null>(null);
+ trackerRef.current ??= createArtifactUploadTracker();
+ const tracker = trackerRef.current;
+ return useMemo(() => tracker.update(events), [events, tracker]);
+}
diff --git a/products/desktop/packages/ui/src/features/sessions/components/useArtifactEditing.ts b/products/desktop/packages/ui/src/features/sessions/components/useArtifactEditing.ts
new file mode 100644
index 000000000000..c640a9cd4b31
--- /dev/null
+++ b/products/desktop/packages/ui/src/features/sessions/components/useArtifactEditing.ts
@@ -0,0 +1,193 @@
+import { runArtifactVersionKey } from "@posthog/core/canvas/runArtifactSchemas";
+import type { SessionService } from "@posthog/core/sessions/sessionService";
+import type { TaskRunArtifact } from "@posthog/shared";
+import { toast } from "@posthog/ui/primitives/toast";
+import { useMutation, useQueryClient } from "@tanstack/react-query";
+import { useRef, useState } from "react";
+import {
+ type ArtifactPreviewResult,
+ type EditableArtifactKind,
+ editableArtifactKind,
+ newestUndismissedVersion,
+} from "./useArtifactPreviewData";
+
+interface SaveArtifactVariables {
+ artifact: TaskRunArtifact;
+ content: string;
+}
+
+export type ArtifactEditConflict = "newer-version" | "dismissed";
+
+export function useArtifactEditing({
+ sessionService,
+ artifactResult,
+ versions,
+ versionsLoading,
+ refreshVersions,
+ taskId,
+ runId,
+ name,
+ authIdentity,
+ openArtifactTab,
+}: {
+ sessionService: SessionService;
+ artifactResult: ArtifactPreviewResult | undefined;
+ versions: TaskRunArtifact[];
+ versionsLoading: boolean;
+ refreshVersions: () => Promise<TaskRunArtifact[]>;
+ taskId: string;
+ runId: string;
+ name: string;
+ authIdentity: string | null;
+ openArtifactTab: (
+ taskId: string,
+ artifact: { runId: string; artifactId: string; name: string },
+ ) => void;
+}): {
+ editableKind: EditableArtifactKind | null;
+ canEdit: boolean;
+ isEditing: boolean;
+ saving: boolean;
+ conflict: ArtifactEditConflict | null;
+ setConflictOpen: (open: boolean) => void;
+ beginEditing: () => void;
+ cancelEditing: () => void;
+ saveDraft: () => Promise<void>;
+ forceSaveDraft: () => Promise<void>;
+ getDraftContent: () => string;
+ setDraftContent: (content: string) => void;
+} {
+ const queryClient = useQueryClient();
+ const [isEditing, setIsEditing] = useState(false);
+ const [checkingLatest, setCheckingLatest] = useState(false);
+ const [conflict, setConflict] = useState<ArtifactEditConflict | null>(null);
+ const draftRef = useRef("");
+ const editingBaseKeyRef = useRef<string | null>(null);
+ const editableKind = artifactResult
+ ? editableArtifactKind(artifactResult.artifact)
+ : null;
+ const latest = artifactResult
+ ? newestUndismissedVersion(versions, artifactResult.artifact.name)
+ : undefined;
+ const canEdit = Boolean(
+ editableKind &&
+ !versionsLoading &&
+ artifactResult?.source !== undefined &&
+ latest &&
+ artifactResult &&
+ runArtifactVersionKey(latest) ===
+ runArtifactVersionKey(artifactResult.artifact),
+ );
+
+ const saveArtifact = useMutation({
+ mutationFn: (variables: SaveArtifactVariables) =>
+ sessionService.uploadCloudRunArtifactVersion(
+ taskId,
+ runId,
+ variables.artifact.name,
+ variables.content,
+ variables.artifact.content_type,
+ ),
+ onSuccess: async (savedArtifactId) => {
+ await Promise.all([
+ queryClient.invalidateQueries({
+ queryKey: ["cloudRunArtifacts", authIdentity, taskId, runId],
+ }),
+ queryClient.invalidateQueries({ queryKey: ["task-runs", taskId] }),
+ ]);
+ setConflict(null);
+ setIsEditing(false);
+ openArtifactTab(taskId, {
+ runId,
+ artifactId: savedArtifactId,
+ name,
+ });
+ },
+ onError: () =>
+ toast.error("Couldn't save file", {
+ description: "Try again. Your changes are still in the editor.",
+ }),
+ });
+
+ const beginEditing = (): void => {
+ if (!artifactResult || artifactResult.source === undefined) return;
+ draftRef.current = artifactResult.source;
+ editingBaseKeyRef.current = runArtifactVersionKey(artifactResult.artifact);
+ setIsEditing(true);
+ };
+
+ const cancelEditing = (): void => {
+ setIsEditing(false);
+ setConflict(null);
+ draftRef.current = "";
+ editingBaseKeyRef.current = null;
+ };
+
+ const saveDraft = async (): Promise<void> => {
+ if (!artifactResult || checkingLatest || saveArtifact.isPending) return;
+ setCheckingLatest(true);
+ let currentLatest: TaskRunArtifact | undefined;
+ try {
+ const refreshedVersions = await refreshVersions();
+ currentLatest = newestUndismissedVersion(
+ refreshedVersions,
+ artifactResult.artifact.name,
+ );
+ } catch {
+ toast.error("Couldn't check the latest file version", {
+ description: "Try saving again. Your changes are still in the editor.",
+ });
+ return;
+ } finally {
+ setCheckingLatest(false);
+ }
+
+ if (!currentLatest) {
+ setConflict("dismissed");
+ return;
+ }
+ if (runArtifactVersionKey(currentLatest) !== editingBaseKeyRef.current) {
+ setConflict("newer-version");
+ return;
+ }
+ try {
+ await saveArtifact.mutateAsync({
+ artifact: artifactResult.artifact,
+ content: draftRef.current,
+ });
+ } catch {
+ return;
+ }
+ };
+
+ const forceSaveDraft = async (): Promise<void> => {
+ if (!artifactResult || saveArtifact.isPending) return;
+ try {
+ await saveArtifact.mutateAsync({
+ artifact: artifactResult.artifact,
+ content: draftRef.current,
+ });
+ } catch {
+ return;
+ }
+ };
+
+ return {
+ editableKind,
+ canEdit,
+ isEditing,
+ saving: checkingLatest || saveArtifact.isPending,
+ conflict,
+ setConflictOpen: (open) => {
+ if (!open) setConflict(null);
+ },
+ beginEditing,
+ cancelEditing,
+ saveDraft,
+ forceSaveDraft,
+ getDraftContent: () => draftRef.current,
+ setDraftContent: (content) => {
+ draftRef.current = content;
+ },
+ };
+}
diff --git a/products/desktop/packages/ui/src/features/sessions/components/useArtifactPreviewData.ts b/products/desktop/packages/ui/src/features/sessions/components/useArtifactPreviewData.ts
new file mode 100644
index 000000000000..3a23663e3011
--- /dev/null
+++ b/products/desktop/packages/ui/src/features/sessions/components/useArtifactPreviewData.ts
@@ -0,0 +1,158 @@
+import { groupRunArtifactVersions } from "@posthog/core/canvas/runArtifactSchemas";
+import type { SessionService } from "@posthog/core/sessions/sessionService";
+import type { TaskRunArtifact } from "@posthog/shared";
+import { AUTH_SCOPED_QUERY_META } from "@posthog/ui/features/auth/useCurrentUser";
+import { useQuery } from "@tanstack/react-query";
+import { useEffect, useState } from "react";
+import { artifactPreviewBlob } from "./artifactPreviewDocument";
+
+const MARKDOWN_EXTENSIONS = new Set(["md", "mdx", "markdown"]);
+const HTML_EXTENSIONS = new Set(["html", "htm"]);
+
+export type HtmlPreview = { kind: "html"; html: string };
+export type PreviewData = string | Blob | HtmlPreview;
+export type EditableArtifactKind = "html" | "markdown" | "plain-text";
+
+export interface ArtifactPreviewResult {
+ artifact: TaskRunArtifact;
+ artifacts: TaskRunArtifact[];
+ preview: PreviewData;
+ source?: string;
+}
+
+function extension(filename: string): string {
+ return filename.split(".").pop()?.toLowerCase() ?? "";
+}
+
+export function editableArtifactKind(
+ artifact: TaskRunArtifact,
+): EditableArtifactKind | null {
+ const contentType = artifact.content_type
+ ?.split(";")[0]
+ ?.trim()
+ .toLowerCase();
+ if (contentType === "text/markdown") return "markdown";
+ if (contentType === "text/html") return "html";
+ if (contentType === "text/plain") return "plain-text";
+ if (contentType) return null;
+
+ if (extension(artifact.name) === "md") return "markdown";
+ if (extension(artifact.name) === "html") return "html";
+ if (extension(artifact.name) === "txt") return "plain-text";
+ return null;
+}
+
+export function newestUndismissedVersion(
+ artifacts: TaskRunArtifact[],
+ name: string,
+): TaskRunArtifact | undefined {
+ const group = groupRunArtifactVersions(artifacts).find(
+ (candidate) => candidate.name === name,
+ );
+ return group?.versions.find((version) => !version.dismissed_at);
+}
+
+export function editorFilePath(
+ kind: EditableArtifactKind,
+ name: string,
+): string {
+ const expectedExtension =
+ kind === "markdown" ? "md" : kind === "html" ? "html" : "txt";
+ return extension(name) === expectedExtension
+ ? name
+ : `artifact.${expectedExtension}`;
+}
+
+function isArtifactPreviewResult(
+ data: PreviewData | ArtifactPreviewResult | undefined,
+): data is ArtifactPreviewResult {
+ return Boolean(data && typeof data === "object" && "preview" in data);
+}
+
+export function useArtifactPreviewData({
+ sessionService,
+ authIdentity,
+ taskId,
+ runId,
+ artifactId,
+ name,
+}: {
+ sessionService: SessionService;
+ authIdentity: string | null;
+ taskId: string;
+ runId: string;
+ artifactId: string;
+ name: string;
+}): {
+ artifactResult: ArtifactPreviewResult | undefined;
+ previewData: PreviewData | undefined;
+ previewUrl: string | null;
+ isLoading: boolean;
+ isError: boolean;
+} {
+ const { data, isLoading, isError } = useQuery<
+ PreviewData | ArtifactPreviewResult
+ >({
+ queryKey: ["artifactPreview", authIdentity, taskId, runId, artifactId],
+ queryFn: async () => {
+ const [artifacts, url] = await Promise.all([
+ sessionService.getCloudRunArtifacts(taskId, runId),
+ sessionService.getCloudAttachmentPreviewUrl(taskId, runId, artifactId),
+ ]);
+ const artifact = artifacts.find(
+ (candidate) => candidate.id === artifactId,
+ );
+ if (!artifact) throw new Error("Artifact is unavailable");
+ if (!url) throw new Error("Artifact is unavailable");
+ const response = await fetch(url);
+ if (!response.ok) throw new Error("Artifact preview failed");
+ const blob = await response.blob();
+ const fileExtension = extension(name);
+ const editableKind = editableArtifactKind(artifact);
+ const needsSource =
+ editableKind !== null || MARKDOWN_EXTENSIONS.has(fileExtension);
+ const source = needsSource ? await blob.text() : undefined;
+ let preview: PreviewData;
+ if (
+ editableKind === "markdown" ||
+ MARKDOWN_EXTENSIONS.has(fileExtension)
+ ) {
+ preview = source ?? "";
+ } else if (
+ editableKind === "html" ||
+ HTML_EXTENSIONS.has(fileExtension)
+ ) {
+ preview = { kind: "html", html: source ?? (await blob.text()) };
+ } else {
+ preview = await artifactPreviewBlob(blob, name);
+ }
+ return {
+ artifact,
+ artifacts,
+ preview,
+ ...(source === undefined ? {} : { source }),
+ };
+ },
+ enabled: authIdentity !== null,
+ staleTime: Infinity,
+ retry: false,
+ meta: AUTH_SCOPED_QUERY_META,
+ });
+ const artifactResult = isArtifactPreviewResult(data) ? data : undefined;
+ const previewData: PreviewData | undefined = artifactResult
+ ? artifactResult.preview
+ : (data as PreviewData | undefined);
+ const [previewUrl, setPreviewUrl] = useState<string | null>(null);
+
+ useEffect(() => {
+ if (!(previewData instanceof Blob)) {
+ setPreviewUrl(null);
+ return;
+ }
+ const objectUrl = URL.createObjectURL(previewData);
+ setPreviewUrl(objectUrl);
+ return () => URL.revokeObjectURL(objectUrl);
+ }, [previewData]);
+
+ return { artifactResult, previewData, previewUrl, isLoading, isError };
+}
diff --git a/products/desktop/packages/ui/src/features/sessions/sessionServiceHost.ts b/products/desktop/packages/ui/src/features/sessions/sessionServiceHost.ts
index 9811a824307a..70522ffc080e 100644
--- a/products/desktop/packages/ui/src/features/sessions/sessionServiceHost.ts
+++ b/products/desktop/packages/ui/src/features/sessions/sessionServiceHost.ts
@@ -157,6 +157,15 @@ function buildSessionServiceDeps(): SessionServiceDeps {
getCloudPromptTransport,
resolveLocalSkillCommandPrompt: (prompt) =>
resolveLocalSkillPrompt(prompt, () => trpc.skills.list.query()),
+ uploadRunOutput: (client, taskId, runId, name, content, contentType) =>
+ cloudArtifactService.uploadRunOutput(
+ client,
+ taskId,
+ runId,
+ name,
+ content,
+ contentType,
+ ),
uploadRunAttachments: (client, taskId, runId, filePaths, skillBundles) =>
cloudArtifactService.uploadRunAttachments(
client,