Skip to content

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

TypeScript

fix(desktop-ui): recover dropped documents without losing text or resending them

Alfredo Lopez74535cbdca55
diff --git a/desktop-app/ui/src/hooks/domain/__tests__/sendAgentMessage.documents.test.tsx b/desktop-app/ui/src/hooks/domain/__tests__/sendAgentMessage.documents.test.tsx
index 1eea21e68..8c7009ec7 100644
--- a/desktop-app/ui/src/hooks/domain/__tests__/sendAgentMessage.documents.test.tsx
+++ b/desktop-app/ui/src/hooks/domain/__tests__/sendAgentMessage.documents.test.tsx
@@ -7,7 +7,7 @@
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
import { act, waitFor } from '@testing-library/react'
import { createHash } from 'node:crypto'
-import { getComposerDraft } from '@lib/composerDraftStore'
+import { getComposerDraft, setComposerDraft } from '@lib/composerDraftStore'
import { loadHostModels, resetHostModelSelectionStore } from '@lib/hostModelSelectionStore'
import type { HostModelsResult } from '../../../../../src/types'
import { renderController } from './__fixtures__/controllerHarness'
@@ -320,6 +320,45 @@ describe('sendAgentMessage — a Host without file attachments (#678 D13)', () =
expect(rendered.result.current.failedAgentSend?.files).toHaveLength(2)
})
+ it('recovers only the files the Host did not receive after a partial drop', async () => {
+ const rendered = renderController()
+ await settleMount()
+ act(() => {
+ rendered.result.current.handleAddComposerFiles(
+ [
+ new File([NOTES_BYTES], 'a.txt', { type: 'text/plain' }),
+ new File([NOTES_BYTES], 'b.txt', { type: 'text/plain' }),
+ ],
+ ''
+ )
+ })
+ await waitFor(() =>
+ expect(rendered.result.current.composerFileAttachments.map(item => item.status)).toEqual([
+ 'ready',
+ 'ready',
+ ])
+ )
+ const [delivered, dropped] = rendered.result.current.composerFileAttachments
+ clerum.rpc.invokeHostMessage.mockResolvedValueOnce({
+ response: 'done',
+ acceptedAttachmentIds: [delivered!.id],
+ })
+ await act(async () => {
+ await rendered.result.current.handleSendAgentMessage('Summarize these')
+ })
+ // Witness: the failure is a files-only recovery holding both documents.
+ expect(rendered.result.current.failedAgentSend?.answeredWithoutFiles).toBe(true)
+ expect(rendered.result.current.failedAgentSend?.files).toHaveLength(2)
+
+ act(() => rendered.result.current.handleRecoverFailedAgentSend())
+
+ // The Host read a.txt already: only b.txt comes back to attach again.
+ expect(rendered.result.current.composerFileAttachments.map(item => item.id)).toEqual([
+ dropped!.id,
+ ])
+ expect(rendered.result.current.failedAgentSend).toBeNull()
+ })
+
it('async task accepted without listing the file: keeps the snapshot after the task succeeds', async () => {
clerum.rpc.getTaskResult.mockResolvedValue({ status: 'completed', response: 'all done' })
const rendered = renderController()
@@ -366,6 +405,49 @@ describe('sendAgentMessage — a Host without file attachments (#678 D13)', () =
expect(rendered.result.current.failedAgentSend?.answeredWithoutFiles).toBe(true)
})
+ it('async task accepted without listing the file, then failed: the text comes back with the files', async () => {
+ clerum.rpc.getTaskResult.mockResolvedValue({
+ status: 'failed',
+ error: { message: 'LLM down', code: 'provider_error' },
+ })
+ const rendered = renderController()
+ await settleMount()
+ const file = await addReadyFile(rendered)
+ clerum.rpc.invokeHostMessage.mockResolvedValueOnce({
+ taskId: 'task-doc',
+ acceptedAttachmentIds: [],
+ })
+ const send = act(async () => {
+ await rendered.result.current.handleSendAgentMessage('Summarize this')
+ })
+ await waitFor(() => expect(clerum.hasProgressHandler('task-doc')).toBe(true))
+ await send
+ // Witness: the drop was recorded first, as a files-only recovery.
+ expect(rendered.result.current.failedAgentSend?.answeredWithoutFiles).toBe(true)
+ const chat = rendered.result.current.activeChatId
+
+ await act(async () => {
+ clerum.emitTaskProgress('task-doc', {
+ type: 'terminal',
+ data: { taskId: 'task-doc', status: 'failed' },
+ })
+ })
+
+ // Witness that the failure branch ran: its message replaced the drop notice.
+ await waitFor(() => expect(rendered.result.current.failedAgentSend?.message).toBe('LLM down'))
+ // The task answered nothing, so this is a rejected send: text and files.
+ expect(rendered.result.current.failedAgentSend?.answeredWithoutFiles).toBe(false)
+ expect(rendered.result.current.failedAgentSend?.files.map(item => item.id)).toEqual([file.id])
+
+ act(() => rendered.result.current.handleRecoverFailedAgentSend())
+
+ expect(getComposerDraft(chat, 'agent-x')).toBe('Summarize this')
+ expect(rendered.result.current.composerFileAttachments).toEqual([
+ expect.objectContaining({ id: file.id, status: 'ready', digestHex: NOTES_DIGEST }),
+ ])
+ expect(clerum.rpc.invokeHostMessage).toHaveBeenCalledTimes(1)
+ })
+
it('titles a new chat from both the images and the documents of a send without text', async () => {
clerum.rpc.invokeHostMessage.mockResolvedValue({ response: 'done' })
const modelTransport = {
@@ -490,4 +572,40 @@ describe('sendAgentMessage — a message answered without its documents', () =>
expect(rendered.result.current.failedAgentSend).toBeNull()
expect(clerum.rpc.invokeHostMessage).toHaveBeenCalledTimes(1)
})
+
+ it('recovers the files next to a new draft and keeps the draft', async () => {
+ const rendered = renderController()
+ await settleMount()
+ const file = await answeredWithoutFiles(rendered)
+ const chat = rendered.result.current.activeChatId
+ act(() => setComposerDraft(chat, 'A new question', 'agent-x'))
+
+ act(() => rendered.result.current.handleRecoverFailedAgentSend())
+
+ expect(rendered.result.current.composerFileAttachments).toEqual([
+ expect.objectContaining({ id: file.id, status: 'ready' }),
+ ])
+ expect(getComposerDraft(chat, 'agent-x')).toBe('A new question')
+ expect(rendered.result.current.failedAgentSend).toBeNull()
+ })
+
+ it('does not replace documents already in the composer', async () => {
+ const rendered = renderController()
+ await settleMount()
+ const file = await answeredWithoutFiles(rendered)
+ const other = await addReadyFile(
+ rendered,
+ new File([new TextEncoder().encode('other')], 'other.txt', { type: 'text/plain' })
+ )
+
+ act(() => rendered.result.current.handleRecoverFailedAgentSend())
+
+ // Witness: the refusal was shown, so the recover path ran.
+ expect(rendered.spies.pushToast).toHaveBeenCalledWith(
+ 'Remove the documents in the composer before recovering the earlier files.',
+ 'error'
+ )
+ expect(rendered.result.current.composerFileAttachments.map(item => item.id)).toEqual([other.id])
+ expect(rendered.result.current.failedAgentSend?.files.map(item => item.id)).toEqual([file.id])
+ })
})
diff --git a/desktop-app/ui/src/hooks/domain/useAgentChatController.ts b/desktop-app/ui/src/hooks/domain/useAgentChatController.ts
index 265ae7621..40da25d7c 100644
--- a/desktop-app/ui/src/hooks/domain/useAgentChatController.ts
+++ b/desktop-app/ui/src/hooks/domain/useAgentChatController.ts
@@ -3221,11 +3221,13 @@ export function useAgentChatController({
// only in this composer, so the send keeps its snapshot and shows the
// failure instead of looking delivered.
let filesNotDeliveredMessage: string | null = null
+ let undeliveredFileIds: string[] = []
if (ackOk && !ackIsEmpty && effectiveFiles.length > 0) {
const acceptedAttachmentIds = new Set<string>(
Array.isArray(response.acceptedAttachmentIds) ? response.acceptedAttachmentIds : []
)
const undelivered = effectiveFiles.filter(file => !acceptedAttachmentIds.has(file.id))
+ undeliveredFileIds = undelivered.map(file => file.id)
if (undelivered.length > 0) {
filesNotDeliveredMessage =
undelivered.length === effectiveFiles.length
@@ -3319,7 +3321,8 @@ export function useAgentChatController({
userMessageId,
'host_files_dropped',
filesNotDeliveredMessage,
- 'upstream'
+ 'upstream',
+ undeliveredFileIds
)
updateMessageActivity(sendAgent, userMessageId, previous => ({
...previous,
@@ -3361,7 +3364,13 @@ export function useAgentChatController({
if (filesNotDeliveredMessage) {
// The task runs without the documents; the snapshot survives its
// success (see releaseSucceededRetainedSendsForTask).
- markRetainedSendReason(taskId, 'host_files_dropped', filesNotDeliveredMessage, 'upstream')
+ markRetainedSendReason(
+ taskId,
+ 'host_files_dropped',
+ filesNotDeliveredMessage,
+ 'upstream',
+ undeliveredFileIds
+ )
}
activityTaskToMessageByAgentRef.current[sendAgent] = {
...(activityTaskToMessageByAgentRef.current[sendAgent] || {}),
@@ -3631,6 +3640,23 @@ export function useAgentChatController({
visibleFailure.chatId !== activeChatVisibilityRef.current.activeChatId
)
return
+ if (visibleFailure.answeredWithoutFiles) {
+ // The text and the other attachments were answered: bring back only the
+ // documents the Host never received, and send nothing. Restoring replaces
+ // the composer's documents, so only documents already there block it; a
+ // new draft or other attachments stay as they are.
+ if (composerFileAttachments.length) {
+ pushToast(
+ 'Remove the documents in the composer before recovering the earlier files.',
+ 'error'
+ )
+ return
+ }
+ const undelivered = new Set(visibleFailure.undeliveredFileIds ?? [])
+ handleRestoreComposerFiles(visibleFailure.files.filter(file => undelivered.has(file.id)))
+ handleDiscardFailedAgentSend()
+ return
+ }
if (
getComposerDraft(activeChatId, selectedAgent ?? undefined) ||
composerImageAttachments.length ||
@@ -3640,13 +3666,6 @@ export function useAgentChatController({
pushToast('Keep or clear the current draft before recovering the earlier input.', 'error')
return
}
- if (visibleFailure.answeredWithoutFiles) {
- // The text and the other attachments were answered: bring back only the
- // documents the Host never received, and send nothing.
- handleRestoreComposerFiles(visibleFailure.files)
- handleDiscardFailedAgentSend()
- return
- }
setComposerDraft(activeChatId, visibleFailure.content, selectedAgent ?? undefined)
handleAddComposerImageAttachments(
visibleFailure.attachments.map(attachment => ({
diff --git a/desktop-app/ui/src/lib/__tests__/retainedSendStore.test.ts b/desktop-app/ui/src/lib/__tests__/retainedSendStore.test.ts
index aa20d2f11..f7524239d 100644
--- a/desktop-app/ui/src/lib/__tests__/retainedSendStore.test.ts
+++ b/desktop-app/ui/src/lib/__tests__/retainedSendStore.test.ts
@@ -105,9 +105,33 @@ describe('retainedSendStore — documents the Host never received (#678 D13)', (
expect(held(store, ['chat-1/delivered'])).toEqual([])
})
+ it('keeps the undelivered file ids only while the text counts as answered', () => {
+ const store = createRetainedSendStore(vi.fn())
+ store.retainSendSnapshot(
+ snapshot('with-files', 200, { reason: 'awaiting_terminal', failure: undefined })
+ )
+ store.attachTaskIdToRetainedSend('agent-x', 'chat-1', 'with-files', 'task-files')
+ store.markRetainedSendReason('task-files', 'host_files_dropped', 'Dropped.', 'upstream', ['b'])
+ // Witness: the drop recorded which document the Host did not admit.
+ const dropped = store.getRetainedSendSnapshot('agent-x', 'chat-1', 'with-files')
+ expect(dropped?.undeliveredFileIds).toEqual(['b'])
+
+ store.markRetainedSendReason('task-files', 'async_task_failed', 'Failed.', 'upstream')
+
+ // The text was not answered either: a retry sends every document again.
+ const failed = store.getRetainedSendSnapshot('agent-x', 'chat-1', 'with-files')
+ expect(failed?.reason).toBe('host_files_unsupported')
+ expect(failed).not.toHaveProperty('undeliveredFileIds')
+ })
+
// Both reasons hold documents that exist nowhere else: a rejected send
// (nothing answered) and a message answered without its documents.
describe.each(['host_files_unsupported', 'host_files_dropped'] as const)('%s', reason => {
+ // A failure recorded after the drop means the text was not answered
+ // either: the snapshot becomes a rejected send, so the files stay held and
+ // the text and Retry come back.
+ const reasonAfterFailure = 'host_files_unsupported'
+
it('keeps the snapshot of a task that succeeded without its files', () => {
const store = createRetainedSendStore(vi.fn())
store.retainSendSnapshot(snapshot('older', 100))
@@ -178,7 +202,7 @@ describe('retainedSendStore — documents the Host never received (#678 D13)', (
expect(held(store, SEEDED)).toEqual(['chat-1/later'])
})
- it('a later task failure updates the message and keeps the undelivered-files reason', () => {
+ it('a later task failure updates the message and keeps the files held as a rejected send', () => {
const store = createRetainedSendStore(vi.fn())
store.retainSendSnapshot(
snapshot('with-files', 200, { reason: 'awaiting_terminal', failure: undefined })
@@ -201,13 +225,13 @@ describe('retainedSendStore — documents the Host never received (#678 D13)', (
const kept = store.getRetainedSendSnapshot('agent-x', 'chat-1', 'with-files')
// Witness: the second mark ran and replaced the failure message.
expect(kept?.failure).toEqual({ message: 'The task failed.', kind: 'upstream' })
- expect(kept?.reason).toBe(reason)
+ expect(kept?.reason).toBe(reasonAfterFailure)
// So the task's later success still keeps it.
store.releaseSucceededRetainedSendsForTask('task-files')
expect(held(store, ['chat-1/with-files'])).toEqual(['chat-1/with-files'])
})
- it('a later send failure updates the message and keeps the undelivered-files reason', () => {
+ it('a later send failure updates the message and keeps the files held as a rejected send', () => {
const store = seedUndeliveredFiles()
store.failRetainedSend(
@@ -221,7 +245,7 @@ describe('retainedSendStore — documents the Host never received (#678 D13)', (
const kept = store.getRetainedSendSnapshot('agent-x', 'chat-1', 'undelivered')
expect(kept?.failure).toEqual({ message: 'The stream was lost.', kind: 'network' })
- expect(kept?.reason).toBe(reason)
+ expect(kept?.reason).toBe(reasonAfterFailure)
})
})
})
diff --git a/desktop-app/ui/src/lib/retainedSendStore.ts b/desktop-app/ui/src/lib/retainedSendStore.ts
index abadd9341..a8969495a 100644
--- a/desktop-app/ui/src/lib/retainedSendStore.ts
+++ b/desktop-app/ui/src/lib/retainedSendStore.ts
@@ -42,6 +42,12 @@ export interface RetainedSendSnapshot {
model?: string
/** Why the snapshot is still retained (stable code for tests/telemetry). */
reason: RetainedSendReason
+ /**
+ * Set only with `host_files_dropped`: the ids of the documents the Host did
+ * not admit. `files` keeps every document so a later failure can still retry
+ * the whole send; recovery after the answer brings back only these.
+ */
+ undeliveredFileIds?: string[]
timestamp: number
draftRevision: number
failure?: { message: string; kind: FailedAgentSend['kind'] }
@@ -199,17 +205,41 @@ export function createRetainedSendStore(changed: () => void) {
}
/**
- * A snapshot whose documents the Host never received keeps that reason when a
+ * A snapshot whose documents the Host never received keeps holding them when a
* later failure is recorded: the reason is what stops a later success from
- * releasing files that exist nowhere else. Only the shown failure changes.
+ * releasing files that exist nowhere else. A failure after `host_files_dropped`
+ * means the text was not answered either, so the snapshot becomes a rejected
+ * send (`host_files_unsupported`) and Retry and text recovery come back.
*/
function nextReason(
snapshot: RetainedSendSnapshot,
reason: RetainedSendReason
): RetainedSendReason {
+ if (snapshot.reason === 'host_files_dropped' && reason !== 'host_files_dropped') {
+ return 'host_files_unsupported'
+ }
return holdsUndeliveredFiles(snapshot.reason) ? snapshot.reason : reason
}
+ /** The failed snapshot, with the undelivered ids kept only while the text counts as answered. */
+ function withFailure(
+ snapshot: RetainedSendSnapshot,
+ reason: RetainedSendReason,
+ message: string,
+ kind: FailedAgentSend['kind'],
+ undeliveredFileIds: string[] | undefined
+ ): RetainedSendSnapshot {
+ const { undeliveredFileIds: previousIds, ...rest } = snapshot
+ const next = nextReason(snapshot, reason)
+ const ids = next === 'host_files_dropped' ? (undeliveredFileIds ?? previousIds) : undefined
+ return {
+ ...rest,
+ reason: next,
+ ...(ids ? { undeliveredFileIds: ids } : {}),
+ failure: { message, kind },
+ }
+ }
+
/**
* Records why a snapshot is still held once the async outcome is known. Keeps
* the payload and identity untouched; only the recovery code changes.
@@ -218,15 +248,12 @@ export function createRetainedSendStore(changed: () => void) {
taskId: string,
reason: RetainedSendReason,
message: string,
- kind: FailedAgentSend['kind']
+ kind: FailedAgentSend['kind'],
+ undeliveredFileIds?: string[]
): void {
for (const [key, snapshot] of snapshots) {
if (snapshot.taskId !== taskId) continue
- snapshots.set(key, {
- ...snapshot,
- reason: nextReason(snapshot, reason),
- failure: { message, kind },
- })
+ snapshots.set(key, withFailure(snapshot, reason, message, kind, undeliveredFileIds))
changed()
}
}
@@ -243,16 +270,13 @@ export function createRetainedSendStore(changed: () => void) {
userMessageId: string,
reason: RetainedSendReason,
message: string,
- kind: FailedAgentSend['kind']
+ kind: FailedAgentSend['kind'],
+ undeliveredFileIds?: string[]
): void {
const key = keyFor(agentRef, chatId, userMessageId)
const existing = snapshots.get(key)
if (!existing) return
- snapshots.set(key, {
- ...existing,
- reason: nextReason(existing, reason),
- failure: { message, kind },
- })
+ snapshots.set(key, withFailure(existing, reason, message, kind, undeliveredFileIds))
changed()
}
return {
diff --git a/desktop-app/ui/src/uiTypes.ts b/desktop-app/ui/src/uiTypes.ts
index 192fe810c..7ca3ba208 100644
--- a/desktop-app/ui/src/uiTypes.ts
+++ b/desktop-app/ui/src/uiTypes.ts
@@ -180,6 +180,11 @@ export type FailedAgentSend = {
* Only the documents can be recovered; a retry would send the text again.
*/
answeredWithoutFiles?: boolean
+ /**
+ * With `answeredWithoutFiles`: the documents the Host did not admit. The Host
+ * already read the others, so recovery brings back only these.
+ */
+ undeliveredFileIds?: string[]
}
export type HostConnectionTone = 'healthy' | 'degraded' | 'offline'