Evenfire is an intelligence layer platform for running LLM agents that take real actions, on your infrastructure
TypeScript
// @vitest-environment jsdom
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
import type { ChatComposerStateContextValue } from '@contexts/ChatComposerStateContext'
import { cleanup, fireEvent, render, screen, waitFor } from '@testing-library/react'
import { readFileSync } from 'node:fs'
import { resolve } from 'node:path'
import {
CODEX_COMPOSER_MAX_IMAGE_BYTES,
CODEX_COMPOSER_MAX_IMAGE_DIMENSION,
COMPOSER_MAX_ATTACHMENTS,
COMPOSER_MAX_IMAGE_BYTES,
COMPOSER_MAX_TOTAL_IMAGE_BASE64_BYTES,
GROK_COMPOSER_MAX_IMAGE_BYTES,
} from '@constants/attachments'
import type { HostModelsResult } from '@hooks/useChatStore'
import { readComposerFile } from '@lib/composerFileAdmission'
import {
type ImageInputDecision,
imageInputBlockMessage,
} from '../../../../../src/imageInputDecision'
import type { WorkflowRecipeListResult } from '../../../../../src/types'
import type {
ComposerFileAttachment,
ComposerImageAttachment,
ComposerReferenceAttachment,
FailedAgentSend,
} from '../../../uiTypes'
import { ComposerPanel } from '../ComposerPanel'
// Resolve the stylesheet relative to THIS test file (not process.cwd()) so the
// test passes regardless of the directory vitest is launched from. CI runs it
// from desktop-app/ui, where the old cwd-relative 'ui/src/styles.css' resolved
// to desktop-app/ui/ui/src/styles.css and failed with ENOENT.
const composerStyles = readFileSync(resolve(__dirname, '../../../styles.css'), 'utf8')
const composerState: ChatComposerStateContextValue = {
composerImageAttachments: [],
composerFileAttachments: [],
composerFileRefusals: [],
composerReferenceAttachments: [],
agentSending: false,
agentError: null,
failedAgentSend: null,
activeChatId: null,
activeMessageCount: 0,
composerFocusRequestId: 0,
requestComposerFocus: vi.fn(),
}
const draftState = { value: '', set: vi.fn() }
/** Stable action spies so guard tests can assert what did (not) reach the controller. */
const actionsMock = {
clearComposerSendError: vi.fn(),
handleAddComposerImageAttachments: vi.fn(),
handleUpdateComposerImageAttachment: vi.fn(),
handleRemoveComposerImageAttachment: vi.fn(),
handleAddComposerFiles: vi.fn(),
handleRemoveComposerFileAttachment: vi.fn(),
handleAddComposerReferenceAttachments: vi.fn(),
handleRemoveComposerReferenceAttachment: vi.fn(),
handleClearComposerAttachments: vi.fn(),
handleSendAgentMessage: vi.fn(),
handleRetryFailedAgentSend: vi.fn(),
handleRecoverFailedAgentSend: vi.fn(),
handleDiscardFailedAgentSend: vi.fn(),
}
vi.mock('@contexts/AgentChatActionsContext', () => ({
useAgentChatActionsContext: () => actionsMock,
}))
vi.mock('@contexts/ChatComposerStateContext', () => ({
useChatComposerStateContext: () => composerState,
}))
vi.mock('@contexts/McpRuntimeContext', () => ({
useMcpRuntimeContext: () => ({ hostRuntimeStatus: null, activeLlmProvider: null }),
}))
vi.mock('@contexts/NavigationContext', () => ({
useNavigationContext: () => ({ selectedAgent: 'agent-1' }),
}))
vi.mock('@hooks/domain/useContextsDataController', () => ({
useContextsDataController: () => ({ sharedFilesByContext: {}, refreshSharedFiles: vi.fn() }),
}))
vi.mock('@hooks/domain/useMcpServersDataController', () => ({
useMcpServersDataController: () => ({
selectedAgentMcpServers: [],
agentContextByName: {},
refresh: vi.fn(),
}),
}))
vi.mock('@hooks/useComposerDraft', () => ({
useComposerDraft: () => [draftState.value, draftState.set],
}))
/**
* Shared model-selection view (issue #654). Mutable so a test can swap the
* capability/state per case; every field of the hook's real return shape must be
* present because ModelSelector reads them directly.
*/
const composerModelState = {
data: {
provider: 'claude',
hostDefault: 'claude-haiku-4-5',
sessionModel: null,
degraded: false,
models: [{ name: 'claude-haiku-4-5', displayName: 'Haiku 4.5' }],
} as HostModelsResult | null | undefined,
loading: false,
saving: false,
error: null as string | null,
state: 'ready' as 'unloaded' | 'loading' | 'ready' | 'unavailable',
effectiveModel: 'claude-haiku-4-5',
intentModel: null as string | null,
pending: false,
selectionUnsettled: false,
conflicted: false,
confirmedRevision: null as number | null,
imageInput: { state: 'unknown' as const, reason: 'model_unknown' },
canAttachImages: false,
imageBlockMessage: null as string | null,
visualSendBlocked: false,
selectModel: vi.fn(async () => true),
clearError: vi.fn(),
refresh: vi.fn(async () => undefined),
}
vi.mock('@hooks/useHostModels', () => ({
useHostModels: () => composerModelState,
}))
vi.mock('../ComposerAgentFilesModal', () => ({ ComposerAgentFilesModal: () => null }))
const globalFilesMock = vi.hoisted(() => ({
showComposerItem: false,
modalProps: undefined as { attachedIds: readonly string[] } | undefined,
}))
vi.mock('@constants/agentFeatures', async importOriginal => ({
...(await importOriginal<typeof import('@constants/agentFeatures')>()),
get SHOW_GLOBAL_FILE_SYSTEM_COMPOSER_ITEM() {
return globalFilesMock.showComposerItem
},
}))
vi.mock('../ComposerGlobalFilesModal', () => ({
ComposerGlobalFilesModal: (props: { attachedIds: readonly string[] }) => {
globalFilesMock.modalProps = props
return null
},
}))
const annotationCanvasMock = vi.hoisted(() => ({
onSave: undefined as ((updated: ComposerImageAttachment) => void) | undefined,
}))
vi.mock('../AnnotationCanvas', () => ({
AnnotationCanvas: (props: { onSave: (updated: ComposerImageAttachment) => void }) => {
annotationCanvasMock.onSave = props.onSave
return null
},
}))
function setScrollHeight(textarea: HTMLTextAreaElement, value: number) {
Object.defineProperty(textarea, 'scrollHeight', { configurable: true, value })
}
beforeEach(() => {
Object.defineProperty(window, 'clerum', {
configurable: true,
value: {
workflows: {
list: vi.fn(async (): Promise<WorkflowRecipeListResult> => ({ items: [], count: 0 })),
},
},
})
})
afterEach(() => {
cleanup()
annotationCanvasMock.onSave = undefined
globalFilesMock.showComposerItem = false
globalFilesMock.modalProps = undefined
draftState.value = ''
draftState.set.mockReset()
Object.assign(composerState, {
composerImageAttachments: [],
composerFileAttachments: [],
composerFileRefusals: [],
composerReferenceAttachments: [],
agentSending: false,
agentError: null,
failedAgentSend: null,
activeChatId: null,
activeMessageCount: 0,
composerFocusRequestId: 0,
})
Object.assign(composerModelState, {
visualSendBlocked: false,
canAttachImages: false,
imageBlockMessage: null,
imageInput: { state: 'unknown', reason: 'model_unknown' },
data: {
provider: 'claude',
hostDefault: 'claude-haiku-4-5',
sessionModel: null,
degraded: false,
models: [{ name: 'claude-haiku-4-5', displayName: 'Haiku 4.5' }],
},
effectiveModel: 'claude-haiku-4-5',
})
for (const spy of Object.values(actionsMock)) spy.mockReset()
delete (window as Partial<typeof window>).clerum
})
function cssRule(selector: string) {
const match = composerStyles.match(new RegExp(`${selector}\\s*\\{([^}]*)\\}`))
return match?.[1] ?? ''
}
describe.each([
['inline new-chat', true],
['docked conversation', false],
])('ComposerPanel %s', (_name, inline) => {
it('grows, caps scrolling, and shrinks its text viewport without covering it with actions', () => {
const { container, rerender } = render(<ComposerPanel inline={inline} />)
const textarea = screen.getByTestId('chat-input') as HTMLTextAreaElement
const shell = container.querySelector('.composer-input-shell')
const viewport = container.querySelector('.composer-textarea-viewport')
const toolbar = container.querySelector('.composer-input-actions')
expect(shell).toBeTruthy()
expect(viewport).toBeTruthy()
expect(toolbar).toBeTruthy()
expect(shell?.contains(viewport)).toBe(true)
expect(shell?.contains(toolbar)).toBe(true)
expect(viewport?.contains(toolbar)).toBe(false)
setScrollHeight(textarea, 96)
fireEvent.change(textarea, { target: { value: 'first\nsecond\nthird' } })
expect(textarea.style.height).toBe('96px')
expect(textarea.style.overflowY).toBe('hidden')
setScrollHeight(textarea, 1000)
fireEvent.change(textarea, { target: { value: 'a very long draft' } })
expect(textarea.style.height).toBe('240px')
expect(textarea.style.overflowY).toBe('auto')
draftState.value = 'a very long draft'
rerender(<ComposerPanel inline={inline} />)
draftState.value = ''
setScrollHeight(textarea, inline ? 48 : 56)
rerender(<ComposerPanel inline={inline} />)
expect(textarea.style.height).toBe(inline ? '48px' : '56px')
expect(textarea.style.overflowY).toBe('hidden')
})
it('keeps context and model popovers outside the clipped text viewport', () => {
const { container } = render(<ComposerPanel inline={inline} />)
const shell = container.querySelector('.composer-input-shell')
const viewport = container.querySelector('.composer-textarea-viewport')
fireEvent.click(screen.getByRole('button', { name: 'Add context' }))
fireEvent.mouseEnter(screen.getByRole('menuitem', { name: /Plugins/ }))
fireEvent.click(screen.getByRole('button', { name: /Model — Haiku 4.5/ }))
const contextMenu = container.querySelector('.composer-reference-menu-panel')
// The submenu is portaled to document.body, so it lives outside the
// component subtree entirely — query the whole document for it.
const submenu = document.querySelector('.composer-reference-submenu')
const modelMenu = container.querySelector('.model-selector-popover')
expect(contextMenu).toBeTruthy()
expect(submenu).toBeTruthy()
expect(modelMenu).toBeTruthy()
expect(viewport?.contains(contextMenu)).toBe(false)
expect(viewport?.contains(submenu)).toBe(false)
expect(viewport?.contains(modelMenu)).toBe(false)
expect(shell?.contains(contextMenu)).toBe(true)
// Portaled: no longer a descendant of the composer shell (or the container).
expect(shell?.contains(submenu)).toBe(false)
expect(container.contains(submenu)).toBe(false)
expect(shell?.contains(modelMenu)).toBe(true)
expect(cssRule('\\.composer-input-shell')).not.toMatch(/overflow\s*:/)
expect(cssRule('\\.composer-textarea-viewport')).toMatch(/overflow\s*:\s*hidden/)
})
it('focuses on a trusted request and preserves selection when already focused', () => {
const otherInput = document.createElement('input')
document.body.append(otherInput)
otherInput.focus()
const { rerender } = render(<ComposerPanel inline={inline} />)
const textarea = screen.getByTestId('chat-input') as HTMLTextAreaElement
composerState.composerFocusRequestId = 1
rerender(<ComposerPanel inline={inline} />)
expect(document.activeElement).toBe(textarea)
draftState.value = 'preserve this draft'
rerender(<ComposerPanel inline={inline} />)
textarea.setSelectionRange(4, 8)
composerState.composerFocusRequestId = 2
rerender(<ComposerPanel inline={inline} />)
expect(textarea.selectionStart).toBe(4)
expect(textarea.selectionEnd).toBe(8)
otherInput.remove()
})
})
describe('ComposerPanel EvenDrive picker', () => {
it('hands the picker the ids of the global files already in the composer, and only those', () => {
globalFilesMock.showComposerItem = true
Object.assign(composerState, {
composerReferenceAttachments: [
{
id: 'global-file:main:aaaa',
type: 'global_file',
resourceId: 'aaaa',
drive: 'main',
gfsUri: 'gfs://main/aaaa',
label: 'a.md',
version: 1,
bytes: 1,
},
{
id: 'agent-file:ctx:/b.md',
type: 'agent_file',
contextId: 'ctx',
filesystemName: 'ctx',
path: '/b.md',
kind: 'file',
label: 'b.md',
},
],
})
render(<ComposerPanel inline={false} />)
// Liveness witness: the modal is not mounted until EvenDrive is chosen.
expect(globalFilesMock.modalProps).toBeUndefined()
fireEvent.click(screen.getByRole('button', { name: 'Add context' }))
fireEvent.click(screen.getByRole('menuitem', { name: /EvenDrive/ }))
expect(globalFilesMock.modalProps?.attachedIds).toEqual(['global-file:main:aaaa'])
})
})
describe('ComposerPanel reference submenu portaling', () => {
it('portals the submenu out of the drawer overflow-clipping ancestors', () => {
// Reproduce the narrow-drawer DOM: the composer sits inside ancestors that
// clip overflow. In-flow, the submenu was cropped by them; portaled, it is
// no longer their descendant.
const { container } = render(
<div className="chat-drawer">
<div className="chat-drawer__surface">
<div className="agent-workspace-body-slot">
<ComposerPanel inline={false} />
</div>
</div>
</div>
)
fireEvent.click(screen.getByRole('button', { name: 'Add context' }))
fireEvent.mouseEnter(screen.getByRole('menuitem', { name: /Plugins/ }))
const submenu = document.querySelector('.composer-reference-submenu')
expect(submenu).toBeTruthy()
// Not a descendant of the overflow-clipping ancestor, the drawer, or the
// rendered component subtree — it hangs off document.body.
expect(container.querySelector('.agent-workspace-body-slot')?.contains(submenu)).toBe(false)
expect(container.querySelector('.chat-drawer')?.contains(submenu)).toBe(false)
expect(container.contains(submenu)).toBe(false)
expect(submenu?.parentElement).toBe(document.body)
})
it('keeps the menu mounted through a mousedown on a portaled submenu item so its click fires', async () => {
// A clickable plugin so the submenu holds a real menuitem, not an empty state.
window.clerum.workflows.list = vi.fn(
async (): Promise<WorkflowRecipeListResult> => ({
items: [{ metadata: { namespace: 'ns', name: 'plug-a' } }],
count: 1,
})
)
render(<ComposerPanel inline={false} />)
fireEvent.click(screen.getByRole('button', { name: 'Add context' }))
fireEvent.mouseEnter(screen.getByRole('menuitem', { name: /Plugins/ }))
const item = await screen.findByRole('menuitem', { name: 'plug-a' })
// The real pointer sequence is mousedown then click. The click-outside guard
// listens on mousedown; with a single-ref guard the portaled item would read
// as "outside", close the menu, and unmount the item before the click.
fireEvent.mouseDown(item)
expect(screen.queryByRole('menuitem', { name: 'plug-a' })).not.toBeNull()
fireEvent.click(item)
expect(actionsMock.handleAddComposerReferenceAttachments).toHaveBeenCalledWith([
expect.objectContaining({ type: 'plugin', name: 'plug-a', namespace: 'ns' }),
])
})
})
// ---------------------------------------------------------------------------
// Issue #654: composer image attachments through real DOM events.
//
// These drive the real component. jsdom has no file dialog and no DataTransfer,
// so the helpers below stand in for exactly those unavailable browser
// primitives; the accept filter, the FileReader byte preparation and every guard
// stay real. The jsdom environment does provide URL.createObjectURL, so chip
// previews are real `blob:` object URLs.
// ---------------------------------------------------------------------------
/** PNG signature bytes, so "the file's bytes reached the controller" is literal. */
const PNG_BYTES = [137, 80, 78, 71, 13, 10, 26, 10, 0, 1, 2, 3]
/** JPEG SOI/APP0 bytes for the cases that carry a .jpg file. */
const JPEG_BYTES = [255, 216, 255, 224, 0, 16, 74, 70, 73, 70]
function imageFile(name: string, type: string, bytes: Uint8Array | number[] = PNG_BYTES): File {
return new File([new Uint8Array(bytes)], name, { type })
}
/** Reported `File.size` without allocating the payload (the picker guards on size). */
function imageFileWithReportedSize(name: string, type: string, sizeBytes: number): File {
const file = imageFile(name, type)
Object.defineProperty(file, 'size', { configurable: true, value: sizeBytes })
return file
}
const MIB = 1024 * 1024
/** A PNG of exactly `sizeBytes` real bytes; `marker` makes its bytes unique. */
function pngOfSize(name: string, sizeBytes: number, marker: number): File {
const bytes = new Uint8Array(sizeBytes)
bytes.set(PNG_BYTES)
bytes[PNG_BYTES.length] = marker
return imageFile(name, 'image/png', bytes)
}
/** An attached PNG whose canonical base64 decodes to exactly `decodedBytes` bytes. */
function attachedImage(id: string, name: string, decodedBytes: number): ComposerImageAttachment {
const padding = (3 - (decodedBytes % 3)) % 3
const dataBase64 = `iVBORw0KGgo${'A'.repeat(Math.ceil(decodedBytes / 3) * 4 - padding - 11)}${'='.repeat(padding)}`
return {
id,
name,
mimeType: 'image/png',
dataBase64,
sizeBytes: decodedBytes,
previewDataUrl: 'data:image/png;base64,iVBORw0KGgo=',
}
}
function pngIhdrFile(name: string, width: number, height: number): File {
const bytes = new Uint8Array(8 + 8 + 13)
bytes.set([0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a], 0)
const view = new DataView(bytes.buffer)
view.setUint32(8, 13)
bytes.set([0x49, 0x48, 0x44, 0x52], 12)
view.setUint32(16, width)
view.setUint32(20, height)
return new File([bytes], name, { type: 'image/png' })
}
function decodedBytes(base64: string): number[] {
return Array.from(atob(base64), char => char.charCodeAt(0))
}
function addedBatches(): ComposerImageAttachment[][] {
return actionsMock.handleAddComposerImageAttachments.mock.calls.map(([batch]) => batch)
}
/** Asserts that the controller received exactly one batch with one prepared image. */
function expectSinglePreparedImage(): ComposerImageAttachment {
const batches = addedBatches()
expect(batches).toHaveLength(1)
expect(batches[0]).toHaveLength(1)
const attachment = batches[0]?.[0]
if (!attachment) throw new Error('expected one prepared image attachment')
return attachment
}
function pickerInput(container: HTMLElement): HTMLInputElement {
const input = container.querySelector('.composer-file-input')
if (!(input instanceof HTMLInputElement)) throw new Error('expected the composer file picker')
return input
}
function capabilityMessage(decision: ImageInputDecision): string {
const message = imageInputBlockMessage(composerModelState.effectiveModel, decision)
if (!message) throw new Error('expected a blocking image-capability message')
return message
}
/**
* jsdom cannot open a native file dialog, so the picker click is the boundary
* that stays observable: intercept it, and let the test fire the `change` event
* that a real dialog would produce.
*/
async function withPickerClick<T>(run: (timesClicked: () => number) => Promise<T>): Promise<T> {
const clickSpy = vi.spyOn(HTMLInputElement.prototype, 'click').mockImplementation(() => {})
try {
return await run(() => clickSpy.mock.calls.length)
} finally {
clickSpy.mockRestore()
}
}
const SUPPORTED_CAPABILITY = {
imageInput: { state: 'supported', reason: 'supported' } as ImageInputDecision,
canAttachImages: true,
imageBlockMessage: null,
visualSendBlocked: false,
}
const BLOCKED_CAPABILITIES: Array<[string, ImageInputDecision]> = [
['unsupported', { state: 'unsupported', reason: 'model_unsupported' }],
['unverified', { state: 'unknown', reason: 'model_unknown' }],
]
describe.each(BLOCKED_CAPABILITIES)(
'ComposerPanel with %s image capability',
(_label, decision) => {
const blockMessage = capabilityMessage(decision)
beforeEach(() => {
Object.assign(composerModelState, {
imageInput: decision,
canAttachImages: false,
imageBlockMessage: blockMessage,
visualSendBlocked: true,
})
})
// #678: capability gates sending images, never selecting them. The picked
// image is kept so the user can switch to a capable model; the send-time
// notice (covered below) explains the block once the chip is pending.
it('opens the Upload Files picker and attaches the picked image', async () => {
await withPickerClick(async timesClicked => {
const { container } = render(<ComposerPanel inline />)
fireEvent.click(screen.getByRole('button', { name: 'Add context' }))
fireEvent.click(screen.getByRole('menuitem', { name: 'Upload Files' }))
expect(timesClicked()).toBe(1)
fireEvent.change(pickerInput(container), {
target: { files: [imageFile('photo.png', 'image/png')] },
})
await waitFor(() =>
expect(actionsMock.handleAddComposerImageAttachments).toHaveBeenCalledTimes(1)
)
expect(expectSinglePreparedImage()).toMatchObject({ name: 'photo.png' })
expect(screen.queryByText(blockMessage)).toBeNull()
})
})
it('attaches a pasted image', async () => {
render(<ComposerPanel inline />)
const textarea = screen.getByTestId('chat-input')
const notPrevented = fireEvent.paste(textarea, {
clipboardData: { files: [imageFile('clipboard.png', 'image/png')], items: [] },
})
// Consumed like a real paste so the image never lands as text either.
expect(notPrevented).toBe(false)
await waitFor(() =>
expect(actionsMock.handleAddComposerImageAttachments).toHaveBeenCalledTimes(1)
)
expect(expectSinglePreparedImage().mimeType).toBe('image/png')
expect(screen.queryByText(blockMessage)).toBeNull()
})
it('attaches a dropped image and clears the drop overlay', async () => {
const { container } = render(<ComposerPanel inline />)
const shell = container.querySelector('.composer-input-shell') as HTMLElement
fireEvent.dragEnter(shell, { dataTransfer: { types: ['Files'] } })
expect(screen.getByText('Drop files here')).toBeTruthy()
const notPrevented = fireEvent.drop(shell, {
dataTransfer: { files: [imageFile('dropped.png', 'image/png')], types: ['Files'] },
})
expect(notPrevented).toBe(false)
await waitFor(() =>
expect(actionsMock.handleAddComposerImageAttachments).toHaveBeenCalledTimes(1)
)
expect(expectSinglePreparedImage()).toMatchObject({ name: 'dropped.png' })
expect(screen.queryByText('Drop files here')).toBeNull()
expect(screen.queryByText(blockMessage)).toBeNull()
})
}
)
describe('ComposerPanel with an image-capable model', () => {
beforeEach(() => {
Object.assign(composerModelState, SUPPORTED_CAPABILITY)
})
it('opens the picker and hands the picked PNG bytes to the controller', async () => {
await withPickerClick(async timesClicked => {
const { container } = render(<ComposerPanel inline />)
fireEvent.click(screen.getByRole('button', { name: 'Add context' }))
fireEvent.click(screen.getByRole('menuitem', { name: 'Upload Files' }))
expect(timesClicked()).toBe(1)
const fileInput = pickerInput(container)
// Any document can be picked (#678); the picker no longer filters to images.
expect(fileInput.accept).toBe('')
expect(fileInput.multiple).toBe(true)
fireEvent.change(fileInput, { target: { files: [imageFile('photo.png', 'image/png')] } })
await waitFor(() => expect(actionsMock.handleAddComposerImageAttachments).toHaveBeenCalled())
const attachment = expectSinglePreparedImage()
expect(attachment).toMatchObject({
name: 'photo.png',
mimeType: 'image/png',
sizeBytes: PNG_BYTES.length,
})
expect(decodedBytes(attachment.dataBase64)).toEqual(PNG_BYTES)
// createObjectURL is available here, so the chip preview is an object URL
// for the picked file rather than the FileReader fallback.
expect(attachment.previewDataUrl).toMatch(/^blob:/)
expect(screen.queryByRole('alert')).toBeNull()
})
})
it('prepares a pasted PNG once when the clipboard reports it as both file and item', async () => {
render(<ComposerPanel inline />)
const textarea = screen.getByTestId('chat-input')
const pasted = imageFile('image.png', 'image/png')
fireEvent.paste(textarea, {
clipboardData: {
files: [pasted],
items: [{ kind: 'file', getAsFile: () => pasted }],
},
})
await waitFor(() => expect(actionsMock.handleAddComposerImageAttachments).toHaveBeenCalled())
const attachment = expectSinglePreparedImage()
// A generic clipboard name is replaced with a distinguishable pasted-image name.
expect(attachment.name).toMatch(/^pasted-image-\d+-1\.png$/)
expect(attachment.mimeType).toBe('image/png')
expect(decodedBytes(attachment.dataBase64)).toEqual(PNG_BYTES)
})
it('prepares a dropped JPEG and clears the drop overlay after the drop', async () => {
const { container } = render(<ComposerPanel inline />)
const shell = container.querySelector('.composer-input-shell') as HTMLElement
fireEvent.dragEnter(shell, { dataTransfer: { types: ['Files'] } })
expect(screen.getByText('Drop files here')).toBeTruthy()
fireEvent.drop(shell, {
dataTransfer: {
files: [imageFile('dropped.jpg', 'image/jpeg', JPEG_BYTES)],
types: ['Files'],
},
})
await waitFor(() => expect(actionsMock.handleAddComposerImageAttachments).toHaveBeenCalled())
const attachment = expectSinglePreparedImage()
expect(attachment).toMatchObject({
name: 'dropped.jpg',
mimeType: 'image/jpeg',
sizeBytes: JPEG_BYTES.length,
})
expect(decodedBytes(attachment.dataBase64)).toEqual(JPEG_BYTES)
expect(screen.queryByText('Drop files here')).toBeNull()
})
it('infers the mime type from the file name when the OS reports none', async () => {
const { container } = render(<ComposerPanel inline />)
fireEvent.change(pickerInput(container), {
target: { files: [imageFile('screenshot.png', '')] },
})
await waitFor(() => expect(actionsMock.handleAddComposerImageAttachments).toHaveBeenCalled())
expect(expectSinglePreparedImage().mimeType).toBe('image/png')
})
it('routes a non-PNG/JPEG file to the document path and the valid image to the image path', async () => {
draftState.value = 'abc'
const { container } = render(<ComposerPanel inline />)
fireEvent.change(pickerInput(container), {
target: {
files: [imageFile('animation.gif', 'image/gif'), imageFile('good.png', 'image/png')],
},
})
await waitFor(() => expect(actionsMock.handleAddComposerImageAttachments).toHaveBeenCalled())
expect(expectSinglePreparedImage().name).toBe('good.png')
// Liveness witness: the document path ran, with the draft for the body budget.
expect(actionsMock.handleAddComposerFiles).toHaveBeenCalledTimes(1)
const [documents, draft] = actionsMock.handleAddComposerFiles.mock.calls[0] as [File[], string]
expect(documents.map(file => file.name)).toEqual(['animation.gif'])
expect(draft).toBe('abc')
expect(screen.queryByRole('alert')).toBeNull()
})
it('explains an oversize image and attaches nothing', async () => {
const { container } = render(<ComposerPanel inline />)
fireEvent.change(pickerInput(container), {
target: {
files: [imageFileWithReportedSize('huge.png', 'image/png', COMPOSER_MAX_IMAGE_BYTES + 1)],
},
})
await waitFor(() => expect(screen.getByRole('alert')).toBeTruthy())
expect(screen.getByRole('alert').textContent).toBe('huge.png is too large. Max size is 3 MB.')
expect(actionsMock.handleAddComposerImageAttachments).not.toHaveBeenCalled()
})
it('attaches 20 images from one pick and says how many did not fit', async () => {
expect(COMPOSER_MAX_ATTACHMENTS).toBe(20)
const { container } = render(<ComposerPanel inline />)
const files = Array.from({ length: 22 }, (_, index) =>
imageFile(`photo-${index + 1}.png`, 'image/png', [...PNG_BYTES, index])
)
fireEvent.change(pickerInput(container), { target: { files } })
await waitFor(() =>
expect(actionsMock.handleAddComposerImageAttachments).toHaveBeenCalledTimes(1)
)
const [batch] = addedBatches()
expect(batch?.map(attachment => attachment.name)).toEqual(
files.slice(0, 20).map(file => file.name)
)
expect(screen.getByRole('alert').textContent).toBe(
'A message can carry at most 20 attachments; 2 images were not added.'
)
})
it('refuses an image that would push the message past the combined image budget', async () => {
const { container } = render(<ComposerPanel inline />)
const rawBytes = Math.floor(COMPOSER_MAX_IMAGE_BYTES * 0.8)
const base64Bytes = Math.ceil(rawBytes / 3) * 4
expect(base64Bytes * 2).toBeLessThanOrEqual(COMPOSER_MAX_TOTAL_IMAGE_BASE64_BYTES)
expect(base64Bytes * 3).toBeGreaterThan(COMPOSER_MAX_TOTAL_IMAGE_BASE64_BYTES)
const files = ['first.png', 'second.png', 'third.png'].map((name, index) => {
const bytes = new Uint8Array(rawBytes)
bytes.set(PNG_BYTES)
bytes[PNG_BYTES.length] = index
return imageFile(name, 'image/png', bytes)
})
fireEvent.change(pickerInput(container), { target: { files } })
await waitFor(() =>
expect(actionsMock.handleAddComposerImageAttachments).toHaveBeenCalledTimes(1)
)
const [batch] = addedBatches()
expect(batch?.map(attachment => attachment.name)).toEqual(['first.png', 'second.png'])
expect(screen.getByRole('alert').textContent).toBe(
'third.png does not fit in this message: the images in one message are limited to 8 MB in total. Send the attached images first or remove one.'
)
})
it('refuses an annotation save that would exceed the combined image budget', () => {
const already: ComposerImageAttachment = {
id: 'already-attached',
name: 'already.png',
mimeType: 'image/png',
dataBase64: 'A'.repeat(COMPOSER_MAX_TOTAL_IMAGE_BASE64_BYTES - 32),
sizeBytes: 1,
previewDataUrl: 'data:image/png;base64,AAAA',
}
const editing: ComposerImageAttachment = {
id: 'editing',
name: 'edit.png',
mimeType: 'image/png',
dataBase64: 'B'.repeat(16),
sizeBytes: 1,
previewDataUrl: 'data:image/png;base64,BBBB',
}
composerState.composerImageAttachments = [already, editing]
render(<ComposerPanel inline />)
fireEvent.click(screen.getByText('edit.png'))
expect(annotationCanvasMock.onSave).toEqual(expect.any(Function))
expect(() =>
annotationCanvasMock.onSave?.({
...editing,
dataBase64: 'B'.repeat(64),
})
).toThrow(/edit\.png was kept unchanged.*8 MB in total/)
expect(actionsMock.handleUpdateComposerImageAttachment).not.toHaveBeenCalled()
})
it('counts images already in the composer toward the combined budget', async () => {
composerState.composerImageAttachments = [
{
id: 'already-attached',
name: 'already.png',
mimeType: 'image/png',
dataBase64: 'A'.repeat(COMPOSER_MAX_TOTAL_IMAGE_BASE64_BYTES - 8),
sizeBytes: 1,
previewDataUrl: 'data:image/png;base64,AAAA',
},
]
const { container } = render(<ComposerPanel inline />)
fireEvent.change(pickerInput(container), {
target: { files: [imageFile('small.png', 'image/png')] },
})
await waitFor(() =>
expect(screen.getByRole('alert').textContent).toMatch(/^small\.png does not fit/)
)
expect(actionsMock.handleAddComposerImageAttachments).not.toHaveBeenCalled()
})
it('sends a dropped document to the document path without taking an image slot', async () => {
// 18 of the 20 slots are taken; the drop carries a PDF ahead of two PNGs.
composerState.composerImageAttachments = Array.from({ length: 18 }, (_, index) => ({
id: `attached-${index + 1}`,
name: `attached-${index + 1}.png`,
mimeType: 'image/png' as const,
dataBase64: 'iVBORw0KGgo=',
sizeBytes: 8,
previewDataUrl: 'data:image/png;base64,iVBORw0KGgo=',
}))
const { container } = render(<ComposerPanel inline />)
const shell = container.querySelector('.composer-input-shell') as HTMLElement
fireEvent.drop(shell, {
dataTransfer: {
files: [
imageFile('doc.pdf', 'application/pdf'),
imageFile('a.png', 'image/png', [...PNG_BYTES, 1]),
imageFile('b.png', 'image/png', [...PNG_BYTES, 2]),
],
types: ['Files'],
},
})
await waitFor(() =>
expect(actionsMock.handleAddComposerImageAttachments).toHaveBeenCalledTimes(1)
)
const [batch] = addedBatches()
expect(batch?.map(attachment => attachment.name)).toEqual(['a.png', 'b.png'])
// Liveness witness: the PDF reached the document path, not the image path.
expect(actionsMock.handleAddComposerFiles).toHaveBeenCalledTimes(1)
const [documents] = actionsMock.handleAddComposerFiles.mock.calls[0] as [File[], string]
expect(documents.map(file => file.name)).toEqual(['doc.pdf'])
// No image was counted as skipped, so nothing is reported.
expect(screen.queryByRole('alert')).toBeNull()
})
it('routes an image-only drop through the document path once, with no documents', async () => {
draftState.value = 'caption'
const { container } = render(<ComposerPanel inline />)
const shell = container.querySelector('.composer-input-shell') as HTMLElement
fireEvent.drop(shell, {
dataTransfer: {
files: [imageFile('only.png', 'image/png', [...PNG_BYTES, 7])],
types: ['Files'],
},
})
// Witness: the image of the drop was attached.
await waitFor(() =>
expect(actionsMock.handleAddComposerImageAttachments).toHaveBeenCalledTimes(1)
)
expect(expectSinglePreparedImage().name).toBe('only.png')
// The empty call is what replaces the notices of the previous gesture.
expect(actionsMock.handleAddComposerFiles.mock.calls).toEqual([[[], 'caption']])
})
})
describe('ComposerPanel Codex image budgets', () => {
beforeEach(() => {
composerModelState.data = {
provider: 'codex-subscription',
hostDefault: 'gpt-5.6-luna',
sessionModel: 'gpt-5.6-luna',
degraded: false,
models: [{ name: 'gpt-5.6-luna', displayName: 'Luna' }],
}
composerModelState.effectiveModel = 'gpt-5.6-luna'
})
it('explains a Codex oversize image at 16 MiB', async () => {
const { container } = render(<ComposerPanel inline />)
fireEvent.change(pickerInput(container), {
target: {
files: [
imageFileWithReportedSize('huge.png', 'image/png', CODEX_COMPOSER_MAX_IMAGE_BYTES + 1),
],
},
})
await waitFor(() => expect(screen.getByRole('alert')).toBeTruthy())
expect(screen.getByRole('alert').textContent).toBe('huge.png is too large. Max size is 16 MiB.')
expect(actionsMock.handleAddComposerImageAttachments).not.toHaveBeenCalled()
})
it('accepts a 12MiB image above the usual 10MiB target', async () => {
const { container } = render(<ComposerPanel inline />)
fireEvent.change(pickerInput(container), {
target: { files: [imageFileWithReportedSize('large.png', 'image/png', 12 * 1024 * 1024)] },
})
await waitFor(() => expect(actionsMock.handleAddComposerImageAttachments).toHaveBeenCalled())
expect(expectSinglePreparedImage().sizeBytes).toBe(12 * 1024 * 1024)
expect(screen.queryByRole('alert')).toBeNull()
})
it('refuses a 2049 px image before send and names the pixel bound', async () => {
const { container } = render(<ComposerPanel inline />)
fireEvent.change(pickerInput(container), {
target: { files: [pngIhdrFile('over-res.png', CODEX_COMPOSER_MAX_IMAGE_DIMENSION + 1, 128)] },
})
await waitFor(() =>
expect(screen.getByRole('alert').textContent).toContain(
`over-res.png is too large. Max resolution is ${CODEX_COMPOSER_MAX_IMAGE_DIMENSION} px.`
)
)
expect(actionsMock.handleAddComposerImageAttachments).not.toHaveBeenCalled()
})
it('refuses a second 8.5 MiB PNG: rpc-proxy and mcp-host cap the decoded images at 16 MiB', async () => {
const { container } = render(<ComposerPanel inline />)
const files = [pngOfSize('first.png', 8.5 * MIB, 1), pngOfSize('second.png', 8.5 * MIB, 2)]
fireEvent.change(pickerInput(container), { target: { files } })
await waitFor(() =>
expect(actionsMock.handleAddComposerImageAttachments).toHaveBeenCalledTimes(1)
)
// Witness: the first image fits on its own and is attached.
expect(addedBatches()[0]?.map(attachment => attachment.name)).toEqual(['first.png'])
expect(screen.getByRole('alert').textContent).toBe(
'second.png does not fit in this message: the images in one message are limited to 16 MiB in total. Send the attached images first or remove one.'
)
})
it('attaches two PNGs whose decoded bytes fill the 16 MiB image quota exactly', async () => {
const { container } = render(<ComposerPanel inline />)
const files = [pngOfSize('left.png', 8 * MIB, 1), pngOfSize('right.png', 8 * MIB, 2)]
fireEvent.change(pickerInput(container), { target: { files } })
await waitFor(() =>
expect(actionsMock.handleAddComposerImageAttachments).toHaveBeenCalledTimes(1)
)
const [batch] = addedBatches()
expect(batch?.map(attachment => attachment.name)).toEqual(['left.png', 'right.png'])
expect(batch?.map(attachment => attachment.sizeBytes)).toEqual([8 * MIB, 8 * MIB])
expect(screen.queryByRole('alert')).toBeNull()
})
it('counts the decoded bytes of images already in the composer toward the 16 MiB quota', async () => {
composerState.composerImageAttachments = [
attachedImage('already', 'already.png', 8.5 * MIB - 2),
]
const { container } = render(<ComposerPanel inline />)
fireEvent.change(pickerInput(container), {
target: { files: [pngOfSize('next.png', 7.5 * MIB + 3, 1)] },
})
await waitFor(() =>
expect(screen.queryByRole('alert')?.textContent).toBe(
'next.png does not fit in this message: the images in one message are limited to 16 MiB in total. Send the attached images first or remove one.'
)
)
expect(actionsMock.handleAddComposerImageAttachments).not.toHaveBeenCalled()
// Twin: the same composer admits the image one byte smaller, which fills the quota.
cleanup()
composerState.composerImageAttachments = [
attachedImage('already', 'already.png', 8.5 * MIB - 2),
]
const twin = render(<ComposerPanel inline />)
fireEvent.change(pickerInput(twin.container), {
target: { files: [pngOfSize('next.png', 7.5 * MIB + 2, 1)] },
})
await waitFor(() =>
expect(actionsMock.handleAddComposerImageAttachments).toHaveBeenCalledTimes(1)
)
expect(expectSinglePreparedImage().name).toBe('next.png')
})
it('refuses an annotation save that would push the decoded images past 16 MiB', () => {
const already = attachedImage('already', 'already.png', 8 * MIB)
const editing = attachedImage('editing', 'edit.png', 8 * MIB - 3)
composerState.composerImageAttachments = [already, editing]
render(<ComposerPanel inline />)
fireEvent.click(screen.getByText('edit.png'))
expect(annotationCanvasMock.onSave).toEqual(expect.any(Function))
expect(() =>
annotationCanvasMock.onSave?.({ ...attachedImage('editing', 'edit.png', 8 * MIB + 1) })
).toThrow(
'edit.png was kept unchanged. The images in one message are limited to 16 MiB in total.'
)
expect(actionsMock.handleUpdateComposerImageAttachment).not.toHaveBeenCalled()
// Twin: a save that fills the quota exactly replaces the attachment.
const fits = attachedImage('editing', 'edit.png', 8 * MIB)
annotationCanvasMock.onSave?.(fits)
expect(actionsMock.handleUpdateComposerImageAttachment).toHaveBeenCalledWith(fits)
})
})
describe('ComposerPanel Grok image budget', () => {
beforeEach(() => {
composerModelState.data = {
provider: 'grok-subscription',
hostDefault: 'grok-4.6',
sessionModel: 'grok-4.6',
degraded: false,
models: [{ name: 'grok-4.6', displayName: 'Grok 4.6' }],
}
composerModelState.effectiveModel = 'grok-4.6'
Object.assign(composerModelState, SUPPORTED_CAPABILITY)
})
// The budget sums the decoded `sizeBytes` of each image against the
// ingress's 16 MiB decoded total, and the copy names that figure.
it('names the 16 MiB decoded total when an annotation save exceeds it', () => {
const already: ComposerImageAttachment = {
id: 'already-attached',
name: 'already.png',
mimeType: 'image/png',
dataBase64: 'AAAA',
sizeBytes: GROK_COMPOSER_MAX_IMAGE_BYTES - 32,
previewDataUrl: 'data:image/png;base64,AAAA',
}
const editing: ComposerImageAttachment = {
id: 'editing',
name: 'edit.png',
mimeType: 'image/png',
dataBase64: 'BBBB',
sizeBytes: 16,
previewDataUrl: 'data:image/png;base64,BBBB',
}
composerState.composerImageAttachments = [already, editing]
render(<ComposerPanel inline />)
fireEvent.click(screen.getByText('edit.png'))
expect(annotationCanvasMock.onSave).toEqual(expect.any(Function))
// Liveness witness: a save that keeps the total at the limit is applied.
annotationCanvasMock.onSave?.({ ...editing, sizeBytes: 32 })
expect(actionsMock.handleUpdateComposerImageAttachment).toHaveBeenCalledTimes(1)
expect(() => annotationCanvasMock.onSave?.({ ...editing, sizeBytes: 33 })).toThrow(
'edit.png was kept unchanged. The images in one message are limited to 16 MiB in total.'
)
// Still the one call from the accepted save: the refused save never called through.
expect(actionsMock.handleUpdateComposerImageAttachment).toHaveBeenCalledTimes(1)
})
it('refuses a picked image that would push the message past the 16 MiB ingress total', async () => {
const { container } = render(<ComposerPanel inline />)
const rawBytes = Math.floor(GROK_COMPOSER_MAX_IMAGE_BYTES / 2)
expect(rawBytes * 2).toBeLessThanOrEqual(GROK_COMPOSER_MAX_IMAGE_BYTES)
expect(rawBytes * 3).toBeGreaterThan(GROK_COMPOSER_MAX_IMAGE_BYTES)
const files = ['first.png', 'second.png', 'third.png'].map((name, index) => {
const bytes = new Uint8Array(rawBytes)
bytes.set(PNG_BYTES)
bytes[PNG_BYTES.length] = index
return imageFile(name, 'image/png', bytes)
})
fireEvent.change(pickerInput(container), { target: { files } })
await waitFor(() =>
expect(actionsMock.handleAddComposerImageAttachments).toHaveBeenCalledTimes(1)
)
const [batch] = addedBatches()
expect(batch?.map(attachment => attachment.name)).toEqual(['first.png', 'second.png'])
expect(screen.getByRole('alert').textContent).toBe(
'third.png does not fit in this message: the images in one message are limited to 16 MiB in total. Send the attached images first or remove one.'
)
})
})
describe('ComposerPanel Grok image total counts decoded bytes', () => {
beforeEach(() => {
composerModelState.data = {
provider: 'grok-subscription',
hostDefault: 'grok-4.6',
sessionModel: 'grok-4.6',
degraded: false,
models: [{ name: 'grok-4.6', displayName: 'Grok 4.6' }],
}
composerModelState.effectiveModel = 'grok-4.6'
Object.assign(composerModelState, SUPPORTED_CAPABILITY)
})
// The ingress counts decoded bytes. 8,388,609 + 8,388,608 decoded bytes is
// one byte over 16 MiB, while the base64 characters of the two files sum to
// exactly the 22,369,624 the base64 rule allowed, so only a decoded sum
// refuses the second image.
it('refuses the image that takes the decoded total one byte past 16 MiB', async () => {
const { container } = render(<ComposerPanel inline />)
const sizes = [8 * 1024 * 1024 + 1, 8 * 1024 * 1024]
const files = ['first.png', 'second.png'].map((name, index) => {
const bytes = new Uint8Array(sizes[index] as number)
bytes.set(PNG_BYTES)
return imageFile(name, 'image/png', bytes)
})
fireEvent.change(pickerInput(container), { target: { files } })
await waitFor(() =>
expect(actionsMock.handleAddComposerImageAttachments).toHaveBeenCalledTimes(1)
)
const [batch] = addedBatches()
expect(batch?.map(attachment => [attachment.name, attachment.sizeBytes])).toEqual([
['first.png', 8 * 1024 * 1024 + 1],
])
expect(screen.getByRole('alert').textContent).toBe(
'second.png does not fit in this message: the images in one message are limited to 16 MiB in total. Send the attached images first or remove one.'
)
})
it('accepts two images whose decoded sizes sum to exactly 16 MiB', async () => {
const { container } = render(<ComposerPanel inline />)
const files = ['first.png', 'second.png'].map(name => {
const bytes = new Uint8Array(8 * 1024 * 1024)
bytes.set(PNG_BYTES)
return imageFile(name, 'image/png', bytes)
})
fireEvent.change(pickerInput(container), { target: { files } })
await waitFor(() =>
expect(actionsMock.handleAddComposerImageAttachments).toHaveBeenCalledTimes(1)
)
expect(addedBatches()[0]?.map(attachment => attachment.name)).toEqual([
'first.png',
'second.png',
])
expect(screen.queryByRole('alert')).toBeNull()
})
})
describe('ComposerPanel with a pending image after a model switch', () => {
const pendingImage: ComposerImageAttachment = {
id: 'pending-image-1',
name: 'pending.png',
mimeType: 'image/png',
dataBase64: 'iVBORw0KGgo=',
sizeBytes: 8,
previewDataUrl: 'data:image/png;base64,iVBORw0KGgo=',
}
const switchedAway: ImageInputDecision = { state: 'unknown', reason: 'model_unknown' }
beforeEach(() => {
composerState.composerImageAttachments = [pendingImage]
draftState.value = 'inspect this image'
Object.assign(composerModelState, SUPPORTED_CAPABILITY)
})
it('keeps the pending chip, shows the block notice, and refuses Enter and the send button', () => {
const { rerender } = render(<ComposerPanel inline />)
expect(screen.queryByTestId('composer-image-capability-notice')).toBeNull()
// The host now reports the effective model as unable to receive images.
Object.assign(composerModelState, {
imageInput: switchedAway,
canAttachImages: false,
imageBlockMessage: capabilityMessage(switchedAway),
visualSendBlocked: true,
})
rerender(<ComposerPanel inline />)
// The pending attachment is still there, with the reason it cannot be sent.
expect(screen.getByRole('button', { name: 'Remove pending.png' })).toBeTruthy()
const notice = screen.getByTestId('composer-image-capability-notice')
expect(notice.getAttribute('role')).toBe('alert')
expect(notice.textContent).toBe(capabilityMessage(switchedAway))
// The disabled send button points assistive technology at the reason.
const describedBy = screen.getByTestId('send-button').getAttribute('aria-describedby')
expect(describedBy).toBeTruthy()
expect(document.getElementById(describedBy as string)).toBe(notice)
const textarea = screen.getByTestId('chat-input') as HTMLTextAreaElement
expect((screen.getByTestId('send-button') as HTMLButtonElement).disabled).toBe(true)
expect(fireEvent.keyDown(textarea, { key: 'Enter' })).toBe(false)
expect(actionsMock.handleSendAgentMessage).not.toHaveBeenCalled()
// Shift+Enter is still a newline, and still not a send.
expect(fireEvent.keyDown(textarea, { key: 'Enter', shiftKey: true })).toBe(true)
expect(actionsMock.handleSendAgentMessage).not.toHaveBeenCalled()
})
it('sends the pending image with Enter while the model can receive images', () => {
render(<ComposerPanel inline />)
expect(screen.queryByTestId('composer-image-capability-notice')).toBeNull()
expect(screen.getByTestId('send-button').hasAttribute('aria-describedby')).toBe(false)
const textarea = screen.getByTestId('chat-input') as HTMLTextAreaElement
expect((screen.getByTestId('send-button') as HTMLButtonElement).disabled).toBe(false)
expect(fireEvent.keyDown(textarea, { key: 'Enter' })).toBe(false)
expect(actionsMock.handleSendAgentMessage).toHaveBeenCalledWith('inspect this image')
fireEvent.click(screen.getByTestId('send-button'))
expect(actionsMock.handleSendAgentMessage).toHaveBeenCalledTimes(2)
})
it('renders the pending image chip and dispatches removal with its id', () => {
render(<ComposerPanel inline />)
expect(screen.getByText('pending.png')).toBeTruthy()
fireEvent.click(screen.getByRole('button', { name: 'Remove pending.png' }))
expect(actionsMock.handleRemoveComposerImageAttachment).toHaveBeenCalledWith('pending-image-1')
})
})
describe('ComposerPanel attachments chip row (STORY-38)', () => {
const firstImage: ComposerImageAttachment = {
id: 'kept-image-1',
name: 'kept-a.png',
mimeType: 'image/png',
dataBase64: 'iVBORw0KGgo=',
sizeBytes: 8,
previewDataUrl: 'data:image/png;base64,iVBORw0KGgo=',
}
const secondImage: ComposerImageAttachment = {
id: 'kept-image-2',
name: 'kept-b.png',
mimeType: 'image/png',
dataBase64: 'iVBORw0KGgoB',
sizeBytes: 9,
previewDataUrl: 'data:image/png;base64,iVBORw0KGgoB',
}
const pluginReference: ComposerReferenceAttachment = {
id: 'kept-ref-1',
type: 'plugin',
namespace: 'ns',
name: 'helper',
label: 'helper plugin',
}
it('shows no count or clear control while the composer has no attachments', () => {
render(<ComposerPanel inline />)
expect(screen.queryByTestId('composer-attachments-count')).toBeNull()
expect(screen.queryByRole('button', { name: 'Clear all attachments' })).toBeNull()
})
it('counts every pending attachment, singular and plural, with per-file remove buttons', () => {
composerState.composerImageAttachments = [firstImage]
const { rerender } = render(<ComposerPanel inline />)
expect(screen.getByTestId('composer-attachments-count').textContent).toBe('1 attachment')
expect(screen.getByRole('button', { name: 'Remove kept-a.png' })).toBeTruthy()
composerState.composerImageAttachments = [firstImage, secondImage]
composerState.composerReferenceAttachments = [pluginReference]
rerender(<ComposerPanel inline />)
expect(screen.getByTestId('composer-attachments-count').textContent).toBe('3 attachments')
expect(screen.getByRole('button', { name: 'Remove kept-b.png' })).toBeTruthy()
expect(screen.getByRole('button', { name: 'Remove helper plugin' })).toBeTruthy()
})
it('clears every pending attachment through the explicit clear control', () => {
composerState.composerImageAttachments = [firstImage, secondImage]
composerState.composerReferenceAttachments = [pluginReference]
render(<ComposerPanel inline />)
fireEvent.click(screen.getByRole('button', { name: 'Clear all attachments' }))
expect(actionsMock.handleClearComposerAttachments).toHaveBeenCalledTimes(1)
expect(actionsMock.handleRemoveComposerImageAttachment).not.toHaveBeenCalled()
expect(actionsMock.handleRemoveComposerReferenceAttachment).not.toHaveBeenCalled()
})
it('styles the clear control and the count as part of the inline chip row', () => {
composerState.composerImageAttachments = [firstImage]
render(<ComposerPanel inline />)
expect(cssRule('.composer-attachments-count')).toContain('white-space: nowrap')
expect(cssRule('.composer-attachments-clear')).toContain('cursor: pointer')
})
})
describe('ComposerPanel failed-send recovery actions', () => {
const failedSend: FailedAgentSend = {
content: 'inspect this image',
attachments: [],
files: [],
references: [],
message: 'Image input evidence changed',
kind: 'upstream',
timestamp: 1,
agentRef: 'agent-1',
chatId: 'chat-1',
}
it('offers explicit recovery and dispatch and routes each action to the controller', () => {
composerState.failedAgentSend = failedSend
composerState.agentError = 'Sending failed'
render(<ComposerPanel inline />)
expect(screen.getByText('Sending failed')).toBeTruthy()
expect(screen.getByText('Image input evidence changed')).toBeTruthy()
fireEvent.click(screen.getByRole('button', { name: 'Recover input' }))
expect(actionsMock.handleRecoverFailedAgentSend).toHaveBeenCalledTimes(1)
expect(actionsMock.handleDiscardFailedAgentSend).not.toHaveBeenCalled()
fireEvent.click(screen.getByRole('button', { name: 'Discard failed input' }))
expect(actionsMock.handleDiscardFailedAgentSend).toHaveBeenCalledTimes(1)
fireEvent.click(screen.getByRole('button', { name: 'Retry last send' }))
expect(actionsMock.handleRetryFailedAgentSend).toHaveBeenCalledTimes(1)
})
it('offers only the files back for a message answered without them', () => {
composerState.failedAgentSend = { ...failedSend, answeredWithoutFiles: true }
composerState.agentError = 'The Host does not accept file attachments yet'
render(<ComposerPanel inline />)
// A retry would send the answered text again; recovering the input would
// bring that text back as a draft.
expect(screen.queryByRole('button', { name: 'Retry last send' })).toBeNull()
expect(screen.queryByRole('button', { name: 'Recover input' })).toBeNull()
// Liveness: the failure is shown and its recovery and discard are offered.
expect(screen.getByText('The Host does not accept file attachments yet')).toBeTruthy()
fireEvent.click(screen.getByRole('button', { name: 'Recover files' }))
expect(actionsMock.handleRecoverFailedAgentSend).toHaveBeenCalledTimes(1)
fireEvent.click(screen.getByRole('button', { name: 'Discard failed input' }))
expect(actionsMock.handleDiscardFailedAgentSend).toHaveBeenCalledTimes(1)
expect(actionsMock.handleRetryFailedAgentSend).not.toHaveBeenCalled()
})
it('disables recovery while a send is in flight', () => {
composerState.failedAgentSend = failedSend
composerState.agentError = 'Sending failed'
composerState.agentSending = true
render(<ComposerPanel inline />)
for (const name of ['Recover input', 'Discard failed input', 'Retry last send']) {
expect((screen.getByRole('button', { name }) as HTMLButtonElement).disabled).toBe(true)
}
})
it('explains the waking state and routes its retry to the controller', () => {
composerState.failedAgentSend = { ...failedSend, kind: 'waking' }
composerState.agentError = 'Sending failed'
render(<ComposerPanel inline />)
const waking = screen.getByTestId('waking-state')
expect(waking.getAttribute('role')).toBe('status')
expect(waking.textContent).toContain('Agent is waking up')
fireEvent.click(screen.getByRole('button', { name: 'Retry last send' }))
expect(actionsMock.handleRetryFailedAgentSend).toHaveBeenCalledTimes(1)
})
})
describe('ComposerPanel document attachments (#678)', () => {
/** A chip built by the same read the composer runs, never by hand. */
async function readyFile(
id: string,
name: string,
bytes: Uint8Array<ArrayBuffer>,
type: string
): Promise<ComposerFileAttachment> {
const result = await readComposerFile(new File([bytes], name, { type }), id)
if (result.status !== 'ready') throw new Error(`fixture ${name} did not read: ${result.error}`)
return result
}
const notesBytes = new TextEncoder().encode('n'.repeat(2048))
// A ZIP local-file header: bytes the agent has no reader for.
const zipBytes = new Uint8Array([0x50, 0x4b, 0x03, 0x04, ...new Array(60).fill(0)])
const pdfBytes = new TextEncoder().encode('%PDF-1.4\n1 0 obj\n<<>>\nendobj\n%%EOF\n')
function notesFile() {
return readyFile('file-1', 'notes.txt', notesBytes, 'text/plain')
}
function sendButton(): HTMLButtonElement {
return screen.getByRole('button', { name: 'Send message' }) as HTMLButtonElement
}
it('shows a ready document chip and lets a message with only that document be sent', async () => {
composerState.composerFileAttachments = [await notesFile()]
render(<ComposerPanel inline />)
const chip = screen.getByTestId('composer-file-chip')
expect(chip.textContent).toContain('notes.txt')
expect(chip.textContent).toContain('2.0 KiB · text')
expect(chip.getAttribute('data-file-status')).toBe('ready')
expect(sendButton().disabled).toBe(false)
})
it('gives a document chip its own icon class, not the image one', async () => {
composerState.composerFileAttachments = [await notesFile()]
render(<ComposerPanel inline />)
const chip = screen.getByTestId('composer-file-chip')
// Witness: the chip renders its icon at all.
expect(chip.querySelector('.composer-reference-icon')).not.toBeNull()
expect(chip.querySelector('.composer-reference-icon--uploaded-file')).not.toBeNull()
expect(chip.querySelector('.composer-reference-icon--uploaded-image')).toBeNull()
})
it('removes a document through its chip button', async () => {
composerState.composerFileAttachments = [await notesFile()]
render(<ComposerPanel inline />)
fireEvent.click(screen.getByRole('button', { name: 'Remove notes.txt' }))
expect(actionsMock.handleRemoveComposerFileAttachment).toHaveBeenCalledWith('file-1')
})
it('blocks the send while a document is reading', () => {
// A reading chip has no read result yet, so it is the one built by hand.
composerState.composerFileAttachments = [
{
id: 'file-2',
type: 'file',
filename: 'big.pdf',
sizeBytes: 1024,
declaredMediaType: 'application/pdf',
status: 'reading',
},
]
draftState.value = 'read this'
render(<ComposerPanel inline />)
// Liveness witness: the chip for this very file is on screen with its reading state.
expect(screen.getByTestId('composer-file-chip').textContent).toContain('Reading...')
expect(sendButton().disabled).toBe(true)
})
it('shows a refused document as an alert without a chip and does not block the send', () => {
composerState.composerFileRefusals = [
{ id: 'refusal-1', text: 'broken.bin could not be read: permission denied' },
]
draftState.value = 'hello'
render(<ComposerPanel inline />)
// Witness for the two negative checks below: the refusal is on screen.
expect(screen.getByRole('alert').textContent).toBe(
'broken.bin could not be read: permission denied'
)
expect(screen.queryAllByTestId('composer-file-chip')).toHaveLength(0)
expect(sendButton().disabled).toBe(false)
})
it('lists refusals before the notices of ready documents', async () => {
composerState.composerFileRefusals = [{ id: 'refusal-2', text: 'huge.bin is too large.' }]
composerState.composerFileAttachments = [
await readyFile('file-5', 'archive.zip', zipBytes, 'application/zip'),
]
render(<ComposerPanel inline />)
const notices = screen.getByTestId('composer-file-notices')
const roles = Array.from(notices.children).map(child => child.getAttribute('role'))
expect(roles).toEqual(['alert', 'status'])
expect(screen.getByTestId('composer-file-chip').getAttribute('data-file-status')).toBe('ready')
})
it('says when the agent has no reader for an attached document', async () => {
const archive = await readyFile('file-4', 'archive.zip', zipBytes, 'application/zip')
// Precondition: the real read classifies these bytes as unreadable.
expect(archive.status === 'ready' && archive.classification.reader).toBe('none')
composerState.composerFileAttachments = [archive]
render(<ComposerPanel inline />)
expect(screen.getByTestId('composer-file-chip').textContent).toContain('No reader available')
expect(screen.getByRole('status').textContent).toBe(
'archive.zip is attached, but the agent has no reader for this kind of file.'
)
expect(sendButton().disabled).toBe(false)
})
it('warns when the bytes do not match the name or type', async () => {
const report = await readyFile('file-5', 'report.txt', pdfBytes, 'text/plain')
// Precondition: the real read sees PDF bytes behind a text name.
expect(report.status === 'ready' && report.classification.mismatch).toBe(true)
composerState.composerFileAttachments = [report]
render(<ComposerPanel inline />)
expect(screen.getByRole('status').textContent).toBe(
'report.txt looks like a pdf file, not what its name or type says. It is attached as it is.'
)
})
it('keeps send disabled with an empty draft and no attachment of any kind', () => {
render(<ComposerPanel inline />)
// Witness: nothing renders for documents, and the button itself is the guard under test.
expect(screen.queryByTestId('composer-file-chip')).toBeNull()
expect(sendButton().disabled).toBe(true)
})
})