: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.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
feat(tasks): add the logic and helpers for task run artifacts (#109669)
Shy Alter767ed1ef7ec1
diff --git a/products/posthog_ai/frontend/scenes/TaskTracker/taskRunArtifacts.test.ts b/products/posthog_ai/frontend/scenes/TaskTracker/taskRunArtifacts.test.tsnew file mode 100644index 000000000000..41603f6b714c--- /dev/null+++ b/products/posthog_ai/frontend/scenes/TaskTracker/taskRunArtifacts.test.ts@@ -0,0 +1,65 @@+import type { TaskRunArtifactResponseApi } from 'products/tasks/frontend/generated/api.schemas'++import { artifactPreviewKind, parseCsv, visibleRunArtifacts } from './taskRunArtifacts'++function artifact(overrides: Partial<TaskRunArtifactResponseApi>): TaskRunArtifactResponseApi {+ return {+ id: 'a1',+ name: 'report.md',+ type: 'output',+ source: 'agent_output',+ storage_path: 'tasks/artifacts/a1',+ uploaded_at: '2026-09-28T18:00:00Z',+ ...overrides,+ }+}++describe('taskRunArtifacts', () => {+ test.each([+ [+ 'plain rows',+ 'a,b\n1,2\n',+ [+ ['a', 'b'],+ ['1', '2'],+ ],+ ],+ [+ 'quoted comma and newline',+ 'name,note\n"Ada","x, y\nz"\n',+ [+ ['name', 'note'],+ ['Ada', 'x, y\nz'],+ ],+ ],+ ['doubled quotes and CRLF', 'q\r\n"say ""hi"""\r\n', [['q'], ['say "hi"']]],+ ['blank lines and no trailing newline', 'a\n\n1', [['a'], ['1']]],+ ])('parseCsv handles %s', (_, text, expected) => {+ expect(parseCsv(text)).toEqual(expected)+ })++ test.each([+ ['the content type', { name: 'x', content_type: 'text/html; charset=utf-8' }, 'html'],+ [+ 'the extension when the type is octet-stream',+ { name: 'chart.png', content_type: 'application/octet-stream' },+ 'image',+ ],+ ['the extension with no type', { name: 'weeks.csv' }, 'csv'],+ ['an unknown binary', { name: 'bundle.zip', content_type: 'application/zip' }, 'none'],+ ])('artifactPreviewKind reads %s', (_, overrides, expected) => {+ expect(artifactPreviewKind(artifact(overrides))).toBe(expected)+ })++ it('visibleRunArtifacts keeps only files the agent wrote', () => {+ const kept = artifact({ id: 'kept' })+ const artifacts = [+ kept,+ artifact({ id: 'attachment', source: 'user_attachment' }),+ artifact({ id: 'plan', type: 'plan' }),+ artifact({ id: 'dismissed', dismissed_at: '2026-09-28T19:00:00Z' }),+ artifact({ id: 'reference', storage_path: undefined }),+ ]+ expect(visibleRunArtifacts(artifacts)).toEqual([kept])+ })+})diff --git a/products/posthog_ai/frontend/scenes/TaskTracker/taskRunArtifacts.ts b/products/posthog_ai/frontend/scenes/TaskTracker/taskRunArtifacts.tsnew file mode 100644index 000000000000..e14c6dfeba80--- /dev/null+++ b/products/posthog_ai/frontend/scenes/TaskTracker/taskRunArtifacts.ts@@ -0,0 +1,105 @@+import type { TaskRunArtifactResponseApi } from 'products/tasks/frontend/generated/api.schemas'++export type TaskRunTab = 'conversation' | 'artifacts'++export type ArtifactPreviewKind = 'markdown' | 'html' | 'image' | 'csv' | 'text' | 'none'++export const ARTIFACT_KIND_LABEL: Record<ArtifactPreviewKind, string> = {+ markdown: 'Markdown',+ html: 'HTML',+ image: 'Image',+ csv: 'CSV',+ text: 'Text',+ none: 'File',+}++const TEXT_EXTENSIONS = ['txt', 'json', 'log', 'yaml', 'yml', 'xml', 'sql', 'py', 'ts', 'tsx', 'js', 'sh']++function extension(name: string): string {+ const dot = name.lastIndexOf('.')+ return dot === -1 ? '' : name.slice(dot + 1).toLowerCase()+}++export function artifactPreviewKind(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') {+ return 'html'+ }+ if (contentType.startsWith('image/') || ['png', 'jpg', 'jpeg', 'gif', 'webp', 'svg'].includes(ext)) {+ return 'image'+ }+ if (contentType === 'text/csv' || ext === 'csv') {+ return 'csv'+ }+ if (contentType === 'text/markdown' || ext === 'md' || ext === 'markdown') {+ return 'markdown'+ }+ if (contentType.startsWith('text/') || contentType === 'application/json' || TEXT_EXTENSIONS.includes(ext)) {+ return 'text'+ }+ return 'none'+}++export function isTextPreview(kind: ArtifactPreviewKind): boolean {+ return kind === 'markdown' || kind === 'html' || kind === 'csv' || kind === 'text'+}++/** Files the agent wrote for the user. Attachments, plans, skill bundles and dismissed files stay out. */+export function visibleRunArtifacts(artifacts: readonly TaskRunArtifactResponseApi[]): TaskRunArtifactResponseApi[] {+ return artifacts.filter(+ (artifact) =>+ !!artifact.id &&+ !!artifact.storage_path &&+ (artifact.type === 'output' || artifact.type === 'artifact') &&+ artifact.source === 'agent_output' &&+ !artifact.dismissed_at+ )+}++export function formatArtifactSize(bytes = 0): string {+ return bytes < 1024 * 1024+ ? `${Math.max(1, Math.round(bytes / 1024))} KB`+ : `${(bytes / 1024 / 1024).toFixed(1)} MB`+}++/** RFC 4180 CSV: quoted fields may hold commas, newlines and doubled quotes. */+export function parseCsv(text: string): string[][] {+ const rows: string[][] = []+ let row: string[] = []+ let field = ''+ let quoted = false+ for (let i = 0; i < text.length; i++) {+ const char = text[i]+ if (quoted) {+ if (char === '"' && text[i + 1] === '"') {+ field += '"'+ i+++ } else if (char === '"') {+ quoted = false+ } else {+ field += char+ }+ } else if (char === '"') {+ quoted = true+ } else if (char === ',') {+ row.push(field)+ field = ''+ } else if (char === '\n' || char === '\r') {+ if (char === '\r' && text[i + 1] === '\n') {+ i+++ }+ row.push(field)+ rows.push(row)+ row = []+ field = ''+ } else {+ field += char+ }+ }+ if (field !== '' || row.length > 0) {+ row.push(field)+ rows.push(row)+ }+ return rows.filter((cells) => cells.some((cell) => cell !== ''))+}diff --git a/products/posthog_ai/frontend/scenes/TaskTracker/taskRunArtifactsLogic.ts b/products/posthog_ai/frontend/scenes/TaskTracker/taskRunArtifactsLogic.tsnew file mode 100644index 000000000000..a4ebb71bfdbb--- /dev/null+++ b/products/posthog_ai/frontend/scenes/TaskTracker/taskRunArtifactsLogic.ts@@ -0,0 +1,246 @@+import { MakeLogicType, actions, connect, kea, key, listeners, path, props, reducers, selectors } from 'kea'+import { loaders } from 'kea-loaders'+import posthog from 'posthog-js'++import api from 'lib/api'+import { projectLogic } from 'scenes/projectLogic'++import {+ getTasksRunsArtifactsDownloadCreateUrl,+ getTasksRunsArtifactsDownloadRetrieveUrl,+} from 'products/tasks/frontend/generated/api'+import type { TaskRunArtifactResponseApi, TaskRunDetailDTOApi } from 'products/tasks/frontend/generated/api.schemas'++import { taskDetailSceneLogic } from './taskDetailSceneLogic'+import {+ ArtifactPreviewKind,+ TaskRunTab,+ artifactPreviewKind,+ isTextPreview,+ visibleRunArtifacts,+} from './taskRunArtifacts'++export interface TaskRunArtifactsLogicProps {+ taskId: string+}++export interface ArtifactText {+ artifactId: string+ text: string | null+ error: string | null+}++// Generated by kea-typegen. Update if you're an agent, ignore if you're human.+export interface taskRunArtifactsLogicValues {+ currentProjectId: number | null // projectLogic+ selectedRun: TaskRunDetailDTOApi | null // taskDetailSceneLogic+ activeTab: TaskRunTab+ artifactText: ArtifactText | null+ artifactTextLoading: boolean+ artifacts: TaskRunArtifactResponseApi[]+ selectedArtifact: TaskRunArtifactResponseApi | null+ selectedArtifactId: string | null+ selectedIndex: number+ selectedKind: ArtifactPreviewKind | null+ selectedText: ArtifactText | null+ textsById: Record<string, ArtifactText>+}++// Generated by kea-typegen. Update if you're an agent, ignore if you're human.+export interface taskRunArtifactsLogicActions {+ downloadArtifact: (artifact: TaskRunArtifactResponseApi) => {+ artifact: TaskRunArtifactResponseApi+ }+ ensureSelectedText: () => {+ value: true+ }+ loadArtifactText: (artifact: TaskRunArtifactResponseApi) => TaskRunArtifactResponseApi+ loadArtifactTextFailure: (+ error: string,+ errorObject?: any+ ) => {+ error: string+ errorObject?: any+ }+ loadArtifactTextSuccess: (+ artifactText: ArtifactText | null,+ payload?: TaskRunArtifactResponseApi+ ) => {+ artifactText: ArtifactText | null+ payload?: TaskRunArtifactResponseApi+ }+ selectArtifact: (artifactId: string) => {+ artifactId: string+ }+ setActiveTab: (tab: TaskRunTab) => {+ tab: TaskRunTab+ }+ stepArtifact: (delta: number) => {+ delta: number+ }+}++// Generated by kea-typegen. Update if you're an agent, ignore if you're human.+export interface taskRunArtifactsLogicMeta {+ key: string+ __keaTypeGenInternalSelectorTypes: {+ artifacts: (selectedRun: TaskRunDetailDTOApi | null) => TaskRunArtifactResponseApi[]+ selectedIndex: (artifacts: TaskRunArtifactResponseApi[], selectedArtifactId: string | null) => number+ selectedArtifact: (+ artifacts: TaskRunArtifactResponseApi[],+ selectedIndex: number+ ) => TaskRunArtifactResponseApi | null+ selectedKind: (selectedArtifact: TaskRunArtifactResponseApi | null) => ArtifactPreviewKind | null+ selectedText: (+ selectedArtifact: TaskRunArtifactResponseApi | null,+ textsById: Record<string, ArtifactText>+ ) => ArtifactText | null+ }+}++export type taskRunArtifactsLogicType = MakeLogicType<+ taskRunArtifactsLogicValues,+ taskRunArtifactsLogicActions,+ TaskRunArtifactsLogicProps,+ taskRunArtifactsLogicMeta+>++/** The download-by-id URL redirects to a fresh presigned link, so an `img` or an `a` can use it directly. */+export function artifactDownloadUrl(+ projectId: number | null,+ run: TaskRunDetailDTOApi | null,+ artifact: TaskRunArtifactResponseApi+): string | null {+ if (projectId === null || !run || !artifact.id) {+ return null+ }+ return getTasksRunsArtifactsDownloadRetrieveUrl(String(projectId), run.task, run.id, artifact.id)+}++export const taskRunArtifactsLogic = kea<taskRunArtifactsLogicType>([+ props({} as TaskRunArtifactsLogicProps),+ key((props) => props.taskId),+ path((key) => ['products', 'posthog_ai', 'frontend', 'scenes', 'TaskTracker', 'taskRunArtifactsLogic', key]),+ connect((props: TaskRunArtifactsLogicProps) => ({+ values: [taskDetailSceneLogic({ taskId: props.taskId }), ['selectedRun'], projectLogic, ['currentProjectId']],+ })),+ actions({+ setActiveTab: (tab: TaskRunTab) => ({ tab }),+ selectArtifact: (artifactId: string) => ({ artifactId }),+ stepArtifact: (delta: number) => ({ delta }),+ downloadArtifact: (artifact: TaskRunArtifactResponseApi) => ({ artifact }),+ ensureSelectedText: true,+ }),+ loaders(({ values }) => ({+ artifactText: [+ null as ArtifactText | null,+ {+ loadArtifactText: async (artifact: TaskRunArtifactResponseApi): Promise<ArtifactText | null> => {+ const run = values.selectedRun+ if (values.currentProjectId === null || !run || !artifact.id || !artifact.storage_path) {+ return null+ }+ // The POST download streams the bytes from the app origin, so reading them needs no CORS+ // grant on the bucket. The GET variant redirects to object storage instead.+ try {+ // nosemgrep: prefer-codegen-api -- A file download: the generated function parses the body as JSON.+ const response = await api.createResponse(+ getTasksRunsArtifactsDownloadCreateUrl(String(values.currentProjectId), run.task, run.id),+ { storage_path: artifact.storage_path }+ )+ return { artifactId: artifact.id, text: await response.text(), error: null }+ } catch {+ return {+ artifactId: artifact.id,+ text: null,+ error: 'This file did not load. Try again later.',+ }+ }+ },+ },+ ],+ })),+ reducers({+ activeTab: ['conversation' as TaskRunTab, { setActiveTab: (_, { tab }) => tab }],+ selectedArtifactId: [null as string | null, { selectArtifact: (_, { artifactId }) => artifactId }],+ textsById: [+ {} as Record<string, ArtifactText>,+ {+ loadArtifactTextSuccess: (state, { artifactText }) =>+ artifactText ? { ...state, [artifactText.artifactId]: artifactText } : state,+ },+ ],+ }),+ selectors({+ artifacts: [+ (s) => [s.selectedRun],+ (selectedRun: TaskRunDetailDTOApi | null): TaskRunArtifactResponseApi[] =>+ visibleRunArtifacts(selectedRun?.artifacts ?? []),+ ],+ selectedIndex: [+ (s) => [s.artifacts, s.selectedArtifactId],+ (artifacts: TaskRunArtifactResponseApi[], selectedArtifactId: string | null): number =>+ Math.max(+ 0,+ artifacts.findIndex((artifact) => artifact.id === selectedArtifactId)+ ),+ ],+ selectedArtifact: [+ (s) => [s.artifacts, s.selectedIndex],+ (artifacts: TaskRunArtifactResponseApi[], selectedIndex: number): TaskRunArtifactResponseApi | null =>+ artifacts[selectedIndex] ?? null,+ ],+ selectedKind: [+ (s) => [s.selectedArtifact],+ (selectedArtifact: TaskRunArtifactResponseApi | null): ArtifactPreviewKind | null =>+ selectedArtifact ? artifactPreviewKind(selectedArtifact) : null,+ ],+ selectedText: [+ (s) => [s.selectedArtifact, s.textsById],+ (+ selectedArtifact: TaskRunArtifactResponseApi | null,+ textsById: Record<string, ArtifactText>+ ): ArtifactText | null => (selectedArtifact?.id && textsById[selectedArtifact.id]) || null,+ ],+ }),+ listeners(({ actions, values }) => {+ const loadSelectedText = (): void => {+ const artifact = values.selectedArtifact+ const kind = values.selectedKind+ if (values.activeTab === 'artifacts' && artifact && kind && isTextPreview(kind) && !values.selectedText) {+ actions.loadArtifactText(artifact)+ }+ }+ const previewSelected = (): void => {+ const artifact = values.selectedArtifact+ if (values.activeTab !== 'artifacts' || !artifact || !values.selectedKind) {+ return+ }+ // pinned: analytics event name and properties. Renaming them breaks insights.+ posthog.capture('task artifact previewed', {+ kind: values.selectedKind,+ content_type: artifact.content_type ?? null,+ })+ }+ return {+ setActiveTab: ({ tab }) => {+ if (tab === 'artifacts') {+ posthog.capture('task artifacts tab opened', { artifact_count: values.artifacts.length })+ }+ previewSelected()+ },+ selectArtifact: previewSelected,+ ensureSelectedText: loadSelectedText,+ stepArtifact: ({ delta }) => {+ const { artifacts, selectedIndex } = values+ const next = artifacts[(selectedIndex + delta + artifacts.length) % artifacts.length]+ if (next?.id) {+ actions.selectArtifact(next.id)+ }+ },+ downloadArtifact: ({ artifact }) => {+ posthog.capture('task artifact downloaded', { kind: artifactPreviewKind(artifact) })+ },+ }+ }),+])