Evenfire is an intelligence layer platform for running LLM agents that take real actions, on your infrastructure
TypeScript
fix: address paged chat review findings
Josuédbc085e805ae
diff --git a/desktop-app/package-lock.json b/desktop-app/package-lock.jsonindex ecff9fed5..d554b86d2 100644--- a/desktop-app/package-lock.json+++ b/desktop-app/package-lock.json@@ -1,12 +1,12 @@{"name": "evenfire",- "version": "0.1.333",+ "version": "0.1.334","lockfileVersion": 3,"requires": true,"packages": {"": {"name": "evenfire",- "version": "0.1.333",+ "version": "0.1.334","license": "MPL-2.0","dependencies": {"@tanstack/react-query": "5.100.10",diff --git a/desktop-app/package.json b/desktop-app/package.jsonindex 6bcdd01aa..afbf6e5ee 100644--- a/desktop-app/package.json+++ b/desktop-app/package.json@@ -1,7 +1,7 @@{"name": "evenfire","productName": "Evenfire",- "version": "0.1.333",+ "version": "0.1.334","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 422ee48a2..93ccf67e0 100644--- a/desktop-app/src/__tests__/chatMessageMerge.test.ts+++ b/desktop-app/src/__tests__/chatMessageMerge.test.ts@@ -74,6 +74,40 @@ describe('mergeAuthoritativeServerMessages', () => {expect(merged.map(message => message.id)).toEqual(['turn-3-user', 'pending'])})+ it('does not duplicate an active optimistic message when the server returns its turn', () => {+ const merged = mergeAuthoritativeServerMessages(+ [+ {+ 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,+ task_id: 'task-2',+ },+ ],+ { activeTaskIds: new Set(['task-2']) }+ )++ expect(merged.map(message => message.id)).toEqual(['turn-1-user', 'optimistic-task-2'])+ })+it('replaces completed task-backed echoes inside their authoritative turn', () => {const merged = mergeAuthoritativeServerMessages([diff --git a/desktop-app/src/__tests__/chatStore.test.ts b/desktop-app/src/__tests__/chatStore.test.tsindex c34d5800e..e901ed856 100644--- a/desktop-app/src/__tests__/chatStore.test.ts+++ b/desktop-app/src/__tests__/chatStore.test.ts@@ -1,7 +1,7 @@import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'import { promises as fs } from 'node:fs'import { tmpdir } from 'node:os'-import { join } from 'node:path'+import { dirname, join } from 'node:path'import { ChatStore } from '../chatStore.js'import type { ChatMessage } from '../types.js'@@ -34,6 +34,19 @@ function chatPagesDir(chatId: string): string {return join(chatCacheDir(chatId), 'pages')}+function chatSnapshotDir(+ chatId: string,+ kind: 'next' | 'previous' | 'corrupt',+ token: string+): string {+ return agentPath(+ 'chats',+ '.snapshots',+ Buffer.from(chatId, 'utf8').toString('base64url'),+ `${kind}-${token}`+ )+}+function transientFileReadError(code = 'EMFILE'): NodeJS.ErrnoException {const err = new Error(code) as NodeJS.ErrnoExceptionerr.code = code@@ -361,7 +374,13 @@ describe('messages', () => {const originalWriteFile = fs.writeFile.bind(fs)vi.spyOn(fs, 'writeFile').mockImplementation(async (...args) => {const filePath = String(args[0])- if (filePath.includes('rewrite-failure.next-') && filePath.endsWith('000001.json.tmp')) {+ if (+ filePath.includes(+ join('.snapshots', Buffer.from('rewrite-failure').toString('base64url'))+ ) &&+ filePath.includes('next-') &&+ filePath.endsWith('000001.json.tmp')+ ) {throw new Error('injected page write failure')}return originalWriteFile(...(args as Parameters<typeof fs.writeFile>))@@ -457,10 +476,9 @@ describe('messages', () => {{ id: 'm1', role: 'assistant', content: 'msg-1', timestamp: 1 },])- await fs.rename(- chatCacheDir('switch-recovery'),- `${chatCacheDir('switch-recovery')}.previous-test`- )+ const previousSnapshot = chatSnapshotDir('switch-recovery', 'previous', 'test')+ await fs.mkdir(dirname(previousSnapshot), { recursive: true })+ await fs.rename(chatCacheDir('switch-recovery'), previousSnapshot)const reloaded = await pagedStore.loadMessages('agent-1', 'switch-recovery')expect(reloaded.map(message => message.id)).toEqual(['m0', 'm1'])@@ -477,17 +495,20 @@ describe('messages', () => {{ id: 'old-0', role: 'user', content: 'old-0', timestamp: 0 },])- const nextDir = `${chatCacheDir('next-recovery')}.next-test`+ const nextDir = chatSnapshotDir('next-recovery', 'next', 'test')await writePagedSnapshotDir('next-recovery', nextDir, [{ id: 'new-0', role: 'user', content: 'new-0', timestamp: 1 },{ id: 'new-1', role: 'assistant', content: 'new-1', timestamp: 2 },])- await fs.rename(chatCacheDir('next-recovery'), `${chatCacheDir('next-recovery')}.previous-test`)+ await fs.rename(+ chatCacheDir('next-recovery'),+ chatSnapshotDir('next-recovery', 'previous', 'test')+ )const reloaded = await pagedStore.loadMessages('agent-1', 'next-recovery')expect(reloaded.map(message => message.id)).toEqual(['new-0', 'new-1'])- await expect(fs.access(`${chatCacheDir('next-recovery')}.next-test`)).rejects.toThrow()- await expect(fs.access(`${chatCacheDir('next-recovery')}.previous-test`)).rejects.toThrow()+ await expect(fs.access(chatSnapshotDir('next-recovery', 'next', 'test'))).rejects.toThrow()+ await expect(fs.access(chatSnapshotDir('next-recovery', 'previous', 'test'))).rejects.toThrow()})it('uses the newest valid snapshot group instead of preferring stale next snapshots', async () => {@@ -500,8 +521,8 @@ describe('messages', () => {{ id: 'active-0', role: 'user', content: 'active-0', timestamp: 0 },])- const staleNext = `${chatCacheDir('snapshot-order')}.next-old`- const freshPrevious = `${chatCacheDir('snapshot-order')}.previous-new`+ const staleNext = chatSnapshotDir('snapshot-order', 'next', 'old')+ const freshPrevious = chatSnapshotDir('snapshot-order', 'previous', 'new')await writePagedSnapshotDir('snapshot-order', staleNext, [{ id: 'stale-0', role: 'user', content: 'stale-0', timestamp: 1 },])@@ -524,7 +545,7 @@ describe('messages', () => {maxLocalSyncedMessages: Number.POSITIVE_INFINITY,})await pagedStore.createChat('agent-1', 'incomplete-snapshot')- const incomplete = `${chatCacheDir('incomplete-snapshot')}.previous-test`+ const incomplete = chatSnapshotDir('incomplete-snapshot', 'previous', 'test')await writePagedSnapshotDir('incomplete-snapshot', incomplete, [{ id: 'backup-0', role: 'user', content: 'backup-0', timestamp: 0 },])@@ -545,8 +566,8 @@ describe('messages', () => {{ id: 'm0', role: 'user', content: 'msg-0', timestamp: 0 },])- await fs.mkdir(`${chatCacheDir('stale-snapshots')}.next-stale`, { recursive: true })- await fs.mkdir(`${chatCacheDir('stale-snapshots')}.previous-stale`, { recursive: true })+ await fs.mkdir(chatSnapshotDir('stale-snapshots', 'next', 'stale'), { recursive: true })+ await fs.mkdir(chatSnapshotDir('stale-snapshots', 'previous', 'stale'), { recursive: true })const restartedStore = new ChatStore(tempDir, {pageSize: 2,@@ -554,8 +575,10 @@ describe('messages', () => {})const reloaded = await restartedStore.loadMessages('agent-1', 'stale-snapshots')expect(reloaded.map(message => message.id)).toEqual(['m0'])- await expect(fs.access(`${chatCacheDir('stale-snapshots')}.next-stale`)).rejects.toThrow()- await expect(fs.access(`${chatCacheDir('stale-snapshots')}.previous-stale`)).rejects.toThrow()+ await expect(fs.access(chatSnapshotDir('stale-snapshots', 'next', 'stale'))).rejects.toThrow()+ await expect(+ fs.access(chatSnapshotDir('stale-snapshots', 'previous', 'stale'))+ ).rejects.toThrow()})it('deletes snapshot siblings so removed chats cannot be recovered later', async () => {@@ -569,14 +592,16 @@ describe('messages', () => {])await writePagedSnapshotDir('delete-siblings',- `${chatCacheDir('delete-siblings')}.previous-test`,+ chatSnapshotDir('delete-siblings', 'previous', 'test'),[{ id: 'backup-0', role: 'user', content: 'backup-0', timestamp: 1 }])await pagedStore.deleteChat('agent-1', 'delete-siblings')expect(await pagedStore.loadMessages('agent-1', 'delete-siblings')).toEqual([])- await expect(fs.access(`${chatCacheDir('delete-siblings')}.previous-test`)).rejects.toThrow()+ await expect(+ fs.access(chatSnapshotDir('delete-siblings', 'previous', 'test'))+ ).rejects.toThrow()})it('prunes only old pages whose messages are known to exist on the server', async () => {@@ -601,13 +626,11 @@ describe('messages', () => {messageCount: numberlocalMessageCount: numberprunedBeforeCount: number- prunedThroughServerTurnNumber: number}>(chatMetaPath('pruned'))expect(meta).toMatchObject({messageCount: 6,localMessageCount: 4,prunedBeforeCount: 2,- prunedThroughServerTurnNumber: 2,})const chat = (await prunedStore.listChats('agent-1')).find(item => item.id === 'pruned')@@ -616,7 +639,7 @@ describe('messages', () => {expect(localMessages.map(message => message.id)).toEqual(['m2', 'm3', 'm4', 'm5'])})- it('keeps local-only pages while pruning later fully synced pages', async () => {+ it('keeps a contiguous transcript when an older local-only page blocks pruning', async () => {const prunedStore = new ChatStore(tempDir, {pageSize: 2,maxLocalSyncedMessages: 4,@@ -632,12 +655,40 @@ describe('messages', () => {await prunedStore.saveMessages('agent-1', 'local-only', msgs)- expect(await fs.readdir(chatPagesDir('local-only'))).toEqual(['000001.json', '000003.json'])+ expect(await fs.readdir(chatPagesDir('local-only'))).toEqual([+ '000001.json',+ '000002.json',+ '000003.json',+ ])const meta = await readJsonFile<{ localMessageCount: number; prunedBeforeCount?: number }>(chatMetaPath('local-only'))- expect(meta.localMessageCount).toBe(4)- expect(meta.prunedBeforeCount).toBe(2)+ expect(meta.localMessageCount).toBe(6)+ expect(meta.prunedBeforeCount).toBeUndefined()+ expect(+ (await prunedStore.loadMessages('agent-1', 'local-only')).map(message => message.id)+ ).toEqual(msgs.map(message => message.id))+ })++ it('recognizes legacy turn-N-role ids as server-synced for safe prefix pruning', async () => {+ const prunedStore = new ChatStore(tempDir, {+ pageSize: 2,+ maxLocalSyncedMessages: 2,+ })+ await prunedStore.createChat('agent-1', 'legacy-turn-ids')+ const msgs = [+ { id: 'turn-1-user', role: 'user' as const, content: 'q1', timestamp: 1 },+ { id: 'turn-1-assistant', role: 'assistant' as const, content: 'a1', timestamp: 2 },+ { id: 'turn-2-user', role: 'user' as const, content: 'q2', timestamp: 3 },+ { id: 'turn-2-assistant', role: 'assistant' as const, content: 'a2', timestamp: 4 },+ ]++ await prunedStore.saveMessages('agent-1', 'legacy-turn-ids', msgs)++ expect(await fs.readdir(chatPagesDir('legacy-turn-ids'))).toEqual(['000002.json'])+ expect(+ (await prunedStore.loadMessages('agent-1', 'legacy-turn-ids')).map(message => message.id)+ ).toEqual(['turn-2-user', 'turn-2-assistant'])})it('updates messageCount in index after save', async () => {@@ -1058,7 +1109,13 @@ describe('messages', () => {let injected = falsevi.spyOn(fs, 'writeFile').mockImplementation(async (...args) => {const filePath = String(args[0])- if (!injected && filePath.includes('migration-failure.next-')) {+ if (+ !injected &&+ filePath.includes(+ join('.snapshots', Buffer.from('migration-failure').toString('base64url'))+ ) &&+ filePath.includes('next-')+ ) {injected = truethrow transientFileReadError('ENOSPC')}@@ -1121,6 +1178,26 @@ describe('corrupt/missing files', () => {const messages = await store.loadMessages('agent-1', 'nonexistent')expect(messages).toEqual([])})++ it('quarantines a corrupt legacy chat and allows it to become writable again', async () => {+ const chatId = 'corrupt-legacy'+ await store.createChat('agent-1', chatId)+ await fs.writeFile(agentPath(`${chatId}.json`), '{"version":2,"messages":[')++ await expect(store.loadMessages('agent-1', chatId)).resolves.toEqual([])+ const quarantined = await fs.readdir(agentPath('.corrupt'))+ expect(quarantined).toHaveLength(1)+ await expect(fs.stat(agentPath(`${chatId}.json`))).rejects.toMatchObject({ code: 'ENOENT' })++ const replacement = {+ id: 'turn-1-user',+ role: 'user' as const,+ content: 'rehydrated',+ timestamp: 1,+ }+ await store.appendMessages('agent-1', chatId, [replacement])+ await expect(store.loadMessages('agent-1', chatId)).resolves.toEqual([replacement])+ })})// ── unreadTerminal flag (D.5) ────────────────────────────────────────────────@@ -1188,9 +1265,7 @@ describe('path-segment validation', () => {/unsafe path segment/)await expect(store.saveMessages('agent-1', 'a/b', [])).rejects.toThrow(/unsafe path segment/)- await expect(store.saveMessages('agent-1', 'other.next-shadow', [])).rejects.toThrow(- /unsafe path segment/- )+ await expect(store.saveMessages('agent-1', 'other.next-shadow', [])).resolves.toBeUndefined()})// Read verbs are tolerant-by-contract (return empty on any failure) — the keydiff --git a/desktop-app/src/__tests__/chatStoreBinding.test.ts b/desktop-app/src/__tests__/chatStoreBinding.test.tsindex a76f87be5..46e1ce64f 100644--- a/desktop-app/src/__tests__/chatStoreBinding.test.ts+++ b/desktop-app/src/__tests__/chatStoreBinding.test.ts@@ -38,6 +38,36 @@ describe('chatStoreBinding', () => {expect(() => requireChatStore()).toThrow(/Not authenticated/)})+ it('does not publish a stale store when logout interrupts an in-flight bind', async () => {+ await bindChatStoreForUser('seed-user', ENV_A)+ unbindChatStore()++ const originalReadDir = fs.readdir.bind(fs)+ let releaseRead: (() => void) | undefined+ const readBlocked = new Promise<void>(resolve => {+ releaseRead = resolve+ })+ let readStarted: (() => void) | undefined+ const started = new Promise<void>(resolve => {+ readStarted = resolve+ })+ vi.spyOn(fs, 'readdir').mockImplementation(async (...args) => {+ if (String(args[0]).endsWith(path.join(ENV_A, 'user-b'))) {+ readStarted?.()+ await readBlocked+ }+ return originalReadDir(...(args as Parameters<typeof fs.readdir>))+ })++ const binding = bindChatStoreForUser('user-b', ENV_A)+ await started+ unbindChatStore()+ releaseRead?.()+ await binding++ expect(() => requireChatStore()).toThrow(/Not authenticated/)+ })+it('roots the store under <base>/<envKey>/<userId> (spec §5.2)', async () => {await bindChatStoreForUser('user-a', ENV_A)const store = requireChatStore()diff --git a/desktop-app/src/__tests__/config.runtimeConfig.test.ts b/desktop-app/src/__tests__/config.runtimeConfig.test.tsindex 5c81fd5ca..4226fa011 100644--- a/desktop-app/src/__tests__/config.runtimeConfig.test.ts+++ b/desktop-app/src/__tests__/config.runtimeConfig.test.ts@@ -184,6 +184,33 @@ describe('desktop runtime config', () => {})})+ it('does not let the packaged-development escape hatch select arbitrary loopback ports', async () => {+ tempUserDataDir = await fsp.mkdtemp(path.join(os.tmpdir(), 'evenfire-user-data-'))+ delete process.env.CLERUM_DESKTOP_CONFIG_PATH+ process.env.EXTERNAL_REST_API_BASE_URL = 'http://127.0.0.1:21770'+ process.env.RPC_PROXY_BASE_URL = 'http://127.0.0.1:21773'+ process.argv.push('--evenfire-desktop-dev-package')++ vi.doMock('electron', () => ({+ app: {+ getPath: vi.fn((name: string) =>+ name === 'userData' ? tempUserDataDir : path.dirname(tempUserDataDir || os.tmpdir())+ ),+ isPackaged: true,+ isReady: vi.fn(() => true),+ setName: vi.fn(),+ setPath: vi.fn(),+ },+ }))++ const { getDesktopRuntimeConfigState } = await import('../config.js')++ expect(getDesktopRuntimeConfigState()).toMatchObject({+ configured: false,+ activeOptionId: null,+ })+ })+it('preserves env-provided localhost runtime ports without selecting the fixed localhost profile', async () => {tempUserDataDir = await fsp.mkdtemp(path.join(os.tmpdir(), 'evenfire-user-data-'))delete process.env.CLERUM_DESKTOP_CONFIG_PATHdiff --git a/desktop-app/src/appService.ts b/desktop-app/src/appService.tsindex ea42774a8..d0f30fb09 100644--- a/desktop-app/src/appService.ts+++ b/desktop-app/src/appService.ts@@ -270,6 +270,7 @@ export class AppService {private teamDirectoryCache: TeamDirectoryResult | null = nullprivate teamContextQueue: Promise<void> = Promise.resolve()private restoreSavedSessionInFlight: Promise<SessionState> | null = null+ private logoutInProgress = falseprivate sessionGeneration = 0private workflowApprovalTeamById = new Map<string, string>()private workflowTeamByKey = new Map<string, string>()@@ -551,10 +552,12 @@ export class AppService {}private async restoreSavedSessionOnce(options: { runLaunchMaintenance?: boolean } = {}) {+ if (this.logoutInProgress) return { authenticated: false, me: null }const restoreGeneration = this.sessionGenerationhydrateDesktopRuntimeConfig()const envKey = getActiveEnvKey()const token = await this.tokenStore.getSessionToken(envKey)+ if (this.logoutInProgress) return { authenticated: false, me: null }if (!token) {if (this.sessionGeneration === restoreGeneration) {this.clearAuthenticatedSessionState()@@ -571,14 +574,16 @@ export class AppService {if (this.sessionGeneration !== restoreGeneration || this.sessionToken !== token) {return { authenticated: Boolean(this.sessionToken && this.me), me: this.me }}- this.me = restoredMeawait bindChatStoreForUser(restoredMe.id, envKey)if (this.sessionGeneration !== restoreGeneration || this.sessionToken !== token) {if (this.me) {await bindChatStoreForUser(this.me.id, getActiveEnvKey())+ } else {+ unbindChatStore()}return { authenticated: Boolean(this.sessionToken && this.me), me: this.me }}+ this.me = restoredMethis.accessCatalog = nullthis.teamDirectoryCache = nullthis.workflowApprovalTeamById.clear()@@ -630,6 +635,7 @@ export class AppService {private async completePasswordLogin(email: string, password: string): Promise<SessionState> {const result = await this.authClient.passwordLogin(email, password)+ this.logoutInProgress = falsethis.sessionGeneration += 1this.sessionToken = result.tokenthis.me = result.me@@ -700,6 +706,7 @@ export class AppService {async googleLogin(idToken: string): Promise<SessionState> {const result = await this.authClient.googleLogin(idToken)+ this.logoutInProgress = falsethis.sessionGeneration += 1this.sessionToken = result.tokenthis.me = result.me@@ -885,8 +892,10 @@ export class AppService {}async logout(): Promise<void> {+ this.logoutInProgress = truethis.clearAuthenticatedSessionState()await this.tokenStore.clearSessionToken(getActiveEnvKey())+ this.logoutInProgress = false}/** Resolve a gfs:// URI to its current resource via the API (no local mirror). */diff --git a/desktop-app/src/chatMessageMerge.ts b/desktop-app/src/chatMessageMerge.tsindex d7b38a4cd..2d864f89b 100644--- a/desktop-app/src/chatMessageMerge.ts+++ b/desktop-app/src/chatMessageMerge.ts@@ -99,15 +99,30 @@ export function mergeAuthoritativeServerMessages(entries.push(message)availableByRole.set(message.role, entries)}- const replacements = authoritative.map(message => {- const sameTurn = removed.find(- local =>- messageServerTurnNumber(local) === messageServerTurnNumber(message) &&- local.role === message.role+ const retainedActiveTaskRoles = new Set(+ kept+ .filter(+ message =>+ message.task_id !== undefined &&+ options.activeTaskIds?.has(message.task_id) === true &&+ (message.role === 'user' || message.role === 'assistant')+ )+ .map(message => `${message.task_id}\u0000${message.role}`)+ )+ const replacements = authoritative+ .filter(+ message =>+ !(message.task_id && retainedActiveTaskRoles.has(`${message.task_id}\u0000${message.role}`)))- const local = sameTurn ?? availableByRole.get(message.role)?.shift()- return preferredServerMessage(message, local)- })+ .map(message => {+ const sameTurn = removed.find(+ local =>+ messageServerTurnNumber(local) === messageServerTurnNumber(message) &&+ local.role === message.role+ )+ const local = sameTurn ?? availableByRole.get(message.role)?.shift()+ return preferredServerMessage(message, local)+ })kept.splice(insertionIndex, 0, ...replacements)return keptdiff --git a/desktop-app/src/chatStore.ts b/desktop-app/src/chatStore.tsindex 5420cc0d1..a5fcc3b48 100644--- a/desktop-app/src/chatStore.ts+++ b/desktop-app/src/chatStore.ts@@ -1,7 +1,7 @@import { createHash, randomUUID } from 'node:crypto'import { promises as fs } from 'node:fs'import { join } from 'node:path'-import { mergeAuthoritativeServerMessages } from './chatMessageMerge.js'+import { mergeAuthoritativeServerMessages, messageServerTurnNumber } from './chatMessageMerge.js'import type { ChatFile, ChatIndex, ChatMessage, ChatMetadata } from './types.js'// Keep the catalog at v2 while paged transcripts are dual-readable by the@@ -9,6 +9,7 @@ import type { ChatFile, ChatIndex, ChatMessage, ChatMetadata } from './types.js'const INDEX_VERSION = 2const PAGED_CHAT_VERSION = 1const DEFAULT_PAGE_SIZE = 100+const MAX_COMPATIBILITY_WINDOWS = 100const DEFAULT_MAX_LOCAL_SYNCED_MESSAGES = 1000const LEGACY_COMPATIBILITY_MESSAGE_LIMIT = 100const PAGE_FILE_PATTERN = /^\d{6}\.json$/@@ -33,9 +34,6 @@ interface PagedChatMeta {messageCount: numberlocalMessageCount: numberprunedBeforeCount?: number- prunedThroughServerTurnNumber?: number- oldestLocalServerTurnNumber?: number- latestServerTurnNumber?: numberlegacyCompatibilitySignature?: stringpages: ChatPageEntry[]}@@ -77,10 +75,6 @@ function pageNumberFromFileName(fileName: string): number {return Number(fileName.slice(0, 6))}-function serverTurnNumber(message: ChatMessage): number | undefined {- return Number.isFinite(message.serverTurnNumber) ? message.serverTurnNumber : undefined-}-function isNotFoundError(err: unknown): boolean {return (err as NodeJS.ErrnoException | undefined)?.code === 'ENOENT'}@@ -104,7 +98,7 @@ function aggregateMessages(function pageEntry(file: string, messages: ChatMessage[]): ChatPageEntry {const serverTurns = messages- .map(serverTurnNumber)+ .map(messageServerTurnNumber).filter((turn): turn is number => turn !== undefined)return {file,@@ -123,23 +117,15 @@ function pageEntry(file: string, messages: ChatMessage[]): ChatPageEntry {* so we guard centrally where the on-disk path is built.*/function assertSafeSegment(label: string, value: string): void {- const collidesWithSnapshotNamespace =- label === 'chatId' && /\.(?:next|previous|corrupt)-/.test(value)- if (- !value ||- value === '.' ||- value === '..' ||- /[/\\\0]/.test(value) ||- collidesWithSnapshotNamespace- ) {+ if (!value || value === '.' || value === '..' || /[/\\\0]/.test(value)) {throw new Error(`Invalid ${label}: unsafe path segment`)}}function sameReconciledMessage(local: ChatMessage, server: ChatMessage): boolean {if (local.id === server.id) return true- const localTurn = serverTurnNumber(local)- const serverTurn = serverTurnNumber(server)+ const localTurn = messageServerTurnNumber(local)+ const serverTurn = messageServerTurnNumber(server)if (localTurn !== undefined &&serverTurn !== undefined &&@@ -177,12 +163,12 @@ function mergeReconciledMessages(existing: ChatMessage[], incoming: ChatMessage[continue}- const serverTurn = serverTurnNumber(serverMessage)+ const serverTurn = messageServerTurnNumber(serverMessage)const insertionIndex =serverTurn === undefined? -1: merged.findIndex(message => {- const messageTurn = serverTurnNumber(message)+ const messageTurn = messageServerTurnNumber(message)if (messageTurn === undefined) return falsereturn (messageTurn > serverTurn ||@@ -229,6 +215,16 @@ export class ChatStore {private compatibilityCheckedKeys = new Set<string>()private compatibilityWindows = new Map<string, ChatMessage[]>()+ private cacheCompatibilityWindow(key: string, messages: ChatMessage[]): void {+ this.compatibilityWindows.delete(key)+ this.compatibilityWindows.set(key, [...messages])+ while (this.compatibilityWindows.size > MAX_COMPATIBILITY_WINDOWS) {+ const oldestKey = this.compatibilityWindows.keys().next().value+ if (typeof oldestKey !== 'string') break+ this.compatibilityWindows.delete(oldestKey)+ }+ }+private serialize<T>(chains: Map<string, Promise<unknown>>,key: string,@@ -278,6 +274,12 @@ export class ChatStore {return join(this.agentDir(agentRef), `${chatId}.compat`)}+ private corruptLegacyChatFilePath(agentRef: string, chatId: string): string {+ assertSafeSegment('chatId', chatId)+ const encodedChatId = Buffer.from(chatId, 'utf8').toString('base64url')+ return join(this.agentDir(agentRef), '.corrupt', `${encodedChatId}-${randomUUID()}.json`)+ }+private chatDirPath(agentRef: string, chatId: string): string {assertSafeSegment('chatId', chatId)return join(this.agentDir(agentRef), 'chats', chatId)@@ -290,7 +292,14 @@ export class ChatStore {token: string): string {assertSafeSegment('chatId', chatId)- return join(this.agentDir(agentRef), 'chats', `${chatId}.${kind}-${token}`)+ const encodedChatId = Buffer.from(chatId, 'utf8').toString('base64url')+ return join(this.agentDir(agentRef), 'chats', '.snapshots', encodedChatId, `${kind}-${token}`)+ }++ private chatSnapshotRootPath(agentRef: string, chatId: string): string {+ assertSafeSegment('chatId', chatId)+ const encodedChatId = Buffer.from(chatId, 'utf8').toString('base64url')+ return join(this.agentDir(agentRef), 'chats', '.snapshots', encodedChatId)}private chatPagesDirPath(agentRef: string, chatId: string): string {@@ -328,19 +337,11 @@ export class ChatStore {private finalizePagedMeta(meta: PagedChatMeta): PagedChatMeta {const localMessageCount = meta.pages.reduce((total, page) => total + page.count, 0)- const oldestLocalServerTurnNumber = meta.pages.find(- page => page.firstServerTurnNumber !== undefined- )?.firstServerTurnNumber- const latestServerTurnNumber = [...meta.pages]- .reverse()- .find(page => page.lastServerTurnNumber !== undefined)?.lastServerTurnNumberreturn {...meta,pageSize: this.pageSize,localMessageCount,- oldestLocalServerTurnNumber,- latestServerTurnNumber,}}@@ -402,7 +403,16 @@ export class ChatStore {}return file.messages} catch (err) {- throw new Error(`Unable to read legacy chat file for ${chatId}`, { cause: err })+ // Old flat chat files were written in place, so a crash could leave+ // truncated JSON. Quarantine only malformed content; filesystem errors+ // above still propagate. Returning "no legacy snapshot" lets the server+ // rehydrate the chat and makes subsequent appends writable again.+ await fs.mkdir(join(this.agentDir(agentRef), '.corrupt'), { recursive: true })+ await fs.rename(+ this.chatFilePath(agentRef, chatId),+ this.corruptLegacyChatFilePath(agentRef, chatId)+ )+ return null}}@@ -439,7 +449,7 @@ export class ChatStore {await this.writeJsonAtomic(this.chatCompatibilitySignaturePath(agentRef, chatId), {signature,})- this.compatibilityWindows.set(this.chatSnapshotCleanupKey(agentRef, chatId), [...file.messages])+ this.cacheCompatibilityWindow(this.chatSnapshotCleanupKey(agentRef, chatId), file.messages)return signature}@@ -514,7 +524,7 @@ export class ChatStore {this.compatibilityCheckedKeys.add(compatibilityKey)return refreshed}- this.compatibilityWindows.set(compatibilityKey, [...legacyMessages])+ this.cacheCompatibilityWindow(compatibilityKey, legacyMessages)const legacySignature = this.legacyCompatibilitySnapshot(chatId, legacyMessages).signatureif (legacySignature === meta.legacyCompatibilitySignature) {@@ -662,7 +672,6 @@ export class ChatStore {let localCount = meta.pages.reduce((total, page) => total + page.count, 0)let prunedBeforeCount = meta.prunedBeforeCount ?? 0- let prunedThroughServerTurnNumber = meta.prunedThroughServerTurnNumberconst retained: ChatPageEntry[] = []const removedFiles: string[] = []for (const page of meta.pages) {@@ -673,14 +682,15 @@ export class ChatStore {removedFiles.push(page.file)localCount -= page.countprunedBeforeCount += page.count- prunedThroughServerTurnNumber = Math.max(- prunedThroughServerTurnNumber ?? 0,- page.lastServerTurnNumber ?? 0- )continue}retained.push(page)+ // Pruning must remove only a contiguous prefix. Once a legacy/local-only+ // page is retained, deleting a later synced page would punch a permanent+ // hole in the middle of the transcript and make load-older cursors lie.+ retained.push(...meta.pages.slice(retained.length + removedFiles.length))+ break}return {@@ -688,7 +698,6 @@ export class ChatStore {...meta,pages: retained,prunedBeforeCount: prunedBeforeCount > 0 ? prunedBeforeCount : undefined,- prunedThroughServerTurnNumber,}),removedFiles,}@@ -827,7 +836,7 @@ export class ChatStore {chatId: string): Promise<PagedChatMeta | null> {const activeDir = this.chatDirPath(agentRef, chatId)- const chatsDir = join(this.agentDir(agentRef), 'chats')+ const snapshotRoot = this.chatSnapshotRootPath(agentRef, chatId)const cleanupKey = this.chatSnapshotCleanupKey(agentRef, chatId)let activeMeta: PagedChatMeta | null = nulllet activeReadError: unknown@@ -843,7 +852,7 @@ export class ChatStore {if (this.cleanedSnapshotSiblingKeys.has(cleanupKey)) return activeMetaconst repaired = await this.adoptDurablePageWritesUnlocked(agentRef, chatId, activeMeta)if (repaired) {- await this.removePagedChatSnapshotSiblings(chatsDir, chatId)+ await this.removePagedChatSnapshotSiblings(agentRef, chatId)this.cleanedSnapshotSiblingKeys.add(cleanupKey)return repaired}@@ -860,17 +869,18 @@ export class ChatStore {let entries: Array<{ name: string; isDirectory: () => boolean }>try {- entries = await fs.readdir(chatsDir, { withFileTypes: true })+ entries = await fs.readdir(snapshotRoot, { withFileTypes: true })} catch {- return null+ entries = []}+ if (!activeReadError && entries.length === 0) return nullconst snapshots = await Promise.all(entries.filter(entry => entry.isDirectory()).map(async entry => {- const nextPrefix = `${chatId}.next-`- const previousPrefix = `${chatId}.previous-`+ const nextPrefix = 'next-'+ const previousPrefix = 'previous-'const kind = entry.name.startsWith(nextPrefix)? 'next': entry.name.startsWith(previousPrefix)@@ -882,7 +892,7 @@ export class ChatStore {? entry.name.slice(nextPrefix.length): entry.name.slice(previousPrefix.length)if (!token) return null- const dir = join(chatsDir, entry.name)+ const dir = join(snapshotRoot, entry.name)const meta = await this.readPagedMetaAtPath(this.chatMetaPathFromChatDir(dir),chatId@@ -928,7 +938,7 @@ export class ChatStore {await fs.rm(activeDir, { recursive: true, force: true })}await fs.rename(snapshot.dir, activeDir)- await this.removePagedChatSnapshotSiblings(chatsDir, chatId)+ await this.removePagedChatSnapshotSiblings(agentRef, chatId)if (corruptDir) {await fs.rm(corruptDir, { recursive: true, force: true }).catch(() => undefined)}@@ -950,24 +960,11 @@ export class ChatStore {return null}- private async removePagedChatSnapshotSiblings(chatsDir: string, chatId: string): Promise<void> {- let entries: Array<{ name: string; isDirectory: () => boolean }>- try {- entries = await fs.readdir(chatsDir, { withFileTypes: true })- } catch {- return- }-- await Promise.all(- entries- .filter(- entry =>- entry.isDirectory() &&- (entry.name.startsWith(`${chatId}.next-`) ||- entry.name.startsWith(`${chatId}.previous-`))- )- .map(entry => fs.rm(join(chatsDir, entry.name), { recursive: true, force: true }))- )+ private async removePagedChatSnapshotSiblings(agentRef: string, chatId: string): Promise<void> {+ await fs.rm(this.chatSnapshotRootPath(agentRef, chatId), {+ recursive: true,+ force: true,+ })}private async isCompletePagedSnapshot(@@ -1300,7 +1297,7 @@ export class ChatStore {await fs.rm(this.chatFilePath(agentRef, chatId), { force: true })await fs.rm(this.chatCompatibilitySignaturePath(agentRef, chatId), { force: true })await fs.rm(this.chatDirPath(agentRef, chatId), { recursive: true, force: true })- await this.removePagedChatSnapshotSiblings(join(this.agentDir(agentRef), 'chats'), chatId)+ await this.removePagedChatSnapshotSiblings(agentRef, chatId)const cacheKey = this.chatSnapshotCleanupKey(agentRef, chatId)this.cleanedSnapshotSiblingKeys.delete(cacheKey)this.compatibilityCheckedKeys.delete(cacheKey)@@ -1411,6 +1408,17 @@ export class ChatStore {})}+ async backfillChatCounters(+ agentRef: string,+ chatId: string,+ messages: ChatMessage[]+ ): Promise<void> {+ await this.updateChatIndexFromMessages(agentRef, chatId, messages, {+ preserveExistingTotals: true,+ touchUpdatedAt: false,+ })+ }+async appendMessages(agentRef: string,chatId: string,diff --git a/desktop-app/src/chatStoreBinding.ts b/desktop-app/src/chatStoreBinding.tsindex 6f6f8c356..ad6d9ef5b 100644--- a/desktop-app/src/chatStoreBinding.ts+++ b/desktop-app/src/chatStoreBinding.ts@@ -23,6 +23,7 @@ let activeChatStore: ChatStore | null = nulllet activeUserId: string | null = nulllet activeEnvKey: string | null = nulllet bindInFlight: { key: string; promise: Promise<void> } | null = null+let bindingGeneration = 0/** Marker file (per base dir) that records the pre-`envKey` legacy wipe ran. */const PRE_ENV_MIGRATION_MARKER = '.env-scoped'@@ -58,6 +59,7 @@ export async function bindChatStoreForUser(userId: string, envKey: string): Promif (activeChatStore && activeUserId === userId && activeEnvKey === envKey) returnconst bindKey = `${envKey}::${userId}`if (bindInFlight?.key === bindKey) return bindInFlight.promise+ const generation = ++bindingGenerationconst promise = (async () => {// bind is async (it awaits a directory wipe); until it completes,@@ -71,6 +73,7 @@ export async function bindChatStoreForUser(userId: string, envKey: string): Promawait maybeWipePreEnvLegacyCache(baseDir)const userDir = join(baseDir, envKey, userId)await maybeWipeLegacyCache(userDir)+ if (generation !== bindingGeneration) returnactiveChatStore = new ChatStore(userDir)activeUserId = userIdactiveEnvKey = envKey@@ -217,6 +220,7 @@ async function maybeWipeLegacyCache(userDir: string): Promise<void> {}export function unbindChatStore(): void {+ bindingGeneration += 1activeChatStore = nullactiveUserId = nullactiveEnvKey = nulldiff --git a/desktop-app/src/config.ts b/desktop-app/src/config.tsindex 5efe732ce..7d981aafe 100644--- a/desktop-app/src/config.ts+++ b/desktop-app/src/config.ts@@ -483,7 +483,7 @@ const envRuntimeConfig = validateRuntimeConfig({})const desktopDevPackageRuntimeConfigEnabled =process.argv.includes('--evenfire-desktop-dev-package') &&- isLocalhostRuntimeConfig(envRuntimeConfig)+ runtimeEndpointsMatch(envRuntimeConfig, localhostRuntimeConfig)const canUseEnvRuntimeConfig = !app?.isPackaged || desktopDevPackageRuntimeConfigEnabledconst envRuntimeConfigured = Boolean(canUseEnvRuntimeConfig &&diff --git a/desktop-app/src/ipc.ts b/desktop-app/src/ipc.tsindex 4da7e400f..b96f8eed2 100644--- a/desktop-app/src/ipc.ts+++ b/desktop-app/src/ipc.ts@@ -36,6 +36,43 @@ function sanitizeOptionalInteger(input: unknown): number | undefined {return value}+function sanitizeSessionsListQuery(+ input: import('./types.js').SessionsListQuery | undefined+): import('./types.js').SessionsListQuery {+ const agent = sanitizeString(input?.agent)+ const cursor = sanitizeString(input?.cursor)+ if (agent && (agent.length > 200 || agent.includes(':'))) {+ throw new Error('Invalid session agent')+ }+ if (cursor.length > 4096) throw new Error('Invalid sessions cursor')+ const rawLimit = sanitizeOptionalInteger(input?.limit)+ if (rawLimit !== undefined && rawLimit < 1) throw new Error('Invalid sessions limit')+ return {+ ...(agent ? { agent } : {}),+ ...(rawLimit !== undefined ? { limit: Math.min(rawLimit, 100) } : {}),+ ...(cursor ? { cursor } : {}),+ }+}++function sanitizeSessionMessagesQuery(+ input: import('./types.js').SessionMessagesQuery | undefined+): import('./types.js').SessionMessagesQuery {+ const rawLimit = sanitizeOptionalInteger(input?.limit)+ const beforeTurn = sanitizeOptionalInteger(input?.beforeTurn)+ const afterTurn = sanitizeOptionalInteger(input?.afterTurn)+ if (rawLimit !== undefined && rawLimit < 1) throw new Error('Invalid messages limit')+ if (beforeTurn !== undefined && beforeTurn < 1) throw new Error('Invalid beforeTurn')+ if (afterTurn !== undefined && afterTurn < 0) throw new Error('Invalid afterTurn')+ if (beforeTurn !== undefined && afterTurn !== undefined) {+ throw new Error('beforeTurn and afterTurn are mutually exclusive')+ }+ return {+ ...(rawLimit !== undefined ? { limit: Math.min(rawLimit, 200) } : {}),+ ...(beforeTurn !== undefined ? { beforeTurn } : {}),+ ...(afterTurn !== undefined ? { afterTurn } : {}),+ }+}+function runScopedArtifactDownloadName(runId: string, artifactName: string): string {const rawName = path.basename(artifactName).replace(/[\\/:*?"<>|\u0000-\u001f]/g, '_')const safeName = rawName || 'artifact'@@ -929,7 +966,11 @@ export function registerIpcHandlers(service: AppService): void {assertTrustedSender(event)const hostRef = sanitizeString(payload?.hostRef)if (!hostRef) throw new Error('hostRef is required')- return service.listSessions(hostRef, payload?.hostRefs, payload?.query)+ return service.listSessions(+ hostRef,+ payload?.hostRefs,+ sanitizeSessionsListQuery(payload?.query)+ )})@@ -952,7 +993,13 @@ export function registerIpcHandlers(service: AppService): void {if (!hostRef || !agent || !chatId) {throw new Error('hostRef, agent, and chatId are required')}- return service.loadSessionMessages(hostRef, agent, chatId, payload?.hostRefs, payload?.query)+ return service.loadSessionMessages(+ hostRef,+ agent,+ chatId,+ payload?.hostRefs,+ sanitizeSessionMessagesQuery(payload?.query)+ )})@@ -1094,6 +1141,22 @@ export function registerIpcHandlers(service: AppService): void {})+ ipcMain.handle(+ 'chat:backfillCounters',+ async (event, payload: { agentRef: string; chatId: string; messages: unknown[] }) => {+ assertTrustedSender(event)+ const agentRef = sanitizeString(payload?.agentRef)+ const chatId = sanitizeString(payload?.chatId)+ if (!agentRef || !chatId) throw new Error('agentRef and chatId are required')+ const messages = Array.isArray(payload?.messages) ? payload.messages : []+ await requireChatStore().backfillChatCounters(+ agentRef,+ chatId,+ messages as import('./types.js').ChatMessage[]+ )+ }+ )+ipcMain.handle('chat:markUnreadTerminal',async (event, payload: { agentRef: string; chatId: string }) => {diff --git a/desktop-app/src/preload.ts b/desktop-app/src/preload.tsindex d3e1fa160..7c2729108 100644--- a/desktop-app/src/preload.ts+++ b/desktop-app/src/preload.ts@@ -402,6 +402,8 @@ const clerum = Object.freeze({ipcRenderer.invoke('chat:appendMessages', { agentRef, chatId, messages }),replaceMessages: (agentRef: string, chatId: string, messages: unknown[]) =>ipcRenderer.invoke('chat:replaceMessages', { agentRef, chatId, messages }),+ backfillCounters: (agentRef: string, chatId: string, messages: unknown[]) =>+ ipcRenderer.invoke('chat:backfillCounters', { agentRef, chatId, messages }),markUnreadTerminal: (agentRef: string, chatId: string) =>ipcRenderer.invoke('chat:markUnreadTerminal', { agentRef, chatId }),clearUnreadTerminal: (agentRef: string, chatId: string) =>diff --git a/desktop-app/src/renderer.d.ts b/desktop-app/src/renderer.d.tsindex eca35619d..5df8a83a8 100644--- a/desktop-app/src/renderer.d.ts+++ b/desktop-app/src/renderer.d.ts@@ -494,6 +494,11 @@ declare global {chatId: string,messages: ChatMessage[]) => Promise<void>+ backfillCounters: (+ agentRef: string,+ chatId: string,+ messages: ChatMessage[]+ ) => Promise<void>getLastActive: (agentRef: string) => Promise<string | null>setLastActive: (agentRef: string, chatId: string) => Promise<void>getIndex: (agentRef: string) => Promise<ChatIndex>diff --git a/desktop-app/src/rpcProxyClient.ts b/desktop-app/src/rpcProxyClient.tsindex 69c771483..b1856e217 100644--- a/desktop-app/src/rpcProxyClient.ts+++ b/desktop-app/src/rpcProxyClient.ts@@ -551,6 +551,7 @@ export class RpcProxyClient {query: SessionsListQuery = {}): Promise<SessionsListResult> {const requestUrl = new URL(url(`/api/v1/rpc/hosts/${encodeURIComponent(hostRef)}/sessions`))+ if (query.agent) requestUrl.searchParams.set('agent', query.agent)if (query.limit !== undefined) requestUrl.searchParams.set('limit', String(query.limit))if (query.cursor) requestUrl.searchParams.set('cursor', query.cursor)const response = await fetch(requestUrl, {diff --git a/desktop-app/src/types.ts b/desktop-app/src/types.tsindex 50ab7da89..875c43e3a 100644--- a/desktop-app/src/types.ts+++ b/desktop-app/src/types.ts@@ -878,6 +878,7 @@ export interface SessionMessagesQuery {}export interface SessionsListQuery {+ agent?: stringlimit?: numbercursor?: 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 7243c5373..0860834c6 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@@ -296,12 +296,11 @@ describe('switchToChat (unified, D.4)', () => {undefined,{ limit: 80 })- expect(result.current.chatMessages).toEqual(- expect.arrayContaining([- expect.objectContaining({ id: 'turn-1-user' }),- expect.objectContaining({ id: 'turn-999-assistant' }),- ])- )+ expect(result.current.chatMessages.map(message => message.id)).toEqual([+ 'turn-999-user',+ 'turn-999-assistant',+ ])+ expect(result.current.hasOlderMessages).toBe(true)})it('loads older history on demand and prepends it without blocking first render', async () => {diff --git a/desktop-app/ui/src/hooks/domain/useActivityController.ts b/desktop-app/ui/src/hooks/domain/useActivityController.tsindex a0da03e68..fd65af124 100644--- a/desktop-app/ui/src/hooks/domain/useActivityController.ts+++ b/desktop-app/ui/src/hooks/domain/useActivityController.ts@@ -114,6 +114,12 @@ export function useActivityController({const messages = await chatStore.loadMessages(selectedAgent, chatId, ACTIVITY_SUMMARY_MESSAGE_SCAN_LIMIT).catch(() => [])+ try {+ await chatStore.backfillCounters(selectedAgent, chatId, messages)+ } catch {+ // Older preload bridges cannot persist the backfill; keep the computed+ // renderer value for this session and retry after the app upgrades.+ }return [activityCounterKey(selectedAgent, chatId),{@@ -132,7 +138,14 @@ export function useActivityController({return () => {cancelled = true}- }, [chatStore.loadMessages, isAuthenticated, loadMenuData, missingCounterChatIds, selectedAgent])+ }, [+ chatStore.backfillCounters,+ chatStore.loadMessages,+ isAuthenticated,+ loadMenuData,+ missingCounterChatIds,+ selectedAgent,+ ])// Compute agentLastActiveByAgent for all agentsuseEffect(() => {diff --git a/desktop-app/ui/src/hooks/domain/useAgentChatController.ts b/desktop-app/ui/src/hooks/domain/useAgentChatController.tsindex 1565d88cc..27adbc399 100644--- a/desktop-app/ui/src/hooks/domain/useAgentChatController.ts+++ b/desktop-app/ui/src/hooks/domain/useAgentChatController.ts@@ -105,6 +105,10 @@ const MAX_ACTIVITY_EVENTS_PER_MESSAGE = 100const MAX_MESSAGES_WITH_ACTIVITY_PER_AGENT = 50const MESSAGE_PAGE_SIZE = 80const MAX_RECONCILE_DELTA_PAGES = 5+const REPLACE_LOCAL_RECONCILIATION_WINDOW = Symbol('replace-local-reconciliation-window')+type ReconciliationMessagesResult = SessionMessagesResult & {+ [REPLACE_LOCAL_RECONCILIATION_WINDOW]?: true+}function serverTurnNumber(message: AgentChatMessage): number | undefined {return messageServerTurnNumber(message)@@ -313,6 +317,7 @@ export function useAgentChatController({// activeChatId) are injected through `chatListHostRef`, filled each render once// those parent callbacks are defined (created here so the hook can receive it).const chatListHostRef = useRef<ChatListControllerHost | null>(null)+ const autoSelectedChatIdRef = useRef<string | null>(null)const chatListCtl = useChatListController({selectedAgent,agentNames,@@ -671,6 +676,7 @@ export function useAgentChatController({...activeChatVisibilityRef.current,activeChatId: null,}+ autoSelectedChatIdRef.current = nullsetActiveChatId(null)clearList()// R-F13 renderer half (spec §4.5-3): tear down EVERY tracked task so a late@@ -841,6 +847,10 @@ export function useAgentChatController({dispatchSession,clearComposerDraft,getActiveChatId: () => activeChatId,+ getAutoSelectedChatId: () => autoSelectedChatIdRef.current,+ markAutoSelectedChat: chatId => {+ autoSelectedChatIdRef.current = chatId+ },shouldAutoSelectLatest: () => navItem === DESKTOP_ROUTES.chat,}})@@ -848,6 +858,7 @@ export function useAgentChatController({const handleSelectChat = useCallback(async (chatId: string) => {if (!selectedAgent) return+ autoSelectedChatIdRef.current = nullawait switchToChat(selectedAgent, chatId)},[selectedAgent, switchToChat]@@ -952,6 +963,7 @@ export function useAgentChatController({// Agent selection → load chatsuseEffect(() => {if (!selectedAgent) {+ autoSelectedChatIdRef.current = nullactiveChatVisibilityRef.current = {...activeChatVisibilityRef.current,activeChatId: null,@@ -1045,12 +1057,14 @@ export function useAgentChatController({if (requestedSelection?.mode === 'latest') {const latest = merged[0]if (latest) {+ autoSelectedChatIdRef.current = latest.idawait switchToChat(selectedAgent, latest.id)}setChatMessagesLoading(false)return}if (requestedSelection?.mode === 'specific') {+ autoSelectedChatIdRef.current = nullconst requested = merged.find(chat => chat.id === requestedSelection.chatId)if (requested) {await switchToChat(selectedAgent, requestedSelection.chatId)@@ -1066,6 +1080,7 @@ export function useAgentChatController({if (navItem === DESKTOP_ROUTES.chat) {const latest = merged[0]if (latest) {+ autoSelectedChatIdRef.current = latest.idawait switchToChat(selectedAgent, latest.id)}}@@ -1311,7 +1326,9 @@ export function useAgentChatController({return []})) as AgentChatMessage[]const visible = isActive() ? chatMessagesRef.current : []- const localMessages = mergeUniqueMessages(visible, cached)+ const replaceLocalWindow =+ (resp as ReconciliationMessagesResult)[REPLACE_LOCAL_RECONCILIATION_WINDOW] === true+ const localMessages = replaceLocalWindow ? [] : mergeUniqueMessages(visible, cached)if (!isActive() || tracker.get(chatKey)) {return { rendered: localMessages, replaced: false, cached: localMessages }}@@ -1322,7 +1339,9 @@ export function useAgentChatController({const localHasServerTurns = localMessages.some(message => serverTurnNumber(message) !== undefined)- if (!localHasServerTurns) {+ if (replaceLocalWindow) {+ setHasOlderMessages(Boolean(resp.hasMoreBefore))+ } else if (!localHasServerTurns) {setHasOlderMessages(previous => previous || Boolean(resp.hasMoreBefore))}if (!localHasServerTurns && localMessages.length > 0) {@@ -1546,6 +1565,7 @@ export function useAgentChatController({})tracker.release(chatKey as TaskKey)await chatStore.deleteChat(agentRef, chatId).catch(() => undefined)+ chatStore.clearCachedRemoteData()removeFromList(chatId)const view = activeChatVisibilityRef.currentif (view.selectedAgent === agentRef && view.activeChatId === chatId) {@@ -1554,7 +1574,7 @@ export function useAgentChatController({setChatMessages([])}},- [tracker, chatStore.deleteChat, removeFromList]+ [tracker, chatStore.deleteChat, chatStore.clearCachedRemoteData, removeFromList])useEffect(() => {@@ -1608,9 +1628,13 @@ export function useAgentChatController({pagesLoaded += 1}if (response.hasMoreAfter) {- return chatStore.loadSessionMessages(agentRef, agentRef, chatId, {+ const latest = await chatStore.loadSessionMessages(agentRef, agentRef, chatId, {limit: requestedQuery.limit ?? MESSAGE_PAGE_SIZE,})+ return {+ ...latest,+ [REPLACE_LOCAL_RECONCILIATION_WINDOW]: true,+ } satisfies ReconciliationMessagesResult}return {...response,@@ -2187,6 +2211,7 @@ export function useAgentChatController({try {const chatId = crypto.randomUUID()const meta = await chatStore.createChat(sendAgent, chatId)+ chatStore.clearCachedRemoteData()autoCreatedMeta = metaappendNewEntry(sendAgent, meta)sendChatId = chatId@@ -2323,6 +2348,9 @@ export function useAgentChatController({async: true,})+ // A successful send creates or updates the durable server session. Do not+ // let the short-lived sidebar cache hide that new catalog state.+ chatStore.clearCachedRemoteData()// The runtime accepted the POST (sync reply or async task) — it received// the piggybacked model, so drop the pending entry. A thrown POST skips// this (the catch below leaves it set) so the next attempt retries it.@@ -2636,6 +2664,7 @@ export function useAgentChatController({...activeChatVisibilityRef.current,activeChatId: null,}+ autoSelectedChatIdRef.current = nullsetActiveChatId(null)setChatMessages([])setChatMessagesLoading(false)diff --git a/desktop-app/ui/src/hooks/domain/useChatListController.ts b/desktop-app/ui/src/hooks/domain/useChatListController.tsindex 56e2895b1..c1964d70a 100644--- a/desktop-app/ui/src/hooks/domain/useChatListController.ts+++ b/desktop-app/ui/src/hooks/domain/useChatListController.ts@@ -58,6 +58,8 @@ export interface ChatListControllerHost {dispatchSession: (chatKey: string, event: SessionFsmEvent) => voidclearComposerDraft: (chatId: string) => voidgetActiveChatId: () => string | null+ getAutoSelectedChatId: () => string | null+ markAutoSelectedChat: (chatId: string | null) => voidshouldAutoSelectLatest: () => boolean}@@ -172,7 +174,7 @@ export function useChatListController({const requestGeneration = requestGenerationRef.currentscheduleAfterFirstPaint(async () => {const serverResult = await chatStore- .listSessions(agentRef, { limit: SESSION_CATALOG_PAGE_LIMIT })+ .listSessions(agentRef, { agent: agentRef, limit: SESSION_CATALOG_PAGE_LIMIT }).catch((): SessionsListResult => ({ items: [] }))if (selectedAgentRef.current !== agentRef ||@@ -218,12 +220,16 @@ export function useChatListController({// it here, after the post-paint continuation reaches the auto-select gate,// instead of clearing it with the synchronous local-index selection.const suppressAutoSelection = suppressAutoSelectionByAgentRef.current.delete(agentRef)+ const activeChatId = host.current?.getActiveChatId() ?? null+ const autoSelectedChatId = host.current?.getAutoSelectedChatId() ?? nullif (latestServerSession &&- host.current?.getActiveChatId() === null &&+ (activeChatId === null || activeChatId === autoSelectedChatId) &&+ activeChatId !== latestServerSession.chatId &&host.current.shouldAutoSelectLatest() &&!suppressAutoSelection) {+ host.current.markAutoSelectedChat(latestServerSession.chatId)void host.current.switchToChat(agentRef, latestServerSession.chatId)}@@ -263,7 +269,11 @@ export function useChatListController({setChatListMoreLoading(true)try {const serverResult = await chatStore- .listSessions(agentRef, { limit: SESSION_CATALOG_PAGE_LIMIT, cursor }, { force: true })+ .listSessions(+ agentRef,+ { agent: agentRef, limit: SESSION_CATALOG_PAGE_LIMIT, cursor },+ { force: true }+ ).catch(() => null)if (!serverResult || requestGenerationRef.current !== requestGeneration) return@@ -472,7 +482,9 @@ export function useChatListController({if (!agentRef) returnconst chatId = crypto.randomUUID()const meta = await chatStore.createChat(agentRef, chatId)+ chatStore.clearCachedRemoteData()appendNewEntry(agentRef, meta)+ host.current?.markAutoSelectedChat(null)await host.current?.switchToChat(agentRef, chatId)host.current?.scrollChatToBottom()}, [chatStore, appendNewEntry, host])@@ -522,6 +534,7 @@ export function useChatListController({// FIRST (before the delete), preserving the ack-before-delete ordering.host.current?.dispatchSession(deletedKey, { type: 'CHAT_DELETED' })await chatStore.deleteChat(agentRef, chatId)+ chatStore.clearCachedRemoteData()host.current?.clearComposerDraft(chatId)removeLatestChatSession(agentRef, chatId)// Post-await guards read the LIVE committed values (selectedAgentRef /@@ -599,7 +612,10 @@ export function useChatListController({// cursors here; the selected-agent session list exposes explicit// on-demand pagination through `loadMoreChatSessions`.const serverResult: SessionsListResult = await chatStore- .listSessions(agentRef, { limit: SESSION_CATALOG_PAGE_LIMIT })+ .listSessions(agentRef, {+ agent: agentRef,+ limit: SESSION_CATALOG_PAGE_LIMIT,+ }).catch((): SessionsListResult => ({ items: [] }))return {agentRef,diff --git a/desktop-app/ui/src/hooks/useAppController.ts b/desktop-app/ui/src/hooks/useAppController.tsindex 61bf08640..9b728c210 100644--- a/desktop-app/ui/src/hooks/useAppController.ts+++ b/desktop-app/ui/src/hooks/useAppController.ts@@ -546,6 +546,9 @@ export function useAppController() {const switchedIdentity = `${sessionState.me.id}:${sessionState.me.email}:${sessionState.me.teamId || ''}`activeAuthenticatedSessionIdentityRef.current = switchedIdentityauthenticatedSessionIdentityRef.current = switchedIdentity+ // Team switching owns a complete foreground refresh. If it invalidated+ // the login-time post-paint callback, re-enable deferred menu data here.+ setPostPaintDataReady(true)await refreshAuthenticatedData()if (announce) {const teamName =@@ -566,6 +569,7 @@ export function useAppController() {chat.resetChat,fullSetStatus,refreshAuthenticatedData,+ setPostPaintDataReady,teamsData.teams,])@@ -657,6 +661,10 @@ export function useAppController() {if (loaded && activeAuthenticatedSessionIdentityRef.current === sessionIdentity) {authenticatedSessionIdentityRef.current = sessionIdentity}+ } else {+ // A prior post-paint callback may have been invalidated by an identity+ // transition. An already-initialized matching session is ready now.+ setPostPaintDataReady(true)}if (!preserveNav) {nav.handleNavSelect(DESKTOP_ROUTES.chat)diff --git a/desktop-app/ui/src/hooks/useChatStore.ts b/desktop-app/ui/src/hooks/useChatStore.tsindex 9bf51c680..c85111845 100644--- a/desktop-app/ui/src/hooks/useChatStore.ts+++ b/desktop-app/ui/src/hooks/useChatStore.ts@@ -102,6 +102,15 @@ export function useChatStore() {window.clerum.chat.appendMessages(agentRef, chatId, messages),[])+ const backfillCounters = useCallback(+ (agentRef: string, chatId: string, messages: ChatMessage[]) => {+ const backfill = window.clerum.chat.backfillCounters+ return typeof backfill === 'function'+ ? backfill(agentRef, chatId, messages)+ : Promise.resolve()+ },+ []+ )const replaceMessages = useCallback((agentRef: string, chatId: string, messages: ChatMessage[]) =>window.clerum.chat.replaceMessages(agentRef, chatId, messages),@@ -145,7 +154,13 @@ export function useChatStore() {sessionCatalogRequests.clear()sessionCatalogSource = source}- const key = `${remoteCacheScope}:${hostRef}:${query.limit ?? 'all'}:${query.cursor ?? ''}`+ const key = [+ remoteCacheScope,+ hostRef,+ query.agent ?? '',+ query.limit ?? 'all',+ query.cursor ?? '',+ ].join(':')const cached = sessionCatalogRequests.get(key)if (!options.force && cached && cached.expiresAt > Date.now()) return cached.promise@@ -249,6 +264,7 @@ export function useChatStore() {loadMessages,appendMessages,replaceMessages,+ backfillCounters,markUnreadTerminal,clearUnreadTerminal,getLastActive,diff --git a/desktop-app/ui/src/pages/AuthPage/index.tsx b/desktop-app/ui/src/pages/AuthPage/index.tsxindex bff4bbcd7..f19d69a15 100644--- a/desktop-app/ui/src/pages/AuthPage/index.tsx+++ b/desktop-app/ui/src/pages/AuthPage/index.tsx@@ -28,6 +28,7 @@ export function AuthPage() {handleSaveRuntimeConfig,handleDeleteRuntimeConfig,handleSelectRuntimeConfig,+ handleClearRuntimeConfigSelection,} = useAuthContext()const runtimeConfigOptions = runtimeConfigState?.options || []@@ -95,6 +96,7 @@ export function AuthPage() {const handleRuntimeOptionSelect = (optionId: string) => {setRuntimeMenuOpen(false)if (optionId === activeRuntimeConfigId) {+ handleClearRuntimeConfigSelection()return}handleSelectRuntimeConfig(optionId)diff --git a/desktop-app/ui/src/pages/__tests__/AuthPage.test.tsx b/desktop-app/ui/src/pages/__tests__/AuthPage.test.tsxindex d7ce82b0d..64b603253 100644--- a/desktop-app/ui/src/pages/__tests__/AuthPage.test.tsx+++ b/desktop-app/ui/src/pages/__tests__/AuthPage.test.tsx@@ -158,7 +158,7 @@ describe('AuthPage', () => {expect(handleSelectRuntimeConfig).toHaveBeenCalledWith(LOCALHOST_RUNTIME_CONFIG_OPTION_ID)})- it('does not clear the selected localhost environment when clicked again', async () => {+ it('clears the selected localhost environment when clicked again', async () => {const user = userEvent.setup()const handleSelectRuntimeConfig = vi.fn()const handleClearRuntimeConfigSelection = vi.fn()@@ -191,6 +191,6 @@ describe('AuthPage', () => {await user.click(screen.getByRole('button', { name: 'Localhost' }))expect(handleSelectRuntimeConfig).not.toHaveBeenCalled()- expect(handleClearRuntimeConfigSelection).not.toHaveBeenCalled()+ expect(handleClearRuntimeConfigSelection).toHaveBeenCalledTimes(1)})})diff --git a/desktop-app/ui/src/styles.css b/desktop-app/ui/src/styles.cssindex 89e42d22b..1fd4d9ae5 100644--- a/desktop-app/ui/src/styles.css+++ b/desktop-app/ui/src/styles.css@@ -6071,6 +6071,10 @@ h3 {contain-intrinsic-size: auto 720px;}+.chat-thread-dedicated .virtualized-message-chunk {+ gap: var(--space-2-5);+}+.chat-empty-state {align-content: center;justify-items: center;diff --git a/mcp-host/package-lock.json b/mcp-host/package-lock.jsonindex 65762d649..7032fcdc4 100644--- a/mcp-host/package-lock.json+++ b/mcp-host/package-lock.json@@ -1,12 +1,12 @@{"name": "clerum-mcp-host",- "version": "0.1.216",+ "version": "0.1.217","lockfileVersion": 3,"requires": true,"packages": {"": {"name": "clerum-mcp-host",- "version": "0.1.216",+ "version": "0.1.217","license": "SEE LICENSE IN LICENSE","dependencies": {"@anthropic-ai/sdk": "^0.32.0",diff --git a/mcp-host/package.json b/mcp-host/package.jsonindex 496b24415..ffc6d6388 100644--- a/mcp-host/package.json+++ b/mcp-host/package.json@@ -1,6 +1,6 @@{"name": "clerum-mcp-host",- "version": "0.1.216",+ "version": "0.1.217","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/__tests__/inMemoryConversationStore.test.ts b/mcp-host/src/core/conversation/__tests__/inMemoryConversationStore.test.tsindex 6a38337c8..feb9d2b6e 100644--- a/mcp-host/src/core/conversation/__tests__/inMemoryConversationStore.test.ts+++ b/mcp-host/src/core/conversation/__tests__/inMemoryConversationStore.test.ts@@ -135,6 +135,17 @@ describe('InMemoryConversationStore', () => {})expect(second.map(session => session.chatId)).toEqual(['a1'])})++ it('projects agent and chat ids from an agent-scoped prefix', async () => {+ store.set('u-1:rpc:agent-x:chat-1', makeConversation('u-1'))+ store.set('u-1:rpc:agent-y:chat-2', makeConversation('u-1'))++ const summaries = await store.listSessionSummariesByPrefix('u-1:rpc:agent-x:')++ expect(summaries.map(session => [session.agent, session.chatId])).toEqual([+ ['agent-x', 'chat-1'],+ ])+ })})describe('getSessionMessagesByKey', () => {diff --git a/mcp-host/src/core/conversation/conversationStore.ts b/mcp-host/src/core/conversation/conversationStore.tsindex 7c9eca0f9..980795663 100644--- a/mcp-host/src/core/conversation/conversationStore.ts+++ b/mcp-host/src/core/conversation/conversationStore.ts@@ -107,7 +107,12 @@ function sessionPartsFromKey(): { agent: string; chatId: string } | null {const rest = key.slice(prefix.length)const colonIdx = rest.indexOf(':')- if (colonIdx < 0) return null+ if (colonIdx < 0) {+ const rpcPrefixIndex = prefix.lastIndexOf(':rpc:')+ const scopedAgent =+ rpcPrefixIndex >= 0 ? prefix.slice(rpcPrefixIndex + ':rpc:'.length).replace(/:$/, '') : ''+ return scopedAgent && rest ? { agent: scopedAgent, chatId: rest } : null+ }return {agent: rest.slice(0, colonIdx),chatId: rest.slice(colonIdx + 1),@@ -133,7 +138,7 @@ function afterSessionCursor(return updatedAt < cursorUpdatedAt || (updatedAt === cursorUpdatedAt && summary.key > cursor.key)}-function boundedTurns(turns: Turn[], query: SessionMessagesQuery = {}): Turn[] {+export function boundedTurns(turns: Turn[], query: SessionMessagesQuery = {}): Turn[] {const eligibleTurns =query.afterTurn !== undefined? turns.filter(turn => turn.number > query.afterTurn!)diff --git a/mcp-host/src/core/conversation/persistence/__tests__/sqliteConversationStore.test.ts b/mcp-host/src/core/conversation/persistence/__tests__/sqliteConversationStore.test.tsindex ad11fb835..8a3918bf1 100644--- a/mcp-host/src/core/conversation/persistence/__tests__/sqliteConversationStore.test.ts+++ b/mcp-host/src/core/conversation/persistence/__tests__/sqliteConversationStore.test.ts@@ -241,6 +241,9 @@ describe('SqliteConversationStore — session summary listing', () => {{ key: 'u-1:rpc:agent-x:chat-1', timestamp: 100 },{ key: 'u-1:rpc:agent-x:chat-2', timestamp: 200 },{ key: 'u-1:rpc:agent-y:chat-3', timestamp: 300, awaitingApproval: true },+ // Invalid legacy key: it must be removed before LIMIT so it cannot+ // consume the pagination probe row and end the catalog early.+ { key: 'u-1:rpc:malformed', timestamp: 400 },]for (const session of sessions) {@@ -299,6 +302,14 @@ describe('SqliteConversationStore — session summary listing', () => {})expect(handle.store['cache'].size()).toBe(0)+ const agentPage = await handle.store.listSessionSummariesByPrefix('u-1:rpc:agent-x:', {+ limit: 2,+ })+ expect(agentPage.map(session => [session.agent, session.chatId])).toEqual([+ ['agent-x', 'chat-2'],+ ['agent-x', 'chat-1'],+ ])+const secondPage = await handle.store.listSessionSummariesByPrefix('u-1:rpc:', {limit: 2,cursor: {@@ -624,6 +635,43 @@ describe('SqliteConversationStore — active_task_id (D.1)', () => {}})+ it('reserves a distinct durable turn number before an async cancel write completes', async () => {+ const handle = await freshStore()+ try {+ const manager = new ConversationManager(handle.store)+ const conv = await manager.getOrCreate(SESSION_KEY)++ await manager.startTurn(conv, 'first', 'task-cancelled')+ manager.cancelTurn(conv)+ // Deliberately do not drain or await the fire-and-forget cancel write.+ await manager.startTurn(conv, 'second', 'task-next')+ await manager.completeTurn(conv, 'second response')+ await handle.persistQueue.drainSessionKey(SESSION_KEY)++ 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],+ ['assistant', '[Task cancelled by user before completion]', 1],+ ['user', 'second', 2],+ ['assistant', 'second response', 2],+ ])++ handle.store['cache'].clear()+ const messages = await handle.store.getSessionMessagesByKey(SESSION_KEY, 'u-1:rpc:')+ expect(messages?.turns.map(turn => [turn.number, turn.user_input, turn.response])).toEqual([+ [1, 'first', '[Task cancelled by user before completion]'],+ [2, 'second', 'second response'],+ ])+ } finally {+ await handle.shutdown()+ }+ })+it('persistTurnFail is an awaited durability barrier: the failed-turn state is durable when it resolves', async () => {const handle = await freshStore()try {diff --git a/mcp-host/src/core/conversation/persistence/sqliteConversationStore.ts b/mcp-host/src/core/conversation/persistence/sqliteConversationStore.tsindex 9d8b7c043..a1694ef2c 100644--- a/mcp-host/src/core/conversation/persistence/sqliteConversationStore.ts+++ b/mcp-host/src/core/conversation/persistence/sqliteConversationStore.ts@@ -41,6 +41,7 @@ import {type SessionListQuery,type SessionMessagesQuery,type SessionTokenUsage,+ boundedTurns,} from '../conversationStore'import type { PersistQueue } from './persistQueue'import { CacheOverflowError, PinnedLRUMap } from './pinnedLruMap'@@ -171,12 +172,19 @@ interface SessionOrdinalState {nextTurnNumber: number}-function sessionPartsFromPrefix(key: string, prefix: string): { agent: string; chatId: string } {+function sessionPartsFromPrefix(+ key: string,+ prefix: string+): { agent: string; chatId: string } | null {const rest = key.startsWith(prefix) ? key.slice(prefix.length) : keyconst colonIdx = rest.indexOf(':')- return colonIdx >= 0- ? { agent: rest.slice(0, colonIdx), chatId: rest.slice(colonIdx + 1) }- : { agent: '', chatId: '' }+ if (colonIdx >= 0) {+ return { agent: rest.slice(0, colonIdx), chatId: rest.slice(colonIdx + 1) }+ }+ const rpcPrefixIndex = prefix.lastIndexOf(':rpc:')+ const scopedAgent =+ rpcPrefixIndex >= 0 ? prefix.slice(rpcPrefixIndex + ':rpc:'.length).replace(/:$/, '') : ''+ return scopedAgent && rest ? { agent: scopedAgent, chatId: rest } : null}function conversationStateFromRow(state: string): ConversationState {@@ -376,20 +384,13 @@ export class SqliteConversationStore implements ConversationStore {for (const row of rows) {const key = row.session.session_keyconst cached = this.cache.get(key)- const rest = key.slice(prefix.length)- const colonIdx = rest.indexOf(':')- if (colonIdx < 0) continue- const state = cached- ? cached.state- : row.session.state === ConversationState.Processing- ? ConversationState.Processing- : row.session.state === ConversationState.AwaitingApproval- ? ConversationState.AwaitingApproval- : ConversationState.Idle+ const parts = sessionPartsFromPrefix(key, prefix)+ if (!parts) continue+ const state = cached ? cached.state : conversationStateFromRow(row.session.state)out.push({key,- agent: rest.slice(0, colonIdx),- chatId: rest.slice(colonIdx + 1),+ agent: parts.agent,+ chatId: parts.chatId,state,activeTaskId: cached ? cached.activeTaskId : (row.session.active_task_id ?? undefined),pendingApproval: cached@@ -425,19 +426,9 @@ export class SqliteConversationStore implements ConversationStore {): Promise<ConversationSessionMessages | undefined> {const cached = this.cache.get(sessionKey)const parts = sessionPartsFromPrefix(sessionKey, prefix)+ if (!parts) return undefinedif (cached) {- const eligibleTurns =- query.afterTurn !== undefined- ? cached.turns.filter(turn => turn.number > query.afterTurn!)- : query.beforeTurn !== undefined- ? cached.turns.filter(turn => turn.number < query.beforeTurn!)- : cached.turns- const turns =- query.limit === undefined- ? eligibleTurns- : query.afterTurn !== undefined- ? eligibleTurns.slice(0, query.limit)- : eligibleTurns.slice(-query.limit)+ const turns = boundedTurns(cached.turns, query)return {key: sessionKey,agent: parts.agent,@@ -778,6 +769,11 @@ export class SqliteConversationStore implements ConversationStore {const state = this.ordinals.get(conv.id) ?? this.initOrdinalState(conv.id)const ordinal = state.nextOrdinal++const turnNumber = state.nextTurnNumber+ // cancelTurn() intentionally remains synchronous/fire-and-forget at the+ // ConversationManager boundary. Reserve the next turn number before the+ // first await so an immediate follow-up startTurn cannot reuse this+ // cancelled turn's number while the durable boundary is still queued.+ state.nextTurnNumber += 1// Stamp the partial per-turn total accumulated before cancellation.const turn = conv.turns[conv.turns.length - 1]// ATOMIC boundary (matches persistTurnComplete): the cancel message insert@@ -816,7 +812,6 @@ export class SqliteConversationStore implements ConversationStore {},sessionKey)- state.nextTurnNumber += 1}/**diff --git a/mcp-host/src/db/migrations/001-initial-schema.ts b/mcp-host/src/db/migrations/001-initial-schema.tsindex 8252297f0..27548fb57 100644--- a/mcp-host/src/db/migrations/001-initial-schema.ts+++ b/mcp-host/src/db/migrations/001-initial-schema.ts@@ -66,16 +66,10 @@ export function up(db: Database): void {);CREATE INDEX IF NOT EXISTS idx_messages_sessionON messages(session_id, ordinal);- CREATE INDEX IF NOT EXISTS idx_messages_turn- ON messages(session_id, turn_number);CREATE INDEX IF NOT EXISTS idx_messages_spilloverON messages(spillover_ref) WHERE spillover_ref IS NOT NULL;CREATE INDEX IF NOT EXISTS idx_messages_timestampON messages(timestamp);- CREATE INDEX IF NOT EXISTS idx_messages_session_timestamp- ON messages(session_id, timestamp);- CREATE INDEX IF NOT EXISTS idx_messages_session_turn_ordinal- ON messages(session_id, turn_number, ordinal);CREATE TABLE IF NOT EXISTS pending_approvals (request_id TEXT PRIMARY KEY,diff --git a/mcp-host/src/db/migrations/009-session-summary-indexes.ts b/mcp-host/src/db/migrations/009-session-summary-indexes.tsindex 41d5c5722..b22312be4 100644--- a/mcp-host/src/db/migrations/009-session-summary-indexes.ts+++ b/mcp-host/src/db/migrations/009-session-summary-indexes.ts@@ -15,6 +15,7 @@ export function up(db: Database): void {ON messages(session_id, timestamp);CREATE INDEX IF NOT EXISTS idx_messages_session_turn_ordinalON messages(session_id, turn_number, ordinal);+ DROP INDEX IF EXISTS idx_messages_turn;`)}@@ -22,5 +23,7 @@ export function down(db: Database): void {db.exec(`DROP INDEX IF EXISTS idx_messages_session_timestamp;DROP INDEX IF EXISTS idx_messages_session_turn_ordinal;+ CREATE INDEX IF NOT EXISTS idx_messages_turn+ ON messages(session_id, turn_number);`)}diff --git a/mcp-host/src/db/statements.ts b/mcp-host/src/db/statements.tsindex e4ca52268..52a1d81e3 100644--- a/mcp-host/src/db/statements.ts+++ b/mcp-host/src/db/statements.ts@@ -190,37 +190,50 @@ export function prepareStatements(db: Database): PreparedStatements {SELECT * FROM sessions WHERE session_key LIKE ? ORDER BY started_at DESC`),selectSessionSummariesByPrefix: db.prepare(`- WITH session_summaries AS (+ WITH scoped_sessions AS (+ SELECT *+ FROM sessions+ WHERE session_key >= @prefix_start+ AND session_key < @prefix_end+ AND (+ (@agent_scoped = 1 AND length(session_key) > length(@prefix_start))+ OR+ (+ @agent_scoped = 0+ AND instr(substr(session_key, length(@prefix_start) + 1), ':') > 0+ )+ )+ ),+ message_summaries AS (+ SELECT m.session_id,+ MAX(m.timestamp) AS last_activity_at,+ COUNT(DISTINCT COALESCE(m.turn_number, 0)) AS turn_count+ FROM messages m+ JOIN scoped_sessions s ON s.id = m.session_id+ GROUP BY m.session_id+ ),+ ranked_approvals AS (+ SELECT pa.session_id,+ pa.request_id,+ pa.tool_name,+ ROW_NUMBER() OVER (+ PARTITION BY pa.session_id+ ORDER BY pa.registered_at ASC, pa.request_id ASC+ ) AS approval_rank+ FROM pending_approvals pa+ JOIN scoped_sessions s ON s.id = pa.session_id+ ),+ session_summaries AS (SELECT s.*,- COALESCE(- (SELECT MAX(m.timestamp) FROM messages m WHERE m.session_id = s.id),- s.started_at- ) AS last_activity_at,- COALESCE(- (- SELECT COUNT(DISTINCT COALESCE(m.turn_number, 0))- FROM messages m- WHERE m.session_id = s.id- ),- 0- ) AS turn_count,- (- SELECT pa.request_id- FROM pending_approvals pa- WHERE pa.session_id = s.id- ORDER BY pa.registered_at ASC, pa.request_id ASC- LIMIT 1- ) AS pending_request_id,- (- SELECT pa.tool_name- FROM pending_approvals pa- WHERE pa.session_id = s.id- ORDER BY pa.registered_at ASC, pa.request_id ASC- LIMIT 1- ) AS pending_tool_name- FROM sessions s- WHERE s.session_key >= @prefix_start- AND s.session_key < @prefix_end+ COALESCE(ms.last_activity_at, s.started_at) AS last_activity_at,+ COALESCE(ms.turn_count, 0) AS turn_count,+ pa.request_id AS pending_request_id,+ pa.tool_name AS pending_tool_name+ FROM scoped_sessions s+ LEFT JOIN message_summaries ms ON ms.session_id = s.id+ LEFT JOIN ranked_approvals pa+ ON pa.session_id = s.id+ AND pa.approval_rank = 1)SELECT *FROM session_summaries@@ -235,8 +248,8 @@ export function prepareStatements(db: Database): PreparedStatements {`),selectSessionTurnBounds: db.prepare(`SELECT COUNT(DISTINCT COALESCE(turn_number, 0)) AS total_turns,- MIN(turn_number) AS first_turn_number,- MAX(turn_number) AS last_turn_number,+ MIN(COALESCE(turn_number, 0)) AS first_turn_number,+ MAX(COALESCE(turn_number, 0)) AS last_turn_number,MAX(timestamp) AS last_activity_atFROM messagesWHERE session_id = ?diff --git a/mcp-host/src/db/worker/dispatcher.ts b/mcp-host/src/db/worker/dispatcher.tsindex 42bef40ea..84eba66f3 100644--- a/mcp-host/src/db/worker/dispatcher.ts+++ b/mcp-host/src/db/worker/dispatcher.ts@@ -617,9 +617,14 @@ export async function dispatch(op: WorkerOp, deps: DispatcherDeps): Promise<unkn0,op.sessionKeyPrefix.length - (finalCodePoint > 0xffff ? 2 : 1))}${String.fromCodePoint(finalCodePoint + 1)}`+ const rpcPrefixIndex = op.sessionKeyPrefix.lastIndexOf(':rpc:')+ const agentScoped =+ rpcPrefixIndex >= 0 &&+ op.sessionKeyPrefix.slice(rpcPrefixIndex + ':rpc:'.length).replace(/:$/, '').length > 0const rows = s.selectSessionSummariesByPrefix.all({prefix_start: prefixStart,prefix_end: prefixEnd,+ agent_scoped: agentScoped ? 1 : 0,limit: op.limit ?? -1,cursor_updated_at: op.cursorUpdatedAt ?? null,cursor_key: op.cursorKey ?? null,diff --git a/mcp-host/src/main.ts b/mcp-host/src/main.tsindex ae67f17d0..c3d96661e 100644--- a/mcp-host/src/main.ts+++ b/mcp-host/src/main.ts@@ -2066,25 +2066,26 @@ async function startRPCServer(): Promise<void> {const handleSessionsList = async (userSub: string,- query: { limit?: number; cursor?: string }+ query: { agent?: string; limit?: number; cursor?: string }) => {const convManager = agent!.getConversationManager()- const keyPrefix = `${userSub}:rpc:`+ const keyPrefix = query.agent ? `${userSub}:rpc:${query.agent}:` : `${userSub}:rpc:`const cursor = decodeSessionsCursor(query.cursor)const entries = await convManager.listSessionSummariesForUserAsync(keyPrefix, {limit: query.limit === undefined ? undefined : query.limit + 1,- cursor: cursor ? { updatedAt: new Date(cursor.updatedAt), key: cursor.key } : undefined,+ cursor: cursor+ ? { updatedAt: new Date(cursor.updatedAt), key: `${keyPrefix}${cursor.key}` }+ : undefined,})- const { page, nextCursor } = paginateSessionSummaries(entries, query.limit)+ const { page, nextCursor } = paginateSessionSummaries(entries, query.limit, key =>+ key.slice(keyPrefix.length)+ )return {items: page.map(summary => ({agent: summary.agent,chatId: summary.chatId,turnCount: summary.turnCount,- // A message is one renderable user/assistant part. Derive from logical- // turns so in-memory and SQLite stores report the same unit regardless- // of persisted tool-call rows.- messageCount: summary.turnCount * 2,+ messageCount: summary.messageCount,lastActivityAt: summary.lastActivityAt.toISOString(),...sessionStateView(summary),})),diff --git a/mcp-host/src/server/__tests__/sessionsRoutes.test.ts b/mcp-host/src/server/__tests__/sessionsRoutes.test.tsindex 1694f8c1e..3de829466 100644--- a/mcp-host/src/server/__tests__/sessionsRoutes.test.ts+++ b/mcp-host/src/server/__tests__/sessionsRoutes.test.ts@@ -71,6 +71,7 @@ describe('handleSessionsListRoute', () => {],})expect(sessionsListHandler).toHaveBeenCalledWith('user-1', {+ agent: undefined,limit: undefined,cursor: undefined,})@@ -91,12 +92,31 @@ describe('handleSessionsListRoute', () => {expect(captured.statusCode).toBe(200)expect(sessionsListHandler).toHaveBeenCalledWith('user-1', {+ agent: undefined,limit: 100,cursor: encodeSessionsCursor('2026-04-22T00:00:00.000Z', 'k1'),})expect(captured.jsonBody).toEqual({ items: [], nextCursor: 'next-page' })})+ it('passes a validated agent scope to the catalog handler before pagination', async () => {+ const sessionsListHandler: SessionsListHandler = vi.fn().mockReturnValue({ items: [] })+ const req = {+ ...makeReqWithAuth('user-1'),+ query: { agent: 'chatllm', limit: '25' },+ } as unknown as Request+ const captured = makeRes()++ await handleSessionsListRoute(req, captured.res, makeHandlers({ sessionsListHandler }))++ expect(captured.statusCode).toBe(200)+ expect(sessionsListHandler).toHaveBeenCalledWith('user-1', {+ agent: 'chatllm',+ limit: 25,+ cursor: undefined,+ })+ })+it('rejects malformed session cursors instead of treating them as page one', async () => {const sessionsListHandler: SessionsListHandler = vi.fn()const req = {diff --git a/mcp-host/src/server/routes.ts b/mcp-host/src/server/routes.tsindex 007092631..a7866e582 100644--- a/mcp-host/src/server/routes.ts+++ b/mcp-host/src/server/routes.ts@@ -35,6 +35,7 @@ import type {WorkflowApprovalNotificationTerminalHandler,} from './types'import type { RuntimeCallerContext } from './types'+import { decodeSessionsCursor } from './wireProjections'export type RouteHandlers = {messageHandler: MessageHandler | null@@ -66,17 +67,7 @@ export type RouteHandlers = {function parseSessionsCursorParam(cursor: unknown): string | undefined | null {if (cursor === undefined) return undefinedif (typeof cursor !== 'string' || cursor.length > 2048) return null- try {- const parsed = JSON.parse(Buffer.from(cursor, 'base64url').toString('utf8')) as {- updatedAt?: unknown- key?: unknown- }- if (typeof parsed.updatedAt !== 'string' || typeof parsed.key !== 'string') return null- if (!Number.isFinite(Date.parse(parsed.updatedAt))) return null- return cursor- } catch {- return null- }+ return decodeSessionsCursor(cursor) ? cursor : null}function channelRuntimeSourceMismatch(@@ -1106,6 +1097,11 @@ export async function handleSessionsListRoute(json(res, 501, { error: 'Sessions handler not configured' })return}+ const agent = typeof req.query.agent === 'string' ? req.query.agent.trim() : undefined+ if (agent !== undefined && (!agent || agent.length > 200 || agent.includes(':'))) {+ badRequest(res, 'Invalid session agent')+ return+ }const cursor = parseSessionsCursorParam(req.query.cursor)if (cursor === null) {badRequest(res, 'Invalid sessions cursor')@@ -1121,7 +1117,7 @@ export async function handleSessionsListRoute(}const limit =rawLimit === undefined ? (cursor ? 50 : undefined) : Math.min(Math.floor(rawLimit), 100)- const result = await handlers.sessionsListHandler(caller.userId, { limit, cursor })+ const result = await handlers.sessionsListHandler(caller.userId, { agent, limit, cursor })json(res, 200, result)} catch (error) {console.error('[Server] Error listing sessions:', error)diff --git a/mcp-host/src/server/types.ts b/mcp-host/src/server/types.tsindex f459332cf..fabff0c14 100644--- a/mcp-host/src/server/types.ts+++ b/mcp-host/src/server/types.ts@@ -493,6 +493,7 @@ export type SessionsListItem = {} & SessionStateWireexport type SessionsListQuery = {+ agent?: stringlimit?: numbercursor?: string}diff --git a/mcp-host/src/server/wireProjections.ts b/mcp-host/src/server/wireProjections.tsindex c8a8d9c11..2f4c4528b 100644--- a/mcp-host/src/server/wireProjections.ts+++ b/mcp-host/src/server/wireProjections.ts@@ -46,7 +46,8 @@ export function encodeSessionsCursor(updatedAt: string, key: string): string {export function paginateSessionSummaries<T extends { key: string; lastActivityAt: Date }>(entries: T[],- limit: number | undefined+ limit: number | undefined,+ encodeKey: (key: string) => string = key => key): { page: T[]; nextCursor?: string } {if (limit === undefined) return { page: entries }const page = entries.slice(0, limit)@@ -54,7 +55,9 @@ export function paginateSessionSummaries<T extends { key: string; lastActivityAtreturn {page,...(entries.length > page.length && last- ? { nextCursor: encodeSessionsCursor(last.lastActivityAt.toISOString(), last.key) }+ ? {+ nextCursor: encodeSessionsCursor(last.lastActivityAt.toISOString(), encodeKey(last.key)),+ }: {}),}}diff --git a/rpc-proxy/package-lock.json b/rpc-proxy/package-lock.jsonindex 4cbf75686..7ed94a896 100644--- a/rpc-proxy/package-lock.json+++ b/rpc-proxy/package-lock.json@@ -1,12 +1,12 @@{"name": "clerum-rpc-proxy",- "version": "0.1.54",+ "version": "0.1.55","lockfileVersion": 3,"requires": true,"packages": {"": {"name": "clerum-rpc-proxy",- "version": "0.1.54",+ "version": "0.1.55","dependencies": {"cors": "^2.8.5","express": "^4.21.2",diff --git a/rpc-proxy/package.json b/rpc-proxy/package.jsonindex 7ef7480ff..06e1acb89 100644--- a/rpc-proxy/package.json+++ b/rpc-proxy/package.json@@ -1,6 +1,6 @@{"name": "clerum-rpc-proxy",- "version": "0.1.54",+ "version": "0.1.55","description": "External-facing RPC proxy for tenant-scoped MCP access","main": "dist/main.js","engines": {diff --git a/rpc-proxy/src/__tests__/sessions-passthrough.test.ts b/rpc-proxy/src/__tests__/sessions-passthrough.test.tsindex f1c2c0541..76ed81a53 100644--- a/rpc-proxy/src/__tests__/sessions-passthrough.test.ts+++ b/rpc-proxy/src/__tests__/sessions-passthrough.test.ts@@ -96,6 +96,24 @@ describe('GET /rpc/hosts/:hostRef/sessions — passthrough to mcp-host', () => {expect(String(url)).toBe('http://chatllm:8080/v1/runtime/sessions?limit=25&cursor=current')})+ it('bounds and scopes session pagination before forwarding upstream', async () => {+ const fetchMock = vi.fn().mockResolvedValue(+ new Response(JSON.stringify({ items: [] }), {+ status: 200,+ headers: { 'content-type': 'application/json' },+ })+ )+ globalThis.fetch = fetchMock as unknown as typeof fetch++ await request(makeApp())+ .get('/rpc/hosts/chatllm/sessions?agent=chatllm&limit=500')+ .set('authorization', 'Bearer user-token')+ .expect(200)++ const [url] = fetchMock.mock.calls[0]+ expect(String(url)).toBe('http://chatllm:8080/v1/runtime/sessions?agent=chatllm&limit=100')+ })+it('returns 403 if the user cannot access the host', async () => {serviceMock.resolveHostConnectionForUser.mockResolvedValue(null)await request(makeApp())@@ -169,6 +187,26 @@ describe('GET /rpc/hosts/:hostRef/sessions/:agent/:chatId/messages — passthrou)})+ it('clamps transcript limits before forwarding upstream', async () => {+ const fetchMock = vi.fn().mockResolvedValue(+ new Response(JSON.stringify({ agent: 'chatllm', chatId: 'c1', turns: [] }), {+ status: 200,+ headers: { 'content-type': 'application/json' },+ })+ )+ globalThis.fetch = fetchMock as unknown as typeof fetch++ await request(makeApp())+ .get('/rpc/hosts/chatllm/sessions/chatllm/c1/messages?limit=999')+ .set('authorization', 'Bearer user-token')+ .expect(200)++ const [url] = fetchMock.mock.calls[0]+ expect(String(url)).toBe(+ 'http://chatllm:8080/v1/runtime/sessions/chatllm/c1/messages?limit=200'+ )+ })+it('returns 404 when the upstream returns 404', async () => {const fetchMock = vi.fn().mockResolvedValue({status: 404,diff --git a/rpc-proxy/src/routes/rpc.ts b/rpc-proxy/src/routes/rpc.tsindex 5f73f9836..2c7c65f6d 100644--- a/rpc-proxy/src/routes/rpc.ts+++ b/rpc-proxy/src/routes/rpc.ts@@ -644,11 +644,23 @@ export function createRpcRouter(): Router {const baseUrl = host.url.replace(/\/+$/, '')console.info(`[RPC_PROXY] user=${auth.sub} host=${hostRef} method=list-sessions`)const upstreamUrl = new URL(`${baseUrl}/v1/runtime/sessions`)- for (const key of ['limit', 'cursor'] as const) {- if (typeof req.query[key] === 'string') {- upstreamUrl.searchParams.set(key, req.query[key])- }+ const sessionAgent = typeof req.query.agent === 'string' ? req.query.agent.trim() : ''+ const sessionCursor = typeof req.query.cursor === 'string' ? req.query.cursor : ''+ const sessionLimit =+ typeof req.query.limit === 'string' ? Number(req.query.limit) : undefined+ if (+ (sessionAgent && (sessionAgent.length > 200 || sessionAgent.includes(':'))) ||+ sessionCursor.length > 2048 ||+ (sessionLimit !== undefined && (!Number.isInteger(sessionLimit) || sessionLimit < 1))+ ) {+ res.status(400).json({ error: 'Invalid session pagination query' })+ return+ }+ if (sessionAgent) upstreamUrl.searchParams.set('agent', sessionAgent)+ if (sessionLimit !== undefined) {+ upstreamUrl.searchParams.set('limit', String(Math.min(sessionLimit, 100)))}+ if (sessionCursor) upstreamUrl.searchParams.set('cursor', sessionCursor)// Wake-eligible finite operation (§11.4): the route scope stays// host:session:read; wake capability rides on the token. A suspended// (network-down) or draining Host triggers a wake-and-hold instead of a@@ -722,11 +734,27 @@ export function createRpcRouter(): Router {const upstreamUrl = new URL(`${baseUrl}/v1/runtime/sessions/${encodeURIComponent(agent)}/${encodeURIComponent(chatId)}/messages`)- for (const key of ['limit', 'beforeTurn', 'afterTurn'] as const) {- if (typeof req.query[key] === 'string') {- upstreamUrl.searchParams.set(key, req.query[key])- }+ const rawLimit = typeof req.query.limit === 'string' ? Number(req.query.limit) : undefined+ const beforeTurn =+ typeof req.query.beforeTurn === 'string' ? Number(req.query.beforeTurn) : undefined+ const afterTurn =+ typeof req.query.afterTurn === 'string' ? Number(req.query.afterTurn) : undefined+ if (+ (rawLimit !== undefined && (!Number.isInteger(rawLimit) || rawLimit < 1)) ||+ (beforeTurn !== undefined && (!Number.isInteger(beforeTurn) || beforeTurn < 1)) ||+ (afterTurn !== undefined && (!Number.isInteger(afterTurn) || afterTurn < 0)) ||+ (beforeTurn !== undefined && afterTurn !== undefined)+ ) {+ res.status(400).json({ error: 'Invalid session messages pagination query' })+ return+ }+ if (rawLimit !== undefined) {+ upstreamUrl.searchParams.set('limit', String(Math.min(rawLimit, 200)))+ }+ if (beforeTurn !== undefined) {+ upstreamUrl.searchParams.set('beforeTurn', String(beforeTurn))}+ if (afterTurn !== undefined) upstreamUrl.searchParams.set('afterTurn', String(afterTurn))// Wake-eligible finite operation (§11.4): scope stays host:session:read.const forwardTranscript = async () => {const response = await fetch(upstreamUrl, {