Skip to content

Evenfire is an intelligence layer platform for running LLM agents that take real actions, on your infrastructure

TypeScript

fix(desktop): honest cancel-restore toast and agent-bound discard (STORY-38 review L2, L3)

M293b00abe3c9
diff --git a/desktop-app/ui/src/hooks/domain/__tests__/cancelKeepsAttachments.test.tsx b/desktop-app/ui/src/hooks/domain/__tests__/cancelKeepsAttachments.test.tsx
index d8dee505e..bde452cfc 100644
--- a/desktop-app/ui/src/hooks/domain/__tests__/cancelKeepsAttachments.test.tsx
+++ b/desktop-app/ui/src/hooks/domain/__tests__/cancelKeepsAttachments.test.tsx
@@ -67,11 +67,18 @@ afterEach(() => {
uninstallMockClerum()
})
+function keptToastCall(
+ spies: ReturnType<typeof renderController>['spies']
+): [string, unknown, { action?: ToastMessageAction } | undefined] | undefined {
+ return spies.pushToast.mock.calls.find(([message]) =>
+ String(message).startsWith('Attachments kept')
+ ) as ReturnType<typeof keptToastCall>
+}
+
function keptToastAction(
spies: ReturnType<typeof renderController>['spies']
): ToastMessageAction | undefined {
- const call = spies.pushToast.mock.calls.find(([message]) => message === 'Attachments kept')
- return call?.[2]?.action
+ return keptToastCall(spies)?.[2]?.action
}
/** Mounts with a capable model catalog, then attaches an image + a reference. */
@@ -171,4 +178,74 @@ describe('STORY-38 — attachments survive message cancel', () => {
'error'
)
})
+
+ it('reports images the composer cap drops instead of claiming all were kept (L2)', async () => {
+ const sent = [0, 1, 2].map(index => ({
+ ...image,
+ id: `sent-${index}`,
+ name: `sent-${index}.png`,
+ dataBase64: `c2VudC0-${index}`,
+ previewDataUrl: `data:image/png;base64,c2VudC0-${index}`,
+ }))
+ const rendered = renderController()
+ await waitFor(() => expect(clerum.chat.getIndex).toHaveBeenCalled())
+ await act(async () => {
+ await loadHostModels(modelTransport, 'agent-x', null)
+ })
+ act(() => rendered.result.current.handleAddComposerImageAttachments(sent))
+ await sendAsync(rendered.result, 'task-cap')
+
+ // While the task runs, the user fills the composer to the 20-image cap.
+ const filler = Array.from({ length: 19 }, (_, index) => ({
+ ...image,
+ id: `filler-${index}`,
+ name: `filler-${index}.png`,
+ dataBase64: `ZmlsbGVy-${index}`,
+ previewDataUrl: `data:image/png;base64,ZmlsbGVy-${index}`,
+ }))
+ act(() => rendered.result.current.handleAddComposerImageAttachments(filler))
+ expect(rendered.result.current.composerImageAttachments).toHaveLength(19)
+
+ await act(async () => {
+ await rendered.result.current.cancelTask('task-cap')
+ })
+
+ // 19 held + 1 free slot: only 1 of the 3 canceled images returns, and the
+ // toast must say so instead of a plain "Attachments kept".
+ expect(rendered.result.current.composerImageAttachments).toHaveLength(20)
+ const call = keptToastCall(rendered.spies)
+ expect(call?.[0]).toBe(
+ 'Attachments kept — 2 of 3 images exceed the 20-image limit and were dropped.'
+ )
+ expect(call?.[1]).toBe('info')
+ expect(call?.[2]?.action?.label).toBe('Discard all')
+ })
+
+ it('never clears another agent composer from a stale Discard all toast (L3)', async () => {
+ const { result, spies, rerender } = await mountedControllerWithAttachments()
+ await sendAsync(result, 'task-switch')
+
+ await act(async () => {
+ await result.current.cancelTask('task-switch')
+ })
+ const staleAction = keptToastAction(spies)
+ expect(staleAction?.label).toBe('Discard all')
+
+ // The toast outlives an agent switch; the new agent's composer holds its
+ // own fresh attachment that the stale action must not destroy.
+ rerender({ selectedAgent: 'agent-y', agentNames: ['agent-x', 'agent-y'] })
+ const otherAgentImage = {
+ ...image,
+ id: 'agent-y-image',
+ dataBase64: 'YWdlbnQteQ',
+ previewDataUrl: 'data:image/png;base64,YWdlbnQteQ',
+ }
+ act(() => result.current.handleAddComposerImageAttachments([otherAgentImage]))
+ expect(result.current.composerImageAttachments).toHaveLength(1)
+
+ act(() => staleAction?.onAction())
+
+ expect(result.current.composerImageAttachments).toHaveLength(1)
+ expect(result.current.composerImageAttachments[0]).toMatchObject({ id: 'agent-y-image' })
+ })
})
diff --git a/desktop-app/ui/src/hooks/domain/useAgentChatController.ts b/desktop-app/ui/src/hooks/domain/useAgentChatController.ts
index 03afb4785..87e5e7649 100644
--- a/desktop-app/ui/src/hooks/domain/useAgentChatController.ts
+++ b/desktop-app/ui/src/hooks/domain/useAgentChatController.ts
@@ -6,6 +6,7 @@ import {
parseTaskKey,
useAgentTaskTracker,
} from '@contexts/AgentTaskTrackerContext'
+import { COMPOSER_MAX_IMAGE_ATTACHMENTS } from '@constants/attachments'
import {
buildChatMessageAttachments,
buildResponseFileAttachments,
@@ -94,7 +95,7 @@ import {
} from './useChatListController'
import { type ActiveChatVisibility, useChatNotifications } from './useChatNotifications'
import { useChatScroll } from './useChatScroll'
-import { useComposerAttachments } from './useComposerAttachments'
+import { predictComposerImageMerge, useComposerAttachments } from './useComposerAttachments'
import type { PushToastOptions } from './useToastController'
// Re-exported from `useChatListController` (§4.4) so external importers
@@ -3501,13 +3502,19 @@ export function useAgentChatController({
* released), but the attachments of the canceled message return to the
* composer so the user can reuse them. In-memory only: the composer state,
* not GFS or any persisted store, owns the kept attachments.
+ *
+ * The toast reports what actually survived the composer's image cap, and its
+ * Discard-all action is bound to the agent that was canceled: the toast can
+ * outlive an agent switch, and clearing the composer of a DIFFERENT agent
+ * would destroy that agent's own pending attachments.
*/
const restoreComposerAttachmentsAfterCancel = useCallback(
- (taskId: string) => {
+ (taskId: string, agentRef: string) => {
const snapshots = getRetainedSendsForTask(taskId)
const images = snapshots.flatMap(snapshot => snapshot.attachments)
const references = snapshots.flatMap(snapshot => snapshot.references)
if (!images.length && !references.length) return
+ const { dropped } = predictComposerImageMerge(composerImageAttachments, images)
handleAddComposerImageAttachments(
images.map(attachment => ({
...attachment,
@@ -3515,12 +3522,26 @@ export function useAgentChatController({
}))
)
handleAddComposerReferenceAttachments(references)
- pushToast('Attachments kept', 'info', {
- action: { label: 'Discard all', onAction: resetComposerAttachments },
+ const message =
+ dropped > 0
+ ? `Attachments kept — ${dropped} of ${images.length} ${dropped === 1 ? 'image exceeds' : 'images exceed'} the ${COMPOSER_MAX_IMAGE_ATTACHMENTS}-image limit and ${dropped === 1 ? 'was' : 'were'} dropped.`
+ : 'Attachments kept'
+ pushToast(message, 'info', {
+ action: {
+ label: 'Discard all',
+ onAction: () => {
+ // Attachments are per-agent; chat switches do not change who owns
+ // them, but an agent switch does — no-op instead of clearing
+ // another agent's composer.
+ if (activeChatVisibilityRef.current.selectedAgent !== agentRef) return
+ resetComposerAttachments()
+ },
+ },
})
},
[
getRetainedSendsForTask,
+ composerImageAttachments,
handleAddComposerImageAttachments,
handleAddComposerReferenceAttachments,
pushToast,
@@ -3579,7 +3600,7 @@ export function useAgentChatController({
// payload resent, so nothing will read the retained snapshot again. The
// attachments themselves return to the composer (STORY-38) before the
// snapshot that carried them is released.
- restoreComposerAttachmentsAfterCancel(taskId)
+ restoreComposerAttachmentsAfterCancel(taskId, hostRef)
releaseRetainedSendsForTask(taskId)
} catch (err) {
const message = err instanceof Error ? err.message : String(err)
@@ -3587,7 +3608,7 @@ export function useAgentChatController({
markCancelled('Task already finished or is no longer active.')
// The task is gone upstream, so it can no longer produce a terminal
// event — same reasoning as the successful cancel above.
- restoreComposerAttachmentsAfterCancel(taskId)
+ restoreComposerAttachmentsAfterCancel(taskId, hostRef)
releaseRetainedSendsForTask(taskId)
pushToast('That task is no longer active.', 'info')
return
diff --git a/desktop-app/ui/src/hooks/domain/useComposerAttachments.ts b/desktop-app/ui/src/hooks/domain/useComposerAttachments.ts
index 63a6812c3..a640f5d42 100644
--- a/desktop-app/ui/src/hooks/domain/useComposerAttachments.ts
+++ b/desktop-app/ui/src/hooks/domain/useComposerAttachments.ts
@@ -3,6 +3,45 @@ import { COMPOSER_MAX_IMAGE_ATTACHMENTS } from '@constants/attachments'
import { clearComposerDraft, clearComposerDraftAfterSend } from '@lib/composerDraftStore'
import type { ComposerImageAttachment, ComposerReferenceAttachment } from '../../uiTypes'
+export interface ComposerImageMergePrediction {
+ /** Incoming attachments that would take a slot in the composer. */
+ kept: number
+ /** Incoming byte-identical copies of attachments already held (not added). */
+ duplicates: number
+ /** Incoming attachments the 20-image cap leaves no room for (lost). */
+ dropped: number
+}
+
+/**
+ * Mirrors `handleAddComposerImageAttachments`'s dedupe/cap rules exactly, so a
+ * caller that restores a payload can honestly report what will survive before
+ * the state update lands (used by the cancel-restore toast).
+ */
+export function predictComposerImageMerge(
+ existing: ComposerImageAttachment[],
+ incoming: ComposerImageAttachment[]
+): ComposerImageMergePrediction {
+ const accepted = [...existing]
+ let kept = 0
+ let duplicates = 0
+ for (const attachment of incoming) {
+ if (accepted.length >= COMPOSER_MAX_IMAGE_ATTACHMENTS) break
+ const duplicate = accepted.some(
+ candidate =>
+ candidate.mimeType === attachment.mimeType &&
+ candidate.sizeBytes === attachment.sizeBytes &&
+ candidate.dataBase64 === attachment.dataBase64
+ )
+ if (duplicate) {
+ duplicates += 1
+ continue
+ }
+ accepted.push(attachment)
+ kept += 1
+ }
+ return { kept, duplicates, dropped: incoming.length - kept - duplicates }
+}
+
interface UseComposerAttachmentsParams {
/** Attachments are per-agent; switching agents clears the pending composer. */
selectedAgent: string | null