Skip to content

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

TypeScript

fix(desktop-app): bind reconciled attachments to proven turns

M2d6ed58d63e1
diff --git a/desktop-app/src/__tests__/chatMessageMerge.test.ts b/desktop-app/src/__tests__/chatMessageMerge.test.ts
index 59d2289f1..d6ebe1bde 100644
--- a/desktop-app/src/__tests__/chatMessageMerge.test.ts
+++ b/desktop-app/src/__tests__/chatMessageMerge.test.ts
@@ -352,7 +352,7 @@ describe('mergeAuthoritativeServerMessages', () => {
expect(merged.map(message => message.id)).toEqual(['turn-1-user', 'turn-2-user'])
})
- it('replaces completed task-backed echoes inside their authoritative turn', () => {
+ it('does not attribute an unscoped completed task ID to an authoritative turn', () => {
const merged = mergeAuthoritativeServerMessages(
[
{
@@ -389,7 +389,7 @@ describe('mergeAuthoritativeServerMessages', () => {
)
expect(merged.map(message => message.id)).toEqual(['turn-4-user', 'turn-4-assistant'])
- expect(merged.every(message => message.task_id === 'completed-task')).toBe(true)
+ expect(merged.every(message => message.task_id === undefined)).toBe(true)
})
it('preserves turnless system messages inside an authoritative range', () => {
diff --git a/desktop-app/src/chatMessageMerge.ts b/desktop-app/src/chatMessageMerge.ts
index c7214d8d0..e3dcb41a1 100644
--- a/desktop-app/src/chatMessageMerge.ts
+++ b/desktop-app/src/chatMessageMerge.ts
@@ -18,7 +18,102 @@ function attachmentName(attachment: ChatMessageAttachment): string {
return (attachment.filename || attachment.label).trim()
}
-/** Keep server chips in order while pairing repeated image names by occurrence. */
+type AttachmentRule = { identified: 'enrich' | 'server'; contentEcho: 'unique' | 'retain' }
+
+/** Mirrors work-tracker/specs/attachment-reconciliation-provenance.md. */
+const ATTACHMENT_RULES: Record<ChatMessageAttachment['type'], AttachmentRule> = {
+ uploaded_file: { identified: 'enrich', contentEcho: 'retain' },
+ global_file: { identified: 'enrich', contentEcho: 'retain' },
+ agent_file: { identified: 'enrich', contentEcho: 'retain' },
+ response_file: { identified: 'enrich', contentEcho: 'unique' },
+ plugin: { identified: 'server', contentEcho: 'retain' },
+ connector: { identified: 'server', contentEcho: 'retain' },
+}
+
+function attachmentIdentitiesConflict(
+ server: ChatMessageAttachment,
+ local: ChatMessageAttachment
+): boolean {
+ if (server.type === 'global_file' && local.type === 'global_file') {
+ return Boolean(
+ (server.gfsUri && local.gfsUri && server.gfsUri !== local.gfsUri) ||
+ (server.version !== undefined &&
+ local.version !== undefined &&
+ server.version !== local.version)
+ )
+ }
+ if (server.type === 'agent_file' && local.type === 'agent_file') {
+ return Boolean(
+ server.filesystemName &&
+ local.filesystemName &&
+ server.path &&
+ local.path &&
+ (server.filesystemName !== local.filesystemName || server.path !== local.path)
+ )
+ }
+ return false
+}
+
+function sameStructuredAttachmentIdentity(
+ server: ChatMessageAttachment,
+ local: ChatMessageAttachment
+): boolean {
+ if (server.type === 'global_file' && local.type === 'global_file') {
+ return Boolean(server.gfsUri && server.gfsUri === local.gfsUri)
+ }
+ if (server.type === 'agent_file' && local.type === 'agent_file') {
+ return Boolean(
+ server.filesystemName &&
+ server.path &&
+ server.filesystemName === local.filesystemName &&
+ server.path === local.path
+ )
+ }
+ return false
+}
+
+function enrichIdentifiedAttachment(
+ server: ChatMessageAttachment,
+ local: ChatMessageAttachment
+): ChatMessageAttachment {
+ if (server.type === 'global_file') {
+ if (
+ !local.gfsUri ||
+ !Number.isSafeInteger(local.version) ||
+ !Number.isSafeInteger(local.bytes) ||
+ (server.version !== undefined && server.version !== local.version)
+ ) {
+ return server
+ }
+ return {
+ ...server,
+ gfsUri: server.gfsUri ?? local.gfsUri,
+ drive: server.drive ?? local.drive,
+ resourceId: server.resourceId ?? local.resourceId,
+ version: server.version ?? local.version,
+ bytes: server.bytes ?? local.bytes,
+ }
+ }
+ if (server.type === 'agent_file') {
+ if (!local.filesystemName || !local.path) return server
+ return {
+ ...server,
+ filesystemName: server.filesystemName ?? local.filesystemName,
+ path: server.path ?? local.path,
+ }
+ }
+ if (!local.dataBase64) return server
+ return {
+ ...server,
+ filename: server.filename ?? local.filename,
+ mimeType: server.mimeType ?? local.mimeType,
+ encoding: server.encoding ?? local.encoding,
+ dataBase64: server.dataBase64 ?? local.dataBase64,
+ sizeBytes: server.sizeBytes ?? local.sizeBytes,
+ }
+}
+
+/** Keep server chips in order while pairing names only within an identified turn. */
function mergeAttachmentChips(
server: ChatMessageAttachment[] | undefined,
local: ChatMessageAttachment[] | undefined
@@ -32,7 +127,8 @@ function mergeAttachmentChips(
const localIndex = local.findIndex(
(attachment, index) =>
!matchedLocalIndexes.has(index) &&
- (attachment.type === 'uploaded_file' || Boolean(attachment.dataBase64)) &&
+ ATTACHMENT_RULES[attachment.type].identified === 'enrich' &&
+ !attachmentIdentitiesConflict(server[serverIndex]!, attachment) &&
predicate(attachment)
)
if (localIndex < 0) return
@@ -44,6 +140,10 @@ function mergeAttachmentChips(
server.forEach((attachment, index) => {
pair(index, candidate => candidate.type === attachment.type && candidate.id === attachment.id)
})
+ server.forEach((attachment, index) => {
+ if (localIndexByServerIndex.has(index)) return
+ pair(index, candidate => sameStructuredAttachmentIdentity(attachment, candidate))
+ })
// 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) => {
@@ -60,50 +160,49 @@ function mergeAttachmentChips(
const merged = server.map((attachment, index) => {
const localIndex = localIndexByServerIndex.get(index)
const match = localIndex === undefined ? undefined : local[localIndex]
- if (!match?.dataBase64) return attachment
- return {
- ...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 match ? enrichIdentifiedAttachment(attachment, match) : attachment
})
return [
...merged,
...local.filter(
(attachment, index) =>
- !matchedLocalIndexes.has(index) &&
- (attachment.type === 'uploaded_file' || Boolean(attachment.dataBase64))
+ !matchedLocalIndexes.has(index) && ATTACHMENT_RULES[attachment.type].identified === 'enrich'
),
]
}
-function collapseSafeAttachments(
- attachments: ChatMessageAttachment[] | undefined
-): ChatMessageAttachment[] | undefined {
- return attachments?.filter(
- attachment =>
- Boolean(attachment.dataBase64) ||
- (attachment.type !== 'plugin' &&
- attachment.type !== 'connector' &&
- attachment.type !== 'agent_file' &&
- attachment.type !== 'global_file')
+function contentEchoIsUnique(
+ local: ChatMessage,
+ authoritative: ChatMessage[],
+ existing: ChatMessage[]
+): boolean {
+ const serverSlots = new Map<string, ChatMessage>()
+ for (const row of [...existing, ...authoritative]) {
+ if (messageServerTurnNumber(row) !== undefined) serverSlots.set(serverSlotKey(row), row)
+ }
+ const matchingSlots = [...serverSlots.values()].filter(
+ row => row.role === local.role && row.content === local.content
+ )
+ const matchingLocals = existing.filter(
+ row =>
+ messageServerTurnNumber(row) === undefined &&
+ row.role === local.role &&
+ row.content === local.content &&
+ !row.isError &&
+ !row.preserveLocal
)
+ return matchingSlots.length === 1 && matchingLocals.length === 1
}
-function hasByteBearingUploadedImage(message: ChatMessage): boolean {
- // Parsed server image chips expose only filename and list position. Those
- // fields cannot distinguish different bytes in same-name prompts. A
- // content-only collapse has no stronger turn identity, so the local image
- // must remain on its own bubble. Response files are assistant output
- // artifacts and retain their established collapse behavior.
- return Boolean(
- message.attachments?.some(
- attachment => attachment.type === 'uploaded_file' && Boolean(attachment.dataBase64)
+function contentEchoMayCollapse(local: ChatMessage, unique: boolean): boolean {
+ if (
+ local.attachments?.some(
+ attachment => ATTACHMENT_RULES[attachment.type].contentEcho === 'retain' || !unique
)
- )
+ ) {
+ return false
+ }
+ return unique || !local.toolSteps?.length
}
function preferredServerMessage(
@@ -227,16 +326,17 @@ export function mergeAuthoritativeServerMessages(
const removedIndexes = new Set<number>()
const removedIndexByMessage = new Map<ChatMessage, number>()
const localByServerMessage = new Map<ChatMessage, ChatMessage>()
- // Side metadata (toolSteps/attachments/tokens via copyLocalMetadata) of a
- // collapsed idle echo, keyed by the authoritative row it merges onto. Kept
- // SEPARATE from localByServerMessage: the collapse is not a positional 1↔1
- // replacement, so it must not drive the local anchor index nor the single-claim
- // filter — it only contributes metadata to a server row that always survives
- // (§6.2, R2-M1).
+ const identifiedServerMessages = new Set<ChatMessage>()
+ // Eligible output artifacts and tool steps from a uniquely owned idle echo.
+ // A content-only collapse cannot establish attachment or task identity.
const collapsedEchoMetadataByServerMessage = new Map<ChatMessage, ChatMessage>()
const consumedLocalMessages = new Set<ChatMessage>()
- const markLocalReplacement = (serverMessage: ChatMessage, localMessage: ChatMessage) => {
+ const markLocalReplacement = (
+ serverMessage: ChatMessage,
+ localMessage: ChatMessage,
+ identified: boolean
+ ) => {
const index = existing.indexOf(localMessage)
if (index < 0 || consumedLocalMessages.has(localMessage)) return
consumedLocalMessages.add(localMessage)
@@ -244,18 +344,12 @@ export function mergeAuthoritativeServerMessages(
removedIndexes.add(index)
removedIndexByMessage.set(localMessage, index)
localByServerMessage.set(serverMessage, localMessage)
+ if (identified) identifiedServerMessages.add(serverMessage)
}
- // Collapse sibling of markLocalReplacement: evicts a turnless idle echo from the
- // output WITHOUT registering localByServerMessage (no positional 1↔1 anchoring),
- // but DOES merge its side metadata (toolSteps/attachments/tokens via
- // copyLocalMetadata) onto the authoritative row of its slot — the same echoRow
- // its content matched. The server row never changes content or presence, so this
- // can never reintroduce R1-B1 (property #1 still guards every numbered server
- // row, §6.1) and never rewrites content (loss-safety of text, §6.2). It is no
- // longer pure drop-only: it is drop of the local ∩ merge of its metadata into the
- // surviving authoritative row, so toolSteps/attachments the optimistic bubble
- // accumulated are not lost when the reconciled server row lacks them (R2-M1).
+ // Remove a proven unique text echo without treating it as an identified
+ // replacement. Only attachment classes allowed by the decision table reach
+ // this path; its metadata cannot become a positional anchor or a task ID.
const dropLocalEcho = (localMessage: ChatMessage, echoRow: ChatMessage) => {
const index = existing.indexOf(localMessage)
if (index < 0 || consumedLocalMessages.has(localMessage)) return
@@ -275,7 +369,7 @@ export function mergeAuthoritativeServerMessages(
messageServerTurnNumber(local) !== undefined &&
serverSlotKey(local) === slot
)
- if (sameSlot) markLocalReplacement(serverMessage, sameSlot)
+ if (sameSlot) markLocalReplacement(serverMessage, sameSlot, true)
}
const serverTurnAllowedForTurnlessLocal = (
@@ -342,7 +436,7 @@ export function mergeAuthoritativeServerMessages(
for (const [message, matches] of liveLocalExactMatches) {
if (matches.length === 1 && exactMatchClaimants.get(matches[0]!) === 1) {
- markLocalReplacement(matches[0]!, message)
+ markLocalReplacement(matches[0]!, message, true)
}
}
@@ -367,7 +461,7 @@ export function mergeAuthoritativeServerMessages(
// this role is free to host the idle optimistic (candidateTurns empty) AND it is
// bracketed on both sides by numbered turns (slot saturation — the core case is
// the consecutive same-role sandwich Q = P + 1), the bubble is the residual echo
- // of an already-materialised numbered turn. We drop it (drop-only) ONLY when its
+ // of an already-materialised numbered turn. We collapse it ONLY when its
// content matches the AUTHORITATIVE incoming row of the same role that fills the
// neighbour's (turn, role) slot — NOT the numbered neighbour taken from
// `existing`, which can be stale: the row that actually lands in that output slot
@@ -421,7 +515,10 @@ export function mergeAuthoritativeServerMessages(
: matchesAuthoritative(previousAuthoritative)
? previousAuthoritative
: undefined
- if (echoRow && !hasByteBearingUploadedImage(message)) {
+ if (
+ echoRow &&
+ contentEchoMayCollapse(message, contentEchoIsUnique(message, authoritative, existing))
+ ) {
dropLocalEcho(message, echoRow)
}
}
@@ -435,35 +532,25 @@ export function mergeAuthoritativeServerMessages(
serverTurnAllowedForTurnlessLocal(serverMessage, message, index)
)
if (!candidates.length) continue
- markLocalReplacement(candidates[0]!, message)
+ // A free positional slot can dedupe plain optimistic text, but it does
+ // not establish ownership for attachments or tool steps.
+ if (message.attachments?.length || message.toolSteps?.length) continue
+ markLocalReplacement(candidates[0]!, message, false)
}
const hydratedReplacements = authoritative.map(message => {
const local = localByServerMessage.get(message)
- let hydrated = preferredServerMessage(message, local, { copyLocalMetadata: Boolean(local) })
- // Merge safe side metadata of a collapsed idle echo onto its authoritative
- // slot row (§6.2, R2-M1). A same-text collapse does not prove that a local
- // plugin/file reference belonged to this server turn; Resend must not turn
- // that unverified reference into a new prompt attachment. Byte-bearing
- // uploaded images never reach this path on a content-only collapse;
- // response-file output artifacts and toolSteps can still be kept. It
- // deliberately
- // does NOT use preferredServerMessage/copyLocalMetadata here: that path also
- // copies `task_id` (echo identity), which is correct for D-1 replacement (the
- // server IS the live task's echo) but WRONG for an idle collapse — the task is
- // done and the collapse is by content coincidence, not identity. Tagging a
- // historical server row with a done task's id leaks identity and would break the
- // task_id-based dedupe consumers rely on (the exact class the ':602' stale-
- // metadata guard forbids). `content` is never touched either (loss-safety, §6.1).
- // This does NOT affect localAnchorIndex: the collapse has no positional anchor.
+ let hydrated = preferredServerMessage(message, local, {
+ copyLocalMetadata: identifiedServerMessages.has(message),
+ })
+ // A unique content-only collapse may carry output artifacts and tool steps.
+ // Images and input references never reach this path, and no task ID or
+ // positional anchor is copied from the echo.
const collapsedEcho = collapsedEchoMetadataByServerMessage.get(message)
if (collapsedEcho) {
hydrated = {
...hydrated,
- attachments: mergeAttachmentChips(
- hydrated.attachments,
- collapseSafeAttachments(collapsedEcho.attachments)
- ),
+ attachments: mergeAttachmentChips(hydrated.attachments, collapsedEcho.attachments),
toolSteps: hydrated.toolSteps?.length ? hydrated.toolSteps : collapsedEcho.toolSteps,
}
}
diff --git a/desktop-app/ui/docs/attachment-reconciliation-provenance.md b/desktop-app/ui/docs/attachment-reconciliation-provenance.md
deleted file mode 100644
index 187ef47a9..000000000
--- a/desktop-app/ui/docs/attachment-reconciliation-provenance.md
+++ /dev/null
@@ -1,13 +0,0 @@
-# Attachment reconciliation provenance mini-spec
-
-## Identity and authority
-
-- A matching server turn number and role, or the same deterministic server message ID, identifies the same turn. A uniquely bound live task can also replace its own optimistic turn. In these cases the server owns the visible chips and local upload bytes may enrich matching image chips or remain as local byte-bearing uploads.
-- A content-only idle echo has no turn identity. Equal role and text alone is only a candidate match. It is unambiguous only when exactly one authoritative turn of that role has that text in the reconciliation input and exactly one local idle echo claims it.
-- Server-parsed image chips currently carry a filename but no turn-scoped image identity or byte digest. Their parsed IDs also derive from list position and filename. Neither a matching filename, parsed ID, nor matching multiplicity proves that two images have the same bytes or belong to the same prompt. Server chips remain authoritative. A plugin or file reference on the local echo never becomes a server reference through text coincidence.
-
-## Transfer and ambiguity
-
-- A content-only collapse must not transfer byte-bearing uploaded images with the current server payload. Keep their local bubble even if role, text, filenames, and chip counts match. Byte recovery remains allowed when turn number plus role, deterministic server message ID, or a unique live-task binding identifies the same turn. A future content-only transfer would require an independently verified turn-scoped image identity or content digest on both sides.
-- This restriction applies to uploaded input images. A `response_file` is an assistant output artifact, not a Resend input; a settled assistant echo carrying its bytes may still collapse under the adjacent-turn rule and retain that artifact on the surviving assistant row. Label-only legacy uploads may also collapse and retain their unrestorable warning. Text-only echoes and other non-reference artifacts keep their existing collapse behavior.
-- Reconciliation is idempotent: repeating it with the same server turns must neither duplicate attachments nor move bytes to another turn. A later server response with stronger identity may safely reconcile a previously retained local bubble.
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.tsx
index 8b695bc46..c893b1d82 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
@@ -333,12 +333,11 @@ describe('ChatThread resend action (TASK-42)', () => {
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)
+ const merged = mergeAuthoritativeServerMessages([local], incoming)
+ expect(merged.map(message => message.id)).toEqual(['optimistic-user', 'turn-10-user'])
+ expect(merged[0]?.attachments?.map(attachment => attachment.type)).toEqual(['uploaded_file'])
+ expect(merged[1]?.attachments?.map(attachment => attachment.type)).toEqual(['plugin'])
+ renderWithUserMessage(merged[0]!)
fireEvent.click(screen.getByRole('button', { name: 'Resend message' }))
expect(pushToast).toHaveBeenCalledWith(
"1 attachment from the original message couldn't be restored.",
diff --git a/desktop-app/ui/src/hooks/__tests__/sessionAdapter.test.ts b/desktop-app/ui/src/hooks/__tests__/sessionAdapter.test.ts
index bb95a3e28..af8ae9439 100644
--- a/desktop-app/ui/src/hooks/__tests__/sessionAdapter.test.ts
+++ b/desktop-app/ui/src/hooks/__tests__/sessionAdapter.test.ts
@@ -5,10 +5,7 @@ import {
buildChatMessageAttachments,
buildResponseFileAttachments,
} from '../../lib/chatMessageAttachments'
-import {
- buildComposerReferencesPromptSection,
- buildComposerRequestContent,
-} from '../../lib/composerReferencesPrompt'
+import { buildComposerRequestContent } from '../../lib/composerReferencesPrompt'
import { buildComposerResendDraft } from '../../lib/composerResend'
import type { ComposerReferenceAttachment } from '../../uiTypes'
import { turnsToChatMessages } from '../sessionAdapter'
@@ -60,7 +57,7 @@ describe('turnsToChatMessages', () => {
])
})
- it('merges an image-only optimistic turn using producer-shaped attachments', () => {
+ it('keeps an image-only optimistic turn without a proved server identity', () => {
const existing: ChatMessage[] = [
{
id: 'optimistic-user',
@@ -95,7 +92,11 @@ describe('turnsToChatMessages', () => {
const merged = mergeAuthoritativeServerMessages(existing, incoming)
- expect(merged.map(message => message.id)).toEqual(['turn-7-user', 'turn-7-assistant'])
+ expect(merged.map(message => message.id)).toEqual([
+ 'optimistic-user',
+ 'turn-7-user',
+ 'turn-7-assistant',
+ ])
expect(merged[0]?.attachments).toMatchObject([{ type: 'uploaded_file', label: 'photo.png' }])
})
@@ -116,9 +117,7 @@ describe('turnsToChatMessages', () => {
])
const existing: ChatMessage[] = [
{
- id: 'optimistic-user',
- role: 'user',
- content: 'Analyze charts',
+ ...incoming[0]!,
timestamp: 1,
attachments: [
{
@@ -207,6 +206,57 @@ describe('turnsToChatMessages', () => {
expect(draft.unrestorable).toEqual([{ type: 'global_file', label: 'Report' }])
})
+ it('retains two versioned same-label global files on their identified server turn', () => {
+ const references: ComposerReferenceAttachment[] = [
+ {
+ id: 'first-global',
+ type: 'global_file',
+ label: 'Report',
+ drive: 'drive-7',
+ resourceId: 'first',
+ gfsUri: 'gfs://drive-7/first',
+ version: 3,
+ bytes: 4096,
+ },
+ {
+ id: 'second-global',
+ type: 'global_file',
+ label: 'Report',
+ drive: 'drive-7',
+ resourceId: 'second',
+ gfsUri: 'gfs://drive-7/second',
+ version: 8,
+ bytes: 8192,
+ },
+ ]
+ const incoming = turnsToChatMessages([
+ {
+ number: 9,
+ user_input: buildComposerRequestContent('Compare both reports', references),
+ started_at: new Date(9).toISOString(),
+ },
+ ])
+ expect(incoming[0]?.attachments).toMatchObject([
+ { type: 'global_file', label: 'Report' },
+ { type: 'global_file', label: 'Report' },
+ ])
+ const local: ChatMessage = {
+ ...incoming[0]!,
+ attachments: buildChatMessageAttachments([], references),
+ }
+ const once = mergeAuthoritativeServerMessages([local], incoming)
+ const twice = mergeAuthoritativeServerMessages(once, incoming)
+ expect(twice).toEqual(once)
+ expect(once).toHaveLength(1)
+ expect(once[0]?.attachments).toHaveLength(2)
+ const draft = buildComposerResendDraft(once[0]!)
+ expect(draft.referenceAttachments).toMatchObject([
+ { type: 'global_file', gfsUri: 'gfs://drive-7/first', version: 3, bytes: 4096 },
+ { type: 'global_file', gfsUri: 'gfs://drive-7/second', version: 8, bytes: 8192 },
+ ])
+ expect(draft.unrestorable).toEqual([])
+ })
+
it('does not resend references from a same-text idle echo onto a context-free server turn', () => {
const incoming = turnsToChatMessages([
{ number: 1, user_input: 'first', started_at: new Date(1).toISOString() },
@@ -370,11 +420,11 @@ describe('turnsToChatMessages', () => {
attachments: [firstImage],
}
const localEcho: ChatMessage = {
- id: 'first-prompt-idle-echo',
+ id: 'second-prompt-idle-echo',
role: 'user',
content: 'repeat',
timestamp: 2,
- attachments: [firstImage],
+ attachments: [secondImage],
}
const existing = [firstTurn, localEcho, incoming[0]!]
const once = mergeAuthoritativeServerMessages(existing, incoming, {
@@ -386,11 +436,11 @@ describe('turnsToChatMessages', () => {
expect(twice).toEqual(once)
expect(once.map(message => message.id)).toEqual([
'turn-1-user',
- 'first-prompt-idle-echo',
+ 'second-prompt-idle-echo',
'turn-2-user',
])
expect(buildComposerResendDraft(once[0]!).imageAttachments[0]?.dataBase64).toBe('AQ==')
- expect(buildComposerResendDraft(once[1]!).imageAttachments[0]?.dataBase64).toBe('AQ==')
+ expect(buildComposerResendDraft(once[1]!).imageAttachments[0]?.dataBase64).toBe('Ag==')
expect(buildComposerResendDraft(once[2]!).imageAttachments).toEqual([])
expect(once[2]?.attachments).toMatchObject([{ type: 'uploaded_file', label: 'shared.png' }])
})
@@ -466,6 +516,46 @@ describe('turnsToChatMessages', () => {
expect(mergeAuthoritativeServerMessages(once, incoming)).toEqual(once)
})
+ it('keeps a response-file echo local when two assistant turns share its text', () => {
+ const incoming = turnsToChatMessages([
+ { number: 1, user_input: 'first', response: 'done', started_at: new Date(1).toISOString() },
+ { number: 2, user_input: 'second', response: 'done', started_at: new Date(3).toISOString() },
+ ])
+ const responseFile = buildResponseFileAttachments({
+ attachments: [
+ {
+ id: 'result',
+ kind: 'file',
+ filename: 'result.txt',
+ mimeType: 'text/plain',
+ encoding: 'base64',
+ dataBase64: 'b2s=',
+ sizeBytes: 2,
+ },
+ ],
+ })[0]!
+ const localEcho: ChatMessage = {
+ id: 'ambiguous-assistant-echo',
+ role: 'assistant',
+ content: 'done',
+ timestamp: 2,
+ attachments: [responseFile],
+ }
+ const once = mergeAuthoritativeServerMessages(
+ [incoming[1]!, localEcho, incoming[3]!],
+ incoming,
+ { activeTaskIds: new Set() }
+ )
+ expect(once.filter(message => message.role === 'assistant').map(message => message.id)).toEqual(
+ ['turn-1-assistant', 'ambiguous-assistant-echo', 'turn-2-assistant']
+ )
+ expect(once.find(message => message.id === 'ambiguous-assistant-echo')?.attachments).toEqual([
+ responseFile,
+ ])
+ expect(once.find(message => message.id === 'turn-2-assistant')?.attachments).toBeUndefined()
+ expect(mergeAuthoritativeServerMessages(once, incoming)).toEqual(once)
+ })
+
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/work-tracker/specs/attachment-reconciliation-provenance.md b/work-tracker/specs/attachment-reconciliation-provenance.md
new file mode 100644
index 000000000..3c7a2714d
--- /dev/null
+++ b/work-tracker/specs/attachment-reconciliation-provenance.md
@@ -0,0 +1,46 @@
+# Attachment reconciliation provenance
+
+## Identity evidence
+
+An authoritative server message owns its turn number and role. A local message
+belongs to that turn only when it has the same server turn number and role (or
+the corresponding deterministic `turn-N-role` ID), or when one active task ID
+binds exactly one eligible local message to exactly one server message. These
+are **identified replacements**. The server owns visible text and parsed chips;
+the identified local message may supply metadata that the server omitted.
+
+An idle, turnless message between numbered turns is a **content-only echo**.
+Equal role, text, or filename is not turn identity. It can be collapsed only
+under the adjacent authoritative text rule, and attachment transfer additionally
+follows the table below. A unique text match means exactly one server slot of
+that role and text across the available existing and incoming messages, and
+exactly one eligible turnless claimant. If either count exceeds one, the match
+is ambiguous. A partial server page does not erase competing existing slots.
+
+## Ownership decision table
+
+| Attachment class | Identified replacement | Unique content-only echo | Ambiguous or unproved echo |
+| -------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------- | ---------------------------------------------- |
+| Uploaded images with bytes | Keep server chips and fill matching image bytes from the same-turn local message; append local-only byte-bearing uploads. Pair repeated names by occurrence only _inside_ this proven turn. | Keep the local message and its image. Server display chips have no turn-scoped byte identity. | Keep the local message and its image. |
+| Legacy label-only uploads | Keep server chips; retain unmatched local labels for Resend's unrestorable warning. | Keep the local message if its label has no independently proven server owner. | Keep local. |
+| Global-file references | The server's complete URI/version/size wins. Otherwise enrich its matching display chip from the identified local reference; keep a local-only complete reference when the server omitted it. Never synthesize version or size from a label or URI. | Keep the local reference on its message; server labels are display-only. | Keep local. |
+| Agent-file references | The server's complete filesystem/path wins; otherwise enrich a matching display chip from the identified local reference, or keep a local-only structured reference. | Keep the local reference on its message; an independent server identity stays on the server turn. | Keep local. |
+| `response_file` output artifacts | Keep server artifacts; fill or retain local artifacts belonging to the identified assistant turn. They are never Resend inputs. | Collapse and transfer only when role and text identify one server slot and one local claimant, with no competing historical slot. | Keep the local assistant message and artifact. |
+| Plugin and connector references | Server-parsed chips are authoritative; local metadata cannot overwrite a server reference. | Keep local references on their message; text coincidence cannot make them actionable on a server turn. | Keep local. |
+| Other non-reference metadata, including tool steps | Server data wins; missing fields may come from the identified local message. | Transfer only with a unique content match and no retained attachment class; otherwise keep local. | Keep local. |
+
+When a class says **keep local**, do not collapse its message: dropping the row
+would lose the attachment's ownership and any unrestorable warning. A plain
+text echo with no owned metadata may still collapse under the adjacent text
+rule. A filename, parsed list-position ID, or equal chip count never proves
+that two image byte streams or two global-file references are the same object.
+
+## Repeated reconciliation
+
+Server chips keep their order and identity. Enrichment fills absent fields
+without replacing complete server identity. Pair each local attachment at most
+once, including duplicate names; do not append a second copy of a matched
+attachment. A second reconciliation with the same server page must leave the
+same attachments on the same logical turns. A retained local row may be merged
+later only if stronger turn identity arrives. Resend reads only the surviving
+message's own byte-bearing images and complete references.