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(tasks): group artifact versions, share links and image zoom (#109814)

Shy Alter8915e7a6b6ef
diff --git a/products/posthog_ai/frontend/scenes/TaskTracker/components/ArtifactImageViewer.tsx b/products/posthog_ai/frontend/scenes/TaskTracker/components/ArtifactImageViewer.tsx
new file mode 100644
index 000000000000..23399ca6a321
--- /dev/null
+++ b/products/posthog_ai/frontend/scenes/TaskTracker/components/ArtifactImageViewer.tsx
@@ -0,0 +1,182 @@
+import { PointerEvent, useCallback, useLayoutEffect, useRef, useState } from 'react'
+
+import { IconMinus, IconPlus } from '@posthog/icons'
+import { Button, Separator, Text, Toggle, Tooltip, TooltipContent, TooltipTrigger, cn } from '@posthog/quill-primitives'
+
+const ZOOM_STEPS = [0.1, 0.25, 0.5, 0.75, 1, 1.5, 2, 3, 4, 6, 8]
+// Room the image keeps from the pane edges when it fits, so its border never touches them.
+const FIT_INSET_PX = 48
+
+type Zoom = 'fit' | number
+
+function nextStep(current: number, direction: 1 | -1): number {
+ const steps = direction === 1 ? ZOOM_STEPS : [...ZOOM_STEPS].reverse()
+ return steps.find((step) => (direction === 1 ? step > current + 0.001 : step < current - 0.001)) ?? current
+}
+
+function ZoomButton({
+ label,
+ disabledReason,
+ onClick,
+ dataAttr,
+ children,
+}: {
+ label: string
+ disabledReason?: string
+ onClick: () => void
+ dataAttr: string
+ children: JSX.Element
+}): JSX.Element {
+ return (
+ <Tooltip>
+ <TooltipTrigger
+ delay={0}
+ render={
+ <Button
+ size="icon"
+ aria-label={label}
+ disabled={!!disabledReason}
+ onClick={onClick}
+ data-attr={dataAttr}
+ />
+ }
+ >
+ {children}
+ </TooltipTrigger>
+ <TooltipContent>{disabledReason ?? label}</TooltipContent>
+ </Tooltip>
+ )
+}
+
+/** An image preview that fits the pane, zooms in steps, and pans by drag once it overflows. */
+export function ArtifactImageViewer({ src, alt }: { src: string; alt: string }): JSX.Element {
+ const paneRef = useRef<HTMLDivElement>(null)
+ const dragRef = useRef<{ x: number; y: number; left: number; top: number } | null>(null)
+ const [natural, setNatural] = useState<{ width: number; height: number } | null>(null)
+ const [pane, setPane] = useState<{ width: number; height: number } | null>(null)
+ const [zoom, setZoom] = useState<Zoom>('fit')
+ const [dragging, setDragging] = useState(false)
+
+ useLayoutEffect(() => {
+ const element = paneRef.current
+ if (!element) {
+ return
+ }
+ const observer = new ResizeObserver(([entry]) =>
+ setPane({ width: entry.contentRect.width, height: entry.contentRect.height })
+ )
+ observer.observe(element)
+ return () => observer.disconnect()
+ }, [])
+
+ // A small image is shown at its own size, never stretched past 100%.
+ const fitScale =
+ natural && pane
+ ? Math.min(1, (pane.width - FIT_INSET_PX) / natural.width, (pane.height - FIT_INSET_PX) / natural.height)
+ : 1
+ const scale = zoom === 'fit' ? fitScale : zoom
+ const width = natural ? Math.max(1, Math.round(natural.width * scale)) : undefined
+ const overflows = !!natural && !!pane && (width! > pane.width || natural.height * scale > pane.height)
+
+ const zoomBy = useCallback((direction: 1 | -1) => setZoom(nextStep(scale, direction)), [scale])
+
+ const onPointerDown = (event: PointerEvent<HTMLDivElement>): void => {
+ const element = paneRef.current
+ if (!overflows || !element || event.button !== 0) {
+ return
+ }
+ dragRef.current = { x: event.clientX, y: event.clientY, left: element.scrollLeft, top: element.scrollTop }
+ element.setPointerCapture(event.pointerId)
+ setDragging(true)
+ }
+ const onPointerMove = (event: PointerEvent<HTMLDivElement>): void => {
+ const element = paneRef.current
+ const start = dragRef.current
+ if (!element || !start) {
+ return
+ }
+ element.scrollLeft = start.left - (event.clientX - start.x)
+ element.scrollTop = start.top - (event.clientY - start.y)
+ }
+ const endDrag = (): void => {
+ dragRef.current = null
+ setDragging(false)
+ }
+
+ return (
+ <div data-quill className="relative size-full">
+ <div
+ ref={paneRef}
+ className={cn(
+ 'size-full overflow-auto',
+ overflows && (dragging ? 'cursor-grabbing select-none' : 'cursor-grab')
+ )}
+ onPointerDown={onPointerDown}
+ onPointerMove={onPointerMove}
+ onPointerUp={endDrag}
+ onPointerCancel={endDrag}
+ onDoubleClick={() => setZoom(zoom === 'fit' ? 1 : 'fit')}
+ >
+ {/* min-size centers the image while it fits and lets the scroll area grow once it does not. */}
+ <div className="flex min-h-full min-w-full w-max items-center justify-center p-6">
+ <img
+ src={src}
+ alt={alt}
+ draggable={false}
+ style={width ? { width } : undefined}
+ className={cn(
+ 'block max-w-none rounded-sm border border-border bg-white',
+ !natural && 'invisible'
+ )}
+ onLoad={(event) =>
+ setNatural({
+ width: event.currentTarget.naturalWidth || 1,
+ height: event.currentTarget.naturalHeight || 1,
+ })
+ }
+ />
+ </div>
+ </div>
+ {natural && (
+ <div className="absolute bottom-3 left-1/2 flex -translate-x-1/2 items-center gap-0.5 rounded-md border border-border bg-background p-0.5 shadow-sm">
+ <ZoomButton
+ label="Zoom out"
+ disabledReason={scale <= ZOOM_STEPS[0] ? 'This is the smallest size' : undefined}
+ onClick={() => zoomBy(-1)}
+ dataAttr="task-artifact-zoom-out"
+ >
+ <IconMinus className="size-4" />
+ </ZoomButton>
+ <Text size="xs" render={<span />} className="w-11 text-center tabular-nums" aria-live="polite">
+ {`${Math.round(scale * 100)}%`}
+ </Text>
+ <ZoomButton
+ label="Zoom in"
+ disabledReason={
+ scale >= ZOOM_STEPS[ZOOM_STEPS.length - 1] ? 'This is the largest size' : undefined
+ }
+ onClick={() => zoomBy(1)}
+ dataAttr="task-artifact-zoom-in"
+ >
+ <IconPlus className="size-4" />
+ </ZoomButton>
+ <Separator orientation="vertical" className="mx-1 h-4" />
+ <Toggle
+ pressed={zoom === 'fit'}
+ onPressedChange={() => setZoom('fit')}
+ data-attr="task-artifact-zoom-fit"
+ >
+ Fit
+ </Toggle>
+ <Toggle
+ pressed={zoom === 1}
+ onPressedChange={() => setZoom(1)}
+ data-attr="task-artifact-zoom-actual"
+ >
+ 100%
+ </Toggle>
+ </div>
+ )}
+ </div>
+ )
+}
diff --git a/products/posthog_ai/frontend/scenes/TaskTracker/components/TaskDetailPage.tsx b/products/posthog_ai/frontend/scenes/TaskTracker/components/TaskDetailPage.tsx
index be1ba46fb722..46f8fbc2a3c1 100644
--- a/products/posthog_ai/frontend/scenes/TaskTracker/components/TaskDetailPage.tsx
+++ b/products/posthog_ai/frontend/scenes/TaskTracker/components/TaskDetailPage.tsx
@@ -115,6 +115,7 @@ export function TaskDetailPage({ taskId, isMobile, titleActions }: TaskDetailPag
task={task}
selectedRun={selectedRun}
isHeaderLoading={isHeaderLoading && !isActiveCreation}
+ headerDivider={!artifactsTabEnabled}
titleActions={
<div className="flex flex-wrap items-center gap-2">
{taskActions}
diff --git a/products/posthog_ai/frontend/scenes/TaskTracker/components/TaskRunArtifacts.tsx b/products/posthog_ai/frontend/scenes/TaskTracker/components/TaskRunArtifacts.tsx
index 7c6c105fe8b9..a856dac705fc 100644
--- a/products/posthog_ai/frontend/scenes/TaskTracker/components/TaskRunArtifacts.tsx
+++ b/products/posthog_ai/frontend/scenes/TaskTracker/components/TaskRunArtifacts.tsx
@@ -19,7 +19,6 @@ import { cn } from 'lib/utils/css-classes'
import { withStrictCsp } from '../artifactHtml'
import {
- ARTIFACT_KIND_LABEL,
ArtifactPreviewKind,
RunArtifact,
TaskRunTab,
@@ -28,6 +27,7 @@ import {
parseCsv,
} from '../taskRunArtifacts'
import { artifactDownloadUrl, taskRunArtifactsLogic } from '../taskRunArtifactsLogic'
+import { ArtifactImageViewer } from './ArtifactImageViewer'
const MAX_CSV_ROWS = 500
@@ -96,17 +96,7 @@ function ArtifactPreview({ taskId }: { taskId: string }): JSX.Element | null {
}
if (selectedKind === 'image') {
const src = artifactDownloadUrl(currentProjectId, taskId, selectedArtifact)
- return (
- <div className="flex min-h-full items-center justify-center p-8">
- {src && (
- <img
- src={src}
- alt={selectedArtifact.name}
- className="max-w-full rounded border border-primary bg-white"
- />
- )}
- </div>
- )
+ return src ? <ArtifactImageViewer src={src} alt={selectedArtifact.name} /> : null
}
if (selectedKind === 'none') {
return (
@@ -157,54 +147,62 @@ function ArtifactPreview({ taskId }: { taskId: string }): JSX.Element | null {
}
function ArtifactNav({ taskId }: { taskId: string }): JSX.Element {
- const { artifacts, selectedArtifact } = useValues(taskRunArtifactsLogic({ taskId }))
+ const { files, selectedFile } = useValues(taskRunArtifactsLogic({ taskId }))
const { selectArtifact } = useActions(taskRunArtifactsLogic({ taskId }))
return (
<nav
- className="hidden w-64 shrink-0 flex-col gap-px overflow-y-auto border-r border-primary p-2 @[52rem]/main-content:flex"
+ className="hidden w-64 shrink-0 flex-col border-r border-primary @[52rem]/main-content:flex"
aria-label="Artifacts"
>
- <span className="py-1 pl-2 text-xs font-semibold text-secondary">{`Files ${artifacts.length}`}</span>
- {artifacts.map((artifact) => {
- const kind = artifactPreviewKind(artifact)
- return (
- <LemonButton
- key={artifact.id}
- fullWidth
- size="small"
- active={artifact.id === selectedArtifact?.id}
- icon={<KindIcon kind={kind} />}
- onClick={() => artifact.id && selectArtifact(artifact.id)}
- data-attr="task-artifact-nav-item"
- >
- <span className="flex min-w-0 flex-col py-0.5">
- <span className="truncate">{artifact.name}</span>
- <span className="text-xs font-normal text-secondary">
- {`${ARTIFACT_KIND_LABEL[kind]} · ${formatArtifactSize(artifact.size)}`}
+ <div className="flex h-10 shrink-0 items-center gap-1.5 border-b border-primary px-3 text-xs font-semibold text-secondary">
+ <span>Files</span>
+ <span className="font-normal tabular-nums">{files.length}</span>
+ </div>
+ <div className="flex min-h-0 flex-1 flex-col gap-px overflow-y-auto p-1.5">
+ {files.map((file) => {
+ const artifact = file.latest
+ const kind = artifactPreviewKind(artifact)
+ return (
+ <LemonButton
+ key={file.name}
+ fullWidth
+ size="small"
+ active={file.name === selectedFile?.name}
+ icon={<KindIcon kind={kind} />}
+ onClick={() => selectArtifact(file.name)}
+ data-attr="task-artifact-nav-item"
+ >
+ <span className="flex min-w-0 flex-col py-0.5">
+ <span className="truncate">{artifact.name}</span>
+ <span className="text-xs font-normal text-secondary">
+ {`${formatArtifactSize(artifact.size)} · ${dayjs(artifact.uploaded_at).fromNow()}`}
+ </span>
</span>
- </span>
- </LemonButton>
- )
- })}
+ </LemonButton>
+ )
+ })}
+ </div>
</nav>
)
}
function ArtifactToolbar({ taskId, artifact }: { taskId: string; artifact: RunArtifact }): JSX.Element {
- const { artifacts, selectedIndex, currentProjectId } = useValues(taskRunArtifactsLogic({ taskId }))
+ const { files, selectedIndex, currentProjectId } = useValues(taskRunArtifactsLogic({ taskId }))
const { stepArtifact, downloadArtifact } = useActions(taskRunArtifactsLogic({ taskId }))
const kind = artifactPreviewKind(artifact)
const downloadUrl = artifactDownloadUrl(currentProjectId, taskId, artifact)
- const single = artifacts.length < 2
+ const single = files.length < 2
return (
- <div className="flex shrink-0 flex-wrap items-center gap-2 border-b border-primary px-3 py-1.5">
+ <div className="flex h-10 shrink-0 items-center gap-2 border-b border-primary px-3">
<span className="flex size-4 shrink-0 items-center text-secondary">
<KindIcon kind={kind} />
</span>
<span className="min-w-0 truncate font-semibold">{artifact.name}</span>
- <span className="text-xs text-secondary">
- {`${formatArtifactSize(artifact.size)} · ${dayjs(artifact.uploaded_at).fromNow()}`}
- </span>
+ <Tooltip title={dayjs(artifact.uploaded_at).format('MMM D, YYYY HH:mm')}>
+ <span className="hidden shrink-0 text-xs text-secondary @[40rem]/main-content:inline">
+ {`${formatArtifactSize(artifact.size)} · ${dayjs(artifact.uploaded_at).fromNow()}`}
+ </span>
+ </Tooltip>
{kind === 'html' && (
<Tooltip title="This page runs in a sandbox with scripts off. It cannot read your PostHog data, cookies or session.">
<LemonTag type="muted" icon={<IconLock />}>
@@ -212,22 +210,25 @@ function ArtifactToolbar({ taskId, artifact }: { taskId: string; artifact: RunAr
</LemonTag>
</Tooltip>
)}
- <div className="ml-auto flex items-center gap-1">
- <span className="px-1 text-xs text-secondary tabular-nums">{`${selectedIndex + 1} of ${artifacts.length}`}</span>
- <LemonButton
- size="small"
- icon={<IconChevronLeft />}
- tooltip="Previous file"
- disabledReason={single ? 'This is the only file' : undefined}
- onClick={() => stepArtifact(-1)}
- />
- <LemonButton
- size="small"
- icon={<IconChevronRight />}
- tooltip="Next file"
- disabledReason={single ? 'This is the only file' : undefined}
- onClick={() => stepArtifact(1)}
- />
+ <div className="ml-auto flex shrink-0 items-center gap-1">
+ {/* The file list replaces these once there is room for it. */}
+ <span className="flex items-center gap-1 @[52rem]/main-content:hidden">
+ <span className="px-1 text-xs text-secondary tabular-nums">{`${selectedIndex + 1} of ${files.length}`}</span>
+ <LemonButton
+ size="small"
+ icon={<IconChevronLeft />}
+ tooltip="Previous file"
+ disabledReason={single ? 'This is the only file' : undefined}
+ onClick={() => stepArtifact(-1)}
+ />
+ <LemonButton
+ size="small"
+ icon={<IconChevronRight />}
+ tooltip="Next file"
+ disabledReason={single ? 'This is the only file' : undefined}
+ onClick={() => stepArtifact(1)}
+ />
+ </span>
<LemonButton
size="small"
icon={<IconDownload />}
@@ -271,7 +272,7 @@ function ArtifactsWorkspace({ taskId }: { taskId: string }): JSX.Element {
<div
className={cn(
'min-h-0 flex-1 bg-surface-secondary',
- selectedKind === 'html' ? 'flex flex-col' : 'overflow-y-auto'
+ selectedKind === 'html' || selectedKind === 'image' ? 'flex flex-col' : 'overflow-y-auto'
)}
>
<ArtifactPreview taskId={taskId} />
@@ -283,7 +284,7 @@ function ArtifactsWorkspace({ taskId }: { taskId: string }): JSX.Element {
/** Conversation and Artifacts tabs for a task run. The caller renders the thread as `conversation`. */
export function TaskRunTabs({ taskId, conversation }: { taskId: string; conversation: JSX.Element }): JSX.Element {
- const { activeTab, artifacts } = useValues(taskRunArtifactsLogic({ taskId }))
+ const { activeTab, files } = useValues(taskRunArtifactsLogic({ taskId }))
const { setActiveTab } = useActions(taskRunArtifactsLogic({ taskId }))
return (
<>
@@ -298,7 +299,10 @@ export function TaskRunTabs({ taskId, conversation }: { taskId: string; conversa
label: (
<span className="flex items-center gap-1.5">
<span>Artifacts</span>
- {artifacts.length > 0 && <span className="text-secondary">{artifacts.length}</span>}
+ {files.length > 0 && (
+ // The active tab colors its whole label, and a count is not a call to action.
+ <span className="font-normal text-secondary! tabular-nums">{files.length}</span>
+ )}
</span>
),
'data-attr': 'task-run-tab-artifacts',
diff --git a/products/posthog_ai/frontend/scenes/TaskTracker/components/TaskRunSceneShell.tsx b/products/posthog_ai/frontend/scenes/TaskTracker/components/TaskRunSceneShell.tsx
index 5ac582c58716..f402968d8bab 100644
--- a/products/posthog_ai/frontend/scenes/TaskTracker/components/TaskRunSceneShell.tsx
+++ b/products/posthog_ai/frontend/scenes/TaskTracker/components/TaskRunSceneShell.tsx
@@ -41,6 +41,8 @@ export interface TaskRunSceneShellProps {
taskError: string | null
onRetry: () => void
isMobile: boolean
+ /** Off when a tab bar sits right under the header and draws its own rule. */
+ headerDivider?: boolean
/** The run-log slot (the streamed thread). */
children: ReactNode
}
@@ -60,6 +62,7 @@ export function TaskRunSceneShell({
taskError,
onRetry,
isMobile,
+ headerDivider = true,
children,
}: TaskRunSceneShellProps): JSX.Element {
return (
@@ -164,7 +167,7 @@ export function TaskRunSceneShell({
selectedRun && <TaskRunMetadata selectedRun={selectedRun} />
)}
- <LemonDivider className="hidden lg:block mb-0 mt-2" />
+ {headerDivider && <LemonDivider className="hidden lg:block mb-0 mt-2" />}
</header>
{children}
diff --git a/products/posthog_ai/frontend/scenes/TaskTracker/taskRunArtifacts.test.ts b/products/posthog_ai/frontend/scenes/TaskTracker/taskRunArtifacts.test.ts
index 7670699b2488..abe4a84d0fd5 100644
--- a/products/posthog_ai/frontend/scenes/TaskTracker/taskRunArtifacts.test.ts
+++ b/products/posthog_ai/frontend/scenes/TaskTracker/taskRunArtifacts.test.ts
@@ -1,6 +1,13 @@
import type { TaskRunArtifactResponseApi } from 'products/tasks/frontend/generated/api.schemas'
-import { artifactPreviewKind, collectRunArtifacts, parseCsv, visibleRunArtifacts } from './taskRunArtifacts'
+import {
+ RunArtifact,
+ artifactPreviewKind,
+ collectRunArtifacts,
+ groupArtifactVersions,
+ parseCsv,
+ visibleRunArtifacts,
+} from './taskRunArtifacts'
function artifact(overrides: Partial<TaskRunArtifactResponseApi>): TaskRunArtifactResponseApi {
return {
@@ -83,4 +90,40 @@ describe('taskRunArtifacts', () => {
{ id: 'report', runId: 'run-1', uploaded_at: '2026-09-30T17:00:00Z' },
])
})
+
+ test.each([
+ [
+ 'merges one name across runs, newest first',
+ [
+ { id: 'report-1', runId: 'run-1', name: 'report.md', uploaded_at: '2026-09-30T17:00:00Z' },
+ { id: 'report-3', runId: 'run-2', name: 'report.md', uploaded_at: '2026-09-30T19:00:00Z' },
+ { id: 'report-2', runId: 'run-1', name: 'report.md', uploaded_at: '2026-09-30T18:00:00Z' },
+ ],
+ [{ name: 'report.md', versionIds: ['report-3', 'report-2', 'report-1'], latestId: 'report-3' }],
+ ],
+ [
+ 'keeps different names apart, by latest upload',
+ [
+ { id: 'chart-1', runId: 'run-1', name: 'chart.svg', uploaded_at: '2026-09-30T18:30:00Z' },
+ { id: 'report-2', runId: 'run-2', name: 'report.md', uploaded_at: '2026-09-30T19:00:00Z' },
+ { id: 'report-1', runId: 'run-1', name: 'report.md', uploaded_at: '2026-09-30T17:00:00Z' },
+ ],
+ [
+ { name: 'report.md', versionIds: ['report-2', 'report-1'], latestId: 'report-2' },
+ { name: 'chart.svg', versionIds: ['chart-1'], latestId: 'chart-1' },
+ ],
+ ],
+ ])('groupArtifactVersions %s', (_, versions, expected) => {
+ const artifacts: RunArtifact[] = versions.map(({ runId, ...overrides }) => ({
+ ...artifact(overrides),
+ runId,
+ }))
+ expect(
+ groupArtifactVersions(artifacts).map((file) => ({
+ name: file.name,
+ versionIds: file.versions.map(({ id }) => id),
+ latestId: file.latest.id,
+ }))
+ ).toEqual(expected)
+ })
})
diff --git a/products/posthog_ai/frontend/scenes/TaskTracker/taskRunArtifacts.ts b/products/posthog_ai/frontend/scenes/TaskTracker/taskRunArtifacts.ts
index 4792822b0225..1c7bd5d4b2fd 100644
--- a/products/posthog_ai/frontend/scenes/TaskTracker/taskRunArtifacts.ts
+++ b/products/posthog_ai/frontend/scenes/TaskTracker/taskRunArtifacts.ts
@@ -132,3 +132,33 @@ export function collectRunArtifacts(runs: readonly (RunWithArtifacts | null | un
}
return [...byId.values()].sort((a, b) => b.uploaded_at.localeCompare(a.uploaded_at))
}
+
+/** One file name with every upload of it. */
+export interface ArtifactFile {
+ name: string
+ /** Newest first. */
+ versions: RunArtifact[]
+ latest: RunArtifact
+}
+
+/**
+ * The agent writes a new artifact each time it saves a file, so each upload of a name is a version of that file.
+ * Versions can sit on different runs of the resume chain.
+ */
+export function groupArtifactVersions(artifacts: readonly RunArtifact[]): ArtifactFile[] {
+ const byName = new Map<string, RunArtifact[]>()
+ for (const artifact of artifacts) {
+ const versions = byName.get(artifact.name)
+ if (versions) {
+ versions.push(artifact)
+ } else {
+ byName.set(artifact.name, [artifact])
+ }
+ }
+ return [...byName]
+ .map(([name, versions]) => {
+ const sorted = [...versions].sort((a, b) => b.uploaded_at.localeCompare(a.uploaded_at))
+ return { name, versions: sorted, latest: sorted[0] }
+ })
+ .sort((a, b) => b.latest.uploaded_at.localeCompare(a.latest.uploaded_at))
+}
diff --git a/products/posthog_ai/frontend/scenes/TaskTracker/taskRunArtifactsLogic.test.ts b/products/posthog_ai/frontend/scenes/TaskTracker/taskRunArtifactsLogic.test.ts
new file mode 100644
index 000000000000..4c4322f52e08
--- /dev/null
+++ b/products/posthog_ai/frontend/scenes/TaskTracker/taskRunArtifactsLogic.test.ts
@@ -0,0 +1,53 @@
+import { router } from 'kea-router'
+import { expectLogic } from 'kea-test-utils'
+
+import { initKeaTests } from '~/test/init'
+
+import { taskRunArtifactsLogic } from './taskRunArtifactsLogic'
+
+const TASK_ID = 'task-123'
+
+describe('taskRunArtifactsLogic', () => {
+ const originalFetch = global.fetch
+
+ beforeEach(() => {
+ initKeaTests()
+ global.fetch = jest.fn((input: RequestInfo | URL) => {
+ const url = String(input)
+ const payload = url.endsWith('/runs/') ? { results: [] } : { id: TASK_ID }
+ return Promise.resolve(
+ new Response(JSON.stringify(payload), { headers: { 'Content-Type': 'application/json' } })
+ )
+ }) as typeof fetch
+ })
+
+ afterEach(() => {
+ global.fetch = originalFetch
+ })
+
+ it('opens a shared artifact link and keeps the url on the open file', async () => {
+ router.actions.push(`/project/1/tasks/${TASK_ID}`, { artifact: 'report.md', artifact_version: 'v1' })
+ const logic = taskRunArtifactsLogic({ taskId: TASK_ID })
+ logic.mount()
+
+ await expectLogic(logic).toMatchValues({
+ activeTab: 'artifacts',
+ selectedFileName: 'report.md',
+ selectedVersionId: 'v1',
+ })
+
+ logic.actions.selectArtifact('chart.svg')
+ expect(router.values.searchParams).toEqual({ artifact: 'chart.svg' })
+
+ logic.actions.setActiveTab('conversation')
+ expect(router.values.searchParams).toEqual({})
+ })
+
+ it('ignores an artifact link for another task', async () => {
+ router.actions.push('/project/1/tasks/other-task', { artifact: 'report.md' })
+ const logic = taskRunArtifactsLogic({ taskId: TASK_ID })
+ logic.mount()
+
+ await expectLogic(logic).toMatchValues({ activeTab: 'conversation', selectedFileName: null })
+ })
+})
diff --git a/products/posthog_ai/frontend/scenes/TaskTracker/taskRunArtifactsLogic.ts b/products/posthog_ai/frontend/scenes/TaskTracker/taskRunArtifactsLogic.ts
index 94f12fa2d763..2704e714a02a 100644
--- a/products/posthog_ai/frontend/scenes/TaskTracker/taskRunArtifactsLogic.ts
+++ b/products/posthog_ai/frontend/scenes/TaskTracker/taskRunArtifactsLogic.ts
@@ -1,5 +1,6 @@
import { MakeLogicType, actions, afterMount, connect, kea, key, listeners, path, props, reducers, selectors } from 'kea'
import { loaders } from 'kea-loaders'
+import { actionToUrl, router, urlToAction } from 'kea-router'
import posthog from 'posthog-js'
import api from 'lib/api'
@@ -15,11 +16,13 @@ import type { TaskRunDetailDTOApi } from 'products/tasks/frontend/generated/api.
import type { TaskRun } from '../../types/taskTypes'
import { taskDetailSceneLogic } from './taskDetailSceneLogic'
import {
+ ArtifactFile,
ArtifactPreviewKind,
RunArtifact,
TaskRunTab,
artifactPreviewKind,
collectRunArtifacts,
+ groupArtifactVersions,
isTextPreview,
} from './taskRunArtifacts'
@@ -44,11 +47,16 @@ export interface taskRunArtifactsLogicValues {
artifacts: RunArtifact[]
chainRuns: TaskRunDetailDTOApi[]
chainRunsLoading: boolean
+ files: ArtifactFile[]
selectedArtifact: RunArtifact | null
- selectedArtifactId: string | null
+ selectedFile: ArtifactFile | null
+ selectedFileName: string | null
selectedIndex: number
selectedKind: ArtifactPreviewKind | null
selectedText: ArtifactText | null
+ selectedVersion: RunArtifact | null
+ selectedVersionId: string | null
+ selectedVersionIndex: number
textsById: Record<string, ArtifactText>
}
@@ -97,8 +105,18 @@ export interface taskRunArtifactsLogicActions {
chainRuns: TaskRunDetailDTOApi[]
payload?: string[]
}
- selectArtifact: (artifactId: string) => {
- artifactId: string
+ openFromUrl: (
+ fileName: string,
+ versionId: string | null
+ ) => {
+ fileName: string
+ versionId: string | null
+ }
+ selectArtifact: (fileName: string) => {
+ fileName: string
+ }
+ selectVersion: (artifactId: string | null) => {
+ artifactId: string | null
}
setActiveTab: (tab: TaskRunTab) => {
tab: TaskRunTab
@@ -113,8 +131,12 @@ export interface taskRunArtifactsLogicMeta {
key: string
__keaTypeGenInternalSelectorTypes: {
artifacts: (selectedRun: TaskRunDetailDTOApi | null, chainRuns: TaskRunDetailDTOApi[]) => RunArtifact[]
- selectedIndex: (artifacts: RunArtifact[], selectedArtifactId: string | null) => number
- selectedArtifact: (artifacts: RunArtifact[], selectedIndex: number) => RunArtifact | null
+ files: (artifacts: RunArtifact[]) => ArtifactFile[]
+ selectedIndex: (files: ArtifactFile[], selectedFileName: string | null) => number
+ selectedFile: (files: ArtifactFile[], selectedIndex: number) => ArtifactFile | null
+ selectedVersionIndex: (selectedFile: ArtifactFile | null, selectedVersionId: string | null) => number
+ selectedVersion: (selectedFile: ArtifactFile | null, selectedVersionIndex: number) => RunArtifact | null
+ selectedArtifact: (selectedVersion: RunArtifact | null) => RunArtifact | null
selectedKind: (selectedArtifact: RunArtifact | null) => ArtifactPreviewKind | null
selectedText: (
selectedArtifact: RunArtifact | null,
@@ -141,6 +163,15 @@ export function artifactDownloadUrl(projectId: number | null, taskId: string, ar
return getTasksRunsArtifactsDownloadRetrieveUrl(String(projectId), taskId, artifact.runId, artifact.id)
}
+// A shared link opens the tab on one file, and on one version when it is not the latest.
+const ARTIFACT_PARAM = 'artifact'
+const VERSION_PARAM = 'artifact_version'
+
+/** The standalone page puts the task in the path, an embedded runner in `?task=`. */
+function urlIsForTask(pathname: string, searchParams: Record<string, any>, taskId: string): boolean {
+ return searchParams.task === taskId || pathname.split('/').includes(taskId)
+}
+
export const taskRunArtifactsLogic = kea<taskRunArtifactsLogicType>([
props({} as TaskRunArtifactsLogicProps),
key((props) => props.taskId),
@@ -156,10 +187,13 @@ export const taskRunArtifactsLogic = kea<taskRunArtifactsLogicType>([
})),
actions({
setActiveTab: (tab: TaskRunTab) => ({ tab }),
- selectArtifact: (artifactId: string) => ({ artifactId }),
+ selectArtifact: (fileName: string) => ({ fileName }),
+ // `null` follows the latest version, so a new upload of the open file shows at once.
+ selectVersion: (artifactId: string | null) => ({ artifactId }),
stepArtifact: (delta: number) => ({ delta }),
downloadArtifact: (artifact: RunArtifact) => ({ artifact }),
ensureSelectedText: true,
+ openFromUrl: (fileName: string, versionId: string | null) => ({ fileName, versionId }),
}),
loaders(({ props, values }) => ({
chainRuns: [
@@ -212,8 +246,22 @@ export const taskRunArtifactsLogic = kea<taskRunArtifactsLogicType>([
],
})),
reducers({
- activeTab: ['conversation' as TaskRunTab, { setActiveTab: (_, { tab }) => tab }],
- selectedArtifactId: [null as string | null, { selectArtifact: (_, { artifactId }) => artifactId }],
+ activeTab: [
+ 'conversation' as TaskRunTab,
+ { setActiveTab: (_, { tab }) => tab, openFromUrl: () => 'artifacts' },
+ ],
+ selectedFileName: [
+ null as string | null,
+ { selectArtifact: (_, { fileName }) => fileName, openFromUrl: (_, { fileName }) => fileName },
+ ],
+ selectedVersionId: [
+ null as string | null,
+ {
+ selectArtifact: () => null,
+ selectVersion: (_, { artifactId }) => artifactId,
+ openFromUrl: (_, { versionId }) => versionId,
+ },
+ ],
textsById: [
{} as Record<string, ArtifactText>,
{
@@ -228,17 +276,34 @@ export const taskRunArtifactsLogic = kea<taskRunArtifactsLogicType>([
(selectedRun: TaskRunDetailDTOApi | null, chainRuns: TaskRunDetailDTOApi[]): RunArtifact[] =>
collectRunArtifacts([selectedRun, ...chainRuns]),
],
+ files: [(s) => [s.artifacts], (artifacts: RunArtifact[]): ArtifactFile[] => groupArtifactVersions(artifacts)],
selectedIndex: [
- (s) => [s.artifacts, s.selectedArtifactId],
- (artifacts: RunArtifact[], selectedArtifactId: string | null): number =>
+ (s) => [s.files, s.selectedFileName],
+ (files: ArtifactFile[], selectedFileName: string | null): number =>
Math.max(
0,
- artifacts.findIndex((artifact) => artifact.id === selectedArtifactId)
+ files.findIndex((file) => file.name === selectedFileName)
),
],
+ selectedFile: [
+ (s) => [s.files, s.selectedIndex],
+ (files: ArtifactFile[], selectedIndex: number): ArtifactFile | null => files[selectedIndex] ?? null,
+ ],
+ /** 0 is the latest version. */
+ selectedVersionIndex: [
+ (s) => [s.selectedFile, s.selectedVersionId],
+ (selectedFile: ArtifactFile | null, selectedVersionId: string | null): number =>
+ Math.max(0, selectedFile?.versions.findIndex((version) => version.id === selectedVersionId) ?? 0),
+ ],
+ selectedVersion: [
+ (s) => [s.selectedFile, s.selectedVersionIndex],
+ (selectedFile: ArtifactFile | null, selectedVersionIndex: number): RunArtifact | null =>
+ selectedFile?.versions[selectedVersionIndex] ?? null,
+ ],
+ // The same value as `selectedVersion`, under the name the preview and download code use.
selectedArtifact: [
- (s) => [s.artifacts, s.selectedIndex],
- (artifacts: RunArtifact[], selectedIndex: number): RunArtifact | null => artifacts[selectedIndex] ?? null,
+ (s) => [s.selectedVersion],
+ (selectedVersion: RunArtifact | null): RunArtifact | null => selectedVersion,
],
selectedKind: [
(s) => [s.selectedArtifact],
@@ -268,6 +333,7 @@ export const taskRunArtifactsLogic = kea<taskRunArtifactsLogicType>([
posthog.capture('task artifact previewed', {
kind: values.selectedKind,
content_type: artifact.content_type ?? null,
+ version_count: values.selectedFile?.versions.length ?? 1,
})
}
return {
@@ -280,22 +346,70 @@ export const taskRunArtifactsLogic = kea<taskRunArtifactsLogicType>([
previewSelected()
},
selectArtifact: previewSelected,
+ selectVersion: () => {
+ // pinned: analytics event name and properties. Renaming them breaks insights.
+ posthog.capture('task artifact version selected', {
+ version_index: values.selectedVersionIndex,
+ version_count: values.selectedFile?.versions.length ?? 1,
+ })
+ },
ensureSelectedText: loadSelectedText,
loadTaskRunsSuccess: ({ runs }) => {
actions.loadChainRuns(runs.map((run) => run.id))
},
stepArtifact: ({ delta }) => {
- const { artifacts, selectedIndex } = values
- const next = artifacts[(selectedIndex + delta + artifacts.length) % artifacts.length]
- if (next?.id) {
- actions.selectArtifact(next.id)
+ const { files, selectedIndex } = values
+ const next = files[(selectedIndex + delta + files.length) % files.length]
+ if (next) {
+ actions.selectArtifact(next.name)
}
},
downloadArtifact: ({ artifact }) => {
posthog.capture('task artifact downloaded', { kind: artifactPreviewKind(artifact) })
},
+ openFromUrl: ({ versionId }) => {
+ // pinned: analytics event name and properties. Renaming them breaks insights.
+ posthog.capture('task artifact link opened', { has_version: !!versionId })
+ },
+ }
+ }),
+ actionToUrl(({ values, props }) => {
+ const syncUrl = (): [string, Record<string, any>, Record<string, any>, { replace: true }] | undefined => {
+ const { pathname, searchParams, hashParams } = router.values.currentLocation
+ if (!urlIsForTask(pathname, searchParams, props.taskId)) {
+ return undefined
+ }
+ const next = { ...searchParams }
+ delete next[ARTIFACT_PARAM]
+ delete next[VERSION_PARAM]
+ const fileName = values.selectedFileName ?? values.selectedFile?.name
+ if (values.activeTab === 'artifacts' && fileName) {
+ next[ARTIFACT_PARAM] = fileName
+ if (values.selectedVersionId) {
+ next[VERSION_PARAM] = values.selectedVersionId
+ }
+ }
+ return [pathname, next, hashParams, { replace: true }]
}
+ return { setActiveTab: syncUrl, selectArtifact: syncUrl, selectVersion: syncUrl }
}),
+ urlToAction(({ actions, values, props }) => ({
+ '*': (_, searchParams, __, { pathname }) => {
+ const fileName = searchParams[ARTIFACT_PARAM]
+ if (typeof fileName !== 'string' || !fileName || !urlIsForTask(pathname, searchParams, props.taskId)) {
+ return
+ }
+ const versionId = typeof searchParams[VERSION_PARAM] === 'string' ? searchParams[VERSION_PARAM] : null
+ // Our own `actionToUrl` writes land here too. Those match the state already.
+ if (
+ values.activeTab !== 'artifacts' ||
+ values.selectedFileName !== fileName ||
+ values.selectedVersionId !== versionId
+ ) {
+ actions.openFromUrl(fileName, versionId)
+ }
+ },
+ })),
afterMount(({ actions, values }) => {
if (values.runs.length > 0) {
actions.loadChainRuns(values.runs.map((run) => run.id))