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.

13.9 KB
Raw Blame
import { MakeLogicType, actions, kea, path, reducers, selectors } from 'kea'

import { type AttachedContextItem, NEW_CHAT_KEY, attachedContextItemKey } from '~/layout/ai/attachedContext'
import { type ChatChipsByTask, addChatChips, removeChatChip, withRemovedGroup } from '~/layout/ai/chatContextChips'

function withoutPicks(
    pickedByChat: Record<string, AttachedContextItem[]>,
    chat: string,
    keys: Set<string>
): Record<string, AttachedContextItem[]> {
    const picks = pickedByChat[chat]
    return picks
        ? { ...pickedByChat, [chat]: picks.filter((item) => !keys.has(attachedContextItemKey(item))) }
        : pickedByChat
}

// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface attachedContextLogicValues {
    chatChipsByTask: ChatChipsByTask
    contextItems: AttachedContextItem[]
    dismissedGroups: Record<string, true>
    dismissedKeys: Record<string, true>
    hasContext: boolean
    pickedByChat: Record<string, AttachedContextItem[]>
    providers: Record<string, AttachedContextItem[]>
    removedGroupsByTask: Record<string, string[]>
    seenContextLinesByTask: Record<string, string[]>
    sentContextKeysByTask: Record<string, string[]>
}

// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface attachedContextLogicActions {
    contextDelivered: (
        taskId: string,
        items: AttachedContextItem[],
        fromNewChat?: boolean
    ) => {
        fromNewChat: boolean
        items: AttachedContextItem[]
        taskId: string
    }
    deregisterContext: (providerId: string) => {
        providerId: string
    }
    dismissContext: (
        key: string,
        dismissGroup?: string
    ) => {
        dismissGroup: string | undefined
        key: string
    }
    markContextLinesSeen: (
        taskId: string,
        lines: string[]
    ) => {
        lines: string[]
        taskId: string
    }
    pickItem: (
        item: AttachedContextItem,
        taskId?: string
    ) => {
        item: AttachedContextItem
        taskId: string
    }
    registerContext: (
        providerId: string,
        items: AttachedContextItem[]
    ) => {
        items: AttachedContextItem[]
        providerId: string
    }
    removeChatChip: (
        taskId: string,
        chipId: string,
        dismissGroup?: string
    ) => {
        chipId: string
        dismissGroup: string | undefined
        taskId: string
    }
    removePickedItem: (
        key: string,
        taskId?: string
    ) => {
        key: string
        taskId: string
    }
    undismissContext: (
        key: string,
        dismissGroup?: string
    ) => {
        dismissGroup: string | undefined
        key: string
    }
}

// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface attachedContextLogicMeta {
    __keaTypeGenInternalSelectorTypes: {
        contextItems: (
            providers: Record<string, AttachedContextItem[]>,
            dismissedKeys: Record<string, true>,
            dismissedGroups: Record<string, true>
        ) => AttachedContextItem[]
        hasContext: (contextItems: AttachedContextItem[]) => boolean
    }
}

export type attachedContextLogicType = MakeLogicType<
    attachedContextLogicValues,
    attachedContextLogicActions,
    Record<string, any>,
    attachedContextLogicMeta
>

/**
 * Global, unkeyed store of attached context for the PostHog AI surface. One mechanism only — a
 * registry of context providers, so registration and removal are symmetric and trivial. Each
 * provider (a mounted hook/component, or a future @-mention picker) owns a stable `providerId` and
 * upserts its items; `contextItems` flattens and dedupes across providers.
 *
 * A consumer reads `contextItems` at send time and wraps the outgoing message with the
 * trusted/untrusted context blocks (`utils/posthogContextBlock`). The registry is not keyed by
 * conversation: the on-screen context is global to the app at any instant, and it only decides what a
 * new chat starts with.
 *
 * `chatChipsByTask` holds the chips of what each chat received, without the payloads, so a started chat
 * keeps its chips when the user navigates away. `chatContextLogic` owns how a chat combines these stores.
 *
 * This store also keeps the sent-context bookkeeping, two layers keyed by task id (task-scoped, not
 * run-scoped, so the dedupe survives a terminal-run send re-pointing the consumer to a fresh run):
 *
 * - `sentContextKeysByTask` — which non-text refs the send paths already wrapped into a message this
 *   session, marked right after a successful send. Covers the send→echo in-flight window, but is
 *   in-memory only: a reload, another tab, or a teammate's browser starts empty.
 * - `seenContextLinesByTask` — the durable layer: rendered block lines reconstructed from the run
 *   log itself. `runStreamLogic` records the lines of every context block found in a persisted or
 *   echoed user message (the `logs/` snapshot replays the task's full resume chain), and the send
 *   paths prune any item whose `contextItemLine` is already recorded. This mirrors the backend's
 *   `_collect_seen_entity_refs`/`prune_repeated_entity_refs`, which dedupe from persisted logs
 *   across a task's whole resume chain.
 */
export const attachedContextLogic = kea<attachedContextLogicType>([
    path(['layout', 'ai', 'attachedContextLogic']),

    actions({
        /** Idempotent upsert — re-register the same `providerId` to update its items. */
        registerContext: (providerId: string, items: AttachedContextItem[]) => ({ providerId, items }),
        deregisterContext: (providerId: string) => ({ providerId }),
        /**
         * A send delivered `items` to the chat: record them for dedupe, and save the visible ones as its chips.
         * `fromNewChat` says the new chat composer sent them, so its draft picks are the ones delivered.
         */
        contextDelivered: (taskId: string, items: AttachedContextItem[], fromNewChat: boolean = false) => ({
            taskId,
            items,
            fromNewChat,
        }),
        /** Record rendered context-block lines observed in `taskId`'s run log (see `seenContextLinesByTask`). */
        markContextLinesSeen: (taskId: string, lines: string[]) => ({ taskId, lines }),
        /**
         * Hide one item (by `attachedContextItemKey`) regardless of which provider contributed it —
         * the user closing a chip must stick even when the provider re-registers the same item
         * (e.g. the scene bridge upserting on every scene read). Passing the item's `dismissGroup`
         * also hides every item sharing that group, including future re-registrations whose value
         * (and therefore key) differs, which is how a chip detaches the hidden payload it stands for.
         */
        dismissContext: (key: string, dismissGroup?: string) => ({ key, dismissGroup }),
        undismissContext: (key: string, dismissGroup?: string) => ({ key, dismissGroup }),
        removeChatChip: (taskId: string, chipId: string, dismissGroup?: string) => ({ taskId, chipId, dismissGroup }),
        pickItem: (item: AttachedContextItem, taskId: string = NEW_CHAT_KEY) => ({ item, taskId }),
        removePickedItem: (key: string, taskId: string = NEW_CHAT_KEY) => ({ key, taskId }),
    }),

    reducers({
        providers: [
            {} as Record<string, AttachedContextItem[]>,
            {
                registerContext: (state, { providerId, items }) => ({ ...state, [providerId]: items }),
                deregisterContext: (state, { providerId }) => {
                    if (!(providerId in state)) {
                        return state
                    }
                    const { [providerId]: _dropped, ...rest } = state
                    return rest
                },
            },
        ],
        // Per-task set of `attachedContextItemKey`s already wrapped into a sent message. Append-only for
        // the session: entity refs sent once anywhere in a task's resume chain stay pruned from later sends.
        sentContextKeysByTask: [
            {} as Record<string, string[]>,
            {
                contextDelivered: (state, { taskId, items }) => {
                    const keys = items.filter((item) => item.type !== 'text').map(attachedContextItemKey)
                    if (keys.length === 0) {
                        return state
                    }
                    const existing = state[taskId] ?? []
                    const added = keys.filter((key) => !existing.includes(key))
                    if (added.length === 0) {
                        return state
                    }
                    return { ...state, [taskId]: [...existing, ...added] }
                },
            },
        ],
        pickedByChat: [
            {} as Record<string, AttachedContextItem[]>,
            {
                pickItem: (state, { item, taskId }) => {
                    const key = attachedContextItemKey(item)
                    const others = (state[taskId] ?? []).filter((existing) => attachedContextItemKey(existing) !== key)
                    return { ...state, [taskId]: [...others, item] }
                },
                removePickedItem: (state, { key, taskId }) => withoutPicks(state, taskId, new Set([key])),
                contextDelivered: (state, { taskId, items, fromNewChat }) =>
                    withoutPicks(
                        state,
                        fromNewChat ? NEW_CHAT_KEY : taskId,
                        new Set(items.map(attachedContextItemKey))
                    ),
            },
        ],
        chatChipsByTask: [
            {} as ChatChipsByTask,
            { persist: true },
            {
                contextDelivered: (state, { taskId, items }) => (taskId ? addChatChips(state, taskId, items) : state),
                removeChatChip: (state, { taskId, chipId, dismissGroup }) =>
                    removeChatChip(state, taskId, chipId, dismissGroup),
            },
        ],
        // Persisted with the chips, because a reload must not resume sending a hidden payload the user removed.
        removedGroupsByTask: [
            {} as Record<string, string[]>,
            { persist: true },
            {
                removeChatChip: (state, { taskId, dismissGroup }) => withRemovedGroup(state, taskId, dismissGroup),
            },
        ],
        // Per-task set of rendered context-block lines observed in the task's run log (replay or live
        // echo). The durable dedupe layer: unlike `sentContextKeysByTask` it is reconstructed from the
        // persisted resume-chain history on every open, so it survives reloads and other sessions.
        seenContextLinesByTask: [
            {} as Record<string, string[]>,
            {
                markContextLinesSeen: (state, { taskId, lines }) => {
                    if (lines.length === 0) {
                        return state
                    }
                    const existing = state[taskId] ?? []
                    const added = lines.filter((line) => !existing.includes(line))
                    if (added.length === 0) {
                        return state
                    }
                    return { ...state, [taskId]: [...existing, ...added] }
                },
            },
        ],
        dismissedKeys: [
            {} as Record<string, true>,
            {
                dismissContext: (state, { key }) => ({ ...state, [key]: true as const }),
                undismissContext: (state, { key }) => {
                    if (!(key in state)) {
                        return state
                    }
                    const { [key]: _dropped, ...rest } = state
                    return rest
                },
            },
        ],
        dismissedGroups: [
            {} as Record<string, true>,
            {
                dismissContext: (state, { dismissGroup }) =>
                    dismissGroup ? { ...state, [dismissGroup]: true as const } : state,
                undismissContext: (state, { dismissGroup }) => {
                    if (!dismissGroup || !(dismissGroup in state)) {
                        return state
                    }
                    const { [dismissGroup]: _dropped, ...rest } = state
                    return rest
                },
            },
        ],
    }),

    selectors({
        // Flattened across providers, deduped by `${type}:${key ?? value}` (first writer wins).
        // Items with neither `key` nor `value` carry no payload and are dropped, as are dismissed
        // keys and members of dismissed groups.
        contextItems: [
            (s) => [s.providers, s.dismissedKeys, s.dismissedGroups],
            (
                providers: Record<string, AttachedContextItem[]>,
                dismissedKeys: Record<string, true>,
                dismissedGroups: Record<string, true>
            ): AttachedContextItem[] => {
                const seen = new Set<string>()
                const out: AttachedContextItem[] = []
                for (const items of Object.values(providers)) {
                    for (const item of items) {
                        const hasKey = item.key !== undefined && item.key !== null && item.key !== ''
                        const hasValue = item.value !== undefined && item.value !== ''
                        if (!hasKey && !hasValue) {
                            continue
                        }
                        if (item.dismissGroup && dismissedGroups[item.dismissGroup]) {
                            continue
                        }
                        const key = attachedContextItemKey(item)
                        if (seen.has(key) || dismissedKeys[key]) {
                            continue
                        }
                        seen.add(key)
                        out.push(item)
                    }
                }
                return out
            },
        ],
        hasContext: [
            (s) => [s.contextItems],
            (contextItems: AttachedContextItem[]): boolean => contextItems.length > 0,
        ],
    }),
])