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): serve living artifact versions and preview slack files (#110456)

Shy Alter73c65586b816
diff --git a/products/posthog_ai/frontend/scenes/TaskTracker/TaskRunArtifacts.stories.tsx b/products/posthog_ai/frontend/scenes/TaskTracker/TaskRunArtifacts.stories.tsx
index ab383799e9e8..83c5d788e2b7 100644
--- a/products/posthog_ai/frontend/scenes/TaskTracker/TaskRunArtifacts.stories.tsx
+++ b/products/posthog_ai/frontend/scenes/TaskTracker/TaskRunArtifacts.stories.tsx
@@ -568,9 +568,26 @@ const LIVING_DOCUMENTS = [
version: 1,
size: 9216,
content_type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
+ location: { kind: 'slack_file', storage_path: 'tasks/living/doc-trial-sheet/trial-starts-by-week.v1.xlsx' },
created_at: '2026-09-28T18:17:00Z',
},
]),
+ livingDocument('doc-trial-chart', 'trial-funnel-chart.svg', 'slack_file', [
+ {
+ version: 1,
+ size: 3584,
+ content_type: 'image/svg+xml',
+ location: { kind: 'slack_file', storage_path: 'tasks/living/doc-trial-chart/trial-funnel-chart.v1.svg' },
+ created_at: '2026-09-28T18:12:00Z',
+ },
+ {
+ version: 2,
+ size: 3712,
+ content_type: 'image/svg+xml',
+ location: { kind: 'slack_file', storage_path: 'tasks/living/doc-trial-chart/trial-funnel-chart.v2.svg' },
+ created_at: '2026-09-28T18:19:00Z',
+ },
+ ]),
]
function livingMocks(): ReturnType<typeof taskMocks> {
@@ -582,6 +599,8 @@ function livingMocks(): ReturnType<typeof taskMocks> {
[`/api/projects/:team_id/tasks/${TASK_ID}/runs/:run_id/living_artifacts/`]: {
artifacts: LIVING_DOCUMENTS,
},
+ [`/api/projects/:team_id/tasks/${TASK_ID}/runs/:run_id/living_artifacts/doc-trial-chart/versions/:version/`]:
+ () => new HttpResponse(CHART_SVG, { headers: { 'Content-Type': 'image/svg+xml' } }),
},
post: { ...mocks.post, ...OBJECT_MOCKS.post },
}
@@ -592,6 +611,11 @@ export const LivingArtifact: Story = {
render: () => <StoryPage fileName="living-doc-weekly-trials" />,
}
+export const LivingSlackFile: Story = {
+ parameters: { msw: { mocks: livingMocks() } },
+ render: () => <StoryPage fileName="living-doc-trial-chart" />,
+}
+
export const ResumedTask: Story = {
parameters: { msw: { mocks: taskMocks(ARTIFACTS, { resumed: true }) } },
render: () => <StoryPage fileName={REPORT_FILE_NAME} />,
diff --git a/products/posthog_ai/frontend/scenes/TaskTracker/components/TaskRunArtifacts.tsx b/products/posthog_ai/frontend/scenes/TaskTracker/components/TaskRunArtifacts.tsx
index e1519fa6aa08..e6af88eb3227 100644
--- a/products/posthog_ai/frontend/scenes/TaskTracker/components/TaskRunArtifacts.tsx
+++ b/products/posthog_ai/frontend/scenes/TaskTracker/components/TaskRunArtifacts.tsx
@@ -79,6 +79,7 @@ import {
artifactPreviewKind,
formatArtifactSize,
hasFullPageView,
+ hasLivingContent,
isTextPreview,
listboxKeyTarget,
parseCsv,
@@ -247,8 +248,15 @@ function TextLoading(): JSX.Element {
}
function VideoPreview({ taskId, name }: { taskId: string; name: string }): JSX.Element {
- const { selectedArtifact, selectedMedia, artifactMediaLoading } = useValues(taskRunArtifactsLogic({ taskId }))
+ const { selectedArtifact, selectedMedia, artifactMediaLoading, currentProjectId } = useValues(
+ taskRunArtifactsLogic({ taskId })
+ )
const { loadArtifactMedia } = useActions(taskRunArtifactsLogic({ taskId }))
+ // A stored living version streams from the app origin, which the media-src policy allows.
+ const livingSrc = selectedArtifact?.living ? artifactDownloadUrl(currentProjectId, taskId, selectedArtifact) : null
+ if (livingSrc) {
+ return <VideoPlayer key={livingSrc} src={livingSrc} name={name} />
+ }
if (!selectedMedia) {
return (
<div className="flex h-full items-center justify-center">
@@ -276,11 +284,14 @@ function VideoPreview({ taskId, name }: { taskId: string; name: string }): JSX.E
</Empty>
)
}
+ return <VideoPlayer key={selectedMedia.artifactId} src={selectedMedia.url} name={name} />
+}
+
+function VideoPlayer({ src, name }: { src: string; name: string }): JSX.Element {
return (
<div className="flex h-full items-center justify-center p-6">
<video
- key={selectedMedia.artifactId}
- src={selectedMedia.url}
+ src={src}
controls
preload="metadata"
aria-label={name}
@@ -380,7 +391,7 @@ function ArtifactPreview({ taskId, mode }: { taskId: string; mode: PreviewMode }
if (selectedKind === 'video') {
return <VideoPreview taskId={taskId} name={selectedArtifact.name} />
}
- if (selectedArtifact.living && selectedArtifact.living.text === null) {
+ if (selectedArtifact.living && !hasLivingContent(selectedArtifact.living)) {
return (
<Empty className="h-full">
<EmptyHeader>
@@ -778,8 +789,8 @@ function ArtifactToolbar({
</IconAction>
</div>
<CopyLinkAction taskId={taskId} />
- {/* No endpoint serves a living document's bytes, so it has no download. */}
- {kind !== 'reference' && !artifact.living && (
+ {/* PostHog stores only the files of a living document. Canvas and message text has no file to download. */}
+ {kind !== 'reference' && (!artifact.living || artifact.living.stored) && (
<IconAction
label={versioned ? 'Download this version' : 'Download'}
href={downloadUrl ?? undefined}
diff --git a/products/posthog_ai/frontend/scenes/TaskTracker/taskRunArtifacts.test.ts b/products/posthog_ai/frontend/scenes/TaskTracker/taskRunArtifacts.test.ts
index 6e88897373e5..3523b3160d5d 100644
--- a/products/posthog_ai/frontend/scenes/TaskTracker/taskRunArtifacts.test.ts
+++ b/products/posthog_ai/frontend/scenes/TaskTracker/taskRunArtifacts.test.ts
@@ -9,7 +9,6 @@ import {
collectRunArtifacts,
groupArtifactVersions,
livingArtifactFiles,
- livingArtifactsFromResponse,
listboxKeyTarget,
parseCsv,
visibleRunArtifacts,
@@ -220,37 +219,82 @@ describe('taskRunArtifacts', () => {
).toEqual(expected)
})
- const slackFile = livingArtifact({
- id: 'doc-2',
- name: 'weeks.xlsx',
- adapter: 'slack_file',
- current_version: 1,
- versions: [{ version: 1, run_id: 'run-1', size: 2048, created_at: '2026-09-30T16:00:00Z' }],
- })
- test.each([
- ['the envelope the endpoint returns', { artifacts: [livingArtifact({}), slackFile] }],
- [
- 'the array of envelopes the generated client types, with a repeated id',
- [{ artifacts: [livingArtifact({})] }, { artifacts: [livingArtifact({}), slackFile] }],
- ],
- ])('living documents read from %s', (_, response) => {
- const files = livingArtifactFiles(livingArtifactsFromResponse(response))
+ function slackFile(
+ location: Record<string, unknown>,
+ name = 'signups.png',
+ contentType = 'image/png'
+ ): TaskRunLivingArtifactResponseApi {
+ return livingArtifact({
+ id: 'doc-2',
+ name,
+ adapter: 'slack_file',
+ current_version: 1,
+ versions: [
+ {
+ version: 1,
+ run_id: 'run-1',
+ size: 2048,
+ content_type: contentType,
+ location,
+ created_at: '2026-09-30T16:00:00Z',
+ },
+ ],
+ })
+ }
+
+ test('livingArtifactFiles keeps each document apart and lists its versions newest first', () => {
+ const files = livingArtifactFiles([livingArtifact({}), slackFile({ storage_path: 'tasks/doc.v1.png' })])
// An uploaded `report.md` keys by its name, so a living document with that name must not take the same key.
expect(
files.map((file) => ({
key: file.key,
- versions: file.versions.map(({ id, living }) => ({ id, text: living?.text })),
+ versions: file.versions.map(({ id, living }) => ({
+ id,
+ version: living?.version,
+ text: living?.text,
+ stored: living?.stored,
+ })),
}))
).toEqual([
{
key: 'living-doc-1',
versions: [
- { id: 'living-doc-1-v2', text: '# Final' },
- { id: 'living-doc-1-v1', text: '# Draft' },
+ { id: 'living-doc-1-v2', version: 2, text: '# Final', stored: false },
+ { id: 'living-doc-1-v1', version: 1, text: '# Draft', stored: false },
],
},
- { key: 'living-doc-2', versions: [{ id: 'living-doc-2-v1', text: null }] },
+ {
+ key: 'living-doc-2',
+ versions: [{ id: 'living-doc-2-v1', version: 1, text: null, stored: true }],
+ },
])
- expect(artifactPreviewKind(files[1].latest)).toBe('none')
+ })
+
+ test.each([
+ [
+ 'a stored Slack file image previews as an image',
+ { storage_path: 'tasks/doc.v1.png' },
+ 'image.png',
+ 'image/png',
+ 'image',
+ ],
+ [
+ 'a stored Slack file video previews as a video',
+ { storage_path: 'tasks/doc.v1.mp4' },
+ 'demo.mp4',
+ 'video/mp4',
+ 'video',
+ ],
+ [
+ 'a stored Slack file CSV has no inline preview',
+ { storage_path: 'tasks/doc.v1.csv' },
+ 'weeks.csv',
+ 'text/csv',
+ 'none',
+ ],
+ ['a Slack file with no stored copy has no preview', {}, 'image.png', 'image/png', 'none'],
+ ])('%s', (_, location, name, contentType, expected) => {
+ const [file] = livingArtifactFiles([slackFile(location, name, contentType)])
+ expect(artifactPreviewKind(file.latest)).toBe(expected)
})
})
diff --git a/products/posthog_ai/frontend/scenes/TaskTracker/taskRunArtifacts.ts b/products/posthog_ai/frontend/scenes/TaskTracker/taskRunArtifacts.ts
index cfb9087097e3..3ba046979800 100644
--- a/products/posthog_ai/frontend/scenes/TaskTracker/taskRunArtifacts.ts
+++ b/products/posthog_ai/frontend/scenes/TaskTracker/taskRunArtifacts.ts
@@ -3,7 +3,6 @@ import { combineUrl } from 'kea-router'
import type {
TaskRunArtifactResponseApi,
TaskRunLivingArtifactResponseApi,
- TaskRunLivingArtifactsResponseApi,
} from 'products/tasks/frontend/generated/api.schemas'
export type TaskRunTab = 'conversation' | 'artifacts'
@@ -66,11 +65,17 @@ export function artifactPreviewKind(
artifact: TaskRunArtifactResponseApi & { living?: LivingVersion }
): ArtifactPreviewKind {
if (artifact.living && artifact.living.text === null) {
- return 'none'
+ // A stored file plays in an `img` or a `video` from its URL. Text needs a read of the body, so it downloads.
+ const kind = artifact.living.stored ? fileKind(artifact) : 'none'
+ return kind === 'image' || kind === 'video' ? kind : 'none'
}
if (artifact.type === 'reference') {
return 'reference'
}
+ return fileKind(artifact)
+}
+
+function fileKind(artifact: TaskRunArtifactResponseApi): ArtifactPreviewKind {
const contentType = (artifact.content_type ?? '').split(';')[0].trim().toLowerCase()
const ext = extension(artifact.name)
if (contentType === 'text/html' || ext === 'html' || ext === 'htm') {
@@ -279,9 +284,18 @@ export function groupArtifactVersions(artifacts: readonly RunArtifact[]): Artifa
export interface LivingVersion {
/** The living artifact id. All versions of one document share it. */
artifactId: string
+ /** The version number in the version content URL. */
+ version: number
adapter: string
/** `null` when PostHog keeps no text for the version, for example a file sent to Slack. */
text: string | null
+ /** True when PostHog stores the version as a file, for example a file sent to Slack. */
+ stored: boolean
+}
+
+/** PostHog keeps the content of a version as text in the registry or as a stored file. */
+export function hasLivingContent(living: LivingVersion): boolean {
+ return living.text !== null || living.stored
}
export const LIVING_ADAPTER_LABEL: Record<string, string> = {
@@ -292,25 +306,8 @@ export const LIVING_ADAPTER_LABEL: Record<string, string> = {
github_pr: 'Pull request',
}
-/**
- * The generated client types the list response as an array of envelopes, but the endpoint returns one
- * envelope. Both shapes are read so the list keeps working after the schema is fixed.
- */
-export function livingArtifactsFromResponse(
- response: TaskRunLivingArtifactsResponseApi | readonly TaskRunLivingArtifactsResponseApi[] | null | undefined
-): TaskRunLivingArtifactResponseApi[] {
- const envelopes: readonly TaskRunLivingArtifactsResponseApi[] = Array.isArray(response)
- ? response
- : response
- ? [response as TaskRunLivingArtifactsResponseApi]
- : []
- const byId = new Map<string, TaskRunLivingArtifactResponseApi>()
- for (const artifact of envelopes.flatMap((envelope) => envelope.artifacts ?? [])) {
- if (artifact.id && !byId.has(artifact.id)) {
- byId.set(artifact.id, artifact)
- }
- }
- return [...byId.values()]
+function isRecord(value: unknown): value is Record<string, unknown> {
+ return typeof value === 'object' && value !== null && !Array.isArray(value)
}
function stringField(record: Record<string, unknown>, field: string): string | undefined {
@@ -335,8 +332,10 @@ function livingVersionArtifact(
runId: stringField(record, 'run_id') ?? artifact.run_id,
living: {
artifactId: artifact.id,
+ version: versionNumber,
adapter: artifact.adapter,
text: typeof record.content === 'string' ? record.content : null,
+ stored: isRecord(record.location) && !!stringField(record.location, 'storage_path'),
},
}
}
diff --git a/products/posthog_ai/frontend/scenes/TaskTracker/taskRunArtifactsLogic.test.ts b/products/posthog_ai/frontend/scenes/TaskTracker/taskRunArtifactsLogic.test.ts
index 9fb0651a6fe3..b64803d66a4d 100644
--- a/products/posthog_ai/frontend/scenes/TaskTracker/taskRunArtifactsLogic.test.ts
+++ b/products/posthog_ai/frontend/scenes/TaskTracker/taskRunArtifactsLogic.test.ts
@@ -3,7 +3,8 @@ import { expectLogic } from 'kea-test-utils'
import { initKeaTests } from '~/test/init'
-import { taskRunArtifactsLogic } from './taskRunArtifactsLogic'
+import type { RunArtifact } from './taskRunArtifacts'
+import { artifactDownloadUrl, taskRunArtifactsLogic } from './taskRunArtifactsLogic'
const TASK_ID = 'task-123'
@@ -55,4 +56,24 @@ describe('taskRunArtifactsLogic', () => {
await expectLogic(logic).toMatchValues({ activeTab: 'conversation', selectedFileKey: null })
})
+
+ it.each([
+ [
+ 'a stored Slack file version streams from its version URL',
+ true,
+ `/api/projects/1/tasks/${TASK_ID}/runs/run-1/living_artifacts/doc-1/versions/3/`,
+ ],
+ ['a living version with no stored file has no URL', false, null],
+ ])('artifactDownloadUrl: %s', (_, stored, expected) => {
+ const version: RunArtifact = {
+ id: 'living-doc-1-v3',
+ name: 'signups.png',
+ type: 'living',
+ content_type: 'image/png',
+ uploaded_at: '2026-09-30T16:00:00Z',
+ runId: 'run-1',
+ living: { artifactId: 'doc-1', version: 3, adapter: 'slack_file', text: null, stored },
+ }
+ expect(artifactDownloadUrl(1, TASK_ID, version)).toBe(expected)
+ })
})
diff --git a/products/posthog_ai/frontend/scenes/TaskTracker/taskRunArtifactsLogic.ts b/products/posthog_ai/frontend/scenes/TaskTracker/taskRunArtifactsLogic.ts
index 219d68c65844..624838ae30fc 100644
--- a/products/posthog_ai/frontend/scenes/TaskTracker/taskRunArtifactsLogic.ts
+++ b/products/posthog_ai/frontend/scenes/TaskTracker/taskRunArtifactsLogic.ts
@@ -26,6 +26,7 @@ import {
getTasksRunsArtifactsDownloadCreateUrl,
getTasksRunsArtifactsDownloadRetrieveUrl,
tasksRunsArtifactsDismissCreate,
+ getTasksRunsLivingArtifactsVersionContentUrl,
tasksRunsLivingArtifactsList,
tasksRunsRetrieve,
} from 'products/tasks/frontend/generated/api'
@@ -47,7 +48,6 @@ import {
groupArtifactVersions,
isTextPreview,
livingArtifactFiles,
- livingArtifactsFromResponse,
postHogObjectRef,
taskArtifactPath,
VERSION_PARAM,
@@ -286,11 +286,25 @@ const MAX_CHAIN_RUNS = 20
// A video plays from a blob in memory, so a very large file goes to a download instead.
const MAX_MEDIA_PREVIEW_BYTES = 200 * 1024 * 1024
-/** The download-by-id URL redirects to a fresh presigned link, so an `img` or an `a` can use it directly. */
+/**
+ * A URL that an `img`, a `video` or an `a` can use directly. The download-by-id URL redirects to a fresh
+ * presigned link. A stored living version streams from the app origin. Other living versions have no URL.
+ */
export function artifactDownloadUrl(projectId: number | null, taskId: string, artifact: RunArtifact): string | null {
if (projectId === null || !artifact.id) {
return null
}
+ if (artifact.living) {
+ return artifact.living.stored
+ ? getTasksRunsLivingArtifactsVersionContentUrl(
+ String(projectId),
+ taskId,
+ artifact.runId,
+ artifact.living.artifactId,
+ artifact.living.version
+ )
+ : null
+ }
return getTasksRunsArtifactsDownloadRetrieveUrl(String(projectId), taskId, artifact.runId, artifact.id)
}
@@ -364,9 +378,12 @@ export const taskRunArtifactsLogic = kea<taskRunArtifactsLogicType>([
return values.livingArtifacts
}
try {
- return livingArtifactsFromResponse(
- await tasksRunsLivingArtifactsList(String(values.currentProjectId), props.taskId, runId)
+ const response = await tasksRunsLivingArtifactsList(
+ String(values.currentProjectId),
+ props.taskId,
+ runId
)
+ return response.artifacts
} catch {
return values.livingArtifacts
}
@@ -604,7 +621,8 @@ export const taskRunArtifactsLogic = kea<taskRunArtifactsLogicType>([
}
if (isTextPreview(kind) && !values.selectedText) {
actions.loadArtifactText(artifact)
- } else if (kind === 'video' && !values.selectedMedia) {
+ } else if (kind === 'video' && !artifact.living && !values.selectedMedia) {
+ // A living version plays from its same-origin URL, so only an uploaded video loads into a blob.
actions.loadArtifactMedia(artifact)
}
}
@@ -681,7 +699,10 @@ export const taskRunArtifactsLogic = kea<taskRunArtifactsLogicType>([
}
},
downloadArtifact: ({ artifact }) => {
- posthog.capture('task artifact downloaded', { kind: artifactPreviewKind(artifact) })
+ posthog.capture('task artifact downloaded', {
+ kind: artifactPreviewKind(artifact),
+ living_adapter: artifact.living?.adapter ?? null,
+ })
},
reportObjectOpened: ({ objectKind }) => {
// pinned: analytics event name and properties. Renaming them breaks insights.
diff --git a/products/tasks/backend/facade/api.py b/products/tasks/backend/facade/api.py
index 9b34cb8f08a7..3618501ae14a 100644
--- a/products/tasks/backend/facade/api.py
+++ b/products/tasks/backend/facade/api.py
@@ -324,6 +324,7 @@ __all__ = [
"presign_task_run_artifact",
"presign_task_run_artifact_download",
"read_task_run_artifact",
+ "read_task_run_living_artifact_version",
"get_task_run_log_urls",
"get_task_run_log_size",
"read_task_run_log_content",
@@ -4353,6 +4354,40 @@ def get_task_run_living_artifact(
return serialized
+def read_task_run_living_artifact_version(
+ run_id: str | UUID, task_id: str | UUID, team_id: int, *, artifact_id: str | UUID, version: int
+) -> tuple[contracts.LivingArtifactVersionContent | None, str | None]:
+ """Read the content of one living artifact version.
+
+ Returns ``(content, error)``: ``(None, None)`` if the run isn't found, ``(None, "not_found")`` if the
+ artifact or version isn't found or keeps no content, ``(None, "read_failed")`` if the storage read
+ raised, else ``(content, None)``.
+ """
+ from products.tasks.backend.logic.services.living_artifacts import ( # noqa: PLC0415 — keep storage deps off the api import path
+ get_task_artifact_for_run,
+ read_living_artifact_version,
+ )
+
+ run = _get_visible_run(run_id, task_id, team_id)
+ if run is None:
+ return None, None
+ try:
+ UUID(str(artifact_id))
+ except ValueError:
+ return None, "not_found"
+ artifact = get_task_artifact_for_run(run, artifact_id)
+ if artifact is None:
+ return None, "not_found"
+ try:
+ content = read_living_artifact_version(artifact, version)
+ except Exception:
+ logger.exception("Failed to read living artifact %s version %s for team %s", artifact_id, version, team_id)
+ return None, "read_failed"
+ if content is None:
+ return None, "not_found"
+ return content, None
+
+
def create_task_run_living_artifact(
run_id: str | UUID,
task_id: str | UUID,
diff --git a/products/tasks/backend/facade/contracts.py b/products/tasks/backend/facade/contracts.py
index 3ff2dc0df3c4..d2eb97f9c108 100644
--- a/products/tasks/backend/facade/contracts.py
+++ b/products/tasks/backend/facade/contracts.py
@@ -1021,3 +1021,10 @@ class ComputeQuotaDenialReason(StrEnum):
class TaskPullRequest:
url: str
state: str
+
+
+@dataclass(frozen=True, kw_only=True)
+class LivingArtifactVersionContent:
+ name: str
+ content_type: str
+ content: bytes
diff --git a/products/tasks/backend/logic/services/living_artifacts.py b/products/tasks/backend/logic/services/living_artifacts.py
index bb20ec992526..4e98221fbfc7 100644
--- a/products/tasks/backend/logic/services/living_artifacts.py
+++ b/products/tasks/backend/logic/services/living_artifacts.py
@@ -15,6 +15,7 @@ from typing import Any
from urllib.parse import urlparse
from uuid import UUID
+from django.conf import settings
from django.db import transaction
from django.db.models import QuerySet
from django.utils import timezone
@@ -33,6 +34,7 @@ from posthog.utils import absolute_uri
from products.exports.backend.facade.api import get_delivery_image_url
from products.slack_app.backend.services.slack_messages import post_slack_thread_reply, slack_message_exists
+from products.tasks.backend.facade.contracts import LivingArtifactVersionContent
from products.tasks.backend.models import TaskArtifact, TaskRun
logger = structlog.get_logger(__name__)
@@ -375,6 +377,49 @@ def open_task_artifact(artifact: TaskArtifact) -> str | None:
return _adapter_for_existing_artifact(artifact).open(artifact)
+def read_living_artifact_version(artifact: TaskArtifact, version: int) -> LivingArtifactVersionContent | None:
+ """Return the content of one version, or None when the version is unknown or keeps no content.
+
+ A Slack file version keeps its bytes in object storage. A canvas or message version keeps its
+ text in the version record. Storage read errors propagate to the caller.
+ """
+ record = next(
+ (
+ candidate
+ for candidate in artifact.versions or []
+ if isinstance(candidate, dict) and candidate.get("version") == version
+ ),
+ None,
+ )
+ if record is None:
+ return None
+ raw_location = record.get("location")
+ location = raw_location if isinstance(raw_location, dict) else {}
+ content_type = str(record.get("content_type") or location.get("content_type") or "") or _guess_content_type(
+ artifact.name
+ )
+
+ storage_path = str(location.get("storage_path") or "")
+ if storage_path:
+ # Every living artifact object sits under its task's prefix. A path outside it is not this artifact's object.
+ if not storage_path.startswith(_task_artifact_s3_prefix(artifact)):
+ return None
+ payload = object_storage.read_bytes(storage_path, missing_ok=True)
+ if payload is None:
+ return None
+ return LivingArtifactVersionContent(name=artifact.name, content_type=content_type, content=payload)
+
+ text = record.get("content")
+ if isinstance(text, str):
+ return LivingArtifactVersionContent(name=artifact.name, content_type=content_type, content=text.encode("utf-8"))
+ return None
+
+
+# The task part of TaskRun.get_artifact_s3_prefix. Keep the two formats the same.
+def _task_artifact_s3_prefix(artifact: TaskArtifact) -> str:
+ return f"{settings.OBJECT_STORAGE_TASKS_FOLDER}/artifacts/team_{artifact.team_id}/task_{artifact.task_id}/"
+
+
def _find_source_artifact(
run: TaskRun,
*,
diff --git a/products/tasks/backend/presentation/serializers.py b/products/tasks/backend/presentation/serializers.py
index 02c24c25b384..7c544beca72c 100644
--- a/products/tasks/backend/presentation/serializers.py
+++ b/products/tasks/backend/presentation/serializers.py
@@ -1507,6 +1507,8 @@ class TaskRunLivingArtifactResponseSerializer(serializers.Serializer):
updated_at = serializers.CharField(allow_null=True, required=False, help_text="ISO timestamp when last updated.")
+# drf-spectacular wraps a `list` action response in an array. This endpoint returns one envelope.
+@extend_schema_serializer(many=False)
class TaskRunLivingArtifactsResponseSerializer(serializers.Serializer):
artifacts = TaskRunLivingArtifactResponseSerializer(many=True, help_text="Living artifacts for this task run.")
diff --git a/products/tasks/backend/presentation/views/api.py b/products/tasks/backend/presentation/views/api.py
index 360152bcd8b1..d2105e81e58f 100644
--- a/products/tasks/backend/presentation/views/api.py
+++ b/products/tasks/backend/presentation/views/api.py
@@ -12,6 +12,7 @@ from uuid import UUID
from django.conf import settings
from django.http import HttpResponse, HttpResponseRedirect, JsonResponse
from django.utils.html import escape
+from django.utils.http import content_disposition_header
import pydantic
import requests as http_requests
@@ -4187,7 +4188,7 @@ class TaskRunLivingArtifactViewSet(TeamAndOrgViewSetMixin, viewsets.GenericViewS
permission_classes = [IsAuthenticated, APIScopePermission]
scope_object = "task"
http_method_names = ["get", "post", "head", "options"]
- # The artifact registry is small and bounded per task; the response is a plain list.
+ # The artifact registry is small and bounded per task, so the list returns one unpaginated envelope.
pagination_class = None
# Fallback for drf-spectacular introspection only; every action declares its own
# request/response schema via @validated_request.
@@ -4216,7 +4217,7 @@ class TaskRunLivingArtifactViewSet(TeamAndOrgViewSetMixin, viewsets.GenericViewS
def _ensure_task_accessible(self) -> str:
"""Gate access to the parent task, mirroring ``TaskRunViewSet._ensure_task_accessible``."""
task_id = self._task_id()
- is_read = self.action in ("list", "retrieve")
+ is_read = self.action in ("list", "retrieve", "version_content")
bypass_visibility = is_read and _can_bypass_visibility(self.request, self.team_id)
if not tasks_facade.task_accessible_for_run_view(
task_id,
@@ -4511,6 +4512,57 @@ class TaskRunLivingArtifactViewSet(TeamAndOrgViewSetMixin, viewsets.GenericViewS
serializer = TaskRunLivingArtifactResponseSerializer(artifact)
return Response(serializer.data)
+ @extend_schema(
+ parameters=[
+ OpenApiParameter(
+ "version",
+ OpenApiTypes.INT,
+ OpenApiParameter.PATH,
+ description="Version number of the living artifact, as listed in its versions.",
+ )
+ ],
+ responses={
+ (200, "application/octet-stream"): OpenApiResponse(
+ response=OpenApiTypes.BINARY,
+ description="Version content, with the content type the version was saved with",
+ ),
+ 400: OpenApiResponse(response=TaskRunErrorResponseSerializer, description="Unable to read the version"),
+ 404: OpenApiResponse(description="Living artifact or version not found, or the version keeps no content"),
+ },
+ summary="Download one version of a living artifact",
+ description=(
+ "Streams the content of one living artifact version from the app origin. Slack file versions return "
+ "their stored file. Slack canvas and message versions return their text."
+ ),
+ operation_id="tasks_runs_living_artifacts_version_content",
+ )
+ @action(
+ detail=True,
+ methods=["get"],
+ url_path=r"versions/(?P<version>[0-9]+)",
+ required_scopes=["task:read"],
+ )
+ def version_content(self, request, pk=None, version=None, **kwargs):
+ task_id = self._ensure_task_accessible()
+ content, error = tasks_facade.read_task_run_living_artifact_version(
+ self._run_id(), task_id, self.team_id, artifact_id=str(pk), version=int(str(version))
+ )
+ if error == "read_failed":
+ return Response(
+ TaskRunErrorResponseSerializer({"error": "Unable to read this version"}).data,
+ status=status.HTTP_400_BAD_REQUEST,
+ )
+ if content is None:
+ raise NotFound()
+ response = HttpResponse(content.content, content_type=content.content_type)
+ response["Cache-Control"] = "no-cache"
+ # Agent-written HTML or SVG must not render as a page on the app origin, so the browser always saves it.
+ response["Content-Disposition"] = (
+ content_disposition_header(as_attachment=True, filename=os.path.basename(content.name) or "artifact")
+ or "attachment"
+ )
+ return response
+
@extend_schema(tags=["tasks"])
class LegacyDesktopAccessViewSet(viewsets.ViewSet):
diff --git a/products/tasks/backend/tests/test_api.py b/products/tasks/backend/tests/test_api.py
index b53151ad61bf..4be6816b4fd1 100644
--- a/products/tasks/backend/tests/test_api.py
+++ b/products/tasks/backend/tests/test_api.py
@@ -8580,6 +8580,104 @@ class TestTaskRunAPI(BaseTaskAPITest):
self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)
+ def _create_slack_file_living_artifact(self, task: Task, run: TaskRun, storage_path: str | None = None):
+ path = storage_path or f"{run.get_artifact_s3_prefix()}/living/doc/signups.v1.png"
+ return TaskArtifact.objects.for_team(task.team_id).create(
+ team_id=task.team_id,
+ task=task,
+ task_run=run,
+ name="signups.png",
+ artifact_type=TaskArtifact.ArtifactType.FILE,
+ adapter=TaskArtifact.Adapter.SLACK_FILE,
+ status=TaskArtifact.Status.ACTIVE,
+ location={"kind": "slack_file", "storage_path": path},
+ versions=[
+ {
+ "version": 1,
+ "run_id": str(run.id),
+ "content_type": "image/png",
+ "location": {"kind": "slack_file", "storage_path": path},
+ },
+ {
+ "version": 2,
+ "run_id": str(run.id),
+ "content_type": "text/markdown; charset=utf-8",
+ "location": {"kind": "slack_canvas"},
+ "content": "# Weekly signups",
+ },
+ ],
+ current_version=2,
+ )
+
+ @parameterized.expand(
+ [
+ ("stored_file", 1, b"png bytes", "image/png"),
+ ("version_text", 2, b"# Weekly signups", "text/markdown; charset=utf-8"),
+ ]
+ )
+ @patch("posthog.storage.object_storage.read_bytes")
+ def test_living_artifact_version_content(self, _name, version, expected_body, expected_type, mock_read_bytes):
+ mock_read_bytes.return_value = b"png bytes"
+ task = self.create_task()
+ run = TaskRun.objects.create(task=task, team=self.team, status=TaskRun.Status.IN_PROGRESS)
+ artifact = self._create_slack_file_living_artifact(task, run)
+
+ response = self.client.get(
+ f"/api/projects/@current/tasks/{task.id}/runs/{run.id}/living_artifacts/{artifact.id}/versions/{version}/"
+ )
+
+ self.assertEqual(response.status_code, status.HTTP_200_OK)
+ self.assertEqual(response.content, expected_body)
+ self.assertEqual(response["Content-Type"], expected_type)
+ self.assertEqual(response["Content-Disposition"], 'attachment; filename="signups.png"')
+
+ @parameterized.expand(
+ [
+ ("unknown_version",),
+ ("other_team",),
+ ("other_task",),
+ ("unknown_run",),
+ ("path_outside_task",),
+ ]
+ )
+ @patch("posthog.storage.object_storage.read_bytes")
+ def test_living_artifact_version_content_not_found(self, case, mock_read_bytes):
+ mock_read_bytes.return_value = b"png bytes"
+ task = self.create_task()
+ run = TaskRun.objects.create(task=task, team=self.team, status=TaskRun.Status.IN_PROGRESS)
+ artifact = self._create_slack_file_living_artifact(task, run)
+ version = 1
+ url_task, url_run = task, str(run.id)
+ if case == "unknown_version":
+ version = 3
+ elif case == "other_team":
+ other_team = Team.objects.create(organization=Organization.objects.create(name="Other Org"), name="Other")
+ other_task = Task.objects.create(
+ team=other_team, title="Other", description="", origin_product=Task.OriginProduct.USER_CREATED
+ )
+ other_run = TaskRun.objects.create(task=other_task, team=other_team, status=TaskRun.Status.IN_PROGRESS)
+ artifact = self._create_slack_file_living_artifact(other_task, other_run)
+ url_task, url_run = other_task, str(other_run.id)
+ elif case == "other_task":
+ other_task = self.create_task()
+ other_run = TaskRun.objects.create(task=other_task, team=self.team, status=TaskRun.Status.IN_PROGRESS)
+ artifact = self._create_slack_file_living_artifact(other_task, other_run)
+ elif case == "unknown_run":
+ url_run = str(uuid.uuid4())
+ elif case == "path_outside_task":
+ other_task = self.create_task()
+ other_run = TaskRun.objects.create(task=other_task, team=self.team, status=TaskRun.Status.IN_PROGRESS)
+ artifact = self._create_slack_file_living_artifact(
+ task, run, storage_path=f"{other_run.get_artifact_s3_prefix()}/living/doc/secret.v1.png"
+ )
+
+ response = self.client.get(
+ f"/api/projects/@current/tasks/{url_task.id}/runs/{url_run}/living_artifacts/{artifact.id}/versions/{version}/"
+ )
+
+ self.assertEqual(response.status_code, status.HTTP_404_NOT_FOUND)
+ mock_read_bytes.assert_not_called()
+
@patch("posthog.storage.object_storage.get_presigned_post")
def test_prepare_artifact_uploads(self, mock_get_presigned_post):
mock_get_presigned_post.return_value = {
@@ -11637,6 +11735,18 @@ class TestTasksAPIPermissions(BaseTaskAPITest):
f"/api/projects/@current/tasks/{{task_id}}/runs/{{run_id}}/living_artifacts/{{artifact_id}}/",
True,
),
+ (
+ "task:read",
+ "GET",
+ f"/api/projects/@current/tasks/{{task_id}}/runs/{{run_id}}/living_artifacts/{{artifact_id}}/versions/1/",
+ True,
+ ),
+ (
+ "other_scope:read",
+ "GET",
+ f"/api/projects/@current/tasks/{{task_id}}/runs/{{run_id}}/living_artifacts/{{artifact_id}}/versions/1/",
+ False,
+ ),
(
"task:read",
"POST",
diff --git a/products/tasks/frontend/generated/api.ts b/products/tasks/frontend/generated/api.ts
index 4fafdd156966..65a3a26963f4 100644
--- a/products/tasks/frontend/generated/api.ts
+++ b/products/tasks/frontend/generated/api.ts
@@ -2592,14 +2592,11 @@ export const tasksRunsLivingArtifactsList = async (
taskId: string,
runId: string,
options?: RequestInit
-): Promise<TaskRunLivingArtifactsResponseApi[]> => {
- return apiMutator<TaskRunLivingArtifactsResponseApi[]>(
- getTasksRunsLivingArtifactsListUrl(projectId, taskId, runId),
- {
- ...options,
- method: 'GET',
- }
- )
+): Promise<TaskRunLivingArtifactsResponseApi> => {
+ return apiMutator<TaskRunLivingArtifactsResponseApi>(getTasksRunsLivingArtifactsListUrl(projectId, taskId, runId), {
+ ...options,
+ method: 'GET',
+ })
}
export const getTasksRunsLivingArtifactsCreateUrl = (projectId: string, taskId: string, runId: string) => {
@@ -2679,6 +2676,34 @@ export const tasksRunsLivingArtifactsEdit = async (
)
}
+export const getTasksRunsLivingArtifactsVersionContentUrl = (
+ projectId: string,
+ taskId: string,
+ runId: string,
+ id: string,
+ version: number
+) => {
+ return `/api/projects/${projectId}/tasks/${taskId}/runs/${runId}/living_artifacts/${id}/versions/${version}/`
+}
+
+/**
+ * Streams the content of one living artifact version from the app origin. Slack file versions return their stored file. Slack canvas and message versions return their text.
+ * @summary Download one version of a living artifact
+ */
+export const tasksRunsLivingArtifactsVersionContent = async (
+ projectId: string,
+ taskId: string,
+ runId: string,
+ id: string,
+ version: number,
+ options?: RequestInit
+): Promise<Blob> => {
+ return apiMutator<Blob>(getTasksRunsLivingArtifactsVersionContentUrl(projectId, taskId, runId, id, version), {
+ ...options,
+ method: 'GET',
+ })
+}
+
export const getTasksRunsLivingArtifactsChartUrl = (projectId: string, taskId: string, runId: string) => {
return `/api/projects/${projectId}/tasks/${taskId}/runs/${runId}/living_artifacts/chart/`
}
diff --git a/products/tasks/mcp/tools.yaml b/products/tasks/mcp/tools.yaml
index f9d7703a3600..46dc0c72c7f5 100644
--- a/products/tasks/mcp/tools.yaml
+++ b/products/tasks/mcp/tools.yaml
@@ -866,6 +866,9 @@ tools:
tasks-runs-living-artifacts-open:
operation: tasks_runs_living_artifacts_open
enabled: false
+ tasks-runs-living-artifacts-version-content:
+ operation: tasks_runs_living_artifacts_version_content
+ enabled: false
tasks-runs-partial-update:
operation: tasks_runs_partial_update
enabled: false