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.

6.3 KB
Raw Blame
import { MakeLogicType, actions, kea, key, listeners, path, props, reducers, selectors } from 'kea'

import { lemonToast } from '@posthog/lemon-ui'

import { uuid } from 'lib/utils/dom'

import { MAX_ATTACHMENTS_PER_MESSAGE, type PendingAttachment, attachmentRejectionReason } from '../utils/attachments'

export interface ComposerAttachmentsLogicProps {
    /** Must match the key its send path connects under, or the send uploads nothing. */
    attachmentsKey: string
}

// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface composerAttachmentsLogicValues {
    attachedFiles: File[]
    attachments: PendingAttachment[]
    hasAttachments: boolean
    isAtAttachmentLimit: boolean
    queuedAttachments: PendingAttachment[]
    stagedAttachments: PendingAttachment[]
    uploading: boolean
}

// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface composerAttachmentsLogicActions {
    addFiles: (files: File[]) => {
        files: File[]
    }
    claimAttachmentsForQueue: () => {
        value: true
    }
    releaseQueuedAttachments: () => {
        value: true
    }
    removeAttachment: (id: string) => {
        id: string
    }
    removeAttachments: (ids: string[]) => {
        ids: string[]
    }
    setUploading: (uploading: boolean) => {
        uploading: boolean
    }
}

// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface composerAttachmentsLogicMeta {
    key: string
    __keaTypeGenInternalSelectorTypes: {
        stagedAttachments: (attachments: PendingAttachment[]) => PendingAttachment[]
        queuedAttachments: (attachments: PendingAttachment[]) => PendingAttachment[]
        attachedFiles: (stagedAttachments: PendingAttachment[]) => File[]
        hasAttachments: (stagedAttachments: PendingAttachment[]) => boolean
        isAtAttachmentLimit: (attachments: PendingAttachment[]) => boolean
    }
}

export type composerAttachmentsLogicType = MakeLogicType<
    composerAttachmentsLogicValues,
    composerAttachmentsLogicActions,
    ComposerAttachmentsLogicProps,
    composerAttachmentsLogicMeta
>

/**
 * Files staged in one composer, held as `File` handles until a send uploads them.
 *
 * Uploading on send rather than on add is what lets the creation composer take files at all: it has no task
 * to upload against until it submits.
 *
 * A send owns exactly the files it took, by id. Clearing the whole list would destroy a file attached while
 * that send was in flight, and let a queue drain carry off the next draft's.
 */
export const composerAttachmentsLogic = kea<composerAttachmentsLogicType>([
    path(['products', 'posthog_ai', 'frontend', 'logics', 'composerAttachmentsLogic']),
    props({} as ComposerAttachmentsLogicProps),
    key((props) => props.attachmentsKey),

    actions({
        addFiles: (files: File[]) => ({ files }),
        removeAttachment: (id: string) => ({ id }),
        removeAttachments: (ids: string[]) => ({ ids }),
        /** The staged files follow the text into the queue, so they arrive with the message they were typed for. */
        claimAttachmentsForQueue: true,
        /** A queue that empties without sending hands its files back rather than dropping them. */
        releaseQueuedAttachments: true,
        setUploading: (uploading: boolean) => ({ uploading }),
    }),

    reducers({
        attachments: [
            [] as PendingAttachment[],
            {
                addFiles: (state, { files }) => {
                    const accepted = acceptableFiles(files).slice(0, remainingSlots(state))
                    return accepted.length > 0 ? [...state, ...accepted.map((file) => ({ id: uuid(), file }))] : state
                },
                removeAttachment: (state, { id }) => state.filter((attachment) => attachment.id !== id),
                removeAttachments: (state, { ids }) => state.filter((attachment) => !ids.includes(attachment.id)),
                claimAttachmentsForQueue: (state) => state.map((attachment) => ({ ...attachment, queued: true })),
                releaseQueuedAttachments: (state) => state.map((attachment) => ({ ...attachment, queued: false })),
            },
        ],
        uploading: [
            false,
            {
                setUploading: (_, { uploading }) => uploading,
            },
        ],
    }),

    selectors({
        stagedAttachments: [
            (s) => [s.attachments],
            (attachments: PendingAttachment[]): PendingAttachment[] =>
                attachments.filter((attachment) => !attachment.queued),
        ],
        queuedAttachments: [
            (s) => [s.attachments],
            (attachments: PendingAttachment[]): PendingAttachment[] =>
                attachments.filter((attachment) => attachment.queued),
        ],
        attachedFiles: [
            (s) => [s.stagedAttachments],
            (stagedAttachments: PendingAttachment[]): File[] => stagedAttachments.map((attachment) => attachment.file),
        ],
        hasAttachments: [
            (s) => [s.stagedAttachments],
            (stagedAttachments: PendingAttachment[]): boolean => stagedAttachments.length > 0,
        ],
        isAtAttachmentLimit: [
            (s) => [s.attachments],
            (attachments: PendingAttachment[]): boolean => remainingSlots(attachments) === 0,
        ],
    }),

    listeners(({ selectors }) => ({
        addFiles: ({ files }, _breakpoint, _action, previousState) => {
            for (const file of files) {
                const reason = attachmentRejectionReason(file)
                if (reason) {
                    lemonToast.error(reason)
                }
            }
            // The count needs the state from before the add, which the reducer has already replaced.
            const dropped = acceptableFiles(files).length - remainingSlots(selectors.attachments(previousState))
            if (dropped > 0) {
                lemonToast.warning(
                    `Only ${MAX_ATTACHMENTS_PER_MESSAGE} files fit in one message, so ${dropped} were left off`
                )
            }
        },
    })),
])

function acceptableFiles(files: File[]): File[] {
    return files.filter((file) => !attachmentRejectionReason(file))
}

function remainingSlots(attachments: PendingAttachment[]): number {
    return Math.max(0, MAX_ATTACHMENTS_PER_MESSAGE - attachments.length)
}