Evenfire is an intelligence layer platform for running LLM agents that take real actions, on your infrastructure
TypeScript
fix(desktop-app): preserve attachment identity through reconciliation
Mb0d6ebeeade5
diff --git a/desktop-app/src/__tests__/chatMessageMerge.test.ts b/desktop-app/src/__tests__/chatMessageMerge.test.tsindex f5d7ced17..d9268f5fd 100644--- a/desktop-app/src/__tests__/chatMessageMerge.test.ts+++ b/desktop-app/src/__tests__/chatMessageMerge.test.ts@@ -16,6 +16,66 @@ const imageWithBytes: ChatMessageAttachment = {}describe('mergeAuthoritativeServerMessages image byte gap-fill', () => {+ it('never duplicates same-name logical images across reconciliation or a repeated merge', () => {+ fc.assert(+ fc.property(+ fc.array(fc.constantFrom('chart.png', 'photo.png'), { minLength: 1, maxLength: 8 }),+ names => {+ const localImages: ChatMessageAttachment[] = names.map((label, index) => ({+ id: `local-${index}`,+ type: 'uploaded_file',+ label,+ filename: label,+ mimeType: 'image/png',+ encoding: 'base64',+ dataBase64: Buffer.from([index]).toString('base64'),+ sizeBytes: 1,+ }))+ const serverImages: ChatMessageAttachment[] = names.map((label, index) => ({+ id: `parsed:uploaded_file:${index}:${label}`,+ type: 'uploaded_file',+ label,+ }))+ const server: ChatMessage = {+ id: 'turn-1-user',+ role: 'user',+ content: 'Analyze',+ timestamp: 2,+ serverTurnNumber: 1,+ task_id: 'task-1',+ attachments: [+ { id: 'server-plugin', type: 'plugin', label: 'profits/revenue' },+ ...serverImages,+ ],+ }+ const local: ChatMessage = {+ id: 'optimistic-user',+ role: 'user',+ content: 'Analyze',+ timestamp: 1,+ task_id: 'task-1',+ attachments: localImages,+ }+ const [merged] = mergeAuthoritativeServerMessages([local], [server], {+ activeTaskIds: new Set(['task-1']),+ })+ const uploaded = merged?.attachments?.filter(+ attachment => attachment.type === 'uploaded_file'+ )+ expect(uploaded).toHaveLength(names.length)+ expect(uploaded?.map(attachment => attachment.dataBase64)).toEqual(+ localImages.map(attachment => attachment.dataBase64)+ )+ expect(merged?.attachments?.[0]).toEqual(server.attachments?.[0])+ expect(mergeAuthoritativeServerMessages([merged!], [server])[0]?.attachments).toEqual(+ merged?.attachments+ )+ }+ ),+ { numRuns: 250 }+ )+ })+it('keeps server reference chips and enriches a matching image during live-task replacement', () => {const serverPlugin: ChatMessageAttachment = {id: 'server-plugin',diff --git a/desktop-app/src/chatMessageMerge.ts b/desktop-app/src/chatMessageMerge.tsindex 4f0d92d8f..f7486a24f 100644--- a/desktop-app/src/chatMessageMerge.ts+++ b/desktop-app/src/chatMessageMerge.ts@@ -18,53 +18,66 @@ function attachmentName(attachment: ChatMessageAttachment): string {return (attachment.filename || attachment.label).trim()}-/** Preserve server chips while recovering bytes that only the optimistic message has. */-function mergeByteBearingAttachments(+/** Keep server chips in order while pairing repeated image names by occurrence. */+function mergeAttachmentChips(server: ChatMessageAttachment[] | undefined,local: ChatMessageAttachment[] | undefined): ChatMessageAttachment[] | undefined {if (!server?.length) return localif (!local?.length) return server- const byteBearing = local.filter(attachment => Boolean(attachment.dataBase64))- if (!byteBearing.length) return server- const consumed = new Set<ChatMessageAttachment>()- const merged = server.map(serverAttachment => {- const sameId = byteBearing.find(- localAttachment =>- !consumed.has(localAttachment) &&- localAttachment.type === serverAttachment.type &&- localAttachment.id === serverAttachment.id+ const matchedLocalIndexes = new Set<number>()+ const localIndexByServerIndex = new Map<number, number>()+ const pair = (serverIndex: number, predicate: (attachment: ChatMessageAttachment) => boolean) => {+ const localIndex = local.findIndex(+ (attachment, index) =>+ !matchedLocalIndexes.has(index) &&+ (attachment.type === 'uploaded_file' || Boolean(attachment.dataBase64)) &&+ predicate(attachment))- const name = attachmentName(serverAttachment)- const nameCandidates = name- ? byteBearing.filter(- localAttachment =>- !consumed.has(localAttachment) &&- localAttachment.type === serverAttachment.type &&- attachmentName(localAttachment) === name- )- : []- const serverNameIsUnique =- name &&- server.filter(- attachment =>- attachment.type === serverAttachment.type && attachmentName(attachment) === name- ).length === 1- const match =- sameId ?? (serverNameIsUnique && nameCandidates.length === 1 ? nameCandidates[0] : undefined)- if (!match) return serverAttachment- consumed.add(match)+ if (localIndex < 0) return+ matchedLocalIndexes.add(localIndex)+ localIndexByServerIndex.set(serverIndex, localIndex)+ }++ // Stable IDs win even when the server changes a display label.+ server.forEach((attachment, index) => {+ pair(index, candidate => candidate.type === attachment.type && candidate.id === attachment.id)+ })+ // Parsed server IDs differ from optimistic IDs. Pair the remaining chips by+ // type + name in order, including collisions such as two "photo.png" images.+ server.forEach((attachment, index) => {+ if (localIndexByServerIndex.has(index)) return+ const name = attachmentName(attachment)+ if (name) {+ pair(+ index,+ candidate => candidate.type === attachment.type && attachmentName(candidate) === name+ )+ }+ })++ const merged = server.map((attachment, index) => {+ const localIndex = localIndexByServerIndex.get(index)+ const match = localIndex === undefined ? undefined : local[localIndex]+ if (!match?.dataBase64) return attachmentreturn {- ...serverAttachment,- filename: serverAttachment.filename ?? match.filename,- mimeType: serverAttachment.mimeType ?? match.mimeType,- encoding: serverAttachment.encoding ?? match.encoding,- dataBase64: serverAttachment.dataBase64 ?? match.dataBase64,- sizeBytes: serverAttachment.sizeBytes ?? match.sizeBytes,+ ...attachment,+ filename: attachment.filename ?? match.filename,+ mimeType: attachment.mimeType ?? match.mimeType,+ encoding: attachment.encoding ?? match.encoding,+ dataBase64: attachment.dataBase64 ?? match.dataBase64,+ sizeBytes: attachment.sizeBytes ?? match.sizeBytes,}})- return [...merged, ...byteBearing.filter(attachment => !consumed.has(attachment))]+ return [+ ...merged,+ ...local.filter(+ (attachment, index) =>+ !matchedLocalIndexes.has(index) &&+ (attachment.type === 'uploaded_file' || Boolean(attachment.dataBase64))+ ),+ ]}function preferredServerMessage(@@ -76,7 +89,7 @@ function preferredServerMessage(return {...server,task_id: local.task_id ?? server.task_id,- attachments: mergeByteBearingAttachments(server.attachments, local.attachments),+ attachments: mergeAttachmentChips(server.attachments, local.attachments),toolSteps: server.toolSteps?.length ? server.toolSteps : local.toolSteps,}}@@ -416,7 +429,7 @@ export function mergeAuthoritativeServerMessages(if (collapsedEcho) {hydrated = {...hydrated,- attachments: mergeByteBearingAttachments(hydrated.attachments, collapsedEcho.attachments),+ attachments: mergeAttachmentChips(hydrated.attachments, collapsedEcho.attachments),toolSteps: hydrated.toolSteps?.length ? hydrated.toolSteps : collapsedEcho.toolSteps,}}diff --git a/desktop-app/src/types.ts b/desktop-app/src/types.tsindex 42d99f7cf..f451ccc6b 100644--- a/desktop-app/src/types.ts+++ b/desktop-app/src/types.ts@@ -1221,6 +1221,12 @@ export interface ChatMessageAttachment {encoding?: 'base64'dataBase64?: stringsizeBytes?: number+ /** Reference identity survives server-turn display parsing for Resend. */+ filesystemName?: string+ path?: string+ drive?: string+ resourceId?: string+ gfsUri?: string}export interface ChatFile {diff --git a/desktop-app/ui/src/components/agents/__tests__/ChatThread.resend.test.tsx b/desktop-app/ui/src/components/agents/__tests__/ChatThread.resend.test.tsxindex b603ad5a8..8b695bc46 100644--- a/desktop-app/ui/src/components/agents/__tests__/ChatThread.resend.test.tsx+++ b/desktop-app/ui/src/components/agents/__tests__/ChatThread.resend.test.tsx@@ -6,6 +6,8 @@ import {resetComposerDraftStore,setComposerDraft,} from '@lib/composerDraftStore'+import { mergeAuthoritativeServerMessages } from '../../../../../src/chatMessageMerge'+import { turnsToChatMessages } from '../../../hooks/sessionAdapter'import { buildLoadedChatSemanticModels } from '../../../lib/chatMessageSemantics'import type { AgentChatMessage, ComposerImageAttachment } from '../../../uiTypes'import { ChatThread } from '../ChatThread'@@ -311,4 +313,36 @@ describe('ChatThread resend action (TASK-42)', () => {)expect(pushToast.mock.calls[0]![1]).toBe('warn')})++ it('warns when a legacy label-only image survives reconciliation beside server references', () => {+ const local: AgentChatMessage = {+ id: 'optimistic-user',+ role: 'user',+ content: 'Analyze this',+ timestamp: 1,+ attachments: [{ id: 'legacy-image', type: 'uploaded_file', label: 'old-chart.png' }],+ }+ const incoming = turnsToChatMessages([+ {+ number: 10,+ user_input: [+ 'Analyze this',+ 'USER-ATTACHED CONTEXT: The user selected these capabilities/files for this message.',+ 'Plugins: profits/revenue. Use workflow tools.',+ ].join('\n'),+ started_at: new Date(2).toISOString(),+ },+ ])+ const user = mergeAuthoritativeServerMessages([local], incoming)[0]!+ expect(user.attachments?.map(attachment => attachment.type)).toEqual([+ 'plugin',+ 'uploaded_file',+ ])+ renderWithUserMessage(user)+ fireEvent.click(screen.getByRole('button', { name: 'Resend message' }))+ expect(pushToast).toHaveBeenCalledWith(+ "1 attachment from the original message couldn't be restored.",+ 'warn'+ )+ })})diff --git a/desktop-app/ui/src/hooks/__tests__/sessionAdapter.test.ts b/desktop-app/ui/src/hooks/__tests__/sessionAdapter.test.tsindex 1117ff5a2..7561fe069 100644--- a/desktop-app/ui/src/hooks/__tests__/sessionAdapter.test.ts+++ b/desktop-app/ui/src/hooks/__tests__/sessionAdapter.test.ts@@ -1,6 +1,12 @@import { describe, expect, it } from 'vitest'import { mergeAuthoritativeServerMessages } from '../../../../src/chatMessageMerge'import type { ChatMessage } from '../../../../src/types'+import {+ buildComposerReferencesPromptSection,+ buildComposerRequestContent,+} from '../../lib/composerReferencesPrompt'+import { buildComposerResendDraft } from '../../lib/composerResend'+import type { ComposerReferenceAttachment } from '../../uiTypes'import { turnsToChatMessages } from '../sessionAdapter'describe('turnsToChatMessages', () => {@@ -89,6 +95,114 @@ describe('turnsToChatMessages', () => {expect(merged[0]?.attachments).toMatchObject([{ type: 'uploaded_file', label: 'photo.png' }])})+ it('reconciles two same-name server image chips without duplicates or resend warnings', () => {+ const incoming = turnsToChatMessages([+ {+ number: 8,+ user_input: [+ 'Analyze charts',+ '[Attached images]',+ '- chart.png',+ '- chart.png',+ 'USER-ATTACHED CONTEXT: The user selected these capabilities/files for this message.',+ 'Plugins: profits/revenue. Use workflow tools.',+ ].join('\n'),+ started_at: new Date(120_003).toISOString(),+ },+ ])+ const existing: ChatMessage[] = [+ {+ id: 'optimistic-user',+ role: 'user',+ content: 'Analyze charts',+ timestamp: 1,+ attachments: [+ {+ id: 'first',+ type: 'uploaded_file',+ label: 'chart.png',+ filename: 'chart.png',+ mimeType: 'image/png',+ encoding: 'base64',+ dataBase64: 'AQ==',+ sizeBytes: 1,+ },+ {+ id: 'second',+ type: 'uploaded_file',+ label: 'chart.png',+ filename: 'chart.png',+ mimeType: 'image/png',+ encoding: 'base64',+ dataBase64: 'Ag==',+ sizeBytes: 1,+ },+ ],+ },+ ]+ const merged = mergeAuthoritativeServerMessages(existing, incoming)+ const user = merged.find(message => message.id === 'turn-8-user')!+ expect(user.attachments?.map(attachment => attachment.type)).toEqual([+ 'uploaded_file',+ 'uploaded_file',+ 'plugin',+ ])+ expect(+ user.attachments?.filter(attachment => attachment.type === 'uploaded_file')+ ).toMatchObject([+ { label: 'chart.png', dataBase64: 'AQ==' },+ { label: 'chart.png', dataBase64: 'Ag==' },+ ])+ const draft = buildComposerResendDraft(user)+ expect(draft.imageAttachments.map(image => image.dataBase64)).toEqual(['AQ==', 'Ag=='])+ expect(draft.unrestorable).toEqual([])+ })++ it('retains agent and global file identity from a real server input through Resend', () => {+ const references: ComposerReferenceAttachment[] = [+ {+ id: 'agent-file',+ type: 'agent_file',+ contextId: 'ctx-1',+ filesystemName: 'shared-fs',+ path: 'notes/todo.md',+ kind: 'file',+ label: 'todo.md',+ },+ {+ id: 'global-file',+ type: 'global_file',+ drive: 'drive-7',+ resourceId: 'res-9',+ gfsUri: 'gfs://drive-7/res-9',+ label: 'Report',+ },+ ]+ const [serverUser] = turnsToChatMessages([+ {+ number: 9,+ user_input: buildComposerRequestContent('Read these files', references),+ started_at: new Date(120_004).toISOString(),+ },+ ])+ expect(serverUser?.content).toBe('Read these files')+ expect(serverUser?.attachments).toMatchObject([+ { type: 'agent_file', label: 'todo.md', filesystemName: 'shared-fs', path: 'notes/todo.md' },+ {+ type: 'global_file',+ label: 'Report',+ drive: 'drive-7',+ resourceId: 'res-9',+ gfsUri: 'gfs://drive-7/res-9',+ },+ ])+ const draft = buildComposerResendDraft(serverUser!)+ expect(draft.unrestorable).toEqual([])+ expect(buildComposerReferencesPromptSection(draft.referenceAttachments)).toBe(+ buildComposerReferencesPromptSection(references)+ )+ })+it('preserves turn order for multi-turn transcripts', () => {const msgs = turnsToChatMessages([{ number: 1, user_input: 'a', response: 'A', started_at: '2026-04-22T10:00:00Z' },diff --git a/desktop-app/ui/src/lib/chatMessageAttachments.ts b/desktop-app/ui/src/lib/chatMessageAttachments.tsindex ebdd4294b..5873573d5 100644--- a/desktop-app/ui/src/lib/chatMessageAttachments.ts+++ b/desktop-app/ui/src/lib/chatMessageAttachments.ts@@ -49,9 +49,30 @@ function createParsedAttachment(type,label: normalizedLabel,addedOrder: index,+ ...(type === 'agent_file' ? parseAgentFileIdentity(label) : {}),+ ...(type === 'global_file' ? parseGlobalFileIdentity(label) : {}),}}+function parseAgentFileIdentity(+ value: string+): Pick<ChatMessageAttachment, 'filesystemName' | 'path'> {+ const slash = value.indexOf('/')+ return slash > 0 && slash < value.length - 1+ ? { filesystemName: value.slice(0, slash), path: value.slice(slash + 1) }+ : {}+}++function parseGlobalFileIdentity(+ value: string+): Pick<ChatMessageAttachment, 'drive' | 'resourceId' | 'gfsUri'> {+ const gfsUri = value.match(/(?:^|\()(gfs:\/\/[^)\s]+)\)?$/i)?.[1]+ const uriParts = gfsUri?.match(/^gfs:\/\/([^/]+)\/(.+)$/i)+ return gfsUri && uriParts?.[1] && uriParts[2]+ ? { gfsUri, drive: uriParts[1], resourceId: uriParts[2] }+ : {}+}+function inferLegacyContextAttachmentType(label: string): ChatMessageAttachment['type'] {const normalizedLabel = label.trim().toLowerCase()if (normalizedLabel.startsWith('mcp-') || normalizedLabel.endsWith('-remote')) {@@ -90,6 +111,16 @@ export function buildChatMessageAttachments(? 'Global File': 'Agent File',addedOrder: attachmentOrder(attachment, index),+ ...(attachment.type === 'agent_file'+ ? { filesystemName: attachment.filesystemName, path: attachment.path }+ : {}),+ ...(attachment.type === 'global_file'+ ? {+ gfsUri: attachment.gfsUri,+ drive: attachment.drive,+ resourceId: attachment.resourceId,+ }+ : {}),}})const imageItems = imageAttachments.map((attachment, index): ChatMessageAttachment => {diff --git a/desktop-app/ui/src/lib/composerResend.ts b/desktop-app/ui/src/lib/composerResend.tsindex 07deeb6c9..bd069fd76 100644--- a/desktop-app/ui/src/lib/composerResend.ts+++ b/desktop-app/ui/src/lib/composerResend.ts@@ -7,14 +7,13 @@* references.** Fidelity ladder (a message can carry its inputs in two places):- * 1. The raw content's `USER-ATTACHED CONTEXT:` block (server-authoritative- * messages) — carries full identity (plugin `ns/name`, agent-file- * `filesystem/path`, global-file `label (gfs://drive/resourceId)`).- * 2. The persisted `attachments` chips (locally optimistic messages) —- * uploaded files carry their base64 bytes, references carry labels only.- * Labels that still encode the identity (`ns/name`) are split back into- * structured fields; bare labels without enough identity are reported as- * unrestorable so the composer never shows a chip that send will omit.+ * 1. Persisted attachment chips carry uploaded image bytes and, for current+ * messages, structured agent/global file identity from the composer or+ * server-turn parser.+ * 2. A legacy raw `USER-ATTACHED CONTEXT:` block can supply missing identity+ * (plugin `ns/name`, agent-file `filesystem/path`, global-file URI).+ * Bare labels without enough identity are reported as unrestorable so the+ * composer never shows a chip that send will omit.** `response_file` attachments are never re-applied: they are artifacts the* previous reply generated, not inputs of the resent prompt.@@ -91,8 +90,8 @@ function pathBasename(path: string): string {/*** Extracts full-identity references from the `USER-ATTACHED CONTEXT:` block a* sent message embeds (the same block `parseChatMessageDisplay` strips for- * display). Only this source carries plugin namespaces, agent-file filesystem- * paths, and global-file URIs.+ * display). Older chips may need this fallback when their structured identity+ * was not persisted.*/export function parseStructuredResendReferences(content: string): StructuredReferences {const result: StructuredReferences = { plugin: [], connector: [], agentFile: [], globalFile: [] }@@ -194,13 +193,19 @@ function buildConnectorReference(}function buildAgentFileReference(- label: string,+ chip: ChatMessageAttachment,structured: StructuredAgentFile[]): Extract<ComposerReferenceAttachment, { type: 'agent_file' }> | null {+ const label = chip.label+ const embedded =+ chip.filesystemName && chip.path+ ? { filesystemName: chip.filesystemName, path: chip.path }+ : nullconst basenameMatches = structured.filter(entry => entry.filesystemName && pathBasename(entry.path) === label)const match =+ embedded ??structured.find(entry =>entry.filesystemName &&@@ -224,10 +229,13 @@ function buildAgentFileReference(}function buildGlobalFileReference(- label: string,+ chip: ChatMessageAttachment,structured: StructuredGlobalFile[]): Extract<ComposerReferenceAttachment, { type: 'global_file' }> | null {+ const label = chip.label+ const embedded = chip.gfsUri ? parseGlobalFileFromUri(label, chip.gfsUri) : nullconst match =+ (embedded?.drive && embedded.resourceId ? embedded : null) ??structured.find(entry => entry.gfsUri && entry.label === label) ??structured.find(entry => entry.gfsUri && pathBasename(entry.gfsUri) === label) ??null@@ -282,13 +290,13 @@ export function buildComposerResendDraft(continue}if (chip.type === 'agent_file') {- const reference = buildAgentFileReference(chip.label, structured.agentFile)+ const reference = buildAgentFileReference(chip, structured.agentFile)if (reference) referenceAttachments.push(reference)else unrestorable.push({ type: chip.type, label: chip.label })continue}if (chip.type === 'global_file') {- const reference = buildGlobalFileReference(chip.label, structured.globalFile)+ const reference = buildGlobalFileReference(chip, structured.globalFile)if (reference) referenceAttachments.push(reference)else unrestorable.push({ type: chip.type, label: chip.label })}