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.

17.4 KB
Raw Blame
import { MakeLogicType, actions, afterMount, connect, kea, key, listeners, path, props, reducers, selectors } from 'kea'
import { loaders } from 'kea-loaders'

import { toast } from '@posthog/quill'

import api from 'lib/api'
import { FEATURE_FLAGS } from 'lib/constants'
import { FeatureFlagsSet, featureFlagLogic } from 'lib/logic/featureFlagLogic'

import type { CommentType } from '~/types'

import { captureCanvasAction } from '../../canvasAnalytics'
import type { CanvasApi, CanvasVersionApi } from '../../generated/api.schemas'
import { canvasHistoryLogic } from '../../history/canvasHistoryLogic'
import type { CanvasCommentHighlight, CanvasRect, CanvasTextSelection } from '../../host/canvasProtocol'
import { canvasSceneLogic } from '../../scene/canvasSceneLogic'
import { canvasCommentTaskId } from '../chat/canvasChatTask'
import {
    CANVAS_COMMENT_SCOPE,
    CanvasCommentThread,
    buildCanvasCommentThreads,
    canvasCommentHighlights,
    canvasTextAnchor,
} from './canvasCommentThreads'

const COMMENTS_POLL_INTERVAL_MS = 10_000
// The comments list pages at 100. This many pages covers any real canvas.
const MAX_COMMENT_PAGES = 10

export interface CanvasCommentsLogicProps {
    id: string
}

export type CanvasThreadSource = 'highlight' | 'menu' | 'created'

async function loadAllCanvasComments(canvasId: string): Promise<CommentType[]> {
    // The comments API has no generated client this product can import, so this goes through lib/api.
    const comments: CommentType[] = []
    let page = await api.comments.list({ scope: CANVAS_COMMENT_SCOPE, item_id: canvasId })
    for (let index = 0; index < MAX_COMMENT_PAGES; index++) {
        comments.push(...page.results)
        if (!page.next || index === MAX_COMMENT_PAGES - 1) {
            break
        }
        // nosemgrep: prefer-codegen-api -- The server supplies this pagination URL.
        page = await api.get(page.next)
    }
    return comments
}

// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface canvasCommentsLogicValues {
    displayedVersionId: string | null // canvasHistoryLogic
    versions: CanvasVersionApi[] // canvasHistoryLogic
    canvas: CanvasApi | null // canvasSceneLogic
    featureFlags: FeatureFlagsSet // featureFlagLogic
    activeThreadId: string | null
    activeThreadRect: CanvasRect | null
    clearTextSelectionKey: number
    commentTaskId: string | null
    comments: CommentType[] | null
    commentsEnabled: boolean
    commentsLoadFailed: boolean
    commentsLoading: boolean
    composing: boolean
    highlights: CanvasCommentHighlight[]
    replyDrafts: Record<string, string>
    resolvedCount: number
    selectionDraft: string
    showResolved: boolean
    textSelection: CanvasTextSelection | null
    threads: CanvasCommentThread[] | null
    visibleThreads: CanvasCommentThread[] | null
    writing: string | null
}

// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface canvasCommentsLogicActions {
    activateThread: (
        id: string,
        rect: CanvasRect | null,
        source: CanvasThreadSource
    ) => {
        id: string
        rect: {
            bottom: number
            left: number
            right: number
            top: number
        } | null
        source: CanvasThreadSource
    }
    createComment: () => {
        value: true
    }
    dismissTextSelection: () => {
        value: true
    }
    loadComments: () => any
    loadCommentsFailure: (
        error: string,
        errorObject?: any
    ) => {
        error: string
        errorObject?: any
    }
    loadCommentsSuccess: (
        comments: CommentType[] | null,
        payload?: any
    ) => {
        comments: CommentType[] | null
        payload?: any
    }
    openSelectionComposer: () => {
        value: true
    }
    replyToThread: (rootId: string) => {
        rootId: string
    }
    setActiveThread: (id: string | null) => {
        id: string | null
    }
    setReplyDraft: (
        rootId: string,
        draft: string
    ) => {
        draft: string
        rootId: string
    }
    setSelectionDraft: (draft: string) => {
        draft: string
    }
    setShowResolved: (showResolved: boolean) => {
        showResolved: boolean
    }
    setTextSelection: (selection: CanvasTextSelection | null) => {
        selection: {
            end: number
            prefix: string
            quote: string
            rect: {
                bottom: number
                left: number
                right: number
                top: number
            }
            start: number
            suffix: string
        } | null
    }
    setThreadResolved: (
        rootId: string,
        resolved: boolean
    ) => {
        resolved: boolean
        rootId: string
    }
    writeFinished: (target: string | null) => {
        target: string | null
    }
}

// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface canvasCommentsLogicMeta {
    key: string
    __keaTypeGenInternalSelectorTypes: {
        commentTaskId: (canvas: CanvasApi | null, versions: CanvasVersionApi[]) => string | null
        commentsEnabled: (featureFlags: FeatureFlagsSet, commentTaskId: string | null) => boolean
        threads: (comments: CommentType[] | null) => CanvasCommentThread[] | null
        visibleThreads: (threads: CanvasCommentThread[] | null, showResolved: boolean) => CanvasCommentThread[] | null
        resolvedCount: (threads: CanvasCommentThread[] | null) => number
        highlights: (
            threads: CanvasCommentThread[] | null,
            displayedVersionId: string | null,
            activeThreadId: string | null,
            commentsEnabled: boolean
        ) => CanvasCommentHighlight[]
    }
}

export type canvasCommentsLogicType = MakeLogicType<
    canvasCommentsLogicValues,
    canvasCommentsLogicActions,
    CanvasCommentsLogicProps,
    canvasCommentsLogicMeta
>

/**
 * Comment threads on a canvas: the thread open over the canvas, the comments menu, commenting on a text
 * selection in the frame, and the highlights the frame draws for each open thread.
 */
export const canvasCommentsLogic = kea<canvasCommentsLogicType>([
    props({} as CanvasCommentsLogicProps),
    key((props) => props.id),
    path((key) => ['products', 'canvas', 'frontend', 'sidePanel', 'comments', 'canvasCommentsLogic', key]),
    connect((props: CanvasCommentsLogicProps) => ({
        values: [
            canvasSceneLogic({ id: props.id }),
            ['canvas'],
            canvasHistoryLogic({ id: props.id }),
            ['displayedVersionId', 'versions'],
            featureFlagLogic,
            ['featureFlags'],
        ],
    })),
    actions({
        openSelectionComposer: true,
        setTextSelection: (selection: CanvasTextSelection | null) => ({ selection }),
        dismissTextSelection: true,
        setActiveThread: (id: string | null) => ({ id }),
        activateThread: (id: string, rect: CanvasRect | null, source: CanvasThreadSource) => ({ id, rect, source }),
        setShowResolved: (showResolved: boolean) => ({ showResolved }),
        createComment: true,
        replyToThread: (rootId: string) => ({ rootId }),
        setThreadResolved: (rootId: string, resolved: boolean) => ({ rootId, resolved }),
        /** The write for `target` ended: a root id or "selection" when it saved, null when it failed. */
        writeFinished: (target: string | null) => ({ target }),
        setReplyDraft: (rootId: string, draft: string) => ({ rootId, draft }),
        setSelectionDraft: (draft: string) => ({ draft }),
    }),
    loaders(({ props, values }) => ({
        comments: [
            null as CommentType[] | null,
            {
                // The poll keeps running while comments are off, so they appear once the canvas gets a task.
                loadComments: async () =>
                    values.commentsEnabled ? await loadAllCanvasComments(props.id) : values.comments,
            },
        ],
    })),
    reducers({
        composing: [
            false,
            {
                openSelectionComposer: () => true,
                setTextSelection: () => false,
                dismissTextSelection: () => false,
                writeFinished: (state, { target }) => (target === 'selection' ? false : state),
            },
        ],
        textSelection: [
            null as CanvasTextSelection | null,
            {
                setTextSelection: (_, { selection }) => selection,
                dismissTextSelection: () => null,
                writeFinished: (state, { target }) => (target === 'selection' ? null : state),
            },
        ],
        // Bumped to tell the frame to drop its native selection.
        clearTextSelectionKey: [
            0,
            {
                dismissTextSelection: (state) => state + 1,
                writeFinished: (state, { target }) => (target === 'selection' ? state + 1 : state),
            },
        ],
        activeThreadId: [
            null as string | null,
            {
                setActiveThread: (_, { id }) => id,
                activateThread: (_, { id }) => id,
            },
        ],
        activeThreadRect: [
            null as CanvasRect | null,
            {
                setActiveThread: () => null,
                activateThread: (_, { rect }) => rect,
            },
        ],
        // Unsent text stays when a write fails, so the viewer can send it again.
        replyDrafts: [
            {} as Record<string, string>,
            {
                setReplyDraft: (state, { rootId, draft }) => ({ ...state, [rootId]: draft }),
                writeFinished: (state, { target }) => {
                    if (!target || !(target in state)) {
                        return state
                    }
                    const { [target]: _sent, ...rest } = state
                    return rest
                },
            },
        ],
        selectionDraft: [
            '',
            {
                setSelectionDraft: (_, { draft }) => draft,
                setTextSelection: () => '',
                dismissTextSelection: () => '',
                writeFinished: (state, { target }) => (target === 'selection' ? '' : state),
            },
        ],
        commentsLoadFailed: [
            false,
            {
                loadCommentsSuccess: () => false,
                loadCommentsFailure: () => true,
            },
        ],
        showResolved: [
            false,
            {
                setShowResolved: (_, { showResolved }) => showResolved,
            },
        ],
        // What is being written: "selection" for a new comment, a root id for a reply or resolve.
        writing: [
            null as string | null,
            {
                createComment: () => 'selection',
                replyToThread: (_, { rootId }) => rootId,
                setThreadResolved: (_, { rootId }) => rootId,
                writeFinished: () => null,
            },
        ],
    }),
    selectors({
        commentTaskId: [
            (s) => [s.canvas, s.versions],
            (canvas: CanvasApi | null, versions: CanvasVersionApi[]): string | null =>
                canvasCommentTaskId(
                    canvas?.generation_task_id,
                    versions.map((version) => ({ taskId: version.task_id }))
                ),
        ],
        // Like PostHog Desktop: the flag turns comments on, and a canvas an agent wrote always has them.
        commentsEnabled: [
            (s) => [s.featureFlags, s.commentTaskId],
            (featureFlags: FeatureFlagsSet, commentTaskId: string | null): boolean =>
                !!featureFlags[FEATURE_FLAGS.CANVAS_COMMENTS] || !!commentTaskId,
        ],
        threads: [
            (s) => [s.comments],
            (comments: CommentType[] | null): CanvasCommentThread[] | null =>
                comments ? buildCanvasCommentThreads(comments) : null,
        ],
        /** Newest thread first, resolved ones only when asked for. */
        visibleThreads: [
            (s) => [s.threads, s.showResolved],
            (threads: CanvasCommentThread[] | null, showResolved: boolean): CanvasCommentThread[] | null =>
                threads ? threads.filter((thread) => showResolved || !thread.resolved).reverse() : null,
        ],
        resolvedCount: [
            (s) => [s.threads],
            (threads: CanvasCommentThread[] | null): number => threads?.filter((thread) => thread.resolved).length ?? 0,
        ],
        highlights: [
            (s) => [s.threads, s.displayedVersionId, s.activeThreadId, s.commentsEnabled],
            (
                threads: CanvasCommentThread[] | null,
                displayedVersionId: string | null,
                activeThreadId: string | null,
                commentsEnabled: boolean
            ): CanvasCommentHighlight[] =>
                commentsEnabled && threads ? canvasCommentHighlights(threads, displayedVersionId, activeThreadId) : [],
        ],
    }),
    listeners(({ actions, values, props, cache }) => {
        const commentContext = (extra: Record<string, unknown>): Record<string, unknown> => ({
            ...extra,
            // The comment API cannot resolve a canvas back to its task, so the task rides along.
            ...(values.commentTaskId ? { taskId: values.commentTaskId } : {}),
        })
        const schedulePoll = (): void => {
            cache.disposables.add(() => {
                const id = setTimeout(() => actions.loadComments(), COMMENTS_POLL_INTERVAL_MS)
                return () => clearTimeout(id)
            }, 'commentsPoll')
        }
        const track = (actionType: 'comment_create' | 'comment_reply' | 'comment_resolve', success: boolean): void =>
            captureCanvasAction(actionType, {
                dashboard_id: props.id,
                channel_id: values.canvas?.channel,
                surface: 'web_canvas_scene',
                success,
            })
        const write = async (
            target: string,
            actionType: 'comment_create' | 'comment_reply' | 'comment_resolve',
            data: Partial<CommentType>
        ): Promise<CommentType | null> => {
            try {
                const saved = await api.comments.create({
                    scope: CANVAS_COMMENT_SCOPE,
                    item_id: props.id,
                    is_task: false,
                    ...data,
                })
                track(actionType, true)
                actions.loadComments()
                actions.writeFinished(target)
                return saved
            } catch (error) {
                track(actionType, false)
                toast.error({
                    title: "Couldn't save the comment",
                    description: error instanceof Error ? error.message : 'Try again in a moment.',
                })
                actions.writeFinished(null)
                return null
            }
        }
        return {
            activateThread: ({ source }) => {
                if (source !== 'created') {
                    captureCanvasAction('comment_open', {
                        dashboard_id: props.id,
                        channel_id: values.canvas?.channel,
                        surface: 'web_canvas_scene',
                        source,
                    })
                }
            },
            createComment: async () => {
                const content = values.selectionDraft
                const selection = values.textSelection
                if (!selection || !content.trim()) {
                    actions.writeFinished(null)
                    return
                }
                const saved = await write('selection', 'comment_create', {
                    content: content.trim(),
                    item_context: commentContext({
                        anchor: canvasTextAnchor(selection),
                        ...(values.displayedVersionId ? { canvasVersionId: values.displayedVersionId } : {}),
                    }),
                })
                if (saved) {
                    actions.activateThread(saved.id, selection.rect, 'created')
                }
            },
            replyToThread: async ({ rootId }) => {
                const content = values.replyDrafts[rootId] ?? ''
                if (!content.trim()) {
                    actions.writeFinished(null)
                    return
                }
                await write(rootId, 'comment_reply', {
                    content: content.trim(),
                    source_comment: rootId,
                    item_context: commentContext({}),
                })
            },
            setThreadResolved: async ({ rootId, resolved }) => {
                const thread = values.threads?.find((candidate) => candidate.root.id === rootId)
                if (!thread) {
                    actions.writeFinished(null)
                    return
                }
                // Resolution is a reply that carries the thread state, the same write path Desktop uses.
                await write(rootId, 'comment_resolve', {
                    content: resolved ? 'Resolved this thread' : 'Reopened this thread',
                    source_comment: rootId,
                    item_context: {
                        ...thread.root.item_context,
                        ...commentContext({ threadState: resolved ? 'resolved' : 'open' }),
                    },
                })
            },
            loadCommentsSuccess: () => schedulePoll(),
            loadCommentsFailure: () => schedulePoll(),
        }
    }),
    afterMount(({ actions }) => {
        actions.loadComments()
    }),
])