Skip to content

Evenfire is an intelligence layer platform for running LLM agents that take real actions, on your infrastructure

TypeScript

fix: harden desktop session paging and reconciliation

Josué407e2a95d614
diff --git a/desktop-app/package-lock.json b/desktop-app/package-lock.json
index fe3f9cad0..618f2fd27 100644
--- a/desktop-app/package-lock.json
+++ b/desktop-app/package-lock.json
@@ -1,12 +1,12 @@
{
"name": "evenfire",
- "version": "0.1.335",
+ "version": "0.1.336",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "evenfire",
- "version": "0.1.335",
+ "version": "0.1.336",
"license": "MPL-2.0",
"dependencies": {
"@tanstack/react-query": "5.100.10",
diff --git a/desktop-app/package.json b/desktop-app/package.json
index 469f173e4..e39cf27b8 100644
--- a/desktop-app/package.json
+++ b/desktop-app/package.json
@@ -1,7 +1,7 @@
{
"name": "evenfire",
"productName": "Evenfire",
- "version": "0.1.335",
+ "version": "0.1.336",
"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.ts
index de9181e42..41e501fce 100644
--- a/desktop-app/src/__tests__/appService.bootstrap.test.ts
+++ b/desktop-app/src/__tests__/appService.bootstrap.test.ts
@@ -267,6 +267,62 @@ describe('AppService invitation configuration lookup', () => {
}
})
+ it('fails closed when the saved-token store cannot be read', async () => {
+ process.env.EXTERNAL_REST_API_BASE_URL = 'https://api.example.com'
+ process.env.RPC_PROXY_BASE_URL = 'https://rpc.example.com'
+ vi.resetModules()
+
+ const { AppService } = await import('../appService.js')
+ const getMe = vi.fn()
+ 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> }
+ getSessionState: () => Promise<unknown>
+ }
+ service.authClient = { getMe } as never
+ service.tokenStore = {
+ getSessionToken: vi.fn().mockRejectedValue(new Error('keychain unavailable')),
+ clearSessionToken: vi.fn(),
+ } as never
+ service.rpcTokenManager = { clear: vi.fn() } as never
+
+ const warn = vi.spyOn(console, 'warn').mockImplementation(() => undefined)
+ try {
+ await expect(service.getSessionState()).resolves.toEqual({
+ authenticated: false,
+ me: null,
+ })
+ } finally {
+ warn.mockRestore()
+ }
+ expect(getMe).not.toHaveBeenCalled()
+ })
+
+ it('releases the logout guard when clearing the saved token fails', async () => {
+ process.env.EXTERNAL_REST_API_BASE_URL = 'https://api.example.com'
+ process.env.RPC_PROXY_BASE_URL = 'https://rpc.example.com'
+ vi.resetModules()
+
+ const { AppService } = await import('../appService.js')
+ const service = new AppService() as unknown as {
+ tokenStore: { clearSessionToken: ReturnType<typeof vi.fn> }
+ rpcTokenManager: { clear: ReturnType<typeof vi.fn> }
+ logoutInProgress: boolean
+ logout: () => Promise<void>
+ }
+ service.tokenStore = {
+ clearSessionToken: vi.fn().mockRejectedValue(new Error('keychain unavailable')),
+ } as never
+ service.rpcTokenManager = { clear: vi.fn() } as never
+
+ await expect(service.logout()).rejects.toThrow(/keychain unavailable/)
+ expect(service.logoutInProgress).toBe(false)
+ })
+
it('shares one saved-session restore across concurrent session-state requests', async () => {
const configPath = await createTempConfigPath('clerum-desktop-restore-single-flight')
await fs.writeFile(
diff --git a/desktop-app/src/__tests__/chatMessageMerge.test.ts b/desktop-app/src/__tests__/chatMessageMerge.test.ts
index 93ccf67e0..daa2ba2fc 100644
--- a/desktop-app/src/__tests__/chatMessageMerge.test.ts
+++ b/desktop-app/src/__tests__/chatMessageMerge.test.ts
@@ -1,5 +1,6 @@
import { describe, expect, it } from 'vitest'
import { mergeAuthoritativeServerMessages } from '../chatMessageMerge.js'
+import { turnsToChatMessages } from '../serverTurnAdapter.js'
import type { ChatMessage } from '../types.js'
describe('mergeAuthoritativeServerMessages', () => {
@@ -75,6 +76,13 @@ describe('mergeAuthoritativeServerMessages', () => {
})
it('does not duplicate an active optimistic message when the server returns its turn', () => {
+ const serverMessages = turnsToChatMessages([
+ {
+ number: 2,
+ user_input: 'second',
+ started_at: new Date(3).toISOString(),
+ },
+ ])
const merged = mergeAuthoritativeServerMessages(
[
{
@@ -92,20 +100,40 @@ describe('mergeAuthoritativeServerMessages', () => {
task_id: 'task-2',
},
],
+ serverMessages,
+ { activeTaskIds: new Set(['task-2']) }
+ )
+
+ expect(merged.map(message => message.id)).toEqual(['turn-1-user', 'optimistic-task-2'])
+ })
+
+ it('replaces a turnless echo after the previous numbered turn', () => {
+ const merged = mergeAuthoritativeServerMessages(
[
{
- id: 'turn-2-user',
+ id: 'turn-1-user',
+ role: 'user',
+ content: 'first',
+ timestamp: 1,
+ serverTurnNumber: 1,
+ },
+ {
+ id: 'optimistic-user',
role: 'user',
content: 'second',
- timestamp: 3,
- serverTurnNumber: 2,
- task_id: 'task-2',
+ timestamp: 2,
},
],
- { activeTaskIds: new Set(['task-2']) }
+ turnsToChatMessages([
+ {
+ number: 2,
+ user_input: 'second',
+ started_at: new Date(3).toISOString(),
+ },
+ ])
)
- expect(merged.map(message => message.id)).toEqual(['turn-1-user', 'optimistic-task-2'])
+ expect(merged.map(message => message.id)).toEqual(['turn-1-user', 'turn-2-user'])
})
it('replaces completed task-backed echoes inside their authoritative turn', () => {
diff --git a/desktop-app/src/__tests__/chatStore.test.ts b/desktop-app/src/__tests__/chatStore.test.ts
index e901ed856..e3b8afe7b 100644
--- a/desktop-app/src/__tests__/chatStore.test.ts
+++ b/desktop-app/src/__tests__/chatStore.test.ts
@@ -764,6 +764,84 @@ describe('messages', () => {
).toEqual(['m1', 'm2', 'm3'])
})
+ it('publishes a true replacement for a bounded reconciliation fallback', async () => {
+ await store.createChat('agent-1', 'true-replace')
+ await store.saveMessages('agent-1', 'true-replace', [
+ {
+ id: 'turn-1-user',
+ role: 'user',
+ content: 'stale',
+ timestamp: 1,
+ serverTurnNumber: 1,
+ },
+ {
+ id: 'turn-999-user',
+ role: 'user',
+ content: 'newest',
+ timestamp: 999,
+ serverTurnNumber: 999,
+ },
+ ])
+
+ await store.replaceMessages(
+ 'agent-1',
+ 'true-replace',
+ [
+ {
+ id: 'turn-999-user',
+ role: 'user',
+ content: 'newest',
+ timestamp: 999,
+ serverTurnNumber: 999,
+ },
+ ],
+ { replaceLocalWindow: true }
+ )
+
+ expect(
+ (await store.loadMessages('agent-1', 'true-replace')).map(message => message.id)
+ ).toEqual(['turn-999-user'])
+ })
+
+ it('uses active task context while persisting an authoritative window', async () => {
+ await store.createChat('agent-1', 'active-window')
+ await store.saveMessages('agent-1', 'active-window', [
+ {
+ id: 'turn-1-user',
+ role: 'user',
+ content: 'first',
+ timestamp: 1,
+ serverTurnNumber: 1,
+ },
+ {
+ id: 'optimistic-user',
+ role: 'user',
+ content: 'second',
+ timestamp: 2,
+ task_id: 'task-2',
+ },
+ ])
+
+ await store.replaceMessages(
+ 'agent-1',
+ 'active-window',
+ [
+ {
+ id: 'turn-2-user',
+ role: 'user',
+ content: 'second',
+ timestamp: 3,
+ serverTurnNumber: 2,
+ },
+ ],
+ { activeTaskIds: ['task-2'] }
+ )
+
+ expect(
+ (await store.loadMessages('agent-1', 'active-window')).map(message => message.id)
+ ).toEqual(['turn-1-user', 'optimistic-user'])
+ })
+
it('keeps unseen numbered history while replacing completed local-only echoes', async () => {
await store.createChat('agent-1', 'reconcile-upsert')
await store.saveMessages('agent-1', 'reconcile-upsert', [
@@ -1018,6 +1096,45 @@ describe('messages', () => {
expect(appended.messages.at(-1)!.id).toBe('m105')
})
+ it('bounds in-memory compatibility windows by serialized bytes', async () => {
+ const largeContent = 'x'.repeat(2 * 1024 * 1024)
+ for (let index = 0; index < 5; index += 1) {
+ const chatId = `large-window-${index}`
+ await store.createChat('agent-1', chatId)
+ await store.saveMessages('agent-1', chatId, [
+ {
+ id: `message-${index}`,
+ role: 'user',
+ content: largeContent,
+ timestamp: index,
+ },
+ ])
+ }
+
+ const internals = store as unknown as {
+ compatibilityWindows: Map<string, ChatMessage[]>
+ compatibilityWindowsTotalBytes: number
+ }
+ expect(internals.compatibilityWindowsTotalBytes).toBeLessThanOrEqual(8 * 1024 * 1024)
+ expect(internals.compatibilityWindows.size).toBeLessThan(5)
+ })
+
+ it('creates chat-store directories with owner-only permissions', async () => {
+ await store.createChat('agent-1', 'private-chat')
+ await store.saveMessages('agent-1', 'private-chat', [
+ { id: 'm1', role: 'user', content: 'private', timestamp: 1 },
+ ])
+
+ for (const dir of [
+ agentPath(),
+ agentPath('chats'),
+ chatCacheDir('private-chat'),
+ chatPagesDir('private-chat'),
+ ]) {
+ expect((await fs.stat(dir)).mode & 0o777).toBe(0o700)
+ }
+ })
+
it('imports local messages written by a downgraded desktop build', async () => {
await store.createChat('agent-1', 'downgraded-write')
const original = { id: 'm1', role: 'user' as const, content: 'original', timestamp: 1 }
@@ -1198,6 +1315,49 @@ describe('corrupt/missing files', () => {
await store.appendMessages('agent-1', chatId, [replacement])
await expect(store.loadMessages('agent-1', chatId)).resolves.toEqual([replacement])
})
+
+ it('quarantines an unreadable paged snapshot and allows server rehydration', async () => {
+ const chatId = 'corrupt-paged'
+ await store.createChat('agent-1', chatId)
+ await store.saveMessages('agent-1', chatId, [
+ { id: 'old', role: 'user', content: 'old', timestamp: 1 },
+ ])
+ await fs.rm(agentPath(`${chatId}.json`), { force: true })
+ await fs.rm(agentPath(`${chatId}.compat`), { force: true })
+ await fs.writeFile(chatMetaPath(chatId), JSON.stringify({ version: 999, chatId }))
+ await fs.writeFile(join(chatPagesDir(chatId), '000001.json'), 'not-json')
+
+ await expect(store.loadMessages('agent-1', chatId)).resolves.toEqual([])
+ const snapshotRoot = agentPath(
+ 'chats',
+ '.snapshots',
+ Buffer.from(chatId, 'utf8').toString('base64url')
+ )
+ expect((await fs.readdir(snapshotRoot)).some(name => name.startsWith('corrupt-'))).toBe(true)
+
+ const replacement = {
+ id: 'turn-1-user',
+ role: 'user' as const,
+ content: 'rehydrated',
+ timestamp: 2,
+ }
+ await store.appendMessages('agent-1', chatId, [replacement])
+ await expect(store.loadMessages('agent-1', chatId)).resolves.toEqual([replacement])
+ })
+
+ it('deletes matching quarantined legacy files with the chat', async () => {
+ const chatId = 'deleted-corrupt'
+ await store.createChat('agent-1', chatId)
+ const corruptDir = agentPath('.corrupt')
+ await fs.mkdir(corruptDir, { recursive: true })
+ const encodedChatId = Buffer.from(chatId, 'utf8').toString('base64url')
+ await fs.writeFile(join(corruptDir, `${encodedChatId}-fixture.json`), '{}')
+ await fs.writeFile(join(corruptDir, 'another-chat-fixture.json'), '{}')
+
+ await store.deleteChat('agent-1', chatId)
+
+ expect(await fs.readdir(corruptDir)).toEqual(['another-chat-fixture.json'])
+ })
})
// ── unreadTerminal flag (D.5) ────────────────────────────────────────────────
@@ -1266,6 +1426,10 @@ describe('path-segment validation', () => {
)
await expect(store.saveMessages('agent-1', 'a/b', [])).rejects.toThrow(/unsafe path segment/)
await expect(store.saveMessages('agent-1', 'other.next-shadow', [])).resolves.toBeUndefined()
+ await expect(store.saveMessages('agent-1', '.snapshots', [])).rejects.toThrow(
+ /unsafe path segment/
+ )
+ await expect(store.saveMessages('agent-1', 'index', [])).rejects.toThrow(/unsafe path segment/)
})
// Read verbs are tolerant-by-contract (return empty on any failure) — the key
diff --git a/desktop-app/src/__tests__/chatStoreBinding.test.ts b/desktop-app/src/__tests__/chatStoreBinding.test.ts
index 46e1ce64f..0f92dd570 100644
--- a/desktop-app/src/__tests__/chatStoreBinding.test.ts
+++ b/desktop-app/src/__tests__/chatStoreBinding.test.ts
@@ -68,6 +68,36 @@ describe('chatStoreBinding', () => {
expect(() => requireChatStore()).toThrow(/Not authenticated/)
})
+ it('allows an immediate rebind after logout invalidates an in-flight bind', async () => {
+ let releaseFirstRead: (() => void) | undefined
+ const firstReadBlocked = new Promise<void>(resolve => {
+ releaseFirstRead = resolve
+ })
+ let firstReadStarted: (() => void) | undefined
+ const started = new Promise<void>(resolve => {
+ firstReadStarted = resolve
+ })
+ const originalReadDir = fs.readdir.bind(fs)
+ let blocked = false
+ vi.spyOn(fs, 'readdir').mockImplementation(async (...args) => {
+ if (!blocked && String(args[0]).endsWith(path.join(ENV_A, 'user-b'))) {
+ blocked = true
+ firstReadStarted?.()
+ await firstReadBlocked
+ }
+ return originalReadDir(...(args as Parameters<typeof fs.readdir>))
+ })
+
+ const staleBind = bindChatStoreForUser('user-b', ENV_A)
+ await started
+ unbindChatStore()
+ const freshBind = bindChatStoreForUser('user-b', ENV_A)
+ releaseFirstRead?.()
+ await Promise.all([staleBind, freshBind])
+
+ expect(requireChatStore()).toBeDefined()
+ })
+
it('roots the store under <base>/<envKey>/<userId> (spec §5.2)', async () => {
await bindChatStoreForUser('user-a', ENV_A)
const store = requireChatStore()
diff --git a/desktop-app/src/appService.ts b/desktop-app/src/appService.ts
index d0f30fb09..7af2af7b6 100644
--- a/desktop-app/src/appService.ts
+++ b/desktop-app/src/appService.ts
@@ -556,7 +556,16 @@ export class AppService {
const restoreGeneration = this.sessionGeneration
hydrateDesktopRuntimeConfig()
const envKey = getActiveEnvKey()
- const token = await this.tokenStore.getSessionToken(envKey)
+ let token: string | null
+ try {
+ token = await this.tokenStore.getSessionToken(envKey)
+ } catch (error) {
+ console.warn('[AppService] Failed to read the saved session token:', error)
+ if (this.sessionGeneration === restoreGeneration) {
+ this.clearAuthenticatedSessionState()
+ }
+ return { authenticated: false, me: null }
+ }
if (this.logoutInProgress) return { authenticated: false, me: null }
if (!token) {
if (this.sessionGeneration === restoreGeneration) {
@@ -893,9 +902,12 @@ export class AppService {
async logout(): Promise<void> {
this.logoutInProgress = true
- this.clearAuthenticatedSessionState()
- await this.tokenStore.clearSessionToken(getActiveEnvKey())
- this.logoutInProgress = false
+ try {
+ this.clearAuthenticatedSessionState()
+ await this.tokenStore.clearSessionToken(getActiveEnvKey())
+ } finally {
+ this.logoutInProgress = false
+ }
}
/** Resolve a gfs:// URI to its current resource via the API (no local mirror). */
diff --git a/desktop-app/src/chatMessageMerge.ts b/desktop-app/src/chatMessageMerge.ts
index 2d864f89b..fd3d67899 100644
--- a/desktop-app/src/chatMessageMerge.ts
+++ b/desktop-app/src/chatMessageMerge.ts
@@ -69,7 +69,7 @@ export function mergeAuthoritativeServerMessages(
const numberedInRange = turn !== undefined && turn >= firstTurn && turn <= lastTurn
const turnlessInRange =
turn === undefined &&
- (previousTurns[index] ?? Number.NEGATIVE_INFINITY) < firstTurn &&
+ (previousTurns[index] ?? Number.NEGATIVE_INFINITY) <= lastTurn &&
(nextTurns[index] ?? Number.POSITIVE_INFINITY) >= firstTurn
const replaceableTurnRole = message.role === 'user' || message.role === 'assistant'
const belongsToActiveTask =
@@ -99,20 +99,37 @@ export function mergeAuthoritativeServerMessages(
entries.push(message)
availableByRole.set(message.role, entries)
}
- const retainedActiveTaskRoles = new Set(
- kept
- .filter(
- message =>
- message.task_id !== undefined &&
- options.activeTaskIds?.has(message.task_id) === true &&
- (message.role === 'user' || message.role === 'assistant')
+ const claimedAuthoritativeSlots = new Set<string>()
+ for (const [index, message] of existing.entries()) {
+ if (
+ message.task_id === undefined ||
+ options.activeTaskIds?.has(message.task_id) !== true ||
+ (message.role !== 'user' && message.role !== 'assistant')
+ ) {
+ continue
+ }
+ const previous = previousTurns[index] ?? Number.NEGATIVE_INFINITY
+ const next = nextTurns[index] ?? Number.POSITIVE_INFINITY
+ const matchingServerMessage = authoritative.find(serverMessage => {
+ const serverTurn = messageServerTurnNumber(serverMessage)!
+ const slot = `${serverTurn}\u0000${serverMessage.role}`
+ return (
+ serverMessage.role === message.role &&
+ serverTurn > previous &&
+ serverTurn < next &&
+ !claimedAuthoritativeSlots.has(slot)
+ )
+ })
+ if (matchingServerMessage) {
+ claimedAuthoritativeSlots.add(
+ `${messageServerTurnNumber(matchingServerMessage)}\u0000${matchingServerMessage.role}`
)
- .map(message => `${message.task_id}\u0000${message.role}`)
- )
+ }
+ }
const replacements = authoritative
.filter(
message =>
- !(message.task_id && retainedActiveTaskRoles.has(`${message.task_id}\u0000${message.role}`))
+ !claimedAuthoritativeSlots.has(`${messageServerTurnNumber(message)}\u0000${message.role}`)
)
.map(message => {
const sameTurn = removed.find(
diff --git a/desktop-app/src/chatStore.ts b/desktop-app/src/chatStore.ts
index a5fcc3b48..5ce6c579f 100644
--- a/desktop-app/src/chatStore.ts
+++ b/desktop-app/src/chatStore.ts
@@ -2,7 +2,13 @@ import { createHash, randomUUID } from 'node:crypto'
import { promises as fs } from 'node:fs'
import { join } from 'node:path'
import { mergeAuthoritativeServerMessages, messageServerTurnNumber } from './chatMessageMerge.js'
-import type { ChatFile, ChatIndex, ChatMessage, ChatMetadata } from './types.js'
+import type {
+ ChatFile,
+ ChatIndex,
+ ChatMessage,
+ ChatMetadata,
+ ReplaceChatMessagesOptions,
+} from './types.js'
// Keep the catalog at v2 while paged transcripts are dual-readable by the
// pre-paging desktop build. The page layout has its own versioned metadata.
@@ -10,6 +16,7 @@ const INDEX_VERSION = 2
const PAGED_CHAT_VERSION = 1
const DEFAULT_PAGE_SIZE = 100
const MAX_COMPATIBILITY_WINDOWS = 100
+const MAX_COMPATIBILITY_WINDOW_BYTES = 8 * 1024 * 1024
const DEFAULT_MAX_LOCAL_SYNCED_MESSAGES = 1000
const LEGACY_COMPATIBILITY_MESSAGE_LIMIT = 100
const PAGE_FILE_PATTERN = /^\d{6}\.json$/
@@ -96,6 +103,13 @@ function aggregateMessages(
}
}
+function visibleMessageCount(messages: ChatMessage[]): number {
+ return messages.reduce(
+ (total, message) => total + (message.role === 'user' || message.role === 'assistant' ? 1 : 0),
+ 0
+ )
+}
+
function pageEntry(file: string, messages: ChatMessage[]): ChatPageEntry {
const serverTurns = messages
.map(messageServerTurnNumber)
@@ -117,7 +131,8 @@ 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 reservedChatId = label === 'chatId' && (value.startsWith('.') || value === 'index')
+ if (!value || value === '.' || value === '..' || reservedChatId || /[/\\\0]/.test(value)) {
throw new Error(`Invalid ${label}: unsafe path segment`)
}
}
@@ -214,14 +229,28 @@ export class ChatStore {
private cleanedSnapshotSiblingKeys = new Set<string>()
private compatibilityCheckedKeys = new Set<string>()
private compatibilityWindows = new Map<string, ChatMessage[]>()
+ private compatibilityWindowBytes = new Map<string, number>()
+ private compatibilityWindowsTotalBytes = 0
- private cacheCompatibilityWindow(key: string, messages: ChatMessage[]): void {
+ private dropCompatibilityWindow(key: string): void {
this.compatibilityWindows.delete(key)
+ this.compatibilityWindowsTotalBytes -= this.compatibilityWindowBytes.get(key) ?? 0
+ this.compatibilityWindowBytes.delete(key)
+ }
+
+ private cacheCompatibilityWindow(key: string, messages: ChatMessage[]): void {
+ this.dropCompatibilityWindow(key)
+ const sizeBytes = Buffer.byteLength(JSON.stringify(messages), 'utf8')
this.compatibilityWindows.set(key, [...messages])
- while (this.compatibilityWindows.size > MAX_COMPATIBILITY_WINDOWS) {
+ this.compatibilityWindowBytes.set(key, sizeBytes)
+ this.compatibilityWindowsTotalBytes += sizeBytes
+ while (
+ this.compatibilityWindows.size > MAX_COMPATIBILITY_WINDOWS ||
+ this.compatibilityWindowsTotalBytes > MAX_COMPATIBILITY_WINDOW_BYTES
+ ) {
const oldestKey = this.compatibilityWindows.keys().next().value
if (typeof oldestKey !== 'string') break
- this.compatibilityWindows.delete(oldestKey)
+ this.dropCompatibilityWindow(oldestKey)
}
}
@@ -407,7 +436,10 @@ export class ChatStore {
// truncated JSON. Quarantine only malformed content; filesystem errors
// above still propagate. Returning "no legacy snapshot" lets the server
// rehydrate the chat and makes subsequent appends writable again.
- await fs.mkdir(join(this.agentDir(agentRef), '.corrupt'), { recursive: true })
+ await fs.mkdir(join(this.agentDir(agentRef), '.corrupt'), {
+ recursive: true,
+ mode: 0o700,
+ })
await fs.rename(
this.chatFilePath(agentRef, chatId),
this.corruptLegacyChatFilePath(agentRef, chatId)
@@ -956,7 +988,18 @@ export class ChatStore {
this.cleanedSnapshotSiblingKeys.add(cleanupKey)
return await this.readPagedMeta(agentRef, chatId)
}
- if (activeReadError) throw activeReadError
+ if (activeReadError) {
+ const corruptDir = this.chatSnapshotSiblingPath(agentRef, chatId, 'corrupt', randomUUID())
+ await fs.mkdir(this.chatSnapshotRootPath(agentRef, chatId), {
+ recursive: true,
+ mode: 0o700,
+ })
+ await fs.rename(activeDir, corruptDir).catch(err => {
+ if (!isNotFoundError(err)) throw err
+ })
+ console.warn(`[chatStore] Quarantined unreadable paged cache for "${chatId}"`)
+ return null
+ }
return null
}
@@ -1002,9 +1045,9 @@ export class ChatStore {
let movedExistingSnapshot = false
this.cleanedSnapshotSiblingKeys.delete(this.chatSnapshotCleanupKey(agentRef, chatId))
- await fs.mkdir(join(this.agentDir(agentRef), 'chats'), { recursive: true })
+ await fs.mkdir(join(this.agentDir(agentRef), 'chats'), { recursive: true, mode: 0o700 })
await fs.rm(stagingDir, { recursive: true, force: true })
- await fs.mkdir(pagesDir, { recursive: true })
+ await fs.mkdir(pagesDir, { recursive: true, mode: 0o700 })
try {
const pages: ChatPageEntry[] = []
@@ -1214,7 +1257,7 @@ export class ChatStore {
private async saveIndex(agentRef: string, index: ChatIndex): Promise<void> {
const dir = this.agentDir(agentRef)
- await fs.mkdir(dir, { recursive: true })
+ await fs.mkdir(dir, { recursive: true, mode: 0o700 })
// Keep the index readable by the pre-paging desktop while the transcript
// files are maintained in both paged and bounded v2-compatible forms.
const normalized: ChatIndex = { ...index, version: INDEX_VERSION }
@@ -1295,13 +1338,21 @@ export class ChatStore {
await this.saveIndex(agentRef, index)
})
await fs.rm(this.chatFilePath(agentRef, chatId), { force: true })
+ const encodedChatId = Buffer.from(chatId, 'utf8').toString('base64url')
+ const corruptLegacyDir = join(this.agentDir(agentRef), '.corrupt')
+ const corruptLegacyEntries = await fs.readdir(corruptLegacyDir).catch(() => [])
+ await Promise.all(
+ corruptLegacyEntries
+ .filter(name => name.startsWith(`${encodedChatId}-`) && name.endsWith('.json'))
+ .map(name => fs.rm(join(corruptLegacyDir, name), { force: true }))
+ )
await fs.rm(this.chatCompatibilitySignaturePath(agentRef, chatId), { force: true })
await fs.rm(this.chatDirPath(agentRef, chatId), { recursive: true, force: true })
await this.removePagedChatSnapshotSiblings(agentRef, chatId)
const cacheKey = this.chatSnapshotCleanupKey(agentRef, chatId)
this.cleanedSnapshotSiblingKeys.delete(cacheKey)
this.compatibilityCheckedKeys.delete(cacheKey)
- this.compatibilityWindows.delete(cacheKey)
+ this.dropCompatibilityWindow(cacheKey)
})
}
@@ -1335,12 +1386,13 @@ export class ChatStore {
if (!chat) return
const aggregate = aggregateMessages(messages)
+ const displayMessageCount = visibleMessageCount(messages)
if (options.preserveExistingTotals) {
- chat.messageCount = Math.max(chat.messageCount ?? 0, messages.length)
+ chat.messageCount = Math.max(chat.messageCount ?? 0, displayMessageCount)
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
+ chat.messageCount = displayMessageCount
Object.assign(chat, aggregate)
}
if (options.touchUpdatedAt !== false) {
@@ -1391,13 +1443,22 @@ export class ChatStore {
* 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> {
+ async replaceMessages(
+ agentRef: string,
+ chatId: string,
+ messages: ChatMessage[],
+ options: ReplaceChatMessagesOptions = {}
+ ): Promise<void> {
await this.serializeChat(agentRef, chatId, async () => {
const existingMeta = await this.readOrMigratePagedChatUnlocked(agentRef, chatId)
const existingMessages = existingMeta
? await this.readMessagesFromPagedMeta(agentRef, chatId, existingMeta)
: []
- const merged = mergeAuthoritativeServerMessages(existingMessages, messages)
+ const merged = options.replaceLocalWindow
+ ? messages
+ : mergeAuthoritativeServerMessages(existingMessages, messages, {
+ activeTaskIds: options.activeTaskIds ? new Set(options.activeTaskIds) : undefined,
+ })
const indexedCount = await this.indexedMessageCount(agentRef, chatId)
await this.writePagedChatUnlocked(agentRef, chatId, merged, {
messageCount: Math.max(merged.length, indexedCount ?? 0),
diff --git a/desktop-app/src/chatStoreBinding.ts b/desktop-app/src/chatStoreBinding.ts
index ad6d9ef5b..49bec7291 100644
--- a/desktop-app/src/chatStoreBinding.ts
+++ b/desktop-app/src/chatStoreBinding.ts
@@ -114,7 +114,7 @@ async function maybeWipePreEnvLegacyCache(baseDir: string): Promise<void> {
if ((err as NodeJS.ErrnoException).code === 'ENOENT') {
// Fresh install — nothing legacy to wipe. Create the base + marker so the
// scan never runs again.
- await fs.mkdir(baseDir, { recursive: true })
+ await fs.mkdir(baseDir, { recursive: true, mode: 0o700 })
await writeMigrationMarker(markerPath)
return
}
@@ -221,6 +221,7 @@ async function maybeWipeLegacyCache(userDir: string): Promise<void> {
export function unbindChatStore(): void {
bindingGeneration += 1
+ bindInFlight = null
activeChatStore = null
activeUserId = null
activeEnvKey = null
diff --git a/desktop-app/src/ipc.ts b/desktop-app/src/ipc.ts
index b96f8eed2..8f09897fe 100644
--- a/desktop-app/src/ipc.ts
+++ b/desktop-app/src/ipc.ts
@@ -44,7 +44,7 @@ function sanitizeSessionsListQuery(
if (agent && (agent.length > 200 || agent.includes(':'))) {
throw new Error('Invalid session agent')
}
- if (cursor.length > 4096) throw new Error('Invalid sessions cursor')
+ if (cursor.length > 2048) throw new Error('Invalid sessions cursor')
const rawLimit = sanitizeOptionalInteger(input?.limit)
if (rawLimit !== undefined && rawLimit < 1) throw new Error('Invalid sessions limit')
return {
@@ -1127,16 +1127,33 @@ export function registerIpcHandlers(service: AppService): void {
ipcMain.handle(
'chat:replaceMessages',
- async (event, payload: { agentRef: string; chatId: string; messages: unknown[] }) => {
+ async (
+ event,
+ payload: {
+ agentRef: string
+ chatId: string
+ messages: unknown[]
+ options?: import('./types.js').ReplaceChatMessagesOptions
+ }
+ ) => {
assertTrustedSender(event)
const agentRef = sanitizeString(payload?.agentRef)
const chatId = sanitizeString(payload?.chatId)
if (!agentRef || !chatId) throw new Error('agentRef and chatId are required')
const messages = Array.isArray(payload?.messages) ? payload.messages : []
+ const activeTaskIds = Array.isArray(payload?.options?.activeTaskIds)
+ ? payload.options.activeTaskIds
+ .filter((taskId): taskId is string => typeof taskId === 'string' && taskId.length > 0)
+ .slice(0, 32)
+ : undefined
await requireChatStore().replaceMessages(
agentRef,
chatId,
- messages as import('./types.js').ChatMessage[]
+ messages as import('./types.js').ChatMessage[],
+ {
+ activeTaskIds,
+ replaceLocalWindow: payload?.options?.replaceLocalWindow === true,
+ }
)
}
)
diff --git a/desktop-app/src/preload.ts b/desktop-app/src/preload.ts
index 7c2729108..24c176c54 100644
--- a/desktop-app/src/preload.ts
+++ b/desktop-app/src/preload.ts
@@ -400,8 +400,12 @@ const clerum = Object.freeze({
ipcRenderer.invoke('chat:loadMessages', { agentRef, chatId, limit, offset }),
appendMessages: (agentRef: string, chatId: string, messages: unknown[]) =>
ipcRenderer.invoke('chat:appendMessages', { agentRef, chatId, messages }),
- replaceMessages: (agentRef: string, chatId: string, messages: unknown[]) =>
- ipcRenderer.invoke('chat:replaceMessages', { agentRef, chatId, messages }),
+ replaceMessages: (
+ agentRef: string,
+ chatId: string,
+ messages: unknown[],
+ options?: import('./types.js').ReplaceChatMessagesOptions
+ ) => ipcRenderer.invoke('chat:replaceMessages', { agentRef, chatId, messages, options }),
backfillCounters: (agentRef: string, chatId: string, messages: unknown[]) =>
ipcRenderer.invoke('chat:backfillCounters', { agentRef, chatId, messages }),
markUnreadTerminal: (agentRef: string, chatId: string) =>
diff --git a/desktop-app/src/renderer.d.ts b/desktop-app/src/renderer.d.ts
index 5df8a83a8..31496c42e 100644
--- a/desktop-app/src/renderer.d.ts
+++ b/desktop-app/src/renderer.d.ts
@@ -22,6 +22,7 @@ import {
PendingWorkflowApproval,
PrewarmHostResult,
ProfileSettingsOpenOptions,
+ ReplaceChatMessagesOptions,
RpcAllowedServersResult,
SessionMessagesQuery,
SessionMessagesResult,
@@ -492,7 +493,8 @@ declare global {
replaceMessages: (
agentRef: string,
chatId: string,
- messages: ChatMessage[]
+ messages: ChatMessage[],
+ options?: ReplaceChatMessagesOptions
) => Promise<void>
backfillCounters: (
agentRef: string,
diff --git a/desktop-app/src/rpcProxyClient.ts b/desktop-app/src/rpcProxyClient.ts
index b1856e217..67f9eef1e 100644
--- a/desktop-app/src/rpcProxyClient.ts
+++ b/desktop-app/src/rpcProxyClient.ts
@@ -29,6 +29,12 @@ import {
*/
const MODEL_NOT_ALLOWED = 'model_not_allowed'
+function assertSafePathSegment(label: string, value: string): void {
+ if (!value || value === '.' || value === '..' || /[/\\\0]/.test(value)) {
+ throw new Error(`Invalid ${label}: unsafe path segment`)
+ }
+}
+
/**
* mcp-host answers HTTP 200 with `{success:false, error}` when an approval was
* already decided by another channel (spec-v2 §4.7.4). Parse the body into a
@@ -576,6 +582,9 @@ export class RpcProxyClient {
chatId: string,
query: SessionMessagesQuery = {}
): Promise<SessionMessagesResult> {
+ assertSafePathSegment('hostRef', hostRef)
+ assertSafePathSegment('agent', agent)
+ assertSafePathSegment('chatId', chatId)
const requestUrl = new URL(
url(
`/api/v1/rpc/hosts/${encodeURIComponent(hostRef)}/sessions/${encodeURIComponent(agent)}/${encodeURIComponent(chatId)}/messages`
@@ -626,6 +635,9 @@ export class RpcProxyClient {
agent: string,
chatId: string
): Promise<ContextBreakdownResult> {
+ assertSafePathSegment('hostRef', hostRef)
+ assertSafePathSegment('agent', agent)
+ assertSafePathSegment('chatId', chatId)
const response = await fetch(
url(
`/api/v1/rpc/hosts/${encodeURIComponent(hostRef)}/sessions/${encodeURIComponent(agent)}/${encodeURIComponent(chatId)}/context-breakdown`
diff --git a/desktop-app/src/serverTurnAdapter.ts b/desktop-app/src/serverTurnAdapter.ts
new file mode 100644
index 000000000..2311ed58c
--- /dev/null
+++ b/desktop-app/src/serverTurnAdapter.ts
@@ -0,0 +1,60 @@
+import type {
+ ChatMessage,
+ ChatMessageAttachment,
+ MessageToolStep,
+ SessionTokensLite,
+} from './types'
+
+export interface ServerTurn {
+ number: number
+ user_input: string
+ response?: string
+ started_at: string
+ completed_at?: string
+ tokens?: SessionTokensLite
+ tool_steps?: MessageToolStep[]
+}
+
+type UserMessageDisplay = {
+ content: string
+ attachments: ChatMessageAttachment[]
+}
+
+/**
+ * Convert runtime turns to deterministic local messages.
+ *
+ * The optional display parser lets the renderer recover structured attachment
+ * chips while keeping server-turn identity shared with main-process tests.
+ */
+export function turnsToChatMessages(
+ turns: ServerTurn[],
+ parseUserDisplay: (content: string) => UserMessageDisplay = content => ({
+ content,
+ attachments: [],
+ })
+): ChatMessage[] {
+ const out: ChatMessage[] = []
+ for (const turn of turns) {
+ const userDisplay = parseUserDisplay(turn.user_input)
+ out.push({
+ id: `turn-${turn.number}-user`,
+ role: 'user',
+ content: userDisplay.content,
+ timestamp: Date.parse(turn.started_at),
+ serverTurnNumber: turn.number,
+ ...(userDisplay.attachments.length ? { attachments: userDisplay.attachments } : {}),
+ })
+ if (turn.response !== undefined) {
+ out.push({
+ id: `turn-${turn.number}-assistant`,
+ role: 'assistant',
+ content: turn.response,
+ timestamp: Date.parse(turn.completed_at ?? turn.started_at),
+ serverTurnNumber: turn.number,
+ ...(turn.tokens ? { tokens: turn.tokens } : {}),
+ ...(turn.tool_steps?.length ? { toolSteps: turn.tool_steps } : {}),
+ })
+ }
+ }
+ return out
+}
diff --git a/desktop-app/src/types.ts b/desktop-app/src/types.ts
index 875c43e3a..70980a115 100644
--- a/desktop-app/src/types.ts
+++ b/desktop-app/src/types.ts
@@ -1038,6 +1038,18 @@ export interface ChatMessage {
toolSteps?: MessageToolStep[]
}
+/**
+ * Controls how an authoritative server page is persisted locally.
+ *
+ * `activeTaskIds` lets the main process protect the same optimistic slots as
+ * the renderer. `replaceLocalWindow` is used only by the bounded latest-page
+ * fallback, where stale numbered turns must not survive on disk.
+ */
+export interface ReplaceChatMessagesOptions {
+ activeTaskIds?: string[]
+ replaceLocalWindow?: boolean
+}
+
/**
* The minimal, serializable subset of a tool call needed to render the desktop
* progress stepper's collapsed "N tools" / "More details" view after a reload.
diff --git a/desktop-app/ui/src/components/agents/__tests__/chatThread.toolSteps.test.tsx b/desktop-app/ui/src/components/agents/__tests__/chatThread.toolSteps.test.tsx
index f78d41aef..a2bf25f2c 100644
--- a/desktop-app/ui/src/components/agents/__tests__/chatThread.toolSteps.test.tsx
+++ b/desktop-app/ui/src/components/agents/__tests__/chatThread.toolSteps.test.tsx
@@ -11,6 +11,7 @@
import type { ReactNode } from 'react'
import { afterEach, describe, expect, it, vi } from 'vitest'
import { cleanup, render, screen } from '@testing-library/react'
+import userEvent from '@testing-library/user-event'
import type { MessageToolStep } from '../../../../../src/types'
import type { AgentChatMessage, TaskProgress } from '../../../uiTypes'
// vi.mock calls are hoisted above this import, so ChatThread binds the mocks.
@@ -34,6 +35,9 @@ let threadStateValue: {
activeChatId: string | null
activityByMessageId: Record<string, unknown>
progressByMessageId: Record<string, TaskProgress>
+ hasOlderMessages: boolean
+ olderMessagesLoading: boolean
+ handleLoadOlderMessages: ReturnType<typeof vi.fn>
}
vi.mock('@contexts/NavigationContext', () => ({ useNavigationContext: () => navValue }))
@@ -85,7 +89,8 @@ const toolSteps: MessageToolStep[] = [
function setThreadState(
groupedMessages: typeof threadStateValue.groupedMessages,
- progressByMessageId: Record<string, TaskProgress> = {}
+ progressByMessageId: Record<string, TaskProgress> = {},
+ options: { hasOlderMessages?: boolean; olderMessagesLoading?: boolean } = {}
) {
const activeMessages = groupedMessages.flatMap(g => g.items)
threadStateValue = {
@@ -95,6 +100,9 @@ function setThreadState(
activeChatId: 'c1',
activityByMessageId: {},
progressByMessageId,
+ hasOlderMessages: options.hasOlderMessages ?? false,
+ olderMessagesLoading: options.olderMessagesLoading ?? false,
+ handleLoadOlderMessages: vi.fn().mockResolvedValue(undefined),
}
}
@@ -209,4 +217,38 @@ describe('ChatThread tool-steps fallback (#582)', () => {
expect(screen.getByText(/More details · 1 tool\b/i)).toBeTruthy()
expect(screen.queryByText(/More details · 2 tools/i)).toBeNull()
})
+
+ it('renders and invokes the older-history page control', async () => {
+ const user = userEvent.setup()
+ setThreadState([{ role: 'user', items: [userMsg] }], {}, { hasOlderMessages: true })
+
+ render(<ChatThread />)
+
+ await user.click(screen.getByRole('button', { name: 'Load older messages' }))
+ expect(threadStateValue.handleLoadOlderMessages).toHaveBeenCalledTimes(1)
+ })
+
+ it('wraps long histories in virtualized message chunks', () => {
+ const groups = Array.from({ length: 10 }, (_, index) => {
+ const role = index % 2 === 0 ? ('user' as const) : ('assistant' as const)
+ const turn = Math.floor(index / 2) + 1
+ return {
+ role,
+ items: [
+ {
+ id: `turn-${turn}-${role}`,
+ role,
+ content: `${role} ${turn}`,
+ timestamp: index,
+ serverTurnNumber: turn,
+ },
+ ],
+ }
+ })
+ setThreadState(groups)
+
+ const { container } = render(<ChatThread />)
+
+ expect(container.querySelectorAll('.virtualized-message-chunk').length).toBeGreaterThan(1)
+ })
})
diff --git a/desktop-app/ui/src/hooks/domain/__tests__/backOnlineDispatcher.test.tsx b/desktop-app/ui/src/hooks/domain/__tests__/backOnlineDispatcher.test.tsx
index 5a6fd148c..63de6a9eb 100644
--- a/desktop-app/ui/src/hooks/domain/__tests__/backOnlineDispatcher.test.tsx
+++ b/desktop-app/ui/src/hooks/domain/__tests__/backOnlineDispatcher.test.tsx
@@ -53,7 +53,7 @@ describe('BACK_ONLINE dispatcher (§4.1)', () => {
'agent-x',
'chat-offline',
undefined,
- { limit: 80 }
+ { limit: 40 }
)
)
})
diff --git a/desktop-app/ui/src/hooks/domain/__tests__/chatSelectionAcrossRouteChange.test.tsx b/desktop-app/ui/src/hooks/domain/__tests__/chatSelectionAcrossRouteChange.test.tsx
index ba9c5be89..470ba685a 100644
--- a/desktop-app/ui/src/hooks/domain/__tests__/chatSelectionAcrossRouteChange.test.tsx
+++ b/desktop-app/ui/src/hooks/domain/__tests__/chatSelectionAcrossRouteChange.test.tsx
@@ -148,7 +148,7 @@ describe('selecting a chat session across a route change', () => {
'agent-x',
'c-old',
undefined,
- { limit: 80 }
+ { limit: 40 }
)
)
expect(result.current.activeChatId).toBe('c-old')
@@ -158,7 +158,7 @@ describe('selecting a chat session across a route change', () => {
'agent-x',
'c-newest',
undefined,
- { limit: 80 }
+ { limit: 40 }
)
})
@@ -182,7 +182,7 @@ describe('selecting a chat session across a route change', () => {
'agent-x',
'c-old',
undefined,
- { limit: 80 }
+ { limit: 40 }
)
})
@@ -213,7 +213,7 @@ describe('selecting a chat session across a route change', () => {
'agent-x',
'c-old',
undefined,
- { limit: 80 }
+ { limit: 40 }
)
)
expect(result.current.activeChatId).toBe('c-old')
@@ -222,7 +222,7 @@ describe('selecting a chat session across a route change', () => {
'agent-x',
'c-newest',
undefined,
- { limit: 80 }
+ { limit: 40 }
)
})
@@ -366,7 +366,7 @@ describe('chat-route guard on the real selection entry points', () => {
'agent-x',
'c-old',
undefined,
- { limit: 80 }
+ { limit: 40 }
),
SLOW
)
@@ -410,7 +410,7 @@ describe('chat-route guard on the real selection entry points', () => {
'agent-x',
'c-old',
undefined,
- { limit: 80 }
+ { limit: 40 }
),
SLOW
)
@@ -471,7 +471,7 @@ describe('chat-route guard on the real selection entry points', () => {
'agent-x',
'c-old',
undefined,
- { limit: 80 }
+ { limit: 40 }
),
SLOW
)
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.tsx
index 697053e9f..8ff3aedff 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
@@ -133,7 +133,7 @@ describe('pendingChatSelection effect', () => {
'agent-x',
'c-latest',
undefined,
- { limit: 80 }
+ { limit: 40 }
)
})
@@ -167,7 +167,7 @@ describe('pendingChatSelection effect', () => {
'agent-x',
'c-newest',
undefined,
- { limit: 80 }
+ { limit: 40 }
)
})
@@ -273,7 +273,7 @@ describe('pendingChatSelection effect', () => {
'agent-x',
'c-specific',
undefined,
- { limit: 80 }
+ { limit: 40 }
)
)
await waitFor(() => expect(result.current.activeChatId).toBe('c-specific'))
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.tsx
index 0860834c6..37f0f14d1 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
@@ -70,7 +70,7 @@ describe('switchToChat (unified, D.4)', () => {
'agent-x',
'c1',
undefined,
- { limit: 80, afterTurn: 1 }
+ { limit: 40, afterTurn: 1 }
)
expect(clerum.chat.replaceMessages).not.toHaveBeenCalled()
expect(result.current.chatMessages).toHaveLength(2)
@@ -169,7 +169,7 @@ describe('switchToChat (unified, D.4)', () => {
'agent-x',
'delta-pages',
undefined,
- { limit: 80, afterTurn: 1 }
+ { limit: 40, afterTurn: 1 }
)
expect(clerum.rpc.loadSessionMessages).toHaveBeenNthCalledWith(
2,
@@ -177,7 +177,7 @@ describe('switchToChat (unified, D.4)', () => {
'agent-x',
'delta-pages',
undefined,
- { limit: 80, afterTurn: 2 }
+ { limit: 40, afterTurn: 2 }
)
expect(result.current.chatMessages).toHaveLength(6)
expect(clerum.chat.replaceMessages).toHaveBeenCalledWith(
@@ -294,13 +294,22 @@ describe('switchToChat (unified, D.4)', () => {
'agent-x',
'delta-cap',
undefined,
- { limit: 80 }
+ { limit: 40 }
)
expect(result.current.chatMessages.map(message => message.id)).toEqual([
'turn-999-user',
'turn-999-assistant',
])
expect(result.current.hasOlderMessages).toBe(true)
+ expect(clerum.chat.replaceMessages).toHaveBeenCalledWith(
+ 'agent-x',
+ 'delta-cap',
+ expect.arrayContaining([expect.objectContaining({ id: 'turn-999-assistant' })]),
+ {
+ activeTaskIds: undefined,
+ replaceLocalWindow: true,
+ }
+ )
})
it('loads older history on demand and prepends it without blocking first render', async () => {
@@ -356,7 +365,7 @@ describe('switchToChat (unified, D.4)', () => {
'agent-x',
'older-pages',
undefined,
- { limit: 80, beforeTurn: 21 }
+ { limit: 40, beforeTurn: 21 }
)
expect(result.current.chatMessages).toHaveLength(120)
expect(result.current.chatMessages[0]?.id).toBe('turn-1-user')
@@ -688,6 +697,15 @@ describe('switchToChat (unified, D.4)', () => {
})
)
expect(result.current.progressByMessageId['<unknown>']).toBeUndefined()
+ expect(clerum.chat.replaceMessages).toHaveBeenCalledWith(
+ 'agent-x',
+ 'p1a',
+ expect.arrayContaining([expect.objectContaining({ id: 'turn-1-user' })]),
+ {
+ activeTaskIds: ['task-p1a'],
+ replaceLocalWindow: false,
+ }
+ )
})
it('P1-B: a processing-snapshot rejoin does not loop and settles within the cap', async () => {
diff --git a/desktop-app/ui/src/hooks/domain/__tests__/useActivityController.test.tsx b/desktop-app/ui/src/hooks/domain/__tests__/useActivityController.test.tsx
index 70da270b3..c8835c9ce 100644
--- a/desktop-app/ui/src/hooks/domain/__tests__/useActivityController.test.tsx
+++ b/desktop-app/ui/src/hooks/domain/__tests__/useActivityController.test.tsx
@@ -109,9 +109,10 @@ describe('useActivityController', () => {
toolSteps: [{ toolName: 'read', displayName: 'Read', state: 'completed' }],
},
])
+ const backfillCounters = vi.fn().mockResolvedValue(undefined)
Object.defineProperty(window, 'clerum', {
configurable: true,
- value: { chat: { getIndex, loadMessages } },
+ value: { chat: { getIndex, loadMessages, backfillCounters } },
})
const { result } = renderHook(() =>
@@ -140,5 +141,110 @@ describe('useActivityController', () => {
})
)
expect(loadMessages).toHaveBeenCalledWith('agent-a', 'legacy-chat', 1000, undefined)
+ expect(backfillCounters).toHaveBeenCalledWith(
+ 'agent-a',
+ 'legacy-chat',
+ expect.arrayContaining([expect.objectContaining({ id: 'm1' })])
+ )
+ })
+
+ it('does not download transcripts for server-only catalog entries', async () => {
+ const getIndex = vi.fn(async () => ({
+ version: 3,
+ lastActiveChatId: null,
+ onboardingDismissed: false,
+ chats: [],
+ }))
+ const loadMessages = vi.fn()
+ Object.defineProperty(window, 'clerum', {
+ configurable: true,
+ value: { chat: { getIndex, loadMessages } },
+ })
+
+ renderHook(() =>
+ useActivityController({
+ selectedAgent: 'agent-a',
+ isAuthenticated: true,
+ loadMenuData: true,
+ chatList: [
+ {
+ id: 'remote-chat',
+ title: 'Remote',
+ createdAt: '2026-07-22T00:00:00.000Z',
+ updatedAt: '2026-07-22T00:00:00.000Z',
+ messageCount: 2,
+ remote: true,
+ },
+ ],
+ progressByAgentMessage: EMPTY_PROGRESS,
+ agentNames: AGENT_A,
+ })
+ )
+
+ await waitFor(() => expect(getIndex).toHaveBeenCalled())
+ expect(loadMessages).not.toHaveBeenCalled()
+ })
+
+ it('keeps prior backfills when a later chat list adds another legacy chat', async () => {
+ const loadMessages = vi.fn(async (_agentRef: string, chatId: string) =>
+ chatId === 'legacy-one'
+ ? [{ id: 'e1', role: 'assistant', content: 'failed', timestamp: 1, isError: true }]
+ : [
+ {
+ id: 't1',
+ role: 'assistant',
+ content: 'used tool',
+ timestamp: 2,
+ toolSteps: [{ toolName: 'read', displayName: 'Read', state: 'completed' }],
+ },
+ ]
+ )
+ Object.defineProperty(window, 'clerum', {
+ configurable: true,
+ value: {
+ chat: {
+ getIndex: vi.fn(async () => ({ chats: [] })),
+ loadMessages,
+ backfillCounters: vi.fn().mockResolvedValue(undefined),
+ },
+ },
+ })
+ const baseChat = {
+ title: 'Legacy',
+ createdAt: '2026-07-22T00:00:00.000Z',
+ updatedAt: '2026-07-22T00:00:00.000Z',
+ messageCount: 1,
+ }
+ const initialProps = {
+ chatList: [{ ...baseChat, id: 'legacy-one' }],
+ }
+ const { result, rerender } = renderHook(
+ ({ chatList }: typeof initialProps) =>
+ useActivityController({
+ selectedAgent: 'agent-a',
+ isAuthenticated: true,
+ loadMenuData: true,
+ chatList,
+ progressByAgentMessage: EMPTY_PROGRESS,
+ agentNames: AGENT_A,
+ }),
+ { initialProps }
+ )
+
+ await waitFor(() => expect(result.current.selectedAgentActivitySummary.errors).toBe(1))
+
+ rerender({
+ chatList: [
+ { ...baseChat, id: 'legacy-one' },
+ { ...baseChat, id: 'legacy-two', updatedAt: '2026-07-23T00:00:00.000Z' },
+ ],
+ })
+
+ await waitFor(() =>
+ expect(result.current.selectedAgentActivitySummary).toMatchObject({
+ errors: 1,
+ toolCalls: 1,
+ })
+ )
})
})
diff --git a/desktop-app/ui/src/hooks/domain/__tests__/useAgentChatController.test.tsx b/desktop-app/ui/src/hooks/domain/__tests__/useAgentChatController.test.tsx
index c47be00ab..afff7d8a3 100644
--- a/desktop-app/ui/src/hooks/domain/__tests__/useAgentChatController.test.tsx
+++ b/desktop-app/ui/src/hooks/domain/__tests__/useAgentChatController.test.tsx
@@ -75,7 +75,7 @@ describe('useAgentChatController — characterization (D.0)', () => {
'agent-x',
'chat-1',
undefined,
- { limit: 80 }
+ { limit: 40 }
)
// Cache was up to date → no overwrite, no rejoin.
expect(clerum.chat.replaceMessages).not.toHaveBeenCalled()
@@ -111,7 +111,7 @@ describe('useAgentChatController — characterization (D.0)', () => {
'agent-x',
'chat-2',
undefined,
- { limit: 80 }
+ { limit: 40 }
)
expect(clerum.chat.create).toHaveBeenCalledWith('agent-x', 'chat-2')
// Server is source of truth → replace, not append.
@@ -1011,6 +1011,40 @@ describe('useAgentChatController — characterization (D.0)', () => {
expect(result.current.latestChatSessionsLoading).toBe(false)
})
+ it('does not replace a newer local auto-selection with an older server session', async () => {
+ clerum.chat.getIndex.mockResolvedValue({
+ version: 1,
+ lastActiveChatId: null,
+ onboardingDismissed: false,
+ chats: [
+ {
+ id: 'newer-local',
+ title: 'Newer local chat',
+ createdAt: '2026-05-03T00:00:00Z',
+ updatedAt: '2026-05-03T00:00:00Z',
+ messageCount: 2,
+ },
+ ],
+ })
+ clerum.rpc.listSessions.mockResolvedValue({
+ items: [
+ {
+ agent: 'agent-x',
+ chatId: 'older-server',
+ turnCount: 1,
+ lastActivityAt: '2026-05-02T00:00:00Z',
+ },
+ ],
+ })
+
+ const { result } = renderController({ navItem: 'chat' })
+
+ await waitFor(() => expect(result.current.activeChatId).toBe('newer-local'))
+ await waitFor(() => expect(clerum.rpc.listSessions).toHaveBeenCalled())
+ expect(result.current.activeChatId).toBe('newer-local')
+ expect(clerum.chat.setLastActive).not.toHaveBeenCalledWith('agent-x', 'older-server')
+ })
+
it('loads the next remote session page only when requested', async () => {
clerum.rpc.listSessions.mockImplementation(
async (_hostRef: string, _teamId: string | undefined, query?: { cursor?: string }) => {
diff --git a/desktop-app/ui/src/hooks/domain/useActivityController.ts b/desktop-app/ui/src/hooks/domain/useActivityController.ts
index fd65af124..af01c00d0 100644
--- a/desktop-app/ui/src/hooks/domain/useActivityController.ts
+++ b/desktop-app/ui/src/hooks/domain/useActivityController.ts
@@ -94,7 +94,14 @@ export function useActivityController({
const missingCounterChatIds = JSON.stringify(
chatList
- .filter(chat => chat.errorCount === undefined || chat.toolCallCount === undefined)
+ .filter(chat => {
+ const key = selectedAgent ? activityCounterKey(selectedAgent, chat.id) : ''
+ return (
+ !chat.remote &&
+ backfilledCountersByChat[key] === undefined &&
+ (chat.errorCount === undefined || chat.toolCallCount === undefined)
+ )
+ })
.sort((left, right) => Date.parse(right.updatedAt) - Date.parse(left.updatedAt))
.slice(0, ACTIVITY_SUMMARY_CHAT_SCAN_LIMIT)
.map(chat => chat.id)
@@ -132,7 +139,12 @@ export function useActivityController({
] as const
})
).then(entries => {
- if (!cancelled) setBackfilledCountersByChat(Object.fromEntries(entries))
+ if (!cancelled) {
+ setBackfilledCountersByChat(previous => ({
+ ...previous,
+ ...Object.fromEntries(entries),
+ }))
+ }
})
return () => {
diff --git a/desktop-app/ui/src/hooks/domain/useAgentChatController.ts b/desktop-app/ui/src/hooks/domain/useAgentChatController.ts
index 27adbc399..6a373b55f 100644
--- a/desktop-app/ui/src/hooks/domain/useAgentChatController.ts
+++ b/desktop-app/ui/src/hooks/domain/useAgentChatController.ts
@@ -103,7 +103,8 @@ const MAX_ACTIVITY_EVENTS_PER_MESSAGE = 100
* persisted `toolSteps` (#582 fallback in ChatThread).
*/
const MAX_MESSAGES_WITH_ACTIVITY_PER_AGENT = 50
-const MESSAGE_PAGE_SIZE = 80
+const LOCAL_MESSAGE_PAGE_SIZE = 80
+const SERVER_TURN_PAGE_SIZE = 40
const MAX_RECONCILE_DELTA_PAGES = 5
const REPLACE_LOCAL_RECONCILIATION_WINDOW = Symbol('replace-local-reconciliation-window')
type ReconciliationMessagesResult = SessionMessagesResult & {
@@ -751,7 +752,7 @@ export function useAgentChatController({
// below requests a delta after the newest cached server turn.
let cached: Awaited<ReturnType<typeof chatStore.loadMessages>> = []
try {
- cached = await chatStore.loadMessages(agentRef, chatId, MESSAGE_PAGE_SIZE)
+ cached = await chatStore.loadMessages(agentRef, chatId, LOCAL_MESSAGE_PAGE_SIZE)
} catch (error) {
console.warn('[chat-history] failed to load local messages', { agentRef, chatId, error })
}
@@ -759,8 +760,8 @@ export function useAgentChatController({
const hasOlderServerMessages = Boolean(oldestCachedTurn && oldestCachedTurn > 1)
const hasOlderLocalMessages =
!hasOlderServerMessages &&
- cached.length === MESSAGE_PAGE_SIZE &&
- (await hasLocalMessagesBeyond(chatStore, agentRef, chatId, MESSAGE_PAGE_SIZE))
+ cached.length === LOCAL_MESSAGE_PAGE_SIZE &&
+ (await hasLocalMessagesBeyond(chatStore, agentRef, chatId, LOCAL_MESSAGE_PAGE_SIZE))
if (!isStillActive()) return
loadedLocalMessageCountRef.current = cached.length
setHasOlderMessages(hasOlderLocalMessages || hasOlderServerMessages)
@@ -809,7 +810,7 @@ export function useAgentChatController({
taskIdHint: zombieBefore?.taskId,
isRelevant: isStillActive,
messagesQuery: {
- limit: MESSAGE_PAGE_SIZE,
+ limit: SERVER_TURN_PAGE_SIZE,
...(latestCachedTurn !== undefined ? { afterTurn: latestCachedTurn } : {}),
},
})
@@ -881,7 +882,7 @@ export function useAgentChatController({
.loadMessages(
requestAgent,
requestChatId,
- MESSAGE_PAGE_SIZE,
+ LOCAL_MESSAGE_PAGE_SIZE,
loadedLocalMessageCountRef.current
)
.catch(() => [])) as AgentChatMessage[]
@@ -895,7 +896,7 @@ export function useAgentChatController({
const hasOlderServerMessages = Boolean(oldestMergedTurn && oldestMergedTurn > 1)
const hasOlderLocalMessages =
!hasOlderServerMessages &&
- localPage.length === MESSAGE_PAGE_SIZE &&
+ localPage.length === LOCAL_MESSAGE_PAGE_SIZE &&
(await hasLocalMessagesBeyond(
chatStore,
requestAgent,
@@ -921,7 +922,7 @@ export function useAgentChatController({
requestAgent,
requestAgent,
requestChatId,
- { limit: MESSAGE_PAGE_SIZE, beforeTurn: oldestTurn }
+ { limit: SERVER_TURN_PAGE_SIZE, beforeTurn: oldestTurn }
)
if (!isStillRelevant()) return
const older = turnsToChatMessages(response.turns) as AgentChatMessage[]
@@ -933,8 +934,13 @@ export function useAgentChatController({
)
chatMessagesRef.current = merged
setChatMessages(merged)
- if (!isStillRelevant()) return
- await chatStore.replaceMessages(requestAgent, requestChatId, merged)
+ if (activeTaskId) {
+ await chatStore.replaceMessages(requestAgent, requestChatId, merged, {
+ activeTaskIds: [activeTaskId],
+ })
+ } else {
+ await chatStore.replaceMessages(requestAgent, requestChatId, merged)
+ }
if (!isStillRelevant()) return
loadedLocalMessageCountRef.current = merged.length
setHasOlderMessages(Boolean(response.hasMoreBefore))
@@ -1065,16 +1071,10 @@ export function useAgentChatController({
}
if (requestedSelection?.mode === 'specific') {
autoSelectedChatIdRef.current = null
- const requested = merged.find(chat => chat.id === requestedSelection.chatId)
- if (requested) {
- await switchToChat(selectedAgent, requestedSelection.chatId)
- } else {
- // 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)
- }
+ // 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 open the requested id directly.
+ await switchToChat(selectedAgent, requestedSelection.chatId)
return
}
if (navItem === DESKTOP_ROUTES.chat) {
@@ -1316,7 +1316,7 @@ export function useAgentChatController({
return v.selectedAgent === agentRef && v.activeChatId === chatId
}
const cached = (await chatStore
- .loadMessages(agentRef, chatId, MESSAGE_PAGE_SIZE)
+ .loadMessages(agentRef, chatId, LOCAL_MESSAGE_PAGE_SIZE)
.catch(error => {
console.warn('[chat-history] failed to read local reconciliation window', {
agentRef,
@@ -1333,17 +1333,17 @@ export function useAgentChatController({
return { rendered: localMessages, replaced: false, cached: localMessages }
}
const hydrated = turnsToChatMessages(resp.turns) as AgentChatMessage[]
+ if (replaceLocalWindow) {
+ setHasOlderMessages(Boolean(resp.hasMoreBefore))
+ } else {
+ setHasOlderMessages(previous => previous || Boolean(resp.hasMoreBefore))
+ }
if (!hydrated.length) {
return { rendered: localMessages, replaced: false, cached: localMessages }
}
const localHasServerTurns = localMessages.some(
message => serverTurnNumber(message) !== undefined
)
- if (replaceLocalWindow) {
- setHasOlderMessages(Boolean(resp.hasMoreBefore))
- } else if (!localHasServerTurns) {
- setHasOlderMessages(previous => previous || Boolean(resp.hasMoreBefore))
- }
if (!localHasServerTurns && localMessages.length > 0) {
const responseContainsAllTurns =
resp.totalTurns === undefined || resp.totalTurns === resp.turns.length
@@ -1371,7 +1371,14 @@ export function useAgentChatController({
chatMessagesRef.current = rendered
setChatMessages(rendered)
const meta = await chatStore.createChat(agentRef, chatId)
- await chatStore.replaceMessages(agentRef, chatId, rendered)
+ if (resp.activeTaskId || replaceLocalWindow) {
+ await chatStore.replaceMessages(agentRef, chatId, rendered, {
+ activeTaskIds: resp.activeTaskId ? [resp.activeTaskId] : undefined,
+ replaceLocalWindow,
+ })
+ } else {
+ 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
@@ -1580,10 +1587,10 @@ export function useAgentChatController({
useEffect(() => {
reconcileBranchesRef.current = {
loadSessionMessages: async (agentRef, chatId, query) => {
- let requestedQuery = query ?? { limit: MESSAGE_PAGE_SIZE }
+ let requestedQuery = query ?? { limit: SERVER_TURN_PAGE_SIZE }
if (requestedQuery.beforeTurn === undefined && requestedQuery.afterTurn === undefined) {
const cached = (await chatStore
- .loadMessages(agentRef, chatId, MESSAGE_PAGE_SIZE)
+ .loadMessages(agentRef, chatId, LOCAL_MESSAGE_PAGE_SIZE)
.catch(error => {
console.warn('[chat-history] failed to read local delta cursor', {
agentRef,
@@ -1611,6 +1618,12 @@ export function useAgentChatController({
const turns = [...response.turns]
const seenCursors = new Set<number>()
let cursor = response.latestTurnNumber ?? turns.at(-1)?.number
+ if (response.hasMoreAfter && (!turns.length || cursor === undefined)) {
+ // A host claiming another page without returning an advancing cursor
+ // is malformed. Preserve the local cache instead of replacing it with
+ // an unrelated latest window.
+ return response
+ }
let pagesLoaded = 1
while (
response.hasMoreAfter &&
@@ -1619,17 +1632,29 @@ export function useAgentChatController({
pagesLoaded < MAX_RECONCILE_DELTA_PAGES
) {
seenCursors.add(cursor)
+ const previousCursor = cursor
response = await chatStore.loadSessionMessages(agentRef, agentRef, chatId, {
- limit: requestedQuery.limit ?? MESSAGE_PAGE_SIZE,
+ limit: requestedQuery.limit ?? SERVER_TURN_PAGE_SIZE,
afterTurn: cursor,
})
turns.push(...response.turns)
cursor = response.latestTurnNumber ?? response.turns.at(-1)?.number
pagesLoaded += 1
+ if (
+ response.hasMoreAfter &&
+ (!response.turns.length || cursor === undefined || cursor === previousCursor)
+ ) {
+ return {
+ ...response,
+ turns,
+ oldestTurnNumber: turns[0]?.number,
+ latestTurnNumber: turns.at(-1)?.number,
+ }
+ }
}
if (response.hasMoreAfter) {
const latest = await chatStore.loadSessionMessages(agentRef, agentRef, chatId, {
- limit: requestedQuery.limit ?? MESSAGE_PAGE_SIZE,
+ limit: requestedQuery.limit ?? SERVER_TURN_PAGE_SIZE,
})
return {
...latest,
diff --git a/desktop-app/ui/src/hooks/domain/useChatListController.ts b/desktop-app/ui/src/hooks/domain/useChatListController.ts
index c1964d70a..be3de4c87 100644
--- a/desktop-app/ui/src/hooks/domain/useChatListController.ts
+++ b/desktop-app/ui/src/hooks/domain/useChatListController.ts
@@ -183,6 +183,9 @@ export function useChatListController({
return
}
+ // New hosts scope the page server-side. Keep this boundary check for
+ // older hosts and malformed proxy responses so another agent's catalog
+ // entry can never leak into the selected agent's sidebar.
const serverSessions = serverResult.items.filter(s => s.agent === agentRef)
chatListNextCursorByAgentRef.current[agentRef] = serverResult.nextCursor ?? null
setChatListHasMoreRemoteSessions(Boolean(serverResult.nextCursor))
@@ -211,6 +214,7 @@ export function useChatListController({
// Activity totals when tool/system messages vary by session.
messageCount: knownServerMessageCount(s),
turnCount: s.turnCount,
+ remote: true,
}))
return [...dedupedPrevious, ...fromServerOnly].sort(byUpdatedDesc)
})
@@ -220,17 +224,27 @@ export function useChatListController({
// it here, after the post-paint continuation reaches the auto-select gate,
// instead of clearing it with the synchronous local-index selection.
const suppressAutoSelection = suppressAutoSelectionByAgentRef.current.delete(agentRef)
- const activeChatId = host.current?.getActiveChatId() ?? null
- const autoSelectedChatId = host.current?.getAutoSelectedChatId() ?? null
+ const currentHost = host.current
+ const activeChatId = currentHost?.getActiveChatId() ?? null
+ const autoSelectedChatId = currentHost?.getAutoSelectedChatId() ?? null
+ const selectedLocalChat = activeChatId
+ ? merged.find(chat => chat.id === activeChatId)
+ : undefined
+ const serverIsNewerThanSelection =
+ !selectedLocalChat ||
+ Date.parse(latestServerSession?.lastActivityAt ?? '') >
+ Date.parse(selectedLocalChat.updatedAt)
if (
+ currentHost &&
latestServerSession &&
(activeChatId === null || activeChatId === autoSelectedChatId) &&
activeChatId !== latestServerSession.chatId &&
- host.current.shouldAutoSelectLatest() &&
+ serverIsNewerThanSelection &&
+ currentHost.shouldAutoSelectLatest() &&
!suppressAutoSelection
) {
- host.current.markAutoSelectedChat(latestServerSession.chatId)
- void host.current.switchToChat(agentRef, latestServerSession.chatId)
+ currentHost.markAutoSelectedChat(latestServerSession.chatId)
+ void currentHost.switchToChat(agentRef, latestServerSession.chatId)
}
// Persist server freshness into the local index (spec §5.3): keeps the
@@ -412,7 +426,7 @@ export function useChatListController({
const upsertHydratedEntry = useCallback((meta: ChatMetadata, title: string) => {
setChatList(prev =>
prev.some(c => c.id === meta.id)
- ? prev.map(c => (c.id === meta.id ? { ...c, title } : c))
+ ? prev.map(c => (c.id === meta.id ? { ...c, ...meta, title, remote: false } : c))
: [...prev, { ...meta, title }]
)
}, [])
diff --git a/desktop-app/ui/src/hooks/sessionAdapter.ts b/desktop-app/ui/src/hooks/sessionAdapter.ts
index 679c7368d..be4d3b4d1 100644
--- a/desktop-app/ui/src/hooks/sessionAdapter.ts
+++ b/desktop-app/ui/src/hooks/sessionAdapter.ts
@@ -1,15 +1,11 @@
-import type { ChatMessage, MessageToolStep, SessionTokensLite } from '../../../src/types'
+import {
+ type ServerTurn,
+ turnsToChatMessages as adaptServerTurnsToChatMessages,
+} from '../../../src/serverTurnAdapter'
+import type { ChatMessage } from '../../../src/types'
import { parseChatMessageDisplay } from '../lib/chatMessageAttachments'
-export interface ServerTurn {
- number: number
- user_input: string
- response?: string
- started_at: string
- completed_at?: string
- tokens?: SessionTokensLite
- tool_steps?: MessageToolStep[]
-}
+export type { ServerTurn }
/**
* Adapt server-side Turn[] to the client's ChatMessage[] shape.
@@ -19,32 +15,5 @@ export interface ServerTurn {
* IDs are derived deterministically from the turn number and role.
*/
export function turnsToChatMessages(turns: ServerTurn[]): ChatMessage[] {
- const out: ChatMessage[] = []
- for (const t of turns) {
- const userDisplay = parseChatMessageDisplay(t.user_input)
- out.push({
- id: `turn-${t.number}-user`,
- role: 'user',
- content: userDisplay.content,
- timestamp: Date.parse(t.started_at),
- serverTurnNumber: t.number,
- ...(userDisplay.attachments.length ? { attachments: userDisplay.attachments } : {}),
- })
- if (t.response !== undefined) {
- out.push({
- // completed_at may be missing on in-flight turns; falling back to started_at
- // means user+assistant share a timestamp, which is acceptable for display.
- id: `turn-${t.number}-assistant`,
- role: 'assistant',
- content: t.response,
- timestamp: Date.parse(t.completed_at ?? t.started_at),
- serverTurnNumber: t.number,
- ...(t.tokens ? { tokens: t.tokens } : {}),
- // #582: carry the turn's tools so the progress stepper's "N tools" view
- // survives a reload / cold-load (live SSE steps are renderer-only).
- ...(t.tool_steps && t.tool_steps.length ? { toolSteps: t.tool_steps } : {}),
- })
- }
- }
- return out
+ return adaptServerTurnsToChatMessages(turns, parseChatMessageDisplay)
}
diff --git a/desktop-app/ui/src/hooks/useChatStore.ts b/desktop-app/ui/src/hooks/useChatStore.ts
index c85111845..7b5e742d9 100644
--- a/desktop-app/ui/src/hooks/useChatStore.ts
+++ b/desktop-app/ui/src/hooks/useChatStore.ts
@@ -2,6 +2,7 @@ import { useCallback } from 'react'
import type {
ChatMessage,
HostModelsResult,
+ ReplaceChatMessagesOptions,
SessionMessagesQuery,
SessionsListQuery,
SessionsListResult,
@@ -112,8 +113,15 @@ export function useChatStore() {
[]
)
const replaceMessages = useCallback(
- (agentRef: string, chatId: string, messages: ChatMessage[]) =>
- window.clerum.chat.replaceMessages(agentRef, chatId, messages),
+ (
+ agentRef: string,
+ chatId: string,
+ messages: ChatMessage[],
+ options?: ReplaceChatMessagesOptions
+ ) =>
+ options
+ ? window.clerum.chat.replaceMessages(agentRef, chatId, messages, options)
+ : window.clerum.chat.replaceMessages(agentRef, chatId, messages),
[]
)
const markUnreadTerminal = useCallback(
diff --git a/desktop-app/ui/src/pages/AuthPage/index.tsx b/desktop-app/ui/src/pages/AuthPage/index.tsx
index f19d69a15..a55f105e4 100644
--- a/desktop-app/ui/src/pages/AuthPage/index.tsx
+++ b/desktop-app/ui/src/pages/AuthPage/index.tsx
@@ -96,7 +96,10 @@ export function AuthPage() {
const handleRuntimeOptionSelect = (optionId: string) => {
setRuntimeMenuOpen(false)
if (optionId === activeRuntimeConfigId) {
- handleClearRuntimeConfigSelection()
+ const selectedOption = runtimeConfigOptions.find(option => option.id === optionId)
+ if (selectedOption?.source === 'localhost') {
+ handleClearRuntimeConfigSelection()
+ }
return
}
handleSelectRuntimeConfig(optionId)
diff --git a/desktop-app/ui/src/pages/__tests__/AuthPage.test.tsx b/desktop-app/ui/src/pages/__tests__/AuthPage.test.tsx
index 64b603253..3f00d4553 100644
--- a/desktop-app/ui/src/pages/__tests__/AuthPage.test.tsx
+++ b/desktop-app/ui/src/pages/__tests__/AuthPage.test.tsx
@@ -193,4 +193,40 @@ describe('AuthPage', () => {
expect(handleSelectRuntimeConfig).not.toHaveBeenCalled()
expect(handleClearRuntimeConfigSelection).toHaveBeenCalledTimes(1)
})
+
+ it('does not clear an active saved environment when clicked again', async () => {
+ const user = userEvent.setup()
+ const handleSelectRuntimeConfig = vi.fn()
+ const handleClearRuntimeConfigSelection = vi.fn()
+
+ renderAuthPage({
+ runtimeConfigState: {
+ configured: true,
+ isLocalhost: false,
+ selectorVisible: true,
+ activeOptionId: 'saved-dev',
+ envKey: 'saved-dev-key',
+ storagePath: '/tmp/evenfire-runtime-config',
+ options: [
+ {
+ id: 'saved-dev',
+ label: 'Development',
+ source: 'file',
+ configPath: '/tmp/evenfire-runtime-config/dev.json',
+ externalRestApiBaseUrl: 'https://api.example.com',
+ rpcProxyBaseUrl: 'https://rpc.example.com',
+ appName: 'Development',
+ },
+ ],
+ },
+ handleSelectRuntimeConfig,
+ handleClearRuntimeConfigSelection,
+ })
+
+ await user.click(screen.getByLabelText('Open environment selector'))
+ await user.click(screen.getByRole('button', { name: 'Development' }))
+
+ expect(handleSelectRuntimeConfig).not.toHaveBeenCalled()
+ expect(handleClearRuntimeConfigSelection).not.toHaveBeenCalled()
+ })
})
diff --git a/mcp-host/package-lock.json b/mcp-host/package-lock.json
index 7032fcdc4..bedcce658 100644
--- a/mcp-host/package-lock.json
+++ b/mcp-host/package-lock.json
@@ -1,12 +1,12 @@
{
"name": "clerum-mcp-host",
- "version": "0.1.217",
+ "version": "0.1.218",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "clerum-mcp-host",
- "version": "0.1.217",
+ "version": "0.1.218",
"license": "SEE LICENSE IN LICENSE",
"dependencies": {
"@anthropic-ai/sdk": "^0.32.0",
diff --git a/mcp-host/package.json b/mcp-host/package.json
index ffc6d6388..492409ddd 100644
--- a/mcp-host/package.json
+++ b/mcp-host/package.json
@@ -1,6 +1,6 @@
{
"name": "clerum-mcp-host",
- "version": "0.1.217",
+ "version": "0.1.218",
"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.ts
index a7fed15bc..1212ab3d4 100644
--- a/mcp-host/src/__tests__/integration/crossDeviceSessions.test.ts
+++ b/mcp-host/src/__tests__/integration/crossDeviceSessions.test.ts
@@ -95,7 +95,7 @@ function makeApp(convManager: ConversationManager) {
.sort(
(left, right) =>
right.lastActivityAt.getTime() - left.lastActivityAt.getTime() ||
- left.key.localeCompare(right.key)
+ (left.key < right.key ? -1 : left.key > right.key ? 1 : 0)
)
const { page, nextCursor } = paginateSessionSummaries(entries, query.limit)
return {
diff --git a/mcp-host/src/core/conversation/__tests__/inMemoryConversationStore.test.ts b/mcp-host/src/core/conversation/__tests__/inMemoryConversationStore.test.ts
index feb9d2b6e..ed589e915 100644
--- a/mcp-host/src/core/conversation/__tests__/inMemoryConversationStore.test.ts
+++ b/mcp-host/src/core/conversation/__tests__/inMemoryConversationStore.test.ts
@@ -146,6 +146,37 @@ describe('InMemoryConversationStore', () => {
['agent-x', 'chat-1'],
])
})
+
+ it('preserves colons in chat ids under an agent-scoped prefix', async () => {
+ store.set('u-1:rpc:agent-x:chat:with:colons', makeConversation('u-1'))
+
+ const summaries = await store.listSessionSummariesByPrefix('u-1:rpc:agent-x:')
+
+ expect(summaries.map(session => [session.agent, session.chatId])).toEqual([
+ ['agent-x', 'chat:with:colons'],
+ ])
+ })
+
+ it('counts user and assistant bubbles without counting tool storage rows', async () => {
+ const conversation = makeConversation('u-1')
+ conversation.turns = [
+ {
+ ...makeTurn(1),
+ tool_calls: [
+ {
+ name: 'search',
+ parameters: {},
+ result: 'found',
+ },
+ ],
+ },
+ ]
+ store.set('u-1:rpc:agent-x:chat-1', conversation)
+
+ const [summary] = await store.listSessionSummariesByPrefix('u-1:rpc:')
+
+ expect(summary?.messageCount).toBe(2)
+ })
})
describe('getSessionMessagesByKey', () => {
diff --git a/mcp-host/src/core/conversation/conversationStore.ts b/mcp-host/src/core/conversation/conversationStore.ts
index 980795663..4dd952540 100644
--- a/mcp-host/src/core/conversation/conversationStore.ts
+++ b/mcp-host/src/core/conversation/conversationStore.ts
@@ -6,6 +6,7 @@ import {
type Turn,
type TurnToolCall,
} from '../types'
+import { sessionPartsFromPrefixedKey } from './sessionKeyParts'
/**
* Token usage from a SINGLE LLM call, accumulated additively into the durable
@@ -101,24 +102,6 @@ export interface ConversationSessionMessages extends Omit<
updatedAt: Date
}
-function sessionPartsFromKey(
- key: string,
- prefix: string
-): { agent: string; chatId: string } | null {
- const rest = key.slice(prefix.length)
- const colonIdx = rest.indexOf(':')
- if (colonIdx < 0) {
- const rpcPrefixIndex = prefix.lastIndexOf(':rpc:')
- const scopedAgent =
- rpcPrefixIndex >= 0 ? prefix.slice(rpcPrefixIndex + ':rpc:'.length).replace(/:$/, '') : ''
- return scopedAgent && rest ? { agent: scopedAgent, chatId: rest } : null
- }
- return {
- agent: rest.slice(0, colonIdx),
- chatId: rest.slice(colonIdx + 1),
- }
-}
-
function compareSessionSummaries(
left: Pick<ConversationSessionSummary, 'key' | 'lastActivityAt'>,
right: Pick<ConversationSessionSummary, 'key' | 'lastActivityAt'>
@@ -158,7 +141,7 @@ function sessionMessagesFromConversation(
conversation: Conversation,
query: SessionMessagesQuery = {}
): ConversationSessionMessages | undefined {
- const parts = sessionPartsFromKey(key, prefix)
+ const parts = sessionPartsFromPrefixedKey(key, prefix)
if (!parts) return undefined
const turns = boundedTurns(conversation.turns, query)
return {
@@ -391,7 +374,7 @@ export class InMemoryConversationStore implements ConversationStore {
): Promise<ConversationSessionSummary[]> {
const summaries: ConversationSessionSummary[] = []
for (const { key, conversation } of this.listByPrefix(prefix)) {
- const parts = sessionPartsFromKey(key, prefix)
+ const parts = sessionPartsFromPrefixedKey(key, prefix)
if (!parts) continue
summaries.push({
key,
@@ -407,8 +390,7 @@ 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,
+ (total, turn) => total + 1 + (turn.response === undefined ? 0 : 1),
0
),
lastActivityAt: conversation.updated_at,
diff --git a/mcp-host/src/core/conversation/persistence/__tests__/sqliteConversationStore.test.ts b/mcp-host/src/core/conversation/persistence/__tests__/sqliteConversationStore.test.ts
index 8a3918bf1..0a221be6c 100644
--- a/mcp-host/src/core/conversation/persistence/__tests__/sqliteConversationStore.test.ts
+++ b/mcp-host/src/core/conversation/persistence/__tests__/sqliteConversationStore.test.ts
@@ -1,4 +1,4 @@
-import { afterEach, describe, expect, it } from 'vitest'
+import { afterEach, describe, expect, it, vi } from 'vitest'
import { ConversationState, type PendingApproval, type TraceContextV1 } from '../../../types'
import { ConversationManager } from '../../conversation'
import { CacheOverflowError } from '../pinnedLruMap'
@@ -269,8 +269,8 @@ describe('SqliteConversationStore — session summary listing', () => {
}
await handle.persistQueue.drainSessionKey(session.key)
handle.worker.db
- .prepare('UPDATE sessions SET started_at = ? WHERE id = ?')
- .run(session.timestamp - 1, conv.id)
+ .prepare('UPDATE sessions SET started_at = ?, last_activity_at = ? WHERE id = ?')
+ .run(session.timestamp - 1, session.timestamp, conv.id)
handle.worker.db
.prepare('UPDATE messages SET timestamp = ? WHERE session_id = ?')
.run(session.timestamp, conv.id)
@@ -291,11 +291,13 @@ describe('SqliteConversationStore — session summary listing', () => {
tool_name: 'shell_exec',
},
turnCount: 1,
+ messageCount: 1,
})
expect(firstPage[1]).toMatchObject({
agent: 'agent-x',
state: ConversationState.Idle,
turnCount: 1,
+ messageCount: 2,
input_tokens: 200,
output_tokens: 100,
cacheTokensReported: true,
@@ -310,6 +312,21 @@ describe('SqliteConversationStore — session summary listing', () => {
['agent-x', 'chat-1'],
])
+ const colonKey = 'u-1:rpc:agent-x:chat:with:colons'
+ const colonConversation = await manager.getOrCreate(colonKey)
+ await manager.startTurn(colonConversation, 'colon chat', 'task-colon')
+ await manager.completeTurn(colonConversation, 'done')
+ handle.store['cache'].clear()
+ handle.store['ordinals'].clear()
+ handle.store['sessionKeyById'].clear()
+ const colonPage = await handle.store.listSessionSummariesByPrefix('u-1:rpc:agent-x:', {
+ limit: 10,
+ })
+ expect(colonPage.find(session => session.key === colonKey)).toMatchObject({
+ agent: 'agent-x',
+ chatId: 'chat:with:colons',
+ })
+
const secondPage = await handle.store.listSessionSummariesByPrefix('u-1:rpc:', {
limit: 2,
cursor: {
@@ -672,6 +689,29 @@ describe('SqliteConversationStore — active_task_id (D.1)', () => {
}
})
+ it('reserves and rolls back a completion turn number around the durability await', 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-complete')
+
+ const enqueueSpy = vi
+ .spyOn(handle.persistQueue, 'enqueueSync')
+ .mockRejectedValueOnce(new Error('disk unavailable'))
+ await expect(handle.store.persistTurnComplete(conv, 'failed write')).rejects.toThrow(
+ /disk unavailable/
+ )
+ expect(handle.store['ordinals'].get(conv.id)?.nextTurnNumber).toBe(1)
+
+ enqueueSpy.mockRestore()
+ await handle.store.persistTurnComplete(conv, 'durable response')
+ expect(handle.store['ordinals'].get(conv.id)?.nextTurnNumber).toBe(2)
+ } finally {
+ await handle.shutdown()
+ }
+ })
+
it('persistTurnFail is an awaited durability barrier: the failed-turn state is durable when it resolves', async () => {
const handle = await freshStore()
try {
diff --git a/mcp-host/src/core/conversation/persistence/sqliteConversationStore.ts b/mcp-host/src/core/conversation/persistence/sqliteConversationStore.ts
index a1694ef2c..580c02cd3 100644
--- a/mcp-host/src/core/conversation/persistence/sqliteConversationStore.ts
+++ b/mcp-host/src/core/conversation/persistence/sqliteConversationStore.ts
@@ -43,6 +43,7 @@ import {
type SessionTokenUsage,
boundedTurns,
} from '../conversationStore'
+import { sessionPartsFromPrefixedKey } from '../sessionKeyParts'
import type { PersistQueue } from './persistQueue'
import { CacheOverflowError, PinnedLRUMap } from './pinnedLruMap'
import {
@@ -172,21 +173,6 @@ interface SessionOrdinalState {
nextTurnNumber: number
}
-function sessionPartsFromPrefix(
- key: string,
- prefix: string
-): { agent: string; chatId: string } | null {
- const rest = key.startsWith(prefix) ? key.slice(prefix.length) : key
- const colonIdx = rest.indexOf(':')
- if (colonIdx >= 0) {
- return { agent: rest.slice(0, colonIdx), chatId: rest.slice(colonIdx + 1) }
- }
- const rpcPrefixIndex = prefix.lastIndexOf(':rpc:')
- const scopedAgent =
- rpcPrefixIndex >= 0 ? prefix.slice(rpcPrefixIndex + ':rpc:'.length).replace(/:$/, '') : ''
- return scopedAgent && rest ? { agent: scopedAgent, chatId: rest } : null
-}
-
function conversationStateFromRow(state: string): ConversationState {
return state === ConversationState.Processing
? ConversationState.Processing
@@ -384,7 +370,7 @@ export class SqliteConversationStore implements ConversationStore {
for (const row of rows) {
const key = row.session.session_key
const cached = this.cache.get(key)
- const parts = sessionPartsFromPrefix(key, prefix)
+ const parts = sessionPartsFromPrefixedKey(key, prefix)
if (!parts) continue
const state = cached ? cached.state : conversationStateFromRow(row.session.state)
out.push({
@@ -425,7 +411,7 @@ export class SqliteConversationStore implements ConversationStore {
query: SessionMessagesQuery = {}
): Promise<ConversationSessionMessages | undefined> {
const cached = this.cache.get(sessionKey)
- const parts = sessionPartsFromPrefix(sessionKey, prefix)
+ const parts = sessionPartsFromPrefixedKey(sessionKey, prefix)
if (!parts) return undefined
if (cached) {
const turns = boundedTurns(cached.turns, query)
@@ -725,41 +711,51 @@ export class SqliteConversationStore implements ConversationStore {
const state = this.ordinals.get(conv.id) ?? this.initOrdinalState(conv.id)
const ordinal = state.nextOrdinal++
const turnNumber = state.nextTurnNumber
+ // Reserve before the durability await so an immediate follow-up turn cannot
+ // reuse this number while the completion boundary is still queued.
+ state.nextTurnNumber += 1
// Stamp the per-turn token total onto the final assistant message (the turn
// accumulated it in RAM via recordSessionUsage). reconstruct sums these back
// onto the Turn on cold-load.
const turn = conv.turns[conv.turns.length - 1]
- await this.persistQueue.enqueueSync(
- {
- kind: 'persist_turn_boundary',
- message: {
- session_id: conv.id,
- ordinal,
- role: 'assistant',
- content: response,
- content_parts: null,
- tool_call_id: null,
- tool_calls: null,
- tool_name: null,
- timestamp: Date.now() / 1000,
- token_count: null,
- finish_reason: 'stop',
- spillover_ref: null,
- is_error: 0,
- turn_number: turnNumber,
- input_tokens: turn?.input_tokens ?? null,
- output_tokens: turn?.output_tokens ?? null,
- cache_read_tokens: turn?.cache_read_tokens ?? null,
- cache_write_tokens: turn?.cache_write_tokens ?? null,
+ try {
+ await this.persistQueue.enqueueSync(
+ {
+ kind: 'persist_turn_boundary',
+ message: {
+ session_id: conv.id,
+ ordinal,
+ role: 'assistant',
+ content: response,
+ content_parts: null,
+ tool_call_id: null,
+ tool_calls: null,
+ tool_name: null,
+ timestamp: Date.now() / 1000,
+ token_count: null,
+ finish_reason: 'stop',
+ spillover_ref: null,
+ is_error: 0,
+ turn_number: turnNumber,
+ input_tokens: turn?.input_tokens ?? null,
+ output_tokens: turn?.output_tokens ?? null,
+ cache_read_tokens: turn?.cache_read_tokens ?? null,
+ cache_write_tokens: turn?.cache_write_tokens ?? null,
+ },
+ sessionId: conv.id,
+ state: conv.state,
+ activeTaskId: null, // D.1 — turn complete clears the in-flight task
+ activeTraceContext: null,
},
- sessionId: conv.id,
- state: conv.state,
- activeTaskId: null, // D.1 — turn complete clears the in-flight task
- activeTraceContext: null,
- },
- sessionKey
- )
- state.nextTurnNumber += 1
+ sessionKey
+ )
+ } catch (error) {
+ // Roll back only if no later turn has advanced the same state meanwhile.
+ if (state.nextTurnNumber === turnNumber + 1) {
+ state.nextTurnNumber = turnNumber
+ }
+ throw error
+ }
}
async persistTurnCancel(conv: Conversation): Promise<void> {
diff --git a/mcp-host/src/core/conversation/sessionKeyParts.ts b/mcp-host/src/core/conversation/sessionKeyParts.ts
new file mode 100644
index 000000000..1fd58cbf1
--- /dev/null
+++ b/mcp-host/src/core/conversation/sessionKeyParts.ts
@@ -0,0 +1,45 @@
+export interface AgentChatSessionParts {
+ agent: string
+ chatId: string
+}
+
+/**
+ * Return the agent embedded in an agent-scoped RPC prefix.
+ *
+ * Unscoped prefixes end immediately after `:rpc:`. Scoped prefixes append the
+ * agent and a trailing colon, for example `user:rpc:agent-a:`.
+ */
+export function scopedAgentFromSessionPrefix(prefix: string): string | null {
+ const rpcPrefixIndex = prefix.lastIndexOf(':rpc:')
+ if (rpcPrefixIndex < 0) return null
+ const suffix = prefix.slice(rpcPrefixIndex + ':rpc:'.length)
+ if (!suffix.endsWith(':')) return null
+ const agent = suffix.slice(0, -1)
+ return agent || null
+}
+
+/**
+ * Parse a key relative to the exact prefix used to fetch it.
+ *
+ * For an agent-scoped prefix, the entire suffix is the chat ID. This preserves
+ * chat IDs containing colons instead of treating their first segment as
+ * another agent name.
+ */
+export function sessionPartsFromPrefixedKey(
+ key: string,
+ prefix: string
+): AgentChatSessionParts | null {
+ if (!key.startsWith(prefix)) return null
+ const rest = key.slice(prefix.length)
+ if (!rest) return null
+
+ const scopedAgent = scopedAgentFromSessionPrefix(prefix)
+ if (scopedAgent) return { agent: scopedAgent, chatId: rest }
+
+ const colonIndex = rest.indexOf(':')
+ if (colonIndex <= 0 || colonIndex === rest.length - 1) return null
+ return {
+ agent: rest.slice(0, colonIndex),
+ chatId: rest.slice(colonIndex + 1),
+ }
+}
diff --git a/mcp-host/src/db/migrations/010-materialized-session-summaries.ts b/mcp-host/src/db/migrations/010-materialized-session-summaries.ts
new file mode 100644
index 000000000..fd5767c9b
--- /dev/null
+++ b/mcp-host/src/db/migrations/010-materialized-session-summaries.ts
@@ -0,0 +1,52 @@
+/**
+ * Migration 010 — materialize the fields used by the paged session catalog.
+ *
+ * Computing last activity, visible messages, and distinct turns from the
+ * messages table made every catalog page proportional to the user's complete
+ * transcript history. Backfill the summaries once, then maintain them on the
+ * write path so catalog reads only scan session rows.
+ */
+import type { Database } from 'better-sqlite3'
+
+export const name = '010-materialized-session-summaries'
+
+export function up(db: Database): void {
+ db.exec(`
+ ALTER TABLE sessions ADD COLUMN last_activity_at REAL;
+ ALTER TABLE sessions ADD COLUMN turn_count INTEGER NOT NULL DEFAULT 0;
+
+ UPDATE sessions
+ SET last_activity_at = COALESCE(
+ (SELECT MAX(m.timestamp) FROM messages m WHERE m.session_id = sessions.id),
+ started_at
+ ),
+ turn_count = (
+ SELECT COUNT(DISTINCT COALESCE(m.turn_number, 0))
+ FROM messages m
+ WHERE m.session_id = sessions.id
+ ),
+ message_count = (
+ SELECT COUNT(*)
+ FROM messages m
+ WHERE m.session_id = sessions.id
+ AND (
+ m.role = 'user'
+ OR (m.role = 'assistant' AND m.tool_calls IS NULL)
+ )
+ );
+
+ CREATE INDEX IF NOT EXISTS idx_sessions_summary_activity
+ ON sessions(last_activity_at DESC, session_key ASC);
+ CREATE INDEX IF NOT EXISTS idx_messages_session_turn_key_ordinal
+ ON messages(session_id, COALESCE(turn_number, 0), ordinal);
+ `)
+}
+
+export function down(db: Database): void {
+ db.exec(`
+ DROP INDEX IF EXISTS idx_sessions_summary_activity;
+ DROP INDEX IF EXISTS idx_messages_session_turn_key_ordinal;
+ ALTER TABLE sessions DROP COLUMN turn_count;
+ ALTER TABLE sessions DROP COLUMN last_activity_at;
+ `)
+}
diff --git a/mcp-host/src/db/migrations/__tests__/008-active-trace-context.test.ts b/mcp-host/src/db/migrations/__tests__/008-active-trace-context.test.ts
index bf12581a6..ba5ba1b81 100644
--- a/mcp-host/src/db/migrations/__tests__/008-active-trace-context.test.ts
+++ b/mcp-host/src/db/migrations/__tests__/008-active-trace-context.test.ts
@@ -71,6 +71,7 @@ describe('migration 008 — active trace context', () => {
'007-sessions-model-selections',
'008-active-trace-context',
'009-session-summary-indexes',
+ '010-materialized-session-summaries',
],
pending: [],
})
diff --git a/mcp-host/src/db/migrations/__tests__/010-materialized-session-summaries.test.ts b/mcp-host/src/db/migrations/__tests__/010-materialized-session-summaries.test.ts
new file mode 100644
index 000000000..b786e774a
--- /dev/null
+++ b/mcp-host/src/db/migrations/__tests__/010-materialized-session-summaries.test.ts
@@ -0,0 +1,79 @@
+import { describe, expect, it } from 'vitest'
+import Database from 'better-sqlite3'
+import * as m010 from '../010-materialized-session-summaries'
+import { migrations } from '../index'
+
+describe('migration 010 — materialized session summaries', () => {
+ it('backfills activity, visible-message, and turn counters from legacy rows', () => {
+ const db = new Database(':memory:')
+ for (const migration of migrations) {
+ if (migration.name === m010.name) break
+ migration.up(db)
+ }
+
+ const insertSession = db.prepare(
+ `INSERT INTO sessions (id, session_key, source, started_at)
+ VALUES (?, ?, 'rpc', ?)`
+ )
+ insertSession.run('session-with-messages', 'u-1:rpc:agent:chat-1', 1)
+ insertSession.run('empty-session', 'u-1:rpc:agent:chat-2', 5)
+
+ const insertMessage = db.prepare(
+ `INSERT INTO messages (
+ session_id, ordinal, role, content, tool_calls, timestamp, turn_number
+ ) VALUES (?, ?, ?, ?, ?, ?, ?)`
+ )
+ insertMessage.run('session-with-messages', 0, 'user', 'question', null, 10, 1)
+ insertMessage.run('session-with-messages', 1, 'assistant', null, '[]', 11, 1)
+ insertMessage.run('session-with-messages', 2, 'tool', 'result', null, 11, 1)
+ insertMessage.run('session-with-messages', 3, 'assistant', 'answer', null, 12, 1)
+ insertMessage.run('session-with-messages', 4, 'user', 'next', null, 20, 2)
+
+ m010.up(db)
+
+ expect(
+ db
+ .prepare(
+ `SELECT last_activity_at, turn_count, message_count
+ FROM sessions
+ WHERE id = 'session-with-messages'`
+ )
+ .get()
+ ).toEqual({
+ last_activity_at: 20,
+ turn_count: 2,
+ message_count: 3,
+ })
+ expect(
+ db
+ .prepare(
+ `SELECT last_activity_at, turn_count, message_count
+ FROM sessions
+ WHERE id = 'empty-session'`
+ )
+ .get()
+ ).toEqual({
+ last_activity_at: 5,
+ turn_count: 0,
+ message_count: 0,
+ })
+
+ const indexes = db
+ .prepare(
+ `SELECT name
+ FROM sqlite_master
+ WHERE type = 'index'
+ AND name IN (
+ 'idx_sessions_summary_activity',
+ 'idx_messages_session_turn_key_ordinal'
+ )
+ ORDER BY name`
+ )
+ .all() as Array<{ name: string }>
+ expect(indexes.map(index => index.name)).toEqual([
+ 'idx_messages_session_turn_key_ordinal',
+ 'idx_sessions_summary_activity',
+ ])
+ db.close()
+ })
+})
diff --git a/mcp-host/src/db/migrations/index.ts b/mcp-host/src/db/migrations/index.ts
index b6cb6f1af..5355e2a5d 100644
--- a/mcp-host/src/db/migrations/index.ts
+++ b/mcp-host/src/db/migrations/index.ts
@@ -7,6 +7,7 @@ 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'
+import * as materializedSessionSummaries from './010-materialized-session-summaries'
/**
* Ordered list of migrations. New migrations append; never reorder or rename.
@@ -27,4 +28,5 @@ export const migrations: Array<{
sessionsModelSelections,
activeTraceContext,
sessionSummaryIndexes,
+ materializedSessionSummaries,
]
diff --git a/mcp-host/src/db/statements.ts b/mcp-host/src/db/statements.ts
index 52a1d81e3..ba3270904 100644
--- a/mcp-host/src/db/statements.ts
+++ b/mcp-host/src/db/statements.ts
@@ -21,6 +21,8 @@ export interface PreparedStatements {
deleteUnrehydratablePendingApprovals: Statement
deletePendingApprovalsBySession: Statement
updateSessionCounters: Statement
+ updateSessionSummaryAfterInsert: Statement
+ recomputeSessionMessageSummary: Statement
updateSessionPromptStableHash: Statement
updateSessionModelSelections: Statement
selectSessionBySessionKey: Statement
@@ -60,7 +62,7 @@ export function prepareStatements(db: Database): PreparedStatements {
id, session_key, source, user_id, team_id,
channel_type, channel_id, thread_id,
model, model_selections, system_prompt_stable_hash, parent_session_id,
- started_at, ended_at, end_reason,
+ started_at, last_activity_at, turn_count, ended_at, end_reason,
message_count, tool_call_count,
input_tokens, output_tokens, cache_read_tokens, cache_write_tokens,
cache_tokens_reported,
@@ -69,7 +71,7 @@ export function prepareStatements(db: Database): PreparedStatements {
@id, @session_key, @source, @user_id, @team_id,
@channel_type, @channel_id, @thread_id,
@model, @model_selections, @system_prompt_stable_hash, @parent_session_id,
- @started_at, @ended_at, @end_reason,
+ @started_at, @last_activity_at, @turn_count, @ended_at, @end_reason,
@message_count, @tool_call_count,
@input_tokens, @output_tokens, @cache_read_tokens, @cache_write_tokens,
@cache_tokens_reported,
@@ -183,6 +185,48 @@ export function prepareStatements(db: Database): PreparedStatements {
cache_tokens_reported = cache_tokens_reported | @cache_reported
WHERE id = @id
`),
+ updateSessionSummaryAfterInsert: db.prepare(`
+ UPDATE sessions
+ SET last_activity_at = CASE
+ WHEN last_activity_at IS NULL OR last_activity_at < @timestamp
+ THEN @timestamp
+ ELSE last_activity_at
+ END,
+ turn_count = turn_count + CASE
+ WHEN (
+ SELECT COUNT(*)
+ FROM messages
+ WHERE session_id = @id
+ AND COALESCE(turn_number, 0) = COALESCE(@turn_number, 0)
+ ) = 1
+ THEN 1
+ ELSE 0
+ END,
+ message_count = message_count + @visible_message_delta
+ WHERE id = @id
+ `),
+ recomputeSessionMessageSummary: db.prepare(`
+ UPDATE sessions
+ SET last_activity_at = COALESCE(
+ (SELECT MAX(timestamp) FROM messages WHERE session_id = @id),
+ started_at
+ ),
+ turn_count = (
+ SELECT COUNT(DISTINCT COALESCE(turn_number, 0))
+ FROM messages
+ WHERE session_id = @id
+ ),
+ message_count = (
+ SELECT COUNT(*)
+ FROM messages
+ WHERE session_id = @id
+ AND (
+ role = 'user'
+ OR (role = 'assistant' AND tool_calls IS NULL)
+ )
+ )
+ WHERE id = @id
+ `),
selectSessionBySessionKey: db.prepare(`
SELECT * FROM sessions WHERE session_key = ?
`),
@@ -203,14 +247,16 @@ export function prepareStatements(db: Database): PreparedStatements {
AND instr(substr(session_key, length(@prefix_start) + 1), ':') > 0
)
)
- ),
- message_summaries AS (
- SELECT m.session_id,
- MAX(m.timestamp) AS last_activity_at,
- COUNT(DISTINCT COALESCE(m.turn_number, 0)) AS turn_count
- FROM messages m
- JOIN scoped_sessions s ON s.id = m.session_id
- GROUP BY m.session_id
+ AND (
+ @cursor_updated_at IS NULL
+ OR COALESCE(last_activity_at, started_at) < @cursor_updated_at
+ OR (
+ COALESCE(last_activity_at, started_at) = @cursor_updated_at
+ AND session_key > @cursor_key
+ )
+ )
+ ORDER BY COALESCE(last_activity_at, started_at) DESC, session_key ASC
+ LIMIT @limit
),
ranked_approvals AS (
SELECT pa.session_id,
@@ -222,29 +268,17 @@ export function prepareStatements(db: Database): PreparedStatements {
) AS approval_rank
FROM pending_approvals pa
JOIN scoped_sessions s ON s.id = pa.session_id
- ),
- session_summaries AS (
- SELECT s.*,
- COALESCE(ms.last_activity_at, s.started_at) AS last_activity_at,
- COALESCE(ms.turn_count, 0) AS turn_count,
- pa.request_id AS pending_request_id,
- pa.tool_name AS pending_tool_name
- FROM scoped_sessions s
- LEFT JOIN message_summaries ms ON ms.session_id = s.id
- LEFT JOIN ranked_approvals pa
- ON pa.session_id = s.id
- AND pa.approval_rank = 1
)
- SELECT *
- FROM session_summaries
- WHERE @cursor_updated_at IS NULL
- OR last_activity_at < @cursor_updated_at
- OR (
- last_activity_at = @cursor_updated_at
- AND session_key > @cursor_key
- )
- ORDER BY last_activity_at DESC, session_key ASC
- LIMIT @limit
+ SELECT s.*,
+ COALESCE(s.last_activity_at, s.started_at) AS summary_last_activity_at,
+ COALESCE(s.turn_count, 0) AS summary_turn_count,
+ pa.request_id AS pending_request_id,
+ pa.tool_name AS pending_tool_name
+ FROM scoped_sessions s
+ LEFT JOIN ranked_approvals pa
+ ON pa.session_id = s.id
+ AND pa.approval_rank = 1
+ ORDER BY summary_last_activity_at DESC, s.session_key ASC
`),
selectSessionTurnBounds: db.prepare(`
SELECT COUNT(DISTINCT COALESCE(turn_number, 0)) AS total_turns,
diff --git a/mcp-host/src/db/worker/__tests__/dispatcher.test.ts b/mcp-host/src/db/worker/__tests__/dispatcher.test.ts
index d7e190260..e510c3011 100644
--- a/mcp-host/src/db/worker/__tests__/dispatcher.test.ts
+++ b/mcp-host/src/db/worker/__tests__/dispatcher.test.ts
@@ -102,7 +102,7 @@ describe('dbWorker dispatcher', () => {
expect(row.message_count).toBe(1)
})
- it('insert_message does NOT touch token columns (no double-count)', async () => {
+ it('separates tool-call storage rows from visible messages and token counters', async () => {
const deps = createDispatcher(db)
await dispatch(
{ kind: 'insert_session', payload: makeSession('conv-2t', 'u-2t:rpc:agent:default') },
@@ -135,7 +135,7 @@ describe('dbWorker dispatcher', () => {
'SELECT message_count, tool_call_count, input_tokens, output_tokens, cache_read_tokens, cache_write_tokens FROM sessions WHERE id = ?'
)
.get('conv-2t') as Record<string, number>
- expect(row.message_count).toBe(1)
+ expect(row.message_count).toBe(0)
expect(row.tool_call_count).toBe(1)
// tokens stay at DEFAULT 0 — only update_session_counters writes them
expect(row.input_tokens).toBe(0)
diff --git a/mcp-host/src/db/worker/dispatcher.ts b/mcp-host/src/db/worker/dispatcher.ts
index 84eba66f3..eea3ccca0 100644
--- a/mcp-host/src/db/worker/dispatcher.ts
+++ b/mcp-host/src/db/worker/dispatcher.ts
@@ -6,6 +6,7 @@
* worker_threads boilerplate.
*/
import type { Database } from 'better-sqlite3'
+import { scopedAgentFromSessionPrefix } from '../../core/conversation/sessionKeyParts'
import { PreparedStatements, prepareStatements } from '../statements'
import { withBusyRetry } from './busyRetry'
import type {
@@ -28,6 +29,27 @@ export function createDispatcher(db: Database): DispatcherDeps {
return { db, statements: prepareStatements(db) }
}
+function updateSessionSummaryAfterInsert(
+ statements: PreparedStatements,
+ message: {
+ session_id: string
+ role: string
+ tool_calls: string | null
+ timestamp: number
+ turn_number: number | null
+ }
+): void {
+ statements.updateSessionSummaryAfterInsert.run({
+ id: message.session_id,
+ timestamp: message.timestamp,
+ turn_number: message.turn_number,
+ visible_message_delta:
+ message.role === 'user' || (message.role === 'assistant' && message.tool_calls === null)
+ ? 1
+ : 0,
+ })
+}
+
/**
* Strict ISO 8601 — `YYYY-MM-DD` optionally followed by `THH:MM[:SS[.sss]]`
* and a `Z`/`±HH:MM` offset. Rejects bare numeric strings ("1000000") that
@@ -93,6 +115,8 @@ export async function dispatch(op: WorkerOp, deps: DispatcherDeps): Promise<unkn
system_prompt_stable_hash: row.system_prompt_stable_hash ?? null,
parent_session_id: row.parent_session_id ?? null,
started_at: row.started_at,
+ last_activity_at: row.last_activity_at ?? row.started_at,
+ turn_count: row.turn_count ?? 0,
ended_at: row.ended_at ?? null,
end_reason: row.end_reason ?? null,
message_count: row.message_count ?? 0,
@@ -196,6 +220,13 @@ export async function dispatch(op: WorkerOp, deps: DispatcherDeps): Promise<unkn
cache_read_tokens: null,
cache_write_tokens: null,
})
+ updateSessionSummaryAfterInsert(s, {
+ session_id: sess.id,
+ role: 'assistant',
+ tool_calls: null,
+ timestamp: nowMs / 1000,
+ turn_number: agg.max_turn,
+ })
s.updateSessionState.run({
id: sess.id,
state: 'idle',
@@ -311,6 +342,13 @@ export async function dispatch(op: WorkerOp, deps: DispatcherDeps): Promise<unkn
cache_read_tokens: null,
cache_write_tokens: null,
})
+ updateSessionSummaryAfterInsert(s, {
+ session_id: sess.id,
+ role: 'assistant',
+ tool_calls: null,
+ timestamp: nowMs / 1000,
+ turn_number: agg.max_turn,
+ })
// Resolve the (expired) approval row(s) atomically with the state
// flip so PHASE 2's load_all_pending_approvals can't resurrect them.
// No-op for the orphan case (row already gone).
@@ -413,9 +451,10 @@ export async function dispatch(op: WorkerOp, deps: DispatcherDeps): Promise<unkn
cache_read_tokens: op.payload.cache_read_tokens ?? null,
cache_write_tokens: op.payload.cache_write_tokens ?? null,
})
+ updateSessionSummaryAfterInsert(s, op.payload)
s.updateSessionCounters.run({
id: op.payload.session_id,
- message_count_delta: 1,
+ message_count_delta: 0,
tool_call_count_delta: op.payload.role === 'assistant' && op.payload.tool_calls ? 1 : 0,
input_tokens_delta: 0,
output_tokens_delta: 0,
@@ -455,9 +494,10 @@ export async function dispatch(op: WorkerOp, deps: DispatcherDeps): Promise<unkn
cache_read_tokens: op.message.cache_read_tokens ?? null,
cache_write_tokens: op.message.cache_write_tokens ?? null,
})
+ updateSessionSummaryAfterInsert(s, op.message)
s.updateSessionCounters.run({
id: op.message.session_id,
- message_count_delta: 1,
+ message_count_delta: 0,
tool_call_count_delta: op.message.role === 'assistant' && op.message.tool_calls ? 1 : 0,
input_tokens_delta: 0,
output_tokens_delta: 0,
@@ -510,6 +550,7 @@ export async function dispatch(op: WorkerOp, deps: DispatcherDeps): Promise<unkn
cache_write_tokens: m.cache_write_tokens ?? null,
})
}
+ s.recomputeSessionMessageSummary.run({ id: op.sessionId })
})
tx.immediate()
return { ok: true, count: op.messages.length }
@@ -617,10 +658,7 @@ export async function dispatch(op: WorkerOp, deps: DispatcherDeps): Promise<unkn
0,
op.sessionKeyPrefix.length - (finalCodePoint > 0xffff ? 2 : 1)
)}${String.fromCodePoint(finalCodePoint + 1)}`
- const rpcPrefixIndex = op.sessionKeyPrefix.lastIndexOf(':rpc:')
- const agentScoped =
- rpcPrefixIndex >= 0 &&
- op.sessionKeyPrefix.slice(rpcPrefixIndex + ':rpc:'.length).replace(/:$/, '').length > 0
+ const agentScoped = scopedAgentFromSessionPrefix(op.sessionKeyPrefix) !== null
const rows = s.selectSessionSummariesByPrefix.all({
prefix_start: prefixStart,
prefix_end: prefixEnd,
@@ -630,19 +668,24 @@ export async function dispatch(op: WorkerOp, deps: DispatcherDeps): Promise<unkn
cursor_key: op.cursorKey ?? null,
}) as Array<
SessionRow & {
- last_activity_at: number
- turn_count: number
+ summary_last_activity_at: number
+ summary_turn_count: number
pending_request_id: string | null
pending_tool_name: string | null
}
>
return rows.map(row => {
- const { last_activity_at, turn_count, pending_request_id, pending_tool_name, ...session } =
- row
+ const {
+ summary_last_activity_at,
+ summary_turn_count,
+ pending_request_id,
+ pending_tool_name,
+ ...session
+ } = row
return {
session: session as SessionRow,
- last_activity_at,
- turn_count,
+ last_activity_at: summary_last_activity_at,
+ turn_count: summary_turn_count,
pending_approval:
pending_request_id && pending_tool_name
? { request_id: pending_request_id, tool_name: pending_tool_name }
diff --git a/mcp-host/src/db/worker/protocol.ts b/mcp-host/src/db/worker/protocol.ts
index 59db99a6f..9e0302ae9 100644
--- a/mcp-host/src/db/worker/protocol.ts
+++ b/mcp-host/src/db/worker/protocol.ts
@@ -30,6 +30,10 @@ export interface SessionRow {
system_prompt_stable_hash: string | null
parent_session_id: string | null
started_at: number
+ /** Materialized catalog sort key (migration 010). */
+ last_activity_at?: number | null
+ /** Materialized count of distinct persisted turn numbers (migration 010). */
+ turn_count?: number
ended_at: number | null
end_reason: string | null
message_count: number
diff --git a/mcp-host/src/main.ts b/mcp-host/src/main.ts
index c3d96661e..c34744df6 100644
--- a/mcp-host/src/main.ts
+++ b/mcp-host/src/main.ts
@@ -105,6 +105,7 @@ import {
projectSessionTokens,
projectTurnTokens,
projectTurnToolSteps,
+ sessionsCursorScope,
} from './server/wireProjections'
import { SessionProcessor } from './session'
import { serializeSessionKey } from './session/types.js'
@@ -2070,15 +2071,19 @@ async function startRPCServer(): Promise<void> {
) => {
const convManager = agent!.getConversationManager()
const keyPrefix = query.agent ? `${userSub}:rpc:${query.agent}:` : `${userSub}:rpc:`
- const cursor = decodeSessionsCursor(query.cursor)
+ const cursorScope = sessionsCursorScope(userSub, query.agent)
+ const cursor = decodeSessionsCursor(query.cursor, cursorScope)
const entries = await convManager.listSessionSummariesForUserAsync(keyPrefix, {
limit: query.limit === undefined ? undefined : query.limit + 1,
cursor: cursor
? { updatedAt: new Date(cursor.updatedAt), key: `${keyPrefix}${cursor.key}` }
: undefined,
})
- const { page, nextCursor } = paginateSessionSummaries(entries, query.limit, key =>
- key.slice(keyPrefix.length)
+ const { page, nextCursor } = paginateSessionSummaries(
+ entries,
+ query.limit,
+ key => key.slice(keyPrefix.length),
+ cursorScope
)
return {
items: page.map(summary => ({
diff --git a/mcp-host/src/server/__tests__/sessionsRoutes.test.ts b/mcp-host/src/server/__tests__/sessionsRoutes.test.ts
index 3de829466..992837aa8 100644
--- a/mcp-host/src/server/__tests__/sessionsRoutes.test.ts
+++ b/mcp-host/src/server/__tests__/sessionsRoutes.test.ts
@@ -6,6 +6,7 @@ import {
handleSessionsListRoute,
} from '../routes'
import type { ContextBreakdownHandler, SessionMessagesHandler, SessionsListHandler } from '../types'
+import { encodeSessionsCursor, sessionsCursorScope } from '../wireProjections'
import { makeHandlers } from './testHelpers'
interface CapturedRes {
@@ -50,10 +51,6 @@ 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({
@@ -84,7 +81,14 @@ describe('handleSessionsListRoute', () => {
})
const req = {
...makeReqWithAuth('user-1'),
- query: { limit: '500', cursor: encodeSessionsCursor('2026-04-22T00:00:00.000Z', 'k1') },
+ query: {
+ limit: '500',
+ cursor: encodeSessionsCursor(
+ '2026-04-22T00:00:00.000Z',
+ 'k1',
+ sessionsCursorScope('user-1')
+ ),
+ },
} as unknown as Request
const captured = makeRes()
@@ -94,7 +98,7 @@ describe('handleSessionsListRoute', () => {
expect(sessionsListHandler).toHaveBeenCalledWith('user-1', {
agent: undefined,
limit: 100,
- cursor: encodeSessionsCursor('2026-04-22T00:00:00.000Z', 'k1'),
+ cursor: encodeSessionsCursor('2026-04-22T00:00:00.000Z', 'k1', sessionsCursorScope('user-1')),
})
expect(captured.jsonBody).toEqual({ items: [], nextCursor: 'next-page' })
})
@@ -117,6 +121,27 @@ describe('handleSessionsListRoute', () => {
})
})
+ it('rejects a cursor issued for another agent scope', async () => {
+ const sessionsListHandler: SessionsListHandler = vi.fn().mockReturnValue({ items: [] })
+ const req = {
+ ...makeReqWithAuth('user-1'),
+ query: {
+ agent: 'agent-b',
+ cursor: encodeSessionsCursor(
+ '2026-04-22T00:00:00.000Z',
+ 'chat-1',
+ sessionsCursorScope('user-1', 'agent-a')
+ ),
+ },
+ } as unknown as Request
+ const captured = makeRes()
+
+ await handleSessionsListRoute(req, captured.res, makeHandlers({ sessionsListHandler }))
+
+ expect(captured.statusCode).toBe(400)
+ expect(sessionsListHandler).not.toHaveBeenCalled()
+ })
+
it('rejects malformed session cursors instead of treating them as page one', async () => {
const sessionsListHandler: SessionsListHandler = vi.fn()
const req = {
@@ -145,6 +170,27 @@ describe('handleSessionsListRoute', () => {
expect(sessionsListHandler).not.toHaveBeenCalled()
})
+ it.each([
+ ['fractional limit', { limit: '1.5' }],
+ ['repeated limit', { limit: ['1', '2'] }],
+ ['repeated cursor', { cursor: ['one', 'two'] }],
+ ['repeated agent', { agent: ['agent-a', 'agent-b'] }],
+ ['dot agent', { agent: '.' }],
+ ['colon-bearing agent', { agent: 'agent:other' }],
+ ])('rejects %s query input', async (_label, query) => {
+ const sessionsListHandler: SessionsListHandler = vi.fn()
+ const req = {
+ ...makeReqWithAuth('user-1'),
+ query,
+ } 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()
@@ -260,8 +306,11 @@ describe('handleSessionMessagesRoute', () => {
it.each([
['beforeTurn', 'abc'],
['beforeTurn', '0'],
+ ['beforeTurn', '1.5'],
['afterTurn', 'abc'],
['afterTurn', '-1'],
+ ['afterTurn', '1.5'],
+ ['limit', '1.5'],
])('rejects malformed %s cursors', async (name, value) => {
const sessionMessagesHandler: SessionMessagesHandler = vi.fn()
const req = {
@@ -276,6 +325,35 @@ describe('handleSessionMessagesRoute', () => {
expect(sessionMessagesHandler).not.toHaveBeenCalled()
})
+ it('rejects repeated message pagination parameters', async () => {
+ const sessionMessagesHandler: SessionMessagesHandler = vi.fn()
+ const req = {
+ ...makeReqWithParams('user-1', 'chatllm', 'c1'),
+ query: { limit: ['1', '2'] },
+ } as unknown as Request
+ const captured = makeRes()
+
+ await handleSessionMessagesRoute(req, captured.res, makeHandlers({ sessionMessagesHandler }))
+
+ expect(captured.statusCode).toBe(400)
+ expect(sessionMessagesHandler).not.toHaveBeenCalled()
+ })
+
+ it.each([
+ ['dot agent', '.', 'chat-1'],
+ ['dot-dot chat id', 'agent', '..'],
+ ['separator-bearing chat id', 'agent', 'nested/chat'],
+ ])('rejects unsafe %s route segments', async (_label, agent, chatId) => {
+ const sessionMessagesHandler: SessionMessagesHandler = vi.fn()
+ const req = makeReqWithParams('user-1', agent, chatId)
+ 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/__tests__/wireProjections.test.ts b/mcp-host/src/server/__tests__/wireProjections.test.ts
index 5c5ef98c8..e8c658284 100644
--- a/mcp-host/src/server/__tests__/wireProjections.test.ts
+++ b/mcp-host/src/server/__tests__/wireProjections.test.ts
@@ -24,6 +24,25 @@ describe('session pagination projections', () => {
expect(decodeSessionsCursor(invalidDate)).toBeNull()
})
+ it('rejects legacy and cross-scope cursors', () => {
+ const legacy = Buffer.from(
+ JSON.stringify({ updatedAt: '2026-01-03T00:00:00.000Z', key: 'a' })
+ ).toString('base64url')
+ expect(decodeSessionsCursor(legacy)).toBeNull()
+
+ const scoped = paginateSessionSummaries(
+ [
+ { key: 'a', lastActivityAt: new Date('2026-01-03T00:00:00Z') },
+ { key: 'b', lastActivityAt: new Date('2026-01-02T00:00:00Z') },
+ ],
+ 1,
+ key => key,
+ 'scope-a'
+ ).nextCursor
+ expect(decodeSessionsCursor(scoped, 'scope-a')).not.toBeNull()
+ expect(decodeSessionsCursor(scoped, 'scope-b')).toBeNull()
+ })
+
it('returns a cursor only when another summary page exists', () => {
const entries = [
{ key: 'a', lastActivityAt: new Date('2026-01-03T00:00:00Z') },
@@ -32,6 +51,8 @@ describe('session pagination projections', () => {
const result = paginateSessionSummaries(entries, 1)
expect(result.page).toEqual([entries[0]])
expect(decodeSessionsCursor(result.nextCursor)).toEqual({
+ version: 1,
+ scope: 'unscoped',
updatedAt: '2026-01-03T00:00:00.000Z',
key: 'a',
})
diff --git a/mcp-host/src/server/routes.ts b/mcp-host/src/server/routes.ts
index a7866e582..ceed39c36 100644
--- a/mcp-host/src/server/routes.ts
+++ b/mcp-host/src/server/routes.ts
@@ -35,7 +35,7 @@ import type {
WorkflowApprovalNotificationTerminalHandler,
} from './types'
import type { RuntimeCallerContext } from './types'
-import { decodeSessionsCursor } from './wireProjections'
+import { decodeSessionsCursor, sessionsCursorScope } from './wireProjections'
export type RouteHandlers = {
messageHandler: MessageHandler | null
@@ -64,10 +64,23 @@ export type RouteHandlers = {
setModelHandler?: SetModelHandler | null
}
-function parseSessionsCursorParam(cursor: unknown): string | undefined | null {
+function parseSessionsCursorParam(
+ cursor: unknown,
+ expectedScope: string
+): string | undefined | null {
if (cursor === undefined) return undefined
if (typeof cursor !== 'string' || cursor.length > 2048) return null
- return decodeSessionsCursor(cursor) ? cursor : null
+ return decodeSessionsCursor(cursor, expectedScope) ? cursor : null
+}
+
+function isSafeRouteSegment(value: string): boolean {
+ return (
+ value.length > 0 &&
+ value !== '.' &&
+ value !== '..' &&
+ value.length <= 500 &&
+ !/[/\\\0]/.test(value)
+ )
}
function channelRuntimeSourceMismatch(
@@ -1097,26 +1110,32 @@ export async function handleSessionsListRoute(
json(res, 501, { error: 'Sessions handler not configured' })
return
}
+ if (req.query.agent !== undefined && typeof req.query.agent !== 'string') {
+ badRequest(res, 'Invalid session agent')
+ return
+ }
const agent = typeof req.query.agent === 'string' ? req.query.agent.trim() : undefined
- if (agent !== undefined && (!agent || agent.length > 200 || agent.includes(':'))) {
+ if (
+ agent !== undefined &&
+ (!isSafeRouteSegment(agent) || agent.length > 200 || agent.includes(':'))
+ ) {
badRequest(res, 'Invalid session agent')
return
}
- const cursor = parseSessionsCursorParam(req.query.cursor)
+ const cursor = parseSessionsCursorParam(
+ req.query.cursor,
+ sessionsCursorScope(caller.userId, agent)
+ )
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)
- ) {
+ if (req.query.limit !== undefined && (!Number.isInteger(rawLimit) || 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 limit = rawLimit === undefined ? (cursor ? 50 : undefined) : Math.min(rawLimit, 100)
const result = await handlers.sessionsListHandler(caller.userId, { agent, limit, cursor })
json(res, 200, result)
} catch (error) {
@@ -1195,7 +1214,7 @@ export async function handleSessionMessagesRoute(
}
const agent = String(req.params.agent || '').trim()
const chatId = String(req.params.chatId || '').trim()
- if (!agent || !chatId) {
+ if (!isSafeRouteSegment(agent) || !isSafeRouteSegment(chatId)) {
badRequest(res, 'agent and chatId are required')
return
}
@@ -1203,6 +1222,13 @@ export async function handleSessionMessagesRoute(
json(res, 501, { error: 'Sessions handler not configured' })
return
}
+ const invalidQueryShape = ['limit', 'beforeTurn', 'afterTurn'].some(
+ key => req.query[key] !== undefined && typeof req.query[key] !== 'string'
+ )
+ if (invalidQueryShape) {
+ badRequest(res, 'pagination parameters must be specified once')
+ return
+ }
const rawLimit = typeof req.query.limit === 'string' ? Number(req.query.limit) : undefined
const rawBeforeTurn =
typeof req.query.beforeTurn === 'string' ? Number(req.query.beforeTurn) : undefined
@@ -1210,14 +1236,14 @@ export async function handleSessionMessagesRoute(
typeof req.query.afterTurn === 'string' ? Number(req.query.afterTurn) : undefined
if (
req.query.beforeTurn !== undefined &&
- (!Number.isFinite(rawBeforeTurn) || Math.floor(rawBeforeTurn!) < 1)
+ (!Number.isInteger(rawBeforeTurn) || rawBeforeTurn! < 1)
) {
badRequest(res, 'beforeTurn must be a positive integer')
return
}
if (
req.query.afterTurn !== undefined &&
- (!Number.isFinite(rawAfterTurn) || Math.floor(rawAfterTurn!) < 0)
+ (!Number.isInteger(rawAfterTurn) || rawAfterTurn! < 0)
) {
badRequest(res, 'afterTurn must be a non-negative integer')
return
@@ -1226,10 +1252,7 @@ export async function handleSessionMessagesRoute(
badRequest(res, 'beforeTurn and afterTurn are mutually exclusive')
return
}
- if (
- req.query.limit !== undefined &&
- (!Number.isFinite(rawLimit) || Math.floor(rawLimit!) < 1)
- ) {
+ if (req.query.limit !== undefined && (!Number.isInteger(rawLimit) || rawLimit! < 1)) {
badRequest(res, 'limit must be a positive integer')
return
}
@@ -1238,9 +1261,9 @@ export async function handleSessionMessagesRoute(
? 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) : undefined
+ : Math.min(rawLimit, 200)
+ const beforeTurn = rawBeforeTurn
+ const afterTurn = rawAfterTurn
const result = await handlers.sessionMessagesHandler(caller.userId, agent, chatId, {
limit,
beforeTurn,
@@ -1275,7 +1298,7 @@ export async function handleContextBreakdownRoute(
}
const agent = String(req.params.agent || '').trim()
const chatId = String(req.params.chatId || '').trim()
- if (!agent || !chatId) {
+ if (!isSafeRouteSegment(agent) || !isSafeRouteSegment(chatId)) {
badRequest(res, 'agent and chatId are required')
return
}
diff --git a/mcp-host/src/server/wireProjections.ts b/mcp-host/src/server/wireProjections.ts
index 2f4c4528b..ff6ab014e 100644
--- a/mcp-host/src/server/wireProjections.ts
+++ b/mcp-host/src/server/wireProjections.ts
@@ -1,3 +1,4 @@
+import { createHash } from 'node:crypto'
import type { Conversation, Turn } from '../core/types'
import { getDisplayName } from '../progress/intentExtraction'
import type { ContextBreakdownWire, SessionTokensWire, TurnToolStepWire } from './types'
@@ -16,38 +17,63 @@ type SessionTokenSource = Pick<
>
export interface SessionsCursor {
+ version: 1
+ scope: string
updatedAt: string
key: string
}
-export function decodeSessionsCursor(cursor: string | undefined): SessionsCursor | null {
+export function sessionsCursorScope(userSub: string, agent?: string): string {
+ return createHash('sha256')
+ .update(JSON.stringify([userSub, agent ?? null]))
+ .digest('base64url')
+ .slice(0, 24)
+}
+
+export function decodeSessionsCursor(
+ cursor: string | undefined,
+ expectedScope?: string
+): SessionsCursor | null {
if (!cursor) return null
try {
const parsed = JSON.parse(Buffer.from(cursor, 'base64url').toString('utf8')) as {
+ version?: unknown
+ scope?: unknown
updatedAt?: unknown
key?: unknown
}
if (
+ parsed.version !== 1 ||
+ typeof parsed.scope !== 'string' ||
+ (expectedScope !== undefined && parsed.scope !== expectedScope) ||
typeof parsed.updatedAt !== 'string' ||
typeof parsed.key !== 'string' ||
!Number.isFinite(Date.parse(parsed.updatedAt))
) {
return null
}
- return { updatedAt: parsed.updatedAt, key: parsed.key }
+ return {
+ version: 1,
+ scope: parsed.scope,
+ updatedAt: parsed.updatedAt,
+ key: parsed.key,
+ }
} catch {
return null
}
}
-export function encodeSessionsCursor(updatedAt: string, key: string): string {
- return Buffer.from(JSON.stringify({ updatedAt, key }), 'utf8').toString('base64url')
+export function encodeSessionsCursor(updatedAt: string, key: string, scope = 'unscoped'): string {
+ return Buffer.from(JSON.stringify({ version: 1, scope, updatedAt, key }), 'utf8').toString(
+ 'base64url'
+ )
}
export function paginateSessionSummaries<T extends { key: string; lastActivityAt: Date }>(
entries: T[],
limit: number | undefined,
- encodeKey: (key: string) => string = key => key
+ encodeKey: (key: string) => string = key => key,
+ cursorScope = 'unscoped'
): { page: T[]; nextCursor?: string } {
if (limit === undefined) return { page: entries }
const page = entries.slice(0, limit)
@@ -56,7 +82,11 @@ export function paginateSessionSummaries<T extends { key: string; lastActivityAt
page,
...(entries.length > page.length && last
? {
- nextCursor: encodeSessionsCursor(last.lastActivityAt.toISOString(), encodeKey(last.key)),
+ nextCursor: encodeSessionsCursor(
+ last.lastActivityAt.toISOString(),
+ encodeKey(last.key),
+ cursorScope
+ ),
}
: {}),
}
diff --git a/rpc-proxy/package-lock.json b/rpc-proxy/package-lock.json
index 7ed94a896..e99ec57b3 100644
--- a/rpc-proxy/package-lock.json
+++ b/rpc-proxy/package-lock.json
@@ -1,12 +1,12 @@
{
"name": "clerum-rpc-proxy",
- "version": "0.1.55",
+ "version": "0.1.56",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "clerum-rpc-proxy",
- "version": "0.1.55",
+ "version": "0.1.56",
"dependencies": {
"cors": "^2.8.5",
"express": "^4.21.2",
diff --git a/rpc-proxy/package.json b/rpc-proxy/package.json
index 06e1acb89..0b35a6d1c 100644
--- a/rpc-proxy/package.json
+++ b/rpc-proxy/package.json
@@ -1,6 +1,6 @@
{
"name": "clerum-rpc-proxy",
- "version": "0.1.55",
+ "version": "0.1.56",
"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.ts
index 76ed81a53..015c8f0a4 100644
--- a/rpc-proxy/src/__tests__/sessions-passthrough.test.ts
+++ b/rpc-proxy/src/__tests__/sessions-passthrough.test.ts
@@ -114,6 +114,21 @@ describe('GET /rpc/hosts/:hostRef/sessions — passthrough to mcp-host', () => {
expect(String(url)).toBe('http://chatllm:8080/v1/runtime/sessions?agent=chatllm&limit=100')
})
+ it.each([
+ '/rpc/hosts/chatllm/sessions?limit=1.5',
+ '/rpc/hosts/chatllm/sessions?limit=1&limit=2',
+ '/rpc/hosts/chatllm/sessions?cursor=one&cursor=two',
+ '/rpc/hosts/chatllm/sessions?agent=one&agent=two',
+ '/rpc/hosts/chatllm/sessions?agent=.',
+ ])('rejects malformed session pagination before forwarding upstream: %s', async path => {
+ const fetchMock = vi.fn()
+ globalThis.fetch = fetchMock as unknown as typeof fetch
+
+ await request(makeApp()).get(path).set('authorization', 'Bearer user-token').expect(400)
+
+ expect(fetchMock).not.toHaveBeenCalled()
+ })
+
it('returns 403 if the user cannot access the host', async () => {
serviceMock.resolveHostConnectionForUser.mockResolvedValue(null)
await request(makeApp())
@@ -207,6 +222,25 @@ describe('GET /rpc/hosts/:hostRef/sessions/:agent/:chatId/messages — passthrou
)
})
+ it.each([
+ '?limit=1.5',
+ '?limit=1&limit=2',
+ '?beforeTurn=1.5',
+ '?beforeTurn=1&beforeTurn=2',
+ '?afterTurn=1.5',
+ '?beforeTurn=2&afterTurn=1',
+ ])('rejects malformed transcript pagination before forwarding upstream: %s', async query => {
+ const fetchMock = vi.fn()
+ globalThis.fetch = fetchMock as unknown as typeof fetch
+
+ await request(makeApp())
+ .get(`/rpc/hosts/chatllm/sessions/chatllm/c1/messages${query}`)
+ .set('authorization', 'Bearer user-token')
+ .expect(400)
+
+ expect(fetchMock).not.toHaveBeenCalled()
+ })
+
it('returns 404 when the upstream returns 404', async () => {
const fetchMock = vi.fn().mockResolvedValue({
status: 404,
diff --git a/rpc-proxy/src/routes/rpc.ts b/rpc-proxy/src/routes/rpc.ts
index 2c7c65f6d..6a67906d0 100644
--- a/rpc-proxy/src/routes/rpc.ts
+++ b/rpc-proxy/src/routes/rpc.ts
@@ -32,6 +32,16 @@ import { mintOrReuseDirectTraceContext } from '../traceContext.js'
const RFC1123_RE = /^[a-z0-9]([a-z0-9-]{0,61}[a-z0-9])?$/
+function isSafeUpstreamPathSegment(value: string): boolean {
+ return (
+ value.length > 0 &&
+ value !== '.' &&
+ value !== '..' &&
+ value.length <= 500 &&
+ !/[/\\\0]/.test(value)
+ )
+}
+
/**
* Pre-wake host error mapping: AbortError → 504, everything else → 502.
*
@@ -242,7 +252,7 @@ export function createRpcRouter(): Router {
const auth = req.auth!
const rpcAccessToken = extractAuthToken(req)
const hostRef = String(req.params.hostRef || '').trim()
- if (!hostRef) {
+ if (!isSafeUpstreamPathSegment(hostRef)) {
res.status(400).json({ error: 'hostRef is required' })
return
}
@@ -649,7 +659,13 @@ export function createRpcRouter(): Router {
const sessionLimit =
typeof req.query.limit === 'string' ? Number(req.query.limit) : undefined
if (
- (sessionAgent && (sessionAgent.length > 200 || sessionAgent.includes(':'))) ||
+ (req.query.agent !== undefined && typeof req.query.agent !== 'string') ||
+ (req.query.cursor !== undefined && typeof req.query.cursor !== 'string') ||
+ (req.query.limit !== undefined && typeof req.query.limit !== 'string') ||
+ (sessionAgent &&
+ (!isSafeUpstreamPathSegment(sessionAgent) ||
+ sessionAgent.length > 200 ||
+ sessionAgent.includes(':'))) ||
sessionCursor.length > 2048 ||
(sessionLimit !== undefined && (!Number.isInteger(sessionLimit) || sessionLimit < 1))
) {
@@ -716,7 +732,11 @@ export function createRpcRouter(): Router {
const hostRef = String(req.params.hostRef || '').trim()
const agent = String(req.params.agent || '').trim()
const chatId = String(req.params.chatId || '').trim()
- if (!hostRef || !agent || !chatId) {
+ if (
+ !isSafeUpstreamPathSegment(hostRef) ||
+ !isSafeUpstreamPathSegment(agent) ||
+ !isSafeUpstreamPathSegment(chatId)
+ ) {
res.status(400).json({ error: 'hostRef, agent, and chatId are required' })
return
}
@@ -739,7 +759,11 @@ export function createRpcRouter(): Router {
typeof req.query.beforeTurn === 'string' ? Number(req.query.beforeTurn) : undefined
const afterTurn =
typeof req.query.afterTurn === 'string' ? Number(req.query.afterTurn) : undefined
+ const invalidQueryShape = ['limit', 'beforeTurn', 'afterTurn'].some(
+ key => req.query[key] !== undefined && typeof req.query[key] !== 'string'
+ )
if (
+ invalidQueryShape ||
(rawLimit !== undefined && (!Number.isInteger(rawLimit) || rawLimit < 1)) ||
(beforeTurn !== undefined && (!Number.isInteger(beforeTurn) || beforeTurn < 1)) ||
(afterTurn !== undefined && (!Number.isInteger(afterTurn) || afterTurn < 0)) ||