Evenfire is an intelligence layer platform for running LLM agents that take real actions, on your infrastructure
TypeScript
fix: preserve desktop chat history during reconciliation
Josué6709ae6161cc
diff --git a/desktop-app/package-lock.json b/desktop-app/package-lock.jsonindex f1f5014ab..e30f2070b 100644--- a/desktop-app/package-lock.json+++ b/desktop-app/package-lock.json@@ -1,12 +1,12 @@{"name": "evenfire",- "version": "0.1.338",+ "version": "0.1.339","lockfileVersion": 3,"requires": true,"packages": {"": {"name": "evenfire",- "version": "0.1.338",+ "version": "0.1.339","license": "MPL-2.0","dependencies": {"@tanstack/react-query": "5.100.10",diff --git a/desktop-app/package.json b/desktop-app/package.jsonindex 35ba6fdab..cc1b7d741 100644--- a/desktop-app/package.json+++ b/desktop-app/package.json@@ -1,7 +1,7 @@{"name": "evenfire","productName": "Evenfire",- "version": "0.1.338",+ "version": "0.1.339","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 417b6519e..5b66077b7 100644--- a/desktop-app/src/__tests__/chatMessageMerge.test.ts+++ b/desktop-app/src/__tests__/chatMessageMerge.test.ts@@ -309,4 +309,128 @@ describe('mergeAuthoritativeServerMessages', () => {}),])})++ it('does not reuse later exact matches when backfilling older server turns', () => {+ const existing: ChatMessage[] = Array.from({ length: 4 }, (_, index) => index + 5).flatMap(+ n => [+ {+ id: `turn-${n}-user-local`,+ role: 'user' as const,+ content: `local q${n}`,+ timestamp: n * 10,+ serverTurnNumber: n,+ task_id: `task-${n}`,+ attachments: [+ {+ id: `upload-${n}`,+ type: 'uploaded_file' as const,+ label: `file-${n}.txt`,+ },+ ],+ },+ {+ id: `turn-${n}-assistant-local`,+ role: 'assistant' as const,+ content: `local a${n}`,+ timestamp: n * 10 + 1,+ serverTurnNumber: n,+ task_id: `task-${n}`,+ },+ ]+ )+ const incoming = turnsToChatMessages(+ Array.from({ length: 8 }, (_, index) => ({+ number: index + 1,+ user_input: `q${index + 1}`,+ response: `a${index + 1}`,+ started_at: new Date(index + 1).toISOString(),+ }))+ )++ const merged = mergeAuthoritativeServerMessages(existing, incoming)++ expect(merged.map(message => message.id)).toEqual(+ Array.from({ length: 8 }, (_, index) => index + 1).flatMap(n => [+ `turn-${n}-user`,+ `turn-${n}-assistant`,+ ])+ )+ expect(+ merged+ .filter(message => (message.serverTurnNumber ?? 0) <= 4)+ .flatMap(message => [message.task_id, message.attachments])+ .filter(Boolean)+ ).toEqual([])+ expect(+ merged+ .filter(message => message.serverTurnNumber === 5)+ .map(message => ({+ id: message.id,+ taskId: message.task_id,+ attachmentId: message.attachments?.[0]?.id,+ }))+ ).toEqual([+ { id: 'turn-5-user', taskId: 'task-5', attachmentId: 'upload-5' },+ { id: 'turn-5-assistant', taskId: 'task-5', attachmentId: undefined },+ ])+ })++ it('places a server response after the active optimistic prompt for that turn', () => {+ const merged = mergeAuthoritativeServerMessages(+ [+ {+ id: 'turn-5-user-local',+ role: 'user',+ content: 'q5',+ timestamp: 1,+ serverTurnNumber: 5,+ },+ {+ id: 'turn-5-assistant-local',+ role: 'assistant',+ content: 'a5',+ timestamp: 2,+ serverTurnNumber: 5,+ },+ {+ id: 'optimistic-turn-6-user',+ role: 'user',+ content: 'q6',+ timestamp: 3,+ task_id: 'task-live',+ },+ ],+ [+ {+ id: 'turn-5-user',+ role: 'user',+ content: 'q5',+ timestamp: 4,+ serverTurnNumber: 5,+ },+ {+ id: 'turn-5-assistant',+ role: 'assistant',+ content: 'a5',+ timestamp: 5,+ serverTurnNumber: 5,+ },+ {+ id: 'turn-6-assistant',+ role: 'assistant',+ content: 'a6',+ timestamp: 6,+ serverTurnNumber: 6,+ },+ ],+ { activeTaskIds: new Set(['task-live']) }+ )++ expect(merged.map(message => message.id)).toEqual([+ 'turn-5-user',+ 'turn-5-assistant',+ 'optimistic-turn-6-user',+ 'turn-6-assistant',+ ])+ })})diff --git a/desktop-app/src/__tests__/chatStore.test.ts b/desktop-app/src/__tests__/chatStore.test.tsindex e3b8afe7b..95cee58c5 100644--- a/desktop-app/src/__tests__/chatStore.test.ts+++ b/desktop-app/src/__tests__/chatStore.test.ts@@ -764,9 +764,15 @@ describe('messages', () => {).toEqual(['m1', 'm2', 'm3'])})- it('publishes a true replacement for a bounded reconciliation fallback', async () => {- await store.createChat('agent-1', 'true-replace')- await store.saveMessages('agent-1', 'true-replace', [+ it('preserves local history around a bounded reconciliation fallback', async () => {+ await store.createChat('agent-1', 'bounded-window')+ await store.saveMessages('agent-1', 'bounded-window', [+ {+ id: 'local-note',+ role: 'assistant',+ content: 'local-only message outside the server window',+ timestamp: 0,+ },{id: 'turn-1-user',role: 'user',@@ -785,7 +791,7 @@ describe('messages', () => {await store.replaceMessages('agent-1',- 'true-replace',+ 'bounded-window',[{id: 'turn-999-user',@@ -799,8 +805,8 @@ describe('messages', () => {)expect(- (await store.loadMessages('agent-1', 'true-replace')).map(message => message.id)- ).toEqual(['turn-999-user'])+ (await store.loadMessages('agent-1', 'bounded-window')).map(message => message.id)+ ).toEqual(['local-note', 'turn-1-user', 'turn-999-user'])})it('uses active task context while persisting an authoritative window', async () => {diff --git a/desktop-app/src/chatMessageMerge.ts b/desktop-app/src/chatMessageMerge.tsindex c2c51c4c5..4153577a0 100644--- a/desktop-app/src/chatMessageMerge.ts+++ b/desktop-app/src/chatMessageMerge.ts@@ -118,26 +118,44 @@ export function mergeAuthoritativeServerMessages()}}- const replacements = authoritative- .filter(- message =>- !claimedAuthoritativeSlots.has(`${messageServerTurnNumber(message)}\u0000${message.role}`)+ const replacements = authoritative.filter(+ message =>+ !claimedAuthoritativeSlots.has(`${messageServerTurnNumber(message)}\u0000${message.role}`)+ )+ const consumedRemovedMessages = new Set<ChatMessage>()+ const exactLocalByIncoming = new Map<ChatMessage, ChatMessage>()+ for (const message of replacements) {+ const sameTurn = removed.find(+ local =>+ !consumedRemovedMessages.has(local) &&+ messageServerTurnNumber(local) === messageServerTurnNumber(message) &&+ local.role === message.role)- .map(message => {- const sameTurn = removed.find(- local =>- messageServerTurnNumber(local) === messageServerTurnNumber(message) &&- local.role === message.role- )- const local = sameTurn ?? availableByRole.get(message.role)?.shift()- return {- message: preferredServerMessage(message, local),- localAnchorIndex: local ? removedIndexByMessage.get(local) : undefined,- }- })+ if (sameTurn) {+ consumedRemovedMessages.add(sameTurn)+ exactLocalByIncoming.set(message, sameTurn)+ }+ }+ const takeFallbackByRole = (role: ChatMessage['role']): ChatMessage | undefined => {+ const entries = availableByRole.get(role)+ while (entries?.length) {+ const candidate = entries.shift()!+ if (consumedRemovedMessages.has(candidate)) continue+ consumedRemovedMessages.add(candidate)+ return candidate+ }+ return undefined+ }+ const hydratedReplacements = replacements.map(message => {+ const local = exactLocalByIncoming.get(message) ?? takeFallbackByRole(message.role)+ return {+ message: preferredServerMessage(message, local),+ localAnchorIndex: local ? removedIndexByMessage.get(local) : undefined,+ }+ })const replacementAnchorByTurn = new Map<number, number>()- for (const replacement of replacements) {+ for (const replacement of hydratedReplacements) {const replacementTurn = messageServerTurnNumber(replacement.message)!if (replacement.localAnchorIndex === undefined) continueconst currentAnchor = replacementAnchorByTurn.get(replacementTurn)@@ -146,7 +164,8 @@ export function mergeAuthoritativeServerMessages(}}const replacementBuckets = new Map<number, ChatMessage[]>()- for (const replacement of replacements) {+ let minimumAnchorIndex = 0+ for (const replacement of hydratedReplacements) {const replacementTurn = messageServerTurnNumber(replacement.message)!const exactTurnAnchor = existing.findIndex(message => messageServerTurnNumber(message) === replacementTurn@@ -162,6 +181,8 @@ export function mergeAuthoritativeServerMessages(})}if (anchorIndex < 0) anchorIndex = existing.length+ anchorIndex = Math.max(anchorIndex, minimumAnchorIndex)+ minimumAnchorIndex = anchorIndexreplacementAnchorByTurn.set(replacementTurn, anchorIndex)const bucket = replacementBuckets.get(anchorIndex) ?? []bucket.push(replacement.message)diff --git a/desktop-app/src/chatStore.ts b/desktop-app/src/chatStore.tsindex 5ce6c579f..903e7efc8 100644--- a/desktop-app/src/chatStore.ts+++ b/desktop-app/src/chatStore.ts@@ -1454,11 +1454,9 @@ export class ChatStore {const existingMessages = existingMeta? await this.readMessagesFromPagedMeta(agentRef, chatId, existingMeta): []- const merged = options.replaceLocalWindow- ? messages- : mergeAuthoritativeServerMessages(existingMessages, messages, {- activeTaskIds: options.activeTaskIds ? new Set(options.activeTaskIds) : undefined,- })+ const merged = mergeAuthoritativeServerMessages(existingMessages, messages, {+ activeTaskIds: options.activeTaskIds ? new Set(options.activeTaskIds) : undefined,+ })const indexedCount = await this.indexedMessageCount(agentRef, chatId)await this.writePagedChatUnlocked(agentRef, chatId, merged, {messageCount: Math.max(merged.length, indexedCount ?? 0),diff --git a/desktop-app/src/types.ts b/desktop-app/src/types.tsindex 70980a115..a83d04252 100644--- a/desktop-app/src/types.ts+++ b/desktop-app/src/types.ts@@ -1042,8 +1042,8 @@ export interface ChatMessage {* Controls how an authoritative server page is persisted locally.** `activeTaskIds` lets the main process protect the same optimistic slots as- * the renderer. `replaceLocalWindow` is used only by the bounded latest-page- * fallback, where stale numbered turns must not survive on disk.+ * the renderer. `replaceLocalWindow` marks the bounded latest-page fallback;+ * it still merges into local history rather than truncating the whole chat.*/export interface ReplaceChatMessagesOptions {activeTaskIds?: string[]diff --git a/desktop-app/ui/src/hooks/domain/__tests__/switchToChat.unified.test.tsx b/desktop-app/ui/src/hooks/domain/__tests__/switchToChat.unified.test.tsxindex 37f0f14d1..84c07ea79 100644--- a/desktop-app/ui/src/hooks/domain/__tests__/switchToChat.unified.test.tsx+++ b/desktop-app/ui/src/hooks/domain/__tests__/switchToChat.unified.test.tsx@@ -297,6 +297,8 @@ describe('switchToChat (unified, D.4)', () => {{ limit: 40 })expect(result.current.chatMessages.map(message => message.id)).toEqual([+ 'turn-1-user',+ 'turn-1-assistant','turn-999-user','turn-999-assistant',])@@ -433,6 +435,53 @@ describe('switchToChat (unified, D.4)', () => {expect(result.current.hasOlderMessages).toBe(false)})+ it('ignores hasMoreBefore from an empty afterTurn reconciliation response', async () => {+ const cached = [+ {+ id: 'turn-1-user',+ role: 'user' as const,+ content: 'q1',+ timestamp: 1,+ serverTurnNumber: 1,+ },+ {+ id: 'turn-1-assistant',+ role: 'assistant' as const,+ content: 'a1',+ timestamp: 2,+ serverTurnNumber: 1,+ },+ ]+ clerum.chat.loadMessages.mockResolvedValue(cached)+ clerum.rpc.loadSessionMessages.mockResolvedValue({+ agent: 'agent-x',+ chatId: 'synced-chat',+ state: 'idle',+ turns: [],+ hasMoreBefore: true,+ hasMoreAfter: false,+ })+ const { result } = renderController()+ await settleMount()++ await act(async () => {+ await result.current.switchToChat('agent-x', 'synced-chat')+ })++ expect(clerum.rpc.loadSessionMessages).toHaveBeenCalledWith(+ 'agent-x',+ 'agent-x',+ 'synced-chat',+ undefined,+ { limit: 40, afterTurn: 1 }+ )+ expect(result.current.chatMessages.map(message => message.id)).toEqual([+ 'turn-1-user',+ 'turn-1-assistant',+ ])+ expect(result.current.hasOlderMessages).toBe(false)+ })+it('does not keep older history visible after loading an exact multiple of local pages', async () => {const allMessages = Array.from({ length: 160 }, (_, index) => ({id: `turn-${index + 1}-user`,@@ -530,6 +579,72 @@ describe('switchToChat (unified, D.4)', () => {expect(result.current.olderMessagesLoading).toBe(false)})+ it('ignores an older-page response when switching away and back before it resolves', async () => {+ let resolveOlder!: (messages: unknown[]) => void+ const olderPage = new Promise<unknown[]>(resolve => {+ resolveOlder = resolve+ })+ clerum.chat.loadMessages.mockImplementation(+ async (_agentRef: string, chatId: string, _limit?: number, offset?: number) => {+ if (chatId === 'chat-a' && offset === 1) return olderPage+ if (chatId === 'chat-a') {+ return [+ {+ id: 'turn-10-user',+ role: 'user' as const,+ content: 'q10',+ timestamp: 10,+ serverTurnNumber: 10,+ },+ ]+ }+ return []+ }+ )+ clerum.rpc.loadSessionMessages.mockImplementation(+ async (_hostRef: string, _agent: string, chatId: string) => ({+ agent: 'agent-x',+ chatId,+ state: 'idle',+ turns: [],+ hasMoreBefore: false,+ hasMoreAfter: false,+ })+ )+ const { result } = renderController()+ await settleMount()+ await act(async () => {+ await result.current.switchToChat('agent-x', 'chat-a')+ })++ let pendingOlder!: Promise<void>+ act(() => {+ pendingOlder = result.current.handleLoadOlderMessages()+ })+ await waitFor(() => expect(result.current.olderMessagesLoading).toBe(true))++ await act(async () => {+ await result.current.switchToChat('agent-x', 'chat-b')+ await result.current.switchToChat('agent-x', 'chat-a')+ })++ resolveOlder([+ {+ id: 'turn-1-user',+ role: 'user',+ content: 'stale q1',+ timestamp: 1,+ serverTurnNumber: 1,+ },+ ])+ await act(async () => {+ await pendingOlder+ })++ expect(result.current.chatMessages.map(message => message.id)).toEqual(['turn-10-user'])+ expect(result.current.olderMessagesLoading).toBe(false)+ })+it('adds a server-only chat to the sidebar when switched to directly (S4)', async () => {// chatList starts empty (default getIndex → no chats); simulate opening a// notification for a chat the local list doesn't know about.diff --git a/desktop-app/ui/src/hooks/domain/useAgentChatController.ts b/desktop-app/ui/src/hooks/domain/useAgentChatController.tsindex 6a373b55f..f98ccfb48 100644--- a/desktop-app/ui/src/hooks/domain/useAgentChatController.ts+++ b/desktop-app/ui/src/hooks/domain/useAgentChatController.ts@@ -107,8 +107,10 @@ const LOCAL_MESSAGE_PAGE_SIZE = 80const SERVER_TURN_PAGE_SIZE = 40const MAX_RECONCILE_DELTA_PAGES = 5const REPLACE_LOCAL_RECONCILIATION_WINDOW = Symbol('replace-local-reconciliation-window')+const DELTA_RECONCILIATION_WINDOW = Symbol('delta-reconciliation-window')type ReconciliationMessagesResult = SessionMessagesResult & {[REPLACE_LOCAL_RECONCILIATION_WINDOW]?: true+ [DELTA_RECONCILIATION_WINDOW]?: true}function serverTurnNumber(message: AgentChatMessage): number | undefined {@@ -873,7 +875,11 @@ export function useAgentChatController({olderMessagesRequestRef.current = requestTokenconst isStillRelevant = () => {const visible = activeChatVisibilityRef.current- return visible.selectedAgent === requestAgent && visible.activeChatId === requestChatId+ return (+ olderMessagesRequestRef.current === requestToken &&+ visible.selectedAgent === requestAgent &&+ visible.activeChatId === requestChatId+ )}setOlderMessagesLoading(true)try {@@ -1294,8 +1300,8 @@ export function useAgentChatController({// instance — and its coalescing state — stable across renders.// Shared hydration (§4.3 / A.4.4): materialize the server's page into the- // active view, append a delta when the cache has durable server turn IDs, or- // replace once when migrating a legacy/random-ID cache. It also auto-titles a+ // active view, append a delta when the cache has durable server turn IDs, and+ // merge server windows into legacy/random-ID caches. It also auto-titles a// fresh hydration from turn one and upserts the sidebar (S4).// Both reconcile branches use it: `settleIdle` (idle replace) and// `attachLiveTask` (render in-flight turns so a rejoin can anchor to the@@ -1328,19 +1334,22 @@ export function useAgentChatController({const visible = isActive() ? chatMessagesRef.current : []const replaceLocalWindow =(resp as ReconciliationMessagesResult)[REPLACE_LOCAL_RECONCILIATION_WINDOW] === true- const localMessages = replaceLocalWindow ? [] : mergeUniqueMessages(visible, cached)+ const deltaWindow =+ (resp as ReconciliationMessagesResult)[DELTA_RECONCILIATION_WINDOW] === true+ const hasOlderFromServer = !deltaWindow && Boolean(resp.hasMoreBefore)+ const localMessages = mergeUniqueMessages(visible, cached)if (!isActive() || tracker.get(chatKey)) {return { rendered: localMessages, replaced: false, cached: localMessages }}const hydrated = turnsToChatMessages(resp.turns) as AgentChatMessage[]- if (replaceLocalWindow) {- setHasOlderMessages(Boolean(resp.hasMoreBefore))- } else {- setHasOlderMessages(previous => previous || Boolean(resp.hasMoreBefore))- }if (!hydrated.length) {return { rendered: localMessages, replaced: false, cached: localMessages }}+ if (replaceLocalWindow) {+ setHasOlderMessages(hasOlderFromServer)+ } else {+ setHasOlderMessages(previous => previous || hasOlderFromServer)+ }const localHasServerTurns = localMessages.some(message => serverTurnNumber(message) !== undefined)@@ -1358,7 +1367,7 @@ export function useAgentChatController({if (!isActive() || tracker.get(chatKey)) {return { rendered: localMessages, replaced: false, cached: localMessages }}- const rendered = localHasServerTurns+ const rendered = localMessages.length? mergeServerMessages(localMessages,hydratedWithAttachments,@@ -1612,6 +1621,12 @@ export function useAgentChatController({requestedQuery)if (requestedQuery.afterTurn === undefined || !response.hasMoreAfter) {+ if (requestedQuery.afterTurn !== undefined) {+ return {+ ...response,+ [DELTA_RECONCILIATION_WINDOW]: true,+ } satisfies ReconciliationMessagesResult+ }return response}@@ -1622,7 +1637,10 @@ export function useAgentChatController({// A host claiming another page without returning an advancing cursor// is malformed. Preserve the local cache instead of replacing it with// an unrelated latest window.- return response+ return {+ ...response,+ [DELTA_RECONCILIATION_WINDOW]: true,+ } satisfies ReconciliationMessagesResult}let pagesLoaded = 1while (@@ -1649,6 +1667,7 @@ export function useAgentChatController({turns,oldestTurnNumber: turns[0]?.number,latestTurnNumber: turns.at(-1)?.number,+ [DELTA_RECONCILIATION_WINDOW]: true,}}}@@ -1667,6 +1686,7 @@ export function useAgentChatController({oldestTurnNumber: turns[0]?.number,latestTurnNumber: turns.at(-1)?.number,hasMoreAfter: false,+ [DELTA_RECONCILIATION_WINDOW]: true,}},attachLiveTask: reconcileAttachLiveTask,diff --git a/mcp-host/package-lock.json b/mcp-host/package-lock.jsonindex dbe52f49f..acd624289 100644--- a/mcp-host/package-lock.json+++ b/mcp-host/package-lock.json@@ -1,12 +1,12 @@{"name": "clerum-mcp-host",- "version": "0.1.219",+ "version": "0.1.220","lockfileVersion": 3,"requires": true,"packages": {"": {"name": "clerum-mcp-host",- "version": "0.1.219",+ "version": "0.1.220","license": "SEE LICENSE IN LICENSE","dependencies": {"@anthropic-ai/sdk": "^0.32.0",diff --git a/mcp-host/package.json b/mcp-host/package.jsonindex ee3cf627d..576ac3fa7 100644--- a/mcp-host/package.json+++ b/mcp-host/package.json@@ -1,6 +1,6 @@{"name": "clerum-mcp-host",- "version": "0.1.219",+ "version": "0.1.220","description": "MCP Host - reads Host CRD and provides LLM access via OpenAI/Claude","main": "dist/main.js","engines": {diff --git a/mcp-host/src/core/conversation/persistence/__tests__/sqliteConversationStore.test.ts b/mcp-host/src/core/conversation/persistence/__tests__/sqliteConversationStore.test.tsindex 0a221be6c..501a4f299 100644--- a/mcp-host/src/core/conversation/persistence/__tests__/sqliteConversationStore.test.ts+++ b/mcp-host/src/core/conversation/persistence/__tests__/sqliteConversationStore.test.ts@@ -689,7 +689,7 @@ describe('SqliteConversationStore — active_task_id (D.1)', () => {}})- it('reserves and rolls back a completion turn number around the durability await', async () => {+ it('does not reuse a turn number after completion and failure writes both reject', async () => {const handle = await freshStore()try {const manager = new ConversationManager(handle.store)@@ -699,14 +699,27 @@ describe('SqliteConversationStore — active_task_id (D.1)', () => {const enqueueSpy = vi.spyOn(handle.persistQueue, 'enqueueSync').mockRejectedValueOnce(new Error('disk unavailable'))- await expect(handle.store.persistTurnComplete(conv, 'failed write')).rejects.toThrow(- /disk unavailable/- )- expect(handle.store['ordinals'].get(conv.id)?.nextTurnNumber).toBe(1)+ .mockRejectedValueOnce(new Error('disk still unavailable'))+ await expect(manager.completeTurn(conv, 'failed write')).rejects.toThrow(/disk unavailable/)+ expect(handle.store['ordinals'].get(conv.id)?.nextTurnNumber).toBe(2)+ await expect(manager.failTurn(conv)).rejects.toThrow(/disk still unavailable/)+ expect(handle.store['ordinals'].get(conv.id)?.nextTurnNumber).toBe(2)enqueueSpy.mockRestore()- await handle.store.persistTurnComplete(conv, 'durable response')- expect(handle.store['ordinals'].get(conv.id)?.nextTurnNumber).toBe(2)+ await manager.startTurn(conv, 'second', 'task-next')+ await manager.completeTurn(conv, 'durable response')+ expect(handle.store['ordinals'].get(conv.id)?.nextTurnNumber).toBe(3)++ const rows = handle.worker.db+ .prepare(+ 'SELECT role, content, turn_number FROM messages WHERE session_id = ? ORDER BY ordinal'+ )+ .all(conv.id) as Array<{ role: string; content: string; turn_number: number }>+ expect(rows.map(row => [row.role, row.content, row.turn_number])).toEqual([+ ['user', 'first', 1],+ ['user', 'second', 2],+ ['assistant', 'durable response', 2],+ ])} finally {await handle.shutdown()}diff --git a/mcp-host/src/core/conversation/persistence/sqliteConversationStore.ts b/mcp-host/src/core/conversation/persistence/sqliteConversationStore.tsindex 580c02cd3..045d16f10 100644--- a/mcp-host/src/core/conversation/persistence/sqliteConversationStore.ts+++ b/mcp-host/src/core/conversation/persistence/sqliteConversationStore.ts@@ -718,44 +718,36 @@ export class SqliteConversationStore implements ConversationStore {// accumulated it in RAM via recordSessionUsage). reconstruct sums these back// onto the Turn on cold-load.const turn = conv.turns[conv.turns.length - 1]- try {- await this.persistQueue.enqueueSync(- {- kind: 'persist_turn_boundary',- message: {- session_id: conv.id,- ordinal,- role: 'assistant',- content: response,- content_parts: null,- tool_call_id: null,- tool_calls: null,- tool_name: null,- timestamp: Date.now() / 1000,- token_count: null,- finish_reason: 'stop',- spillover_ref: null,- is_error: 0,- turn_number: turnNumber,- input_tokens: turn?.input_tokens ?? null,- output_tokens: turn?.output_tokens ?? null,- cache_read_tokens: turn?.cache_read_tokens ?? null,- cache_write_tokens: turn?.cache_write_tokens ?? null,- },- sessionId: conv.id,- state: conv.state,- activeTaskId: null, // D.1 — turn complete clears the in-flight task- activeTraceContext: null,+ await this.persistQueue.enqueueSync(+ {+ kind: 'persist_turn_boundary',+ message: {+ session_id: conv.id,+ ordinal,+ role: 'assistant',+ content: response,+ content_parts: null,+ tool_call_id: null,+ tool_calls: null,+ tool_name: null,+ timestamp: Date.now() / 1000,+ token_count: null,+ finish_reason: 'stop',+ spillover_ref: null,+ is_error: 0,+ turn_number: turnNumber,+ input_tokens: turn?.input_tokens ?? null,+ output_tokens: turn?.output_tokens ?? null,+ cache_read_tokens: turn?.cache_read_tokens ?? null,+ cache_write_tokens: turn?.cache_write_tokens ?? null,},- sessionKey- )- } catch (error) {- // Roll back only if no later turn has advanced the same state meanwhile.- if (state.nextTurnNumber === turnNumber + 1) {- state.nextTurnNumber = turnNumber- }- throw error- }+ sessionId: conv.id,+ state: conv.state,+ activeTaskId: null, // D.1 — turn complete clears the in-flight task+ activeTraceContext: null,+ },+ sessionKey+ )}async persistTurnCancel(conv: Conversation): Promise<void> {@@ -822,6 +814,11 @@ export class SqliteConversationStore implements ConversationStore {const sessionKey = this.sessionKeyById.get(conv.id)if (!sessionKey) returnthis.reconcilePinning(sessionKey, conv)+ const state = this.ordinals.get(conv.id) ?? this.initOrdinalState(conv.id)+ // Reserve before the durability await. If persistTurnComplete already+ // reserved this completed turn, keep that reservation rather than skipping+ // another number while failing the same in-RAM turn.+ state.nextTurnNumber = Math.max(state.nextTurnNumber, conv.turns.length + 1)await this.persistQueue.enqueueSync({kind: 'update_session_state',@@ -832,8 +829,6 @@ export class SqliteConversationStore implements ConversationStore {},sessionKey)- const state = this.ordinals.get(conv.id) ?? this.initOrdinalState(conv.id)- state.nextTurnNumber += 1}persistToolCall(conv: Conversation, toolCall: TurnToolCall): void {