Evenfire is an intelligence layer platform for running LLM agents that take real actions, on your infrastructure
TypeScript
fix: address desktop loading review feedback
Josué062ce29a5156
diff --git a/control-api/package-lock.json b/control-api/package-lock.jsonindex ff14bc2b4..96de124bf 100644--- a/control-api/package-lock.json+++ b/control-api/package-lock.json@@ -1,12 +1,12 @@{"name": "clerum-control-api",- "version": "0.1.367",+ "version": "0.1.366","lockfileVersion": 3,"requires": true,"packages": {"": {"name": "clerum-control-api",- "version": "0.1.367",+ "version": "0.1.366","dependencies": {"@clerum/image-policy": "file:../packages/image-policy","@clerum/llm-providers": "file:../packages/llm-providers",diff --git a/control-api/package.json b/control-api/package.jsonindex 2a655b11c..c394516e6 100644--- a/control-api/package.json+++ b/control-api/package.json@@ -1,6 +1,6 @@{"name": "clerum-control-api",- "version": "0.1.367",+ "version": "0.1.366","description": "Internal Clerum control plane REST API + UI for managing CRDs and secrets","main": "dist/main.js","engines": {diff --git a/control-ui/package-lock.json b/control-ui/package-lock.jsonindex ee91beb53..aa10851df 100644--- a/control-ui/package-lock.json+++ b/control-ui/package-lock.json@@ -1,12 +1,12 @@{"name": "clerum-control-ui",- "version": "0.1.351",+ "version": "0.1.352","lockfileVersion": 3,"requires": true,"packages": {"": {"name": "clerum-control-ui",- "version": "0.1.351",+ "version": "0.1.352","dependencies": {"@clerum/llm-providers": "file:../packages/llm-providers","@clerum/workflow-recipe-capability-policy": "file:../packages/workflow-recipe-capability-policy",diff --git a/control-ui/package.json b/control-ui/package.jsonindex e41434edb..8829c1a49 100644--- a/control-ui/package.json+++ b/control-ui/package.json@@ -1,6 +1,6 @@{"name": "clerum-control-ui",- "version": "0.1.351",+ "version": "0.1.352","private": true,"scripts": {"dev": "NEXT_IGNORE_INCORRECT_LOCKFILE=1 next dev",diff --git a/desktop-app/package-lock.json b/desktop-app/package-lock.jsonindex b8086e168..6a2d15a09 100644--- a/desktop-app/package-lock.json+++ b/desktop-app/package-lock.json@@ -1,12 +1,12 @@{"name": "evenfire",- "version": "0.1.326",+ "version": "0.1.327","lockfileVersion": 3,"requires": true,"packages": {"": {"name": "evenfire",- "version": "0.1.326",+ "version": "0.1.327","license": "MPL-2.0","dependencies": {"@tanstack/react-query": "5.100.10",diff --git a/desktop-app/package.json b/desktop-app/package.jsonindex 2743ff9ff..deb4d3990 100644--- a/desktop-app/package.json+++ b/desktop-app/package.json@@ -1,7 +1,7 @@{"name": "evenfire","productName": "Evenfire",- "version": "0.1.326",+ "version": "0.1.327","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 a28d05c51..c2d34c69b 100644--- a/desktop-app/src/__tests__/appService.bootstrap.test.ts+++ b/desktop-app/src/__tests__/appService.bootstrap.test.ts@@ -314,7 +314,7 @@ describe('AppService invitation configuration lookup', () => {expect(clearSessionToken).toHaveBeenCalledWith(resolveEnvKey('https://api.example.com'))})- it('keeps a saved token when startup session restore is forbidden', async () => {+ it('clears a saved token when startup session restore is forbidden', async () => {const configPath = await createTempConfigPath('clerum-desktop-restore-forbidden')await fs.writeFile(configPath,@@ -356,14 +356,9 @@ describe('AppService invitation configuration lookup', () => {clear: vi.fn(),} as never- const warn = vi.spyOn(console, 'warn').mockImplementation(() => undefined)- try {- await expect(service.initialize()).resolves.toEqual({ authenticated: false, me: null })+ await expect(service.initialize()).resolves.toEqual({ authenticated: false, me: null })- expect(clearSessionToken).not.toHaveBeenCalled()- } finally {- warn.mockRestore()- }+ expect(clearSessionToken).toHaveBeenCalled()})it('persists a manually saved runtime environment', async () => {diff --git a/desktop-app/src/__tests__/chatStore.test.ts b/desktop-app/src/__tests__/chatStore.test.tsindex e8ae2343a..54cc1934a 100644--- a/desktop-app/src/__tests__/chatStore.test.ts+++ b/desktop-app/src/__tests__/chatStore.test.ts@@ -34,6 +34,12 @@ function chatPagesDir(chatId: string): string {return join(chatCacheDir(chatId), 'pages')}+function transientFileReadError(code = 'EMFILE'): NodeJS.ErrnoException {+ const err = new Error(code) as NodeJS.ErrnoException+ err.code = code+ return err+}+async function readJsonFile<T = Record<string, unknown>>(path: string): Promise<T> {return JSON.parse(await fs.readFile(path, 'utf-8')) as T}@@ -371,6 +377,75 @@ describe('messages', () => {expect(reloaded.map(message => message.id)).toEqual(['old-0', 'old-1', 'old-2', 'old-3'])})+ it('aborts append instead of resetting the transcript on transient meta read failure', async () => {+ const pagedStore = new ChatStore(tempDir, {+ pageSize: 5,+ maxLocalSyncedMessages: Number.POSITIVE_INFINITY,+ })+ await pagedStore.createChat('agent-1', 'meta-read-failure')+ await pagedStore.saveMessages('agent-1', 'meta-read-failure', [+ { id: 'old-0', role: 'user', content: 'old-0', timestamp: 0 },+ { id: 'old-1', role: 'assistant', content: 'old-1', timestamp: 1 },+ ])++ const originalReadFile = fs.readFile.bind(fs)+ let injected = false+ vi.spyOn(fs, 'readFile').mockImplementation(async (...args) => {+ const filePath = String(args[0])+ if (!injected && filePath.endsWith(join('meta-read-failure', 'meta.json'))) {+ injected = true+ throw transientFileReadError()+ }+ return originalReadFile(...(args as Parameters<typeof fs.readFile>))+ })++ await expect(+ pagedStore.appendMessages('agent-1', 'meta-read-failure', [+ { id: 'new-0', role: 'user', content: 'new-0', timestamp: 2 },+ ])+ ).rejects.toThrow()++ vi.restoreAllMocks()+ const reloaded = await pagedStore.loadMessages('agent-1', 'meta-read-failure')+ expect(reloaded.map(message => message.id)).toEqual(['old-0', 'old-1'])+ })++ it('aborts append instead of truncating the last page on transient page read failure', async () => {+ const pagedStore = new ChatStore(tempDir, {+ pageSize: 10,+ maxLocalSyncedMessages: Number.POSITIVE_INFINITY,+ })+ await pagedStore.createChat('agent-1', 'page-read-failure')+ const originalMessages = Array.from({ length: 5 }, (_, i) => ({+ id: `old-${i}`,+ role: 'user' as const,+ content: `old-${i}`,+ timestamp: i,+ }))+ await pagedStore.saveMessages('agent-1', 'page-read-failure', originalMessages)++ const originalReadFile = fs.readFile.bind(fs)+ let injected = false+ vi.spyOn(fs, 'readFile').mockImplementation(async (...args) => {+ const filePath = String(args[0])+ if (!injected && filePath.includes('page-read-failure') && filePath.endsWith('000001.json')) {+ injected = true+ throw transientFileReadError()+ }+ return originalReadFile(...(args as Parameters<typeof fs.readFile>))+ })++ await expect(+ pagedStore.appendMessages('agent-1', 'page-read-failure', [+ { id: 'new-0', role: 'assistant', content: 'new-0', timestamp: 6 },+ ])+ ).rejects.toThrow()++ vi.restoreAllMocks()+ const reloaded = await pagedStore.loadMessages('agent-1', 'page-read-failure')+ expect(reloaded.map(message => message.id)).toEqual(originalMessages.map(message => message.id))+ })+it('recovers the previous paged snapshot after an interrupted directory switch', async () => {const pagedStore = new ChatStore(tempDir, {pageSize: 2,@@ -415,6 +490,51 @@ describe('messages', () => {await expect(fs.access(`${chatCacheDir('next-recovery')}.previous-test`)).rejects.toThrow()})+ it('uses the newest valid snapshot group instead of preferring stale next snapshots', async () => {+ const pagedStore = new ChatStore(tempDir, {+ pageSize: 2,+ maxLocalSyncedMessages: Number.POSITIVE_INFINITY,+ })+ await pagedStore.createChat('agent-1', 'snapshot-order')+ await pagedStore.saveMessages('agent-1', 'snapshot-order', [+ { id: 'active-0', role: 'user', content: 'active-0', timestamp: 0 },+ ])++ const staleNext = `${chatCacheDir('snapshot-order')}.next-old`+ const freshPrevious = `${chatCacheDir('snapshot-order')}.previous-new`+ await writePagedSnapshotDir('snapshot-order', staleNext, [+ { id: 'stale-0', role: 'user', content: 'stale-0', timestamp: 1 },+ ])+ await writePagedSnapshotDir('snapshot-order', freshPrevious, [+ { id: 'fresh-0', role: 'assistant', content: 'fresh-0', timestamp: 2 },+ ])+ const oldTime = new Date('2026-01-01T00:00:00Z')+ const freshTime = new Date('2026-01-02T00:00:00Z')+ await fs.utimes(staleNext, oldTime, oldTime)+ await fs.utimes(freshPrevious, freshTime, freshTime)+ await fs.writeFile(chatMetaPath('snapshot-order'), 'not-json')++ const reloaded = await pagedStore.loadMessages('agent-1', 'snapshot-order')+ expect(reloaded.map(message => message.id)).toEqual(['fresh-0'])+ })++ it('does not promote an incomplete snapshot whose page files are missing', async () => {+ const pagedStore = new ChatStore(tempDir, {+ pageSize: 2,+ maxLocalSyncedMessages: Number.POSITIVE_INFINITY,+ })+ await pagedStore.createChat('agent-1', 'incomplete-snapshot')+ const incomplete = `${chatCacheDir('incomplete-snapshot')}.previous-test`+ await writePagedSnapshotDir('incomplete-snapshot', incomplete, [+ { id: 'backup-0', role: 'user', content: 'backup-0', timestamp: 0 },+ ])+ await fs.rm(join(incomplete, 'pages', '000001.json'), { force: true })++ const reloaded = await pagedStore.loadMessages('agent-1', 'incomplete-snapshot')+ expect(reloaded).toEqual([])+ await expect(fs.access(chatMetaPath('incomplete-snapshot'))).rejects.toThrow()+ })+it('cleans stale snapshot siblings when the active paged snapshot is healthy', async () => {const pagedStore = new ChatStore(tempDir, {pageSize: 2,@@ -434,6 +554,27 @@ describe('messages', () => {await expect(fs.access(`${chatCacheDir('stale-snapshots')}.previous-stale`)).rejects.toThrow()})+ it('deletes snapshot siblings so removed chats cannot be recovered later', async () => {+ const pagedStore = new ChatStore(tempDir, {+ pageSize: 2,+ maxLocalSyncedMessages: Number.POSITIVE_INFINITY,+ })+ await pagedStore.createChat('agent-1', 'delete-siblings')+ await pagedStore.saveMessages('agent-1', 'delete-siblings', [+ { id: 'm0', role: 'user', content: 'msg-0', timestamp: 0 },+ ])+ await writePagedSnapshotDir(+ 'delete-siblings',+ `${chatCacheDir('delete-siblings')}.previous-test`,+ [{ id: 'backup-0', role: 'user', content: 'backup-0', timestamp: 1 }]+ )++ await pagedStore.deleteChat('agent-1', 'delete-siblings')++ expect(await pagedStore.loadMessages('agent-1', 'delete-siblings')).toEqual([])+ await expect(fs.access(`${chatCacheDir('delete-siblings')}.previous-test`)).rejects.toThrow()+ })+it('prunes only old pages whose messages are known to exist on the server', async () => {const prunedStore = new ChatStore(tempDir, {pageSize: 2,diff --git a/desktop-app/src/appService.ts b/desktop-app/src/appService.tsindex 06f47e0a5..b5ec081d8 100644--- a/desktop-app/src/appService.ts+++ b/desktop-app/src/appService.ts@@ -330,7 +330,10 @@ export class AppService {}private static isRejectedStoredSessionError(error: unknown): boolean {- return error instanceof ApiError && error.status === 401+ return (+ error instanceof ApiError &&+ (error.status === 401 || error.status === 403 || error.status === 410)+ )}/**diff --git a/desktop-app/src/chatStore.ts b/desktop-app/src/chatStore.tsindex eea544794..90da33b84 100644--- a/desktop-app/src/chatStore.ts+++ b/desktop-app/src/chatStore.ts@@ -42,6 +42,13 @@ interface ChatPageFile {messages: ChatMessage[]}+interface SnapshotCandidate {+ dir: string+ kind: 'next' | 'previous'+ token: string+ mtimeMs: number+}+function normalizePositiveInteger(value: number | undefined, fallback: number): number {if (value === undefined) return fallbackif (!Number.isFinite(value)) return fallback@@ -69,6 +76,14 @@ function serverTurnNumber(message: ChatMessage): number | undefined {return Number.isFinite(message.serverTurnNumber) ? message.serverTurnNumber : undefined}+function isNotFoundError(err: unknown): boolean {+ return (err as NodeJS.ErrnoException | undefined)?.code === 'ENOENT'+}++function isUnsafeSegmentError(err: unknown): boolean {+ return err instanceof Error && /unsafe path segment/.test(err.message)+}+function aggregateMessages(messages: ChatMessage[]): Pick<ChatMetadata, 'errorCount' | 'toolCallCount'> {@@ -133,6 +148,7 @@ export class ChatStore {*/private indexChains = new Map<string, Promise<unknown>>()private chatChains = new Map<string, Promise<unknown>>()+ private cleanedSnapshotSiblingKeys = new Set<string>()private serialize<T>(chains: Map<string, Promise<unknown>>,@@ -160,6 +176,10 @@ export class ChatStore {return this.serialize(this.chatChains, JSON.stringify([agentRef, chatId]), fn)}+ private chatSnapshotCleanupKey(agentRef: string, chatId: string): string {+ return JSON.stringify([agentRef, chatId])+ }+private agentDir(agentRef: string): string {assertSafeSegment('agentRef', agentRef)return join(this.baseDir, agentRef)@@ -182,7 +202,7 @@ export class ChatStore {private chatSnapshotSiblingPath(agentRef: string,chatId: string,- kind: 'next' | 'previous',+ kind: 'next' | 'previous' | 'corrupt',token: string): string {assertSafeSegment('chatId', chatId)@@ -248,25 +268,34 @@ export class ChatStore {metaPath: string,chatId: string): Promise<PagedChatMeta | null> {+ let raw: string+ try {+ raw = await fs.readFile(metaPath, 'utf-8')+ } catch (err) {+ if (isNotFoundError(err)) return null+ throw err+ }+try {- const raw = await fs.readFile(metaPath, 'utf-8')const parsed = JSON.parse(raw) as PagedChatMetaif (parsed?.version !== PAGED_CHAT_VERSION ||parsed.chatId !== chatId ||!Array.isArray(parsed.pages)) {- return null+ throw new Error('Invalid paged chat metadata')+ }+ if (parsed.pages.some(page => !PAGE_FILE_PATTERN.test(page.file))) {+ throw new Error('Invalid paged chat metadata page reference')}- if (parsed.pages.some(page => !PAGE_FILE_PATTERN.test(page.file))) return nullreturn this.finalizePagedMeta({...parsed,pageSize: normalizePositiveInteger(parsed.pageSize, this.pageSize),messageCount: Math.max(0, Math.floor(parsed.messageCount ?? 0)),localMessageCount: Math.max(0, Math.floor(parsed.localMessageCount ?? 0)),})- } catch {- return null+ } catch (err) {+ throw new Error(`Unable to read paged chat metadata for ${chatId}`, { cause: err })}}@@ -274,13 +303,22 @@ export class ChatStore {agentRef: string,chatId: string): Promise<ChatMessage[] | null> {+ let raw: string+ try {+ raw = await fs.readFile(this.chatFilePath(agentRef, chatId), 'utf-8')+ } catch (err) {+ if (isNotFoundError(err)) return null+ throw err+ }+try {- const raw = await fs.readFile(this.chatFilePath(agentRef, chatId), 'utf-8')const file = JSON.parse(raw) as ChatFile- if (!file || !Array.isArray(file.messages)) return null+ if (!file || !Array.isArray(file.messages)) {+ throw new Error('Invalid legacy chat file')+ }return file.messages- } catch {- return null+ } catch (err) {+ throw new Error(`Unable to read legacy chat file for ${chatId}`, { cause: err })}}@@ -289,19 +327,38 @@ export class ChatStore {chatId: string,page: ChatPageEntry): Promise<ChatMessage[]> {+ return this.readPageMessagesAtPath(+ chatId,+ pageNumberFromFileName(page.file),+ this.chatPagePath(agentRef, chatId, page.file)+ )+ }++ private async readPageMessagesAtPath(+ chatId: string,+ pageNumber: number,+ pagePath: string+ ): Promise<ChatMessage[]> {+ let raw: string+ try {+ raw = await fs.readFile(pagePath, 'utf-8')+ } catch (err) {+ throw err+ }+try {- const raw = await fs.readFile(this.chatPagePath(agentRef, chatId, page.file), 'utf-8')const parsed = JSON.parse(raw) as ChatPageFileif (parsed?.version !== PAGED_CHAT_VERSION ||parsed.chatId !== chatId ||+ parsed.pageNumber !== pageNumber ||!Array.isArray(parsed.messages)) {- return []+ throw new Error('Invalid chat page file')}return parsed.messages- } catch {- return []+ } catch (err) {+ throw new Error(`Unable to read paged chat page for ${chatId}`, { cause: err })}}@@ -399,13 +456,30 @@ export class ChatStore {private async recoverPagedChatUnlocked(agentRef: string, chatId: string): Promise<void> {const activeDir = this.chatDirPath(agentRef, chatId)const chatsDir = join(this.agentDir(agentRef), 'chats')- const activeMeta = await this.readPagedMeta(agentRef, chatId)+ const cleanupKey = this.chatSnapshotCleanupKey(agentRef, chatId)+ let activeMeta: PagedChatMeta | null = null+ let activeReadError: unknown++ try {+ activeMeta = await this.readPagedMeta(agentRef, chatId)+ } catch (err) {+ activeReadError = err+ }if (activeMeta) {+ if (this.cleanedSnapshotSiblingKeys.has(cleanupKey)) returnawait this.removePagedChatSnapshotSiblings(chatsDir, chatId)+ this.cleanedSnapshotSiblingKeys.add(cleanupKey)return}+ if (!activeReadError) {+ const activeStat = await fs.stat(activeDir).catch(() => null)+ if (activeStat?.isDirectory()) {+ activeReadError = new Error(`Paged chat metadata missing for ${chatId}`)+ }+ }+let entries: Array<{ name: string; isDirectory: () => boolean }>try {entries = await fs.readdir(chatsDir, { withFileTypes: true })@@ -417,45 +491,80 @@ export class ChatStore {entries.filter(entry => entry.isDirectory()).map(async entry => {- const kind = entry.name.startsWith(`${chatId}.next-`)+ const nextPrefix = `${chatId}.next-`+ const previousPrefix = `${chatId}.previous-`+ const kind = entry.name.startsWith(nextPrefix)? 'next'- : entry.name.startsWith(`${chatId}.previous-`)+ : entry.name.startsWith(previousPrefix)? 'previous': nullif (!kind) return null+ const token =+ kind === 'next'+ ? entry.name.slice(nextPrefix.length)+ : entry.name.slice(previousPrefix.length)+ if (!token) return nullconst dir = join(chatsDir, entry.name)- const meta = await this.readPagedMetaAtPath(this.chatMetaPathFromChatDir(dir), chatId)- if (!meta) return null+ const meta = await this.readPagedMetaAtPath(+ this.chatMetaPathFromChatDir(dir),+ chatId+ ).catch(() => null)+ if (!meta || !(await this.isCompletePagedSnapshot(dir, chatId, meta))) return nullconst stat = await fs.stat(dir).catch(() => null)return {dir,kind,+ token,mtimeMs: stat?.mtimeMs ?? 0,}}))const validSnapshots = snapshots- .filter(- (snapshot): snapshot is { dir: string; kind: 'next' | 'previous'; mtimeMs: number } =>- snapshot !== null- )+ .filter((snapshot): snapshot is SnapshotCandidate => snapshot !== null).sort((a, b) => b.mtimeMs - a.mtimeMs)- const candidates = [- ...validSnapshots.filter(snapshot => snapshot.kind === 'next'),- ...validSnapshots.filter(snapshot => snapshot.kind === 'previous'),- ]+ const groups = new Map<+ string,+ { next?: SnapshotCandidate; previous?: SnapshotCandidate; mtimeMs: number }+ >()+ for (const snapshot of validSnapshots) {+ const group = groups.get(snapshot.token) ?? { mtimeMs: 0 }+ group[snapshot.kind] = snapshot+ group.mtimeMs = Math.max(group.mtimeMs, snapshot.mtimeMs)+ groups.set(snapshot.token, group)+ }+ const candidates = [...groups.values()]+ .sort((a, b) => b.mtimeMs - a.mtimeMs)+ .map(group => group.next ?? group.previous)+ .filter((snapshot): snapshot is SnapshotCandidate => Boolean(snapshot))for (const snapshot of candidates) {+ let corruptDir: string | null = nulltry {- await fs.rm(activeDir, { recursive: true, force: true })+ if (activeReadError) {+ corruptDir = this.chatSnapshotSiblingPath(agentRef, chatId, 'corrupt', randomUUID())+ await fs.rename(activeDir, corruptDir).catch(err => {+ if (!isNotFoundError(err)) throw err+ })+ } else {+ await fs.rm(activeDir, { recursive: true, force: true })+ }await fs.rename(snapshot.dir, activeDir)await this.removePagedChatSnapshotSiblings(chatsDir, chatId)+ if (corruptDir) {+ await fs.rm(corruptDir, { recursive: true, force: true }).catch(() => undefined)+ }+ this.cleanedSnapshotSiblingKeys.add(cleanupKey)return- } catch {+ } catch (err) {+ if (corruptDir) {+ await fs.rename(corruptDir, activeDir).catch(() => undefined)+ }// Try the next complete snapshot, if one exists.}}++ if (activeReadError) throw activeReadError}private async removePagedChatSnapshotSiblings(chatsDir: string, chatId: string): Promise<void> {@@ -478,11 +587,32 @@ export class ChatStore {)}+ private async isCompletePagedSnapshot(+ chatDir: string,+ chatId: string,+ meta: PagedChatMeta+ ): Promise<boolean> {+ const pagesDir = this.chatPagesDirFromChatDir(chatDir)+ for (const page of meta.pages) {+ try {+ const messages = await this.readPageMessagesAtPath(+ chatId,+ pageNumberFromFileName(page.file),+ this.chatPagePathFromPagesDir(pagesDir, page.file)+ )+ if (messages.length !== page.count) return false+ } catch {+ return false+ }+ }+ return true+ }+private async writePagedChatUnlocked(agentRef: string,chatId: string,messages: ChatMessage[],- options: { removeLegacy?: boolean } = {}+ options: { removeLegacy?: boolean; messageCount?: number } = {}): Promise<PagedChatMeta> {const chatDir = this.chatDirPath(agentRef, chatId)const snapshotToken = randomUUID()@@ -491,6 +621,7 @@ export class ChatStore {const pagesDir = this.chatPagesDirFromChatDir(stagingDir)let movedExistingSnapshot = false+ this.cleanedSnapshotSiblingKeys.delete(this.chatSnapshotCleanupKey(agentRef, chatId))await fs.mkdir(join(this.agentDir(agentRef), 'chats'), { recursive: true })await fs.rm(stagingDir, { recursive: true, force: true })await fs.mkdir(pagesDir, { recursive: true })@@ -519,7 +650,7 @@ export class ChatStore {version: PAGED_CHAT_VERSION,chatId,pageSize: this.pageSize,- messageCount: messages.length,+ messageCount: Math.max(messages.length, options.messageCount ?? 0),localMessageCount: messages.length,pages,}),@@ -564,7 +695,11 @@ export class ChatStore {const legacyMessages = await this.readLegacyMessages(agentRef, chatId)if (!legacyMessages) return null- return this.writePagedChatUnlocked(agentRef, chatId, legacyMessages, { removeLegacy: true })+ const migrated = await this.writePagedChatUnlocked(agentRef, chatId, legacyMessages, {+ removeLegacy: true,+ })+ await this.updateChatIndexFromMessages(agentRef, chatId, legacyMessages)+ return migrated}private async readMessagesFromPagedMeta(@@ -750,6 +885,8 @@ export class ChatStore {})await fs.rm(this.chatFilePath(agentRef, chatId), { force: true })await fs.rm(this.chatDirPath(agentRef, chatId), { recursive: true, force: true })+ await this.removePagedChatSnapshotSiblings(join(this.agentDir(agentRef), 'chats'), chatId)+ this.cleanedSnapshotSiblingKeys.delete(this.chatSnapshotCleanupKey(agentRef, chatId))})}@@ -765,28 +902,83 @@ export class ChatStore {if (!meta) return []return this.readMessagesFromPagedMeta(agentRef, chatId, meta, limit, offset)})+ } catch (err) {+ if (isUnsafeSegmentError(err) || isNotFoundError(err)) return []+ throw err+ }+ }++ private async updateChatIndexFromMessages(+ agentRef: string,+ chatId: string,+ messages: ChatMessage[],+ options: { preserveExistingTotals?: boolean } = {}+ ): Promise<void> {+ await this.serializeIndex(agentRef, async () => {+ const index = await this.getIndex(agentRef)+ const chat = index.chats.find(c => c.id === chatId)+ if (!chat) return++ const aggregate = aggregateMessages(messages)+ if (options.preserveExistingTotals) {+ chat.messageCount = Math.max(chat.messageCount ?? 0, messages.length)+ chat.errorCount = Math.max(chat.errorCount ?? 0, aggregate.errorCount ?? 0)+ chat.toolCallCount = Math.max(chat.toolCallCount ?? 0, aggregate.toolCallCount ?? 0)+ } else {+ chat.messageCount = messages.length+ Object.assign(chat, aggregate)+ }+ chat.updatedAt = new Date().toISOString()+ await this.saveIndex(agentRef, index)+ })+ }++ private async indexedMessageCount(agentRef: string, chatId: string): Promise<number | undefined> {+ try {+ const index = await this.getIndex(agentRef)+ return index.chats.find(chat => chat.id === chatId)?.messageCount} catch {- return []+ return undefined}}- async saveMessages(agentRef: string, chatId: string, messages: ChatMessage[]): Promise<void> {+ private async saveMessagesInternal(+ agentRef: string,+ chatId: string,+ messages: ChatMessage[],+ options: { preserveExistingTotals?: boolean } = {}+ ): Promise<void> {return this.serializeChat(agentRef, chatId, async () => {- await this.writePagedChatUnlocked(agentRef, chatId, messages, { removeLegacy: true })+ const indexedCount = options.preserveExistingTotals+ ? await this.indexedMessageCount(agentRef, chatId)+ : undefined+ await this.writePagedChatUnlocked(agentRef, chatId, messages, {+ removeLegacy: true,+ messageCount: Math.max(messages.length, indexedCount ?? 0),+ })- await this.serializeIndex(agentRef, async () => {- const index = await this.getIndex(agentRef)- const chat = index.chats.find(c => c.id === chatId)- if (chat) {- chat.messageCount = messages.length- Object.assign(chat, aggregateMessages(messages))- chat.updatedAt = new Date().toISOString()- await this.saveIndex(agentRef, index)- }+ await this.updateChatIndexFromMessages(agentRef, chatId, messages, {+ preserveExistingTotals: options.preserveExistingTotals,})})}+ async saveMessages(agentRef: string, chatId: string, messages: ChatMessage[]): Promise<void> {+ return this.saveMessagesInternal(agentRef, chatId, messages)+ }++ /**+ * Overwrite a chat's cached history with a server reconciliation window.+ *+ * 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.+ */+ async replaceMessages(agentRef: string, chatId: string, messages: ChatMessage[]): Promise<void> {+ await this.saveMessagesInternal(agentRef, chatId, messages, { preserveExistingTotals: true })+ }+async appendMessages(agentRef: string,chatId: string,@@ -813,15 +1005,6 @@ export class ChatStore {})}- /**- * Overwrite a chat's entire history (D.4 reconcile: the server is the source- * of truth, so on a diff the server's turns replace the local cache). Same- * on-disk effect as `saveMessages`, named for the reconcile intent.- */- async replaceMessages(agentRef: string, chatId: string, messages: ChatMessage[]): Promise<void> {- await this.saveMessages(agentRef, chatId, messages)- }-/*** Flag that a task terminated while the chat was not the active view (D.5).* Idempotent: a no-op when already flagged, so a noisy task can't spam FS writes.diff --git a/desktop-app/ui/src/components/agents/ChatThread.tsx b/desktop-app/ui/src/components/agents/ChatThread.tsxindex 461ff205c..991f3452a 100644--- a/desktop-app/ui/src/components/agents/ChatThread.tsx+++ b/desktop-app/ui/src/components/agents/ChatThread.tsx@@ -302,11 +302,22 @@ export function ChatThread({ showAgentLabel = false }: ChatThreadProps) {[groupedMessages])const messageGroupChunks = useMemo(() => {- const indexedGroups = groupedWithKeys.map((group, groupIndex) => ({ group, groupIndex }))- const chunks: (typeof indexedGroups)[] = []- for (let end = indexedGroups.length; end > 0; end -= VIRTUAL_MESSAGE_GROUPS_PER_CHUNK) {- const start = Math.max(0, end - VIRTUAL_MESSAGE_GROUPS_PER_CHUNK)- chunks.unshift(indexedGroups.slice(start, end))+ const chunks: Array<{+ chunkKey: string+ groups: Array<{ group: (typeof groupedWithKeys)[number]; groupIndex: number }>+ }> = []+ for (const [groupIndex, group] of groupedWithKeys.entries()) {+ const firstTurn = group.items[0]?.serverTurnNumber+ const chunkKey =+ firstTurn !== undefined+ ? `server-turns-${Math.floor((firstTurn - 1) / (VIRTUAL_MESSAGE_GROUPS_PER_CHUNK / 2))}`+ : `local-${group.groupKey}`+ const current = chunks.at(-1)+ if (current?.chunkKey === chunkKey) {+ current.groups.push({ group, groupIndex })+ } else {+ chunks.push({ chunkKey, groups: [{ group, groupIndex }] })+ }}return chunks}, [groupedWithKeys])@@ -565,11 +576,11 @@ export function ChatThread({ showAgentLabel = false }: ChatThreadProps) {{activeChatId &&messageGroupChunks.map((chunk, chunkIndex) => (<VirtualizedMessageChunk- key={chunk.at(-1)?.group.groupKey ?? `chunk-${chunkIndex}`}- estimatedHeight={Math.max(240, chunk.length * 180)}+ key={chunk.chunkKey}+ estimatedHeight={Math.max(240, chunk.groups.length * 180)}initiallyVisible={chunkIndex >= messageGroupChunks.length - 2}render={() =>- chunk.map(({ group, groupIndex }) => {+ chunk.groups.map(({ group, groupIndex }) => {const prevGroup = groupIndex > 0 ? groupedWithKeys[groupIndex - 1] : nullreturn (diff --git a/desktop-app/ui/src/hooks/__tests__/useAppController.test.tsx b/desktop-app/ui/src/hooks/__tests__/useAppController.test.tsxindex d7bb82aaa..803e9368b 100644--- a/desktop-app/ui/src/hooks/__tests__/useAppController.test.tsx+++ b/desktop-app/ui/src/hooks/__tests__/useAppController.test.tsx@@ -146,6 +146,24 @@ describe('scheduleAfterFirstPaint', () => {expect(task).toHaveBeenCalledTimes(1)})+ it('falls back to a timeout when animation frames are throttled', async () => {+ vi.useFakeTimers()+ const frames: FrameRequestCallback[] = []+ vi.stubGlobal('requestAnimationFrame', (callback: FrameRequestCallback) => {+ frames.push(callback)+ return frames.length+ })+ const task = vi.fn(async () => undefined)++ scheduleAfterFirstPaint(task)+ expect(task).not.toHaveBeenCalled()++ await vi.advanceTimersByTimeAsync(1000)++ expect(frames).toHaveLength(1)+ expect(task).toHaveBeenCalledTimes(1)+ })+it('runs session-bound deferred startup work when identity is unchanged', async () => {const frames: FrameRequestCallback[] = []vi.stubGlobal('requestAnimationFrame', (callback: FrameRequestCallback) => {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 4131fe720..427b5103b 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@@ -106,7 +106,7 @@ describe('switchToChat (unified, D.4)', () => {expect(result.current.chatMessages).toHaveLength(60)})- it('Phase 2 appends only the missing server delta to a durable-ID cache', async () => {+ it('Phase 2 persists the merged server delta to a durable-ID cache', async () => {clerum.chat.loadMessages.mockResolvedValue([{ id: 'turn-1-user', role: 'user' as const, content: 'q1', timestamp: 1 },])@@ -124,7 +124,7 @@ describe('switchToChat (unified, D.4)', () => {})expect(result.current.chatMessages).toHaveLength(4)- expect(clerum.chat.appendMessages).toHaveBeenCalledWith(+ expect(clerum.chat.replaceMessages).toHaveBeenCalledWith('agent-x','c2',expect.arrayContaining([expect.objectContaining({ id: 'turn-2-assistant' })])@@ -179,7 +179,7 @@ describe('switchToChat (unified, D.4)', () => {{ limit: 80, afterTurn: 2 })expect(result.current.chatMessages).toHaveLength(6)- expect(clerum.chat.appendMessages).toHaveBeenCalledWith(+ expect(clerum.chat.replaceMessages).toHaveBeenCalledWith('agent-x','delta-pages',expect.arrayContaining([@@ -644,9 +644,9 @@ describe('switchToChat (unified, D.4)', () => {await result.current.switchToChat('agent-x', 'z1')})- // With the zombie acked, the missing durable assistant message is appended.+ // With the zombie acked, the missing durable assistant message is persisted.expect(result.current.chatMessages).toHaveLength(2)- expect(clerum.chat.appendMessages).toHaveBeenCalledWith(+ expect(clerum.chat.replaceMessages).toHaveBeenCalledWith('agent-x','z1',expect.arrayContaining([expect.objectContaining({ id: 'turn-1-assistant' })])@@ -735,9 +735,9 @@ describe('switchToChat (unified, D.4)', () => {await result.current.switchToChat('agent-x', 'pa')})- // The retry landed the durable reply: delta appended, zombie acked, NOT offline.+ // The retry landed the durable reply: merged window persisted, zombie acked, NOT offline.expect(result.current.chatMessages).toHaveLength(2)- expect(clerum.chat.appendMessages).toHaveBeenCalledWith(+ expect(clerum.chat.replaceMessages).toHaveBeenCalledWith('agent-x','pa',expect.arrayContaining([expect.objectContaining({ id: 'turn-1-assistant' })])@@ -857,9 +857,9 @@ describe('switchToChat (unified, D.4)', () => {await sw})- // The residual was acked and the durable reply was appended to the cache.+ // The residual was acked and the durable reply was persisted to the cache.expect(result.current.chatMessages).toHaveLength(2)- expect(clerum.chat.appendMessages).toHaveBeenCalledWith(+ expect(clerum.chat.replaceMessages).toHaveBeenCalledWith('agent-x','pb',expect.arrayContaining([expect.objectContaining({ id: 'turn-1-assistant' })])diff --git a/desktop-app/ui/src/hooks/domain/useAgentChatController.ts b/desktop-app/ui/src/hooks/domain/useAgentChatController.tsindex 458b343c8..5c7da498d 100644--- a/desktop-app/ui/src/hooks/domain/useAgentChatController.ts+++ b/desktop-app/ui/src/hooks/domain/useAgentChatController.ts@@ -100,6 +100,7 @@ const MAX_ACTIVITY_EVENTS_PER_MESSAGE = 100*/const MAX_MESSAGES_WITH_ACTIVITY_PER_AGENT = 50const MESSAGE_PAGE_SIZE = 80+const MAX_RECONCILE_DELTA_PAGES = 5function serverTurnNumber(message: AgentChatMessage): number | undefined {if (message.serverTurnNumber !== undefined) return message.serverTurnNumber@@ -114,6 +115,13 @@ function oldestServerTurnNumber(messages: AgentChatMessage[]): number | undefine}, undefined)}+function latestServerTurnNumber(messages: AgentChatMessage[]): number | undefined {+ return messages.reduce<number | undefined>((latest, message) => {+ const current = serverTurnNumber(message)+ return current === undefined ? latest : Math.max(latest ?? current, current)+ }, undefined)+}+type ChatStoreClient = ReturnType<typeof useChatStore>async function hasLocalMessagesBeyond(@@ -142,6 +150,85 @@ function mergeUniqueMessages(})}+function sameLocalServerMessage(local: AgentChatMessage, server: AgentChatMessage): boolean {+ return (+ serverTurnNumber(local) === undefined &&+ serverTurnNumber(server) !== undefined &&+ local.role === server.role &&+ local.content === server.content+ )+}++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 mergeServerMessages(+ existing: AgentChatMessage[],+ incoming: AgentChatMessage[]+): AgentChatMessage[] {+ const merged = [...existing]+ const replacedIndexes = new Set<number>()++ for (const serverMessage of incoming) {+ if (merged.some(message => message.id === serverMessage.id)) continue++ const serverTurn = serverTurnNumber(serverMessage)+ const sameTurnIndex =+ serverTurn === undefined+ ? -1+ : merged.findIndex(+ message =>+ serverTurnNumber(message) === serverTurn && message.role === serverMessage.role+ )+ if (sameTurnIndex >= 0) {+ merged[sameTurnIndex] = {+ ...serverMessage,+ task_id: merged[sameTurnIndex]?.task_id ?? serverMessage.task_id,+ }+ replacedIndexes.add(sameTurnIndex)+ continue+ }++ const localEchoIndex = merged.findIndex(+ (message, index) =>+ !replacedIndexes.has(index) && sameLocalServerMessage(message, serverMessage)+ )+ if (localEchoIndex >= 0) {+ merged[localEchoIndex] = {+ ...serverMessage,+ task_id: merged[localEchoIndex]?.task_id ?? serverMessage.task_id,+ }+ replacedIndexes.add(localEchoIndex)+ continue+ }++ merged.push(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 {+ return (+ a.length === b.length &&+ a.every((message, index) => {+ const other = b[index]+ return (+ other !== undefined &&+ message.id === other.id &&+ serverTurnNumber(message) === serverTurnNumber(other)+ )+ })+ )+}+/** Keep only the last `n` insertion-ordered keys of a per-message map. Returns the* same reference when already within the cap (so React state stays identity-stable). */function pruneToLastN<T>(map: Record<string, T>, n: number): Record<string, T> {@@ -252,6 +339,10 @@ export function useAgentChatController({decideApprovalFromNotification,}: UseAgentChatControllerParams) {const chatStore = useChatStore()++ useEffect(() => {+ chatStore.setRemoteCacheScope(isAuthenticated ? `authenticated:${currentTeamId}` : 'signed-out')+ }, [chatStore.setRemoteCacheScope, currentTeamId, isAuthenticated])const tracker = useAgentTaskTracker()const [activeChatId, setActiveChatId] = useState<string | null>(null)@@ -309,6 +400,7 @@ export function useAgentChatController({const [chatMessagesLoading, setChatMessagesLoading] = useState(false)const [hasOlderMessages, setHasOlderMessages] = useState(false)const [olderMessagesLoading, setOlderMessagesLoading] = useState(false)+ const chatMessagesRef = useRef<AgentChatMessage[]>([])const loadedLocalMessageCountRef = useRef(0)const [activityByAgentMessage, setActivityByAgentMessage] = useState<@@ -318,6 +410,10 @@ export function useAgentChatController({Record<string, Record<string, TaskProgress>>>({})+ useEffect(() => {+ chatMessagesRef.current = chatMessages+ }, [chatMessages])+const [agentSending, setAgentSending] = useState(false)const [agentError, setAgentError] = useState<string | null>(null)const [failedAgentSend, setFailedAgentSend] = useState<FailedAgentSend | null>(null)@@ -688,9 +784,16 @@ export function useAgentChatController({// PHASE 1 — render only the newest local page. The authoritative reconcile// below requests a delta after the newest cached server turn.- const cached = await chatStore- .loadMessages(agentRef, chatId, MESSAGE_PAGE_SIZE)- .catch(() => [])+ 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)const hasOlderLocalMessages =@@ -739,10 +842,7 @@ export function useAgentChatController({// and its `isRelevant`/`taskIdHint` are ignored; `hydrateActiveChatFromServer`'s// own `isActive()` guard still prevents rendering into the wrong chat.const zombieBefore = tracker.get(key)- const latestCachedTurn = cached.reduce<number | undefined>((latest, message) => {- const current = serverTurnNumber(message as AgentChatMessage)- return current === undefined ? latest : Math.max(latest ?? 0, current)- }, undefined)+ const latestCachedTurn = latestServerTurnNumber(cached as AgentChatMessage[])await reconcileChat(key, {reason: 'switch_to_chat',taskIdHint: zombieBefore?.taskId,@@ -798,64 +898,80 @@ export function useAgentChatController({const handleLoadOlderMessages = useCallback(async () => {if (!selectedAgent || !activeChatId || olderMessagesLoading) return+ const requestAgent = selectedAgent+ const requestChatId = activeChatId+ const isStillRelevant = () => {+ const visible = activeChatVisibilityRef.current+ return visible.selectedAgent === requestAgent && visible.activeChatId === requestChatId+ }setOlderMessagesLoading(true)try {const visibleIds = new Set(chatMessages.map(message => message.id))const localPage = (await chatStore.loadMessages(- selectedAgent,- activeChatId,+ requestAgent,+ requestChatId,MESSAGE_PAGE_SIZE,loadedLocalMessageCountRef.current).catch(() => [])) as AgentChatMessage[]+ if (!isStillRelevant()) returnconst unseenLocal = localPage.filter(message => !visibleIds.has(message.id))if (unseenLocal.length) {const nextLoadedLocalMessageCount = loadedLocalMessageCountRef.current + localPage.length- const merged = mergeUniqueMessages(chatMessages, unseenLocal, 'before')- const oldestMergedTurn = oldestServerTurnNumber(merged)+ const currentMessages = chatMessagesRef.current+ const previewMerged = mergeUniqueMessages(currentMessages, unseenLocal, 'before')+ const oldestMergedTurn = oldestServerTurnNumber(previewMerged)const hasOlderServerMessages = Boolean(oldestMergedTurn && oldestMergedTurn > 1)const hasOlderLocalMessages =!hasOlderServerMessages &&localPage.length === MESSAGE_PAGE_SIZE &&(await hasLocalMessagesBeyond(chatStore,- selectedAgent,- activeChatId,+ requestAgent,+ requestChatId,nextLoadedLocalMessageCount))+ if (!isStillRelevant()) returnloadedLocalMessageCountRef.current = nextLoadedLocalMessageCount+ const merged = mergeUniqueMessages(chatMessagesRef.current, unseenLocal, 'before')+ chatMessagesRef.current = mergedsetChatMessages(merged)setHasOlderMessages(hasOlderLocalMessages || hasOlderServerMessages)return}- const oldestTurn = oldestServerTurnNumber(chatMessages)+ const oldestTurn = oldestServerTurnNumber(chatMessagesRef.current)if (oldestTurn === undefined || oldestTurn <= 1) {setHasOlderMessages(false)return}const response = await chatStore.loadSessionMessages(- selectedAgent,- selectedAgent,- activeChatId,+ requestAgent,+ requestAgent,+ requestChatId,{ limit: MESSAGE_PAGE_SIZE, beforeTurn: oldestTurn })+ if (!isStillRelevant()) returnconst older = turnsToChatMessages(response.turns) as AgentChatMessage[]- const merged = mergeUniqueMessages(chatMessages, older, 'before')+ const merged = mergeServerMessages(chatMessagesRef.current, older)+ chatMessagesRef.current = mergedsetChatMessages(merged)- await chatStore.replaceMessages(selectedAgent, activeChatId, merged)+ if (!isStillRelevant()) return+ await chatStore.replaceMessages(requestAgent, requestChatId, merged)loadedLocalMessageCountRef.current = merged.lengthsetHasOlderMessages(Boolean(response.hasMoreBefore))} catch (error) {console.warn('[chat-history] failed to load older messages', {- agentRef: selectedAgent,- chatId: activeChatId,+ agentRef: requestAgent,+ chatId: requestChatId,error,})} finally {- setOlderMessagesLoading(false)+ if (isStillRelevant()) {+ setOlderMessagesLoading(false)+ }}}, [activeChatId,@@ -970,13 +1086,11 @@ export function useAgentChatController({if (requested) {await switchToChat(selectedAgent, requestedSelection.chatId)} else {- // B9: the pending `specific` selection never appeared in the merged- // list (e.g. a server-only chat surfaced by a notification while- // `listSessions` silently failed → items:[]). The spinner was turned- // on above (`setChatMessagesLoading(true)`); switchToChat — the only- // thing that clears it — never runs, so the chat pane would spin- // forever. Clear it here so the consistent empty-state renders instead.- setChatMessagesLoading(false)+ // Server-only chats may not appear in the local index or first server+ // catalog page yet. `switchToChat` already owns the cache-first →+ // server-hydrate path, so still open the requested id instead of+ // clearing the pending notification/deeplink selection.+ await switchToChat(selectedAgent, requestedSelection.chatId)}return}@@ -1217,9 +1331,11 @@ export function useAgentChatController({const v = activeChatVisibilityRef.currentreturn v.selectedAgent === agentRef && v.activeChatId === chatId}- const cached = (await chatStore- .loadMessages(agentRef, chatId, MESSAGE_PAGE_SIZE)- .catch(() => [])) as AgentChatMessage[]+ const cached = (await chatStore.loadMessages(+ agentRef,+ chatId,+ MESSAGE_PAGE_SIZE+ )) as AgentChatMessage[]if (!isActive() || tracker.get(chatKey)) return { rendered: cached, replaced: false, cached }const hydrated = turnsToChatMessages(resp.turns) as AgentChatMessage[]if (!hydrated.length) return { rendered: cached, replaced: false, cached }@@ -1234,25 +1350,21 @@ export function useAgentChatController({return { rendered: cached, replaced: false, cached }}}- const newMessages = hydrated.filter(message => !cached.some(item => item.id === message.id))- if (!newMessages.length) return { rendered: cached, replaced: false, cached }const hydratedWithAttachments = withResponseFileAttachments(- newMessages,+ hydrated,taskIdHint ? await loadTaskResultResponseFileAttachments(agentRef, taskIdHint) : [])if (!isActive() || tracker.get(chatKey)) return { rendered: cached, replaced: false, cached }const rendered = cachedHasServerTurns- ? mergeUniqueMessages(cached, hydratedWithAttachments)+ ? mergeServerMessages(cached, hydratedWithAttachments): hydratedWithAttachments+ if (sameMessageSequence(rendered, cached)) {+ return { rendered: cached, replaced: false, cached }+ }setChatMessages(rendered)const meta = await chatStore.createChat(agentRef, chatId)- if (cachedHasServerTurns) {- await chatStore.appendMessages(agentRef, chatId, hydratedWithAttachments)- loadedLocalMessageCountRef.current += hydratedWithAttachments.length- } else {- await chatStore.replaceMessages(agentRef, chatId, rendered)- loadedLocalMessageCountRef.current = rendered.length- }+ await chatStore.replaceMessages(agentRef, chatId, rendered)+ 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@@ -1275,7 +1387,6 @@ export function useAgentChatController({},[tracker,- chatStore.appendMessages,chatStore.loadMessages,chatStore.createChat,chatStore.replaceMessages,@@ -1459,7 +1570,19 @@ export function useAgentChatController({useEffect(() => {reconcileBranchesRef.current = {loadSessionMessages: async (agentRef, chatId, query) => {- const requestedQuery = query ?? { limit: MESSAGE_PAGE_SIZE }+ 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 latestCachedTurn = latestServerTurnNumber(cached)+ requestedQuery = {+ ...requestedQuery,+ ...(latestCachedTurn !== undefined ? { afterTurn: latestCachedTurn } : {}),+ }+ }let response = await chatStore.loadSessionMessages(agentRef,agentRef,@@ -1473,7 +1596,13 @@ export function useAgentChatController({const turns = [...response.turns]const seenCursors = new Set<number>()let cursor = response.latestTurnNumber ?? turns.at(-1)?.number- while (response.hasMoreAfter && cursor !== undefined && !seenCursors.has(cursor)) {+ let pagesLoaded = 1+ while (+ response.hasMoreAfter &&+ cursor !== undefined &&+ !seenCursors.has(cursor) &&+ pagesLoaded < MAX_RECONCILE_DELTA_PAGES+ ) {seenCursors.add(cursor)response = await chatStore.loadSessionMessages(agentRef, agentRef, chatId, {limit: requestedQuery.limit ?? MESSAGE_PAGE_SIZE,@@ -1481,12 +1610,14 @@ export function useAgentChatController({})turns.push(...response.turns)cursor = response.latestTurnNumber ?? response.turns.at(-1)?.number+ pagesLoaded += 1}return {...response,turns,oldestTurnNumber: turns[0]?.number,latestTurnNumber: turns.at(-1)?.number,+ hasMoreAfter: Boolean(response.hasMoreAfter && pagesLoaded >= MAX_RECONCILE_DELTA_PAGES),}},attachLiveTask: reconcileAttachLiveTask,@@ -1495,6 +1626,7 @@ export function useAgentChatController({}}, [chatStore.loadSessionMessages,+ chatStore.loadMessages,reconcileAttachLiveTask,reconcileSettleIdle,reconcileEvictChat,diff --git a/desktop-app/ui/src/hooks/domain/useChatListController.ts b/desktop-app/ui/src/hooks/domain/useChatListController.tsindex 557f244e3..d1b64d790 100644--- a/desktop-app/ui/src/hooks/domain/useChatListController.ts+++ b/desktop-app/ui/src/hooks/domain/useChatListController.ts@@ -146,6 +146,11 @@ export function useChatListController({const loadChatListOnce = useCallback(async (agentRef: string): Promise<{ index: ChatIndex; merged: SidebarChatEntry[] }> => {+ chatListNextCursorByAgentRef.current[agentRef] = null+ if (selectedAgentRef.current === agentRef) {+ setChatListHasMoreRemoteSessions(false)+ setChatListMoreLoading(false)+ }const index = await chatStore.getIndex(agentRef)const merged = [...index.chats].sort(byUpdatedDesc)setChatList(merged)@@ -225,9 +230,9 @@ export function useChatListController({if (!serverResult) returnconst serverSessions = serverResult.items.filter(s => s.agent === agentRef)- chatListNextCursorByAgentRef.current[agentRef] = serverResult.nextCursor ?? nullif (selectedAgentRef.current !== agentRef) return+ chatListNextCursorByAgentRef.current[agentRef] = serverResult.nextCursor ?? nullsetChatListHasMoreRemoteSessions(Boolean(serverResult.nextCursor))seedSessionSnapshots(fsm, agentRef, serverSessions)setChatList(previous => {@@ -292,8 +297,8 @@ export function useChatListController({/** Reset the selected agent's list (logout teardown / load failure). */const clearList = useCallback(() => {- const agentRef = selectedAgentRef.current- if (agentRef) chatListNextCursorByAgentRef.current[agentRef] = null+ chatListNextCursorByAgentRef.current = {}+ chatListLoadingMoreByAgentRef.current.clear()setChatList([])setChatListMoreLoading(false)setChatListHasMoreRemoteSessions(false)diff --git a/desktop-app/ui/src/hooks/scheduleAfterFirstPaint.ts b/desktop-app/ui/src/hooks/scheduleAfterFirstPaint.tsindex 6fae64241..7ff089cfd 100644--- a/desktop-app/ui/src/hooks/scheduleAfterFirstPaint.ts+++ b/desktop-app/ui/src/hooks/scheduleAfterFirstPaint.ts@@ -1,8 +1,14 @@export function scheduleAfterFirstPaint(task: () => Promise<unknown>): void {+ let didRun = false+ let fallbackTimer: ReturnType<typeof setTimeout> | undefinedconst run = () => {+ if (didRun) return+ didRun = true+ if (fallbackTimer !== undefined) clearTimeout(fallbackTimer)void task().catch(() => undefined)}if (typeof requestAnimationFrame === 'function') {+ fallbackTimer = setTimeout(run, 1000)requestAnimationFrame(() => requestAnimationFrame(run))return}diff --git a/desktop-app/ui/src/hooks/useChatStore.ts b/desktop-app/ui/src/hooks/useChatStore.tsindex 6583f5439..695900c16 100644--- a/desktop-app/ui/src/hooks/useChatStore.ts+++ b/desktop-app/ui/src/hooks/useChatStore.ts@@ -62,6 +62,7 @@ const sessionCatalogRequests = new Map<string, CachedRequest<SessionsListResult>const hostModelRequests = new Map<string, CachedRequest<HostModelsResult | null>>()let sessionCatalogSource: typeof window.clerum.rpc.listSessions | null = nulllet hostModelsSource: typeof window.clerum.rpc.getHostModels | null = null+let remoteCacheScope = 'unknown'/** Composite key mirroring the session `chatKey` convention (`agentRef::chatId`). */function pendingModelKey(agentRef: string, chatId: string): string {@@ -140,7 +141,7 @@ export function useChatStore() {sessionCatalogRequests.clear()sessionCatalogSource = source}- const key = `${hostRef}:${query.limit ?? 'all'}:${query.cursor ?? ''}`+ const key = `${remoteCacheScope}:${hostRef}:${query.limit ?? 'all'}:${query.cursor ?? ''}`const cached = sessionCatalogRequests.get(key)if (!options.force && cached && cached.expiresAt > Date.now()) return cached.promise@@ -172,7 +173,7 @@ export function useChatStore() {hostModelRequests.clear()hostModelsSource = source}- const key = `${hostRef}:${chatId}`+ const key = `${remoteCacheScope}:${hostRef}:${chatId}`const cached = hostModelRequests.get(key)if (cached && cached.expiresAt > Date.now()) return cached.promise@@ -194,6 +195,12 @@ export function useChatStore() {sessionCatalogSource = nullhostModelsSource = null}, [])+ const setRemoteCacheScope = useCallback((scope: string) => {+ if (remoteCacheScope === scope) return+ remoteCacheScope = scope+ sessionCatalogRequests.clear()+ hostModelRequests.clear()+ }, [])// --- Pending (unpersisted) model selections — R2 "Option A" (see the// `pendingModelByChat` note above). Only UNPERSISTED selections are tracked:@@ -251,6 +258,7 @@ export function useChatStore() {getHostModels,setHostModel,clearCachedRemoteData,+ setRemoteCacheScope,setPendingModel,getPendingModel,clearPendingModel,diff --git a/host-context-controller/package-lock.json b/host-context-controller/package-lock.jsonindex 2e04d1e84..854e35948 100644--- a/host-context-controller/package-lock.json+++ b/host-context-controller/package-lock.json@@ -1,12 +1,12 @@{"name": "clerum-host-context-controller",- "version": "0.1.158",+ "version": "0.1.157","lockfileVersion": 3,"requires": true,"packages": {"": {"name": "clerum-host-context-controller",- "version": "0.1.158",+ "version": "0.1.157","license": "SEE LICENSE IN LICENSE","dependencies": {"@clerum/image-policy": "file:../packages/image-policy",diff --git a/host-context-controller/package.json b/host-context-controller/package.jsonindex 32eca539e..0fc08aae0 100644--- a/host-context-controller/package.json+++ b/host-context-controller/package.json@@ -1,6 +1,6 @@{"name": "clerum-host-context-controller",- "version": "0.1.158",+ "version": "0.1.157","description": "Host Context Controller - provides McpServer CRDs to mcp-host via REST API","main": "dist/main.js","engines": {diff --git a/host-context-controller/src/k8sClient.test.ts b/host-context-controller/src/k8sClient.test.tsindex 50a197f91..375a37333 100644--- a/host-context-controller/src/k8sClient.test.ts+++ b/host-context-controller/src/k8sClient.test.ts@@ -2968,7 +2968,10 @@ describe('McpServerWatcher Host watch generation', () => {spec: { host: 'retry-host', lifecycle: { stateless: true } },})expect(reconcile).toHaveBeenCalledOnce()- expect(reconcile).toHaveBeenCalledWith(expect.objectContaining({ uid: 'retry-host-uid' }), 'urgent')+ expect(reconcile).toHaveBeenCalledWith(+ expect.objectContaining({ uid: 'retry-host-uid' }),+ 'urgent'+ )expect((watcher as any).hostWatchRetryTimers.size).toBe(1)expect((watcher as any).latestHostWatchEventRevisions.size).toBe(1)diff --git a/mcp-host/package-lock.json b/mcp-host/package-lock.jsonindex d1d1b6c6e..744d328c2 100644--- a/mcp-host/package-lock.json+++ b/mcp-host/package-lock.json@@ -1,12 +1,12 @@{"name": "clerum-mcp-host",- "version": "0.1.211",+ "version": "0.1.212","lockfileVersion": 3,"requires": true,"packages": {"": {"name": "clerum-mcp-host",- "version": "0.1.211",+ "version": "0.1.212","license": "SEE LICENSE IN LICENSE","dependencies": {"@anthropic-ai/sdk": "^0.32.0",diff --git a/mcp-host/package.json b/mcp-host/package.jsonindex 966d53d88..4662ad56b 100644--- a/mcp-host/package.json+++ b/mcp-host/package.json@@ -1,6 +1,6 @@{"name": "clerum-mcp-host",- "version": "0.1.211",+ "version": "0.1.212","description": "MCP Host - reads Host CRD and provides LLM access via OpenAI/Claude","main": "dist/main.js","engines": {diff --git a/mcp-host/src/core/conversation/__tests__/inMemoryConversationStore.test.ts b/mcp-host/src/core/conversation/__tests__/inMemoryConversationStore.test.tsindex 68f0d68e2..6a38337c8 100644--- a/mcp-host/src/core/conversation/__tests__/inMemoryConversationStore.test.ts+++ b/mcp-host/src/core/conversation/__tests__/inMemoryConversationStore.test.ts@@ -14,6 +14,17 @@ function makeConversation(userId: string): Conversation {}}+function makeTurn(number: number) {+ return {+ number,+ user_input: `user ${number}`,+ response: `assistant ${number}`,+ tool_calls: [],+ started_at: new Date(`2026-01-01T00:00:0${number % 10}.000Z`),+ completed_at: new Date(`2026-01-01T00:00:0${number % 10}.500Z`),+ }+}+describe('InMemoryConversationStore', () => {let store: InMemoryConversationStore@@ -103,4 +114,46 @@ describe('InMemoryConversationStore', () => {expect(store.listByPrefix('u-2:')).toEqual([])})})++ describe('listSessionSummariesByPrefix', () => {+ it('uses the same binary tie-breaker as session cursors', async () => {+ const updatedAt = new Date('2026-01-01T00:00:00.000Z')+ const upper = { ...makeConversation('u-1'), updated_at: updatedAt }+ const lower = { ...makeConversation('u-1'), updated_at: updatedAt }+ store.set('u-1:rpc:agent-x:B1', upper)+ store.set('u-1:rpc:agent-x:a1', lower)++ const first = await store.listSessionSummariesByPrefix('u-1:rpc:', { limit: 1 })+ expect(first.map(session => session.chatId)).toEqual(['B1'])++ const second = await store.listSessionSummariesByPrefix('u-1:rpc:', {+ limit: 1,+ cursor: {+ updatedAt: first[0]!.lastActivityAt,+ key: first[0]!.key,+ },+ })+ expect(second.map(session => session.chatId)).toEqual(['a1'])+ })+ })++ describe('getSessionMessagesByKey', () => {+ it('returns only the requested turn window', async () => {+ const conv = makeConversation('u-1')+ conv.turns = [makeTurn(1), makeTurn(2), makeTurn(3), makeTurn(4)]+ store.set('u-1:rpc:agent-x:chat-1', conv)++ const page = await store.getSessionMessagesByKey('u-1:rpc:agent-x:chat-1', 'u-1:rpc:', {+ limit: 2,+ beforeTurn: 4,+ })++ expect(page?.agent).toBe('agent-x')+ expect(page?.chatId).toBe('chat-1')+ expect(page?.totalTurns).toBe(4)+ expect(page?.firstTurnNumber).toBe(1)+ expect(page?.lastTurnNumber).toBe(4)+ expect(page?.turns.map(turn => turn.number)).toEqual([2, 3])+ })+ })})diff --git a/mcp-host/src/core/conversation/conversation.ts b/mcp-host/src/core/conversation/conversation.tsindex 056ccaaec..24d29f7ce 100644--- a/mcp-host/src/core/conversation/conversation.ts+++ b/mcp-host/src/core/conversation/conversation.ts@@ -17,6 +17,7 @@ import {GetOrCreateOptions,InMemoryConversationStore,SessionListQuery,+ SessionMessagesQuery,} from './conversationStore'/**@@ -158,6 +159,19 @@ export class ConversationManager {return this.store.listSessionSummariesByPrefix(keyPrefix, query)}+ /**+ * Summary-preserving, bounded transcript window for `/messages`.+ * Durable stores can fetch only the requested turns instead of hydrating+ * the whole persisted conversation before slicing.+ */+ async getSessionMessagesByKeyAsync(+ key: string,+ keyPrefix: string,+ query: SessionMessagesQuery = {}+ ) {+ return this.store.getSessionMessagesByKey(key, keyPrefix, query)+ }+/*** Look up a single conversation by its exact session key.* Used by the transcript endpoint: the full key can be reconstructed fromdiff --git a/mcp-host/src/core/conversation/conversationStore.ts b/mcp-host/src/core/conversation/conversationStore.tsindex d2dd4ff3f..789bf7a8b 100644--- a/mcp-host/src/core/conversation/conversationStore.ts+++ b/mcp-host/src/core/conversation/conversationStore.ts@@ -3,6 +3,7 @@ import {type Conversation,ConversationState,type PendingApproval,+ type Turn,type TurnToolCall,} from '../types'@@ -66,6 +67,12 @@ export interface SessionListQuery {cursor?: SessionListCursor}+export interface SessionMessagesQuery {+ limit?: number+ beforeTurn?: number+ afterTurn?: number+}+export interface ConversationSessionSummary {key: stringagent: string@@ -82,6 +89,17 @@ export interface ConversationSessionSummary {cacheTokensReported?: boolean}+export interface ConversationSessionMessages extends Omit<+ ConversationSessionSummary,+ 'lastActivityAt' | 'turnCount'+> {+ turns: Turn[]+ totalTurns: number+ firstTurnNumber?: number+ lastTurnNumber?: number+ updatedAt: Date+}+function sessionPartsFromKey(key: string,prefix: string@@ -100,7 +118,8 @@ function compareSessionSummaries(right: Pick<ConversationSessionSummary, 'key' | 'lastActivityAt'>): number {const byUpdated = right.lastActivityAt.getTime() - left.lastActivityAt.getTime()- return byUpdated || left.key.localeCompare(right.key)+ if (byUpdated) return byUpdated+ return left.key < right.key ? -1 : left.key > right.key ? 1 : 0}function afterSessionCursor(@@ -113,6 +132,54 @@ function afterSessionCursor(return updatedAt < cursorUpdatedAt || (updatedAt === cursorUpdatedAt && summary.key > cursor.key)}+function boundedTurns(turns: Turn[], query: SessionMessagesQuery = {}): Turn[] {+ const eligibleTurns =+ query.afterTurn !== undefined+ ? turns.filter(turn => turn.number > query.afterTurn!)+ : query.beforeTurn !== undefined+ ? turns.filter(turn => turn.number < query.beforeTurn!)+ : turns+ return query.limit === undefined+ ? eligibleTurns+ : query.afterTurn !== undefined+ ? eligibleTurns.slice(0, query.limit)+ : eligibleTurns.slice(-query.limit)+}++function sessionMessagesFromConversation(+ key: string,+ prefix: string,+ conversation: Conversation,+ query: SessionMessagesQuery = {}+): ConversationSessionMessages | undefined {+ const parts = sessionPartsFromKey(key, prefix)+ if (!parts) return undefined+ const turns = boundedTurns(conversation.turns, query)+ return {+ key,+ agent: parts.agent,+ chatId: parts.chatId,+ state: conversation.state,+ activeTaskId: conversation.activeTaskId,+ pendingApproval: conversation.pending_approval+ ? {+ request_id: conversation.pending_approval.request_id,+ tool_name: conversation.pending_approval.tool_name,+ }+ : undefined,+ turns,+ totalTurns: conversation.turns.length,+ firstTurnNumber: conversation.turns[0]?.number,+ lastTurnNumber: conversation.turns.at(-1)?.number,+ updatedAt: conversation.updated_at,+ input_tokens: conversation.input_tokens,+ output_tokens: conversation.output_tokens,+ cache_read_tokens: conversation.cache_read_tokens,+ cache_write_tokens: conversation.cache_write_tokens,+ cacheTokensReported: conversation.cacheTokensReported,+ }+}+/*** Storage-level abstraction for the session-keyed conversation map.*@@ -173,6 +240,16 @@ export interface ConversationStore {query?: SessionListQuery): Promise<ConversationSessionSummary[]>+ /**+ * Return a bounded transcript window for one exact session key.+ * Durable stores should fetch only the requested turn window.+ */+ getSessionMessagesByKey(+ key: string,+ prefix: string,+ query?: SessionMessagesQuery+ ): Promise<ConversationSessionMessages | undefined>+/** Cold-start sweep: load every session with a pending_approval row,* pin them in cache, and return enough metadata for the* `AgentStateMachine` cold-start to wire up `approvalMap`. */@@ -338,6 +415,16 @@ export class InMemoryConversationStore implements ConversationStore {return query.limit === undefined ? filtered : filtered.slice(0, query.limit)}+ async getSessionMessagesByKey(+ key: string,+ prefix: string,+ query: SessionMessagesQuery = {}+ ): Promise<ConversationSessionMessages | undefined> {+ const conversation = this.map.get(key)+ if (!conversation) return undefined+ return sessionMessagesFromConversation(key, prefix, conversation, query)+ }+async loadAllPendingApprovals(): Promise<PersistedSessionListing[]> {const out: PersistedSessionListing[] = []for (const [sessionKey, conv] of this.map) {diff --git a/mcp-host/src/core/conversation/persistence/__tests__/dualConversationStore.test.ts b/mcp-host/src/core/conversation/persistence/__tests__/dualConversationStore.test.tsindex 951fc69c7..06e959300 100644--- a/mcp-host/src/core/conversation/persistence/__tests__/dualConversationStore.test.ts+++ b/mcp-host/src/core/conversation/persistence/__tests__/dualConversationStore.test.ts@@ -80,4 +80,20 @@ describe('DualConversationStore — dual-write parity', () => {await sqlite.shutdown()}})++ it('returns the sqlite summary page instead of falling back to memory rows', async () => {+ const sqlite = makeSqliteStore({ cacheSize: 4 })+ try {+ const memory = new InMemoryConversationStore()+ const dual = new DualConversationStore(memory, sqlite.store)+ const manager = new ConversationManager(memory)+ const memoryOnly = await manager.getOrCreate('u-1:rpc:a:memory-only')+ await manager.startTurn(memoryOnly, 'memory only', 'task-memory')+ await manager.completeTurn(memoryOnly, 'done')++ await expect(dual.listSessionSummariesByPrefix('u-1:rpc:', { limit: 1 })).resolves.toEqual([])+ } finally {+ await sqlite.shutdown()+ }+ })})diff --git a/mcp-host/src/core/conversation/persistence/__tests__/sqliteConversationStore.test.ts b/mcp-host/src/core/conversation/persistence/__tests__/sqliteConversationStore.test.tsindex a18812837..8c0def362 100644--- a/mcp-host/src/core/conversation/persistence/__tests__/sqliteConversationStore.test.ts+++ b/mcp-host/src/core/conversation/persistence/__tests__/sqliteConversationStore.test.ts@@ -312,6 +312,37 @@ describe('SqliteConversationStore — session summary listing', () => {await handle.shutdown()}})++ it('loads a bounded message page without hydrating the full conversation cache', async () => {+ const handle = await freshStore({ cacheSize: 4 })+ try {+ const manager = new ConversationManager(handle.store)+ const conv = await manager.getOrCreate(SESSION_KEY)+ for (let turn = 1; turn <= 5; turn += 1) {+ await manager.startTurn(conv, `user ${turn}`, `task-${turn}`)+ await manager.completeTurn(conv, `assistant ${turn}`)+ }+ await handle.persistQueue.drainSessionKey(SESSION_KEY)+ handle.store['cache'].clear()+ handle.store['ordinals'].clear()+ handle.store['sessionKeyById'].clear()++ const page = await handle.store.getSessionMessagesByKey(SESSION_KEY, 'u-1:rpc:', {+ limit: 2,+ beforeTurn: 5,+ })++ expect(page?.totalTurns).toBe(5)+ expect(page?.firstTurnNumber).toBe(1)+ expect(page?.lastTurnNumber).toBe(5)+ expect(page?.turns.map(turn => turn.number)).toEqual([3, 4])+ expect(page?.turns.map(turn => turn.user_input)).toEqual(['user 3', 'user 4'])+ expect(page?.turns.map(turn => turn.response)).toEqual(['assistant 3', 'assistant 4'])+ expect(handle.store['cache'].size()).toBe(0)+ } finally {+ await handle.shutdown()+ }+ })})describe('SqliteConversationStore — cold-start rehydration', () => {diff --git a/mcp-host/src/core/conversation/persistence/dualConversationStore.ts b/mcp-host/src/core/conversation/persistence/dualConversationStore.tsindex fe4972843..41b0304a0 100644--- a/mcp-host/src/core/conversation/persistence/dualConversationStore.ts+++ b/mcp-host/src/core/conversation/persistence/dualConversationStore.ts@@ -1,7 +1,8 @@/*** `DualConversationStore` — shadow-write to two stores for canary validation.*- * Reads come from `memory` (the canonical store during validation).+ * Hot reads come from `memory`; durable-listing reads return SQLite pages so+ * pagination cannot switch sources mid-flow during validation.* Writes apply to both; parity is recorded via the optional metrics callback.* Used when `CLERUM_SESSION_STORE=dual` to validate that the SQLite store* produces the same observable behavior as the in-memory store before we@@ -11,12 +12,14 @@ import { Counter } from 'prom-client'import type { ReapedSession } from '../../../db/worker/protocol'import type { Conversation, PendingApproval, TurnToolCall } from '../../types'import type {+ ConversationSessionMessages,ConversationSessionSummary,ConversationStore,EvictCallback,GetOrCreateOptions,PersistedSessionListing,SessionListQuery,+ SessionMessagesQuery,SessionTokenUsage,} from '../conversationStore'@@ -136,7 +139,23 @@ export class DualConversationStore implements ConversationStore {this.sqlite.listSessionSummariesByPrefix(prefix, query),])this.recordParity('listSessionSummariesByPrefix', memList.length === sqlList.length)- return sqlList.length ? sqlList : memList+ return sqlList+ }++ async getSessionMessagesByKey(+ key: string,+ prefix: string,+ query: SessionMessagesQuery = {}+ ): Promise<ConversationSessionMessages | undefined> {+ const [memPage, sqlPage] = await Promise.all([+ this.memory.getSessionMessagesByKey(key, prefix, query),+ this.sqlite.getSessionMessagesByKey(key, prefix, query),+ ])+ this.recordParity(+ 'getSessionMessagesByKey',+ memPage === undefined ? sqlPage === undefined : sqlPage !== undefined+ )+ return sqlPage}async loadAllPendingApprovals(): Promise<PersistedSessionListing[]> {diff --git a/mcp-host/src/core/conversation/persistence/reconstruct.ts b/mcp-host/src/core/conversation/persistence/reconstruct.tsindex b48eafb9b..6c0334636 100644--- a/mcp-host/src/core/conversation/persistence/reconstruct.ts+++ b/mcp-host/src/core/conversation/persistence/reconstruct.ts@@ -143,7 +143,7 @@ function mapState(raw: string): ConversationState {}}-function groupMessagesIntoTurns(messages: MessageRow[]): Turn[] {+export function groupMessagesIntoTurns(messages: MessageRow[]): Turn[] {const byTurn = new Map<number, Turn>()for (const m of messages) {const turnNum = m.turn_number ?? 0diff --git a/mcp-host/src/core/conversation/persistence/sqliteConversationStore.ts b/mcp-host/src/core/conversation/persistence/sqliteConversationStore.tsindex 83615af41..ae0485f33 100644--- a/mcp-host/src/core/conversation/persistence/sqliteConversationStore.ts+++ b/mcp-host/src/core/conversation/persistence/sqliteConversationStore.ts@@ -18,6 +18,7 @@ import type {LoadAllPendingApprovalsRow,PendingApprovalRow,PersistedSession,+ PersistedSessionMessagePage,PersistedSessionSummary,ReapedSession,SessionRow,@@ -31,17 +32,23 @@ import {type TurnToolCall,} from '../../types'import {+ type ConversationSessionMessages,type ConversationSessionSummary,type ConversationStore,type EvictCallback,type GetOrCreateOptions,type PersistedSessionListing,type SessionListQuery,+ type SessionMessagesQuery,type SessionTokenUsage,} from '../conversationStore'import type { PersistQueue } from './persistQueue'import { CacheOverflowError, PinnedLRUMap } from './pinnedLruMap'-import { reconstructConversation, reconstructPendingApproval } from './reconstruct'+import {+ groupMessagesIntoTurns,+ reconstructConversation,+ reconstructPendingApproval,+} from './reconstruct'const cacheHitsCounter = (() => {try {@@ -164,6 +171,22 @@ interface SessionOrdinalState {nextTurnNumber: number}+function sessionPartsFromPrefix(key: string, prefix: string): { agent: string; chatId: string } {+ const rest = key.startsWith(prefix) ? key.slice(prefix.length) : key+ const colonIdx = rest.indexOf(':')+ return colonIdx >= 0+ ? { agent: rest.slice(0, colonIdx), chatId: rest.slice(colonIdx + 1) }+ : { agent: '', chatId: '' }+}++function conversationStateFromRow(state: string): ConversationState {+ return state === ConversationState.Processing+ ? ConversationState.Processing+ : state === ConversationState.AwaitingApproval+ ? ConversationState.AwaitingApproval+ : ConversationState.Idle+}+export class SqliteConversationStore implements ConversationStore {private readonly cache: PinnedLRUMap<string, Conversation>private readonly prefetchedPrefixes = new Set<string>()@@ -385,6 +408,88 @@ export class SqliteConversationStore implements ConversationStore {return out}+ async getSessionMessagesByKey(+ sessionKey: string,+ prefix: string,+ query: SessionMessagesQuery = {}+ ): Promise<ConversationSessionMessages | undefined> {+ const cached = this.cache.get(sessionKey)+ const parts = sessionPartsFromPrefix(sessionKey, prefix)+ if (cached) {+ const eligibleTurns =+ query.afterTurn !== undefined+ ? cached.turns.filter(turn => turn.number > query.afterTurn!)+ : query.beforeTurn !== undefined+ ? cached.turns.filter(turn => turn.number < query.beforeTurn!)+ : cached.turns+ const turns =+ query.limit === undefined+ ? eligibleTurns+ : query.afterTurn !== undefined+ ? eligibleTurns.slice(0, query.limit)+ : eligibleTurns.slice(-query.limit)+ return {+ key: sessionKey,+ agent: parts.agent,+ chatId: parts.chatId,+ state: cached.state,+ activeTaskId: cached.activeTaskId,+ pendingApproval: cached.pending_approval+ ? {+ request_id: cached.pending_approval.request_id,+ tool_name: cached.pending_approval.tool_name,+ }+ : undefined,+ turns,+ totalTurns: cached.turns.length,+ firstTurnNumber: cached.turns[0]?.number,+ lastTurnNumber: cached.turns.at(-1)?.number,+ updatedAt: cached.updated_at,+ input_tokens: cached.input_tokens,+ output_tokens: cached.output_tokens,+ cache_read_tokens: cached.cache_read_tokens,+ cache_write_tokens: cached.cache_write_tokens,+ cacheTokensReported: cached.cacheTokensReported,+ }+ }++ const page = await this.persistQueue.enqueueSync<PersistedSessionMessagePage | null>(+ {+ kind: 'load_session_message_page',+ sessionKey,+ limit: query.limit,+ beforeTurn: query.beforeTurn,+ afterTurn: query.afterTurn,+ },+ sessionKey+ )+ if (!page) return undefined++ return {+ key: sessionKey,+ agent: parts.agent,+ chatId: parts.chatId,+ state: conversationStateFromRow(page.session.state),+ activeTaskId: page.session.active_task_id ?? undefined,+ pendingApproval: page.pending_approval+ ? {+ request_id: page.pending_approval.request_id,+ tool_name: page.pending_approval.tool_name,+ }+ : undefined,+ turns: groupMessagesIntoTurns(page.messages),+ totalTurns: Math.max(0, Math.floor(page.total_turns ?? 0)),+ firstTurnNumber: page.first_turn_number ?? undefined,+ lastTurnNumber: page.last_turn_number ?? undefined,+ updatedAt: new Date(page.last_activity_at * 1000),+ input_tokens: page.session.input_tokens,+ output_tokens: page.session.output_tokens,+ cache_read_tokens: page.session.cache_read_tokens,+ cache_write_tokens: page.session.cache_write_tokens,+ cacheTokensReported: page.session.cache_tokens_reported === 1,+ }+ }+async loadAllPendingApprovals(): Promise<PersistedSessionListing[]> {const rows = await this.persistQueue.enqueueSync<LoadAllPendingApprovalsRow[]>({kind: 'load_all_pending_approvals',diff --git a/mcp-host/src/db/migrations/001-initial-schema.ts b/mcp-host/src/db/migrations/001-initial-schema.tsindex ac616c55c..8252297f0 100644--- a/mcp-host/src/db/migrations/001-initial-schema.ts+++ b/mcp-host/src/db/migrations/001-initial-schema.ts@@ -72,6 +72,10 @@ export function up(db: Database): void {ON messages(spillover_ref) WHERE spillover_ref IS NOT NULL;CREATE INDEX IF NOT EXISTS idx_messages_timestampON messages(timestamp);+ CREATE INDEX IF NOT EXISTS idx_messages_session_timestamp+ ON messages(session_id, timestamp);+ CREATE INDEX IF NOT EXISTS idx_messages_session_turn_ordinal+ ON messages(session_id, turn_number, ordinal);CREATE TABLE IF NOT EXISTS pending_approvals (request_id TEXT PRIMARY KEY,diff --git a/mcp-host/src/db/migrations/009-session-summary-indexes.ts b/mcp-host/src/db/migrations/009-session-summary-indexes.tsnew file mode 100644index 000000000..41d5c5722--- /dev/null+++ b/mcp-host/src/db/migrations/009-session-summary-indexes.ts@@ -0,0 +1,26 @@+/**+ * Migration 009 — indexes for paged session-summary catalogs.+ *+ * The desktop session catalog reads sessions by key prefix and projects+ * last-activity/turn-count summaries from messages. Existing databases need the+ * same supporting indexes fresh installs get from migration 001.+ */+import type { Database } from 'better-sqlite3'++export const name = '009-session-summary-indexes'++export function up(db: Database): void {+ db.exec(`+ CREATE INDEX IF NOT EXISTS idx_messages_session_timestamp+ ON messages(session_id, timestamp);+ CREATE INDEX IF NOT EXISTS idx_messages_session_turn_ordinal+ ON messages(session_id, turn_number, ordinal);+ `)+}++export function down(db: Database): void {+ db.exec(`+ DROP INDEX IF EXISTS idx_messages_session_timestamp;+ DROP INDEX IF EXISTS idx_messages_session_turn_ordinal;+ `)+}diff --git a/mcp-host/src/db/migrations/index.ts b/mcp-host/src/db/migrations/index.tsindex 8b49d4d64..b6cb6f1af 100644--- a/mcp-host/src/db/migrations/index.ts+++ b/mcp-host/src/db/migrations/index.ts@@ -6,6 +6,7 @@ import * as messagesTokenUsage from './005-messages-token-usage'import * as sessionsCacheReported from './006-sessions-cache-reported'import * as sessionsModelSelections from './007-sessions-model-selections'import * as activeTraceContext from './008-active-trace-context'+import * as sessionSummaryIndexes from './009-session-summary-indexes'/*** Ordered list of migrations. New migrations append; never reorder or rename.@@ -25,4 +26,5 @@ export const migrations: Array<{sessionsCacheReported,sessionsModelSelections,activeTraceContext,+ sessionSummaryIndexes,]diff --git a/mcp-host/src/db/statements.ts b/mcp-host/src/db/statements.tsindex 901274283..bac9aac95 100644--- a/mcp-host/src/db/statements.ts+++ b/mcp-host/src/db/statements.ts@@ -26,6 +26,10 @@ export interface PreparedStatements {selectSessionBySessionKey: StatementselectSessionsByPrefix: StatementselectSessionSummariesByPrefix: Statement+ selectSessionTurnBounds: Statement+ selectMessagesBySessionNewestTurns: Statement+ selectMessagesBySessionTurnsBefore: Statement+ selectMessagesBySessionTurnsAfter: StatementinsertMessage: StatementselectMessagesBySession: Statement@@ -209,7 +213,8 @@ export function prepareStatements(db: Database): PreparedStatements {LIMIT 1) AS pending_tool_nameFROM sessions s- WHERE s.session_key LIKE @pattern+ WHERE s.session_key >= @prefix_start+ AND s.session_key < @prefix_end)SELECT *FROM session_summaries@@ -219,8 +224,66 @@ export function prepareStatements(db: Database): PreparedStatements {last_activity_at = @cursor_updated_atAND session_key > @cursor_key)- ORDER BY last_activity_at DESC, session_key ASC- LIMIT @limit+ ORDER BY last_activity_at DESC, session_key ASC+ LIMIT @limit+ `),+ selectSessionTurnBounds: db.prepare(`+ SELECT COUNT(DISTINCT 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_at+ FROM messages+ WHERE session_id = ?+ `),+ selectMessagesBySessionNewestTurns: db.prepare(`+ WITH selected_turns AS (+ SELECT COALESCE(turn_number, 0) AS turn_number+ FROM messages+ WHERE session_id = @session_id+ GROUP BY COALESCE(turn_number, 0)+ ORDER BY turn_number DESC+ LIMIT @limit+ )+ SELECT m.*+ FROM messages m+ JOIN selected_turns st+ ON COALESCE(m.turn_number, 0) = st.turn_number+ WHERE m.session_id = @session_id+ ORDER BY COALESCE(m.turn_number, 0) ASC, m.ordinal ASC+ `),+ selectMessagesBySessionTurnsBefore: db.prepare(`+ WITH selected_turns AS (+ SELECT COALESCE(turn_number, 0) AS turn_number+ FROM messages+ WHERE session_id = @session_id+ AND COALESCE(turn_number, 0) < @before_turn+ GROUP BY COALESCE(turn_number, 0)+ ORDER BY turn_number DESC+ LIMIT @limit+ )+ SELECT m.*+ FROM messages m+ JOIN selected_turns st+ ON COALESCE(m.turn_number, 0) = st.turn_number+ WHERE m.session_id = @session_id+ ORDER BY COALESCE(m.turn_number, 0) ASC, m.ordinal ASC+ `),+ selectMessagesBySessionTurnsAfter: db.prepare(`+ WITH selected_turns AS (+ SELECT COALESCE(turn_number, 0) AS turn_number+ FROM messages+ WHERE session_id = @session_id+ AND COALESCE(turn_number, 0) > @after_turn+ GROUP BY COALESCE(turn_number, 0)+ ORDER BY turn_number ASC+ LIMIT @limit+ )+ SELECT m.*+ FROM messages m+ JOIN selected_turns st+ ON COALESCE(m.turn_number, 0) = st.turn_number+ WHERE m.session_id = @session_id+ ORDER BY COALESCE(m.turn_number, 0) ASC, m.ordinal ASC`),insertMessage: db.prepare(`diff --git a/mcp-host/src/db/worker/dispatcher.ts b/mcp-host/src/db/worker/dispatcher.tsindex 20313151e..270ba444b 100644--- a/mcp-host/src/db/worker/dispatcher.ts+++ b/mcp-host/src/db/worker/dispatcher.ts@@ -12,6 +12,7 @@ import type {LoadAllPendingApprovalsRow,PendingApprovalRow,PersistedSession,+ PersistedSessionMessagePage,PersistedSessionSummary,ReapedSession,SessionRow,@@ -545,6 +546,51 @@ export async function dispatch(op: WorkerOp, deps: DispatcherDeps): Promise<unknreturn persisted}+ case 'load_session_message_page': {+ const sessionRow = s.selectSessionBySessionKey.get(op.sessionKey) as SessionRow | undefined+ if (!sessionRow) return null+ const limit = op.limit ?? -1+ const messageRows =+ op.afterTurn !== undefined+ ? s.selectMessagesBySessionTurnsAfter.all({+ session_id: sessionRow.id,+ after_turn: op.afterTurn,+ limit,+ })+ : op.beforeTurn !== undefined+ ? s.selectMessagesBySessionTurnsBefore.all({+ session_id: sessionRow.id,+ before_turn: op.beforeTurn,+ limit,+ })+ : s.selectMessagesBySessionNewestTurns.all({+ session_id: sessionRow.id,+ limit,+ })+ const bounds = s.selectSessionTurnBounds.get(sessionRow.id) as+ | {+ total_turns: number+ first_turn_number: number | null+ last_turn_number: number | null+ last_activity_at: number | null+ }+ | undefined+ const pendingRow = s.selectPendingApprovalBySession.get(sessionRow.id) as+ | PendingApprovalRow+ | undefined+ return {+ session: sessionRow,+ messages: messageRows as PersistedSessionMessagePage['messages'],+ pending_approval: pendingRow+ ? { request_id: pendingRow.request_id, tool_name: pendingRow.tool_name }+ : null,+ total_turns: bounds?.total_turns ?? 0,+ first_turn_number: bounds?.first_turn_number ?? null,+ last_turn_number: bounds?.last_turn_number ?? null,+ last_activity_at: bounds?.last_activity_at ?? sessionRow.started_at,+ } satisfies PersistedSessionMessagePage+ }+case 'list_sessions_by_prefix': {const pattern = `${op.sessionKeyPrefix}%`const sessionRows = s.selectSessionsByPrefix.all(pattern) as SessionRow[]@@ -562,9 +608,11 @@ export async function dispatch(op: WorkerOp, deps: DispatcherDeps): Promise<unkn}case 'list_session_summaries_by_prefix': {- const pattern = `${op.sessionKeyPrefix}%`+ const prefixStart = op.sessionKeyPrefix+ const prefixEnd = `${op.sessionKeyPrefix}\uffff`const rows = s.selectSessionSummariesByPrefix.all({- pattern,+ prefix_start: prefixStart,+ prefix_end: prefixEnd,limit: op.limit ?? -1,cursor_updated_at: op.cursorUpdatedAt ?? null,cursor_key: op.cursorKey ?? null,diff --git a/mcp-host/src/db/worker/protocol.ts b/mcp-host/src/db/worker/protocol.tsindex 5286e7c7e..59db99a6f 100644--- a/mcp-host/src/db/worker/protocol.ts+++ b/mcp-host/src/db/worker/protocol.ts@@ -118,6 +118,16 @@ export interface PersistedSessionSummary {pending_approval: Pick<PendingApprovalRow, 'request_id' | 'tool_name'> | null}+export interface PersistedSessionMessagePage {+ session: SessionRow+ messages: MessageRow[]+ pending_approval: Pick<PendingApprovalRow, 'request_id' | 'tool_name'> | null+ total_turns: number+ first_turn_number: number | null+ last_turn_number: number | null+ last_activity_at: number+}+export interface LoadAllPendingApprovalsRow {approval: PendingApprovalRowsession_key: string@@ -215,6 +225,13 @@ export type WorkerOp =| { kind: 'insert_pending_approval'; payload: PendingApprovalRow }| { kind: 'delete_pending_approval'; requestId: string }| { kind: 'load_active_session'; sessionKey: string }+ | {+ kind: 'load_session_message_page'+ sessionKey: string+ limit?: number+ beforeTurn?: number+ afterTurn?: number+ }| { kind: 'list_sessions_by_prefix'; sessionKeyPrefix: string }| {kind: 'list_session_summaries_by_prefix'diff --git a/mcp-host/src/main.ts b/mcp-host/src/main.tsindex 5f4dcd486..ebd8d2bf5 100644--- a/mcp-host/src/main.ts+++ b/mcp-host/src/main.ts@@ -33,7 +33,10 @@ import {resolveSessionModel,} from './config/modelResolution'import { ContextMapperClient, getContextMapperClient } from './contextMapperClient'-import type { ConversationSessionSummary } from './core/conversation/conversationStore'+import type {+ ConversationSessionMessages,+ ConversationSessionSummary,+} from './core/conversation/conversationStore'import {type ConversationStoreHandle,SqliteColdStartLoader,@@ -2021,7 +2024,9 @@ async function startRPCServer(): Promise<void> {// approve button without waiting for the SSE. `displayName` is derived// server-side (the `tool_name` itself is NOT leaked over the wire — security// patch P1-1).- const sessionStateView = (session: Conversation | ConversationSessionSummary) => {+ const sessionStateView = (+ session: Conversation | ConversationSessionSummary | ConversationSessionMessages+ ) => {const state =session.state === ConversationState.Processing? ('processing' as const)@@ -2115,30 +2120,19 @@ async function startRPCServer(): Promise<void> {const convManager = agent!.getConversationManager()// Direct O(1) key lookup — spec §2: `conversations.get(`${auth.sub}:rpc:${agent}:${chatId}`)`.const key = `${userSub}:rpc:${agentName}:${chatId}`- const conversation = await convManager.getSessionByKeyAsync(key)- if (!conversation) return null- const allTurns = conversation.turns- const eligibleTurns =- query.afterTurn !== undefined- ? allTurns.filter(turn => turn.number > query.afterTurn!)- : query.beforeTurn !== undefined- ? allTurns.filter(turn => turn.number < query.beforeTurn!)- : allTurns- const turns =- query.limit === undefined- ? eligibleTurns- : query.afterTurn !== undefined- ? eligibleTurns.slice(0, query.limit)- : eligibleTurns.slice(-query.limit)+ const keyPrefix = `${userSub}:rpc:`+ const page = await convManager.getSessionMessagesByKeyAsync(key, keyPrefix, query)+ if (!page) return null+ const turns = page.turnsconst oldestTurnNumber = turns[0]?.numberconst latestTurnNumber = turns.at(-1)?.number- const firstConversationTurn = allTurns[0]?.number- const lastConversationTurn = allTurns.at(-1)?.number+ const firstConversationTurn = page.firstTurnNumber+ const lastConversationTurn = page.lastTurnNumberreturn {agent: agentName,chatId,- ...sessionStateView(conversation),- totalTurns: allTurns.length,+ ...sessionStateView(page),+ totalTurns: page.totalTurns,oldestTurnNumber,latestTurnNumber,hasMoreBefore:@@ -2151,7 +2145,7 @@ async function startRPCServer(): Promise<void> {(latestTurnNumber !== undefined? latestTurnNumber < lastConversationTurn: query.beforeTurn !== undefined),- revision: `${allTurns.length}:${conversation.updated_at.getTime()}`,+ 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 6450c214f..2cc61008a 100644--- a/mcp-host/src/server/__tests__/sessionsRoutes.test.ts+++ b/mcp-host/src/server/__tests__/sessionsRoutes.test.ts@@ -50,6 +50,10 @@ function makeReqWithAuth(sub: string): Request {} as unknown as Request}+function encodeSessionsCursor(updatedAt: string, key: string): string {+ return Buffer.from(JSON.stringify({ updatedAt, key }), 'utf8').toString('base64url')+}+describe('handleSessionsListRoute', () => {it('returns 200 with items array for the authenticated user', async () => {const sessionsListHandler: SessionsListHandler = vi.fn().mockReturnValue({@@ -67,7 +71,7 @@ describe('handleSessionsListRoute', () => {],})expect(sessionsListHandler).toHaveBeenCalledWith('user-1', {- limit: undefined,+ limit: 50,cursor: undefined,})})@@ -79,7 +83,7 @@ describe('handleSessionsListRoute', () => {})const req = {...makeReqWithAuth('user-1'),- query: { limit: '500', cursor: 'current-page' },+ query: { limit: '500', cursor: encodeSessionsCursor('2026-04-22T00:00:00.000Z', 'k1') },} as unknown as Requestconst captured = makeRes()@@ -88,11 +92,25 @@ describe('handleSessionsListRoute', () => {expect(captured.statusCode).toBe(200)expect(sessionsListHandler).toHaveBeenCalledWith('user-1', {limit: 100,- cursor: 'current-page',+ cursor: encodeSessionsCursor('2026-04-22T00:00:00.000Z', 'k1'),})expect(captured.jsonBody).toEqual({ items: [], nextCursor: 'next-page' })})+ it('rejects malformed session cursors instead of treating them as page one', async () => {+ const sessionsListHandler: SessionsListHandler = vi.fn()+ const req = {+ ...makeReqWithAuth('user-1'),+ query: { cursor: 'not-json' },+ } 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()@@ -160,7 +178,7 @@ describe('handleSessionMessagesRoute', () => {],})expect(sessionMessagesHandler).toHaveBeenCalledWith('user-1', 'chatllm', 'c1', {- limit: undefined,+ limit: 80,beforeTurn: undefined,afterTurn: undefined,})diff --git a/mcp-host/src/server/routes.ts b/mcp-host/src/server/routes.tsindex 5c47941ca..eac0a4c7a 100644--- a/mcp-host/src/server/routes.ts+++ b/mcp-host/src/server/routes.ts@@ -63,6 +63,22 @@ export type RouteHandlers = {setModelHandler?: SetModelHandler | null}+function parseSessionsCursorParam(cursor: unknown): string | undefined | null {+ if (cursor === undefined) return undefined+ if (typeof cursor !== 'string' || cursor.length > 2048) return null+ try {+ const parsed = JSON.parse(Buffer.from(cursor, 'base64url').toString('utf8')) as {+ updatedAt?: unknown+ key?: unknown+ }+ if (typeof parsed.updatedAt !== 'string' || typeof parsed.key !== 'string') return null+ if (!Number.isFinite(Date.parse(parsed.updatedAt))) return null+ return cursor+ } catch {+ return null+ }+}+function channelRuntimeSourceMismatch(caller: RuntimeCallerContext | undefined,source: { channelType?: string; channelId?: string; sender?: string }@@ -1093,12 +1109,13 @@ export async function handleSessionsListRoute(const rawLimit = typeof req.query.limit === 'string' ? Number(req.query.limit) : undefinedconst limit =rawLimit === undefined- ? undefined+ ? 50: Math.min(Math.max(Number.isFinite(rawLimit) ? Math.floor(rawLimit) : 50, 1), 100)- const cursor =- typeof req.query.cursor === 'string' && req.query.cursor.length <= 2048- ? req.query.cursor- : undefined+ const cursor = parseSessionsCursorParam(req.query.cursor)+ if (cursor === null) {+ badRequest(res, 'Invalid sessions cursor')+ return+ }const result = await handlers.sessionsListHandler(caller.userId, { limit, cursor })json(res, 200, result)} catch (error) {@@ -1196,8 +1213,8 @@ export async function handleSessionMessagesRoute(}const limit =rawLimit === undefined- ? undefined- : Math.min(Math.max(Number.isFinite(rawLimit) ? Math.floor(rawLimit) : 50, 1), 200)+ ? 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))diff --git a/profile-ui/package-lock.json b/profile-ui/package-lock.jsonindex 189a943d0..d4f026f22 100644--- a/profile-ui/package-lock.json+++ b/profile-ui/package-lock.json@@ -1,12 +1,12 @@{"name": "clerum-profile-ui",- "version": "0.1.105",+ "version": "0.1.104","lockfileVersion": 3,"requires": true,"packages": {"": {"name": "clerum-profile-ui",- "version": "0.1.105",+ "version": "0.1.104","dependencies": {"next": "16.2.11","react": "^18.3.1",@@ -696,7 +696,6 @@"integrity": "sha512-z9VXpC7MWrhfWipitjNdgCauoMLRdIILQsAEV+ZesIzBq/oUlxk0m3ApZuMFCXdnS4U7KrI+l3WRUEGQ8K1QKw==","dev": true,"license": "MIT",- "peer": true,"dependencies": {"@types/prop-types": "*","csstype": "^3.2.2"@@ -895,7 +894,6 @@"resolved": "https://registry.npmjs.org/react/-/react-18.3.1.tgz","integrity": "sha512-wS+hAgJShR0KhEvPJArfuPVN1+Hz1t0Y6n5jLrGQbkb4urgPE/0Rve+1kMB1v/oWgHgm4WIcV+i7F2pTVj+2iQ==","license": "MIT",- "peer": true,"dependencies": {"loose-envify": "^1.1.0"},@@ -908,7 +906,6 @@"resolved": "https://registry.npmjs.org/react-dom/-/react-dom-18.3.1.tgz","integrity": "sha512-5m4nQKp+rZRb09LNH59GM4BxTh9251/ylbKIbpe7TpGxfJ+9kv6BLkLBXIjjspbgbnIBNqlI23tRnTWT0snUIw==","license": "MIT",- "peer": true,"dependencies": {"loose-envify": "^1.1.0","scheduler": "^0.23.2"diff --git a/profile-ui/package.json b/profile-ui/package.jsonindex f5c368b96..97f4d1436 100644--- a/profile-ui/package.json+++ b/profile-ui/package.json@@ -1,6 +1,6 @@{"name": "clerum-profile-ui",- "version": "0.1.105",+ "version": "0.1.104","private": true,"scripts": {"dev": "next dev",diff --git a/rpc-proxy/package-lock.json b/rpc-proxy/package-lock.jsonindex 26bef05e7..4370fb52b 100644--- a/rpc-proxy/package-lock.json+++ b/rpc-proxy/package-lock.json@@ -1,12 +1,12 @@{"name": "clerum-rpc-proxy",- "version": "0.1.52",+ "version": "0.1.53","lockfileVersion": 3,"requires": true,"packages": {"": {"name": "clerum-rpc-proxy",- "version": "0.1.52",+ "version": "0.1.53","dependencies": {"cors": "^2.8.5","express": "^4.21.2",diff --git a/rpc-proxy/package.json b/rpc-proxy/package.jsonindex d0951fe4e..bf75abbd1 100644--- a/rpc-proxy/package.json+++ b/rpc-proxy/package.json@@ -1,6 +1,6 @@{"name": "clerum-rpc-proxy",- "version": "0.1.52",+ "version": "0.1.53","description": "External-facing RPC proxy for tenant-scoped MCP access","main": "dist/main.js","engines": {