Skip to content

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

TypeScript

fix(desktop): reconcile cancel-restore drops from one live snapshot (R1-M4)

Md852a9dc9337
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 8ce418203..2300631d3 100644
--- a/desktop-app/ui/src/hooks/domain/__tests__/cancelKeepsAttachments.test.tsx
+++ b/desktop-app/ui/src/hooks/domain/__tests__/cancelKeepsAttachments.test.tsx
@@ -359,4 +359,56 @@ describe('STORY-38 — attachments survive message cancel', () => {
expect(result.current.composerImageAttachments).toHaveLength(1)
})
+
+ it('reports drops from the live composer state, not the render closure at cancel time (R1-M4)', async () => {
+ // The composer fills to 19 WHILE the cancel RPC is in flight — after the
+ // executing closure was captured. The toast must report drops against the
+ // state the merge actually reconciled with, not the stale empty snapshot.
+ let resolveCancel!: () => void
+ clerum.rpc.cancelTask.mockReturnValue(
+ new Promise<void>(resolve => {
+ resolveCancel = resolve
+ })
+ )
+ 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-race')
+
+ let cancelDone!: Promise<void>
+ act(() => {
+ cancelDone = rendered.result.current.cancelTask('task-race')
+ })
+ // 19 fresh images land in the composer while the RPC is pending.
+ 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 () => {
+ resolveCancel()
+ await cancelDone
+ })
+
+ 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.'
+ )
+ })
})
diff --git a/desktop-app/ui/src/hooks/domain/useAgentChatController.ts b/desktop-app/ui/src/hooks/domain/useAgentChatController.ts
index 8c56ae25d..2ecad6c44 100644
--- a/desktop-app/ui/src/hooks/domain/useAgentChatController.ts
+++ b/desktop-app/ui/src/hooks/domain/useAgentChatController.ts
@@ -95,7 +95,7 @@ import {
} from './useChatListController'
import { type ActiveChatVisibility, useChatNotifications } from './useChatNotifications'
import { useChatScroll } from './useChatScroll'
-import { predictComposerImageMerge, useComposerAttachments } from './useComposerAttachments'
+import { useComposerAttachments } from './useComposerAttachments'
import type { PushToastOptions } from './useToastController'
// Re-exported from `useChatListController` (§4.4) so external importers
@@ -708,6 +708,7 @@ export function useAgentChatController({
handleRemoveComposerImageAttachment,
handleAddComposerReferenceAttachments,
handleRemoveComposerReferenceAttachment,
+ restoreComposerImageAttachments,
} = useComposerAttachments({ selectedAgent, clearSendError: clearComposerSendError })
const { chatEndRef, scrollChatToBottom } = useChatScroll({
@@ -3522,8 +3523,9 @@ export function useAgentChatController({
activeChatVisibilityRef.current.selectedAgent === agentRef &&
activeChatVisibilityRef.current.activeChatId === originChatId
if (!stillViewingOrigin()) return
- const { dropped } = predictComposerImageMerge(composerImageAttachments, images)
- handleAddComposerImageAttachments(
+ // One merge against the live composer snapshot — the counts and the
+ // committed state can never disagree (R1-M4).
+ const { dropped } = restoreComposerImageAttachments(
images.map(attachment => ({
...attachment,
previewDataUrl: `data:${attachment.mimeType};base64,${attachment.dataBase64}`,
@@ -3546,11 +3548,10 @@ export function useAgentChatController({
},
[
getRetainedSendsForTask,
- composerImageAttachments,
- handleAddComposerImageAttachments,
handleAddComposerReferenceAttachments,
pushToast,
resetComposerAttachments,
+ restoreComposerImageAttachments,
]
)
diff --git a/desktop-app/ui/src/hooks/domain/useComposerAttachments.ts b/desktop-app/ui/src/hooks/domain/useComposerAttachments.ts
index a640f5d42..5bd32d75d 100644
--- a/desktop-app/ui/src/hooks/domain/useComposerAttachments.ts
+++ b/desktop-app/ui/src/hooks/domain/useComposerAttachments.ts
@@ -3,8 +3,10 @@ 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. */
+export interface ComposerImageMergeOutcome {
+ /** The reconciled composer set (existing + accepted incoming, in order). */
+ next: ComposerImageAttachment[]
+ /** Incoming attachments that took a slot in the composer. */
kept: number
/** Incoming byte-identical copies of attachments already held (not added). */
duplicates: number
@@ -13,14 +15,17 @@ export interface ComposerImageMergePrediction {
}
/**
- * 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).
+ * Reconciles incoming images into the composer's image set with the same
+ * dedupe/cap rules as the add handler, returning the merged set AND the
+ * counts. The restore path calls this against the live composer snapshot and
+ * commits the returned `next` directly, so the reported counts can never
+ * disagree with the state the user sees (spec: restore semantics).
*/
-export function predictComposerImageMerge(
+export function mergeComposerImageAttachments(
existing: ComposerImageAttachment[],
- incoming: ComposerImageAttachment[]
-): ComposerImageMergePrediction {
+ incoming: ComposerImageAttachment[],
+ nextOrder: () => number = () => 0
+): ComposerImageMergeOutcome {
const accepted = [...existing]
let kept = 0
let duplicates = 0
@@ -36,10 +41,12 @@ export function predictComposerImageMerge(
duplicates += 1
continue
}
- accepted.push(attachment)
+ accepted.push(
+ attachment.addedOrder != null ? attachment : { ...attachment, addedOrder: nextOrder() }
+ )
kept += 1
}
- return { kept, duplicates, dropped: incoming.length - kept - duplicates }
+ return { next: accepted, kept, duplicates, dropped: incoming.length - kept - duplicates }
}
interface UseComposerAttachmentsParams {
@@ -60,6 +67,12 @@ interface UseComposerAttachmentsParams {
* and the composer-draft-store integration. Extracted from `useAgentChatController`
* (Fase 1) with NO observable behavior change — the parent composes this and
* re-exposes the same public handlers to consumers.
+ *
+ * The ref mirrors (`composerImageAttachmentsRef` / `composerReferenceAttachmentsRef`)
+ * are written inside every state updater, so they always reflect the committed
+ * transitions — never a stale render closure. The cancel-restore path reads and
+ * writes through them so its reconciliation and its drop reporting use ONE
+ * snapshot (R1-M4).
*/
export function useComposerAttachments({
selectedAgent,
@@ -73,6 +86,8 @@ export function useComposerAttachments({
>([])
const composerAttachmentOrderRef = useRef(0)
const composerAttachmentRevisionRef = useRef(0)
+ const composerImageAttachmentsRef = useRef<ComposerImageAttachment[]>([])
+ const composerReferenceAttachmentsRef = useRef<ComposerReferenceAttachment[]>([])
const revokeComposerPreviewUrls = useCallback((attachments: ComposerImageAttachment[]) => {
composerAttachmentRevisionRef.current += 1
@@ -93,6 +108,7 @@ export function useComposerAttachments({
composerAttachmentRevisionRef.current += 1
setComposerImageAttachments(previous => {
revokeComposerPreviewUrls(previous)
+ composerImageAttachmentsRef.current = []
return []
})
}, [revokeComposerPreviewUrls])
@@ -100,7 +116,10 @@ export function useComposerAttachments({
/** Clear BOTH pending attachment kinds (revoking image blob URLs). */
const resetComposerAttachments = useCallback(() => {
clearComposerImageAttachments()
- setComposerReferenceAttachments([])
+ setComposerReferenceAttachments(previous => {
+ composerReferenceAttachmentsRef.current = []
+ return []
+ })
}, [clearComposerImageAttachments])
/** Post-send cleanup: clear the persisted draft for this chat, then the pending
@@ -148,6 +167,7 @@ export function useComposerAttachments({
addedOrder: attachment.addedOrder ?? composerAttachmentOrderRef.current,
})
}
+ composerImageAttachmentsRef.current = next
return next
})
clearSendError()
@@ -170,6 +190,7 @@ export function useComposerAttachments({
}
const next = [...previous]
next[index] = attachment
+ composerImageAttachmentsRef.current = next
return next
})
clearSendError()
@@ -185,12 +206,41 @@ export function useComposerAttachments({
if (removed.length) {
revokeComposerPreviewUrls(removed)
}
- return previous.filter(att => att.id !== attachmentId)
+ const next = previous.filter(att => att.id !== attachmentId)
+ composerImageAttachmentsRef.current = next
+ return next
})
},
[revokeComposerPreviewUrls]
)
+ /**
+ * Restore-path reconciliation for images (R1-M4): one merge against the live
+ * snapshot (the ref mirror written by every committed transition), committed
+ * directly, returning the counts that describe exactly that snapshot.
+ */
+ const restoreComposerImageAttachments = useCallback(
+ (incoming: ComposerImageAttachment[]): ComposerImageMergeOutcome => {
+ composerAttachmentRevisionRef.current += 1
+ const outcome = mergeComposerImageAttachments(
+ composerImageAttachmentsRef.current,
+ incoming,
+ () => {
+ composerAttachmentOrderRef.current += 1
+ return composerAttachmentOrderRef.current
+ }
+ )
+ for (const attachment of incoming) {
+ if (!outcome.next.includes(attachment)) revokeComposerPreviewUrls([attachment])
+ }
+ composerImageAttachmentsRef.current = outcome.next
+ setComposerImageAttachments(outcome.next)
+ clearSendError()
+ return outcome
+ },
+ [clearSendError, revokeComposerPreviewUrls]
+ )
+
const handleAddComposerReferenceAttachments = useCallback(
(attachments: ComposerReferenceAttachment[]) => {
composerAttachmentRevisionRef.current += 1
@@ -206,6 +256,7 @@ export function useComposerAttachments({
})
}
}
+ composerReferenceAttachmentsRef.current = next
return next
})
clearSendError()
@@ -216,7 +267,11 @@ export function useComposerAttachments({
const handleRemoveComposerReferenceAttachment = useCallback(
(attachmentId: string) => {
composerAttachmentRevisionRef.current += 1
- setComposerReferenceAttachments(previous => previous.filter(att => att.id !== attachmentId))
+ setComposerReferenceAttachments(previous => {
+ const next = previous.filter(att => att.id !== attachmentId)
+ composerReferenceAttachmentsRef.current = next
+ return next
+ })
// Removing a file is how the user answers the "at most 10 files" refusal,
// so the refusal must not stay on screen afterwards.
clearSendError()
@@ -236,5 +291,6 @@ export function useComposerAttachments({
handleRemoveComposerImageAttachment,
handleAddComposerReferenceAttachments,
handleRemoveComposerReferenceAttachment,
+ restoreComposerImageAttachments,
}
}