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(posthog_ai): support attaching files to a message (#106227)

Vojta Bartošfcb95c609118
diff --git a/frontend/snapshots.yml b/frontend/snapshots.yml
index d3de0ccc3954..04461e144c17 100644
--- a/frontend/snapshots.yml
+++ b/frontend/snapshots.yml
@@ -6707,7 +6707,7 @@ snapshots:
products-posthog-ai-startup-chat--queued-wide--dark:
hash: v1.k794b7964.5db40206f864b58e4a84d954fa58639fdec43bc178e008191d410cbeb6053608.cFgGJK6e7olWV45z3ekjUoGPbAMP2EablOmWNqLsACI
products-posthog-ai-startup-chat--queued-wide--light:
- hash: v1.k794b7964.3c58e032bb08060136074b2e28a01545852b1bccd78271c853ab93e144779a20.15rV0dd31YqWPTEJA0RLfsmsM85DJF3Y5pL5qlaGams
+ hash: v1.k794b7964.10bc533e5bca118de3428e4040970188ae5d7798f12e28d01ba4ed88db5c7881.hZvOyfRUVLf0xLYzv1YWZtHEi64XS8BFdrkWRkSGAEY
products-posthog-ai-startup-chat--sidebar--dark:
hash: v1.k794b7964.9df1a431eabd0d314ea291036288e31d351d785e5f511f64fcd255ba86c04c16.YtLvYRZ_hIFGA6PPEN-wZgi5tq85gR0OluUYChuz2KU
products-posthog-ai-startup-chat--sidebar--light:
diff --git a/frontend/src/scenes/max/maxThreadLogic.tsx b/frontend/src/scenes/max/maxThreadLogic.tsx
index ca17f73d8f95..3050ea0bb0a4 100644
--- a/frontend/src/scenes/max/maxThreadLogic.tsx
+++ b/frontend/src/scenes/max/maxThreadLogic.tsx
@@ -354,8 +354,16 @@ export interface maxThreadLogicActions {
errorMessage: string
variant: 'crash' | 'error'
} // runStreamLogic
- pushSandboxHumanMessage: (content: string) => {
+ pushSandboxHumanMessage: (
+ content: string,
+ stagedAttachments?:
+ | import('../../../../products/posthog_ai/frontend/types/streamTypes').StagedAttachment[]
+ | undefined
+ ) => {
content: string
+ stagedAttachments:
+ | import('../../../../products/posthog_ai/frontend/types/streamTypes').StagedAttachment[]
+ | undefined
} // runStreamLogic
resetSandboxStream: () => {
value: true
diff --git a/products/posthog_ai/frontend/components/ThreadAttachments.test.tsx b/products/posthog_ai/frontend/components/ThreadAttachments.test.tsx
new file mode 100644
index 000000000000..bf6fcea18ed5
--- /dev/null
+++ b/products/posthog_ai/frontend/components/ThreadAttachments.test.tsx
@@ -0,0 +1,101 @@
+import '@testing-library/jest-dom'
+
+import { cleanup, fireEvent, render, screen } from '@testing-library/react'
+
+import { projectLogic } from 'scenes/projectLogic'
+
+import { initKeaTests } from '~/test/init'
+
+import { clearAttachmentPreviews, rememberAttachmentPreview } from '../utils/attachmentPreviews'
+import { ThreadAttachments } from './ThreadAttachments'
+
+const RESOLVED = { taskId: 'task-3', runId: 'run-7', artifactId: 'art-9' }
+const DOWNLOAD_URL = '/api/projects/997/tasks/task-3/runs/run-7/artifacts/art-9/download/'
+
+describe('ThreadAttachments', () => {
+ beforeEach(() => {
+ initKeaTests()
+ projectLogic.mount()
+ clearAttachmentPreviews()
+ global.URL.createObjectURL = jest.fn(() => 'blob:local-preview')
+ global.URL.revokeObjectURL = jest.fn()
+ })
+
+ afterEach(() => {
+ cleanup()
+ })
+
+ it('shows an image as itself, linking to its download', () => {
+ render(<ThreadAttachments attachments={[{ name: 'shot.png', ...RESOLVED }]} />)
+
+ const image = screen.getByAltText('shot.png')
+ expect(image).toHaveAttribute('src', DOWNLOAD_URL)
+ expect(image.closest('a')).toHaveAttribute('href', DOWNLOAD_URL)
+ })
+
+ it('shows anything else as a badge linking to its download', () => {
+ render(<ThreadAttachments attachments={[{ name: 'rows.csv', ...RESOLVED }]} />)
+
+ expect(screen.getByText('rows.csv').closest('a')).toHaveAttribute('href', DOWNLOAD_URL)
+ expect(screen.queryByAltText('rows.csv')).not.toBeInTheDocument()
+ })
+
+ it('draws the staged file while the upload is still in flight', () => {
+ const previewId = rememberAttachmentPreview(new File(['x'], 'shot.png'))
+
+ render(<ThreadAttachments attachments={[{ name: 'shot.png', previewId }]} />)
+
+ expect(screen.getByAltText('shot.png')).toHaveAttribute('src', 'blob:local-preview')
+ })
+
+ it('prefers the artifact over the staged file once both are known', () => {
+ const previewId = rememberAttachmentPreview(new File(['x'], 'shot.png'))
+
+ render(<ThreadAttachments attachments={[{ name: 'shot.png', previewId, ...RESOLVED }]} />)
+
+ expect(screen.getByAltText('shot.png')).toHaveAttribute('src', DOWNLOAD_URL)
+ })
+
+ it('holds the space with a skeleton when an image has neither', () => {
+ const { container } = render(<ThreadAttachments attachments={[{ name: 'shot.png' }]} />)
+
+ expect(screen.queryByAltText('shot.png')).not.toBeInTheDocument()
+ expect(container.querySelector('.LemonSkeleton')).toBeInTheDocument()
+ })
+
+ it('names a pending non-image without offering a download', () => {
+ render(<ThreadAttachments attachments={[{ name: 'rows.csv' }]} />)
+
+ expect(screen.getByText('rows.csv').closest('a')).toBeNull()
+ })
+
+ it('puts the images above the badges rather than interleaving them', () => {
+ const { container } = render(
+ <ThreadAttachments
+ attachments={[
+ { name: 'rows.csv', ...RESOLVED },
+ { name: 'shot.png', ...RESOLVED },
+ ]}
+ />
+ )
+
+ const rows = container.firstElementChild!.children
+ expect(rows).toHaveLength(2)
+ expect(rows[0].querySelector('img')).toHaveAttribute('alt', 'shot.png')
+ expect(rows[1].textContent).toContain('rows.csv')
+ })
+
+ it('moves an image that cannot be fetched down to the badges', () => {
+ render(<ThreadAttachments attachments={[{ name: 'shot.png', ...RESOLVED }]} />)
+ fireEvent.error(screen.getByAltText('shot.png'))
+
+ expect(screen.queryByAltText('shot.png')).not.toBeInTheDocument()
+ expect(screen.getByText('shot.png')).toBeInTheDocument()
+ })
+
+ it('renders nothing when a message carried no files', () => {
+ const { container } = render(<ThreadAttachments attachments={[]} />)
+
+ expect(container).toBeEmptyDOMElement()
+ })
+})
diff --git a/products/posthog_ai/frontend/components/ThreadAttachments.tsx b/products/posthog_ai/frontend/components/ThreadAttachments.tsx
new file mode 100644
index 000000000000..f419702eb870
--- /dev/null
+++ b/products/posthog_ai/frontend/components/ThreadAttachments.tsx
@@ -0,0 +1,148 @@
+import { useValues } from 'kea'
+import { memo, useEffect, useState } from 'react'
+
+import { IconDocument } from '@posthog/icons'
+import { LemonSkeleton, LemonTag, Link, Tooltip } from '@posthog/lemon-ui'
+
+import { projectLogic } from 'scenes/projectLogic'
+
+import { getTasksRunsArtifactsDownloadRetrieveUrl } from 'products/tasks/frontend/generated/api'
+
+import type { ThreadAttachment } from '../types/streamTypes'
+import { getAttachmentPreview } from '../utils/attachmentPreviews'
+import { isImageAttachment } from '../utils/attachments'
+
+// Capped on both axes and free to shrink, so no screenshot pushes a message past its panel.
+const THUMBNAIL_CLASSES = 'max-h-48 max-w-full w-auto rounded border border-primary object-contain'
+
+/** The endpoint redirects to a presigned URL and takes the session, so an `img` and an `a` use it directly. */
+function downloadUrl(projectId: string, attachment: ThreadAttachment): string | null {
+ if (!attachment.taskId || !attachment.runId || !attachment.artifactId) {
+ return null
+ }
+ // The run that holds the artifact, not necessarily the one being read: a resume chain reaches back.
+ return getTasksRunsArtifactsDownloadRetrieveUrl(
+ projectId,
+ attachment.taskId,
+ attachment.runId,
+ attachment.artifactId
+ )
+}
+
+/** The staged file's own bytes, available from the send until its upload lands. */
+function useLocalPreviewUrl(previewId: string | undefined): string | null {
+ const [url, setUrl] = useState<string | null>(null)
+ useEffect(() => {
+ const file = getAttachmentPreview(previewId)
+ if (!file) {
+ setUrl(null)
+ return
+ }
+ const objectUrl = URL.createObjectURL(file)
+ setUrl(objectUrl)
+ return () => URL.revokeObjectURL(objectUrl)
+ }, [previewId])
+ return url
+}
+
+function AttachmentChip({ name, href }: { name: string; href: string | null }): JSX.Element {
+ const chip = (
+ <LemonTag icon={<IconDocument />} className="max-w-48">
+ <span className="truncate min-w-0">{name}</span>
+ </LemonTag>
+ )
+ return (
+ <Tooltip title={href ? `Download ${name}` : name}>
+ {href ? (
+ // An API path is not an app route, so client-side routing has to stay out of it.
+ <Link to={href} target="_blank" disableClientSideRouting targetBlankIcon={false}>
+ {chip}
+ </Link>
+ ) : (
+ <span>{chip}</span>
+ )}
+ </Tooltip>
+ )
+}
+
+/** The artifact wins once it exists, so a message shows what the agent received. */
+const ThreadAttachmentImage = memo(function ThreadAttachmentImage({
+ attachment,
+ href,
+ onUnavailable,
+}: {
+ attachment: ThreadAttachment
+ href: string | null
+ onUnavailable: () => void
+}): JSX.Element {
+ const localUrl = useLocalPreviewUrl(attachment.previewId)
+ const src = href ?? localUrl
+
+ if (!src) {
+ return <LemonSkeleton className="h-24 w-32 rounded shrink-0" />
+ }
+ const image = <img src={src} alt={attachment.name} className={THUMBNAIL_CLASSES} onError={onUnavailable} />
+ return (
+ <Tooltip title={attachment.name}>
+ {href ? (
+ <Link to={href} target="_blank" disableClientSideRouting targetBlankIcon={false} className="min-w-0">
+ {image}
+ </Link>
+ ) : (
+ <span className="min-w-0">{image}</span>
+ )}
+ </Tooltip>
+ )
+})
+
+function attachmentKey(attachment: ThreadAttachment): string {
+ return `${attachment.artifactId ?? attachment.previewId ?? 'pending'}-${attachment.name}`
+}
+
+/** Images first, then a badge per remaining file, so a screenshot is not competing with a row of names. */
+export function ThreadAttachments({ attachments }: { attachments: ThreadAttachment[] }): JSX.Element | null {
+ const { currentProjectId } = useValues(projectLogic)
+ // An unfetchable image moves down to the badges rather than leaving a broken frame.
+ const [unavailable, setUnavailable] = useState<Set<string>>(new Set())
+
+ if (attachments.length === 0) {
+ return null
+ }
+
+ const projectId = currentProjectId === null ? null : String(currentProjectId)
+ const showsImage = (attachment: ThreadAttachment): boolean =>
+ isImageAttachment(attachment.name) && !unavailable.has(attachmentKey(attachment))
+ const images = attachments.filter(showsImage)
+ const files = attachments.filter((attachment) => !showsImage(attachment))
+
+ return (
+ <div className="flex flex-col gap-1 mt-1 min-w-0 max-w-full">
+ {images.length > 0 && (
+ <div className="flex flex-wrap items-start gap-1 min-w-0 max-w-full">
+ {images.map((attachment) => {
+ const key = attachmentKey(attachment)
+ return (
+ <ThreadAttachmentImage
+ key={key}
+ attachment={attachment}
+ href={projectId ? downloadUrl(projectId, attachment) : null}
+ onUnavailable={() => setUnavailable((seen) => new Set(seen).add(key))}
+ />
+ )
+ })}
+ </div>
+ )}
+ {files.length > 0 && (
+ <div className="flex flex-wrap items-center gap-1 min-w-0 max-w-full">
+ {files.map((attachment) => (
+ <AttachmentChip
+ key={attachmentKey(attachment)}
+ name={attachment.name}
+ href={projectId ? downloadUrl(projectId, attachment) : null}
+ />
+ ))}
+ </div>
+ )}
+ </div>
+ )
+}
diff --git a/products/posthog_ai/frontend/components/ThreadRow.tsx b/products/posthog_ai/frontend/components/ThreadRow.tsx
index 9aa63a1e65b1..909b9c4e09f1 100644
--- a/products/posthog_ai/frontend/components/ThreadRow.tsx
+++ b/products/posthog_ai/frontend/components/ThreadRow.tsx
@@ -15,6 +15,7 @@ import type { ProgressStep, ThreadItem } from '../types/streamTypes'
import { resolveToolCall } from '../utils/toolResolver'
import { Activity } from './ActivityPrimitives'
import { RunErrorRow } from './RunErrorRow'
+import { ThreadAttachments } from './ThreadAttachments'
import { CompactBoundaryItem, ConversationClearedItem, StatusItem, TaskNotificationItem } from './ThreadItems'
import { ToolCallCard } from './tool/ToolCallCard'
@@ -122,6 +123,7 @@ export const ThreadRow = memo(function ThreadRow({
return (
<MessageTemplate type="human">
<MarkdownMessage content={item.text || '*No text.*'} id={item.id} />
+ {item.attachments && <ThreadAttachments attachments={item.attachments} />}
</MessageTemplate>
)
}
diff --git a/products/posthog_ai/frontend/components/composer/Composer.tsx b/products/posthog_ai/frontend/components/composer/Composer.tsx
index fe7bb88fb410..b2aca66d56cf 100644
--- a/products/posthog_ai/frontend/components/composer/Composer.tsx
+++ b/products/posthog_ai/frontend/components/composer/Composer.tsx
@@ -1,4 +1,5 @@
import {
+ type ClipboardEventHandler,
createContext,
forwardRef,
type HTMLAttributes,
@@ -302,6 +303,8 @@ export interface ComposerTextareaProps {
maxRows?: number
/** Extra key handling (e.g. the mode picker's `shift+tab` cycle); runs after Enter handling. */
onKeyDown?: KeyboardEventHandler<HTMLTextAreaElement>
+ /** Lets a host claim a paste before the textarea takes it — used to attach pasted files. */
+ onPaste?: ClipboardEventHandler<HTMLTextAreaElement>
'data-attr'?: string
}
diff --git a/products/posthog_ai/frontend/components/composer/ComposerAttachments.test.tsx b/products/posthog_ai/frontend/components/composer/ComposerAttachments.test.tsx
new file mode 100644
index 000000000000..fee1c1721c48
--- /dev/null
+++ b/products/posthog_ai/frontend/components/composer/ComposerAttachments.test.tsx
@@ -0,0 +1,136 @@
+import '@testing-library/jest-dom'
+
+import { cleanup, fireEvent, render } from '@testing-library/react'
+import { createRef } from 'react'
+
+import { initKeaTests } from '~/test/init'
+
+import { composerAttachmentsLogic } from '../../logics/composerAttachmentsLogic'
+import { ComposerAttachments, useComposerAttachmentPaste } from './ComposerAttachments'
+
+function PasteTarget(): JSX.Element {
+ const onPaste = useComposerAttachmentPaste('scene')
+ return <textarea onPaste={onPaste} />
+}
+
+function pasteInto(target: HTMLElement, files: File[], text: string): boolean {
+ return fireEvent.paste(target, { clipboardData: { files, getData: () => text } })
+}
+
+function dropFiles(target: HTMLElement, files: File[]): void {
+ fireEvent.drop(target, { dataTransfer: { files, types: ['Files'] } })
+}
+
+describe('ComposerAttachments', () => {
+ let logic: ReturnType<typeof composerAttachmentsLogic.build>
+ const dropTargetRef = createRef<HTMLDivElement>()
+
+ function renderWithDropTarget(): void {
+ render(
+ <div ref={dropTargetRef}>
+ <ComposerAttachments attachmentsKey="scene" dropTargetRef={dropTargetRef} />
+ </div>
+ )
+ }
+
+ beforeEach(() => {
+ initKeaTests()
+ logic = composerAttachmentsLogic({ attachmentsKey: 'scene' })
+ logic.mount()
+ })
+
+ afterEach(() => {
+ cleanup()
+ logic.unmount()
+ })
+
+ it('stages a dropped file once', () => {
+ renderWithDropTarget()
+
+ dropFiles(dropTargetRef.current!, [new File(['a'], 'shot.png')])
+
+ expect(logic.values.attachments.map((attachment) => attachment.file.name)).toEqual(['shot.png'])
+ })
+
+ it('does not re-stage earlier files on a second drop', () => {
+ renderWithDropTarget()
+
+ dropFiles(dropTargetRef.current!, [new File(['a'], 'a.png'), new File(['b'], 'b.png')])
+ dropFiles(dropTargetRef.current!, [new File(['c'], 'c.png'), new File(['d'], 'd.png')])
+
+ expect(logic.values.attachments.map((attachment) => attachment.file.name)).toEqual([
+ 'a.png',
+ 'b.png',
+ 'c.png',
+ 'd.png',
+ ])
+ })
+
+ it('ignores a drop that carries no files, so dragging text does not attach anything', () => {
+ renderWithDropTarget()
+
+ fireEvent.drop(dropTargetRef.current!, { dataTransfer: { files: [], types: ['text/plain'] } })
+
+ expect(logic.values.attachments).toEqual([])
+ })
+
+ it('refuses a drop once the per-message limit is reached', () => {
+ renderWithDropTarget()
+ logic.actions.addFiles(Array.from({ length: 10 }, (_, index) => new File(['x'], `f-${index}.png`)))
+
+ dropFiles(dropTargetRef.current!, [new File(['a'], 'over.png')])
+
+ expect(logic.values.attachments).toHaveLength(10)
+ expect(logic.values.attachments.map((attachment) => attachment.file.name)).not.toContain('over.png')
+ })
+
+ it('stages files chosen through the picker', () => {
+ renderWithDropTarget()
+ const fileInput = document.querySelector('input[type="file"]') as HTMLInputElement
+
+ fireEvent.change(fileInput, { target: { files: [new File(['a'], 'picked.png')] } })
+
+ expect(logic.values.attachments.map((attachment) => attachment.file.name)).toEqual(['picked.png'])
+ })
+
+ describe('paste', () => {
+ it('attaches a pasted file', () => {
+ render(<PasteTarget />)
+
+ pasteInto(document.querySelector('textarea')!, [new File(['a'], 'shot.png')], '')
+
+ expect(logic.values.attachments.map((attachment) => attachment.file.name)).toEqual(['shot.png'])
+ })
+
+ it('lets the text through when the clipboard carries both', () => {
+ render(<PasteTarget />)
+
+ const notPrevented = pasteInto(
+ document.querySelector('textarea')!,
+ [new File(['a'], 'image.png')],
+ 'Revenue\t1200'
+ )
+
+ expect(notPrevented).toBe(true)
+ expect(logic.values.attachments.map((attachment) => attachment.file.name)).toEqual(['image.png'])
+ })
+
+ it('takes the paste when there is no text to lose', () => {
+ render(<PasteTarget />)
+
+ const notPrevented = pasteInto(document.querySelector('textarea')!, [new File(['a'], 'image.png')], '')
+
+ expect(notPrevented).toBe(false)
+ })
+ })
+
+ it('stops listening once unmounted, so a later drop stages nothing', () => {
+ renderWithDropTarget()
+ const target = dropTargetRef.current!
+ cleanup()
+
+ dropFiles(target, [new File(['a'], 'late.png')])
+
+ expect(logic.values.attachments).toEqual([])
+ })
+})
diff --git a/products/posthog_ai/frontend/components/composer/ComposerAttachments.tsx b/products/posthog_ai/frontend/components/composer/ComposerAttachments.tsx
new file mode 100644
index 000000000000..7eb200fac6e5
--- /dev/null
+++ b/products/posthog_ai/frontend/components/composer/ComposerAttachments.tsx
@@ -0,0 +1,202 @@
+import { useActions, useValues } from 'kea'
+import { type ChangeEvent, type ClipboardEvent, type RefObject, useCallback, useEffect, useRef, useState } from 'react'
+
+import { IconDocument, IconImage, IconUpload } from '@posthog/icons'
+import { LemonButton, LemonTag, Spinner, Tooltip } from '@posthog/lemon-ui'
+
+import { composerAttachmentsLogic } from '../../logics/composerAttachmentsLogic'
+import { MAX_ATTACHMENTS_PER_MESSAGE, formatFileSize, isImageAttachment } from '../../utils/attachments'
+
+/**
+ * Not `LemonFileInput`'s `alternativeDropTargetRef`: it keeps its own copy of the file list and re-syncs it
+ * only when the `value` prop changes identity, so a composer whose logic owns the list grows that copy and
+ * re-reports every earlier file on each drop.
+ */
+function useFileDrop(target: RefObject<HTMLElement> | undefined, onFiles: (files: File[]) => void): boolean {
+ const [isOver, setIsOver] = useState(false)
+ // Dragging over a child fires dragleave on the parent, so count nesting rather than flicker off.
+ const depth = useRef(0)
+ const onFilesRef = useRef(onFiles)
+ onFilesRef.current = onFiles
+
+ useEffect(() => {
+ const node = target?.current
+ if (!node) {
+ return
+ }
+ const carriesFiles = (event: DragEvent): boolean =>
+ Array.from(event.dataTransfer?.types ?? []).includes('Files')
+ const onDragEnter = (event: DragEvent): void => {
+ if (!carriesFiles(event)) {
+ return
+ }
+ depth.current += 1
+ setIsOver(true)
+ }
+ const onDragOver = (event: DragEvent): void => {
+ if (carriesFiles(event)) {
+ // Or the browser takes the drop itself and navigates to the file.
+ event.preventDefault()
+ }
+ }
+ const onDragLeave = (): void => {
+ depth.current = Math.max(0, depth.current - 1)
+ if (depth.current === 0) {
+ setIsOver(false)
+ }
+ }
+ const onDrop = (event: DragEvent): void => {
+ if (!carriesFiles(event)) {
+ return
+ }
+ event.preventDefault()
+ depth.current = 0
+ setIsOver(false)
+ const files = Array.from(event.dataTransfer?.files ?? [])
+ if (files.length > 0) {
+ onFilesRef.current(files)
+ }
+ }
+
+ node.addEventListener('dragenter', onDragEnter)
+ node.addEventListener('dragover', onDragOver)
+ node.addEventListener('dragleave', onDragLeave)
+ node.addEventListener('drop', onDrop)
+ return () => {
+ node.removeEventListener('dragenter', onDragEnter)
+ node.removeEventListener('dragover', onDragOver)
+ node.removeEventListener('dragleave', onDragLeave)
+ node.removeEventListener('drop', onDrop)
+ }
+ }, [target])
+
+ return isOver
+}
+
+/** The bytes are already in the browser, so this preview costs an object URL and no request. */
+function AttachmentThumbnail({ file }: { file: File }): JSX.Element {
+ const [src, setSrc] = useState<string | null>(null)
+ useEffect(() => {
+ const objectUrl = URL.createObjectURL(file)
+ setSrc(objectUrl)
+ return () => URL.revokeObjectURL(objectUrl)
+ }, [file])
+
+ if (!src) {
+ return <IconImage />
+ }
+ return <img src={src} alt="" className="size-4 rounded-sm object-cover" />
+}
+
+export interface ComposerAttachmentsProps {
+ attachmentsKey: string
+ dropTargetRef?: RefObject<HTMLElement>
+ disabledReason?: string
+}
+
+export function ComposerAttachments({
+ attachmentsKey,
+ dropTargetRef,
+ disabledReason,
+}: ComposerAttachmentsProps): JSX.Element {
+ const logic = composerAttachmentsLogic({ attachmentsKey })
+ const { stagedAttachments, uploading, isAtAttachmentLimit } = useValues(logic)
+ const { addFiles, removeAttachment } = useActions(logic)
+ const inputRef = useRef<HTMLInputElement>(null)
+
+ const addDisabledReason =
+ disabledReason ?? (isAtAttachmentLimit ? `Up to ${MAX_ATTACHMENTS_PER_MESSAGE} files per message` : undefined)
+
+ const acceptDropped = useCallback(
+ (files: File[]) => {
+ if (!addDisabledReason) {
+ addFiles(files)
+ }
+ },
+ [addFiles, addDisabledReason]
+ )
+ const isOver = useFileDrop(dropTargetRef, acceptDropped)
+
+ const onPicked = (event: ChangeEvent<HTMLInputElement>): void => {
+ const files = Array.from(event.target.files ?? [])
+ if (files.length > 0) {
+ addFiles(files)
+ }
+ // Or picking the same file twice in a row is not a change and never fires.
+ event.target.value = ''
+ }
+
+ return (
+ <div className="flex flex-wrap items-center gap-1 min-w-0">
+ <input
+ ref={inputRef}
+ type="file"
+ multiple
+ // The harness reads the artifact off disk with its own file tools, so narrowing here would
+ // only refuse files that work.
+ accept="*/*"
+ className="hidden"
+ onChange={onPicked}
+ data-attr="posthog-ai-attach-input"
+ />
+ <LemonButton
+ size="xxsmall"
+ type="tertiary"
+ className={isOver ? 'flex-shrink-0 border border-accent' : 'flex-shrink-0 border'}
+ icon={<IconUpload className="text-secondary" />}
+ disabledReason={addDisabledReason}
+ tooltip="Attach files for PostHog AI to read"
+ onClick={() => inputRef.current?.click()}
+ data-attr="posthog-ai-attach-file"
+ >
+ {stagedAttachments.length > 0 ? null : (
+ <span className="text-secondary">{isOver ? 'Drop to attach' : 'Attach'}</span>
+ )}
+ </LemonButton>
+ {stagedAttachments.map(({ id, file }) => (
+ <Tooltip key={id} title={`${file.name} (${formatFileSize(file.size)})`}>
+ <LemonTag
+ icon={
+ uploading ? (
+ <Spinner />
+ ) : isImageAttachment(file.name) ? (
+ <AttachmentThumbnail file={file} />
+ ) : (
+ <IconDocument />
+ )
+ }
+ onClose={() => removeAttachment(id)}
+ closable={!uploading}
+ closeOnClick={!uploading}
+ className="flex items-center text-secondary max-w-48"
+ data-attr="posthog-ai-attachment-chip"
+ >
+ <span className="truncate min-w-0 flex-1">{file.name}</span>
+ </LemonTag>
+ </Tooltip>
+ ))}
+ </div>
+ )
+}
+
+/**
+ * A paste carrying files attaches them. Copying from a spreadsheet or a document puts an image on the
+ * clipboard beside the text, so the text is left to the textarea whenever there is any — taking the paste
+ * outright would swallow what the user meant to write.
+ */
+export function useComposerAttachmentPaste(attachmentsKey: string): (event: ClipboardEvent) => void {
+ const { addFiles } = useActions(composerAttachmentsLogic({ attachmentsKey }))
+ return useCallback(
+ (event: ClipboardEvent) => {
+ const files = Array.from(event.clipboardData?.files ?? [])
+ if (files.length === 0) {
+ return
+ }
+ if (!event.clipboardData?.getData('text/plain')) {
+ event.preventDefault()
+ }
+ addFiles(files)
+ },
+ [addFiles]
+ )
+}
diff --git a/products/posthog_ai/frontend/logics/composerAttachmentsLogic.test.ts b/products/posthog_ai/frontend/logics/composerAttachmentsLogic.test.ts
new file mode 100644
index 000000000000..9b4077a1e23c
--- /dev/null
+++ b/products/posthog_ai/frontend/logics/composerAttachmentsLogic.test.ts
@@ -0,0 +1,119 @@
+import { lemonToast } from '@posthog/lemon-ui'
+
+import { initKeaTests } from '~/test/init'
+
+import { MAX_ATTACHMENTS_PER_MESSAGE } from '../utils/attachments'
+import { composerAttachmentsLogic } from './composerAttachmentsLogic'
+
+function fileOfSize(name: string, size: number): File {
+ const file = new File(['x'], name)
+ Object.defineProperty(file, 'size', { value: size })
+ return file
+}
+
+describe('composerAttachmentsLogic', () => {
+ let logic: ReturnType<typeof composerAttachmentsLogic.build>
+
+ beforeEach(() => {
+ initKeaTests()
+ logic = composerAttachmentsLogic({ attachmentsKey: 'scene' })
+ logic.mount()
+ })
+
+ afterEach(() => {
+ logic.unmount()
+ })
+
+ it('stages the files it is given, in order', () => {
+ logic.actions.addFiles([new File(['a'], 'a.md'), new File(['b'], 'b.png')])
+
+ expect(logic.values.attachments.map((attachment) => attachment.file.name)).toEqual(['a.md', 'b.png'])
+ expect(logic.values.attachedFiles.map((file) => file.name)).toEqual(['a.md', 'b.png'])
+ expect(logic.values.hasAttachments).toBe(true)
+ })
+
+ it('adds to what is already staged rather than replacing it', () => {
+ logic.actions.addFiles([new File(['a'], 'a.md')])
+ logic.actions.addFiles([new File(['b'], 'b.md')])
+
+ expect(logic.values.attachments).toHaveLength(2)
+ })
+
+ it('gives every chip its own id, even for two files of the same name', () => {
+ logic.actions.addFiles([new File(['a'], 'same.md'), new File(['b'], 'same.md')])
+
+ const [first, second] = logic.values.attachments
+ expect(first.id).not.toBe(second.id)
+ })
+
+ it('removes one chip and leaves the rest', () => {
+ logic.actions.addFiles([new File(['a'], 'a.md'), new File(['b'], 'b.md')])
+ logic.actions.removeAttachment(logic.values.attachments[0].id)
+
+ expect(logic.values.attachments.map((attachment) => attachment.file.name)).toEqual(['b.md'])
+ })
+
+ it('drops an oversized file and says why, keeping the rest of the batch', () => {
+ const toast = jest.spyOn(lemonToast, 'error').mockImplementation()
+
+ logic.actions.addFiles([fileOfSize('huge.png', 40 * 1024 * 1024), new File(['ok'], 'ok.md')])
+
+ expect(logic.values.attachments.map((attachment) => attachment.file.name)).toEqual(['ok.md'])
+ expect(toast).toHaveBeenCalledWith('huge.png is over the 30MB limit')
+ })
+
+ it('stops at the per-message limit', () => {
+ logic.actions.addFiles(
+ Array.from({ length: MAX_ATTACHMENTS_PER_MESSAGE + 3 }, (_, index) => new File(['x'], `file-${index}.md`))
+ )
+
+ expect(logic.values.attachments).toHaveLength(MAX_ATTACHMENTS_PER_MESSAGE)
+ expect(logic.values.isAtAttachmentLimit).toBe(true)
+ })
+
+ it('removes only the files a send took, leaving one added since', () => {
+ logic.actions.addFiles([new File(['a'], 'a.md'), new File(['b'], 'b.md')])
+ const sent = logic.values.attachments.map((attachment) => attachment.id)
+ logic.actions.addFiles([new File(['c'], 'c.md')])
+
+ logic.actions.removeAttachments(sent)
+
+ expect(logic.values.attachments.map((attachment) => attachment.file.name)).toEqual(['c.md'])
+ })
+
+ describe('files promised to the queue', () => {
+ beforeEach(() => {
+ logic.actions.addFiles([new File(['a'], 'queued.md')])
+ logic.actions.claimAttachmentsForQueue()
+ })
+
+ it('leaves the composer, so a draft send cannot take them', () => {
+ expect(logic.values.stagedAttachments).toEqual([])
+ expect(logic.values.queuedAttachments.map((attachment) => attachment.file.name)).toEqual(['queued.md'])
+ expect(logic.values.hasAttachments).toBe(false)
+ })
+
+ it('still counts against the per-message limit', () => {
+ logic.actions.addFiles(Array.from({ length: 10 }, (_, index) => new File(['x'], `f-${index}.md`)))
+
+ expect(logic.values.attachments).toHaveLength(MAX_ATTACHMENTS_PER_MESSAGE)
+ })
+
+ it('comes back to the composer when the queue is released', () => {
+ logic.actions.releaseQueuedAttachments()
+
+ expect(logic.values.stagedAttachments.map((attachment) => attachment.file.name)).toEqual(['queued.md'])
+ expect(logic.values.queuedAttachments).toEqual([])
+ })
+ })
+
+ it('keys the staged files per composer, so one composer never sees another one’s', () => {
+ const other = composerAttachmentsLogic({ attachmentsKey: 'side-panel' })
+ other.mount()
+
+ logic.actions.addFiles([new File(['a'], 'a.md')])
+
+ expect(other.values.attachments).toEqual([])
+ other.unmount()
+ })
+})
diff --git a/products/posthog_ai/frontend/logics/composerAttachmentsLogic.ts b/products/posthog_ai/frontend/logics/composerAttachmentsLogic.ts
new file mode 100644
index 000000000000..3739bfc66180
--- /dev/null
+++ b/products/posthog_ai/frontend/logics/composerAttachmentsLogic.ts
@@ -0,0 +1,163 @@
+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)
+}
diff --git a/products/posthog_ai/frontend/logics/runInteractionLogic.test.ts b/products/posthog_ai/frontend/logics/runInteractionLogic.test.ts
index 52768432f056..600a0eef046b 100644
--- a/products/posthog_ai/frontend/logics/runInteractionLogic.test.ts
+++ b/products/posthog_ai/frontend/logics/runInteractionLogic.test.ts
@@ -16,8 +16,10 @@ import {
} from 'products/tasks/frontend/generated/api'
import type { PermissionRequestRecord } from '../types/streamTypes'
+import { uploadRunAttachments, uploadStagedTaskAttachments } from '../utils/artifactUpload'
import { contextItemLine } from '../utils/posthogContextBlock'
import { attachedContextLogic } from './attachedContextLogic'
+import { composerAttachmentsLogic } from './composerAttachmentsLogic'
import { runCancellationLogic } from './runCancellationLogic'
import { runInteractionLogic } from './runInteractionLogic'
import { runStreamLogic } from './runStreamLogic'
@@ -166,6 +168,11 @@ jest.mock('lib/lemon-ui/LemonToast', () => ({
lemonToast: { error: jest.fn() },
}))
+jest.mock('../utils/artifactUpload', () => ({
+ uploadRunAttachments: jest.fn(),
+ uploadStagedTaskAttachments: jest.fn(),
+}))
+
describe('runInteractionLogic', () => {
let logic: ReturnType<typeof runInteractionLogic.build>
let stream: ReturnType<typeof runStreamLogic.build>
@@ -226,6 +233,104 @@ describe('runInteractionLogic', () => {
toolEvents?.unmount()
})
+ describe('file attachments', () => {
+ let attachments: ReturnType<typeof composerAttachmentsLogic.build>
+
+ beforeEach(() => {
+ attachments = composerAttachmentsLogic({ attachmentsKey: RUN_ID })
+ attachments.mount()
+ attachments.actions.addFiles([new File(['a'], 'rows.csv')])
+ })
+
+ afterEach(() => {
+ attachments.unmount()
+ })
+
+ it('uploads the staged files to the run and carries their ids on the follow-up', async () => {
+ ;(uploadRunAttachments as jest.Mock).mockResolvedValue(['art-1'])
+
+ logic.actions.setComposerFormValues({ draft: 'What is wrong here?' })
+ await expectLogic(logic, () => logic.actions.submitComposerForm()).toFinishAllListeners()
+
+ expect(uploadRunAttachments).toHaveBeenCalledWith('997', TASK_ID, RUN_ID, [expect.any(File)])
+ expect(tasksRunsCommandCreate).toHaveBeenCalledWith('997', TASK_ID, RUN_ID, {
+ jsonrpc: '2.0',
+ method: 'user_message',
+ params: { content: 'What is wrong here?', artifact_ids: ['art-1'] },
+ })
+ expect(attachments.values.attachments).toEqual([])
+ expect(attachments.values.uploading).toBe(false)
+ })
+
+ it('keeps the files staged when the send fails', async () => {
+ ;(uploadRunAttachments as jest.Mock).mockRejectedValue(new Error('S3 said no'))
+
+ logic.actions.setComposerFormValues({ draft: 'What is wrong here?' })
+ await expectLogic(logic, () => logic.actions.submitComposerForm()).toFinishAllListeners()
+
+ expect(tasksRunsCommandCreate).not.toHaveBeenCalled()
+ expect(attachments.values.attachments).toHaveLength(1)
+ expect(attachments.values.uploading).toBe(false)
+ expect(logic.values.composerForm.draft).toBe('What is wrong here?')
+ })
+
+ it('sends the files queued with a message, not the ones attached since', async () => {
+ ;(uploadRunAttachments as jest.Mock).mockResolvedValue(['art-queued'])
+ setThinking(true)
+ logic.actions.setComposerFormValues({ draft: 'first message' })
+ await expectLogic(logic, () => logic.actions.submitComposerForm()).toFinishAllListeners()
+
+ attachments.actions.addFiles([new File(['b'], 'next-draft.csv')])
+ setThinking(false)
+ await expectLogic(logic, () => stream.actions.markTurnComplete()).toFinishAllListeners()
+
+ expect(uploadRunAttachments).toHaveBeenCalledWith('997', TASK_ID, RUN_ID, [
+ expect.objectContaining({ name: 'rows.csv' }),
+ ])
+ expect(attachments.values.stagedAttachments.map((attachment) => attachment.file.name)).toEqual([
+ 'next-draft.csv',
+ ])
+ })
+
+ it('hands the files back when the queued message they belong to is removed', async () => {
+ setThinking(true)
+ logic.actions.setComposerFormValues({ draft: 'first message' })
+ await expectLogic(logic, () => logic.actions.submitComposerForm()).toFinishAllListeners()
+ expect(attachments.values.stagedAttachments).toEqual([])
+
+ await expectLogic(logic, () =>
+ logic.actions.removeQueuedMessage(logic.values.queuedMessages[0].id)
+ ).toFinishAllListeners()
+
+ expect(attachments.values.stagedAttachments.map((attachment) => attachment.file.name)).toEqual(['rows.csv'])
+ })
+
+ it('stages the files on the task when a terminal run starts a new one', async () => {
+ ;(uploadStagedTaskAttachments as jest.Mock).mockResolvedValue(['art-2'])
+ setStatus('completed')
+
+ logic.actions.setComposerFormValues({ draft: 'Try again with this' })
+ await expectLogic(logic, () => logic.actions.submitComposerForm()).toFinishAllListeners()
+
+ expect(uploadStagedTaskAttachments).toHaveBeenCalledWith('997', TASK_ID, [expect.any(File)])
+ expect(tasksRunCreate).toHaveBeenCalledWith(
+ '997',
+ TASK_ID,
+ expect.objectContaining({ pending_user_artifact_ids: ['art-2'] }),
+ expect.anything()
+ )
+ expect(attachments.values.attachments).toEqual([])
+ })
+ })
+
+ it('sends a follow-up with no artifact ids when nothing is attached', async () => {
+ logic.actions.setComposerFormValues({ draft: 'Plain follow-up' })
+ await expectLogic(logic, () => logic.actions.submitComposerForm()).toFinishAllListeners()
+
+ expect(uploadRunAttachments).not.toHaveBeenCalled()
+ expect(tasksRunsCommandCreate).toHaveBeenCalledWith(...userMessageCommand('Plain follow-up'))
+ })
+
it('restores queued text and the latest page-exit draft without sending on readiness or turn completion', async () => {
logic.actions.enableTaskDraftPersistence('user-1', 997)
setThinking(true)
diff --git a/products/posthog_ai/frontend/logics/runInteractionLogic.ts b/products/posthog_ai/frontend/logics/runInteractionLogic.ts
index 1f6ba2c64a83..4f96345542d8 100644
--- a/products/posthog_ai/frontend/logics/runInteractionLogic.ts
+++ b/products/posthog_ai/frontend/logics/runInteractionLogic.ts
@@ -46,10 +46,14 @@ import {
} from 'products/tasks/frontend/generated/api.schemas'
import { type AttachedContextItem, attachedContextItemKey } from '../types/contextTypes'
-import type { PermissionRequestRecord } from '../types/streamTypes'
+import type { PermissionRequestRecord, StagedAttachment } from '../types/streamTypes'
+import { uploadRunAttachments, uploadStagedTaskAttachments } from '../utils/artifactUpload'
+import { rememberAttachmentPreview } from '../utils/attachmentPreviews'
+import type { PendingAttachment } from '../utils/attachments'
import { contextItemLine, wrapWithPosthogContext } from '../utils/posthogContextBlock'
import { submitWithWarmRunRetry } from '../utils/warmRunSubmission'
import { attachedContextLogic } from './attachedContextLogic'
+import { composerAttachmentsLogic } from './composerAttachmentsLogic'
import { modelCatalogueLogic } from './modelCatalogueLogic'
import { type CancellationState, runCancellationLogic } from './runCancellationLogic'
import { isTerminalRunStatus, runStreamLogic } from './runStreamLogic'
@@ -122,6 +126,11 @@ const EFFORT_CONFIG_ID = 'effort'
// `set_config_option { configId: 'mode' }` is how `/code` applies a live shift+tab mode change.
const MODE_CONFIG_ID = 'mode'
+/** Hands the echo each file's name plus a handle to its bytes, so the message can draw it right away. */
+function stageAttachmentPreviews(attachments: PendingAttachment[]): StagedAttachment[] {
+ return attachments.map(({ file }) => ({ name: file.name, previewId: rememberAttachmentPreview(file) }))
+}
+
/** Matches a bare `/clear` invocation, not a longer command that starts with it. */
function isClearCommand(content: string): boolean {
return /^\/clear(?:\s|$)/.test(content)
@@ -156,6 +165,8 @@ export interface runInteractionLogicValues {
contextItems: AttachedContextItem[] // attachedContextLogic
seenContextLinesByTask: Record<string, string[]> // attachedContextLogic
sentContextKeysByTask: Record<string, string[]> // attachedContextLogic
+ queuedAttachments: PendingAttachment[] // composerAttachmentsLogic
+ stagedAttachments: PendingAttachment[] // composerAttachmentsLogic
catalogue: ModelChoiceApi[] // modelCatalogueLogic
currentProjectId: number | null // projectLogic
cancellationState: CancellationState // runCancellationLogic
@@ -237,6 +248,18 @@ export interface runInteractionLogicActions {
keys: string[]
taskId: string
} // attachedContextLogic
+ claimAttachmentsForQueue: () => {
+ value: true
+ } // composerAttachmentsLogic
+ releaseQueuedAttachments: () => {
+ value: true
+ } // composerAttachmentsLogic
+ removeAttachments: (ids: string[]) => {
+ ids: string[]
+ } // composerAttachmentsLogic
+ setUploading: (uploading: boolean) => {
+ uploading: boolean
+ } // composerAttachmentsLogic
requestCancellation: () => {
value: true
} // runCancellationLogic
@@ -299,8 +322,12 @@ export interface runInteractionLogicActions {
pushConversationCleared: () => {
value: true
} // runStreamLogic
- pushHumanMessage: (content: string) => {
+ pushHumanMessage: (
+ content: string,
+ stagedAttachments?: StagedAttachment[] | undefined
+ ) => {
content: string
+ stagedAttachments: StagedAttachment[] | undefined
} // runStreamLogic
resetStream: () => {
value: true
@@ -322,8 +349,12 @@ export interface runInteractionLogicActions {
setCurrentMode: (mode: string) => {
mode: string
} // runStreamLogic
- startOptimisticResume: (message: string) => {
+ startOptimisticResume: (
+ message: string,
+ stagedAttachments?: StagedAttachment[] | undefined
+ ) => {
message: string
+ stagedAttachments: StagedAttachment[] | undefined
} // runStreamLogic
claimApplyBackTargets: (streamKey: string) => {
streamKey: string
@@ -622,6 +653,8 @@ export const runInteractionLogic = kea<runInteractionLogicType>([
['defaultModel', 'defaultEffort'],
runCancellationLogic({ streamKey: props.streamKey ?? props.runId }),
['cancellationState'],
+ composerAttachmentsLogic({ attachmentsKey: props.interactionKey ?? props.runId }),
+ ['stagedAttachments', 'queuedAttachments'],
],
actions: [
runStreamLogic({ streamKey: props.streamKey ?? props.runId }),
@@ -650,6 +683,8 @@ export const runInteractionLogic = kea<runInteractionLogicType>([
['claimApplyBackTargets', 'releaseApplyBackTargets'],
runCancellationLogic({ streamKey: props.streamKey ?? props.runId }),
['requestCancellation'],
+ composerAttachmentsLogic({ attachmentsKey: props.interactionKey ?? props.runId }),
+ ['removeAttachments', 'setUploading', 'claimAttachmentsForQueue', 'releaseQueuedAttachments'],
],
})),
@@ -918,6 +953,7 @@ export const runInteractionLogic = kea<runInteractionLogicType>([
values.queuedMessages.length > 0
) {
actions.enqueueMessage(content)
+ actions.claimAttachmentsForQueue()
actions.resetComposerForm()
actions.flushQueue()
} else {
@@ -1233,14 +1269,17 @@ export const runInteractionLogic = kea<runInteractionLogicType>([
}
actions.flushQueue(steer)
},
+ // An emptied queue hands its files back rather than deleting them for the user.
removeQueuedMessage: () => {
if (!values.queuedMessages.length) {
actions.clearQueue()
+ actions.releaseQueuedAttachments()
}
},
updateQueuedMessage: () => {
if (!values.queuedMessages.length) {
actions.clearQueue()
+ actions.releaseQueuedAttachments()
}
},
// A turn that ended while a row was open skipped the drain, and an idle agent sends no further
@@ -1345,6 +1384,21 @@ export const runInteractionLogic = kea<runInteractionLogicType>([
}
}
actions.setSentMode(values.selectedMode)
+ // A drain carries the files queued with its text, not whatever the composer holds now.
+ const sending = source === 'queue' ? values.queuedAttachments : values.stagedAttachments
+ let artifactIds: string[] = []
+ if (sending.length > 0) {
+ actions.setUploading(true)
+ artifactIds = await uploadRunAttachments(
+ String(projectId),
+ taskId,
+ runId,
+ sending.map((attachment) => attachment.file)
+ )
+ if (!isCurrent()) {
+ return
+ }
+ }
// Wrap the outgoing content with the on-screen context block (invisible to the user —
// `runStreamLogic.unwrapUserMessageContent` strips it on replay, and the echo below is raw).
if (!isCurrent() || values.hasUnresolvedApproval) {
@@ -1356,6 +1410,7 @@ export const runInteractionLogic = kea<runInteractionLogicType>([
params: {
content: wrapWithPosthogContext(content, pendingContext),
...(steer ? { steer: true } : {}),
+ ...(artifactIds.length > 0 ? { artifact_ids: artifactIds } : {}),
},
})
if (!isCurrent()) {
@@ -1373,8 +1428,11 @@ export const runInteractionLogic = kea<runInteractionLogicType>([
throw new Error('The agent did not confirm this message')
}
// The SSE echo (`pushHumanMessage`) reopens the turn — always the raw text the user typed.
- actions.pushHumanMessage(content)
+ // The names ride along so the chips show on send, not when the turn echoes back.
+ actions.pushHumanMessage(content, stageAttachmentPreviews(sending))
markPendingContextSent(pendingContext)
+ // One attached while this send was in flight belongs to the next message.
+ actions.removeAttachments(sending.map((attachment) => attachment.id))
actions.finishTaskDraftDelivery()
} catch {
if (!isCurrent()) {
@@ -1400,6 +1458,8 @@ export const runInteractionLogic = kea<runInteractionLogicType>([
if (isCurrent()) {
actions.setSending(false)
}
+ // Drops the spinners off chips that outlived a failed send.
+ actions.setUploading(false)
}
},
@@ -1485,14 +1545,38 @@ export const runInteractionLogic = kea<runInteractionLogicType>([
pending_user_message: wrapWithPosthogContext(content, pendingContext),
}
)
+ // The task already exists here, so staged artifacts hold the files whether this request
+ // activates a warm run or cold-boots one.
+ // The queue rides along into the run this send starts, so its files come too.
+ const sending = [...values.queuedAttachments, ...values.stagedAttachments]
+ let stagedArtifactIds: string[] = []
+ if (sending.length > 0) {
+ actions.setUploading(true)
+ stagedArtifactIds = await uploadStagedTaskAttachments(
+ projectId,
+ taskId,
+ sending.map((attachment) => attachment.file)
+ )
+ if (!isCurrent()) {
+ return
+ }
+ }
const warmSubmission: WarmSubmission = { projectId, lease: null }
getWarmLogic()?.actions.prepareSubmit(warmSubmission)
actions.beginTaskDraftDelivery(content)
actions.resetComposerForm()
- actions.startOptimisticResume(content)
+ actions.startOptimisticResume(content, stageAttachmentPreviews(sending))
optimisticStarted = true
const result = await submitWithWarmRunRetry(
- (options) => tasksRunCreate(projectId, taskId, createRequest, options),
+ (options) =>
+ tasksRunCreate(
+ projectId,
+ taskId,
+ stagedArtifactIds.length > 0
+ ? { ...createRequest, pending_user_artifact_ids: stagedArtifactIds }
+ : createRequest,
+ options
+ ),
disposables
)
if (!isCurrent()) {
@@ -1506,6 +1590,8 @@ export const runInteractionLogic = kea<runInteractionLogicType>([
accepted = true
actions.finishTaskDraftDelivery()
markPendingContextSent(pendingContext)
+ // A failure leaves them staged for the retry.
+ actions.removeAttachments(sending.map((attachment) => attachment.id))
props.flushDraft?.()
const handoff = { run, streamKey, draft: values.composerForm.draft }
actions.attachOptimisticResume(taskId, run)
@@ -1535,6 +1621,8 @@ export const runInteractionLogic = kea<runInteractionLogicType>([
if (isCurrent()) {
actions.setStartingRun(false)
}
+ // Drops the spinners off chips that outlived a failed start.
+ actions.setUploading(false)
}
},
diff --git a/products/posthog_ai/frontend/logics/runStreamLogic.test.ts b/products/posthog_ai/frontend/logics/runStreamLogic.test.ts
index 7b69ffb8f732..a992f5e8d8c7 100644
--- a/products/posthog_ai/frontend/logics/runStreamLogic.test.ts
+++ b/products/posthog_ai/frontend/logics/runStreamLogic.test.ts
@@ -20,6 +20,7 @@ import { lookupToolRenderer, toolRegistry } from '../components/tool/toolRegistr
import { extractQueryResult } from '../components/tool/widgets/extractors'
import { defaultPermissionDecision } from '../policy/toolPolicy'
import type { AttachedContextItem } from '../types/contextTypes'
+import type { ThreadItem } from '../types/streamTypes'
import { TaskRunEnvironment, TaskRunStatus } from '../types/taskTypes'
import type { PermissionRequestFrame, StoredLogEntry } from '../types/wireTypes'
import { contextItemLine, wrapWithPosthogContext } from '../utils/posthogContextBlock'
@@ -1266,6 +1267,261 @@ describe('runStreamLogic', () => {
])
})
+ describe('attachments the send carried', () => {
+ const SANDBOX_URI = 'file:///tmp/workspace/.posthog/attachments/run-7/art-9/report.csv'
+
+ const foldReplay = (frames: StoredLogEntry[]): ThreadItem[] =>
+ foldLogToThread(
+ frames.map((entry) => ({ source: 'replay' as const, entry })),
+ { isResumeRun: false, taskId: 'task-3' }
+ ).threadItems
+
+ it('names a resource link on the message it arrived with', () => {
+ const items = foldReplay([
+ sessionUpdate({
+ sessionUpdate: 'user_message_chunk',
+ content: { type: 'text', text: 'Look here' },
+ }),
+ sessionUpdate({
+ sessionUpdate: 'user_message_chunk',
+ content: { type: 'resource_link', uri: 'file:///tmp/x/report.csv', name: 'report.csv' },
+ }),
+ ])
+
+ expect(items.filter((item) => item.type === 'human_message')).toEqual([
+ expect.objectContaining({
+ text: 'Look here',
+ attachments: [{ name: 'report.csv' }],
+ }),
+ ])
+ })
+
+ it('falls back to the file name in the uri when the block is unnamed', () => {
+ const items = foldReplay([
+ sessionUpdate({ sessionUpdate: 'user_message_chunk', content: { type: 'text', text: 'Look' } }),
+ sessionUpdate({
+ sessionUpdate: 'user_message_chunk',
+ content: { type: 'image', uri: 'file:///tmp/x/.posthog/attachments/run/art/my%20shot.png' },
+ }),
+ ])
+
+ expect(items[0].attachments).toEqual([
+ { name: 'my shot.png', taskId: 'task-3', runId: 'run', artifactId: 'art' },
+ ])
+ })
+
+ it('keeps two files on one message and does not repeat a name', () => {
+ const items = foldReplay([
+ notification('_posthog/user_message', {
+ content: [
+ { type: 'text', text: 'Compare these' },
+ { type: 'resource_link', uri: 'file:///a.csv', name: 'a.csv' },
+ { type: 'resource_link', uri: 'file:///b.csv', name: 'b.csv' },
+ { type: 'resource_link', uri: 'file:///b.csv', name: 'b.csv' },
+ ],
+ }),
+ ])
+
+ expect(items[0].attachments).toEqual([{ name: 'a.csv' }, { name: 'b.csv' }])
+ })
+
+ // The echo carrying the names is the one the text dedupe drops, so the names must survive it.
+ it('lands on a message the optimistic send already rendered', () => {
+ const frames: StoredLogEntry[] = [
+ notification('_client/human_message', { content: 'Look here' }),
+ sessionUpdate({
+ sessionUpdate: 'user_message_chunk',
+ content: { type: 'text', text: 'Look here' },
+ }),
+ sessionUpdate({
+ sessionUpdate: 'user_message_chunk',
+ content: { type: 'resource_link', uri: 'file:///a.csv', name: 'a.csv' },
+ }),
+ ]
+ const items = foldLogToThread(
+ frames.map((entry) => ({ source: 'live' as const, entry })),
+ { isResumeRun: false, taskId: 'task-3' }
+ ).threadItems
+
+ const humanMessages = items.filter((item) => item.type === 'human_message')
+ expect(humanMessages).toHaveLength(1)
+ expect(humanMessages[0].attachments).toEqual([{ name: 'a.csv' }])
+ })
+
+ it('leaves a message with no files without an attachments field', () => {
+ const items = foldReplay([
+ sessionUpdate({
+ sessionUpdate: 'user_message_chunk',
+ content: { type: 'text', text: 'Just text' },
+ }),
+ ])
+
+ expect(items[0].attachments).toBeUndefined()
+ })
+
+ it('recovers the run and artifact from the sandbox attachment path', () => {
+ const items = foldReplay([
+ sessionUpdate({
+ sessionUpdate: 'user_message_chunk',
+ content: { type: 'text', text: 'Look here' },
+ }),
+ sessionUpdate({
+ sessionUpdate: 'user_message_chunk',
+ content: { type: 'resource_link', uri: SANDBOX_URI, name: 'report.csv' },
+ }),
+ ])
+
+ expect(items[0].attachments).toEqual([
+ { name: 'report.csv', taskId: 'task-3', runId: 'run-7', artifactId: 'art-9' },
+ ])
+ })
+
+ it('leaves a path outside the attachments layout without ids', () => {
+ const items = foldReplay([
+ sessionUpdate({
+ sessionUpdate: 'user_message_chunk',
+ content: { type: 'text', text: 'Look here' },
+ }),
+ sessionUpdate({
+ sessionUpdate: 'user_message_chunk',
+ content: { type: 'resource_link', uri: 'file:///tmp/elsewhere/report.csv' },
+ }),
+ ])
+
+ expect(items[0].attachments).toEqual([{ name: 'report.csv' }])
+ })
+
+ it('shows the names an optimistic send staged, before any artifact exists', () => {
+ const items = foldReplay([
+ notification('_client/human_message', {
+ content: 'Look here',
+ attachments: [{ name: 'report.csv', previewId: 'preview-1' }],
+ }),
+ ])
+
+ expect(items[0].attachments).toEqual([{ name: 'report.csv', previewId: 'preview-1' }])
+ })
+
+ it('keeps a name with a broken percent escape instead of aborting the thread', () => {
+ const items = foldReplay([
+ sessionUpdate({
+ sessionUpdate: 'user_message_chunk',
+ content: { type: 'text', text: 'Look here' },
+ }),
+ sessionUpdate({
+ sessionUpdate: 'user_message_chunk',
+ content: { type: 'resource_link', uri: 'file:///tmp/bad%ZZ.png' },
+ }),
+ ])
+
+ expect(items[0].attachments).toEqual([{ name: 'bad%ZZ.png' }])
+ })
+
+ it('leaves a hidden block out, the same as it is left out of the text', () => {
+ const items = foldReplay([
+ notification('_posthog/user_message', {
+ content: [
+ { type: 'text', text: 'Look here' },
+ {
+ type: 'resource_link',
+ uri: 'file:///internal.md',
+ name: 'internal.md',
+ _meta: { ui: { hidden: true } },
+ },
+ ],
+ }),
+ ])
+
+ expect(items[0].attachments).toBeUndefined()
+ })
+
+ it('keeps two files that share a name apart, giving each its own artifact', () => {
+ const items = foldReplay([
+ notification('_client/human_message', {
+ content: 'Compare these',
+ attachments: [
+ { name: 'image.png', previewId: 'preview-1' },
+ { name: 'image.png', previewId: 'preview-2' },
+ ],
+ }),
+ sessionUpdate({
+ sessionUpdate: 'user_message_chunk',
+ content: {
+ type: 'resource_link',
+ uri: 'file:///w/.posthog/attachments/run-7/art-A/image.png',
+ name: 'image.png',
+ },
+ }),
+ sessionUpdate({
+ sessionUpdate: 'user_message_chunk',
+ content: {
+ type: 'resource_link',
+ uri: 'file:///w/.posthog/attachments/run-7/art-B/image.png',
+ name: 'image.png',
+ },
+ }),
+ ])
+
+ expect(items[0].attachments).toEqual([
+ {
+ name: 'image.png',
+ previewId: 'preview-1',
+ taskId: 'task-3',
+ runId: 'run-7',
+ artifactId: 'art-A',
+ },
+ {
+ name: 'image.png',
+ previewId: 'preview-2',
+ taskId: 'task-3',
+ runId: 'run-7',
+ artifactId: 'art-B',
+ },
+ ])
+ })
+
+ it('lands a file echoed in both wire forms once', () => {
+ const link = {
+ type: 'resource_link',
+ uri: 'file:///w/.posthog/attachments/run-7/art-A/report.csv',
+ name: 'report.csv',
+ }
+ const items = foldReplay([
+ notification('_posthog/user_message', { content: [{ type: 'text', text: 'Look' }, link] }),
+ sessionUpdate({ sessionUpdate: 'user_message_chunk', content: link }),
+ ])
+
+ expect(items[0].attachments).toHaveLength(1)
+ })
+
+ it('fills the ids onto that optimistic name rather than adding a second chip', () => {
+ const frames: StoredLogEntry[] = [
+ notification('_client/human_message', {
+ content: 'Look here',
+ attachments: [{ name: 'report.csv', previewId: 'preview-1' }],
+ }),
+ sessionUpdate({
+ sessionUpdate: 'user_message_chunk',
+ content: { type: 'resource_link', uri: SANDBOX_URI, name: 'report.csv' },
+ }),
+ ]
+ const items = foldLogToThread(
+ frames.map((entry) => ({ source: 'live' as const, entry })),
+ { isResumeRun: false, taskId: 'task-3' }
+ ).threadItems
+
+ expect(items[0].attachments).toEqual([
+ {
+ name: 'report.csv',
+ previewId: 'preview-1',
+ taskId: 'task-3',
+ runId: 'run-7',
+ artifactId: 'art-9',
+ },
+ ])
+ })
+ })
+
it('renders a seeded user turn into the thread on bootstrap replay', async () => {
const frames: StoredLogEntry[] = [
notification('_posthog/user_message', { content: 'Why did checkout drop?' }),
diff --git a/products/posthog_ai/frontend/logics/runStreamLogic.ts b/products/posthog_ai/frontend/logics/runStreamLogic.ts
index 5f295b84f743..2cf40bfc8f74 100644
--- a/products/posthog_ai/frontend/logics/runStreamLogic.ts
+++ b/products/posthog_ai/frontend/logics/runStreamLogic.ts
@@ -41,6 +41,8 @@ import type {
RunConnectionState,
RunTerminalStatus,
SdkSession,
+ StagedAttachment,
+ ThreadAttachment,
ThreadItem,
ThreadItemType,
ToolInvocation,
@@ -380,6 +382,97 @@ function isHiddenUserContent(content: unknown): boolean {
return content._meta.ui.hidden === true
}
+function uriPathSegments(uri: string): string[] {
+ let path = uri
+ try {
+ path = new URL(uri).pathname
+ } catch {
+ // A uri the parser rejects still splits on its separators below.
+ }
+ return path.split('/').filter(Boolean)
+}
+
+/** A segment with a broken percent escape stands as it is, rather than throwing through the whole fold. */
+function decodeUriSegment(segment: string): string {
+ try {
+ return decodeURIComponent(segment)
+ } catch {
+ return segment
+ }
+}
+
+/**
+ * The run and artifact a sandbox attachment path names, or null for any other path.
+ *
+ * The agent server writes each artifact to `.posthog/attachments/<runId>/<artifactId>/<name>`
+ * (`hydrateArtifactToPromptBlock`), and that layout is the only place the wire carries the ids. A path that
+ * does not match returns null and renders as a plain name, so a change there degrades rather than breaks.
+ */
+export function artifactRefFromUri(uri: string): { runId: string; artifactId: string } | null {
+ const segments = uriPathSegments(uri)
+ const marker = segments.lastIndexOf('attachments')
+ if (marker < 1 || segments[marker - 1] !== '.posthog' || segments.length < marker + 4) {
+ return null
+ }
+ return { runId: segments[marker + 1], artifactId: segments[marker + 2] }
+}
+
+/**
+ * A file the send carried, or null for any other content block. An attachment arrives as a `resource_link`
+ * to the copy the sandbox wrote to disk; an inline image arrives as an `image` block, which names the file
+ * only through that same `uri`.
+ */
+export function userAttachment(content: unknown): ThreadAttachment | null {
+ if (!isRecord(content) || (content.type !== 'resource_link' && content.type !== 'image')) {
+ return null
+ }
+ const uri = typeof content.uri === 'string' ? content.uri : ''
+ const named = typeof content.name === 'string' && content.name.trim() ? content.name.trim() : null
+ const fromUri = uri ? uriPathSegments(uri).at(-1) : undefined
+ const name = named ?? (fromUri ? decodeUriSegment(fromUri) : null)
+ if (!name) {
+ return null
+ }
+ return { name, ...(uri ? (artifactRefFromUri(uri) ?? {}) : {}) }
+}
+
+/**
+ * Identity is the artifact, never the name: two pasted screenshots are both `image.png`. A known artifact
+ * wins, so a file echoed in both wire forms lands once; otherwise it claims the first entry of that name
+ * still waiting for one, which a send uploads in order.
+ */
+function mergeAttachment(existing: ThreadAttachment[], incoming: ThreadAttachment): ThreadAttachment[] {
+ const byArtifact = incoming.artifactId
+ ? existing.findIndex((candidate) => candidate.artifactId === incoming.artifactId)
+ : -1
+ const target =
+ byArtifact !== -1
+ ? byArtifact
+ : existing.findIndex((candidate) => candidate.name === incoming.name && !candidate.artifactId)
+ if (target === -1) {
+ return [...existing, incoming]
+ }
+ return existing.map((candidate, position) => (position === target ? { ...candidate, ...incoming } : candidate))
+}
+
+/** What an optimistic send knows before its files have artifacts to point at. */
+function optimisticAttachments(value: unknown): ThreadAttachment[] {
+ if (!Array.isArray(value)) {
+ return []
+ }
+ return value.flatMap((entry) => {
+ if (!isRecord(entry) || typeof entry.name !== 'string' || !entry.name.trim()) {
+ return []
+ }
+ return [
+ {
+ name: entry.name.trim(),
+ ...(typeof entry.previewId === 'string' ? { previewId: entry.previewId } : {}),
+ },
+ ]
+ })
+}
+
function isRecord(value: unknown): value is Record<string, unknown> {
return typeof value === 'object' && value !== null && !Array.isArray(value)
}
@@ -1390,7 +1483,7 @@ function readPendingRunMessage(state: unknown, runId: string): PendingRunMessage
*/
export function foldLogToThread(
entries: StoredEntry[],
- options: { isResumeRun: boolean; pendingMessage?: PendingRunMessage | null }
+ options: { isResumeRun: boolean; pendingMessage?: PendingRunMessage | null; taskId?: string | null }
): FoldedThread {
let items: ThreadItem[] = []
const invocations = new Map<string, ToolInvocation>()
@@ -1412,18 +1505,40 @@ export function foldLogToThread(
let entryRunId: string | undefined
let pendingMessageSeen = false
let pendingInsertionIndex: number | undefined
+ let bufferedAttachments: ThreadAttachment[] = []
- const pushHuman = (text: string): void => {
+ const pushHuman = (text: string, attachments: ThreadAttachment[] = []): void => {
if (options.pendingMessage?.text === text && entryRunId === options.pendingMessage.runId) {
pendingMessageSeen = true
}
+ const carried = [...attachments, ...bufferedAttachments]
items = insertHumanMessageAtTurnStart(items, {
id: `human-${humanCount++}`,
type: 'human_message',
text,
complete: true,
+ ...(carried.length > 0 && { attachments: carried }),
...(timestamp !== undefined && { startedAt: timestamp }),
})
+ bufferedAttachments = []
+ }
+
+ /**
+ * A prompt's blocks arrive as consecutive frames with the text first, so the file lands on the message
+ * already rendered — including one an optimistic send drew, which the echo's text dedupe drops. That
+ * entry knows the name but not the ids, so a later frame for the same name fills them in.
+ */
+ const noteAttachment = (found: ThreadAttachment): void => {
+ // The sandbox path names the run and the artifact; the download endpoint also needs the task.
+ const attachment = found.artifactId && options.taskId ? { ...found, taskId: options.taskId } : found
+ for (let index = items.length - 1; index >= 0; index--) {
+ if (items[index].type === 'human_message') {
+ const existing = items[index].attachments ?? []
+ items[index] = { ...items[index], attachments: mergeAttachment(existing, attachment) }
+ return
+ }
+ }
+ bufferedAttachments = mergeAttachment(bufferedAttachments, attachment)
}
// Surface the context blocks a send was wrapped with as copyable debug rows (gated downstream by
@@ -1620,7 +1735,7 @@ export function foldLogToThread(
timestamp = !importedRun && !updateMeta?.imported && Number.isFinite(recordedAt) ? recordedAt : undefined
if (method === '_client/human_message') {
- pushHuman(String(params.content ?? ''))
+ pushHuman(String(params.content ?? ''), optimisticAttachments(params.attachments))
continue
}
if (method === '_client/error') {
@@ -1759,6 +1874,17 @@ export function foldLogToThread(
} else {
renderLiveHuman(userText)
}
+ if (Array.isArray(params.content)) {
+ for (const block of params.content) {
+ if (isHiddenUserContent(block)) {
+ continue
+ }
+ const attachment = userAttachment(block)
+ if (attachment) {
+ noteAttachment(attachment)
+ }
+ }
+ }
continue
}
if (method === '_posthog/console') {
@@ -1791,6 +1917,12 @@ export function foldLogToThread(
if (isHiddenUserContent(update.content)) {
continue
}
+ // An attached file is its own frame, carrying a resource link instead of text.
+ const attachment = userAttachment(update.content)
+ if (attachment) {
+ noteAttachment(attachment)
+ continue
+ }
const content = update.content as { text?: string } | undefined
const userText = String(content?.text ?? update.text ?? '')
if (source === 'replay') {
@@ -2096,8 +2228,12 @@ export interface runStreamLogicActions {
errorMessage: string
variant: 'crash' | 'error'
}
- pushHumanMessage: (content: string) => {
+ pushHumanMessage: (
+ content: string,
+ stagedAttachments?: StagedAttachment[]
+ ) => {
content: string
+ stagedAttachments: StagedAttachment[] | undefined
}
recoveryProgress: (
phase: RecoveryPhase,
@@ -2189,11 +2325,19 @@ export interface runStreamLogicActions {
sseReconnecting: (attempt: number) => {
attempt: number
}
- startOptimisticResume: (message: string) => {
+ startOptimisticResume: (
+ message: string,
+ stagedAttachments?: StagedAttachment[]
+ ) => {
message: string
+ stagedAttachments: StagedAttachment[] | undefined
}
- startOptimisticRun: (message?: string) => {
+ startOptimisticRun: (
+ message?: string,
+ stagedAttachments?: StagedAttachment[]
+ ) => {
message: string | undefined
+ stagedAttachments: StagedAttachment[] | undefined
}
streamEnded: () => {
value: true
@@ -2211,7 +2355,8 @@ export interface runStreamLogicMeta {
foldedThread: (
log: RunLog,
isBootstrapResumeRun: boolean,
- pendingRunMessage: PendingRunMessage | null
+ pendingRunMessage: PendingRunMessage | null,
+ bootstrappedTaskId: string | null
) => FoldedThread
errorTraceIds: (threadItems: ThreadItem[]) => Map<string, string>
latestTurnTraceId: (threadItems: ThreadItem[]) => string | null
@@ -2456,7 +2601,10 @@ export const runStreamLogic = kea<runStreamLogicType>([
*/
markTurnStarted: true,
/** Echoes the user's own message into the thread as a `client`-sourced log entry (the wire never replays a live turn). */
- pushHumanMessage: (content: string) => ({ content }),
+ pushHumanMessage: (content: string, stagedAttachments?: StagedAttachment[]) => ({
+ content,
+ stagedAttachments,
+ }),
/**
* Open a run optimistically before its real id exists: flips the thread to the provisioning
* indicator and, when a first message is given, renders it immediately as the human bubble. The
@@ -2465,9 +2613,15 @@ export const runStreamLogic = kea<runStreamLogicType>([
* created; the live SSE echo dedups the seeded message. Pure composition of `setRunOpening` +
* `pushHumanMessage`.
*/
- startOptimisticRun: (message?: string) => ({ message }),
+ startOptimisticRun: (message?: string, stagedAttachments?: StagedAttachment[]) => ({
+ message,
+ stagedAttachments,
+ }),
setPendingRunMessage: (message: PendingRunMessage | null) => ({ message }),
- startOptimisticResume: (message: string) => ({ message }),
+ startOptimisticResume: (message: string, stagedAttachments?: StagedAttachment[]) => ({
+ message,
+ stagedAttachments,
+ }),
appendResumeBoundary: true,
rollbackOptimisticResume: true,
attachOptimisticResume: (taskId: string, run: TaskRunDetailDTOApi) => ({ taskId, run }),
@@ -2877,9 +3031,13 @@ export const runStreamLogic = kea<runStreamLogicType>([
* Memoized on `log` identity, so it recomputes only when a frame is actually appended.
*/
foldedThread: [
- (s) => [s.log, s.isBootstrapResumeRun, s.pendingRunMessage],
- (log: RunLog, isResumeRun: boolean, pendingMessage: PendingRunMessage | null): FoldedThread =>
- foldLogToThread(log.entries, { isResumeRun, pendingMessage }),
+ (s) => [s.log, s.isBootstrapResumeRun, s.pendingRunMessage, s.bootstrappedTaskId],
+ (
+ log: RunLog,
+ isResumeRun: boolean,
+ pendingMessage: PendingRunMessage | null,
+ taskId: string | null
+ ): FoldedThread => foldLogToThread(log.entries, { isResumeRun, pendingMessage, taskId }),
],
errorTraceIds: [
(s) => [s.threadItems],
@@ -4102,10 +4260,10 @@ export const runStreamLogic = kea<runStreamLogicType>([
cache.streamTokenRefreshes = 0
cache.disposables.dispose('event-source')
},
- startOptimisticRun: ({ message }) => {
+ startOptimisticRun: ({ message, stagedAttachments }) => {
actions.setRunOpening(true)
if (message) {
- actions.pushHumanMessage(message)
+ actions.pushHumanMessage(message, stagedAttachments)
}
},
appendResumeBoundary: () => {
@@ -4123,13 +4281,13 @@ export const runStreamLogic = kea<runStreamLogicType>([
])
}
},
- startOptimisticResume: ({ message }) => {
+ startOptimisticResume: ({ message, stagedAttachments }) => {
const historyComplete = values.historyComplete
const turnComplete = values.turnComplete
const previousEntryCount = values.log.entries.length
actions.appendResumeBoundary()
actions.setRunOpening(true)
- actions.pushHumanMessage(message)
+ actions.pushHumanMessage(message, stagedAttachments)
cache.optimisticResume = {
entries: values.log.entries.slice(previousEntryCount),
message,
@@ -4172,7 +4330,7 @@ export const runStreamLogic = kea<runStreamLogicType>([
...(!resume.historyComplete ? { retainedMessage: resume.message } : {}),
})
},
- pushHumanMessage: ({ content }) => {
+ pushHumanMessage: ({ content, stagedAttachments }) => {
// The echo is always a live turn (replayed human turns render straight from the log), so
// stamp the turn start for per-turn duration metrics and append it as a `client`-sourced
// log entry the projection renders in order.
@@ -4188,7 +4346,13 @@ export const runStreamLogic = kea<runStreamLogicType>([
{
entry: {
type: 'notification',
- notification: { method: '_client/human_message', params: { content } },
+ notification: {
+ method: '_client/human_message',
+ params: {
+ content,
+ ...(stagedAttachments?.length ? { attachments: stagedAttachments } : {}),
+ },
+ },
},
source: 'client',
},
diff --git a/products/posthog_ai/frontend/scenes/TaskTracker/components/TaskComposer.tsx b/products/posthog_ai/frontend/scenes/TaskTracker/components/TaskComposer.tsx
index 55174f1ba248..4e3b2172b649 100644
--- a/products/posthog_ai/frontend/scenes/TaskTracker/components/TaskComposer.tsx
+++ b/products/posthog_ai/frontend/scenes/TaskTracker/components/TaskComposer.tsx
@@ -26,6 +26,7 @@ import {
} from 'products/posthog_ai/frontend/utils/composerModes'
import { AttachedContextBar } from '../../../components/composer/AttachedContextBar'
+import { ComposerAttachments, useComposerAttachmentPaste } from '../../../components/composer/ComposerAttachments'
import { ComposerModelEffortPickers } from '../../../components/composer/ComposerModelEffortPickers'
import { ComposerModePicker } from '../../../components/composer/ComposerModePicker'
import { ComposerModeShortcut } from '../../../components/composer/ComposerModeShortcut'
@@ -59,6 +60,10 @@ export function TaskComposer(): JSX.Element {
// The bound instance's key — 'scene' on `/ai` and `/tasks`, the panel key when embedded. The onboarding
// takeover is keyed the same way, so a starter prompt chosen on replay reaches this composer.
const panelId = useMountedLogic(taskTrackerSceneLogic).props.panelId
+ // Matches the key `taskTrackerSceneLogic` connects the attachments logic under, so the files this
+ // composer stages are the ones its submit uploads.
+ const attachmentsKey = panelId ?? 'scene'
+ const onPaste = useComposerAttachmentPaste(attachmentsKey)
// Buffer the description locally and debounce the write to kea so each keystroke is a cheap, isolated
// re-render instead of a store dispatch. `Composer.Root` already blocks send on an empty `draft.value`
@@ -66,6 +71,8 @@ export function TaskComposer(): JSX.Element {
const draft = useDebouncedDraft(newTaskData.description, (value) => setNewTaskData({ description: value }))
const textAreaRef = useRef<HTMLTextAreaElement>(null)
+ // The whole input frame is the drop target, so a file dropped anywhere on it attaches.
+ const frameRef = useRef<HTMLLabelElement>(null)
const handleSelectSuggestion = (item: SuggestionItem): void => {
applySuggestion(item)
@@ -111,15 +118,16 @@ export function TaskComposer(): JSX.Element {
loading={isSubmittingTask}
textAreaRef={textAreaRef}
>
- <Composer.Frame>
- <Composer.Header>
+ <Composer.Frame ref={frameRef}>
+ <Composer.Header className="flex flex-wrap items-center gap-1">
<AttachedContextBar />
+ <ComposerAttachments attachmentsKey={attachmentsKey} dropTargetRef={frameRef} />
</Composer.Header>
<Composer.Field>
<Composer.Placeholder>
{composerOverride?.placeholder ?? 'Describe the task in detail…'}
</Composer.Placeholder>
- <Composer.Textarea autoFocus data-attr="task-composer-input" />
+ <Composer.Textarea autoFocus onPaste={onPaste} data-attr="task-composer-input" />
</Composer.Field>
<Composer.Footer className="flex flex-wrap items-center gap-1 pl-2">
<ComposerModePicker
diff --git a/products/posthog_ai/frontend/scenes/TaskTracker/components/TaskRunComposer.tsx b/products/posthog_ai/frontend/scenes/TaskTracker/components/TaskRunComposer.tsx
index f4c1658398f5..178b19a5cb4f 100644
--- a/products/posthog_ai/frontend/scenes/TaskTracker/components/TaskRunComposer.tsx
+++ b/products/posthog_ai/frontend/scenes/TaskTracker/components/TaskRunComposer.tsx
@@ -1,6 +1,6 @@
import { useActions, useValues } from 'kea'
import { router } from 'kea-router'
-import { type MutableRefObject, type RefObject, useEffect, useMemo } from 'react'
+import { type MutableRefObject, type RefObject, useEffect, useMemo, useRef } from 'react'
import { projectLogic } from 'scenes/projectLogic'
import { AIConsentPopoverWrapper } from 'scenes/settings/organization/AIConsentPopoverWrapper'
@@ -17,6 +17,7 @@ import { cycleMode, getModesForRuntimeAdapter } from 'products/posthog_ai/fronte
import { AttachedContextBar } from '../../../components/composer/AttachedContextBar'
import { CommandResultCard } from '../../../components/composer/CommandResultCard'
+import { ComposerAttachments, useComposerAttachmentPaste } from '../../../components/composer/ComposerAttachments'
import { ComposerCommandMenu } from '../../../components/composer/ComposerCommandMenu'
import { ComposerModelEffortPickers } from '../../../components/composer/ComposerModelEffortPickers'
import { ComposerModePicker } from '../../../components/composer/ComposerModePicker'
@@ -91,6 +92,13 @@ export function TaskRunComposer({
flushDraftRef.current = draft.flush
}, [flushDraftRef, draft.flush])
+ // Matches the key `runInteractionLogic` connects the attachments logic under, so the files this
+ // composer stages are the ones its send uploads.
+ const attachmentsKey = logicProps.interactionKey ?? logicProps.runId
+ const onPaste = useComposerAttachmentPaste(attachmentsKey)
+ // The whole input frame is the drop target, so a file dropped anywhere on it attaches.
+ const frameRef = useRef<HTMLLabelElement>(null)
+
return (
<div onFocusCapture={() => setComposerFocused(true)} onBlurCapture={() => setComposerFocused(false)}>
<ComposerModeShortcut
@@ -150,9 +158,10 @@ export function TaskRunComposer({
/>
</Composer.Banner>
)}
- <Composer.Frame>
- <Composer.Header>
+ <Composer.Frame ref={frameRef}>
+ <Composer.Header className="flex flex-wrap items-center gap-1">
<AttachedContextBar />
+ <ComposerAttachments attachmentsKey={attachmentsKey} dropTargetRef={frameRef} />
</Composer.Header>
<ComposerCommandMenu commands={slashCommands}>
<Composer.Field>
@@ -161,7 +170,11 @@ export function TaskRunComposer({
? 'Send a message to start a new run, or type / for commands…'
: 'Send a follow-up message, or type / for commands…'}
</Composer.Placeholder>
- <Composer.Textarea data-attr="sandbox-composer-input" autoFocus={autoFocus} />
+ <Composer.Textarea
+ data-attr="sandbox-composer-input"
+ autoFocus={autoFocus}
+ onPaste={onPaste}
+ />
</Composer.Field>
</ComposerCommandMenu>
<Composer.Footer className="flex flex-wrap items-center gap-1 pl-2">
diff --git a/products/posthog_ai/frontend/scenes/TaskTracker/taskTrackerSceneLogic.test.ts b/products/posthog_ai/frontend/scenes/TaskTracker/taskTrackerSceneLogic.test.ts
index c838ada98ab0..e7e0ec3d7ca3 100644
--- a/products/posthog_ai/frontend/scenes/TaskTracker/taskTrackerSceneLogic.test.ts
+++ b/products/posthog_ai/frontend/scenes/TaskTracker/taskTrackerSceneLogic.test.ts
@@ -13,16 +13,24 @@ import { initKeaTests } from '~/test/init'
import { TaskRuntimeEnumApi } from 'products/tasks/frontend/generated/api.schemas'
import { attachedContextLogic, runStreamLogic } from '../../api/logics'
+import { composerAttachmentsLogic } from '../../logics/composerAttachmentsLogic'
import { composerOverrideLogic } from '../../logics/composerOverrideLogic'
import { composerSeedLogic } from '../../logics/composerSeedLogic'
import { runCancellationLogic } from '../../logics/runCancellationLogic'
import { runInteractionLogic } from '../../logics/runInteractionLogic'
import { TaskDraftPersistence, taskDraftStorageKey } from '../../logics/taskDraftPersistence'
+import { taskWarmLogic } from '../../logics/taskWarmLogic'
import { toolStreamEventsLogic } from '../../logics/toolStreamEventsLogic'
import { welcomeOverrideLogic } from '../../logics/welcomeOverrideLogic'
import { OriginProduct, Task, TaskRunEnvironment, TaskRunStatus } from '../../types/taskTypes'
+import { uploadRunAttachments, uploadStagedTaskAttachments } from '../../utils/artifactUpload'
import { taskTrackerSceneLogic } from './taskTrackerSceneLogic'
+jest.mock('../../utils/artifactUpload', () => ({
+ uploadRunAttachments: jest.fn(),
+ uploadStagedTaskAttachments: jest.fn(),
+}))
+
const buildTask = (overrides: Partial<Task> = {}): Task => ({
id: 'task-1',
task_number: 1,
@@ -47,6 +55,7 @@ describe('taskTrackerSceneLogic', () => {
let logic: ReturnType<typeof taskTrackerSceneLogic.build>
let createBody: Record<string, any> | null
let runBody: Record<string, any> | null
+ let cancelledWarmRuns: string[]
let toolEvents: ReturnType<typeof toolStreamEventsLogic.build>
const myConfigResponse = (resolved: Record<string, any> | null): Record<string, any> => ({
@@ -63,6 +72,7 @@ describe('taskTrackerSceneLogic', () => {
localStorage.clear()
createBody = null
runBody = null
+ cancelledWarmRuns = []
useMocks({
get: {
'/api/code/invites/check-access/': { has_access: true, has_loops_access: false },
@@ -80,6 +90,10 @@ describe('taskTrackerSceneLogic', () => {
runBody = (await request.json()) as Record<string, any>
return [200, { id: 'new-task', latest_run: { id: 'run-1' } }]
},
+ '/api/projects/:team/tasks/:taskId/runs/:id/cancel/': ({ params }) => {
+ cancelledWarmRuns.push(params.id as string)
+ return [200, {}]
+ },
},
})
initKeaTests()
@@ -98,6 +112,76 @@ describe('taskTrackerSceneLogic', () => {
toolEvents?.unmount()
})
+ describe('file attachments', () => {
+ let attachments: ReturnType<typeof composerAttachmentsLogic.build>
+
+ beforeEach(() => {
+ attachments = composerAttachmentsLogic({ attachmentsKey: 'scene' })
+ attachments.mount()
+ attachments.actions.addFiles([new File(['a'], 'rows.csv')])
+ })
+
+ afterEach(() => {
+ attachments.unmount()
+ })
+
+ // With no warm lease the create must give up warm reuse, which it does by leaving `branch` off.
+ it('stages the files on the cold task and attaches them to its run', async () => {
+ ;(uploadStagedTaskAttachments as jest.Mock).mockResolvedValue(['art-1'])
+ router.actions.push('/tasks/new')
+ logic.mount()
+ logic.actions.setNewTaskData({ description: 'Why does this chart look wrong?' })
+ await expectLogic(logic).toFinishAllListeners()
+ await expectLogic(logic, () => logic.actions.submitNewTask()).toFinishAllListeners()
+
+ expect(createBody).not.toHaveProperty('branch')
+ expect(uploadStagedTaskAttachments).toHaveBeenCalledWith('997', 'new-task', [expect.any(File)])
+ expect(runBody?.pending_user_artifact_ids).toEqual(['art-1'])
+ expect(attachments.values.attachments).toEqual([])
+ expect(attachments.values.uploading).toBe(false)
+ })
+
+ it('keeps the files staged and never starts the run when the upload fails', async () => {
+ ;(uploadStagedTaskAttachments as jest.Mock).mockRejectedValue(new Error('S3 said no'))
+ router.actions.push('/tasks/new')
+ logic.mount()
+ logic.actions.setNewTaskData({ description: 'Why does this chart look wrong?' })
+ await expectLogic(logic).toFinishAllListeners()
+ await expectLogic(logic, () => logic.actions.submitNewTask()).toFinishAllListeners()
+
+ expect(runBody).toBeNull()
+ expect(attachments.values.attachments).toHaveLength(1)
+ expect(attachments.values.uploading).toBe(false)
+ })
+
+ it('hands a leased warm run back when the upload to it fails', async () => {
+ ;(uploadRunAttachments as jest.Mock).mockRejectedValue(new Error('S3 said no'))
+ const warm = taskWarmLogic({ panelId: undefined })
+ warm.mount()
+ warm.actions.setWarmLease({ key: 'k', taskId: 'warm-task', runId: 'warm-run' })
+ router.actions.push('/tasks/new')
+ logic.mount()
+ logic.actions.setNewTaskData({ description: 'Why does this chart look wrong?' })
+ await expectLogic(logic).toFinishAllListeners()
+ await expectLogic(logic, () => logic.actions.submitNewTask()).toFinishAllListeners()
+
+ expect(cancelledWarmRuns).toEqual(['warm-run'])
+ warm.unmount()
+ })
+ })
+
+ it('still offers a warm run its branch when nothing is attached', async () => {
+ router.actions.push('/tasks/new')
+ logic.mount()
+ logic.actions.setNewTaskData({ description: 'Summarize a sample funnel' })
+ await expectLogic(logic).toFinishAllListeners()
+ await expectLogic(logic, () => logic.actions.submitNewTask()).toFinishAllListeners()
+
+ expect(createBody).toHaveProperty('branch', null)
+ expect(uploadStagedTaskAttachments).not.toHaveBeenCalled()
+ expect(runBody).not.toHaveProperty('pending_user_artifact_ids')
+ })
+
it.each([
['/ai', '/ai', { task: 'new-task' }],
['/tasks/new', '/tasks/new-task', {}],
diff --git a/products/posthog_ai/frontend/scenes/TaskTracker/taskTrackerSceneLogic.ts b/products/posthog_ai/frontend/scenes/TaskTracker/taskTrackerSceneLogic.ts
index c336eb5e0de5..6922352275e9 100644
--- a/products/posthog_ai/frontend/scenes/TaskTracker/taskTrackerSceneLogic.ts
+++ b/products/posthog_ai/frontend/scenes/TaskTracker/taskTrackerSceneLogic.ts
@@ -30,6 +30,7 @@ import type { IntegrationType } from '../../../../../frontend/src/types'
import { attachedContextItemKey, attachedContextLogic, runStreamLogic } from '../../api/logics'
import type { SuggestionGroup, SuggestionItem } from '../../api/primitives'
import { DEFAULT_HEADLINES, pickHeadline } from '../../api/primitives'
+import { composerAttachmentsLogic } from '../../logics/composerAttachmentsLogic'
import { composerOverrideLogic } from '../../logics/composerOverrideLogic'
import type { ComposerOverride } from '../../logics/composerOverrideLogic'
import { composerSeedLogic } from '../../logics/composerSeedLogic'
@@ -48,6 +49,9 @@ import { welcomeOverrideLogic } from '../../logics/welcomeOverrideLogic'
import type { AttachedContextItem } from '../../types/contextTypes'
import type { RepositoryConfig, Task } from '../../types/taskTypes'
import type { TaskListParams } from '../../types/taskTypes'
+import { uploadRunAttachments, uploadStagedTaskAttachments } from '../../utils/artifactUpload'
+import { rememberAttachmentPreview } from '../../utils/attachmentPreviews'
+import type { PendingAttachment } from '../../utils/attachments'
import {
buildRunCreateRequest,
buildServerResolvedRunCreateRequest,
@@ -166,6 +170,7 @@ const EMPTY_TASK_FORM: TaskCreateForm = {
export interface taskTrackerSceneLogicValues {
dataProcessingAccepted: boolean // aiConsentLogic
contextItems: AttachedContextItem[] // attachedContextLogic
+ stagedAttachments: PendingAttachment[] // composerAttachmentsLogic
composerOverride: ComposerOverride | null // composerOverrideLogic
seed: ComposerSeed | null // composerSeedLogic
integrations: IntegrationType[] | null // integrationsLogic
@@ -208,6 +213,12 @@ export interface taskTrackerSceneLogicActions {
keys: string[]
taskId: string
} // attachedContextLogic
+ removeAttachments: (ids: string[]) => {
+ ids: string[]
+ } // composerAttachmentsLogic
+ setUploading: (uploading: boolean) => {
+ uploading: boolean
+ } // composerAttachmentsLogic
consumeSeed: () => {
value: true
} // composerSeedLogic
@@ -406,6 +417,8 @@ export const taskTrackerSceneLogic = kea<taskTrackerSceneLogicType>([
// the resume endpoint for a task that doesn't exist yet.
taskWarmLogic({ panelId: props.panelId }),
['warmLease'],
+ composerAttachmentsLogic({ attachmentsKey: props.panelId ?? 'scene' }),
+ ['stagedAttachments'],
taskRunDefaultsLogic,
['defaultModel', 'defaultEffort', 'defaultRuntimeAdapter'],
],
@@ -424,6 +437,8 @@ export const taskTrackerSceneLogic = kea<taskTrackerSceneLogicType>([
['consumeSeed', 'setSeed'],
taskWarmLogic({ panelId: props.panelId }),
['noteDraft', 'prepareSubmit', 'consumeWarm', 'releaseWarm'],
+ composerAttachmentsLogic({ attachmentsKey: props.panelId ?? 'scene' }),
+ ['removeAttachments', 'setUploading'],
],
})),
@@ -680,6 +695,7 @@ export const taskTrackerSceneLogic = kea<taskTrackerSceneLogicType>([
cache.submittingTask = disposables
const projectId = String(values.currentProjectId)
const warmSubmission: WarmSubmission = { projectId, lease: null }
+ let warmConsumed = false
actions.prepareSubmit(warmSubmission)
// Optimistically open the thread on send: a `runStreamLogic` keyed by a client `streamKey`, seeded
@@ -719,9 +735,32 @@ export const taskTrackerSceneLogic = kea<taskTrackerSceneLogicType>([
)
cache.creationRoute = creationRouteKey(router.values.location.pathname, router.values.searchParams)
actions.setActiveCreation({ streamKey, interactionKey: streamKey })
- stream.actions.startOptimisticRun(description)
+ const sending = values.stagedAttachments
+ stream.actions.startOptimisticRun(
+ description,
+ sending.map(({ file }) => ({ name: file.name, previewId: rememberAttachmentPreview(file) }))
+ )
try {
+ // Files can only be uploaded against something that already exists. A warm lease names a task
+ // and a run, so they go onto that run and ride its activation. Without one there is nothing
+ // to upload to yet, so warm reuse is given up and the files are staged on the cold task.
+ const attachedFiles = sending.map(({ file }) => file)
+ const warmLease = warmSubmission.lease
+ const suppressWarmReuse = attachedFiles.length > 0 && !warmLease
+ let pendingUserArtifactIds: string[] = []
+ if (attachedFiles.length > 0) {
+ actions.setUploading(true)
+ if (warmLease) {
+ pendingUserArtifactIds = await uploadRunAttachments(
+ projectId,
+ warmLease.taskId,
+ warmLease.runId,
+ attachedFiles
+ )
+ }
+ }
+
const pendingUserMessage = wrapWithPosthogContext(description, seededContext)
const runPayload = {
branch: repositoryConfig.branch ?? null,
@@ -758,9 +797,11 @@ export const taskTrackerSceneLogic = kea<taskTrackerSceneLogicType>([
// Warm-reuse hints. The backend matches these against an idling warm Run and, on a hit,
// activates it in place and returns it as `latest_run` — no second Run is created. All of
// them are write-only and ignored on a cold create. `branch` must be present as a key
- // (even `null`) or reuse is never attempted at all. The model triple is left off when
- // the selection is untouched, so the backend resolves it for warm matching too.
- branch: runPayload.branch,
+ // (even `null`) or reuse is never attempted at all — which is how lease-less attachments
+ // opt out. The model triple is left off when the selection is untouched, so the backend
+ // resolves it for warm matching too.
+ ...(suppressWarmReuse ? {} : { branch: runPayload.branch }),
+ ...(pendingUserArtifactIds.length > 0 ? { pending_user_artifact_ids: pendingUserArtifactIds } : {}),
...(pinnedRequest
? {
runtime_adapter: pinnedRequest.runtime_adapter,
@@ -777,6 +818,7 @@ export const taskTrackerSceneLogic = kea<taskTrackerSceneLogicType>([
disposables
)
actions.consumeWarm(warmSubmission, newTask.latest_run?.id ?? null)
+ warmConsumed = true
if (!disposables.isDisposed && values.activeCreation?.streamKey === streamKey) {
interaction.props.flushDraft?.()
@@ -795,8 +837,23 @@ export const taskTrackerSceneLogic = kea<taskTrackerSceneLogicType>([
let createdRun = newTask.latest_run
let runId = createdRun?.id
if (!runId) {
+ // Also covers a warm miss: reaching here after a lease upload means the create did not
+ // activate that warm run, and a cold create drops its warm hints — including the artifact
+ // ids — so the files are staged again rather than left on a run nothing will read.
+ const stagedArtifactIds =
+ attachedFiles.length > 0
+ ? await uploadStagedTaskAttachments(projectId, newTask.id, attachedFiles)
+ : []
const runResponse = await submitWithWarmRunRetry(
- (options) => tasksRunCreate(projectId, newTask.id, runRequest, options),
+ (options) =>
+ tasksRunCreate(
+ projectId,
+ newTask.id,
+ stagedArtifactIds.length > 0
+ ? { ...runRequest, pending_user_artifact_ids: stagedArtifactIds }
+ : runRequest,
+ options
+ ),
disposables
)
createdRun = runResponse.latest_run
@@ -860,6 +917,8 @@ export const taskTrackerSceneLogic = kea<taskTrackerSceneLogicType>([
if (creationIsActive || values.newTaskData.description.trim() === description) {
actions.resetNewTaskData()
}
+ // Only what this send took. A failure leaves them staged, since the restored draft is resent.
+ actions.removeAttachments(sending.map(({ id }) => id))
cache.submittingTask = null
actions.submitNewTaskSuccess()
actions.loadTasks(values.taskListParams)
@@ -869,6 +928,12 @@ export const taskTrackerSceneLogic = kea<taskTrackerSceneLogicType>([
return
}
actions.releaseApplyBackTargets(streamKey)
+ // `prepareSubmit` took the lease out of `taskWarmLogic`, so only `consumeWarm` releases it,
+ // and a run that never got a message would hold a warm slot until its idle timeout.
+ if (!warmConsumed) {
+ actions.consumeWarm(warmSubmission, null)
+ warmConsumed = true
+ }
if (values.activeCreation?.streamKey === streamKey) {
interaction.props.flushDraft?.()
const unsent = [
@@ -892,6 +957,8 @@ export const taskTrackerSceneLogic = kea<taskTrackerSceneLogicType>([
if (cache.submittingTask === disposables) {
cache.submittingTask = null
}
+ // Drops the spinners off chips that outlived a failed send.
+ actions.setUploading(false)
}
},
openExistingTask: ({ task }) => {
diff --git a/products/posthog_ai/frontend/types/streamTypes.ts b/products/posthog_ai/frontend/types/streamTypes.ts
index 089051b6f49c..30e853a9796c 100644
--- a/products/posthog_ai/frontend/types/streamTypes.ts
+++ b/products/posthog_ai/frontend/types/streamTypes.ts
@@ -118,6 +118,25 @@ export interface TurnCompleteEvent {
streamKey: string
}
+/** What a send hands its own echo: enough to draw the file before it has an artifact. */
+export interface StagedAttachment {
+ name: string
+ previewId?: string
+}
+
+/**
+ * A file a send carried. The ids are what let the thread build a download URL, and are absent until the
+ * upload lands — until then `previewId` finds the staged file to draw instead.
+ */
+export interface ThreadAttachment {
+ name: string
+ taskId?: string
+ runId?: string
+ artifactId?: string
+ /** Looks up the staged `File` in `attachmentPreviews`, so a send can show its image before it uploads. */
+ previewId?: string
+}
+
export type ThreadItemType =
| 'human_message'
| 'assistant_message'
@@ -147,6 +166,8 @@ export interface ThreadItem {
endedAt?: number
/** For `human_message`, `assistant_message`, and `assistant_thought` items. */
text?: string
+ /** For `human_message` items — the files the send carried. */
+ attachments?: ThreadAttachment[]
/** Whether the assistant message buffer is finalized. */
complete?: boolean
/** For `tool_invocation` items — the keyed tool call id (look up in `toolInvocations`). */
diff --git a/products/posthog_ai/frontend/utils/artifactUpload.test.ts b/products/posthog_ai/frontend/utils/artifactUpload.test.ts
new file mode 100644
index 000000000000..495442396233
--- /dev/null
+++ b/products/posthog_ai/frontend/utils/artifactUpload.test.ts
@@ -0,0 +1,121 @@
+import {
+ tasksRunsArtifactsFinalizeUploadCreate,
+ tasksRunsArtifactsPrepareUploadCreate,
+ tasksStagedArtifactsFinalizeUploadCreate,
+ tasksStagedArtifactsPrepareUploadCreate,
+} from 'products/tasks/frontend/generated/api'
+
+import { uploadRunAttachments, uploadStagedTaskAttachments } from './artifactUpload'
+
+jest.mock('products/tasks/frontend/generated/api', () => ({
+ tasksRunsArtifactsFinalizeUploadCreate: jest.fn(),
+ tasksRunsArtifactsPrepareUploadCreate: jest.fn(),
+ tasksStagedArtifactsFinalizeUploadCreate: jest.fn(),
+ tasksStagedArtifactsPrepareUploadCreate: jest.fn(),
+}))
+
+const prepareRun = tasksRunsArtifactsPrepareUploadCreate as jest.Mock
+const finalizeRun = tasksRunsArtifactsFinalizeUploadCreate as jest.Mock
+const prepareStaged = tasksStagedArtifactsPrepareUploadCreate as jest.Mock
+const finalizeStaged = tasksStagedArtifactsFinalizeUploadCreate as jest.Mock
+
+function preparedArtifact(id: string, name: string, contentType: string): Record<string, unknown> {
+ return {
+ id,
+ name,
+ type: 'user_attachment',
+ source: 'posthog_ai',
+ size: 3,
+ content_type: contentType,
+ storage_path: `artifacts/${id}/${name}`,
+ expires_in: 900,
+ presigned_post: { url: 'https://s3.test/upload', fields: { key: `artifacts/${id}/${name}`, policy: 'p' } },
+ }
+}
+
+describe('artifact uploads', () => {
+ let fetchMock: jest.Mock
+
+ beforeEach(() => {
+ jest.clearAllMocks()
+ fetchMock = jest.fn().mockResolvedValue({ ok: true })
+ global.fetch = fetchMock as unknown as typeof fetch
+ })
+
+ it('does nothing at all when there is nothing to upload', async () => {
+ await expect(uploadRunAttachments('1', 'task', 'run', [])).resolves.toEqual([])
+ expect(prepareRun).not.toHaveBeenCalled()
+ expect(fetchMock).not.toHaveBeenCalled()
+ })
+
+ it('prepares, uploads and finalizes a run attachment, answering with its id', async () => {
+ prepareRun.mockResolvedValue({ artifacts: [preparedArtifact('art-1', 'notes.md', 'text/markdown')] })
+ finalizeRun.mockResolvedValue({ artifacts: [] })
+
+ const ids = await uploadRunAttachments('1', 'task', 'run', [new File(['abc'], 'notes.md')])
+
+ expect(ids).toEqual(['art-1'])
+ expect(prepareRun).toHaveBeenCalledWith('1', 'task', 'run', {
+ artifacts: [
+ {
+ name: 'notes.md',
+ type: 'user_attachment',
+ source: 'posthog_ai',
+ size: 3,
+ content_type: 'text/markdown',
+ },
+ ],
+ })
+ expect(finalizeRun).toHaveBeenCalledWith('1', 'task', 'run', {
+ artifacts: [
+ {
+ id: 'art-1',
+ name: 'notes.md',
+ type: 'user_attachment',
+ source: 'posthog_ai',
+ storage_path: 'artifacts/art-1/notes.md',
+ content_type: 'text/markdown',
+ },
+ ],
+ })
+ })
+
+ it('posts the presigned form fields verbatim, ahead of the file', async () => {
+ prepareStaged.mockResolvedValue({ artifacts: [preparedArtifact('art-2', 'shot.png', 'image/png')] })
+ finalizeStaged.mockResolvedValue({ artifacts: [] })
+
+ await uploadStagedTaskAttachments('1', 'task', [new File(['abc'], 'shot.png')])
+
+ expect(prepareStaged).toHaveBeenCalledWith('1', 'task', expect.anything())
+ const [url, request] = fetchMock.mock.calls[0]
+ expect(url).toBe('https://s3.test/upload')
+ expect(request.method).toBe('POST')
+ const body = request.body as FormData
+ expect([...body.keys()]).toEqual(['key', 'policy', 'file'])
+ expect(body.get('key')).toBe('artifacts/art-2/shot.png')
+ })
+
+ it('rejects the batch when one upload fails, and never finalizes', async () => {
+ prepareRun.mockResolvedValue({
+ artifacts: [
+ preparedArtifact('art-1', 'a.md', 'text/markdown'),
+ preparedArtifact('art-2', 'b.md', 'text/markdown'),
+ ],
+ })
+ fetchMock.mockResolvedValueOnce({ ok: true }).mockResolvedValueOnce({ ok: false })
+
+ await expect(
+ uploadRunAttachments('1', 'task', 'run', [new File(['a'], 'a.md'), new File(['b'], 'b.md')])
+ ).rejects.toThrow("Couldn't upload b.md")
+ expect(finalizeRun).not.toHaveBeenCalled()
+ })
+
+ it('rejects when the server prepares a different number of uploads than were asked for', async () => {
+ prepareRun.mockResolvedValue({ artifacts: [preparedArtifact('art-1', 'a.md', 'text/markdown')] })
+
+ await expect(
+ uploadRunAttachments('1', 'task', 'run', [new File(['a'], 'a.md'), new File(['b'], 'b.md')])
+ ).rejects.toThrow("Couldn't prepare every attachment for upload")
+ expect(fetchMock).not.toHaveBeenCalled()
+ })
+})
diff --git a/products/posthog_ai/frontend/utils/artifactUpload.ts b/products/posthog_ai/frontend/utils/artifactUpload.ts
new file mode 100644
index 000000000000..56de526bee4a
--- /dev/null
+++ b/products/posthog_ai/frontend/utils/artifactUpload.ts
@@ -0,0 +1,126 @@
+import {
+ tasksRunsArtifactsFinalizeUploadCreate,
+ tasksRunsArtifactsPrepareUploadCreate,
+ tasksStagedArtifactsFinalizeUploadCreate,
+ tasksStagedArtifactsPrepareUploadCreate,
+} from 'products/tasks/frontend/generated/api'
+import { TaskRunArtifactTypeEnumApi } from 'products/tasks/frontend/generated/api.schemas'
+
+import { inferContentType } from './attachments'
+
+const ATTACHMENT_SOURCE = 'posthog_ai'
+
+/** The staged and run-level endpoints take and return the same shapes, so one cycle serves both. */
+interface ArtifactUploadEndpoints {
+ prepare: (artifacts: PrepareRequest[]) => Promise<{ artifacts: PreparedArtifact[] }>
+ finalize: (artifacts: FinalizeRequest[]) => Promise<unknown>
+}
+
+interface PrepareRequest {
+ name: string
+ type: typeof TaskRunArtifactTypeEnumApi.UserAttachment
+ source: string
+ size: number
+ content_type: string
+}
+
+interface PreparedArtifact {
+ id: string
+ name: string
+ type: string
+ source?: string
+ size: number
+ content_type?: string
+ storage_path: string
+ presigned_post: { url: string; fields: Record<string, string> }
+}
+
+interface FinalizeRequest {
+ id: string
+ name: string
+ type: typeof TaskRunArtifactTypeEnumApi.UserAttachment
+ source: string
+ storage_path: string
+ content_type: string
+}
+
+function prepareRequestFor(file: File): PrepareRequest {
+ return {
+ name: file.name,
+ type: TaskRunArtifactTypeEnumApi.UserAttachment,
+ source: ATTACHMENT_SOURCE,
+ size: file.size,
+ content_type: inferContentType(file.name),
+ }
+}
+
+async function uploadToPresignedPost(prepared: PreparedArtifact, 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)) {
+ formData.append(key, value)
+ }
+ formData.append('file', file, prepared.name)
+
+ const response = await fetch(prepared.presigned_post.url, { method: 'POST', body: formData })
+ if (!response.ok) {
+ throw new Error(`Couldn't upload ${prepared.name}`)
+ }
+}
+
+/**
+ * A single failure rejects the whole call: a message that silently arrives with fewer files than the user
+ * attached is worse than one that refuses to send.
+ */
+async function uploadArtifacts(endpoints: ArtifactUploadEndpoints, files: File[]): Promise<string[]> {
+ if (files.length === 0) {
+ return []
+ }
+
+ const { artifacts: prepared } = await endpoints.prepare(files.map(prepareRequestFor))
+ if (prepared.length !== files.length) {
+ throw new Error("Couldn't prepare every attachment for upload")
+ }
+
+ await Promise.all(prepared.map((artifact, index) => uploadToPresignedPost(artifact, files[index])))
+
+ await endpoints.finalize(
+ prepared.map((artifact) => ({
+ id: artifact.id,
+ name: artifact.name,
+ type: TaskRunArtifactTypeEnumApi.UserAttachment,
+ source: ATTACHMENT_SOURCE,
+ storage_path: artifact.storage_path,
+ content_type: artifact.content_type ?? inferContentType(artifact.name),
+ }))
+ )
+
+ return prepared.map((artifact) => artifact.id)
+}
+
+/** Hold files on a task whose run does not exist yet; the ids go to run create as `pending_user_artifact_ids`. */
+export async function uploadStagedTaskAttachments(projectId: string, taskId: string, files: File[]): Promise<string[]> {
+ return uploadArtifacts(
+ {
+ prepare: (artifacts) => tasksStagedArtifactsPrepareUploadCreate(projectId, taskId, { artifacts }),
+ finalize: (artifacts) => tasksStagedArtifactsFinalizeUploadCreate(projectId, taskId, { artifacts }),
+ },
+ files
+ )
+}
+
+/** Attach files to an existing run; the ids go to `user_message` as `params.artifact_ids`. */
+export async function uploadRunAttachments(
+ projectId: string,
+ taskId: string,
+ runId: string,
+ files: File[]
+): Promise<string[]> {
+ return uploadArtifacts(
+ {
+ prepare: (artifacts) => tasksRunsArtifactsPrepareUploadCreate(projectId, taskId, runId, { artifacts }),
+ finalize: (artifacts) => tasksRunsArtifactsFinalizeUploadCreate(projectId, taskId, runId, { artifacts }),
+ },
+ files
+ )
+}
diff --git a/products/posthog_ai/frontend/utils/attachmentPreviews.ts b/products/posthog_ai/frontend/utils/attachmentPreviews.ts
new file mode 100644
index 000000000000..83ffc22de158
--- /dev/null
+++ b/products/posthog_ai/frontend/utils/attachmentPreviews.ts
@@ -0,0 +1,35 @@
+/**
+ * Holds the `File` a send staged, so its message can draw the real image while the upload is in flight.
+ *
+ * Keyed by an id the echo carries, since a name is not unique across messages. An entry only matters until
+ * the artifact exists — a reload finds an empty registry and falls back to the artifact — so the oldest are
+ * dropped rather than held for the life of the tab.
+ */
+
+const MAX_TRACKED_PREVIEWS = 20
+
+const previews = new Map<string, File>()
+let sequence = 0
+
+export function rememberAttachmentPreview(file: File): string {
+ const id = `preview-${++sequence}`
+ previews.set(id, file)
+ while (previews.size > MAX_TRACKED_PREVIEWS) {
+ const oldest = previews.keys().next()
+ if (oldest.done) {
+ break
+ }
+ previews.delete(oldest.value)
+ }
+ return id
+}
+
+export function getAttachmentPreview(previewId: string | undefined): File | undefined {
+ return previewId ? previews.get(previewId) : undefined
+}
+
+/** Test seam: module state would otherwise leak between cases. */
+export function clearAttachmentPreviews(): void {
+ previews.clear()
+ sequence = 0
+}
diff --git a/products/posthog_ai/frontend/utils/attachments.test.ts b/products/posthog_ai/frontend/utils/attachments.test.ts
new file mode 100644
index 000000000000..c9b8c0b753d7
--- /dev/null
+++ b/products/posthog_ai/frontend/utils/attachments.test.ts
@@ -0,0 +1,89 @@
+import {
+ ATTACHMENT_MAX_SIZE_BYTES,
+ PDF_ATTACHMENT_MAX_SIZE_BYTES,
+ attachmentRejectionReason,
+ formatFileSize,
+ inferContentType,
+ isImageAttachment,
+ maxSizeBytesFor,
+} from './attachments'
+
+function fileOfSize(name: string, size: number): File {
+ const file = new File(['x'], name)
+ Object.defineProperty(file, 'size', { value: size })
+ return file
+}
+
+describe('inferContentType', () => {
+ it.each([
+ ['screenshot.png', 'image/png'],
+ ['SCREENSHOT.PNG', 'image/png'],
+ ['report.pdf', 'application/pdf'],
+ ['notes.md', 'text/markdown'],
+ ['rows.csv', 'text/csv'],
+ ])('reads %s as %s', (name, contentType) => {
+ expect(inferContentType(name)).toBe(contentType)
+ })
+
+ it('falls back to a binary type for an unknown or absent extension', () => {
+ expect(inferContentType('mystery.qqq')).toBe('application/octet-stream')
+ expect(inferContentType('Makefile')).toBe('application/octet-stream')
+ })
+
+ it('ignores what the browser claims the file is', () => {
+ const file = new File(['# notes'], 'notes.md', { type: 'application/octet-stream' })
+ expect(inferContentType(file.name)).toBe('text/markdown')
+ })
+})
+
+describe('isImageAttachment', () => {
+ it('recognizes the raster types an agent can look at', () => {
+ expect(isImageAttachment('a.png')).toBe(true)
+ expect(isImageAttachment('a.jpeg')).toBe(true)
+ expect(isImageAttachment('a.webp')).toBe(true)
+ })
+
+ it('does not treat a document as an image', () => {
+ expect(isImageAttachment('a.pdf')).toBe(false)
+ expect(isImageAttachment('a.csv')).toBe(false)
+ })
+})
+
+describe('maxSizeBytesFor', () => {
+ it('holds PDFs to the lower ceiling the model accepts', () => {
+ expect(maxSizeBytesFor('spec.pdf')).toBe(PDF_ATTACHMENT_MAX_SIZE_BYTES)
+ expect(maxSizeBytesFor('spec.png')).toBe(ATTACHMENT_MAX_SIZE_BYTES)
+ })
+})
+
+describe('attachmentRejectionReason', () => {
+ it('accepts a file inside the limit', () => {
+ expect(attachmentRejectionReason(fileOfSize('a.png', 1024))).toBeNull()
+ })
+
+ it('rejects an empty file', () => {
+ expect(attachmentRejectionReason(fileOfSize('a.png', 0))).toBe('a.png is empty')
+ })
+
+ it('rejects a file over the general limit and names the limit', () => {
+ expect(attachmentRejectionReason(fileOfSize('a.png', ATTACHMENT_MAX_SIZE_BYTES + 1))).toBe(
+ 'a.png is over the 30MB limit'
+ )
+ })
+
+ it('rejects a PDF over the PDF limit while the same size passes as a PNG', () => {
+ const size = PDF_ATTACHMENT_MAX_SIZE_BYTES + 1
+ expect(attachmentRejectionReason(fileOfSize('spec.pdf', size))).toBe('spec.pdf is over the 10MB limit for PDFs')
+ expect(attachmentRejectionReason(fileOfSize('spec.png', size))).toBeNull()
+ })
+})
+
+describe('formatFileSize', () => {
+ it.each([
+ [512, '512 B'],
+ [2048, '2 KB'],
+ [1024 * 1024 * 3.5, '3.5 MB'],
+ ])('renders %s bytes as %s', (bytes, formatted) => {
+ expect(formatFileSize(bytes)).toBe(formatted)
+ })
+})
diff --git a/products/posthog_ai/frontend/utils/attachments.ts b/products/posthog_ai/frontend/utils/attachments.ts
new file mode 100644
index 000000000000..81c2698f6c94
--- /dev/null
+++ b/products/posthog_ai/frontend/utils/attachments.ts
@@ -0,0 +1,101 @@
+/** A file staged in the composer, not yet uploaded. */
+export interface PendingAttachment {
+ id: string
+ file: File
+ /** Promised to a message waiting in the queue, so a draft send leaves it alone. */
+ queued?: boolean
+}
+
+/** The artifact API's ceiling: `size` on a prepare request is capped at 31457280. */
+export const ATTACHMENT_MAX_SIZE_BYTES = 30 * 1024 * 1024
+/** A larger PDF is rejected by the model, so it would fail the run after a successful upload. */
+export const PDF_ATTACHMENT_MAX_SIZE_BYTES = 10 * 1024 * 1024
+export const MAX_ATTACHMENTS_PER_MESSAGE = 10
+
+const CONTENT_TYPE_BY_EXTENSION: Record<string, string> = {
+ bmp: 'image/bmp',
+ c: 'text/plain',
+ cc: 'text/plain',
+ conf: 'text/plain',
+ cpp: 'text/plain',
+ css: 'text/css',
+ csv: 'text/csv',
+ gif: 'image/gif',
+ go: 'text/plain',
+ h: 'text/plain',
+ html: 'text/html',
+ ini: 'text/plain',
+ java: 'text/plain',
+ jpeg: 'image/jpeg',
+ jpg: 'image/jpeg',
+ js: 'text/javascript',
+ json: 'application/json',
+ jsx: 'text/javascript',
+ log: 'text/plain',
+ md: 'text/markdown',
+ pdf: 'application/pdf',
+ png: 'image/png',
+ py: 'text/x-python',
+ rb: 'text/plain',
+ rs: 'text/plain',
+ sh: 'text/x-shellscript',
+ sql: 'application/sql',
+ svg: 'image/svg+xml',
+ toml: 'application/toml',
+ ts: 'text/typescript',
+ tsx: 'text/typescript',
+ txt: 'text/plain',
+ webp: 'image/webp',
+ xml: 'application/xml',
+ yaml: 'application/yaml',
+ yml: 'application/yaml',
+ zip: 'application/zip',
+}
+
+const DEFAULT_CONTENT_TYPE = 'application/octet-stream'
+
+export function getFileExtension(fileName: string): string {
+ const parts = fileName.split('.')
+ return parts.length > 1 ? (parts.at(-1)?.toLowerCase() ?? '') : ''
+}
+
+/**
+ * Derived from the extension rather than read off `File.type`: browsers report some text files as
+ * `application/octet-stream`, and the sandbox derives the agent's view of the file from what is recorded
+ * here.
+ */
+export function inferContentType(fileName: string): string {
+ return CONTENT_TYPE_BY_EXTENSION[getFileExtension(fileName)] ?? DEFAULT_CONTENT_TYPE
+}
+
+export function maxSizeBytesFor(fileName: string): number {
+ return getFileExtension(fileName) === 'pdf' ? PDF_ATTACHMENT_MAX_SIZE_BYTES : ATTACHMENT_MAX_SIZE_BYTES
+}
+
+export function isImageAttachment(fileName: string): boolean {
+ return inferContentType(fileName).startsWith('image/')
+}
+
+export function attachmentRejectionReason(file: File): string | null {
+ if (file.size === 0) {
+ return `${file.name} is empty`
+ }
+ const maxSizeBytes = maxSizeBytesFor(file.name)
+ if (file.size > maxSizeBytes) {
+ const maxMb = Math.floor(maxSizeBytes / (1024 * 1024))
+ return getFileExtension(file.name) === 'pdf'
+ ? `${file.name} is over the ${maxMb}MB limit for PDFs`
+ : `${file.name} is over the ${maxMb}MB limit`
+ }
+ return null
+}
+
+export function formatFileSize(bytes: number): string {
+ if (bytes < 1024) {
+ return `${bytes} B`
+ }
+ if (bytes < 1024 * 1024) {
+ return `${Math.round(bytes / 1024)} KB`
+ }
+ return `${(bytes / (1024 * 1024)).toFixed(1)} MB`
+}