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): save edited text artifacts as new versions (#110445)

Shy Alter76fc7bd554dd
diff --git a/products/posthog_ai/frontend/scenes/TaskTracker/taskRunArtifacts.test.ts b/products/posthog_ai/frontend/scenes/TaskTracker/taskRunArtifacts.test.ts
index 3523b3160d5d..5ea5eb87142c 100644
--- a/products/posthog_ai/frontend/scenes/TaskTracker/taskRunArtifacts.test.ts
+++ b/products/posthog_ai/frontend/scenes/TaskTracker/taskRunArtifacts.test.ts
@@ -5,8 +5,10 @@ import type {
import {
RunArtifact,
+ artifactEditConflict,
artifactPreviewKind,
collectRunArtifacts,
+ editableArtifactKind,
groupArtifactVersions,
livingArtifactFiles,
listboxKeyTarget,
@@ -122,7 +124,37 @@ describe('taskRunArtifacts', () => {
artifact({ id: 'dismissed', dismissed_at: '2026-09-28T19:00:00Z' }),
artifact({ id: 'reference', storage_path: undefined }),
]
- expect(visibleRunArtifacts(artifacts)).toEqual([kept, insight])
+ const savedByUser = artifact({ id: 'saved-by-user', source: '', uploaded_by: 'user' })
+ expect(visibleRunArtifacts([...artifacts, savedByUser])).toEqual([kept, insight, savedByUser])
+ })
+
+ test.each([
+ ['markdown by content type', { content_type: 'text/markdown' }, 'markdown'],
+ ['plain text by extension with no type', { name: 'notes.txt', content_type: undefined }, 'plain-text'],
+ ['CSV as not editable', { name: 'weeks.csv', content_type: 'text/csv' }, null],
+ ['JSON as not editable', { name: 'data.json', content_type: 'application/json' }, null],
+ ])('editableArtifactKind reads %s', (_, overrides, expected) => {
+ expect(editableArtifactKind({ ...artifact(overrides), runId: 'run-1' })).toBe(expected)
+ })
+
+ const base = artifact({ id: 'v1', uploaded_at: '2026-09-30T17:00:00Z' })
+ test.each([
+ ['no conflict when the base is still the latest', [{ id: 'run-1', artifacts: [base] }], null],
+ [
+ 'a newer version from a later run',
+ [
+ { id: 'run-2', artifacts: [artifact({ id: 'v2', uploaded_at: '2026-09-30T18:00:00Z' })] },
+ { id: 'run-1', artifacts: [base] },
+ ],
+ 'newer-version',
+ ],
+ [
+ 'every version dismissed',
+ [{ id: 'run-1', artifacts: [{ ...base, dismissed_at: '2026-09-30T18:00:00Z' }] }],
+ 'dismissed',
+ ],
+ ])('artifactEditConflict finds %s', (_, runs, expected) => {
+ expect(artifactEditConflict(runs, 'report.md', 'v1')).toBe(expected)
})
it('collectRunArtifacts keeps files from earlier runs of a resumed task', () => {
diff --git a/products/posthog_ai/frontend/scenes/TaskTracker/taskRunArtifacts.ts b/products/posthog_ai/frontend/scenes/TaskTracker/taskRunArtifacts.ts
index 3ba046979800..067b15462077 100644
--- a/products/posthog_ai/frontend/scenes/TaskTracker/taskRunArtifacts.ts
+++ b/products/posthog_ai/frontend/scenes/TaskTracker/taskRunArtifacts.ts
@@ -110,7 +110,7 @@ export function isTextPreview(kind: ArtifactPreviewKind): boolean {
}
/**
- * Files the agent wrote for the user, and the PostHog objects the run cites.
+ * Files the agent wrote for the user, versions of them a user saved, and the PostHog objects the run cites.
* Attachments, plans, skill bundles and dismissed entries stay out.
*/
export function visibleRunArtifacts(artifacts: readonly TaskRunArtifactResponseApi[]): TaskRunArtifactResponseApi[] {
@@ -121,10 +121,14 @@ export function visibleRunArtifacts(artifacts: readonly TaskRunArtifactResponseA
if (postHogObjectRef(artifact)) {
return true
}
+ if (!artifact.storage_path) {
+ return false
+ }
+ // An edit saved here or in PostHog Desktop is an `output` upload by a user, with no source label.
+ const savedByUser = artifact.type === 'output' && artifact.uploaded_by === 'user'
return (
- !!artifact.storage_path &&
- (artifact.type === 'output' || artifact.type === 'artifact') &&
- artifact.source === 'agent_output'
+ savedByUser ||
+ ((artifact.type === 'output' || artifact.type === 'artifact') && artifact.source === 'agent_output')
)
})
}
@@ -356,3 +360,56 @@ export function livingArtifactFiles(artifacts: readonly TaskRunLivingArtifactRes
})
.sort((a, b) => b.latest.uploaded_at.localeCompare(a.latest.uploaded_at))
}
+
+/** The text files a user can edit, the same set PostHog Desktop edits. */
+export type EditableArtifactKind = 'markdown' | 'html' | 'plain-text'
+
+export const EDITOR_LANGUAGE: Record<EditableArtifactKind, string> = {
+ markdown: 'markdown',
+ html: 'html',
+ 'plain-text': 'plaintext',
+}
+
+export function editableArtifactKind(artifact: RunArtifact): EditableArtifactKind | null {
+ // A living document and a cited object have no uploaded file to replace.
+ if (artifact.living || artifact.type === 'reference' || !artifact.storage_path || !artifact.id) {
+ return 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'
+ }
+ // A file with any other content type is not text the editor can round-trip safely.
+ if (contentType) {
+ return null
+ }
+ const ext = extension(artifact.name)
+ return ext === 'md' ? 'markdown' : ext === 'html' ? 'html' : ext === 'txt' ? 'plain-text' : null
+}
+
+/** Why a save must ask first: the agent wrote a newer version, or every version was dismissed. */
+export type ArtifactEditConflict = 'newer-version' | 'dismissed'
+
+/**
+ * Compares the newest shown version of a file with the version the edit started from.
+ * Pass freshly read runs, because a stale manifest can still show a version that is now dismissed.
+ */
+export function artifactEditConflict(
+ runs: readonly (RunWithArtifacts | null | undefined)[],
+ name: string,
+ baseArtifactId: string
+): ArtifactEditConflict | null {
+ const file = groupArtifactVersions(collectRunArtifacts(runs)).find(
+ (candidate) => candidate.latest.type !== 'reference' && candidate.name === name
+ )
+ if (!file) {
+ return 'dismissed'
+ }
+ return file.latest.id === baseArtifactId ? null : 'newer-version'
+}
diff --git a/products/posthog_ai/frontend/scenes/TaskTracker/taskRunArtifactsLogic.test.ts b/products/posthog_ai/frontend/scenes/TaskTracker/taskRunArtifactsLogic.test.ts
index b64803d66a4d..3426ac55d2e9 100644
--- a/products/posthog_ai/frontend/scenes/TaskTracker/taskRunArtifactsLogic.test.ts
+++ b/products/posthog_ai/frontend/scenes/TaskTracker/taskRunArtifactsLogic.test.ts
@@ -3,19 +3,49 @@ import { expectLogic } from 'kea-test-utils'
import { initKeaTests } from '~/test/init'
+import type { TaskRunArtifactResponseApi } from 'products/tasks/frontend/generated/api.schemas'
+
+import { uploadRunOutputVersion } from '../../utils/artifactUpload'
import type { RunArtifact } from './taskRunArtifacts'
import { artifactDownloadUrl, taskRunArtifactsLogic } from './taskRunArtifactsLogic'
+jest.mock('../../utils/artifactUpload', () => ({ uploadRunOutputVersion: jest.fn() }))
+
const TASK_ID = 'task-123'
+const RUN_ID = 'run-1'
+
+function reportVersion(id: string, uploadedAt: string): TaskRunArtifactResponseApi {
+ return {
+ id,
+ name: 'report.md',
+ type: 'output',
+ source: 'agent_output',
+ content_type: 'text/markdown',
+ storage_path: `tasks/artifacts/${id}`,
+ uploaded_at: uploadedAt,
+ }
+}
describe('taskRunArtifactsLogic', () => {
const originalFetch = global.fetch
+ let runArtifacts: TaskRunArtifactResponseApi[] = []
beforeEach(() => {
initKeaTests()
+ runArtifacts = []
+ jest.mocked(uploadRunOutputVersion).mockReset()
global.fetch = jest.fn((input: RequestInfo | URL) => {
const url = String(input)
- const payload = url.endsWith('/runs/') ? { results: [] } : { id: TASK_ID }
+ if (url.includes('/artifacts/download/')) {
+ return Promise.resolve(new Response('# Report'))
+ }
+ const payload = /\/runs\/(\?.*)?$/.test(url)
+ ? { results: runArtifacts.length ? [{ id: RUN_ID }] : [] }
+ : url.includes('/living_artifacts/')
+ ? { artifacts: [] }
+ : url.includes(`/runs/${RUN_ID}/`)
+ ? { id: RUN_ID, artifacts: runArtifacts }
+ : { id: TASK_ID }
return Promise.resolve(
new Response(JSON.stringify(payload), { headers: { 'Content-Type': 'application/json' } })
)
@@ -76,4 +106,32 @@ describe('taskRunArtifactsLogic', () => {
}
expect(artifactDownloadUrl(1, TASK_ID, version)).toBe(expected)
})
+
+ it('asks before a save replaces a version the agent wrote during the edit', async () => {
+ runArtifacts = [reportVersion('report-v1', '2026-09-28T18:00:00Z')]
+ jest.mocked(uploadRunOutputVersion).mockResolvedValue('report-v3')
+ const logic = taskRunArtifactsLogic({ taskId: TASK_ID })
+ logic.mount()
+ logic.actions.setActiveTab('artifacts')
+ await expectLogic(logic).toFinishAllListeners()
+ await expectLogic(logic, () => logic.actions.ensureSelectedText()).toFinishAllListeners()
+ expect(logic.values.selectedText?.text).toBe('# Report')
+
+ logic.actions.startEditing()
+ logic.actions.setEditDraft('# Report, edited')
+ runArtifacts = [...runArtifacts, reportVersion('report-v2', '2026-09-28T18:10:00Z')]
+ await expectLogic(logic, () => logic.actions.saveEdit()).toFinishAllListeners()
+
+ expect(logic.values.editConflict).toBe('newer-version')
+ expect(uploadRunOutputVersion).not.toHaveBeenCalled()
+
+ await expectLogic(logic, () => logic.actions.resolveEditConflict('save_as_latest')).toFinishAllListeners()
+
+ expect(uploadRunOutputVersion).toHaveBeenCalledWith(expect.any(String), TASK_ID, RUN_ID, {
+ name: 'report.md',
+ content: '# Report, edited',
+ contentType: 'text/markdown',
+ })
+ expect(logic.values).toMatchObject({ isEditing: false, editConflict: null })
+ })
})
diff --git a/products/posthog_ai/frontend/scenes/TaskTracker/taskRunArtifactsLogic.ts b/products/posthog_ai/frontend/scenes/TaskTracker/taskRunArtifactsLogic.ts
index 624838ae30fc..4cbf4bb4d32d 100644
--- a/products/posthog_ai/frontend/scenes/TaskTracker/taskRunArtifactsLogic.ts
+++ b/products/posthog_ai/frontend/scenes/TaskTracker/taskRunArtifactsLogic.ts
@@ -13,7 +13,7 @@ import {
selectors,
} from 'kea'
import { loaders } from 'kea-loaders'
-import { actionToUrl, router, urlToAction } from 'kea-router'
+import { actionToUrl, beforeUnload, router, urlToAction } from 'kea-router'
import posthog from 'posthog-js'
import { toast } from '@posthog/quill-primitives'
@@ -36,15 +36,20 @@ import type {
} from 'products/tasks/frontend/generated/api.schemas'
import type { TaskRun } from '../../types/taskTypes'
+import { uploadRunOutputVersion } from '../../utils/artifactUpload'
import { taskDetailSceneLogic } from './taskDetailSceneLogic'
import {
ARTIFACT_PARAM,
+ ArtifactEditConflict,
ArtifactFile,
ArtifactPreviewKind,
+ EditableArtifactKind,
RunArtifact,
TaskRunTab,
+ artifactEditConflict,
artifactPreviewKind,
collectRunArtifacts,
+ editableArtifactKind,
groupArtifactVersions,
isTextPreview,
livingArtifactFiles,
@@ -67,6 +72,20 @@ export interface ArtifactText {
error: string | null
}
+/** The file version an edit started from, and the text it had then. */
+export interface ArtifactEditSession {
+ fileKey: string
+ name: string
+ /** The run that holds the base version. The saved version goes to the same run. */
+ runId: string
+ baseArtifactId: string
+ contentType: string
+ kind: EditableArtifactKind
+ original: string
+}
+
+export type ArtifactConflictResolution = 'keep_editing' | 'save_as_latest'
+
export interface ArtifactMedia {
artifactId: string
/** A `blob:` URL. The app's media-src allows it, and not the object storage origin. */
@@ -90,12 +109,21 @@ export interface taskRunArtifactsLogicValues {
commentsOpen: boolean
dismissalPending: boolean
dismissals: Record<string, boolean>
+ editConflict: ArtifactEditConflict | null
+ editDirty: boolean
+ editDisabledReason: string | null
+ editDraft: string
+ editError: string | null
+ editSaving: boolean
+ editSession: ArtifactEditSession | null
files: ArtifactFile[]
+ isEditing: boolean
livingArtifacts: TaskRunLivingArtifactResponseApi[]
livingArtifactsLoading: boolean
livingFiles: ArtifactFile[]
mediaById: Record<string, ArtifactMedia>
selectedArtifact: RunArtifact | null
+ selectedEditableKind: EditableArtifactKind | null
selectedFile: ArtifactFile | null
selectedFileKey: string | null
selectedIndex: number
@@ -118,6 +146,9 @@ export interface taskRunArtifactsLogicActions {
payload?: any
runs: TaskRun[]
} // taskDetailSceneLogic
+ cancelEditing: () => {
+ value: true
+ }
dismissFile: (fileKey: string) => {
fileKey: string
}
@@ -127,6 +158,9 @@ export interface taskRunArtifactsLogicActions {
downloadArtifact: (artifact: RunArtifact) => {
artifact: RunArtifact
}
+ editSaved: (artifactId: string) => {
+ artifactId: string
+ }
ensureSelectedText: () => {
value: true
}
@@ -206,9 +240,15 @@ export interface taskRunArtifactsLogicActions {
reportObjectOpened: (objectKind: string) => {
objectKind: string
}
+ resolveEditConflict: (resolution: ArtifactConflictResolution) => {
+ resolution: ArtifactConflictResolution
+ }
restoreFile: (file: ArtifactFile) => {
file: ArtifactFile
}
+ saveEdit: () => {
+ value: true
+ }
selectArtifact: (
fileKey: string,
source?: ArtifactSelectSource
@@ -225,6 +265,21 @@ export interface taskRunArtifactsLogicActions {
setCommentsOpen: (open: boolean) => {
open: boolean
}
+ setEditConflict: (conflict: ArtifactEditConflict | null) => {
+ conflict: ArtifactEditConflict | null
+ }
+ setEditDraft: (draft: string) => {
+ draft: string
+ }
+ setEditError: (error: string | null) => {
+ error: string | null
+ }
+ setEditSaving: (saving: boolean) => {
+ saving: boolean
+ }
+ setEditSession: (session: ArtifactEditSession | null) => {
+ session: ArtifactEditSession | null
+ }
setFileDismissed: (
artifactIds: string[],
dismissed: boolean,
@@ -234,6 +289,9 @@ export interface taskRunArtifactsLogicActions {
dismissed: boolean
selectKey: string | null
}
+ startEditing: () => {
+ value: true
+ }
stepArtifact: (delta: number) => {
delta: number
}
@@ -267,6 +325,14 @@ export interface taskRunArtifactsLogicMeta {
selectedVersionId: string | null,
arg: any
) => string | null
+ isEditing: (editSession: ArtifactEditSession | null) => boolean
+ editDirty: (editSession: ArtifactEditSession | null, editDraft: string) => boolean
+ selectedEditableKind: (selectedArtifact: RunArtifact | null) => EditableArtifactKind | null
+ editDisabledReason: (
+ selectedEditableKind: EditableArtifactKind | null,
+ selectedVersionIndex: number,
+ selectedText: ArtifactText | null
+ ) => string | null
selectedText: (
selectedArtifact: RunArtifact | null,
textsById: Record<string, ArtifactText>
@@ -283,6 +349,20 @@ export type taskRunArtifactsLogicType = MakeLogicType<
// A long-lived task can have many runs. Older runs past this cap keep their files out of the list.
const MAX_CHAIN_RUNS = 20
+
+const EDIT_CONTENT_TYPE: Record<EditableArtifactKind, string> = {
+ markdown: 'text/markdown',
+ html: 'text/html',
+ 'plain-text': 'text/plain',
+}
+
+/** The runs list carries no artifact manifests, so each run's detail is read to find its files. */
+async function fetchChainRuns(projectId: string, taskId: string, runIds: string[]): Promise<TaskRunDetailDTOApi[]> {
+ const runs = await Promise.all(
+ runIds.slice(0, MAX_CHAIN_RUNS).map((runId) => tasksRunsRetrieve(projectId, taskId, runId).catch(() => null))
+ )
+ return runs.filter((run): run is TaskRunDetailDTOApi => run !== null)
+}
// 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
@@ -349,23 +429,26 @@ export const taskRunArtifactsLogic = kea<taskRunArtifactsLogicType>([
selectKey,
}),
dismissalFailed: true,
+ startEditing: true,
+ setEditSession: (session: ArtifactEditSession | null) => ({ session }),
+ setEditDraft: (draft: string) => ({ draft }),
+ cancelEditing: true,
+ saveEdit: true,
+ resolveEditConflict: (resolution: ArtifactConflictResolution) => ({ resolution }),
+ setEditConflict: (conflict: ArtifactEditConflict | null) => ({ conflict }),
+ setEditSaving: (saving: boolean) => ({ saving }),
+ setEditError: (error: string | null) => ({ error }),
+ editSaved: (artifactId: string) => ({ artifactId }),
}),
loaders(({ props, values }) => ({
chainRuns: [
[] as TaskRunDetailDTOApi[],
{
- // The runs list carries no artifact manifests, so each run's detail is read to find its files.
loadChainRuns: async (runIds: string[]): Promise<TaskRunDetailDTOApi[]> => {
if (values.currentProjectId === null) {
return values.chainRuns
}
- const projectId = String(values.currentProjectId)
- const runs = await Promise.all(
- runIds
- .slice(0, MAX_CHAIN_RUNS)
- .map((runId) => tasksRunsRetrieve(projectId, props.taskId, runId).catch(() => null))
- )
- return runs.filter((run): run is TaskRunDetailDTOApi => run !== null)
+ return fetchChainRuns(String(values.currentProjectId), props.taskId, runIds)
},
},
],
@@ -477,6 +560,8 @@ export const taskRunArtifactsLogic = kea<taskRunArtifactsLogicType>([
selectArtifact: () => null,
selectVersion: (_, { artifactId }) => artifactId,
openFromUrl: (_, { versionId }) => versionId,
+ // The saved version is the newest one, so following the latest opens it.
+ editSaved: () => null,
setFileDismissed: () => null,
},
],
@@ -499,6 +584,44 @@ export const taskRunArtifactsLogic = kea<taskRunArtifactsLogicType>([
dismissalFailed: () => false,
},
],
+ editSession: [
+ null as ArtifactEditSession | null,
+ {
+ setEditSession: (_, { session }) => session,
+ cancelEditing: () => null,
+ editSaved: () => null,
+ // The file list is locked while editing, so only a link or the back button opens another file.
+ openFromUrl: () => null,
+ },
+ ],
+ editDraft: [
+ '',
+ {
+ setEditSession: (_, { session }) => session?.original ?? '',
+ setEditDraft: (_, { draft }) => draft,
+ cancelEditing: () => '',
+ editSaved: () => '',
+ openFromUrl: () => '',
+ },
+ ],
+ editSaving: [false, { setEditSaving: (_, { saving }) => saving }],
+ editConflict: [
+ null as ArtifactEditConflict | null,
+ {
+ setEditConflict: (_, { conflict }) => conflict,
+ cancelEditing: () => null,
+ editSaved: () => null,
+ },
+ ],
+ editError: [
+ null as string | null,
+ {
+ setEditError: (_, { error }) => error,
+ setEditSession: () => null,
+ cancelEditing: () => null,
+ editSaved: () => null,
+ },
+ ],
mediaById: [
{} as Record<string, ArtifactMedia>,
{
@@ -601,6 +724,38 @@ export const taskRunArtifactsLogic = kea<taskRunArtifactsLogicType>([
)
},
],
+ isEditing: [(s) => [s.editSession], (editSession: ArtifactEditSession | null): boolean => !!editSession],
+ editDirty: [
+ (s) => [s.editSession, s.editDraft],
+ (editSession: ArtifactEditSession | null, editDraft: string): boolean =>
+ !!editSession && editDraft !== editSession.original,
+ ],
+ selectedEditableKind: [
+ (s) => [s.selectedArtifact],
+ (selectedArtifact: RunArtifact | null): EditableArtifactKind | null =>
+ selectedArtifact ? editableArtifactKind(selectedArtifact) : null,
+ ],
+ /** Why the open file can't be edited now, or null when it can. */
+ editDisabledReason: [
+ (s) => [s.selectedEditableKind, s.selectedVersionIndex, s.selectedText],
+ (
+ selectedEditableKind: EditableArtifactKind | null,
+ selectedVersionIndex: number,
+ selectedText: ArtifactText | null
+ ): string | null => {
+ if (!selectedEditableKind) {
+ return "This file type can't be edited here"
+ }
+ // A save always adds a new latest version, so an edit must start from the latest one.
+ if (selectedVersionIndex !== 0) {
+ return 'Only the latest version can be edited'
+ }
+ if (!selectedText || selectedText.text === null) {
+ return 'The file has not loaded yet'
+ }
+ return null
+ },
+ ],
selectedText: [
(s) => [s.selectedArtifact, s.textsById],
(selectedArtifact: RunArtifact | null, textsById: Record<string, ArtifactText>): ArtifactText | null => {
@@ -613,6 +768,44 @@ export const taskRunArtifactsLogic = kea<taskRunArtifactsLogicType>([
],
}),
listeners(({ actions, values, props }) => {
+ const editProperties = (session: ArtifactEditSession): Record<string, unknown> => ({
+ kind: session.kind,
+ content_type: session.contentType,
+ version_count: values.files.find((file) => file.key === session.fileKey)?.versions.length ?? 1,
+ })
+ const saveVersion = async (afterConflict: boolean): Promise<void> => {
+ const session = values.editSession
+ if (!session || values.currentProjectId === null) {
+ return
+ }
+ const projectId = String(values.currentProjectId)
+ const content = values.editDraft
+ actions.setEditSaving(true)
+ actions.setEditError(null)
+ try {
+ const artifactId = await uploadRunOutputVersion(projectId, props.taskId, session.runId, {
+ name: session.name,
+ content,
+ contentType: session.contentType,
+ })
+ // Read the manifests before the edit ends, so the new version is in the list when the preview opens.
+ actions.loadChainRunsSuccess(
+ await fetchChainRuns(
+ projectId,
+ props.taskId,
+ values.runs.map((run) => run.id)
+ )
+ )
+ actions.loadArtifactTextSuccess({ artifactId, text: content, error: null })
+ // pinned: analytics event name and properties. Renaming them breaks insights.
+ posthog.capture('task artifact saved', { ...editProperties(session), after_conflict: afterConflict })
+ actions.editSaved(artifactId)
+ } catch {
+ actions.setEditError("Couldn't save the file. Try again. Your changes are still in the editor.")
+ } finally {
+ actions.setEditSaving(false)
+ }
+ }
const loadSelectedText = (): void => {
const artifact = values.selectedArtifact
const kind = values.selectedKind
@@ -769,6 +962,79 @@ export const taskRunArtifactsLogic = kea<taskRunArtifactsLogicType>([
// pinned: analytics event name and properties. Renaming them breaks insights.
posthog.capture('task artifact link opened', { has_version: !!versionId })
},
+ startEditing: () => {
+ const file = values.selectedFile
+ const artifact = values.selectedArtifact
+ const kind = values.selectedEditableKind
+ const text = values.selectedText?.text
+ if (values.editDisabledReason || !file || !artifact?.id || !kind || typeof text !== 'string') {
+ return
+ }
+ const session: ArtifactEditSession = {
+ fileKey: file.key,
+ name: artifact.name,
+ runId: artifact.runId,
+ baseArtifactId: artifact.id,
+ contentType: artifact.content_type || EDIT_CONTENT_TYPE[kind],
+ kind,
+ original: text,
+ }
+ actions.setEditSession(session)
+ // pinned: analytics event name and properties. Renaming them breaks insights.
+ posthog.capture('task artifact edit started', editProperties(session))
+ },
+ saveEdit: async () => {
+ const session = values.editSession
+ if (!session || values.editSaving || values.currentProjectId === null) {
+ return
+ }
+ actions.setEditSaving(true)
+ actions.setEditError(null)
+ let conflict: ArtifactEditConflict | null
+ try {
+ const runs = await fetchChainRuns(
+ String(values.currentProjectId),
+ props.taskId,
+ values.runs.map((run) => run.id)
+ )
+ // fetchChainRuns drops a run that fails to load, so no runs means the check could not run.
+ if (runs.length === 0) {
+ throw new Error('No runs loaded')
+ }
+ actions.loadChainRunsSuccess(runs)
+ conflict = artifactEditConflict(runs, session.name, session.baseArtifactId)
+ } catch {
+ actions.setEditError(
+ "Couldn't check for a newer version of the file. Try again. Your changes are still in the editor."
+ )
+ actions.setEditSaving(false)
+ return
+ }
+ if (conflict) {
+ actions.setEditConflict(conflict)
+ actions.setEditSaving(false)
+ return
+ }
+ await saveVersion(false)
+ },
+ resolveEditConflict: async ({ resolution }) => {
+ const conflict = values.editConflict
+ const session = values.editSession
+ if (!conflict || !session || values.editSaving) {
+ return
+ }
+ // pinned: analytics event name and properties. Renaming them breaks insights.
+ posthog.capture('task artifact save conflict', {
+ ...editProperties(session),
+ conflict: conflict === 'dismissed' ? 'dismissed' : 'newer_version',
+ resolution,
+ })
+ if (resolution === 'keep_editing') {
+ actions.setEditConflict(null)
+ return
+ }
+ await saveVersion(true)
+ },
}
}),
actionToUrl(({ values, props }) => {
@@ -808,6 +1074,14 @@ export const taskRunArtifactsLogic = kea<taskRunArtifactsLogicType>([
}
},
})),
+ beforeUnload(({ values, actions, props }) => ({
+ // The artifact and version params change while the user stays on the task, so only leaving it asks.
+ enabled: (newLocation) =>
+ values.editDirty &&
+ (!newLocation || !urlIsForTask(newLocation.pathname, newLocation.searchParams, props.taskId)),
+ message: "Leave this task? Your changes to the file aren't saved.",
+ onConfirm: () => actions.cancelEditing(),
+ })),
afterMount(({ actions, values }) => {
if (values.runs.length > 0) {
actions.loadChainRuns(values.runs.map((run) => run.id))
diff --git a/products/posthog_ai/frontend/utils/artifactUpload.ts b/products/posthog_ai/frontend/utils/artifactUpload.ts
index 56de526bee4a..baa1fd582c2c 100644
--- a/products/posthog_ai/frontend/utils/artifactUpload.ts
+++ b/products/posthog_ai/frontend/utils/artifactUpload.ts
@@ -54,7 +54,10 @@ function prepareRequestFor(file: File): PrepareRequest {
}
}
-async function uploadToPresignedPost(prepared: PreparedArtifact, file: File): Promise<void> {
+async function uploadToPresignedPost(
+ prepared: Pick<PreparedArtifact, 'name' | 'presigned_post'>,
+ file: File
+): Promise<void> {
const formData = new FormData()
// S3 requires the presigned fields verbatim and ahead of the file part.
for (const [key, value] of Object.entries(prepared.presigned_post.fields)) {
@@ -124,3 +127,42 @@ export async function uploadRunAttachments(
files
)
}
+
+/**
+ * Save text as a new version of a run file, the same upload PostHog Desktop makes for an edit.
+ * The artifacts tab groups uploads by file name, so the same name adds a version. Returns the new artifact id.
+ */
+export async function uploadRunOutputVersion(
+ projectId: string,
+ taskId: string,
+ runId: string,
+ { name, content, contentType }: { name: string; content: string; contentType: string }
+): Promise<string> {
+ const file = new File([content], name, { type: contentType })
+ const {
+ artifacts: [prepared],
+ } = await tasksRunsArtifactsPrepareUploadCreate(projectId, taskId, runId, {
+ artifacts: [{ name, type: TaskRunArtifactTypeEnumApi.Output, size: file.size, content_type: contentType }],
+ })
+ if (!prepared) {
+ throw new Error(`Couldn't prepare ${name} for upload`)
+ }
+ await uploadToPresignedPost(prepared, file)
+ const {
+ artifacts: [finalized],
+ } = await tasksRunsArtifactsFinalizeUploadCreate(projectId, taskId, runId, {
+ artifacts: [
+ {
+ id: prepared.id,
+ name: prepared.name,
+ type: TaskRunArtifactTypeEnumApi.Output,
+ storage_path: prepared.storage_path,
+ content_type: contentType,
+ },
+ ],
+ })
+ if (!finalized?.id) {
+ throw new Error(`Couldn't save ${name}`)
+ }
+ return finalized.id
+}