Skip to content

The agent that grows with you

fix(desktop): make image attachment updates occurrence-safe

Jakub Wolniewicz193c199b23b5
diff --git a/apps/desktop/src/app/chat/composer/attachments.test.tsx b/apps/desktop/src/app/chat/composer/attachments.test.tsx
index 917cdb374e0..7377691f0f5 100644
--- a/apps/desktop/src/app/chat/composer/attachments.test.tsx
+++ b/apps/desktop/src/app/chat/composer/attachments.test.tsx
@@ -177,6 +177,65 @@ describe('AttachmentList', () => {
expect((await screen.findByRole('dialog')).querySelector<HTMLImageElement>('img')?.src).toBe(DATA_URL)
})
+ it('does not let an old occurrence open a replacement lightbox after a deferred read', async () => {
+ let resolveOldRead!: (value: string) => void
+
+ const oldRead = new Promise<string>(resolve => {
+ resolveOldRead = resolve
+ })
+
+ const readFileDataUrl = vi.fn((path: string) =>
+ path === '/tmp/old.png' ? oldRead : Promise.resolve('data:image/png;base64,replacement')
+ )
+
+ Object.defineProperty(window, 'hermesDesktop', {
+ configurable: true,
+ value: { readFileDataUrl }
+ })
+
+ const oldOccurrence: ComposerAttachment = {
+ id: 'image:same-path',
+ kind: 'image',
+ label: 'same.png',
+ occurrenceId: 'occurrence-old',
+ path: '/tmp/old.png',
+ thumbnailUrl: THUMBNAIL_URL
+ }
+
+ const replacement: ComposerAttachment = {
+ ...oldOccurrence,
+ occurrenceId: 'occurrence-replacement',
+ path: '/tmp/replacement.png'
+ }
+
+ const { rerender } = await renderWithI18n(<AttachmentList attachments={[oldOccurrence]} />)
+
+ fireEvent.click(screen.getByRole('button', { name: /same\.png/ }))
+ expect(readFileDataUrl).toHaveBeenCalledWith('/tmp/old.png')
+
+ rerender(
+ <I18nProvider configClient={{ getConfig: async () => ({}), saveConfig: async () => ({ ok: true }) }}>
+ <AttachmentList attachments={[replacement]} />
+ </I18nProvider>
+ )
+
+ await act(async () => {
+ resolveOldRead(DATA_URL)
+ await oldRead
+ })
+
+ expect(screen.queryByRole('dialog')).toBeNull()
+
+ await act(async () => {
+ fireEvent.click(screen.getByRole('button', { name: /same\.png/ }))
+ })
+
+ expect(readFileDataUrl).toHaveBeenCalledWith('/tmp/replacement.png')
+ expect((await screen.findByRole('dialog')).querySelector<HTMLImageElement>('img')?.src).toBe(
+ 'data:image/png;base64,replacement'
+ )
+ })
+
it('still routes a non-image attachment to the preview rail', async () => {
$previewTabs.set([])
diff --git a/apps/desktop/src/app/chat/composer/attachments.tsx b/apps/desktop/src/app/chat/composer/attachments.tsx
index 759d9ca6f8d..b87e69068ff 100644
--- a/apps/desktop/src/app/chat/composer/attachments.tsx
+++ b/apps/desktop/src/app/chat/composer/attachments.tsx
@@ -25,7 +25,11 @@ export function AttachmentList({
return (
<div className="flex max-w-full flex-wrap gap-1.5 px-1 pt-1" data-slot="composer-attachments">
{attachments.filter(Boolean).map(attachment => (
- <AttachmentPill attachment={attachment} key={attachment.id} onRemove={onRemove} />
+ <AttachmentPill
+ attachment={attachment}
+ key={attachment.occurrenceId ? `occ:${attachment.occurrenceId}` : attachment.id}
+ onRemove={onRemove}
+ />
))}
</div>
)
diff --git a/apps/desktop/src/app/chat/composer/hooks/use-composer-draft.test.tsx b/apps/desktop/src/app/chat/composer/hooks/use-composer-draft.test.tsx
index 92d89ea947e..eab570bf428 100644
--- a/apps/desktop/src/app/chat/composer/hooks/use-composer-draft.test.tsx
+++ b/apps/desktop/src/app/chat/composer/hooks/use-composer-draft.test.tsx
@@ -92,7 +92,7 @@ describe('useComposerDraft — attachment scope stays coherent with the committe
expect(snapshots[0]).toEqual([])
})
- it('applies a delayed image preview after its attachment survives an A → B → A draft round-trip', async () => {
+ it('applies a delayed image preview when it resolves while its attachment draft is inactive', async () => {
const fullResolution =
'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mP8/x8AAwMCAO+GkZcAAAAASUVORK5CYII='
@@ -153,10 +153,7 @@ describe('useComposerDraft — attachment scope stays coherent with the committe
await waitFor(() => expect(createImageBitmap).toHaveBeenCalledOnce())
act(() => rerender(<PreviewHarness activeQueueSessionKey="session-B" />))
- act(() => rerender(<PreviewHarness activeQueueSessionKey="session-A" />))
-
- expect(mainComposerScope.$attachments.get()).toHaveLength(1)
- expect(mainComposerScope.$attachments.get()[0]?.thumbnailUrl).toBeUndefined()
+ expect(mainComposerScope.$attachments.get()).toEqual([])
resolveBitmap({ close: vi.fn(), height: 3000, width: 4000 })
@@ -164,6 +161,11 @@ describe('useComposerDraft — attachment scope stays coherent with the committe
await pending
})
+ // The late completion belongs to A and must not leak into active session B.
+ expect(mainComposerScope.$attachments.get()).toEqual([])
+
+ act(() => rerender(<PreviewHarness activeQueueSessionKey="session-A" />))
+
expect(mainComposerScope.$attachments.get()[0]?.thumbnailUrl).toMatch(/^data:image\/png;base64,/)
})
})
diff --git a/apps/desktop/src/app/chat/hooks/use-composer-actions.test.ts b/apps/desktop/src/app/chat/hooks/use-composer-actions.test.ts
index 3fb4b3dbac6..8fe4e66fafa 100644
--- a/apps/desktop/src/app/chat/hooks/use-composer-actions.test.ts
+++ b/apps/desktop/src/app/chat/hooks/use-composer-actions.test.ts
@@ -1,7 +1,7 @@
import { act, renderHook, waitFor } from '@testing-library/react'
import { afterEach, describe, expect, it, vi } from 'vitest'
-import { $composerAttachments, type ComposerAttachment } from '@/store/composer'
+import { $composerAttachments, type ComposerAttachment, updateComposerAttachment } from '@/store/composer'
import { $connection } from '@/store/session'
import {
@@ -468,6 +468,73 @@ describe('attachImagePath thumbnail separation', () => {
expect($composerAttachments.get()[0]?.previewUrl).toBe('data:text/plain;base64,c2Vjb25k')
})
+ it('merges a delayed thumbnail into the latest staged state of the same occurrence', async () => {
+ const readFileDataUrl = vi.fn(async () => FULL_RES)
+
+ ;(
+ window as unknown as {
+ hermesDesktop: { readFileDataUrl: typeof readFileDataUrl }
+ }
+ ).hermesDesktop = { readFileDataUrl }
+
+ let resolveBitmap!: (bitmap: { close: () => void; height: number; width: number }) => void
+
+ vi.stubGlobal(
+ 'fetch',
+ vi.fn(async () => ({ blob: async () => new Blob([new Uint8Array([0])], { type: 'image/png' }) }))
+ )
+ vi.stubGlobal(
+ 'createImageBitmap',
+ vi.fn(
+ () =>
+ new Promise<{ close: () => void; height: number; width: number }>(resolve => {
+ resolveBitmap = resolve
+ })
+ )
+ )
+
+ class MockOffscreenCanvas {
+ getContext = () => ({ drawImage: vi.fn() })
+ convertToBlob = vi.fn(async () => new Blob(['thumbnail'], { type: 'image/png' }))
+ constructor(_width: number, _height: number) {}
+ }
+
+ vi.stubGlobal('OffscreenCanvas', MockOffscreenCanvas)
+
+ const { result } = renderHook(() =>
+ useComposerActions({ activeSessionId: null, currentCwd: '', requestGateway: vi.fn() })
+ )
+
+ let pending!: Promise<boolean>
+
+ act(() => {
+ pending = result.current.attachImagePath('C:\\Users\\alice\\Pictures\\photo.png')
+ })
+
+ await waitFor(() => expect(createImageBitmap).toHaveBeenCalledOnce())
+
+ const original = $composerAttachments.get()[0]!
+ updateComposerAttachment({
+ ...original,
+ attachedSessionId: 'session-1',
+ label: 'photo.png',
+ path: '/root/.hermes/attachments/photo.png',
+ uploadState: undefined
+ })
+
+ resolveBitmap({ close: vi.fn(), height: 3000, width: 4000 })
+
+ await act(async () => {
+ await pending
+ })
+
+ expect($composerAttachments.get()[0]).toMatchObject({
+ attachedSessionId: 'session-1',
+ path: '/root/.hermes/attachments/photo.png',
+ thumbnailUrl: expect.stringMatching(/^data:image\/png;base64,/)
+ })
+ })
+
it('retains only the bounded thumbnail after creating a composer image preview', async () => {
const readFileDataUrl = vi.fn(async () => FULL_RES)
diff --git a/apps/desktop/src/app/chat/hooks/use-composer-actions.ts b/apps/desktop/src/app/chat/hooks/use-composer-actions.ts
index 82c5c17ca04..814ce524937 100644
--- a/apps/desktop/src/app/chat/hooks/use-composer-actions.ts
+++ b/apps/desktop/src/app/chat/hooks/use-composer-actions.ts
@@ -12,8 +12,9 @@ import { normalize } from '@/lib/text'
import {
addComposerAttachment,
type ComposerAttachment,
+ type ComposerAttachmentPatch,
createComposerAttachmentOccurrenceId,
- mainComposerScope,
+ patchMainComposerAttachmentOccurrence,
removeComposerAttachment,
setComposerTerminalSelection,
updateComposerAttachment
@@ -274,7 +275,7 @@ interface ComposerActionsScope {
add: (attachment: ComposerAttachment) => void
remove: (id: string) => ComposerAttachment | null
update: (attachment: ComposerAttachment) => boolean
- updateIfCurrent: (expected: ComposerAttachment, attachment: ComposerAttachment) => boolean
+ updateIfCurrent: (expected: ComposerAttachment, patch: ComposerAttachmentPatch) => boolean
target: string
}
@@ -282,7 +283,7 @@ const MAIN_ACTIONS_SCOPE: ComposerActionsScope = {
add: addComposerAttachment,
remove: removeComposerAttachment,
update: updateComposerAttachment,
- updateIfCurrent: (expected, attachment) => mainComposerScope.updateIfCurrent(expected, attachment),
+ updateIfCurrent: patchMainComposerAttachmentOccurrence,
target: 'main'
}
@@ -491,10 +492,7 @@ export function useComposerActions({
// Object identity is insufficient because a session draft round-trip
// clones attachments; id alone is insufficient because remove +
// reattach of the same path reuses it.
- scope.updateIfCurrent(
- baseAttachment,
- thumbnailUrl ? { ...baseAttachment, thumbnailUrl } : { ...baseAttachment, previewUrl }
- )
+ scope.updateIfCurrent(baseAttachment, thumbnailUrl ? { thumbnailUrl } : { previewUrl })
}
return true
diff --git a/apps/desktop/src/app/session/hooks/use-prompt-actions/index.test.tsx b/apps/desktop/src/app/session/hooks/use-prompt-actions/index.test.tsx
index 765a26f05ca..5994893eabd 100644
--- a/apps/desktop/src/app/session/hooks/use-prompt-actions/index.test.tsx
+++ b/apps/desktop/src/app/session/hooks/use-prompt-actions/index.test.tsx
@@ -2675,6 +2675,56 @@ describe('usePromptActions file attachment sync', () => {
expect(uploaded.path).toBe('/root/tmp/photo.jpg')
})
+ it('merges image staging into the current occurrence without dropping its thumbnail', async () => {
+ $connection.set({ mode: 'local' } as never)
+ $currentCwd.set('/root')
+
+ const hostPath = 'C:\\Users\\alice\\Pictures\\photo.jpg'
+ const thumbnailUrl = 'data:image/jpeg;base64,dGh1bWJuYWls'
+
+ Object.defineProperty(window, 'hermesDesktop', {
+ configurable: true,
+ value: { readFileDataUrl: vi.fn(async () => 'data:image/jpeg;base64,aGVsbG8=') }
+ })
+
+ $composerAttachments.set([
+ {
+ detail: hostPath,
+ id: 'image:photo.jpg',
+ kind: 'image',
+ label: 'photo.jpg',
+ occurrenceId: 'occurrence-photo',
+ path: hostPath,
+ thumbnailUrl
+ }
+ ])
+
+ const requestGateway = vi.fn(async (method: string) => {
+ if (method === 'image.attach_bytes') {
+ return { attached: true, path: '/root/tmp/photo.jpg' } as never
+ }
+
+ if (method === 'prompt.submit') {
+ throw new Error('submit failed after staging')
+ }
+
+ return {} as never
+ })
+
+ let handle: HarnessHandle | null = null
+ await actRender(
+ <Harness onReady={h => (handle = h)} refreshSessions={async () => undefined} requestGateway={requestGateway} />
+ )
+
+ expect(await handle!.submitText('describe this')).toBe(false)
+ expect($composerAttachments.get()[0]).toMatchObject({
+ attachedSessionId: RUNTIME_SESSION_ID,
+ occurrenceId: 'occurrence-photo',
+ path: '/root/tmp/photo.jpg',
+ thumbnailUrl
+ })
+ })
+
it('uploads file bytes when the terminal backend is a container (docker)', async () => {
// Container backends have their own filesystem: the host drop path would
// dangle inside the sandbox, so the bytes must cross via file.attach's
diff --git a/apps/desktop/src/app/session/hooks/use-prompt-actions/index.ts b/apps/desktop/src/app/session/hooks/use-prompt-actions/index.ts
index 20ebc58ccf0..155f7888362 100644
--- a/apps/desktop/src/app/session/hooks/use-prompt-actions/index.ts
+++ b/apps/desktop/src/app/session/hooks/use-prompt-actions/index.ts
@@ -15,6 +15,7 @@ import { clearClarifyRequest } from '@/store/clarify'
import {
$composerAttachments,
type ComposerAttachment,
+ patchMainComposerAttachmentOccurrence,
setComposerAttachmentUploadState,
updateComposerAttachment
} from '@/store/composer'
@@ -387,7 +388,19 @@ export function usePromptActions({
// Update-only: never resurrect a chip the user removed mid-upload.
if (updateComposerAttachments) {
- updateComposerAttachment(nextAttachment)
+ if (original.occurrenceId) {
+ // Preserve a preview that may have completed after staging began,
+ // while still refusing a remove + re-add of the same path.
+ patchMainComposerAttachmentOccurrence(original, {
+ attachedSessionId: nextAttachment.attachedSessionId,
+ label: nextAttachment.label,
+ path: nextAttachment.path,
+ refText: nextAttachment.refText,
+ uploadState: nextAttachment.uploadState
+ })
+ } else {
+ updateComposerAttachment(nextAttachment)
+ }
}
synced.push(nextAttachment)
@@ -408,11 +421,11 @@ export function usePromptActions({
// stalling the send. The card shows a spinner via `uploadState`; on success
// the chip carries its gateway-side ref so submit skips re-uploading.
//
- // Images are intentionally NOT eager-uploaded: attachImagePath adds the chip
- // and then fills in `previewUrl` (the base64 thumbnail) on a second tick, so
- // an eager upload would race that write — clobbering the thumbnail and
- // swapping `path` to a gateway path the local preview can't read. Images are
- // small and still byte-upload at submit via image.attach_bytes.
+ // Images are intentionally NOT eager-uploaded: thumbnail preparation already
+ // performs a bounded full-file read/decode, and an eager upload would perform
+ // another full-file read/IPC transfer immediately for every image in a batch.
+ // Original bytes are still uploaded sequentially at submit via
+ // image.attach_bytes.
const eagerlyUploadAttachment = useCallback(
async (sessionId: string, attachment: ComposerAttachment) => {
const remote = $connection.get()?.mode === 'remote'
diff --git a/apps/desktop/src/store/composer.test.ts b/apps/desktop/src/store/composer.test.ts
index 3860bb4e377..52136136520 100644
--- a/apps/desktop/src/store/composer.test.ts
+++ b/apps/desktop/src/store/composer.test.ts
@@ -85,11 +85,9 @@ describe('updateComposerAttachment', () => {
scope.remove(first.id)
scope.add(replacement)
- expect(scope.updateIfCurrent(first, { ...first, thumbnailUrl: 'data:image/png;base64,stale' })).toBe(false)
+ expect(scope.updateIfCurrent(first, { thumbnailUrl: 'data:image/png;base64,stale' })).toBe(false)
expect(scope.$attachments.get()).toEqual([replacement])
- expect(scope.updateIfCurrent(replacement, { ...replacement, thumbnailUrl: 'data:image/png;base64,current' })).toBe(
- true
- )
+ expect(scope.updateIfCurrent(replacement, { thumbnailUrl: 'data:image/png;base64,current' })).toBe(true)
expect(scope.$attachments.get()[0]?.thumbnailUrl).toBe('data:image/png;base64,current')
})
@@ -108,10 +106,37 @@ describe('updateComposerAttachment', () => {
scope.add(restored)
expect(restored).not.toBe(original)
- expect(scope.updateIfCurrent(original, { ...original, thumbnailUrl: 'data:image/png;base64,current' })).toBe(true)
+ expect(scope.updateIfCurrent(original, { thumbnailUrl: 'data:image/png;base64,current' })).toBe(true)
expect(scope.$attachments.get()[0]?.thumbnailUrl).toBe('data:image/png;base64,current')
clearSessionDraft('session-a')
})
+
+ it('merges concurrent staging fields without discarding an existing thumbnail', () => {
+ const scope = createComposerAttachmentScope()
+
+ const original = attachment({
+ id: 'image:staging',
+ kind: 'image',
+ occurrenceId: createComposerAttachmentOccurrenceId(),
+ path: 'C:\\Users\\alice\\Pictures\\photo.png'
+ })
+
+ scope.add(original)
+ expect(scope.updateIfCurrent(original, { thumbnailUrl: 'data:image/png;base64,current' })).toBe(true)
+ expect(
+ scope.updateIfCurrent(original, {
+ attachedSessionId: 'session-1',
+ path: '/root/.hermes/attachments/photo.png',
+ uploadState: undefined
+ })
+ ).toBe(true)
+
+ expect(scope.$attachments.get()[0]).toMatchObject({
+ attachedSessionId: 'session-1',
+ path: '/root/.hermes/attachments/photo.png',
+ thumbnailUrl: 'data:image/png;base64,current'
+ })
+ })
})
describe('session drafts', () => {
diff --git a/apps/desktop/src/store/composer.ts b/apps/desktop/src/store/composer.ts
index 3b9ea812404..5d3c0b8b499 100644
--- a/apps/desktop/src/store/composer.ts
+++ b/apps/desktop/src/store/composer.ts
@@ -26,6 +26,8 @@ export interface ComposerAttachment {
uploadState?: 'uploading' | 'error'
}
+export type ComposerAttachmentPatch = Partial<Omit<ComposerAttachment, 'id' | 'occurrenceId'>>
+
export const $composerDraft = atom('')
export const $composerAttachments = atom<ComposerAttachment[]>([])
export const $composerTerminalSelections = atom<Record<string, string>>({})
@@ -64,7 +66,15 @@ export interface ComposerAttachmentScope {
remove(id: string): ComposerAttachment | null
setUploadState(id: string, uploadState?: ComposerAttachment['uploadState']): void
update(attachment: ComposerAttachment): boolean
- updateIfCurrent(expected: ComposerAttachment, attachment: ComposerAttachment): boolean
+ updateIfCurrent(expected: ComposerAttachment, patch: ComposerAttachmentPatch): boolean
+}
+
+function attachmentOccurrenceIndex(attachments: ComposerAttachment[], expected: ComposerAttachment): number {
+ return attachments.findIndex(item =>
+ expected.occurrenceId === undefined
+ ? item === expected
+ : item.id === expected.id && item.occurrenceId === expected.occurrenceId
+ )
}
export function createComposerAttachmentScope($attachments = atom<ComposerAttachment[]>([])): ComposerAttachmentScope {
@@ -115,21 +125,16 @@ export function createComposerAttachmentScope($attachments = atom<ComposerAttach
return true
},
- updateIfCurrent(expected, attachment) {
+ updateIfCurrent(expected, patch) {
const current = $attachments.get()
-
- const index = current.findIndex(item =>
- expected.occurrenceId === undefined
- ? item === expected
- : item.id === expected.id && item.occurrenceId === expected.occurrenceId
- )
+ const index = attachmentOccurrenceIndex(current, expected)
if (index < 0) {
return false
}
const next = [...current]
- next[index] = attachment
+ next[index] = { ...next[index]!, ...patch }
$attachments.set(next)
return true
@@ -181,6 +186,35 @@ function loadPersistedDraftTexts(): [string, SessionDraft][] {
const draftsBySession = new Map<string, SessionDraft>(loadPersistedDraftTexts())
+/**
+ * Patch one asynchronous attachment occurrence wherever the main composer owns
+ * it. During a session switch the occurrence moves from the live atom into the
+ * per-session in-memory draft stash; a preview may finish on either side of
+ * that handoff. Updating both stores is safe because occurrence ids are unique,
+ * and merging into the latest object preserves concurrent staging metadata.
+ */
+export function patchMainComposerAttachmentOccurrence(
+ expected: ComposerAttachment,
+ patch: ComposerAttachmentPatch
+): boolean {
+ let updated = mainComposerScope.updateIfCurrent(expected, patch)
+
+ for (const [key, draft] of draftsBySession) {
+ const index = attachmentOccurrenceIndex(draft.attachments, expected)
+
+ if (index < 0) {
+ continue
+ }
+
+ const attachments = [...draft.attachments]
+ attachments[index] = { ...attachments[index]!, ...patch }
+ draftsBySession.set(key, { ...draft, attachments })
+ updated = true
+ }
+
+ return updated
+}
+
/**
* What each unsent draft would be called, keyed the same way its text is.
*