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): add the logic for artifact comments (#110450)

Shy Alter4e6ec4e78988
diff --git a/products/posthog_ai/frontend/scenes/TaskTracker/taskArtifactCommentsLogic.test.ts b/products/posthog_ai/frontend/scenes/TaskTracker/taskArtifactCommentsLogic.test.ts
new file mode 100644
index 000000000000..a86fd3b734f3
--- /dev/null
+++ b/products/posthog_ai/frontend/scenes/TaskTracker/taskArtifactCommentsLogic.test.ts
@@ -0,0 +1,88 @@
+import { expectLogic } from 'kea-test-utils'
+
+import { initKeaTests } from '~/test/init'
+
+import { regionAnchorAt } from './artifactComments'
+import { taskArtifactCommentsLogic } from './taskArtifactCommentsLogic'
+
+const TASK_ID = 'task-123'
+const ARTIFACT_ID = 'artifact-chart'
+
+const ROOT = {
+ id: 'root-1',
+ created_by: null,
+ created_at: '2026-09-30T18:00:00Z',
+ content: 'Is this axis right?',
+ scope: 'task_artifact',
+ item_id: ARTIFACT_ID,
+ source_comment: null,
+ completed_at: null,
+ item_context: { anchor: { kind: 'region', x: 0.4, y: 0.2, width: 0.035, height: 0.035 }, taskId: TASK_ID },
+}
+
+describe('taskArtifactCommentsLogic', () => {
+ const originalFetch = global.fetch
+ let posted: Record<string, unknown>[]
+
+ beforeEach(() => {
+ initKeaTests()
+ posted = []
+ global.fetch = jest.fn((_input: RequestInfo | URL, init?: RequestInit) => {
+ if (init?.method === 'POST') {
+ posted.push(JSON.parse(String(init.body)))
+ return Promise.resolve(
+ new Response(JSON.stringify({ ...ROOT, id: `saved-${posted.length}` }), {
+ headers: { 'Content-Type': 'application/json' },
+ })
+ )
+ }
+ return Promise.resolve(
+ new Response(JSON.stringify({ results: [ROOT], next: null }), {
+ headers: { 'Content-Type': 'application/json' },
+ })
+ )
+ }) as typeof fetch
+ })
+
+ afterEach(() => {
+ global.fetch = originalFetch
+ })
+
+ // Desktop lists artifact comments by task id from the context and draws pins from the anchor, so a write
+ // without either would not show there.
+ it('writes pins and resolves in the shape Desktop reads', async () => {
+ const logic = taskArtifactCommentsLogic({ taskId: TASK_ID, artifactId: ARTIFACT_ID, kind: 'image' })
+ logic.mount()
+ await expectLogic(logic).toFinishAllListeners()
+
+ logic.actions.setPinMode(true)
+ logic.actions.setPendingAnchor(regionAnchorAt(0.5, 0.5), null)
+ logic.actions.setDraft('pending', ' The legend covers the bars ')
+ logic.actions.submitComment('pending')
+ await expectLogic(logic).toFinishAllListeners()
+
+ logic.actions.setThreadResolved(ROOT.id, true)
+ await expectLogic(logic).toFinishAllListeners()
+
+ expect(posted).toEqual([
+ expect.objectContaining({
+ scope: 'task_artifact',
+ item_id: ARTIFACT_ID,
+ content: 'The legend covers the bars',
+ item_context: { anchor: regionAnchorAt(0.5, 0.5), taskId: TASK_ID },
+ }),
+ expect.objectContaining({
+ scope: 'task_artifact',
+ item_id: ARTIFACT_ID,
+ source_comment: ROOT.id,
+ item_context: { ...ROOT.item_context, threadState: 'resolved' },
+ }),
+ ])
+ await expectLogic(logic).toMatchValues({
+ pinMode: false,
+ pendingAnchor: null,
+ activeThreadId: 'saved-1',
+ writing: null,
+ })
+ })
+})
diff --git a/products/posthog_ai/frontend/scenes/TaskTracker/taskArtifactCommentsLogic.ts b/products/posthog_ai/frontend/scenes/TaskTracker/taskArtifactCommentsLogic.ts
new file mode 100644
index 000000000000..1d303a39f94d
--- /dev/null
+++ b/products/posthog_ai/frontend/scenes/TaskTracker/taskArtifactCommentsLogic.ts
@@ -0,0 +1,417 @@
+import { MakeLogicType, actions, afterMount, connect, kea, key, listeners, path, props, reducers, selectors } from 'kea'
+import { loaders } from 'kea-loaders'
+import posthog from 'posthog-js'
+
+import { lemonToast } from 'lib/lemon-ui/LemonToast/LemonToast'
+import { projectLogic } from 'scenes/projectLogic'
+
+import { commentsCreate, commentsList } from 'products/platform_features/frontend/generated/api'
+import type { CommentApi } from 'products/platform_features/frontend/generated/api.schemas'
+
+import {
+ ARTIFACT_COMMENT_SCOPE,
+ ArtifactCommentAnchor,
+ ArtifactCommentThread,
+ RegionCommentAnchor,
+ TextCommentAnchor,
+ anchorKindLabel,
+ buildArtifactCommentThreads,
+} from './artifactComments'
+import type { ArtifactPreviewKind } from './taskRunArtifacts'
+import { taskRunArtifactsLogic } from './taskRunArtifactsLogic'
+
+const COMMENTS_POLL_INTERVAL_MS = 10_000
+// The comments list pages at 100. This many pages covers any real artifact, the same cap as Desktop.
+const MAX_COMMENT_PAGES = 50
+
+export interface TaskArtifactCommentsLogicProps {
+ taskId: string
+ /** The artifact version id. Each version has its own threads, the same as in Desktop. */
+ artifactId: string
+ kind: ArtifactPreviewKind
+}
+
+/** What a draft or a write is for: a new comment on the whole file, the pending pin or selection, or a thread. */
+export type CommentTarget = 'document' | 'pending' | string
+
+/** Where the pending selection composer sits, in pixels inside the scroll content of the preview. */
+export interface PendingPosition {
+ left: number
+ top: number
+}
+
+async function loadAllArtifactComments(projectId: string, taskId: string, artifactId: string): Promise<CommentApi[]> {
+ const comments: CommentApi[] = []
+ let cursor: string | undefined
+ for (let index = 0; index < MAX_COMMENT_PAGES; index++) {
+ const page = await commentsList(projectId, {
+ scope: ARTIFACT_COMMENT_SCOPE,
+ item_id: artifactId,
+ task_id: taskId,
+ cursor,
+ })
+ comments.push(...page.results)
+ cursor = page.next
+ ? (new URL(page.next, window.location.origin).searchParams.get('cursor') ?? undefined)
+ : undefined
+ if (!cursor) {
+ break
+ }
+ }
+ return comments
+}
+
+// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
+export interface taskArtifactCommentsLogicValues {
+ currentProjectId: number | null // projectLogic
+ activeThreadId: string | null
+ anchoredThreads: ArtifactCommentThread[]
+ comments: CommentApi[] | null
+ commentsLoadFailed: boolean
+ commentsLoading: boolean
+ drafts: Record<CommentTarget, string>
+ openCount: number
+ pendingAnchor: RegionCommentAnchor | TextCommentAnchor | null
+ pendingPosition: PendingPosition | null
+ pinMode: boolean
+ resolvedCount: number
+ showResolved: boolean
+ threads: ArtifactCommentThread[] | null
+ visibleThreads: ArtifactCommentThread[] | null
+ writing: CommentTarget | null
+}
+
+// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
+export interface taskArtifactCommentsLogicActions {
+ setCommentsOpen: (open: boolean) => {
+ open: boolean
+ } // taskRunArtifactsLogic
+ activateThread: (id: string | null) => {
+ id: string | null
+ }
+ dismissPending: () => {
+ value: true
+ }
+ loadComments: () => any
+ loadCommentsFailure: (
+ error: string,
+ errorObject?: any
+ ) => {
+ error: string
+ errorObject?: any
+ }
+ loadCommentsSuccess: (
+ comments: CommentApi[] | null,
+ payload?: any
+ ) => {
+ comments: CommentApi[] | null
+ payload?: any
+ }
+ replyToThread: (rootId: string) => {
+ rootId: string
+ }
+ setDraft: (
+ target: CommentTarget,
+ draft: string
+ ) => {
+ draft: string
+ target: string
+ }
+ setPendingAnchor: (
+ anchor: RegionCommentAnchor | TextCommentAnchor,
+ position: PendingPosition | null
+ ) => {
+ anchor: RegionCommentAnchor | TextCommentAnchor
+ position: PendingPosition | null
+ }
+ setPinMode: (pinMode: boolean) => {
+ pinMode: boolean
+ }
+ setShowResolved: (showResolved: boolean) => {
+ showResolved: boolean
+ }
+ setThreadResolved: (
+ rootId: string,
+ resolved: boolean
+ ) => {
+ resolved: boolean
+ rootId: string
+ }
+ submitComment: (target: 'document' | 'pending') => {
+ target: 'document' | 'pending'
+ }
+ writeFinished: (target: CommentTarget | null) => {
+ target: string | null
+ }
+}
+
+// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
+export interface taskArtifactCommentsLogicMeta {
+ key: string
+ __keaTypeGenInternalSelectorTypes: {
+ threads: (comments: CommentApi[] | null) => ArtifactCommentThread[] | null
+ visibleThreads: (
+ threads: ArtifactCommentThread[] | null,
+ showResolved: boolean
+ ) => ArtifactCommentThread[] | null
+ openCount: (threads: ArtifactCommentThread[] | null) => number
+ resolvedCount: (threads: ArtifactCommentThread[] | null) => number
+ anchoredThreads: (
+ threads: ArtifactCommentThread[] | null,
+ activeThreadId: string | null
+ ) => ArtifactCommentThread[]
+ }
+}
+
+export type taskArtifactCommentsLogicType = MakeLogicType<
+ taskArtifactCommentsLogicValues,
+ taskArtifactCommentsLogicActions,
+ TaskArtifactCommentsLogicProps,
+ taskArtifactCommentsLogicMeta
+>
+
+/**
+ * Comment threads on one artifact version: comments on the whole file, pins on an image, and comments on a
+ * text selection. The rows are the ones PostHog Desktop reads and writes.
+ */
+export const taskArtifactCommentsLogic = kea<taskArtifactCommentsLogicType>([
+ props({} as TaskArtifactCommentsLogicProps),
+ key((props) => `${props.taskId}:${props.artifactId}`),
+ path((key) => ['products', 'posthog_ai', 'frontend', 'scenes', 'TaskTracker', 'taskArtifactCommentsLogic', key]),
+ connect((props: TaskArtifactCommentsLogicProps) => ({
+ values: [projectLogic, ['currentProjectId']],
+ actions: [taskRunArtifactsLogic({ taskId: props.taskId }), ['setCommentsOpen']],
+ })),
+ actions({
+ setDraft: (target: CommentTarget, draft: string) => ({ target, draft }),
+ setPinMode: (pinMode: boolean) => ({ pinMode }),
+ setPendingAnchor: (anchor: TextCommentAnchor | RegionCommentAnchor, position: PendingPosition | null) => ({
+ anchor,
+ position,
+ }),
+ dismissPending: true,
+ submitComment: (target: 'document' | 'pending') => ({ target }),
+ replyToThread: (rootId: string) => ({ rootId }),
+ setThreadResolved: (rootId: string, resolved: boolean) => ({ rootId, resolved }),
+ /** The write for `target` ended. `target` is null when it failed. */
+ writeFinished: (target: CommentTarget | null) => ({ target }),
+ activateThread: (id: string | null) => ({ id }),
+ setShowResolved: (showResolved: boolean) => ({ showResolved }),
+ }),
+ loaders(({ props, values }) => ({
+ comments: [
+ null as CommentApi[] | null,
+ {
+ loadComments: async () =>
+ values.currentProjectId === null
+ ? values.comments
+ : await loadAllArtifactComments(
+ String(values.currentProjectId),
+ props.taskId,
+ props.artifactId
+ ),
+ },
+ ],
+ })),
+ reducers({
+ // Unsent text stays when a write fails, so the person can send it again.
+ drafts: [
+ {} as Record<CommentTarget, string>,
+ {
+ setDraft: (state, { target, draft }) => ({ ...state, [target]: draft }),
+ dismissPending: ({ pending: _pending, ...rest }) => rest,
+ writeFinished: (state, { target }) => {
+ if (!target || !(target in state)) {
+ return state
+ }
+ const { [target]: _sent, ...rest } = state
+ return rest
+ },
+ },
+ ],
+ pinMode: [
+ false,
+ {
+ setPinMode: (_, { pinMode }) => pinMode,
+ writeFinished: (state, { target }) => (target === 'pending' ? false : state),
+ },
+ ],
+ pendingAnchor: [
+ null as TextCommentAnchor | RegionCommentAnchor | null,
+ {
+ setPendingAnchor: (_, { anchor }) => anchor,
+ dismissPending: () => null,
+ setPinMode: (state, { pinMode }) => (pinMode ? state : null),
+ writeFinished: (state, { target }) => (target === 'pending' ? null : state),
+ },
+ ],
+ pendingPosition: [
+ null as PendingPosition | null,
+ {
+ setPendingAnchor: (_, { position }) => position,
+ dismissPending: () => null,
+ writeFinished: (state, { target }) => (target === 'pending' ? null : state),
+ },
+ ],
+ // What is being written: "document", "pending", or a root id for a reply or a resolve.
+ writing: [
+ null as CommentTarget | null,
+ {
+ submitComment: (_, { target }) => target,
+ replyToThread: (_, { rootId }) => rootId,
+ setThreadResolved: (_, { rootId }) => rootId,
+ writeFinished: () => null,
+ },
+ ],
+ activeThreadId: [null as string | null, { activateThread: (_, { id }) => id }],
+ showResolved: [false, { setShowResolved: (_, { showResolved }) => showResolved }],
+ commentsLoadFailed: [false, { loadCommentsSuccess: () => false, loadCommentsFailure: () => true }],
+ }),
+ selectors({
+ threads: [
+ (s) => [s.comments],
+ (comments: CommentApi[] | null): ArtifactCommentThread[] | null =>
+ comments ? buildArtifactCommentThreads(comments) : null,
+ ],
+ /** Newest thread first. Resolved threads show only when asked for. */
+ visibleThreads: [
+ (s) => [s.threads, s.showResolved],
+ (threads: ArtifactCommentThread[] | null, showResolved: boolean): ArtifactCommentThread[] | null =>
+ threads ? threads.filter((thread) => showResolved || !thread.resolved).reverse() : null,
+ ],
+ openCount: [
+ (s) => [s.threads],
+ (threads: ArtifactCommentThread[] | null): number =>
+ threads?.filter((thread) => !thread.resolved).length ?? 0,
+ ],
+ resolvedCount: [
+ (s) => [s.threads],
+ (threads: ArtifactCommentThread[] | null): number =>
+ threads?.filter((thread) => thread.resolved).length ?? 0,
+ ],
+ /** Threads drawn on the preview: the open ones, and a resolved one while it is the active thread. */
+ anchoredThreads: [
+ (s) => [s.threads, s.activeThreadId],
+ (threads: ArtifactCommentThread[] | null, activeThreadId: string | null): ArtifactCommentThread[] =>
+ (threads ?? []).filter((thread) => !thread.resolved || thread.root.id === activeThreadId),
+ ],
+ }),
+ listeners(({ actions, values, props, cache }) => {
+ const schedulePoll = (): void => {
+ cache.disposables.add(() => {
+ const id = setTimeout(() => actions.loadComments(), COMMENTS_POLL_INTERVAL_MS)
+ return () => clearTimeout(id)
+ }, 'commentsPoll')
+ }
+ const write = async (target: CommentTarget, data: Partial<CommentApi>): Promise<CommentApi | null> => {
+ if (values.currentProjectId === null) {
+ actions.writeFinished(null)
+ return null
+ }
+ try {
+ const saved = await commentsCreate(String(values.currentProjectId), {
+ scope: ARTIFACT_COMMENT_SCOPE,
+ item_id: props.artifactId,
+ is_task: false,
+ mentions: [],
+ ...data,
+ })
+ actions.loadComments()
+ actions.writeFinished(target)
+ return saved
+ } catch {
+ lemonToast.error("Couldn't save the comment. Try again in a moment.")
+ actions.writeFinished(null)
+ return null
+ }
+ }
+ return {
+ setPinMode: ({ pinMode }) => {
+ if (pinMode) {
+ actions.setCommentsOpen(true)
+ }
+ },
+ setPendingAnchor: ({ anchor }) => {
+ // pinned: analytics event name and properties. Renaming them breaks insights.
+ posthog.capture('task artifact comment started', {
+ anchor_kind: anchorKindLabel(anchor),
+ kind: props.kind,
+ })
+ },
+ submitComment: async ({ target }) => {
+ const content = (values.drafts[target] ?? '').trim()
+ const anchor: ArtifactCommentAnchor | null =
+ target === 'document' ? { kind: 'document' } : values.pendingAnchor
+ if (!content || !anchor) {
+ actions.writeFinished(null)
+ return
+ }
+ // The server cannot find the task from an artifact id, so the task rides along in the context.
+ const saved = await write(target, { content, item_context: { anchor, taskId: props.taskId } })
+ if (saved) {
+ // pinned: analytics event name and properties. Renaming them breaks insights.
+ posthog.capture('task artifact comment added', {
+ anchor_kind: anchorKindLabel(anchor),
+ kind: props.kind,
+ })
+ if (target === 'pending') {
+ window.getSelection()?.removeAllRanges()
+ }
+ actions.setCommentsOpen(true)
+ actions.activateThread(saved.id)
+ }
+ },
+ replyToThread: async ({ rootId }) => {
+ const content = (values.drafts[rootId] ?? '').trim()
+ if (!content) {
+ actions.writeFinished(null)
+ return
+ }
+ const saved = await write(rootId, {
+ content,
+ source_comment: rootId,
+ item_context: { taskId: props.taskId },
+ })
+ if (saved) {
+ // pinned: analytics event name and properties. Renaming them breaks insights.
+ posthog.capture('task artifact comment replied', { kind: props.kind })
+ }
+ },
+ setThreadResolved: async ({ rootId, resolved }) => {
+ const thread = values.threads?.find((candidate) => candidate.root.id === rootId)
+ if (!thread) {
+ actions.writeFinished(null)
+ return
+ }
+ const rootContext =
+ thread.root.item_context && typeof thread.root.item_context === 'object'
+ ? (thread.root.item_context as Record<string, unknown>)
+ : {}
+ // Resolution is a reply that carries the thread state, the same write that Desktop makes.
+ const saved = await write(rootId, {
+ content: resolved ? 'Resolved this thread' : 'Reopened this thread',
+ source_comment: rootId,
+ item_context: { ...rootContext, taskId: props.taskId, threadState: resolved ? 'resolved' : 'open' },
+ })
+ if (saved) {
+ // pinned: analytics event name and properties. Renaming them breaks insights.
+ posthog.capture('task artifact comment resolved', {
+ resolved,
+ anchor_kind: anchorKindLabel(thread.anchor),
+ kind: props.kind,
+ })
+ }
+ },
+ activateThread: ({ id }) => {
+ if (id) {
+ actions.setCommentsOpen(true)
+ }
+ },
+ loadCommentsSuccess: () => schedulePoll(),
+ loadCommentsFailure: () => schedulePoll(),
+ }
+ }),
+ afterMount(({ actions }) => {
+ actions.loadComments()
+ }),
+])
diff --git a/products/posthog_ai/frontend/scenes/TaskTracker/taskRunArtifactsLogic.ts b/products/posthog_ai/frontend/scenes/TaskTracker/taskRunArtifactsLogic.ts
index b7183dabc528..d37a275df05b 100644
--- a/products/posthog_ai/frontend/scenes/TaskTracker/taskRunArtifactsLogic.ts
+++ b/products/posthog_ai/frontend/scenes/TaskTracker/taskRunArtifactsLogic.ts
@@ -82,6 +82,7 @@ export interface taskRunArtifactsLogicValues {
artifacts: RunArtifact[]
chainRuns: TaskRunDetailDTOApi[]
chainRunsLoading: boolean
+ commentsOpen: boolean
files: ArtifactFile[]
livingArtifacts: TaskRunLivingArtifactResponseApi[]
livingArtifactsLoading: boolean
@@ -202,6 +203,9 @@ export interface taskRunArtifactsLogicActions {
setActiveTab: (tab: TaskRunTab) => {
tab: TaskRunTab
}
+ setCommentsOpen: (open: boolean) => {
+ open: boolean
+ }
stepArtifact: (delta: number) => {
delta: number
}
@@ -287,6 +291,7 @@ export const taskRunArtifactsLogic = kea<taskRunArtifactsLogicType>([
openFromUrl: (fileKey: string, versionId: string | null) => ({ fileKey, versionId }),
reportLinkCopied: true,
reportObjectOpened: (objectKind: string) => ({ objectKind }),
+ setCommentsOpen: (open: boolean) => ({ open }),
}),
loaders(({ props, values }) => ({
chainRuns: [
@@ -396,6 +401,8 @@ export const taskRunArtifactsLogic = kea<taskRunArtifactsLogicType>([
'conversation' as TaskRunTab,
{ setActiveTab: (_, { tab }) => tab, openFromUrl: () => 'artifacts' },
],
+ // The panel stays open across files, so a reviewer can read the comments on each one in turn.
+ commentsOpen: [false, { setCommentsOpen: (_, { open }) => open }],
selectedFileKey: [
null as string | null,
{ selectArtifact: (_, { fileKey }) => fileKey, openFromUrl: (_, { fileKey }) => fileKey },
@@ -593,6 +600,12 @@ export const taskRunArtifactsLogic = kea<taskRunArtifactsLogicType>([
is_latest_version: values.selectedVersionIndex === 0,
})
},
+ setCommentsOpen: ({ open }) => {
+ if (open) {
+ // pinned: analytics event name and properties. Renaming them breaks insights.
+ posthog.capture('task artifact comments opened', { kind: values.selectedKind })
+ }
+ },
openFromUrl: ({ versionId }) => {
// pinned: analytics event name and properties. Renaming them breaks insights.
posthog.capture('task artifact link opened', { has_version: !!versionId })