Evenfire is an intelligence layer platform for running LLM agents that take real actions, on your infrastructure
TypeScript
fix: address desktop loading review findings
Josuéd03bdc29f35b
diff --git a/desktop-app/package-lock.json b/desktop-app/package-lock.jsonindex efa56e867..d78d2a0a9 100644--- a/desktop-app/package-lock.json+++ b/desktop-app/package-lock.json@@ -1,12 +1,12 @@{"name": "evenfire",- "version": "0.1.328",+ "version": "0.1.329","lockfileVersion": 3,"requires": true,"packages": {"": {"name": "evenfire",- "version": "0.1.328",+ "version": "0.1.329","license": "MPL-2.0","dependencies": {"@tanstack/react-query": "5.100.10",diff --git a/desktop-app/package.json b/desktop-app/package.jsonindex 66dbf7754..e25374665 100644--- a/desktop-app/package.json+++ b/desktop-app/package.json@@ -1,7 +1,7 @@{"name": "evenfire","productName": "Evenfire",- "version": "0.1.328",+ "version": "0.1.329","private": true,"license": "MPL-2.0","description": "Evenfire desktop client for secure agent and workflow access",diff --git a/desktop-app/src/__tests__/appService.bootstrap.test.ts b/desktop-app/src/__tests__/appService.bootstrap.test.tsindex c2d34c69b..de9181e42 100644--- a/desktop-app/src/__tests__/appService.bootstrap.test.ts+++ b/desktop-app/src/__tests__/appService.bootstrap.test.ts@@ -9,6 +9,7 @@ import path from 'node:path'vi.mock('../chatStoreBinding.js', () => ({bindChatStoreForUser: vi.fn(),unbindChatStore: vi.fn(),+ __setChatStoreBaseDirForTests: vi.fn(),}))describe('AppService invitation configuration lookup', () => {@@ -266,6 +267,79 @@ describe('AppService invitation configuration lookup', () => {}})+ it('shares one saved-session restore across concurrent session-state requests', async () => {+ const configPath = await createTempConfigPath('clerum-desktop-restore-single-flight')+ await fs.writeFile(+ configPath,+ JSON.stringify({+ externalRestApiBaseUrl: 'http://127.0.0.1:8091',+ rpcProxyBaseUrl: 'http://127.0.0.1:8094',+ appName: 'Localhost',+ })+ )+ process.env.CLERUM_DESKTOP_CONFIG_PATH = configPath+ process.env.EXTERNAL_REST_API_BASE_URL = 'http://127.0.0.1:8091'+ process.env.RPC_PROXY_BASE_URL = 'http://127.0.0.1:8094'+ vi.resetModules()+ vi.doMock('electron', () => ({+ app: {+ getPath: vi.fn(() => path.dirname(configPath)),+ isPackaged: false,+ isReady: vi.fn(() => true),+ setName: vi.fn(),+ setPath: vi.fn(),+ },+ }))++ const [{ AppService }, chatStoreBinding] = await Promise.all([+ import('../appService.js'),+ import('../chatStoreBinding.js'),+ ])+ chatStoreBinding.__setChatStoreBaseDirForTests(path.dirname(configPath))+ const me = {+ id: 'user-1',+ email: '[email protected]',+ name: null,+ picture: null,+ teamId: 'team-1',+ teamName: 'Marketing',+ role: 'member',+ }+ let resolveMe!: (value: typeof me) => void+ const pendingMe = new Promise<typeof me>(resolve => {+ resolveMe = resolve+ })+ const getSessionToken = vi.fn().mockResolvedValue('stored-token')+ const getMe = vi.fn().mockReturnValue(pendingMe)+ const service = new AppService() as unknown as {+ authClient: { getMe: ReturnType<typeof vi.fn> }+ tokenStore: {+ getSessionToken: ReturnType<typeof vi.fn>+ clearSessionToken: ReturnType<typeof vi.fn>+ }+ rpcTokenManager: { clear: ReturnType<typeof vi.fn> }+ initialize: () => Promise<unknown>+ getSessionState: () => Promise<unknown>+ }+ service.authClient = { getMe } as never+ service.tokenStore = {+ getSessionToken,+ clearSessionToken: vi.fn(),+ } as never+ service.rpcTokenManager = { clear: vi.fn() } as never++ const first = service.initialize()+ const second = service.getSessionState()+ resolveMe(me)++ await expect(Promise.all([first, second])).resolves.toEqual([+ { authenticated: true, me },+ { authenticated: true, me },+ ])+ expect(getSessionToken).toHaveBeenCalledTimes(1)+ expect(getMe).toHaveBeenCalledTimes(1)+ })+it('clears a saved token when startup session restore is rejected by the API', async () => {const configPath = await createTempConfigPath('clerum-desktop-restore-api')await fs.writeFile(diff --git a/desktop-app/src/__tests__/chatStore.test.ts b/desktop-app/src/__tests__/chatStore.test.tsindex fe8b109cd..eb4f11dc1 100644--- a/desktop-app/src/__tests__/chatStore.test.ts+++ b/desktop-app/src/__tests__/chatStore.test.ts@@ -707,7 +707,116 @@ describe('messages', () => {const meta = await readJsonFile<{ messageCount: number; localMessageCount: number }>(chatMetaPath('bounded-replace'))- expect(meta).toMatchObject({ messageCount: 3, localMessageCount: 1 })+ expect(meta).toMatchObject({ messageCount: 3, localMessageCount: 3 })+ expect(+ (await store.loadMessages('agent-1', 'bounded-replace')).map(message => message.id)+ ).toEqual(['m1', 'm2', 'm3'])+ })++ it('keeps unseen and local-only messages when reconciling a bounded server window', async () => {+ await store.createChat('agent-1', 'reconcile-upsert')+ await store.saveMessages('agent-1', 'reconcile-upsert', [+ {+ id: 'turn-1-user',+ role: 'user',+ content: 'old',+ timestamp: 1,+ serverTurnNumber: 1,+ },+ {+ id: 'local-only',+ role: 'assistant',+ content: 'not on the server',+ timestamp: 2,+ task_id: 'local-task',+ },+ {+ id: 'turn-2-user',+ role: 'user',+ content: 'new',+ timestamp: 3,+ serverTurnNumber: 2,+ },+ ])++ await store.replaceMessages('agent-1', 'reconcile-upsert', [+ {+ id: 'turn-2-user',+ role: 'user',+ content: 'new',+ timestamp: 3,+ serverTurnNumber: 2,+ },+ {+ id: 'turn-2-assistant',+ role: 'assistant',+ content: 'reply',+ timestamp: 4,+ serverTurnNumber: 2,+ },+ ])++ expect(+ (await store.loadMessages('agent-1', 'reconcile-upsert')).map(message => message.id)+ ).toEqual(['turn-1-user', 'local-only', 'turn-2-user', 'turn-2-assistant'])+ })++ it('repairs a missing page from the surviving page files instead of returning an empty chat', async () => {+ const pagedStore = new ChatStore(tempDir, {+ pageSize: 2,+ maxLocalSyncedMessages: Number.POSITIVE_INFINITY,+ })+ await pagedStore.createChat('agent-1', 'missing-page')+ await pagedStore.saveMessages(+ 'agent-1',+ 'missing-page',+ Array.from({ length: 6 }, (_, index) => ({+ id: `m${index}`,+ role: 'user' as const,+ content: `message-${index}`,+ timestamp: index,+ serverTurnNumber: index + 1,+ }))+ )+ await fs.rm(join(chatPagesDir('missing-page'), '000002.json'))++ const recovered = await pagedStore.loadMessages('agent-1', 'missing-page')++ expect(recovered.map(message => message.id)).toEqual(['m0', 'm1', 'm4', 'm5'])+ const repairedMeta = await readJsonFile<{ localMessageCount: number }>(+ chatMetaPath('missing-page')+ )+ expect(repairedMeta.localMessageCount).toBe(4)+ })++ it('adopts a fully written orphan page left by an interrupted append', async () => {+ const pagedStore = new ChatStore(tempDir, {+ pageSize: 2,+ maxLocalSyncedMessages: Number.POSITIVE_INFINITY,+ })+ await pagedStore.createChat('agent-1', 'orphan-append')+ await pagedStore.saveMessages('agent-1', 'orphan-append', [+ { id: 'm0', role: 'user', content: 'zero', timestamp: 0 },+ { id: 'm1', role: 'assistant', content: 'one', timestamp: 1 },+ ])+ await fs.writeFile(+ join(chatPagesDir('orphan-append'), '000002.json'),+ JSON.stringify({+ version: 1,+ chatId: 'orphan-append',+ pageNumber: 2,+ messages: [{ id: 'm2', role: 'user', content: 'durable local', timestamp: 2 }],+ })+ )++ const recovered = await pagedStore.loadMessages('agent-1', 'orphan-append')++ expect(recovered.map(message => message.id)).toEqual(['m0', 'm1', 'm2'])+ const repairedMeta = await readJsonFile<{ localMessageCount: number; pages: unknown[] }>(+ chatMetaPath('orphan-append')+ )+ expect(repairedMeta).toMatchObject({ localMessageCount: 3 })+ expect(repairedMeta.pages).toHaveLength(2)})it('persists task_id and writes the paged chat cache', async () => {@@ -871,7 +980,7 @@ describe('corrupt/missing files', () => {await fs.mkdir(agentDir, { recursive: true })await fs.writeFile(join(agentDir, 'index.json'), 'NOT VALID JSON{{{')const index = await store.getIndex('agent-1')- expect(index.version).toBe(2) // empty index is created at the current schema (D.4)+ expect(index.version).toBe(3) // empty index is created at the current schema (D.4)expect(index.chats).toEqual([])})@@ -946,6 +1055,9 @@ 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/+ )})// 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 ba247ad4e..8d510ae55 100644--- a/desktop-app/src/__tests__/chatStoreBinding.test.ts+++ b/desktop-app/src/__tests__/chatStoreBinding.test.ts@@ -154,7 +154,7 @@ describe('chatStoreBinding', () => {expect(await exists(path.join(tmpBase, ENV_A, 'user-broken', 'agent-y'))).toBe(false)})- it('preserves a v2 agent dir', async () => {+ it('preserves a v2 agent dir and marks it as v3 for downgrade safety', async () => {const v2Index = JSON.stringify({version: 2,chats: [{ id: 'keep', title: 'Keep', createdAt: 'x', updatedAt: 'x', messageCount: 1 }],@@ -171,6 +171,13 @@ describe('chatStoreBinding', () => {expect((await requireChatStore().listChats('agent-x')).find(c => c.id === 'keep')).toBeDefined()+ const migrated = JSON.parse(+ await fs.readFile(+ path.join(tmpBase, ENV_A, 'user-current', 'agent-x', 'index.json'),+ 'utf-8'+ )+ ) as { version: number }+ expect(migrated.version).toBe(3)})it('is a no-op when the user has no cache directory yet', async () => {diff --git a/desktop-app/src/__tests__/config.runtimeConfig.test.ts b/desktop-app/src/__tests__/config.runtimeConfig.test.tsindex 6bb701167..36fd8ac5e 100644--- a/desktop-app/src/__tests__/config.runtimeConfig.test.ts+++ b/desktop-app/src/__tests__/config.runtimeConfig.test.ts@@ -161,6 +161,33 @@ describe('desktop runtime config', () => {})})+ it('does not let the packaged-development escape hatch activate remote endpoints', 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 = 'https://attacker.example.com'+ process.env.RPC_PROXY_BASE_URL = 'https://rpc.attacker.example.com'+ process.env.EVENFIRE_DESKTOP_DEV_PACKAGE = '1'++ 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 b5ec081d8..dd9436764 100644--- a/desktop-app/src/appService.ts+++ b/desktop-app/src/appService.ts@@ -269,6 +269,7 @@ export class AppService {private accessCatalog: AccessCatalog | null = nullprivate teamDirectoryCache: TeamDirectoryResult | null = nullprivate teamContextQueue: Promise<void> = Promise.resolve()+ private restoreSavedSessionInFlight: Promise<SessionState> | null = nullprivate workflowApprovalTeamById = new Map<string, string>()private workflowTeamByKey = new Map<string, string>()private readonly prewarmAttemptAtByHostRef = new Map<string, number>()@@ -532,6 +533,19 @@ export class AppService {}private async restoreSavedSession(options: { runLaunchMaintenance?: boolean } = {}) {+ if (this.restoreSavedSessionInFlight) return this.restoreSavedSessionInFlight+ const restore = this.restoreSavedSessionOnce(options)+ this.restoreSavedSessionInFlight = restore+ try {+ return await restore+ } finally {+ if (this.restoreSavedSessionInFlight === restore) {+ this.restoreSavedSessionInFlight = null+ }+ }+ }++ private async restoreSavedSessionOnce(options: { runLaunchMaintenance?: boolean } = {}) {hydrateDesktopRuntimeConfig()const envKey = getActiveEnvKey()const token = await this.tokenStore.getSessionToken(envKey)@@ -2600,7 +2614,6 @@ export class AppService {totalTurns: 0,hasMoreBefore: false,hasMoreAfter: false,- revision: '0:unavailable',}}throw errordiff --git a/desktop-app/src/chatStore.ts b/desktop-app/src/chatStore.tsindex 90da33b84..a19de9b03 100644--- a/desktop-app/src/chatStore.ts+++ b/desktop-app/src/chatStore.ts@@ -3,7 +3,7 @@ import { promises as fs } from 'node:fs'import { join } from 'node:path'import type { ChatFile, ChatIndex, ChatMessage, ChatMetadata } from './types.js'-const INDEX_VERSION = 2+const INDEX_VERSION = 3const PAGED_CHAT_VERSION = 1const DEFAULT_PAGE_SIZE = 100const DEFAULT_MAX_LOCAL_SYNCED_MESSAGES = 1000@@ -80,6 +80,10 @@ function isNotFoundError(err: unknown): boolean {return (err as NodeJS.ErrnoException | undefined)?.code === 'ENOENT'}+function isRawFilesystemError(err: unknown): boolean {+ return typeof (err as NodeJS.ErrnoException | undefined)?.code === 'string'+}+function isUnsafeSegmentError(err: unknown): boolean {return err instanceof Error && /unsafe path segment/.test(err.message)}@@ -114,11 +118,79 @@ 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 {- if (!value || value === '.' || value === '..' || /[/\\\0]/.test(value)) {+ const collidesWithSnapshotNamespace =+ label === 'chatId' && /\.(?:next|previous|corrupt)-/.test(value)+ if (+ !value ||+ value === '.' ||+ value === '..' ||+ /[/\\\0]/.test(value) ||+ collidesWithSnapshotNamespace+ ) {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)+ if (+ localTurn !== undefined &&+ serverTurn !== undefined &&+ localTurn === serverTurn &&+ local.role === server.role+ ) {+ return true+ }+ if (+ localTurn === undefined &&+ serverTurn !== undefined &&+ local.role === server.role &&+ ((local.task_id && server.task_id && local.task_id === server.task_id) ||+ (local.content.trim() === server.content.trim() &&+ Math.abs(local.timestamp - server.timestamp) <= 60_000))+ ) {+ return true+ }+ return false+}++function reconciledMessageRoleRank(message: ChatMessage): number {+ return message.role === 'user' ? 0 : message.role === 'assistant' ? 1 : 2+}++function mergeReconciledMessages(existing: ChatMessage[], incoming: ChatMessage[]): ChatMessage[] {+ const merged = [...existing]+ for (const serverMessage of incoming) {+ const matchIndex = merged.findIndex(message => sameReconciledMessage(message, serverMessage))+ if (matchIndex >= 0) {+ merged[matchIndex] = {+ ...serverMessage,+ task_id: merged[matchIndex]?.task_id ?? serverMessage.task_id,+ }+ continue+ }++ const serverTurn = serverTurnNumber(serverMessage)+ const insertionIndex =+ serverTurn === undefined+ ? -1+ : merged.findIndex(message => {+ const messageTurn = serverTurnNumber(message)+ if (messageTurn === undefined) return false+ return (+ messageTurn > serverTurn ||+ (messageTurn === serverTurn &&+ reconciledMessageRoleRank(message) > reconciledMessageRoleRank(serverMessage))+ )+ })+ if (insertionIndex < 0) merged.push(serverMessage)+ else merged.splice(insertionIndex, 0, serverMessage)+ }+ return merged+}+function emptyIndex(): ChatIndex {return {version: INDEX_VERSION,@@ -413,19 +485,17 @@ export class ChatStore {}private async pruneSyncedPages(- agentRef: string,- chatId: string,- meta: PagedChatMeta,- options: { pagesDir?: string } = {}- ): Promise<PagedChatMeta> {+ meta: PagedChatMeta+ ): Promise<{ meta: PagedChatMeta; removedFiles: string[] }> {if (this.maxLocalSyncedMessages === Number.POSITIVE_INFINITY) {- return this.finalizePagedMeta(meta)+ return { meta: this.finalizePagedMeta(meta), removedFiles: [] }}let localCount = meta.pages.reduce((total, page) => total + page.count, 0)let prunedBeforeCount = meta.prunedBeforeCount ?? 0let prunedThroughServerTurnNumber = meta.prunedThroughServerTurnNumberconst retained: ChatPageEntry[] = []+ const removedFiles: string[] = []let pruning = truefor (const page of meta.pages) {@@ -433,8 +503,7 @@ export class ChatStore {pruning && page.serverSynced && localCount - page.count >= this.maxLocalSyncedMessagesif (canPrunePage) {- const pagesDir = options.pagesDir ?? this.chatPagesDirPath(agentRef, chatId)- await fs.rm(this.chatPagePathFromPagesDir(pagesDir, page.file), { force: true })+ removedFiles.push(page.file)localCount -= page.countprunedBeforeCount += page.countprunedThroughServerTurnNumber = page.lastServerTurnNumber ?? prunedThroughServerTurnNumber@@ -445,12 +514,128 @@ export class ChatStore {retained.push(page)}- return this.finalizePagedMeta({+ return {+ meta: this.finalizePagedMeta({+ ...meta,+ pages: retained,+ prunedBeforeCount: prunedBeforeCount > 0 ? prunedBeforeCount : undefined,+ prunedThroughServerTurnNumber,+ }),+ removedFiles,+ }+ }++ /**+ * Finish page writes that reached disk before their metadata update.+ *+ * Existing pages may contain a durable append beyond the count recorded in+ * meta.json, and newly-created pages may exist after the last referenced page.+ * Both are safe to adopt because page files are themselves written atomically.+ */+ private async adoptDurablePageWritesUnlocked(+ agentRef: string,+ chatId: string,+ meta: PagedChatMeta+ ): Promise<PagedChatMeta | null> {+ const pagesDir = this.chatPagesDirPath(agentRef, chatId)+ const repairedPages: ChatPageEntry[] = []+ let changed = false++ for (const [index, page] of meta.pages.entries()) {+ let messages: ChatMessage[]+ try {+ messages = await this.readPageMessages(agentRef, chatId, page)+ } catch (error) {+ if (isRawFilesystemError(error) && !isNotFoundError(error)) throw error+ return null+ }+ if (messages.length < page.count) return null+ if (messages.length > page.count && index !== meta.pages.length - 1) return null+ const repaired = pageEntry(page.file, messages)+ repairedPages.push(repaired)+ changed ||= repaired.count !== page.count+ }++ const referenced = new Set(repairedPages.map(page => page.file))+ const lastReferencedNumber = pageNumberFromFileName(repairedPages.at(-1)?.file ?? '')+ const entries = await fs.readdir(pagesDir).catch(() => [])+ const durableOrphans = entries+ .filter(+ file =>+ PAGE_FILE_PATTERN.test(file) &&+ !referenced.has(file) &&+ pageNumberFromFileName(file) > lastReferencedNumber+ )+ .sort((a, b) => pageNumberFromFileName(a) - pageNumberFromFileName(b))++ for (const file of durableOrphans) {+ try {+ const messages = await this.readPageMessagesAtPath(+ chatId,+ pageNumberFromFileName(file),+ this.chatPagePathFromPagesDir(pagesDir, file)+ )+ if (!messages.length) continue+ repairedPages.push(pageEntry(file, messages))+ referenced.add(file)+ changed = true+ } catch (error) {+ if (isRawFilesystemError(error) && !isNotFoundError(error)) throw error+ // Leave an invalid orphan untouched. It is not referenced by metadata,+ // so it cannot break reads and may still be useful for manual recovery.+ }+ }++ if (!changed) return meta+ const previousLocalCount = meta.pages.reduce((total, page) => total + page.count, 0)+ const nextLocalCount = repairedPages.reduce((total, page) => total + page.count, 0)+ const repaired = this.finalizePagedMeta({...meta,- pages: retained,- prunedBeforeCount: prunedBeforeCount > 0 ? prunedBeforeCount : undefined,- prunedThroughServerTurnNumber,+ messageCount: Math.max(+ meta.messageCount + Math.max(0, nextLocalCount - previousLocalCount),+ nextLocalCount + (meta.prunedBeforeCount ?? 0)+ ),+ pages: repairedPages,+ })+ await this.writePagedMeta(agentRef, chatId, repaired)+ return repaired+ }++ private async rebuildPagedChatFromSurvivingFilesUnlocked(+ agentRef: string,+ chatId: string+ ): Promise<boolean> {+ const pagesDir = this.chatPagesDirPath(agentRef, chatId)+ const entries = await fs.readdir(pagesDir).catch(() => [])+ const surviving: ChatMessage[] = []+ for (const file of entries+ .filter(candidate => PAGE_FILE_PATTERN.test(candidate))+ .sort((a, b) => pageNumberFromFileName(a) - pageNumberFromFileName(b))) {+ try {+ surviving.push(+ ...(await this.readPageMessagesAtPath(+ chatId,+ pageNumberFromFileName(file),+ this.chatPagePathFromPagesDir(pagesDir, file)+ ))+ )+ } catch (error) {+ if (isRawFilesystemError(error) && !isNotFoundError(error)) throw error+ // Skip only the unreadable page; readable siblings are still valuable.+ }+ }++ const legacy = await this.readLegacyMessages(agentRef, chatId).catch(error => {+ if (isRawFilesystemError(error) && !isNotFoundError(error)) throw error+ return null+ })+ const recovered = mergeReconciledMessages(surviving, legacy ?? [])+ if (!recovered.length) return false+ await this.writePagedChatUnlocked(agentRef, chatId, recovered, {+ removeLegacy: true,+ messageCount: recovered.length,})+ return true}private async recoverPagedChatUnlocked(agentRef: string, chatId: string): Promise<void> {@@ -463,14 +648,20 @@ export class ChatStore {try {activeMeta = await this.readPagedMeta(agentRef, chatId)} catch (err) {+ if (isRawFilesystemError(err) && !isNotFoundError(err)) throw erractiveReadError = err}if (activeMeta) {- if (this.cleanedSnapshotSiblingKeys.has(cleanupKey)) return- await this.removePagedChatSnapshotSiblings(chatsDir, chatId)- this.cleanedSnapshotSiblingKeys.add(cleanupKey)- return+ const repaired = await this.adoptDurablePageWritesUnlocked(agentRef, chatId, activeMeta)+ if (repaired) {+ if (this.cleanedSnapshotSiblingKeys.has(cleanupKey)) return+ await this.removePagedChatSnapshotSiblings(chatsDir, chatId)+ this.cleanedSnapshotSiblingKeys.add(cleanupKey)+ return+ }+ activeReadError = new Error(`Paged chat snapshot is incomplete for ${chatId}`)+ activeMeta = null}if (!activeReadError) {@@ -564,6 +755,7 @@ export class ChatStore {}}+ if (await this.rebuildPagedChatFromSurvivingFilesUnlocked(agentRef, chatId)) returnif (activeReadError) throw activeReadError}@@ -643,9 +835,7 @@ export class ChatStore {)}- const meta = await this.pruneSyncedPages(- agentRef,- chatId,+ const pruned = await this.pruneSyncedPages(this.finalizePagedMeta({version: PAGED_CHAT_VERSION,chatId,@@ -653,10 +843,14 @@ export class ChatStore {messageCount: Math.max(messages.length, options.messageCount ?? 0),localMessageCount: messages.length,pages,- }),- { pagesDir }+ })+ )+ await this.writePagedMetaToDir(chatId, stagingDir, pruned.meta)+ await Promise.all(+ pruned.removedFiles.map(file =>+ fs.rm(this.chatPagePathFromPagesDir(pagesDir, file), { force: true })+ ))- await this.writePagedMetaToDir(chatId, stagingDir, meta)try {await fs.rename(chatDir, backupDir)@@ -674,7 +868,7 @@ export class ChatStore {await fs.rm(this.chatFilePath(agentRef, chatId), { force: true })}- return meta+ return pruned.meta} catch (err) {await fs.rm(stagingDir, { recursive: true, force: true }).catch(() => undefined)if (movedExistingSnapshot) {@@ -776,23 +970,28 @@ export class ChatStore {const messageCount =Math.max(meta.messageCount, meta.localMessageCount ?? 0) + newMessages.length- const pruned = await this.pruneSyncedPages(agentRef, chatId, {+ const pruned = await this.pruneSyncedPages({...meta,messageCount,pages,})- await this.writePagedMeta(agentRef, chatId, pruned)+ await this.writePagedMeta(agentRef, chatId, pruned.meta)+ await Promise.all(+ pruned.removedFiles.map(file =>+ fs.rm(this.chatPagePath(agentRef, chatId, file), { force: true })+ )+ )await fs.rm(this.chatFilePath(agentRef, chatId), { force: true })- return pruned+ return pruned.meta}async getIndex(agentRef: string): Promise<ChatIndex> {try {const raw = await fs.readFile(this.indexPath(agentRef), 'utf-8')const parsed = JSON.parse(raw) as ChatIndex- // Version-agnostic read: legacy (v1) dirs are removed at bind time by the- // bootstrap wipe (chatStoreBinding), so any index we read here is current;- // saveIndex normalizes the stored version to v2 on the next write.+ // Version-agnostic read: legacy directories are handled at bind time by+ // chatStoreBinding, so any index we read here is safe to normalize;+ // saveIndex writes the current v3 marker on the next update.if (parsed && Array.isArray(parsed.chats)) {return parsed}@@ -809,7 +1008,7 @@ export class ChatStore {const normalized: ChatIndex = { ...index, version: INDEX_VERSION }// Atomic write (temp + rename): a crash mid-write must never leave a// truncated index.json, because the bootstrap wipe treats an unparseable- // index as legacy and would delete live v2 chats.+ // index as legacy and would delete live v3 chats.const target = this.indexPath(agentRef)const tmp = `${target}.tmp`await fs.writeFile(tmp, JSON.stringify(normalized, null, 2), { mode: 0o600 })@@ -903,7 +1102,7 @@ export class ChatStore {return this.readMessagesFromPagedMeta(agentRef, chatId, meta, limit, offset)})} catch (err) {- if (isUnsafeSegmentError(err) || isNotFoundError(err)) return []+ if (isUnsafeSegmentError(err)) return []throw err}}@@ -968,15 +1167,29 @@ export class ChatStore {}/**- * Overwrite a chat's cached history with a server reconciliation window.+ * Upsert a server reconciliation window without truncating unseen history.*- * The message array may be bounded to the most recent page, so preserve- * persisted aggregate counters when the window is smaller than the full- * conversation. The server remains the source of truth for message contents;- * the index counters remain cumulative sidebar/activity metadata.+ * Reconciliation is intentionally bounded, while the local store may contain+ * older pages or optimistic messages that are not present in that window.+ * Merge the window into the complete local snapshot before publishing a new+ * generation so a background reconcile cannot discard either category.*/async replaceMessages(agentRef: string, chatId: string, messages: ChatMessage[]): Promise<void> {- await this.saveMessagesInternal(agentRef, chatId, messages, { preserveExistingTotals: true })+ await this.serializeChat(agentRef, chatId, async () => {+ const existingMeta = await this.readOrMigratePagedChatUnlocked(agentRef, chatId)+ const existingMessages = existingMeta+ ? await this.readMessagesFromPagedMeta(agentRef, chatId, existingMeta)+ : []+ const merged = mergeReconciledMessages(existingMessages, messages)+ const indexedCount = await this.indexedMessageCount(agentRef, chatId)+ await this.writePagedChatUnlocked(agentRef, chatId, merged, {+ removeLegacy: true,+ messageCount: Math.max(merged.length, indexedCount ?? 0),+ })+ await this.updateChatIndexFromMessages(agentRef, chatId, merged, {+ preserveExistingTotals: true,+ })+ })}async appendMessages(diff --git a/desktop-app/src/chatStoreBinding.ts b/desktop-app/src/chatStoreBinding.tsindex 15a96f197..9e0e80a7d 100644--- a/desktop-app/src/chatStoreBinding.ts+++ b/desktop-app/src/chatStoreBinding.ts@@ -4,7 +4,8 @@ import { join } from 'node:path'import { ChatStore } from './chatStore.js'/** Current persisted chat schema. Anything older is wiped on bind (§7.1). */-const SCHEMA_VERSION = 2+const SCHEMA_VERSION = 3+const PAGED_V2_SCHEMA_VERSION = 2// Default base dir derived from Electron's userData path. Tests override via// __setChatStoreBaseDirForTests to point at a tmpdir, which means the@@ -177,7 +178,18 @@ async function maybeWipeLegacyCache(userDir: string): Promise<void> {try {const raw = await fs.readFile(indexPath, 'utf-8')const parsed = JSON.parse(raw) as { version?: number }- isLegacy = parsed.version !== SCHEMA_VERSION+ if (parsed.version === PAGED_V2_SCHEMA_VERSION) {+ const migratedIndexPath = `${indexPath}.v3.tmp`+ await fs.writeFile(+ migratedIndexPath,+ JSON.stringify({ ...parsed, version: SCHEMA_VERSION }, null, 2),+ { mode: 0o600 }+ )+ await fs.rename(migratedIndexPath, indexPath)+ isLegacy = false+ } else {+ isLegacy = parsed.version !== SCHEMA_VERSION+ }} catch {// index.json missing or unparseable → treat as legacyisLegacy = truediff --git a/desktop-app/src/config.ts b/desktop-app/src/config.tsindex cebc1bee2..682beb6c2 100644--- a/desktop-app/src/config.ts+++ b/desktop-app/src/config.ts@@ -482,7 +482,8 @@ const envRuntimeConfig = validateRuntimeConfig({appName: requiredOrDefault('DESKTOP_APP_NAME', DEFAULT_APP_NAME),})const desktopDevPackageRuntimeConfigEnabled =- process.env.EVENFIRE_DESKTOP_DEV_PACKAGE?.trim() === '1'+ process.env.EVENFIRE_DESKTOP_DEV_PACKAGE?.trim() === '1' &&+ isLocalhostRuntimeConfig(envRuntimeConfig)const canUseEnvRuntimeConfig = !app?.isPackaged || desktopDevPackageRuntimeConfigEnabledconst envRuntimeConfigured = Boolean(canUseEnvRuntimeConfig &&diff --git a/desktop-app/src/renderer.d.ts b/desktop-app/src/renderer.d.tsindex d29543269..eca35619d 100644--- a/desktop-app/src/renderer.d.ts+++ b/desktop-app/src/renderer.d.ts@@ -18,9 +18,7 @@ import {HostModelsResult,HostRuntimeStatus,HostStatusStreamEvent,- MessageToolStep,PasswordLoginResult,- PendingApprovalLite,PendingWorkflowApproval,PrewarmHostResult,ProfileSettingsOpenOptions,diff --git a/desktop-app/src/types.ts b/desktop-app/src/types.tsindex 24e064b87..4e37b6a75 100644--- a/desktop-app/src/types.ts+++ b/desktop-app/src/types.ts@@ -807,8 +807,8 @@ export interface ChatMetadata {}export interface ChatIndex {- /** v2 aligns with ChatFile v2; bootstrap wipes any v1/missing-version dir (D.4 §7.1). */- version: 1 | 2+ /** v3 marks paged chat caches so older builds wipe rather than mix storage formats. */+ version: 1 | 2 | 3lastActiveChatId: string | nullonboardingDismissed: booleanchats: ChatMetadata[]@@ -856,7 +856,6 @@ export interface SessionMessagesResult {latestTurnNumber?: numberhasMoreBefore?: booleanhasMoreAfter?: boolean- revision?: stringstate?: SessionLifecycleStateactiveTaskId?: stringpendingApproval?: PendingApprovalLite@@ -888,6 +887,7 @@ export interface SessionsListResult {agent: stringchatId: stringturnCount: number+ messageCount?: numberlastActivityAt: stringstate?: SessionLifecycleStateactiveTaskId?: stringdiff --git a/desktop-app/ui/src/components/agents/ChatThread.tsx b/desktop-app/ui/src/components/agents/ChatThread.tsxindex ce34cfd36..1d861bf7a 100644--- a/desktop-app/ui/src/components/agents/ChatThread.tsx+++ b/desktop-app/ui/src/components/agents/ChatThread.tsx@@ -1,7 +1,6 @@import {Fragment,type ReactElement,- type ReactNode,useCallback,useEffect,useMemo,@@ -89,68 +88,6 @@ export function buildMessageGroupChunks<T extends ChunkableMessageGroup>(return chunks}-function VirtualizedMessageChunk({- estimatedHeight,- initiallyVisible,- render,-}: {- estimatedHeight: number- initiallyVisible: boolean- render: () => ReactNode-}) {- const containerRef = useRef<HTMLDivElement | null>(null)- const [visible, setVisible] = useState(initiallyVisible)- const measuredHeightRef = useRef(estimatedHeight)-- useEffect(() => {- const element = containerRef.current- if (!element || typeof IntersectionObserver === 'undefined') {- setVisible(true)- return- }- const observer = new IntersectionObserver(- entries => {- const entry = entries[0]- if (!entry) return- if (entry.isIntersecting) {- setVisible(true)- } else if (measuredHeightRef.current > 0) {- setVisible(false)- }- },- {- root: element.closest('.chat-thread'),- rootMargin: '1000px 0px',- }- )- observer.observe(element)- return () => observer.disconnect()- }, [])-- useEffect(() => {- const element = containerRef.current- if (!element || !visible || typeof ResizeObserver === 'undefined') return- const updateHeight = () => {- const height = element.getBoundingClientRect().height- if (height > 0) measuredHeightRef.current = height- }- updateHeight()- const observer = new ResizeObserver(updateHeight)- observer.observe(element)- return () => observer.disconnect()- }, [visible])-- return (- <div- ref={containerRef}- className="virtualized-message-chunk"- style={visible ? undefined : { height: measuredHeightRef.current }}- >- {visible ? render() : null}- </div>- )-}-type WorkflowArtifactScope = {namespace: stringname: string@@ -589,203 +526,191 @@ export function ChatThread({ showAgentLabel = false }: ChatThreadProps) {</div>)}{activeChatId &&- messageGroupChunks.map((chunk, chunkIndex) => (- <VirtualizedMessageChunk- key={chunk.chunkKey}- estimatedHeight={Math.max(240, chunk.groups.length * 180)}- initiallyVisible={chunkIndex >= messageGroupChunks.length - 2}- render={() =>- chunk.groups.map(({ group, groupIndex }) => {- const prevGroup = groupIndex > 0 ? groupedWithKeys[groupIndex - 1] : null-- return (- <Fragment key={group.groupKey}>- <section className={`chat-group ${group.role}`}>- {group.items.map((message, messageIndex) => {- const parsedUserMessage =- message.role === 'user' ? parseChatMessageDisplay(message.content) : null- const displayContent = parsedUserMessage?.content ?? message.content- const displayAttachments =- message.role === 'user'- ? message.attachments && message.attachments.length- ? message.attachments- : (parsedUserMessage?.attachments ?? [])- : message.attachments && message.attachments.length- ? message.attachments- : []- const hasResponseFileAttachment = displayAttachments.some(- attachment => attachment.type === 'response_file'- )- const isJson = looksLikeJson(displayContent)- const htmlPreview =- message.role === 'assistant'- ? extractHtmlVisualization(displayContent)- : null- const hasHtmlArtifactMention =- message.role === 'assistant' &&- /\b[a-zA-Z0-9][a-zA-Z0-9._-]*\.html?\b/i.test(displayContent)- const showMetaRow = message.role === 'assistant' || message.role === 'user'- const copyContent =- message.role === 'user' ? displayContent : message.content- const metaRowRoleClass =- message.role === 'user'- ? 'chat-message-meta-row--user'- : message.role === 'assistant'- ? 'chat-message-meta-row--assistant'- : ''- const isLastAssistantMessage =- group.role === 'assistant' && messageIndex === group.items.length - 1- const workflowArtifactScopeForAssistant =- message.role === 'assistant' && prevGroup?.role === 'user'- ? (prevGroup.items- .map(prevMessage =>- extractWorkflowArtifactScopeFromProgress(- progressByMessageId[prevMessage.id]- )+ messageGroupChunks.map(chunk => (+ <div key={chunk.chunkKey} className="virtualized-message-chunk">+ {chunk.groups.map(({ group, groupIndex }) => {+ const prevGroup = groupIndex > 0 ? groupedWithKeys[groupIndex - 1] : null++ return (+ <Fragment key={group.groupKey}>+ <section className={`chat-group ${group.role}`}>+ {group.items.map((message, messageIndex) => {+ const parsedUserMessage =+ message.role === 'user' ? parseChatMessageDisplay(message.content) : null+ const displayContent = parsedUserMessage?.content ?? message.content+ const displayAttachments =+ message.role === 'user'+ ? message.attachments && message.attachments.length+ ? message.attachments+ : (parsedUserMessage?.attachments ?? [])+ : message.attachments && message.attachments.length+ ? message.attachments+ : []+ const hasResponseFileAttachment = displayAttachments.some(+ attachment => attachment.type === 'response_file'+ )+ const isJson = looksLikeJson(displayContent)+ const htmlPreview =+ message.role === 'assistant'+ ? extractHtmlVisualization(displayContent)+ : null+ const hasHtmlArtifactMention =+ message.role === 'assistant' &&+ /\b[a-zA-Z0-9][a-zA-Z0-9._-]*\.html?\b/i.test(displayContent)+ const showMetaRow = message.role === 'assistant' || message.role === 'user'+ const copyContent = message.role === 'user' ? displayContent : message.content+ const metaRowRoleClass =+ message.role === 'user'+ ? 'chat-message-meta-row--user'+ : message.role === 'assistant'+ ? 'chat-message-meta-row--assistant'+ : ''+ const isLastAssistantMessage =+ group.role === 'assistant' && messageIndex === group.items.length - 1+ const workflowArtifactScopeForAssistant =+ message.role === 'assistant' && prevGroup?.role === 'user'+ ? (prevGroup.items+ .map(prevMessage =>+ extractWorkflowArtifactScopeFromProgress(+ progressByMessageId[prevMessage.id])- .find((scope): scope is WorkflowArtifactScope => scope !== null) ??- null)- : null- return (- <article- key={message.messageKey}- data-testid={- message.role === 'assistant' ? 'agent-response' : undefined- }- className={`chat-bubble ${message.role}${message.isError ? ' chat-bubble--error' : ''}${- htmlPreview || hasHtmlArtifactMention ? ' chat-bubble--wide' : ''- }`}- >- {message.isError ? (- <div className="error-bubble-content">- <div className="error-bubble-icon">✕</div>- <div className="error-bubble-body">- <div className="error-bubble-label">- {AGENT_ERROR_CODE_LABELS[message.errorCode ?? ''] ?? 'Error'}- {message.errorProvider- ? ` · ${message.errorProvider.toUpperCase()}`- : ''}- </div>- <div className="error-bubble-message">- {message.content.length > 180- ? `${message.content.slice(0, 177)}...`- : message.content}- </div>- <details className="error-bubble-details">- <summary>Details</summary>- <pre className="error-bubble-details-text">- {message.content}- </pre>- </details>+ )+ .find((scope): scope is WorkflowArtifactScope => scope !== null) ??+ null)+ : null+ return (+ <article+ key={message.messageKey}+ data-testid={message.role === 'assistant' ? 'agent-response' : undefined}+ className={`chat-bubble ${message.role}${message.isError ? ' chat-bubble--error' : ''}${+ htmlPreview || hasHtmlArtifactMention ? ' chat-bubble--wide' : ''+ }`}+ >+ {message.isError ? (+ <div className="error-bubble-content">+ <div className="error-bubble-icon">✕</div>+ <div className="error-bubble-body">+ <div className="error-bubble-label">+ {AGENT_ERROR_CODE_LABELS[message.errorCode ?? ''] ?? 'Error'}+ {message.errorProvider+ ? ` · ${message.errorProvider.toUpperCase()}`+ : ''}+ </div>+ <div className="error-bubble-message">+ {message.content.length > 180+ ? `${message.content.slice(0, 177)}...`+ : message.content}</div>+ <details className="error-bubble-details">+ <summary>Details</summary>+ <pre className="error-bubble-details-text">{message.content}</pre>+ </details></div>- ) : (- <>- {htmlPreview && (- <SecureHtmlPreview- html={htmlPreview}- previewId={message.messageKey}- title="HTML visualization"- maxBytes={HTML_PREVIEW_INLINE_MAX_BYTES}- />- )}- {isJson ? (- <pre className="message-block json-content">{displayContent}</pre>- ) : message.role === 'assistant' ? (- <div className="message-block markdown-content">- <ReactMarkdown remarkPlugins={[remarkGfm]}>- {displayContent}- </ReactMarkdown>- {selectedAgent && !hasResponseFileAttachment && (- <MessageArtifactActions- hostRef={selectedAgent}- content={displayContent}- />- )}- {workflowArtifactScopeForAssistant ? (- <WorkflowRunArtifactActions- workflow={workflowArtifactScopeForAssistant}- />- ) : null}- </div>- ) : displayContent ? (- <p className="message-block">{displayContent}</p>- ) : null}- <MessageAttachmentList attachments={displayAttachments} />- </>- )}- {isLastAssistantMessage &&- prevGroup?.role === 'user' &&- (() => {- // Prefer the live progress (keyed by the user message);- // fall back to the assistant's persisted toolSteps after- // a reload, when the live map is empty (#582).- const liveNodes = prevGroup.items- .map(msg => renderProgressStepper(msg, 'completed'))- .filter((node): node is ReactElement => node != null)- if (liveNodes.length > 0) return liveNodes- return renderHydratedToolSteps(message)- })()}- {showMetaRow && (- <footer- className={`chat-message-meta-row ${metaRowRoleClass}`.trim()}- >- <div className="chat-message-meta-main">- <span className="chat-time-label">- {formatChatTimestamp(message.timestamp || Date.now())}- </span>- {message.role === 'assistant' && message.tokens && (- <MessageTokens tokens={message.tokens} />+ </div>+ ) : (+ <>+ {htmlPreview && (+ <SecureHtmlPreview+ html={htmlPreview}+ previewId={message.messageKey}+ title="HTML visualization"+ maxBytes={HTML_PREVIEW_INLINE_MAX_BYTES}+ />+ )}+ {isJson ? (+ <pre className="message-block json-content">{displayContent}</pre>+ ) : message.role === 'assistant' ? (+ <div className="message-block markdown-content">+ <ReactMarkdown remarkPlugins={[remarkGfm]}>+ {displayContent}+ </ReactMarkdown>+ {selectedAgent && !hasResponseFileAttachment && (+ <MessageArtifactActions+ hostRef={selectedAgent}+ content={displayContent}+ />)}+ {workflowArtifactScopeForAssistant ? (+ <WorkflowRunArtifactActions+ workflow={workflowArtifactScopeForAssistant}+ />+ ) : null}</div>- <IconButton- className={`message-copy-button message-copy-button--inline${- copiedMessageKey === message.messageKey ? ' copied' : ''- }`}- onClick={() =>- void handleCopyMessage(message.messageKey, copyContent)- }- aria-label={- copiedMessageKey === message.messageKey ? 'Copied' : 'Copy text'- }- label={- copiedMessageKey === message.messageKey ? 'Copied' : 'Copy text'- }- size="xs"- variant="ghost"- >- <svg viewBox="0 0 24 24" aria-hidden="true">- <path fill="none" d="M0 0h24v24H0V0z" />- <path d="M16 1H4c-1.1 0-2 .9-2 2v14h2V3h12V1zm3 4H8c-1.1 0-2 .9-2 2v14c0 1.1.9 2 2 2h11c1.1 0 2-.9 2-2V7c0-1.1-.9-2-2-2zm0 16H8V7h11v14z" />- </svg>- {copiedMessageKey === message.messageKey && (- <span className="copy-tooltip">Copied!</span>- )}- </IconButton>- </footer>- )}- </article>- )- })}- </section>- {group.role === 'user' &&- group.items.map(message => {- const node = renderProgressStepper(message, 'non-completed')- if (!node) return null- return (- <section- key={`progress-${message.messageKey}`}- className="chat-group assistant"- >- <div className="chat-bubble assistant">{node}</div>- </section>- )- })}- </Fragment>- )- })- }- />+ ) : displayContent ? (+ <p className="message-block">{displayContent}</p>+ ) : null}+ <MessageAttachmentList attachments={displayAttachments} />+ </>+ )}+ {isLastAssistantMessage &&+ prevGroup?.role === 'user' &&+ (() => {+ // Prefer the live progress (keyed by the user message);+ // fall back to the assistant's persisted toolSteps after+ // a reload, when the live map is empty (#582).+ const liveNodes = prevGroup.items+ .map(msg => renderProgressStepper(msg, 'completed'))+ .filter((node): node is ReactElement => node != null)+ if (liveNodes.length > 0) return liveNodes+ return renderHydratedToolSteps(message)+ })()}+ {showMetaRow && (+ <footer className={`chat-message-meta-row ${metaRowRoleClass}`.trim()}>+ <div className="chat-message-meta-main">+ <span className="chat-time-label">+ {formatChatTimestamp(message.timestamp || Date.now())}+ </span>+ {message.role === 'assistant' && message.tokens && (+ <MessageTokens tokens={message.tokens} />+ )}+ </div>+ <IconButton+ className={`message-copy-button message-copy-button--inline${+ copiedMessageKey === message.messageKey ? ' copied' : ''+ }`}+ onClick={() =>+ void handleCopyMessage(message.messageKey, copyContent)+ }+ aria-label={+ copiedMessageKey === message.messageKey ? 'Copied' : 'Copy text'+ }+ label={+ copiedMessageKey === message.messageKey ? 'Copied' : 'Copy text'+ }+ size="xs"+ variant="ghost"+ >+ <svg viewBox="0 0 24 24" aria-hidden="true">+ <path fill="none" d="M0 0h24v24H0V0z" />+ <path d="M16 1H4c-1.1 0-2 .9-2 2v14h2V3h12V1zm3 4H8c-1.1 0-2 .9-2 2v14c0 1.1.9 2 2 2h11c1.1 0 2-.9 2-2V7c0-1.1-.9-2-2-2zm0 16H8V7h11v14z" />+ </svg>+ {copiedMessageKey === message.messageKey && (+ <span className="copy-tooltip">Copied!</span>+ )}+ </IconButton>+ </footer>+ )}+ </article>+ )+ })}+ </section>+ {group.role === 'user' &&+ group.items.map(message => {+ const node = renderProgressStepper(message, 'non-completed')+ if (!node) return null+ return (+ <section+ key={`progress-${message.messageKey}`}+ className="chat-group assistant"+ >+ <div className="chat-bubble assistant">{node}</div>+ </section>+ )+ })}+ </Fragment>+ )+ })}+ </div>))}{activeChatId && chatMessagesLoading && groupedWithKeys.length === 0 && (<section className="chat-group assistant" aria-label="Loading conversation">diff --git a/desktop-app/ui/src/hooks/__tests__/useAppController.test.tsx b/desktop-app/ui/src/hooks/__tests__/useAppController.test.tsxindex 803e9368b..74e712324 100644--- a/desktop-app/ui/src/hooks/__tests__/useAppController.test.tsx+++ b/desktop-app/ui/src/hooks/__tests__/useAppController.test.tsx@@ -170,7 +170,7 @@ describe('scheduleAfterFirstPaint', () => {frames.push(callback)return frames.length})- const identityRef = { current: 'user-1:team-1' }+ const identityRef: { current: string | null } = { current: 'user-1:team-1' }const task = vi.fn(async () => undefined)scheduleAfterFirstPaintForSession(identityRef, 'user-1:team-1', task)@@ -186,7 +186,7 @@ describe('scheduleAfterFirstPaint', () => {frames.push(callback)return frames.length})- const identityRef = { current: 'user-1:team-1' }+ const identityRef: { current: string | null } = { current: 'user-1:team-1' }const task = vi.fn(async () => undefined)scheduleAfterFirstPaintForSession(identityRef, 'user-1:team-1', task)diff --git a/desktop-app/ui/src/hooks/__tests__/useChatStore.test.tsx b/desktop-app/ui/src/hooks/__tests__/useChatStore.test.tsxindex f9059d637..0b00366c5 100644--- a/desktop-app/ui/src/hooks/__tests__/useChatStore.test.tsx+++ b/desktop-app/ui/src/hooks/__tests__/useChatStore.test.tsx@@ -53,4 +53,22 @@ describe('useChatStore remote request cache', () => {expect(listSessions).toHaveBeenCalledTimes(2)expect(getHostModels).toHaveBeenCalledTimes(2)})++ it('invalidates the scoped host-model cache after changing a model', async () => {+ const getHostModels = vi.fn(async () => ({ models: [] }))+ const setHostModel = vi.fn(async () => ({ success: true }))+ Object.defineProperty(window, 'clerum', {+ configurable: true,+ value: { rpc: { getHostModels, setHostModel } },+ })+ const { result } = renderHook(() => useChatStore())++ result.current.setRemoteCacheScope('authenticated:team-a')+ await result.current.getHostModels('cache-test-host', 'chat-1')+ await result.current.setHostModel('cache-test-host', 'chat-1', 'model-b')+ await result.current.getHostModels('cache-test-host', 'chat-1')++ expect(setHostModel).toHaveBeenCalledTimes(1)+ expect(getHostModels).toHaveBeenCalledTimes(2)+ })})diff --git a/desktop-app/ui/src/hooks/domain/__tests__/pendingChatSelection.characterization.test.tsx b/desktop-app/ui/src/hooks/domain/__tests__/pendingChatSelection.characterization.test.tsxindex 433d26290..74337d62b 100644--- a/desktop-app/ui/src/hooks/domain/__tests__/pendingChatSelection.characterization.test.tsx+++ b/desktop-app/ui/src/hooks/domain/__tests__/pendingChatSelection.characterization.test.tsx@@ -52,6 +52,30 @@ function deferred<T>() {}describe('pendingChatSelection effect', () => {+ it('opens the newest server session after first paint when the local index is empty', async () => {+ clerum.chat.getIndex.mockResolvedValue({+ version: 3,+ lastActiveChatId: null,+ onboardingDismissed: false,+ chats: [],+ })+ clerum.rpc.listSessions.mockResolvedValue({+ items: [+ {+ agent: 'agent-x',+ chatId: 'server-latest',+ turnCount: 2,+ messageCount: 4,+ lastActivityAt: '2026-05-01T00:00:00Z',+ },+ ],+ })++ const { result } = renderController({ navItem: 'chat' })++ await waitFor(() => expect(result.current.activeChatId).toBe('server-latest'))+ })+it('latest → switches to the most recent chat', async () => {clerum.chat.getIndex.mockResolvedValue({version: 1,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 862943d56..7243c5373 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@@ -8,6 +8,7 @@* registered progress handler for the task is the observable proof of rejoin.*/import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'+import { makeTaskKey } from '@contexts/AgentTaskTrackerContext/types'import { act, waitFor } from '@testing-library/react'import { renderController } from './__fixtures__/controllerHarness'import { type MockClerum, installMockClerum, uninstallMockClerum } from './__fixtures__/mockClerum'@@ -131,7 +132,7 @@ describe('switchToChat (unified, D.4)', () => {)})- it('follows server delta pages until the active chat reaches the latest revision', async () => {+ it('follows server delta pages until the active chat reaches the latest turn', async () => {clerum.chat.loadMessages.mockResolvedValue([{ id: 'turn-1-user', role: 'user' as const, content: 'q1', timestamp: 1 },{ id: 'turn-1-assistant', role: 'assistant' as const, content: 'a1', timestamp: 2 },@@ -189,6 +190,68 @@ describe('switchToChat (unified, D.4)', () => {)})+ it('keeps durable local bubbles in place and deduplicates trimmed server echoes', async () => {+ const turnTwoStartedAt = Date.parse('2026-05-28T10:02:00Z')+ clerum.chat.loadMessages.mockResolvedValue([+ {+ 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,+ },+ {+ id: 'durable-error',+ role: 'assistant' as const,+ content: 'Recovered warning',+ timestamp: 3,+ isError: true,+ },+ {+ id: 'local-turn-2-user',+ role: 'user' as const,+ content: 'q2',+ timestamp: turnTwoStartedAt,+ },+ {+ id: 'local-turn-2-assistant',+ role: 'assistant' as const,+ content: 'a2 ',+ timestamp: turnTwoStartedAt + 5_000,+ },+ ])+ clerum.rpc.loadSessionMessages.mockResolvedValue({+ agent: 'agent-x',+ chatId: 'stable-local-order',+ state: 'idle',+ totalTurns: 2,+ hasMoreBefore: false,+ hasMoreAfter: false,+ turns: [turn(2, 'q2', 'a2')],+ })+ const { result } = renderController()+ await settleMount()++ await act(async () => {+ await result.current.switchToChat('agent-x', 'stable-local-order')+ })++ expect(result.current.chatMessages.map(message => message.id)).toEqual([+ 'turn-1-user',+ 'turn-1-assistant',+ 'durable-error',+ 'turn-2-user',+ 'turn-2-assistant',+ ])+ })+it('caps server delta pagination so reconcile cannot walk an unbounded cursor chain', async () => {clerum.chat.loadMessages.mockResolvedValue([{ id: 'turn-1-user', role: 'user' as const, content: 'q1', timestamp: 1 },@@ -196,6 +259,17 @@ describe('switchToChat (unified, D.4)', () => {])clerum.rpc.loadSessionMessages.mockImplementation(async (_hostRef, _agent, chatId, _teamId, query?: { afterTurn?: number }) => {+ if (query?.afterTurn === undefined) {+ return {+ agent: 'agent-x',+ chatId,+ state: 'idle',+ latestTurnNumber: 999,+ hasMoreBefore: true,+ hasMoreAfter: false,+ turns: [turn(999, 'newest question', 'newest answer')],+ }+ }const nextTurn = (query?.afterTurn ?? 1) + 1return {agent: 'agent-x',@@ -214,15 +288,20 @@ describe('switchToChat (unified, D.4)', () => {await result.current.switchToChat('agent-x', 'delta-cap')})- expect(clerum.rpc.loadSessionMessages).toHaveBeenCalledTimes(5)+ expect(clerum.rpc.loadSessionMessages).toHaveBeenCalledTimes(6)expect(clerum.rpc.loadSessionMessages).toHaveBeenLastCalledWith('agent-x','agent-x','delta-cap',undefined,- { limit: 80, afterTurn: 5 }+ { 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).toHaveLength(12)})it('loads older history on demand and prepends it without blocking first render', async () => {@@ -288,6 +367,26 @@ describe('switchToChat (unified, D.4)', () => {'older-pages',expect.arrayContaining([expect.objectContaining({ id: 'turn-1-assistant' })]))++ clerum.rpc.loadSessionMessages.mockResolvedValueOnce({+ agent: 'agent-x',+ chatId: 'older-pages',+ state: 'idle',+ totalTurns: 101,+ oldestTurnNumber: 101,+ latestTurnNumber: 101,+ hasMoreBefore: true,+ hasMoreAfter: false,+ turns: [turn(101, 'q101', 'a101')],+ })+ await act(async () => {+ await result.current.reconcileChat(makeTaskKey('agent-x', 'older-pages'), {+ reason: 'system_resume',+ })+ })++ expect(result.current.chatMessages[0]?.id).toBe('turn-1-user')+ expect(result.current.chatMessages.at(-1)?.id).toBe('turn-101-assistant')})it('does not show older history for a complete exact-page-size local chat', async () => {@@ -369,6 +468,60 @@ describe('switchToChat (unified, D.4)', () => {expect(clerum.rpc.loadSessionMessages).toHaveBeenCalledTimes(1)})+ it('cancels an in-flight older-page request when switching chats', 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.mockResolvedValue({+ agent: 'agent-x',+ chatId: 'chat-a',+ state: 'idle',+ turns: [],+ hasMoreBefore: true,+ 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')+ })+ expect(result.current.olderMessagesLoading).toBe(false)++ resolveOlder([])+ await act(async () => {+ await pendingOlder+ })+ 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/__tests__/useActivityController.test.tsx b/desktop-app/ui/src/hooks/domain/__tests__/useActivityController.test.tsxindex be2d1750e..f9a119b55 100644--- a/desktop-app/ui/src/hooks/domain/__tests__/useActivityController.test.tsx+++ b/desktop-app/ui/src/hooks/domain/__tests__/useActivityController.test.tsx@@ -90,4 +90,55 @@ describe('useActivityController', () => {await waitFor(() => expect(getIndex).toHaveBeenCalledTimes(2))})++ it('backfills missing activity counters for chats created before metadata counters existed', async () => {+ const getIndex = vi.fn(async () => ({+ version: 3,+ lastActiveChatId: null,+ onboardingDismissed: false,+ chats: [],+ }))+ const loadMessages = vi.fn(async () => [+ { id: 'm1', role: 'user', content: 'hello', timestamp: 1 },+ {+ id: 'm2',+ role: 'assistant',+ content: 'failed',+ timestamp: 2,+ isError: true,+ toolSteps: [{ toolName: 'read', displayName: 'Read', state: 'completed' }],+ },+ ])+ Object.defineProperty(window, 'clerum', {+ configurable: true,+ value: { chat: { getIndex, loadMessages } },+ })++ const { result } = renderHook(() =>+ useActivityController({+ selectedAgent: 'agent-a',+ isAuthenticated: true,+ loadMenuData: true,+ chatList: [+ {+ id: 'legacy-chat',+ title: 'Legacy',+ createdAt: '2026-07-22T00:00:00.000Z',+ updatedAt: '2026-07-22T00:00:00.000Z',+ messageCount: 2,+ },+ ],+ progressByAgentMessage: EMPTY_PROGRESS,+ agentNames: AGENT_A,+ })+ )++ await waitFor(() =>+ expect(result.current.selectedAgentActivitySummary).toMatchObject({+ errors: 1,+ toolCalls: 1,+ })+ )+ expect(loadMessages).toHaveBeenCalledWith('agent-a', 'legacy-chat', undefined, undefined)+ })})diff --git a/desktop-app/ui/src/hooks/domain/useActivityController.ts b/desktop-app/ui/src/hooks/domain/useActivityController.tsindex cdd8f6955..8fcd5a974 100644--- a/desktop-app/ui/src/hooks/domain/useActivityController.ts+++ b/desktop-app/ui/src/hooks/domain/useActivityController.ts@@ -12,6 +12,10 @@ interface UseActivityControllerParams {agentNames: string[]}+function activityCounterKey(agentRef: string, chatId: string): string {+ return `${agentRef}\u0000${chatId}`+}+export function useActivityController({selectedAgent,isAuthenticated,@@ -25,6 +29,9 @@ export function useActivityController({const [agentLastActiveByAgent, setAgentLastActiveByAgent] = useState<Record<string, string | null>>({})+ const [backfilledCountersByChat, setBackfilledCountersByChat] = useState<+ Record<string, { errors: number; toolCalls: number }>+ >({})const selectedAgentActivitySummary = useMemo(() => {if (!selectedAgent) {return {@@ -50,9 +57,11 @@ export function useActivityController({let persistedToolCalls = 0for (const chat of chatList) {+ const backfilledCounters =+ backfilledCountersByChat[activityCounterKey(selectedAgent, chat.id)]totalMessages += chat.messageCount || 0- totalErrors += chat.errorCount || 0- persistedToolCalls += chat.toolCallCount || 0+ totalErrors += chat.errorCount ?? backfilledCounters?.errors ?? 0+ persistedToolCalls += chat.toolCallCount ?? backfilledCounters?.toolCalls ?? 0const chatTimestamp = Date.parse(chat.updatedAt)if (Number.isNaN(chatTimestamp)) continue@@ -78,7 +87,45 @@ export function useActivityController({count,})),}- }, [chatList, progressByAgentMessage, selectedAgent])+ }, [backfilledCountersByChat, chatList, progressByAgentMessage, selectedAgent])++ const missingCounterChatIds = JSON.stringify(+ chatList+ .filter(chat => chat.errorCount === undefined || chat.toolCallCount === undefined)+ .map(chat => chat.id)+ )++ useEffect(() => {+ if (!isAuthenticated || !loadMenuData || !selectedAgent) {+ setBackfilledCountersByChat({})+ return+ }+ const chatIds = JSON.parse(missingCounterChatIds) as string[]+ if (!chatIds.length) return++ let cancelled = false+ void Promise.all(+ chatIds.map(async chatId => {+ const messages = await chatStore.loadMessages(selectedAgent, chatId).catch(() => [])+ return [+ activityCounterKey(selectedAgent, chatId),+ {+ errors: messages.reduce((total, message) => total + (message.isError ? 1 : 0), 0),+ toolCalls: messages.reduce(+ (total, message) => total + (message.toolSteps?.length ?? 0),+ 0+ ),+ },+ ] as const+ })+ ).then(entries => {+ if (!cancelled) setBackfilledCountersByChat(Object.fromEntries(entries))+ })++ return () => {+ cancelled = true+ }+ }, [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 5c7da498d..86b8d3e52 100644--- a/desktop-app/ui/src/hooks/domain/useAgentChatController.ts+++ b/desktop-app/ui/src/hooks/domain/useAgentChatController.ts@@ -151,19 +151,21 @@ function mergeUniqueMessages(}function sameLocalServerMessage(local: AgentChatMessage, server: AgentChatMessage): boolean {+ const sameTask =+ Boolean(local.task_id) && Boolean(server.task_id) && local.task_id === server.task_id+ const sameNearbyContent =+ local.content.trim() === server.content.trim() &&+ Math.abs(local.timestamp - server.timestamp) <= 60_000return (serverTurnNumber(local) === undefined &&serverTurnNumber(server) !== undefined &&local.role === server.role &&- local.content === server.content+ (sameTask || sameNearbyContent))}-function messageSortRank(message: AgentChatMessage, fallbackIndex: number): number {- const turnNumber = serverTurnNumber(message)- if (turnNumber === undefined) return 1_000_000_000 + fallbackIndex- const roleRank = message.role === 'user' ? 0 : message.role === 'assistant' ? 1 : 2- return turnNumber * 10 + roleRank+function messageRoleRank(message: AgentChatMessage): number {+ return message.role === 'user' ? 0 : message.role === 'assistant' ? 1 : 2}function mergeServerMessages(@@ -206,13 +208,23 @@ function mergeServerMessages(continue}- merged.push(serverMessage)+ const insertionIndex =+ serverTurn === undefined+ ? -1+ : merged.findIndex(message => {+ const messageTurn = serverTurnNumber(message)+ if (messageTurn === undefined) return false+ return (+ messageTurn > serverTurn ||+ (messageTurn === serverTurn &&+ messageRoleRank(message) > messageRoleRank(serverMessage))+ )+ })+ if (insertionIndex < 0) merged.push(serverMessage)+ else merged.splice(insertionIndex, 0, serverMessage)}return merged- .map((message, index) => ({ message, index }))- .sort((a, b) => messageSortRank(a.message, a.index) - messageSortRank(b.message, b.index))- .map(item => item.message)}function sameMessageSequence(a: AgentChatMessage[], b: AgentChatMessage[]): boolean {@@ -402,6 +414,12 @@ export function useAgentChatController({const [olderMessagesLoading, setOlderMessagesLoading] = useState(false)const chatMessagesRef = useRef<AgentChatMessage[]>([])const loadedLocalMessageCountRef = useRef(0)+ const olderMessagesRequestRef = useRef<symbol | null>(null)++ const cancelOlderMessagesLoad = useCallback(() => {+ olderMessagesRequestRef.current = null+ setOlderMessagesLoading(false)+ }, [])const [activityByAgentMessage, setActivityByAgentMessage] = useState<Record<string, Record<string, AgentMessageActivity>>@@ -734,7 +752,7 @@ export function useAgentChatController({setChatMessages([])setChatMessagesLoading(false)setHasOlderMessages(false)- setOlderMessagesLoading(false)+ cancelOlderMessagesLoad()loadedLocalMessageCountRef.current = 0// The error/resend banner is per-chat view state — drop it when the active// chat is torn down (logout / unauth boot) so it can't survive into the next.@@ -747,6 +765,7 @@ export function useAgentChatController({fsm,resetReplyNotificationDedupe,chatStore.clearCachedRemoteData,+ cancelOlderMessagesLoad,])// Unified switch (post-D.4): cache-first render → server reconcile → tracker@@ -764,6 +783,7 @@ export function useAgentChatController({setChatMessages([])setChatMessagesLoading(true)setHasOlderMessages(false)+ cancelOlderMessagesLoad()loadedLocalMessageCountRef.current = 0// The error/resend banner is per-chat view state, not global: clear it on// every chat switch (same-agent switches don't trip the selectedAgent@@ -784,15 +804,11 @@ export function useAgentChatController({// PHASE 1 — render only the newest local page. The authoritative reconcile// below requests a delta after the newest cached server turn.- let cached: Awaited<ReturnType<typeof chatStore.loadMessages>>+ let cached: Awaited<ReturnType<typeof chatStore.loadMessages>> = []try {cached = await chatStore.loadMessages(agentRef, chatId, MESSAGE_PAGE_SIZE)} catch (error) {console.warn('[chat-history] failed to load local messages', { agentRef, chatId, error })- if (isStillActive()) {- setChatMessagesLoading(false)- }- return}const oldestCachedTurn = oldestServerTurnNumber(cached as AgentChatMessage[])const hasOlderServerMessages = Boolean(oldestCachedTurn && oldestCachedTurn > 1)@@ -860,6 +876,7 @@ export function useAgentChatController({reconcileChat,scrollChatToBottom,clearUnreadInList,+ cancelOlderMessagesLoad,chatStore.setLastActive,chatStore.loadMessages,chatStore.clearUnreadTerminal,@@ -885,6 +902,7 @@ export function useAgentChatController({dispatchSession,clearComposerDraft,getActiveChatId: () => activeChatId,+ shouldAutoSelectLatest: () => navItem === DESKTOP_ROUTES.chat,}})@@ -897,9 +915,11 @@ export function useAgentChatController({)const handleLoadOlderMessages = useCallback(async () => {- if (!selectedAgent || !activeChatId || olderMessagesLoading) return+ if (!selectedAgent || !activeChatId || olderMessagesRequestRef.current) returnconst requestAgent = selectedAgentconst requestChatId = activeChatId+ const requestToken = Symbol(`${requestAgent}:${requestChatId}`)+ olderMessagesRequestRef.current = requestTokenconst isStillRelevant = () => {const visible = activeChatVisibilityRef.currentreturn visible.selectedAgent === requestAgent && visible.activeChatId === requestChatId@@ -960,6 +980,7 @@ export function useAgentChatController({setChatMessages(merged)if (!isStillRelevant()) returnawait chatStore.replaceMessages(requestAgent, requestChatId, merged)+ if (!isStillRelevant()) returnloadedLocalMessageCountRef.current = merged.lengthsetHasOlderMessages(Boolean(response.hasMoreBefore))} catch (error) {@@ -969,7 +990,8 @@ export function useAgentChatController({error,})} finally {- if (isStillRelevant()) {+ if (olderMessagesRequestRef.current === requestToken) {+ olderMessagesRequestRef.current = nullsetOlderMessagesLoading(false)}}@@ -979,7 +1001,6 @@ export function useAgentChatController({chatStore.loadMessages,chatStore.loadSessionMessages,chatStore.replaceMessages,- olderMessagesLoading,selectedAgent,])@@ -998,6 +1019,7 @@ export function useAgentChatController({setChatMessages([])setChatMessagesLoading(false)setHasOlderMessages(false)+ cancelOlderMessagesLoad()loadedLocalMessageCountRef.current = 0return}@@ -1015,6 +1037,7 @@ export function useAgentChatController({setChatMessages([])setChatMessagesLoading(true)setHasOlderMessages(false)+ cancelOlderMessagesLoad()loadedLocalMessageCountRef.current = 0if (requestedSelection.title) {upsertProvisionalEntry(@@ -1034,6 +1057,7 @@ export function useAgentChatController({setChatMessages([])setChatMessagesLoading(false)setHasOlderMessages(false)+ cancelOlderMessagesLoad()loadedLocalMessageCountRef.current = 0}setChatListLoading(true)@@ -1106,7 +1130,7 @@ export function useAgentChatController({return () => {cancelled = true}- }, [currentTeamId, navItem, selectedAgent])+ }, [cancelOlderMessagesLoad, currentTeamId, navItem, selectedAgent])const mapComposerAttachmentsToHostRequest = (attachments: ComposerImageAttachment[]@@ -1331,44 +1355,61 @@ export function useAgentChatController({const v = activeChatVisibilityRef.currentreturn v.selectedAgent === agentRef && v.activeChatId === chatId}- const cached = (await chatStore.loadMessages(- agentRef,- chatId,- MESSAGE_PAGE_SIZE- )) as AgentChatMessage[]- if (!isActive() || tracker.get(chatKey)) return { rendered: cached, replaced: false, cached }+ const cached = (await chatStore+ .loadMessages(agentRef, chatId, MESSAGE_PAGE_SIZE)+ .catch(error => {+ console.warn('[chat-history] failed to read local reconciliation window', {+ agentRef,+ chatId,+ error,+ })+ return []+ })) as AgentChatMessage[]+ const visible = isActive() ? chatMessagesRef.current : []+ 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 (!hydrated.length) return { rendered: cached, replaced: false, cached }- const cachedHasServerTurns = cached.some(message => serverTurnNumber(message) !== undefined)- if (!cachedHasServerTurns) {+ if (!hydrated.length) {+ return { rendered: localMessages, replaced: false, cached: localMessages }+ }+ const localHasServerTurns = localMessages.some(+ message => serverTurnNumber(message) !== undefined+ )+ if (!localHasServerTurns) {setHasOlderMessages(previous => previous || Boolean(resp.hasMoreBefore))}- if (!cachedHasServerTurns && cached.length > 0) {+ if (!localHasServerTurns && localMessages.length > 0) {const responseContainsAllTurns =resp.totalTurns === undefined || resp.totalTurns === resp.turns.length- if (responseContainsAllTurns && hydrated.length <= cached.length) {- return { rendered: cached, replaced: false, cached }+ if (responseContainsAllTurns && hydrated.length <= localMessages.length) {+ return { rendered: localMessages, replaced: false, cached: localMessages }}}const hydratedWithAttachments = withResponseFileAttachments(hydrated,taskIdHint ? await loadTaskResultResponseFileAttachments(agentRef, taskIdHint) : [])- if (!isActive() || tracker.get(chatKey)) return { rendered: cached, replaced: false, cached }- const rendered = cachedHasServerTurns- ? mergeServerMessages(cached, hydratedWithAttachments)+ if (!isActive() || tracker.get(chatKey)) {+ return { rendered: localMessages, replaced: false, cached: localMessages }+ }+ const rendered = localHasServerTurns+ ? mergeServerMessages(localMessages, hydratedWithAttachments): hydratedWithAttachments- if (sameMessageSequence(rendered, cached)) {- return { rendered: cached, replaced: false, cached }+ if (sameMessageSequence(rendered, localMessages)) {+ return { rendered: localMessages, replaced: false, cached: localMessages }}+ chatMessagesRef.current = renderedsetChatMessages(rendered)const meta = await chatStore.createChat(agentRef, chatId)await chatStore.replaceMessages(agentRef, chatId, rendered)+ if (!isActive()) return { rendered, replaced: true, cached: localMessages }loadedLocalMessageCountRef.current = rendered.length// Auto-title a fresh hydration (empty cache) from the first user turn, so a// server-only chat doesn't keep its "Chat <id>" placeholder (A.4.4 / S4).let title = meta.title- if (cached.length === 0 && (resp.oldestTurnNumber ?? resp.turns[0]?.number) === 1) {+ if (localMessages.length === 0 && (resp.oldestTurnNumber ?? resp.turns[0]?.number) === 1) {const firstUserInput = resp.turns.find(t => t.user_input?.trim())?.user_input?.trim() || ''const hydratedTitle =firstUserInput.length > 60@@ -1383,7 +1424,7 @@ export function useAgentChatController({// S4: upsert into the sidebar. A chat opened via a notification for the// already-selected agent may not be in chatList yet; a bare `.map` drops it.upsertHydratedEntry(meta, title)- return { rendered, replaced: true, cached }+ return { rendered, replaced: true, cached: localMessages }},[tracker,@@ -1572,11 +1613,16 @@ export function useAgentChatController({loadSessionMessages: async (agentRef, chatId, query) => {let requestedQuery = query ?? { limit: MESSAGE_PAGE_SIZE }if (requestedQuery.beforeTurn === undefined && requestedQuery.afterTurn === undefined) {- const cached = (await chatStore.loadMessages(- agentRef,- chatId,- MESSAGE_PAGE_SIZE- )) as AgentChatMessage[]+ const cached = (await chatStore+ .loadMessages(agentRef, chatId, MESSAGE_PAGE_SIZE)+ .catch(error => {+ console.warn('[chat-history] failed to read local delta cursor', {+ agentRef,+ chatId,+ error,+ })+ return []+ })) as AgentChatMessage[]const latestCachedTurn = latestServerTurnNumber(cached)requestedQuery = {...requestedQuery,@@ -1612,12 +1658,17 @@ export function useAgentChatController({cursor = response.latestTurnNumber ?? response.turns.at(-1)?.numberpagesLoaded += 1}+ if (response.hasMoreAfter) {+ return chatStore.loadSessionMessages(agentRef, agentRef, chatId, {+ limit: requestedQuery.limit ?? MESSAGE_PAGE_SIZE,+ })+ }return {...response,turns,oldestTurnNumber: turns[0]?.number,latestTurnNumber: turns.at(-1)?.number,- hasMoreAfter: Boolean(response.hasMoreAfter && pagesLoaded >= MAX_RECONCILE_DELTA_PAGES),+ hasMoreAfter: false,}},attachLiveTask: reconcileAttachLiveTask,@@ -2622,12 +2673,13 @@ export function useAgentChatController({setChatMessages([])setChatMessagesLoading(true)setHasOlderMessages(false)+ cancelOlderMessagesLoad()loadedLocalMessageCountRef.current = 0if (options.title) {upsertProvisionalEntry(chatId, options.title, options.isRemote === true)}},- [currentTeamId, writePendingSelection, upsertProvisionalEntry]+ [cancelOlderMessagesLoad, currentTeamId, writePendingSelection, upsertProvisionalEntry])const clearActiveChat = useCallback(() => {@@ -2639,12 +2691,13 @@ export function useAgentChatController({setChatMessages([])setChatMessagesLoading(false)setHasOlderMessages(false)+ cancelOlderMessagesLoad()loadedLocalMessageCountRef.current = 0// Deselecting the active chat (e.g. team switch) must also drop its per-chat// error/resend banner so it doesn't bleed into the next active chat.setAgentError(null)setFailedAgentSend(null)- }, [])+ }, [cancelOlderMessagesLoad])const groupedMessages = useMemo(() => {const groups: Array<{ role: 'user' | 'assistant' | 'system'; items: AgentChatMessage[] }> = []diff --git a/desktop-app/ui/src/hooks/domain/useChatListController.ts b/desktop-app/ui/src/hooks/domain/useChatListController.tsindex d1b64d790..f235e4400 100644--- a/desktop-app/ui/src/hooks/domain/useChatListController.ts+++ b/desktop-app/ui/src/hooks/domain/useChatListController.ts@@ -58,6 +58,7 @@ export interface ChatListControllerHost {dispatchSession: (chatKey: string, event: SessionFsmEvent) => voidclearComposerDraft: (chatId: string) => voidgetActiveChatId: () => string | null+ shouldAutoSelectLatest: () => boolean}interface UseChatListControllerParams {@@ -102,6 +103,7 @@ export function useChatListController({// Selection requested for an agent before its chats have loaded, consumed by// the parent's agent-selection effect. Ref (not state): imperative, per-agent.const pendingChatSelectionByAgentRef = useRef<Record<string, PendingChatSelection>>({})+ const suppressAutoSelectionByAgentRef = useRef<Set<string>>(new Set())const chatListNextCursorByAgentRef = useRef<Record<string, string | null | undefined>>({})const chatListLoadingMoreByAgentRef = useRef<Set<string>>(new Set())@@ -184,12 +186,22 @@ export function useChatListController({title: `Chat ${s.chatId.slice(0, 8)}`,createdAt: s.lastActivityAt,updatedAt: s.lastActivityAt,- messageCount: s.turnCount * 2,+ messageCount: s.messageCount ?? s.turnCount * 2,turnCount: s.turnCount,}))return [...dedupedPrevious, ...fromServerOnly].sort(byUpdatedDesc)})+ const latestServerSession = serverSessions[0]+ if (+ latestServerSession &&+ host.current?.getActiveChatId() === null &&+ host.current.shouldAutoSelectLatest() &&+ !suppressAutoSelectionByAgentRef.current.has(agentRef)+ ) {+ void host.current.switchToChat(agentRef, latestServerSession.chatId)+ }+// Persist server freshness into the local index (spec §5.3): keeps the// durable sidebar order aligned with the source of truth. Best-effort:// must never block or fail the visible local-cache render.@@ -245,7 +257,7 @@ export function useChatListController({title: `Chat ${s.chatId.slice(0, 8)}`,createdAt: s.lastActivityAt,updatedAt: s.lastActivityAt,- messageCount: s.turnCount * 2,+ messageCount: s.messageCount ?? s.turnCount * 2,turnCount: s.turnCount,}))return [...dedupedPrevious, ...fromServerOnly].sort(byUpdatedDesc)@@ -299,6 +311,7 @@ export function useChatListController({const clearList = useCallback(() => {chatListNextCursorByAgentRef.current = {}chatListLoadingMoreByAgentRef.current.clear()+ suppressAutoSelectionByAgentRef.current.clear()setChatList([])setChatListMoreLoading(false)setChatListHasMoreRemoteSessions(false)@@ -417,6 +430,8 @@ export function useChatListController({const writePendingSelection = useCallback((agentName: string, selection: PendingChatSelection) => {pendingChatSelectionByAgentRef.current[agentName] = selection+ if (selection.mode === 'none') suppressAutoSelectionByAgentRef.current.add(agentName)+ else suppressAutoSelectionByAgentRef.current.delete(agentName)},[])@@ -583,7 +598,7 @@ export function useChatListController({title: `Remote · ${session.chatId.slice(0, 8)}`,createdAt: session.lastActivityAt,updatedAt: session.lastActivityAt,- messageCount: session.turnCount * 2,+ messageCount: session.messageCount ?? session.turnCount * 2,remote: true,turnCount: session.turnCount,agentRef: group.agentRef,diff --git a/desktop-app/ui/src/hooks/useAppController.ts b/desktop-app/ui/src/hooks/useAppController.tsindex 70768dd4a..f7cffef26 100644--- a/desktop-app/ui/src/hooks/useAppController.ts+++ b/desktop-app/ui/src/hooks/useAppController.ts@@ -153,6 +153,7 @@ export function useAppController() {// Use a ref so the stable onSessionNeedsLoad callback can call the real loadSession// without creating a circular dependency (loadSession is defined after auth+session).const loadSessionRef = useRef(async (_options?: { preserveNav?: boolean }) => {})+ const activeAuthenticatedSessionIdentityRef = useRef<string | null>(null)const authenticatedSessionIdentityRef = useRef<string | null>(null)const catalogRefreshPromiseRef = useRef<Promise<AccessCatalog> | null>(null)@@ -372,31 +373,36 @@ export function useAppController() {}, [queryClient])const refreshAuthenticatedData = useCallback(- async (options: { initialLoad?: boolean } = {}) => {+ async (options: { initialLoad?: boolean; sessionIdentity?: string } = {}) => {const refreshTeams = options.initialLoad? teamsData.refreshInitialDirectory: teamsData.refreshif (options.initialLoad) {- const scheduledIdentity = authenticatedSessionIdentityRef.current- await refreshAgentsData()- if (!scheduledIdentity || authenticatedSessionIdentityRef.current !== scheduledIdentity) {- return+ const scheduledIdentity = options.sessionIdentity+ if (!scheduledIdentity) return false+ let agentsLoaded = false+ try {+ await refreshAgentsData()+ agentsLoaded = true+ } catch (error) {+ console.warn('[startup] failed to load the initial agent catalog', error)+ } finally {+ scheduleAfterFirstPaintForSession(+ activeAuthenticatedSessionIdentityRef,+ scheduledIdentity,+ async () => {+ setPostPaintDataReady(true)+ await Promise.all([+ refreshContextsData(),+ refreshMcpServersData(),+ refreshTeams(),+ refreshWorkflowsData(),+ notif.handleRefreshPendingApprovals({ silent: true }),+ ])+ }+ )}- scheduleAfterFirstPaintForSession(- authenticatedSessionIdentityRef,- scheduledIdentity,- async () => {- setPostPaintDataReady(true)- await Promise.all([- refreshContextsData(),- refreshMcpServersData(),- refreshTeams(),- refreshWorkflowsData(),- notif.handleRefreshPendingApprovals({ silent: true }),- ])- }- )- return+ return agentsLoaded}return Promise.all([refreshAgentsData(),@@ -536,7 +542,9 @@ export function useAppController() {auth.setMe(sessionState.me)auth.setEmail(sessionState.me.email || '')currentTeamIdRef.current = sessionState.me.teamId || teamId- authenticatedSessionIdentityRef.current = `${sessionState.me.id}:${sessionState.me.email}:${sessionState.me.teamId || ''}`+ const switchedIdentity = `${sessionState.me.id}:${sessionState.me.email}:${sessionState.me.teamId || ''}`+ activeAuthenticatedSessionIdentityRef.current = switchedIdentity+ authenticatedSessionIdentityRef.current = switchedIdentityawait refreshAuthenticatedData()if (announce) {const teamName =@@ -628,6 +636,7 @@ export function useAppController() {queryClient.removeQueries({ queryKey: desktopQueryKeys.gfsRoot })chat.resetChat()notif.resetNotifications()+ activeAuthenticatedSessionIdentityRef.current = nullauthenticatedSessionIdentityRef.current = nullif (!preserveNav) nav.handleNavSelect(DESKTOP_ROUTES.chat)return@@ -637,10 +646,16 @@ export function useAppController() {auth.setEmail(sessionState.me.email || '')void auth.refreshDesktopReleaseStatus()const sessionIdentity = `${sessionState.me.id}:${sessionState.me.email}:${sessionState.me.teamId || ''}`+ activeAuthenticatedSessionIdentityRef.current = sessionIdentityif (authenticatedSessionIdentityRef.current !== sessionIdentity) {setPostPaintDataReady(false)- authenticatedSessionIdentityRef.current = sessionIdentity- await refreshAuthenticatedData({ initialLoad: true })+ const loaded = await refreshAuthenticatedData({+ initialLoad: true,+ sessionIdentity,+ })+ if (loaded && activeAuthenticatedSessionIdentityRef.current === sessionIdentity) {+ authenticatedSessionIdentityRef.current = sessionIdentity+ }}if (!preserveNav) {nav.handleNavSelect(DESKTOP_ROUTES.chat)@@ -695,6 +710,7 @@ export function useAppController() {// in cache would otherwise bleed into the next login (possibly a different// environment, since the env is chosen pre-login).queryClient.clear()+ activeAuthenticatedSessionIdentityRef.current = nullauthenticatedSessionIdentityRef.current = nullawait window.clerum.auth.logout()chat.resetChat()diff --git a/desktop-app/ui/src/hooks/useChatStore.ts b/desktop-app/ui/src/hooks/useChatStore.tsindex 695900c16..9bf51c680 100644--- a/desktop-app/ui/src/hooks/useChatStore.ts+++ b/desktop-app/ui/src/hooks/useChatStore.ts@@ -69,6 +69,10 @@ function pendingModelKey(agentRef: string, chatId: string): string {return `${agentRef}::${chatId}`}+function hostModelKey(hostRef: string, chatId: string): string {+ return `${remoteCacheScope}:${hostRef}:${chatId}`+}+/*** Hook providing typed access to the chat persistence IPC layer.* All methods are stable (useCallback) and safe to use in dependency arrays.@@ -173,7 +177,7 @@ export function useChatStore() {hostModelRequests.clear()hostModelsSource = source}- const key = `${remoteCacheScope}:${hostRef}:${chatId}`+ const key = hostModelKey(hostRef, chatId)const cached = hostModelRequests.get(key)if (cached && cached.expiresAt > Date.now()) return cached.promise@@ -186,7 +190,7 @@ export function useChatStore() {}, [])const setHostModel = useCallback(async (hostRef: string, chatId: string, model: string) => {const result = await window.clerum.rpc.setHostModel(hostRef, chatId, model)- hostModelRequests.delete(`${hostRef}:${chatId}`)+ hostModelRequests.delete(hostModelKey(hostRef, chatId))return result}, [])const clearCachedRemoteData = useCallback(() => {diff --git a/desktop-app/ui/src/styles.css b/desktop-app/ui/src/styles.cssindex 27b3a2d68..89e42d22b 100644--- a/desktop-app/ui/src/styles.css+++ b/desktop-app/ui/src/styles.css@@ -6067,6 +6067,8 @@ h3 {display: grid;gap: var(--space-2);min-width: 0;+ content-visibility: auto;+ contain-intrinsic-size: auto 720px;}.chat-empty-state {diff --git a/mcp-host/package-lock.json b/mcp-host/package-lock.jsonindex 611f4a185..a66c660a1 100644--- a/mcp-host/package-lock.json+++ b/mcp-host/package-lock.json@@ -1,12 +1,12 @@{"name": "clerum-mcp-host",- "version": "0.1.213",+ "version": "0.1.214","lockfileVersion": 3,"requires": true,"packages": {"": {"name": "clerum-mcp-host",- "version": "0.1.213",+ "version": "0.1.214","license": "SEE LICENSE IN LICENSE","dependencies": {"@anthropic-ai/sdk": "^0.32.0",diff --git a/mcp-host/package.json b/mcp-host/package.jsonindex b28758c4c..dfb6f2a56 100644--- a/mcp-host/package.json+++ b/mcp-host/package.json@@ -1,6 +1,6 @@{"name": "clerum-mcp-host",- "version": "0.1.213",+ "version": "0.1.214","description": "MCP Host - reads Host CRD and provides LLM access via OpenAI/Claude","main": "dist/main.js","engines": {diff --git a/mcp-host/src/__tests__/integration/crossDeviceSessions.test.ts b/mcp-host/src/__tests__/integration/crossDeviceSessions.test.tsindex 9d0f14f3d..ad48621b0 100644--- a/mcp-host/src/__tests__/integration/crossDeviceSessions.test.ts+++ b/mcp-host/src/__tests__/integration/crossDeviceSessions.test.ts@@ -115,7 +115,6 @@ function makeApp(convManager: ConversationManager) {latestTurnNumber: turns.at(-1)?.number,hasMoreBefore: Boolean(turns[0] && turns[0].number > 1),hasMoreAfter: Boolean(turns.at(-1) && turns.at(-1)!.number < conversation.turns.length),- revision: `${conversation.turns.length}:${conversation.updated_at.getTime()}`,turns: turns.map(t => ({number: t.number,user_input: t.user_input,diff --git a/mcp-host/src/core/conversation/conversationStore.ts b/mcp-host/src/core/conversation/conversationStore.tsindex 789bf7a8b..7c9eca0f9 100644--- a/mcp-host/src/core/conversation/conversationStore.ts+++ b/mcp-host/src/core/conversation/conversationStore.ts@@ -81,6 +81,7 @@ export interface ConversationSessionSummary {activeTaskId?: stringpendingApproval?: Pick<PendingApproval, 'request_id' | 'tool_name'>turnCount: number+ messageCount: numberlastActivityAt: Dateinput_tokens?: numberoutput_tokens?: number@@ -91,7 +92,7 @@ export interface ConversationSessionSummary {export interface ConversationSessionMessages extends Omit<ConversationSessionSummary,- 'lastActivityAt' | 'turnCount'+ 'lastActivityAt' | 'turnCount' | 'messageCount'> {turns: Turn[]totalTurns: number@@ -400,6 +401,11 @@ export class InMemoryConversationStore implements ConversationStore {}: undefined,turnCount: conversation.turns.length,+ messageCount: conversation.turns.reduce(+ (total, turn) =>+ total + 1 + (turn.response === undefined ? 0 : 1) + turn.tool_calls.length,+ 0+ ),lastActivityAt: conversation.updated_at,input_tokens: conversation.input_tokens,output_tokens: conversation.output_tokens,diff --git a/mcp-host/src/core/conversation/persistence/__tests__/sqliteConversationStore.test.ts b/mcp-host/src/core/conversation/persistence/__tests__/sqliteConversationStore.test.tsindex 8c0def362..ad11fb835 100644--- a/mcp-host/src/core/conversation/persistence/__tests__/sqliteConversationStore.test.ts+++ b/mcp-host/src/core/conversation/persistence/__tests__/sqliteConversationStore.test.ts@@ -648,6 +648,37 @@ describe('SqliteConversationStore — active_task_id (D.1)', () => {}})+ it('advances durable turn numbering after a failed turn', 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-1')+ await manager.completeTurn(conv, 'done')+ await manager.startTurn(conv, 'failed', 'task-2')+ await manager.failTurn(conv)+ await manager.startTurn(conv, 'retry', 'task-3')+ await manager.completeTurn(conv, 'recovered')+ await handle.persistQueue.drainSessionKey(SESSION_KEY)++ const turnNumbers = handle.worker.db+ .prepare(+ 'SELECT DISTINCT turn_number FROM messages WHERE session_id = ? ORDER BY turn_number'+ )+ .all(conv.id) as Array<{ turn_number: number }>+ expect(turnNumbers.map(row => row.turn_number)).toEqual([1, 2, 3])++ handle.store['cache'].clear()+ const summaries = await handle.store.listSessionSummariesByPrefix('u-1:rpc:')+ expect(summaries[0]?.turnCount).toBe(3)+ const messages = await handle.store.getSessionMessagesByKey(SESSION_KEY, 'u-1:rpc:')+ expect(messages?.totalTurns).toBe(3)+ expect(messages?.turns.map(turn => turn.number)).toEqual([1, 2, 3])+ } finally {+ await handle.shutdown()+ }+ })+it('suspendForApproval preserves active_task_id (same task across approval)', 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 ae0485f33..3942be6ff 100644--- a/mcp-host/src/core/conversation/persistence/sqliteConversationStore.ts+++ b/mcp-host/src/core/conversation/persistence/sqliteConversationStore.ts@@ -375,11 +375,13 @@ export class SqliteConversationStore implements ConversationStore {const out: ConversationSessionSummary[] = []for (const row of rows) {const key = row.session.session_key+ const cached = this.cache.get(key)const rest = key.slice(prefix.length)const colonIdx = rest.indexOf(':')if (colonIdx < 0) continue- const state =- row.session.state === ConversationState.Processing+ const state = cached+ ? cached.state+ : row.session.state === ConversationState.Processing? ConversationState.Processing: row.session.state === ConversationState.AwaitingApproval? ConversationState.AwaitingApproval@@ -389,14 +391,22 @@ export class SqliteConversationStore implements ConversationStore {agent: rest.slice(0, colonIdx),chatId: rest.slice(colonIdx + 1),state,- activeTaskId: row.session.active_task_id ?? undefined,- pendingApproval: row.pending_approval- ? {- request_id: row.pending_approval.request_id,- tool_name: row.pending_approval.tool_name,- }- : undefined,+ activeTaskId: cached ? cached.activeTaskId : (row.session.active_task_id ?? undefined),+ pendingApproval: cached+ ? cached.pending_approval+ ? {+ request_id: cached.pending_approval.request_id,+ tool_name: cached.pending_approval.tool_name,+ }+ : undefined+ : row.pending_approval+ ? {+ request_id: row.pending_approval.request_id,+ tool_name: row.pending_approval.tool_name,+ }+ : undefined,turnCount: Math.max(0, Math.floor(row.turn_count ?? 0)),+ messageCount: Math.max(0, Math.floor(row.session.message_count ?? 0)),lastActivityAt: new Date(row.last_activity_at * 1000),input_tokens: row.session.input_tokens,output_tokens: row.session.output_tokens,@@ -831,6 +841,8 @@ 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 {diff --git a/mcp-host/src/db/statements.ts b/mcp-host/src/db/statements.tsindex bac9aac95..d82d6d45c 100644--- a/mcp-host/src/db/statements.ts+++ b/mcp-host/src/db/statements.ts@@ -202,14 +202,16 @@ export function prepareStatements(db: Database): PreparedStatements {) AS turn_count,(SELECT pa.request_id- FROM pending_approvals pa+ FROM pending_approvals paWHERE pa.session_id = s.id+ ORDER BY pa.registered_at ASC, pa.request_id ASCLIMIT 1) AS pending_request_id,(SELECT pa.tool_name- FROM pending_approvals pa+ FROM pending_approvals paWHERE pa.session_id = s.id+ ORDER BY pa.registered_at ASC, pa.request_id ASCLIMIT 1) AS pending_tool_nameFROM sessions s@@ -228,7 +230,7 @@ export function prepareStatements(db: Database): PreparedStatements {LIMIT @limit`),selectSessionTurnBounds: db.prepare(`- SELECT COUNT(DISTINCT COALESCE(turn_number, 0)) AS total_turns,+ SELECT MAX(COALESCE(turn_number, 0)) AS total_turns,MIN(COALESCE(turn_number, 0)) AS first_turn_number,MAX(COALESCE(turn_number, 0)) AS last_turn_number,MAX(timestamp) AS last_activity_atdiff --git a/mcp-host/src/db/worker/dispatcher.ts b/mcp-host/src/db/worker/dispatcher.tsindex 270ba444b..42bef40ea 100644--- a/mcp-host/src/db/worker/dispatcher.ts+++ b/mcp-host/src/db/worker/dispatcher.ts@@ -609,7 +609,14 @@ export async function dispatch(op: WorkerOp, deps: DispatcherDeps): Promise<unkncase 'list_session_summaries_by_prefix': {const prefixStart = op.sessionKeyPrefix- const prefixEnd = `${op.sessionKeyPrefix}\uffff`+ const finalCodePoint = op.sessionKeyPrefix.codePointAt(op.sessionKeyPrefix.length - 1)+ if (finalCodePoint === undefined || finalCodePoint >= 0x10ffff) {+ throw new Error('Session key prefix must have a finite lexicographic upper bound')+ }+ const prefixEnd = `${op.sessionKeyPrefix.slice(+ 0,+ op.sessionKeyPrefix.length - (finalCodePoint > 0xffff ? 2 : 1)+ )}${String.fromCodePoint(finalCodePoint + 1)}`const rows = s.selectSessionSummariesByPrefix.all({prefix_start: prefixStart,prefix_end: prefixEnd,diff --git a/mcp-host/src/main.ts b/mcp-host/src/main.tsindex ebd8d2bf5..431b1fdd8 100644--- a/mcp-host/src/main.ts+++ b/mcp-host/src/main.ts@@ -2100,6 +2100,7 @@ async function startRPCServer(): Promise<void> {agent: summary.agent,chatId: summary.chatId,turnCount: summary.turnCount,+ messageCount: summary.messageCount,lastActivityAt: summary.lastActivityAt.toISOString(),...sessionStateView(summary),})),@@ -2145,7 +2146,6 @@ async function startRPCServer(): Promise<void> {(latestTurnNumber !== undefined? latestTurnNumber < lastConversationTurn: query.beforeTurn !== undefined),- revision: `${page.totalTurns}:${page.updatedAt.getTime()}`,turns: turns.map(t => ({number: t.number,user_input: t.user_input,diff --git a/mcp-host/src/server/__tests__/sessionsRoutes.test.ts b/mcp-host/src/server/__tests__/sessionsRoutes.test.tsindex 2cc61008a..1694f8c1e 100644--- a/mcp-host/src/server/__tests__/sessionsRoutes.test.ts+++ b/mcp-host/src/server/__tests__/sessionsRoutes.test.ts@@ -71,7 +71,7 @@ describe('handleSessionsListRoute', () => {],})expect(sessionsListHandler).toHaveBeenCalledWith('user-1', {- limit: 50,+ limit: undefined,cursor: undefined,})})@@ -111,6 +111,20 @@ describe('handleSessionsListRoute', () => {expect(sessionsListHandler).not.toHaveBeenCalled()})+ it('rejects malformed limits instead of silently changing the request', async () => {+ const sessionsListHandler: SessionsListHandler = vi.fn()+ const req = {+ ...makeReqWithAuth('user-1'),+ query: { limit: 'not-a-number' },+ } as unknown as Request+ const captured = makeRes()++ await handleSessionsListRoute(req, captured.res, makeHandlers({ sessionsListHandler }))++ expect(captured.statusCode).toBe(400)+ expect(sessionsListHandler).not.toHaveBeenCalled()+ })+it('returns 501 when sessionsListHandler is not configured', async () => {const req = makeReqWithAuth('user-1')const captured = makeRes()@@ -155,7 +169,6 @@ describe('handleSessionMessagesRoute', () => {latestTurnNumber: 1,hasMoreBefore: false,hasMoreAfter: false,- revision: '1:1776816000000',turns: [{ number: 1, user_input: 'hello', response: 'hi', started_at: '2026-04-22T00:00:00Z' },],@@ -172,13 +185,12 @@ describe('handleSessionMessagesRoute', () => {latestTurnNumber: 1,hasMoreBefore: false,hasMoreAfter: false,- revision: '1:1776816000000',turns: [{ number: 1, user_input: 'hello', response: 'hi', started_at: '2026-04-22T00:00:00Z' },],})expect(sessionMessagesHandler).toHaveBeenCalledWith('user-1', 'chatllm', 'c1', {- limit: 80,+ limit: undefined,beforeTurn: undefined,afterTurn: undefined,})@@ -193,7 +205,6 @@ describe('handleSessionMessagesRoute', () => {latestTurnNumber: 20,hasMoreBefore: true,hasMoreAfter: true,- revision: '30:1776816000000',turns: [],})const req = {@@ -226,6 +237,25 @@ describe('handleSessionMessagesRoute', () => {expect(sessionMessagesHandler).not.toHaveBeenCalled()})+ it.each([+ ['beforeTurn', 'abc'],+ ['beforeTurn', '0'],+ ['afterTurn', 'abc'],+ ['afterTurn', '-1'],+ ])('rejects malformed %s cursors', async (name, value) => {+ const sessionMessagesHandler: SessionMessagesHandler = vi.fn()+ const req = {+ ...makeReqWithParams('user-1', 'chatllm', 'c1'),+ query: { [name]: value },+ } as unknown as Request+ const captured = makeRes()++ await handleSessionMessagesRoute(req, captured.res, makeHandlers({ sessionMessagesHandler }))++ expect(captured.statusCode).toBe(400)+ expect(sessionMessagesHandler).not.toHaveBeenCalled()+ })+it('returns 404 with the canonical body when the session does not exist', async () => {const sessionMessagesHandler: SessionMessagesHandler = vi.fn().mockReturnValue(null)const req = makeReqWithParams('user-1', 'chatllm', 'c-missing')diff --git a/mcp-host/src/server/routes.ts b/mcp-host/src/server/routes.tsindex eac0a4c7a..007092631 100644--- a/mcp-host/src/server/routes.ts+++ b/mcp-host/src/server/routes.ts@@ -1106,16 +1106,21 @@ export async function handleSessionsListRoute(json(res, 501, { error: 'Sessions handler not configured' })return}- const rawLimit = typeof req.query.limit === 'string' ? Number(req.query.limit) : undefined- const limit =- rawLimit === undefined- ? 50- : Math.min(Math.max(Number.isFinite(rawLimit) ? Math.floor(rawLimit) : 50, 1), 100)const cursor = parseSessionsCursorParam(req.query.cursor)if (cursor === null) {badRequest(res, 'Invalid sessions cursor')return}+ const rawLimit = typeof req.query.limit === 'string' ? Number(req.query.limit) : undefined+ if (+ req.query.limit !== undefined &&+ (!Number.isFinite(rawLimit) || Math.floor(rawLimit!) < 1)+ ) {+ badRequest(res, 'limit must be a positive integer')+ return+ }+ const limit =+ rawLimit === undefined ? (cursor ? 50 : undefined) : Math.min(Math.floor(rawLimit), 100)const result = await handlers.sessionsListHandler(caller.userId, { limit, cursor })json(res, 200, result)} catch (error) {@@ -1207,22 +1212,39 @@ export async function handleSessionMessagesRoute(typeof req.query.beforeTurn === 'string' ? Number(req.query.beforeTurn) : undefinedconst rawAfterTurn =typeof req.query.afterTurn === 'string' ? Number(req.query.afterTurn) : undefined+ if (+ req.query.beforeTurn !== undefined &&+ (!Number.isFinite(rawBeforeTurn) || Math.floor(rawBeforeTurn!) < 1)+ ) {+ badRequest(res, 'beforeTurn must be a positive integer')+ return+ }+ if (+ req.query.afterTurn !== undefined &&+ (!Number.isFinite(rawAfterTurn) || Math.floor(rawAfterTurn!) < 0)+ ) {+ badRequest(res, 'afterTurn must be a non-negative integer')+ return+ }if (rawBeforeTurn !== undefined && rawAfterTurn !== undefined) {badRequest(res, 'beforeTurn and afterTurn are mutually exclusive')return}+ if (+ req.query.limit !== undefined &&+ (!Number.isFinite(rawLimit) || Math.floor(rawLimit!) < 1)+ ) {+ badRequest(res, 'limit must be a positive integer')+ return+ }const limit =rawLimit === undefined- ? 80- : Math.min(Math.max(Number.isFinite(rawLimit) ? Math.floor(rawLimit) : 80, 1), 200)- const beforeTurn =- rawBeforeTurn !== undefined && Number.isFinite(rawBeforeTurn)- ? Math.max(1, Math.floor(rawBeforeTurn))- : undefined- const afterTurn =- rawAfterTurn !== undefined && Number.isFinite(rawAfterTurn)- ? Math.max(0, Math.floor(rawAfterTurn))- : undefined+ ? rawBeforeTurn !== undefined || rawAfterTurn !== undefined+ ? 80+ : undefined+ : Math.min(Math.floor(rawLimit), 200)+ const beforeTurn = rawBeforeTurn !== undefined ? Math.floor(rawBeforeTurn) : undefined+ const afterTurn = rawAfterTurn !== undefined ? Math.floor(rawAfterTurn) : undefinedconst result = await handlers.sessionMessagesHandler(caller.userId, agent, chatId, {limit,beforeTurn,diff --git a/mcp-host/src/server/types.ts b/mcp-host/src/server/types.tsindex 0b35c2e56..f459332cf 100644--- a/mcp-host/src/server/types.ts+++ b/mcp-host/src/server/types.ts@@ -488,6 +488,7 @@ export type SessionsListItem = {agent: stringchatId: stringturnCount: number+ messageCount?: numberlastActivityAt: string} & SessionStateWire@@ -535,7 +536,6 @@ export type SessionMessagesResult = {latestTurnNumber?: numberhasMoreBefore: booleanhasMoreAfter: boolean- revision: stringturns: Array<{number: numberuser_input: stringdiff --git a/rpc-proxy/package-lock.json b/rpc-proxy/package-lock.jsonindex 4370fb52b..4cbf75686 100644--- a/rpc-proxy/package-lock.json+++ b/rpc-proxy/package-lock.json@@ -1,12 +1,12 @@{"name": "clerum-rpc-proxy",- "version": "0.1.53",+ "version": "0.1.54","lockfileVersion": 3,"requires": true,"packages": {"": {"name": "clerum-rpc-proxy",- "version": "0.1.53",+ "version": "0.1.54","dependencies": {"cors": "^2.8.5","express": "^4.21.2",diff --git a/rpc-proxy/package.json b/rpc-proxy/package.jsonindex bf75abbd1..7ef7480ff 100644--- a/rpc-proxy/package.json+++ b/rpc-proxy/package.json@@ -1,6 +1,6 @@{"name": "clerum-rpc-proxy",- "version": "0.1.53",+ "version": "0.1.54","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 79f7b6fe3..f1c2c0541 100644--- a/rpc-proxy/src/__tests__/sessions-passthrough.test.ts+++ b/rpc-proxy/src/__tests__/sessions-passthrough.test.ts@@ -153,7 +153,6 @@ describe('GET /rpc/hosts/:hostRef/sessions/:agent/:chatId/messages — passthroutotalTurns: 10,hasMoreBefore: true,hasMoreAfter: false,- revision: '10:1',turns: [],}),} as unknown as Response)