Evenfire is an intelligence layer platform for running LLM agents that take real actions, on your infrastructure
TypeScript
fix(desktop): collapse idle echo gated by content (R2-H1)
Diego Zacarias40cc7afebc25
diff --git a/desktop-app/package-lock.json b/desktop-app/package-lock.jsonindex f279250a9..cd6097964 100644--- a/desktop-app/package-lock.json+++ b/desktop-app/package-lock.json@@ -1,12 +1,12 @@{"name": "evenfire",- "version": "0.1.345",+ "version": "0.1.346","lockfileVersion": 3,"requires": true,"packages": {"": {"name": "evenfire",- "version": "0.1.345",+ "version": "0.1.346","license": "MPL-2.0","dependencies": {"@tanstack/react-query": "5.100.10",diff --git a/desktop-app/package.json b/desktop-app/package.jsonindex efad974c3..2710bc5ba 100644--- a/desktop-app/package.json+++ b/desktop-app/package.json@@ -1,7 +1,7 @@{"name": "evenfire","productName": "Evenfire",- "version": "0.1.345",+ "version": "0.1.346","private": true,"license": "MPL-2.0","description": "Evenfire desktop client for secure agent and workflow access",diff --git a/desktop-app/src/__tests__/chatMessageMerge.test.ts b/desktop-app/src/__tests__/chatMessageMerge.test.tsindex be32bfbfe..cf324c605 100644--- a/desktop-app/src/__tests__/chatMessageMerge.test.ts+++ b/desktop-app/src/__tests__/chatMessageMerge.test.ts@@ -1255,3 +1255,185 @@ describe('mergeAuthoritativeServerMessages unique claim (D-1 ↔ D-2)', () => {expect(ids).toHaveLength(3)})})++describe('mergeAuthoritativeServerMessages — R2-H1 idle echo liveness (§6.1, prop #7)', () => {+ // Models the active -> idle transition the real flow performs across TWO merge+ // calls with different activeTaskIds:+ // 1. active reconcile persists the numbered server turn NEXT TO the still-live+ // optimistic bubble (D-3, what fix 229369e4 now does).+ // 2. the task leaves activeTaskIds (idle).+ // 3. the idle reconcile MUST collapse the residual optimistic echo — but only+ // because its content matches the adjacent numbered turn (gate (b)).+ // Assertion is on the observable id list the user sees (T4).+ it('collapses the transient duplicate once the task leaves activeTaskIds (exact repro)', () => {+ // Server window derived from the real producer (T1): no hand-built rows.+ const incoming = turnsToChatMessages([+ { number: 1, user_input: 'first', started_at: new Date(1).toISOString() },+ { number: 2, user_input: 'second', started_at: new Date(3).toISOString() },+ ])++ // Disk after the ACTIVE reconcile of task-2: the numbered turn-2-user the fix+ // now persists sits as the immediate numbered neighbour of the still-turnless+ // optimistic bubble, whose content ('second') mirrors turn-2-user.+ const activePersisted: ChatMessage[] = [+ { id: 'turn-1-user', role: 'user', content: 'first', timestamp: 1, serverTurnNumber: 1 },+ { id: 'optimistic-task-2', role: 'user', content: 'second', timestamp: 2, task_id: 'task-2' },+ { id: 'turn-2-user', role: 'user', content: 'second', timestamp: 3, serverTurnNumber: 2 },+ ]++ // While task-2 is still active the duplicate is tolerated (§3 / D-3).+ const activeMerge = mergeAuthoritativeServerMessages(activePersisted, incoming, {+ activeTaskIds: new Set(['task-2']),+ })+ expect(activeMerge.map(m => m.id)).toContain('optimistic-task-2')+ expect(activeMerge.map(m => m.id)).toEqual(+ expect.arrayContaining(['turn-1-user', 'turn-2-user'])+ )++ // Transition to idle: task-2 has left activeTaskIds. The echo collapses because+ // its content == turn-2-user; both server turns remain. FAILS against 229369e4.+ const idleMerge = mergeAuthoritativeServerMessages(activePersisted, incoming, {+ activeTaskIds: new Set(),+ })+ expect(idleMerge.map(m => m.id)).toEqual(['turn-1-user', 'turn-2-user'])++ // Convergence: re-applying the merge does not re-materialise the echo.+ const reMerge = mergeAuthoritativeServerMessages(idleMerge, incoming, {+ activeTaskIds: new Set(),+ })+ expect(reMerge.map(m => m.id)).toEqual(['turn-1-user', 'turn-2-user'])+ })++ it('does NOT drop an idle orphan whose content diverges from its numbered neighbours (gate (b))', () => {+ // The key test of remediation (b): an accepted task that never registered a+ // server turn (cancelled-in-queue / budget-denied / persistTurnStart failure,+ // verified in mcp-host) leaves a turnless idle non-durable user message. When+ // it lands sandwiched between two consecutive same-role numbered turns, the+ // content-blind positional rule would delete it — LOSING local text. The+ // content gate keeps it because its content ('B') matches neither neighbour.+ // Server turns are derived from the real producer (T1).+ const incoming = turnsToChatMessages([+ { number: 1, user_input: 'A', started_at: new Date(1).toISOString() },+ { number: 2, user_input: 'C', started_at: new Date(3).toISOString() },+ ])+ const [turn1User, turn2User] = incoming+ const existing: ChatMessage[] = [+ turn1User!,+ { id: 'orphan-user', role: 'user', content: 'B', timestamp: 2, task_id: 'done-task' },+ turn2User!,+ ]++ const merged = mergeAuthoritativeServerMessages(existing, incoming, {+ activeTaskIds: new Set(),+ })++ // The orphan survives (at worst a duplicate) — no local text is lost.+ expect(merged.map(m => m.id)).toContain('orphan-user')+ expect(merged.find(m => m.id === 'orphan-user')).toEqual(+ expect.objectContaining({ content: 'B' })+ )+ // Non-reintroduction of R1-B1: both numbered server rows survive.+ expect(merged.map(m => m.id)).toEqual(expect.arrayContaining(['turn-1-user', 'turn-2-user']))+ })++ it('does NOT collapse an optimistic-live bubble even when slot-saturated (I-5 gate)', () => {+ // Same sandwich shape and matching content as the exact repro, but the task is+ // ACTIVE: the in-flight bubble must remain visible in the UI (§1/§3, I-5).+ const incoming = turnsToChatMessages([+ { number: 1, user_input: 'first', started_at: new Date(1).toISOString() },+ { number: 2, user_input: 'second', started_at: new Date(3).toISOString() },+ ])+ const existing: ChatMessage[] = [+ { id: 'turn-1-user', role: 'user', content: 'first', timestamp: 1, serverTurnNumber: 1 },+ { id: 'optimistic-task-2', role: 'user', content: 'second', timestamp: 2, task_id: 'task-2' },+ { id: 'turn-2-user', role: 'user', content: 'second', timestamp: 3, serverTurnNumber: 2 },+ ]+ const merged = mergeAuthoritativeServerMessages(existing, incoming, {+ activeTaskIds: new Set(['task-2']),+ })+ expect(merged.map(m => m.id)).toContain('optimistic-task-2')+ })++ it('property: a same-role sandwiched idle echo collapses, an orphan survives, and no numbered row is lost', () => {+ const durableIds = (messages: ChatMessage[]) =>+ messages.filter(m => m.role === 'system' || m.isError || m.preserveLocal).map(m => m.id)+ const numberedIds = (messages: ChatMessage[]) =>+ messages.filter(m => messageServerTurnNumber(m) !== undefined).map(m => m.id)++ const scenarioArb = fc.record({+ start: fc.integer({ min: 1, max: 6 }),+ role: fc.constantFrom<'user' | 'assistant'>('user', 'assistant'),+ // true -> echo (content mirrors the higher numbered neighbour), false -> orphan.+ isEcho: fc.boolean(),+ // If active, the bubble is optimistic-live and must never collapse (I-5).+ active: fc.boolean(),+ })++ fc.assert(+ fc.property(scenarioArb, ({ start, role, isEcho, active }) => {+ const turns = [+ { number: start, user_input: `q${start}`, started_at: new Date(start).toISOString() },+ {+ number: start + 1,+ user_input: `q${start + 1}`,+ started_at: new Date(start + 1).toISOString(),+ },+ ]+ // Keep only the requested role slot so the bubble is truly sandwiched by+ // two consecutive same-role numbered turns (Q = P + 1). turnsToChatMessages+ // emits an assistant slot only when a response is present; there is none+ // here, so for the assistant role there is no sandwich to build.+ const numbered = turnsToChatMessages(turns).filter(m => m.role === role)+ if (numbered.length !== 2) return+ const [low, high] = numbered+ const bubbleContent = isEcho ? high!.content : `orphan-${start}`+ const bubble: ChatMessage = {+ id: 'sandwiched-bubble',+ role,+ content: bubbleContent,+ timestamp: 999,+ task_id: 'the-task',+ }+ const existing: ChatMessage[] = [low!, bubble, high!]+ const incoming = numbered++ const activeTaskIds = active ? new Set(['the-task']) : new Set<string>()+ const merged = mergeAuthoritativeServerMessages(existing, incoming, { activeTaskIds })+ const ids = merged.map(m => m.id)++ // Prop #7 liveness: an idle content-echo collapses; a live bubble (I-5) and+ // a content-divergent orphan both survive (gate (b) — no local text lost).+ if (isEcho && !active) {+ expect(ids).not.toContain('sandwiched-bubble')+ } else {+ expect(ids).toContain('sandwiched-bubble')+ }++ // Prop #1: no numbered server row is ever suppressed (R1-B1 guard).+ for (const server of incoming) {+ if (messageServerTurnNumber(server) !== undefined) {+ expect(ids).toContain(server.id)+ }+ }+ // Prop #3: no duplicate ids.+ expect(new Set(ids).size).toBe(ids.length)+ // Prop #2: numbered output ordered by (turn, roleRank).+ const orderKeys = merged+ .filter(m => messageServerTurnNumber(m) !== undefined)+ .map(m => [messageServerTurnNumber(m)!, roleRank(m.role)] as const)+ for (let index = 1; index < orderKeys.length; index += 1) {+ const [previousTurn, previousRank] = orderKeys[index - 1]!+ const [turn, rank] = orderKeys[index]!+ expect(previousTurn < turn || (previousTurn === turn && previousRank <= rank)).toBe(true)+ }+ // Prop #4: durable locals never lost (none here, but the invariant holds).+ for (const id of durableIds(existing)) expect(ids).toContain(id)+ // Prop #5 idempotence + Prop #6 composability at the seam.+ const remerged = mergeAuthoritativeServerMessages(merged, incoming, { activeTaskIds })+ expect(remerged).toEqual(merged)+ expect(numberedIds(remerged)).toEqual(numberedIds(merged))+ }),+ { numRuns: 20000 }+ )+ }, 120000)+})diff --git a/desktop-app/src/chatMessageMerge.ts b/desktop-app/src/chatMessageMerge.tsindex 11ec6b607..58fd8471b 100644--- a/desktop-app/src/chatMessageMerge.ts+++ b/desktop-app/src/chatMessageMerge.ts@@ -147,6 +147,18 @@ export function mergeAuthoritativeServerMessages(localByServerMessage.set(serverMessage, localMessage)}+ // Drop-only sibling of markLocalReplacement: evicts a turnless idle echo from+ // the output WITHOUT associating it to any server row (no localByServerMessage+ // write). No server row changes content or presence, so this can never+ // reintroduce R1-B1 — property #1 still guards every numbered server row (§6.1).+ const dropLocalEcho = (localMessage: ChatMessage) => {+ const index = existing.indexOf(localMessage)+ if (index < 0 || consumedLocalMessages.has(localMessage)) return+ consumedLocalMessages.add(localMessage)+ removed.push(localMessage)+ removedIndexes.add(index)+ }+for (const serverMessage of authoritative) {const slot = serverSlotKey(serverMessage)const sameSlot = existing.find(@@ -241,6 +253,39 @@ export function mergeAuthoritativeServerMessages(for (const candidate of authoritativeCandidates) {candidateTurns.add(messageServerTurnNumber(candidate)!)}++ // Idle echo collapse, gated by content (§6.1, R2-H1). When no incoming server+ // row of 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 content matches a numbered neighbour of the same+ // role that is already in the output — so its text still survives in that+ // numbered row and nothing observable is lost. We compare against `next` first+ // (the higher turn, the R2-H1 echo semantics) and fall back to `prev`.+ //+ // The content gate is what makes this safe versus a content-blind positional+ // rule: an orphan of a task that never registered a server turn (cancelled-in-+ // queue, budget-denied, persistTurnStart failure — verified in mcp-host) stays+ // turnless idle non-durable and, with divergent content, is NOT collapsed, so+ // no local text is lost. Declared residual FP: a user message whose content is+ // identical to an adjacent same-role numbered turn AND is an orphan of a+ // turn-less task is dropped — a rare loss of a duplicate-content message,+ // unavoidable without an identity discriminator the server does not provide.+ if (candidateTurns.size === 0) {+ const previousNumbered = previousNumberedMessages[index]+ const nextNumbered = nextNumberedMessages[index]+ if (previousNumbered && nextNumbered) {+ const echoNeighbour =+ nextNumbered.role === message.role && nextNumbered.content === message.content+ ? nextNumbered+ : previousNumbered.role === message.role && previousNumbered.content === message.content+ ? previousNumbered+ : undefined+ if (echoNeighbour) dropLocalEcho(message)+ }+ continue+ }if (candidateTurns.size !== 1) continueconst candidates = authoritativeCandidates.filter(