Skip to content

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

TypeScript

fix(desktop): address loading review regressions

Josué970e02c5b659
diff --git a/desktop-app/package-lock.json b/desktop-app/package-lock.json
index 9597b8544..5021ed01a 100644
--- a/desktop-app/package-lock.json
+++ b/desktop-app/package-lock.json
@@ -1,12 +1,12 @@
{
"name": "evenfire",
- "version": "0.1.323",
+ "version": "0.1.324",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "evenfire",
- "version": "0.1.323",
+ "version": "0.1.324",
"license": "MPL-2.0",
"dependencies": {
"@tanstack/react-query": "5.100.10",
diff --git a/desktop-app/package.json b/desktop-app/package.json
index f07aa132d..4e86e78c8 100644
--- a/desktop-app/package.json
+++ b/desktop-app/package.json
@@ -1,7 +1,7 @@
{
"name": "evenfire",
"productName": "Evenfire",
- "version": "0.1.323",
+ "version": "0.1.324",
"private": true,
"license": "MPL-2.0",
"description": "Evenfire desktop client for secure agent and workflow access",
diff --git a/desktop-app/src/__tests__/chatStore.test.ts b/desktop-app/src/__tests__/chatStore.test.ts
index 7673f9c59..57c68f15a 100644
--- a/desktop-app/src/__tests__/chatStore.test.ts
+++ b/desktop-app/src/__tests__/chatStore.test.ts
@@ -308,6 +308,60 @@ describe('messages', () => {
expect(messages.map(message => message.id)).toEqual(['readable-0'])
})
+ it('keeps the previous paged snapshot if a full rewrite fails while staged', async () => {
+ const pagedStore = new ChatStore(tempDir, {
+ pageSize: 2,
+ maxLocalSyncedMessages: Number.POSITIVE_INFINITY,
+ })
+ await pagedStore.createChat('agent-1', 'rewrite-failure')
+ const originalMessages = [
+ { id: 'old-0', role: 'user' as const, content: 'old-0', timestamp: 0 },
+ { id: 'old-1', role: 'assistant' as const, content: 'old-1', timestamp: 1 },
+ { id: 'old-2', role: 'user' as const, content: 'old-2', timestamp: 2 },
+ { id: 'old-3', role: 'assistant' as const, content: 'old-3', timestamp: 3 },
+ ]
+ await pagedStore.saveMessages('agent-1', 'rewrite-failure', originalMessages)
+
+ const originalWriteFile = fs.writeFile.bind(fs)
+ vi.spyOn(fs, 'writeFile').mockImplementation(async (...args) => {
+ const filePath = String(args[0])
+ if (filePath.includes('rewrite-failure.next-') && filePath.endsWith('000001.json.tmp')) {
+ throw new Error('injected page write failure')
+ }
+ return originalWriteFile(...(args as Parameters<typeof fs.writeFile>))
+ })
+
+ await expect(
+ pagedStore.saveMessages('agent-1', 'rewrite-failure', [
+ { id: 'new-0', role: 'user', content: 'new-0', timestamp: 4 },
+ ])
+ ).rejects.toThrow('injected page write failure')
+
+ const reloaded = await pagedStore.loadMessages('agent-1', 'rewrite-failure')
+ expect(reloaded.map(message => message.id)).toEqual(['old-0', 'old-1', 'old-2', 'old-3'])
+ })
+
+ it('recovers the previous paged snapshot after an interrupted directory switch', async () => {
+ const pagedStore = new ChatStore(tempDir, {
+ pageSize: 2,
+ maxLocalSyncedMessages: Number.POSITIVE_INFINITY,
+ })
+ await pagedStore.createChat('agent-1', 'switch-recovery')
+ await pagedStore.saveMessages('agent-1', 'switch-recovery', [
+ { id: 'm0', role: 'user', content: 'msg-0', timestamp: 0 },
+ { id: 'm1', role: 'assistant', content: 'msg-1', timestamp: 1 },
+ ])
+
+ await fs.rename(
+ chatCacheDir('switch-recovery'),
+ `${chatCacheDir('switch-recovery')}.previous-test`
+ )
+
+ const reloaded = await pagedStore.loadMessages('agent-1', 'switch-recovery')
+ expect(reloaded.map(message => message.id)).toEqual(['m0', 'm1'])
+ await expect(fs.access(chatMetaPath('switch-recovery'))).resolves.toBeUndefined()
+ })
+
it('prunes only old pages whose messages are known to exist on the server', async () => {
const prunedStore = new ChatStore(tempDir, {
pageSize: 2,
diff --git a/desktop-app/src/chatStore.ts b/desktop-app/src/chatStore.ts
index cafb8dddb..a12c46a8c 100644
--- a/desktop-app/src/chatStore.ts
+++ b/desktop-app/src/chatStore.ts
@@ -1,3 +1,4 @@
+import { randomUUID } from 'node:crypto'
import { promises as fs } from 'node:fs'
import { join } from 'node:path'
import type { ChatFile, ChatIndex, ChatMessage, ChatMetadata } from './types.js'
@@ -178,19 +179,41 @@ export class ChatStore {
return join(this.agentDir(agentRef), 'chats', chatId)
}
+ private chatSnapshotSiblingPath(
+ agentRef: string,
+ chatId: string,
+ kind: 'next' | 'previous',
+ token: string
+ ): string {
+ assertSafeSegment('chatId', chatId)
+ return join(this.agentDir(agentRef), 'chats', `${chatId}.${kind}-${token}`)
+ }
+
private chatPagesDirPath(agentRef: string, chatId: string): string {
- return join(this.chatDirPath(agentRef, chatId), 'pages')
+ return this.chatPagesDirFromChatDir(this.chatDirPath(agentRef, chatId))
}
private chatMetaPath(agentRef: string, chatId: string): string {
- return join(this.chatDirPath(agentRef, chatId), 'meta.json')
+ return this.chatMetaPathFromChatDir(this.chatDirPath(agentRef, chatId))
}
- private chatPagePath(agentRef: string, chatId: string, fileName: string): string {
+ private chatPagesDirFromChatDir(chatDir: string): string {
+ return join(chatDir, 'pages')
+ }
+
+ private chatMetaPathFromChatDir(chatDir: string): string {
+ return join(chatDir, 'meta.json')
+ }
+
+ private chatPagePathFromPagesDir(pagesDir: string, fileName: string): string {
if (!PAGE_FILE_PATTERN.test(fileName)) {
throw new Error(`Invalid chat page: unsafe file name`)
}
- return join(this.chatPagesDirPath(agentRef, chatId), fileName)
+ return join(pagesDir, fileName)
+ }
+
+ private chatPagePath(agentRef: string, chatId: string, fileName: string): string {
+ return this.chatPagePathFromPagesDir(this.chatPagesDirPath(agentRef, chatId), fileName)
}
private async writeJsonAtomic(filePath: string, value: unknown): Promise<void> {
@@ -218,8 +241,15 @@ export class ChatStore {
}
private async readPagedMeta(agentRef: string, chatId: string): Promise<PagedChatMeta | null> {
+ return this.readPagedMetaAtPath(this.chatMetaPath(agentRef, chatId), chatId)
+ }
+
+ private async readPagedMetaAtPath(
+ metaPath: string,
+ chatId: string
+ ): Promise<PagedChatMeta | null> {
try {
- const raw = await fs.readFile(this.chatMetaPath(agentRef, chatId), 'utf-8')
+ const raw = await fs.readFile(metaPath, 'utf-8')
const parsed = JSON.parse(raw) as PagedChatMeta
if (
parsed?.version !== PAGED_CHAT_VERSION ||
@@ -280,6 +310,20 @@ export class ChatStore {
chatId: string,
pageNumber: number,
messages: ChatMessage[]
+ ): Promise<ChatPageEntry> {
+ return this.writePageMessagesToDir(
+ chatId,
+ this.chatPagesDirPath(agentRef, chatId),
+ pageNumber,
+ messages
+ )
+ }
+
+ private async writePageMessagesToDir(
+ chatId: string,
+ pagesDir: string,
+ pageNumber: number,
+ messages: ChatMessage[]
): Promise<ChatPageEntry> {
const file = pageFileName(pageNumber)
const page: ChatPageFile = {
@@ -288,7 +332,7 @@ export class ChatStore {
pageNumber,
messages,
}
- await this.writeJsonAtomic(this.chatPagePath(agentRef, chatId, file), page)
+ await this.writeJsonAtomic(this.chatPagePathFromPagesDir(pagesDir, file), page)
return pageEntry(file, messages)
}
@@ -297,13 +341,25 @@ export class ChatStore {
chatId: string,
meta: PagedChatMeta
): Promise<void> {
- await this.writeJsonAtomic(this.chatMetaPath(agentRef, chatId), this.finalizePagedMeta(meta))
+ await this.writePagedMetaToDir(chatId, this.chatDirPath(agentRef, chatId), meta)
+ }
+
+ private async writePagedMetaToDir(
+ chatId: string,
+ chatDir: string,
+ meta: PagedChatMeta
+ ): Promise<void> {
+ await this.writeJsonAtomic(this.chatMetaPathFromChatDir(chatDir), {
+ ...this.finalizePagedMeta(meta),
+ chatId,
+ })
}
private async pruneSyncedPages(
agentRef: string,
chatId: string,
- meta: PagedChatMeta
+ meta: PagedChatMeta,
+ options: { pagesDir?: string } = {}
): Promise<PagedChatMeta> {
if (this.maxLocalSyncedMessages === Number.POSITIVE_INFINITY) {
return this.finalizePagedMeta(meta)
@@ -320,7 +376,8 @@ export class ChatStore {
pruning && page.serverSynced && localCount - page.count >= this.maxLocalSyncedMessages
if (canPrunePage) {
- await fs.rm(this.chatPagePath(agentRef, chatId, page.file), { force: true })
+ const pagesDir = options.pagesDir ?? this.chatPagesDirPath(agentRef, chatId)
+ await fs.rm(this.chatPagePathFromPagesDir(pagesDir, page.file), { force: true })
localCount -= page.count
prunedBeforeCount += page.count
prunedThroughServerTurnNumber = page.lastServerTurnNumber ?? prunedThroughServerTurnNumber
@@ -339,6 +396,32 @@ export class ChatStore {
})
}
+ private async recoverPagedChatUnlocked(agentRef: string, chatId: string): Promise<void> {
+ const activeDir = this.chatDirPath(agentRef, chatId)
+ if (await this.readPagedMeta(agentRef, chatId)) return
+
+ let entries: Array<{ name: string; isDirectory: () => boolean }>
+ try {
+ entries = await fs.readdir(join(this.agentDir(agentRef), 'chats'), { withFileTypes: true })
+ } catch {
+ return
+ }
+
+ const backups = entries
+ .filter(entry => entry.isDirectory() && entry.name.startsWith(`${chatId}.previous-`))
+ .map(entry => join(this.agentDir(agentRef), 'chats', entry.name))
+ .sort()
+ .reverse()
+
+ for (const backupDir of backups) {
+ const meta = await this.readPagedMetaAtPath(this.chatMetaPathFromChatDir(backupDir), chatId)
+ if (!meta) continue
+ await fs.rm(activeDir, { recursive: true, force: true })
+ await fs.rename(backupDir, activeDir)
+ return
+ }
+ }
+
private async writePagedChatUnlocked(
agentRef: string,
chatId: string,
@@ -346,51 +429,79 @@ export class ChatStore {
options: { removeLegacy?: boolean } = {}
): Promise<PagedChatMeta> {
const chatDir = this.chatDirPath(agentRef, chatId)
- const pagesDir = this.chatPagesDirPath(agentRef, chatId)
- await fs.rm(chatDir, { recursive: true, force: true })
+ const snapshotToken = randomUUID()
+ const stagingDir = this.chatSnapshotSiblingPath(agentRef, chatId, 'next', snapshotToken)
+ const backupDir = this.chatSnapshotSiblingPath(agentRef, chatId, 'previous', snapshotToken)
+ const pagesDir = this.chatPagesDirFromChatDir(stagingDir)
+ let movedExistingSnapshot = false
+
+ await fs.mkdir(join(this.agentDir(agentRef), 'chats'), { recursive: true })
+ await fs.rm(stagingDir, { recursive: true, force: true })
await fs.mkdir(pagesDir, { recursive: true })
- const pages: ChatPageEntry[] = []
- for (
- let start = 0, pageNumber = 1;
- start < messages.length;
- start += this.pageSize, pageNumber += 1
- ) {
- pages.push(
- await this.writePageMessages(
- agentRef,
- chatId,
- pageNumber,
- messages.slice(start, start + this.pageSize)
+ try {
+ const pages: ChatPageEntry[] = []
+ for (
+ let start = 0, pageNumber = 1;
+ start < messages.length;
+ start += this.pageSize, pageNumber += 1
+ ) {
+ pages.push(
+ await this.writePageMessagesToDir(
+ chatId,
+ pagesDir,
+ pageNumber,
+ messages.slice(start, start + this.pageSize)
+ )
)
- )
- }
+ }
- const meta = await this.pruneSyncedPages(
- agentRef,
- chatId,
- this.finalizePagedMeta({
- version: PAGED_CHAT_VERSION,
+ const meta = await this.pruneSyncedPages(
+ agentRef,
chatId,
- pageSize: this.pageSize,
- messageCount: messages.length,
- localMessageCount: messages.length,
- pages,
- })
- )
- await this.writePagedMeta(agentRef, chatId, meta)
+ this.finalizePagedMeta({
+ version: PAGED_CHAT_VERSION,
+ chatId,
+ pageSize: this.pageSize,
+ messageCount: messages.length,
+ localMessageCount: messages.length,
+ pages,
+ }),
+ { pagesDir }
+ )
+ await this.writePagedMetaToDir(chatId, stagingDir, meta)
- if (options.removeLegacy) {
- await fs.rm(this.chatFilePath(agentRef, chatId), { force: true })
- }
+ try {
+ await fs.rename(chatDir, backupDir)
+ movedExistingSnapshot = true
+ } catch (err) {
+ if ((err as NodeJS.ErrnoException).code !== 'ENOENT') throw err
+ }
+
+ await fs.rename(stagingDir, chatDir)
+ if (movedExistingSnapshot) {
+ await fs.rm(backupDir, { recursive: true, force: true }).catch(() => undefined)
+ }
+
+ if (options.removeLegacy) {
+ await fs.rm(this.chatFilePath(agentRef, chatId), { force: true })
+ }
- return meta
+ return meta
+ } catch (err) {
+ await fs.rm(stagingDir, { recursive: true, force: true }).catch(() => undefined)
+ if (movedExistingSnapshot) {
+ await fs.rename(backupDir, chatDir).catch(() => undefined)
+ }
+ throw err
+ }
}
private async readOrMigratePagedChatUnlocked(
agentRef: string,
chatId: string
): Promise<PagedChatMeta | null> {
+ await this.recoverPagedChatUnlocked(agentRef, chatId)
const paged = await this.readPagedMeta(agentRef, chatId)
if (paged) return paged
diff --git a/desktop-app/ui/src/hooks/__tests__/useAppController.test.tsx b/desktop-app/ui/src/hooks/__tests__/useAppController.test.tsx
index f688654df..d7bb82aaa 100644
--- a/desktop-app/ui/src/hooks/__tests__/useAppController.test.tsx
+++ b/desktop-app/ui/src/hooks/__tests__/useAppController.test.tsx
@@ -4,6 +4,7 @@ import { scheduleAfterFirstPaint } from '../scheduleAfterFirstPaint'
import {
loadWorkflowRunsWithArtifactsForApprovalRefresh,
loadWorkflowRunsWithArtifactsForWorkflowTarget,
+ scheduleAfterFirstPaintForSession,
} from '../useAppController'
function installWorkflowHarness(runsResult: unknown) {
@@ -124,6 +125,7 @@ describe('loadWorkflowRunsWithArtifactsForWorkflowTarget', () => {
describe('scheduleAfterFirstPaint', () => {
afterEach(() => {
vi.restoreAllMocks()
+ vi.unstubAllGlobals()
})
it('waits for two animation frames before running deferred startup work', async () => {
@@ -143,4 +145,37 @@ describe('scheduleAfterFirstPaint', () => {
frames.shift()?.(2)
expect(task).toHaveBeenCalledTimes(1)
})
+
+ it('runs session-bound deferred startup work when identity is unchanged', async () => {
+ const frames: FrameRequestCallback[] = []
+ vi.stubGlobal('requestAnimationFrame', (callback: FrameRequestCallback) => {
+ frames.push(callback)
+ return frames.length
+ })
+ const identityRef = { current: 'user-1:team-1' }
+ const task = vi.fn(async () => undefined)
+
+ scheduleAfterFirstPaintForSession(identityRef, 'user-1:team-1', task)
+ frames.shift()?.(1)
+ frames.shift()?.(2)
+
+ expect(task).toHaveBeenCalledTimes(1)
+ })
+
+ it('skips session-bound deferred startup work after logout or identity change', async () => {
+ const frames: FrameRequestCallback[] = []
+ vi.stubGlobal('requestAnimationFrame', (callback: FrameRequestCallback) => {
+ frames.push(callback)
+ return frames.length
+ })
+ const identityRef = { current: 'user-1:team-1' }
+ const task = vi.fn(async () => undefined)
+
+ scheduleAfterFirstPaintForSession(identityRef, 'user-1:team-1', task)
+ identityRef.current = null
+ frames.shift()?.(1)
+ frames.shift()?.(2)
+
+ expect(task).not.toHaveBeenCalled()
+ })
})
diff --git a/desktop-app/ui/src/hooks/domain/useChatListController.ts b/desktop-app/ui/src/hooks/domain/useChatListController.ts
index aec6451b2..7cbc9b946 100644
--- a/desktop-app/ui/src/hooks/domain/useChatListController.ts
+++ b/desktop-app/ui/src/hooks/domain/useChatListController.ts
@@ -112,25 +112,6 @@ export function useChatListController({
}
}, [selectedAgent])
- const loadRemainingServerSessions = useCallback(
- async (
- agentRef: string,
- initialCursor: string | undefined
- ): Promise<Awaited<ReturnType<typeof chatStore.listSessions>>['items']> => {
- const items: Awaited<ReturnType<typeof chatStore.listSessions>>['items'] = []
- const seenCursors = new Set<string>()
- let cursor = initialCursor
- while (cursor && !seenCursors.has(cursor)) {
- seenCursors.add(cursor)
- const page = await chatStore.listSessions(agentRef, { limit: 50, cursor })
- items.push(...page.items)
- cursor = page.nextCursor
- }
- return items
- },
- [chatStore.listSessions]
- )
-
// ─── Cross-agent latest-sessions mutators ───
const upsertLatestChatSession = useCallback((agentRef: string, chat: SidebarChatEntry) => {
@@ -190,32 +171,6 @@ export function useChatListController({
return [...dedupedPrevious, ...fromServerOnly].sort(byUpdatedDesc)
})
- if (serverResult.nextCursor) {
- if (selectedAgentRef.current !== agentRef) return
- const additionalItems = await loadRemainingServerSessions(
- agentRef,
- serverResult.nextCursor
- )
- const additionalSessions = additionalItems.filter(session => session.agent === agentRef)
- if (!additionalSessions.length) return
- seedSessionSnapshots(fsm, agentRef, additionalSessions)
- if (selectedAgentRef.current !== agentRef) return
- setChatList(previous => {
- const knownIds = new Set(previous.map(chat => chat.id))
- const additionalChats: SidebarChatEntry[] = additionalSessions
- .filter(session => !knownIds.has(session.chatId))
- .map(session => ({
- id: session.chatId,
- title: `Chat ${session.chatId.slice(0, 8)}`,
- createdAt: session.lastActivityAt,
- updatedAt: session.lastActivityAt,
- messageCount: session.turnCount * 2,
- turnCount: session.turnCount,
- }))
- return [...previous, ...additionalChats].sort(byUpdatedDesc)
- })
- }
-
// Persist server freshness into the local index (spec §5.3): keeps the
// durable sidebar order aligned with the source of truth. Best-effort:
// must never block or fail the visible local-cache render.
@@ -233,13 +188,7 @@ export function useChatListController({
return { index, merged }
},
- [
- chatStore.getIndex,
- chatStore.listSessions,
- chatStore.reconcileServerSessions,
- fsm,
- loadRemainingServerSessions,
- ]
+ [chatStore.getIndex, chatStore.listSessions, chatStore.reconcileServerSessions, fsm]
)
const loadChatList = useCallback(
@@ -527,7 +476,6 @@ export function useChatListController({
return {
agentRef,
sessions: serverResult.items.filter(session => session.agent === agentRef),
- nextCursor: serverResult.nextCursor,
}
})
)
@@ -557,40 +505,6 @@ export function useChatListController({
}
return [...previous, ...remoteOnly].sort(byUpdatedDesc)
})
- void Promise.all(
- sessionGroups.map(async group => ({
- agentRef: group.agentRef,
- sessions: await loadRemainingServerSessions(group.agentRef, group.nextCursor),
- }))
- )
- .then(remainingGroups => {
- if (cancelled) return
- setLatestChatSessions(previous => {
- const knownKeys = new Set(previous.map(item => `${item.agentRef}:${item.id}`))
- const additional: LatestSidebarChatEntry[] = []
- for (const group of remainingGroups) {
- const sessions = group.sessions.filter(session => session.agent === group.agentRef)
- seedSessionSnapshots(fsm, group.agentRef, sessions)
- for (const session of sessions) {
- const key = `${group.agentRef}:${session.chatId}`
- if (knownKeys.has(key)) continue
- knownKeys.add(key)
- additional.push({
- id: session.chatId,
- title: `Chat ${session.chatId.slice(0, 8)}`,
- createdAt: session.lastActivityAt,
- updatedAt: session.lastActivityAt,
- messageCount: session.turnCount * 2,
- turnCount: session.turnCount,
- remote: true,
- agentRef: group.agentRef,
- })
- }
- }
- return [...previous, ...additional].sort(byUpdatedDesc)
- })
- })
- .catch(() => undefined)
} finally {
if (!cancelled) {
setLatestChatSessionsLoading(false)
@@ -601,15 +515,7 @@ export function useChatListController({
return () => {
cancelled = true
}
- }, [
- agentNames,
- chatStore.getIndex,
- chatStore.listSessions,
- isAuthenticated,
- loadMenuData,
- fsm,
- loadRemainingServerSessions,
- ])
+ }, [agentNames, chatStore.getIndex, chatStore.listSessions, isAuthenticated, loadMenuData, fsm])
return {
// State (public contract, re-exported unchanged by the parent).
diff --git a/desktop-app/ui/src/hooks/useAppController.ts b/desktop-app/ui/src/hooks/useAppController.ts
index e9b53495b..3b4954474 100644
--- a/desktop-app/ui/src/hooks/useAppController.ts
+++ b/desktop-app/ui/src/hooks/useAppController.ts
@@ -95,6 +95,21 @@ export async function loadWorkflowRunsWithArtifactsForApprovalRefresh(
})
}
+interface SessionIdentityRef {
+ current: string | null
+}
+
+export function scheduleAfterFirstPaintForSession(
+ sessionIdentityRef: SessionIdentityRef,
+ expectedIdentity: string,
+ task: () => Promise<unknown>
+): void {
+ scheduleAfterFirstPaint(async () => {
+ if (sessionIdentityRef.current !== expectedIdentity) return
+ await task()
+ })
+}
+
export function useAppController() {
const queryClient = useQueryClient()
@@ -362,17 +377,25 @@ export function useAppController() {
? teamsData.refreshInitialDirectory
: teamsData.refresh
if (options.initialLoad) {
+ const scheduledIdentity = authenticatedSessionIdentityRef.current
await refreshAgentsData()
- scheduleAfterFirstPaint(async () => {
- setPostPaintDataReady(true)
- await Promise.all([
- refreshContextsData(),
- refreshMcpServersData(),
- refreshTeams(),
- refreshWorkflowsData(),
- notif.handleRefreshPendingApprovals({ silent: true }),
- ])
- })
+ if (!scheduledIdentity || authenticatedSessionIdentityRef.current !== scheduledIdentity) {
+ return
+ }
+ scheduleAfterFirstPaintForSession(
+ authenticatedSessionIdentityRef,
+ scheduledIdentity,
+ async () => {
+ setPostPaintDataReady(true)
+ await Promise.all([
+ refreshContextsData(),
+ refreshMcpServersData(),
+ refreshTeams(),
+ refreshWorkflowsData(),
+ notif.handleRefreshPendingApprovals({ silent: true }),
+ ])
+ }
+ )
return
}
return Promise.all([
diff --git a/mcp-host/package-lock.json b/mcp-host/package-lock.json
index f488d15a3..d1d1b6c6e 100644
--- a/mcp-host/package-lock.json
+++ b/mcp-host/package-lock.json
@@ -1,12 +1,12 @@
{
"name": "clerum-mcp-host",
- "version": "0.1.210",
+ "version": "0.1.211",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "clerum-mcp-host",
- "version": "0.1.210",
+ "version": "0.1.211",
"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 076738265..966d53d88 100644
--- a/mcp-host/package.json
+++ b/mcp-host/package.json
@@ -1,6 +1,6 @@
{
"name": "clerum-mcp-host",
- "version": "0.1.210",
+ "version": "0.1.211",
"description": "MCP Host - reads Host CRD and provides LLM access via OpenAI/Claude",
"main": "dist/main.js",
"engines": {
diff --git a/mcp-host/src/core/conversation/conversation.ts b/mcp-host/src/core/conversation/conversation.ts
index 649a9681f..056ccaaec 100644
--- a/mcp-host/src/core/conversation/conversation.ts
+++ b/mcp-host/src/core/conversation/conversation.ts
@@ -12,9 +12,11 @@ import {
} from '../types'
import type { SessionTokenUsage } from './conversationStore'
import {
+ ConversationSessionSummary,
ConversationStore,
GetOrCreateOptions,
InMemoryConversationStore,
+ SessionListQuery,
} from './conversationStore'
/**
@@ -144,6 +146,18 @@ export class ConversationManager {
return this.listSessionsForUser(keyPrefix)
}
+ /**
+ * Summary-only listing for `/v1/runtime/sessions`. Durable stores implement
+ * this without loading transcript rows; full turn hydration stays on
+ * `getSessionByKeyAsync` and the messages endpoint.
+ */
+ async listSessionSummariesForUserAsync(
+ keyPrefix: string,
+ query: SessionListQuery = {}
+ ): Promise<ConversationSessionSummary[]> {
+ return this.store.listSessionSummariesByPrefix(keyPrefix, query)
+ }
+
/**
* Look up a single conversation by its exact session key.
* Used by the transcript endpoint: the full key can be reconstructed from
diff --git a/mcp-host/src/core/conversation/conversationStore.ts b/mcp-host/src/core/conversation/conversationStore.ts
index f2869150d..d2dd4ff3f 100644
--- a/mcp-host/src/core/conversation/conversationStore.ts
+++ b/mcp-host/src/core/conversation/conversationStore.ts
@@ -1,5 +1,10 @@
import type { ReapedSession } from '../../db/worker/protocol'
-import type { Conversation, PendingApproval, TurnToolCall } from '../types'
+import {
+ type Conversation,
+ ConversationState,
+ type PendingApproval,
+ type TurnToolCall,
+} from '../types'
/**
* Token usage from a SINGLE LLM call, accumulated additively into the durable
@@ -51,6 +56,63 @@ export interface PersistedSessionListing {
export type EvictCallback = (sessionKey: string, conversation: Conversation) => void
+export interface SessionListCursor {
+ updatedAt: Date
+ key: string
+}
+
+export interface SessionListQuery {
+ limit?: number
+ cursor?: SessionListCursor
+}
+
+export interface ConversationSessionSummary {
+ key: string
+ agent: string
+ chatId: string
+ state: ConversationState
+ activeTaskId?: string
+ pendingApproval?: Pick<PendingApproval, 'request_id' | 'tool_name'>
+ turnCount: number
+ lastActivityAt: Date
+ input_tokens?: number
+ output_tokens?: number
+ cache_read_tokens?: number
+ cache_write_tokens?: number
+ cacheTokensReported?: boolean
+}
+
+function sessionPartsFromKey(
+ key: string,
+ prefix: string
+): { agent: string; chatId: string } | null {
+ const rest = key.slice(prefix.length)
+ const colonIdx = rest.indexOf(':')
+ if (colonIdx < 0) return null
+ return {
+ agent: rest.slice(0, colonIdx),
+ chatId: rest.slice(colonIdx + 1),
+ }
+}
+
+function compareSessionSummaries(
+ left: Pick<ConversationSessionSummary, 'key' | 'lastActivityAt'>,
+ right: Pick<ConversationSessionSummary, 'key' | 'lastActivityAt'>
+): number {
+ const byUpdated = right.lastActivityAt.getTime() - left.lastActivityAt.getTime()
+ return byUpdated || left.key.localeCompare(right.key)
+}
+
+function afterSessionCursor(
+ summary: Pick<ConversationSessionSummary, 'key' | 'lastActivityAt'>,
+ cursor: SessionListCursor | undefined
+): boolean {
+ if (!cursor) return true
+ const updatedAt = summary.lastActivityAt.getTime()
+ const cursorUpdatedAt = cursor.updatedAt.getTime()
+ return updatedAt < cursorUpdatedAt || (updatedAt === cursorUpdatedAt && summary.key > cursor.key)
+}
+
/**
* Storage-level abstraction for the session-keyed conversation map.
*
@@ -102,6 +164,15 @@ export interface ConversationStore {
* list endpoints. Idempotent per prefix. */
prefetchUserSessions(prefix: string): Promise<void>
+ /**
+ * Return bounded session summaries without hydrating complete transcripts.
+ * Full turns are intentionally reserved for `getOrLoad` / message endpoints.
+ */
+ listSessionSummariesByPrefix(
+ prefix: string,
+ query?: SessionListQuery
+ ): Promise<ConversationSessionSummary[]>
+
/** Cold-start sweep: load every session with a pending_approval row,
* pin them in cache, and return enough metadata for the
* `AgentStateMachine` cold-start to wire up `approvalMap`. */
@@ -231,6 +302,42 @@ export class InMemoryConversationStore implements ConversationStore {
/* nothing to prefetch — everything that exists is already in RAM */
}
+ async listSessionSummariesByPrefix(
+ prefix: string,
+ query: SessionListQuery = {}
+ ): Promise<ConversationSessionSummary[]> {
+ const summaries: ConversationSessionSummary[] = []
+ for (const { key, conversation } of this.listByPrefix(prefix)) {
+ const parts = sessionPartsFromKey(key, prefix)
+ if (!parts) continue
+ summaries.push({
+ key,
+ agent: parts.agent,
+ chatId: parts.chatId,
+ state: conversation.state,
+ activeTaskId: conversation.activeTaskId,
+ pendingApproval: conversation.pending_approval
+ ? {
+ request_id: conversation.pending_approval.request_id,
+ tool_name: conversation.pending_approval.tool_name,
+ }
+ : undefined,
+ turnCount: conversation.turns.length,
+ lastActivityAt: conversation.updated_at,
+ input_tokens: conversation.input_tokens,
+ output_tokens: conversation.output_tokens,
+ cache_read_tokens: conversation.cache_read_tokens,
+ cache_write_tokens: conversation.cache_write_tokens,
+ cacheTokensReported: conversation.cacheTokensReported,
+ })
+ }
+
+ const filtered = summaries
+ .filter(summary => afterSessionCursor(summary, query.cursor))
+ .sort(compareSessionSummaries)
+ return query.limit === undefined ? filtered : filtered.slice(0, query.limit)
+ }
+
async loadAllPendingApprovals(): Promise<PersistedSessionListing[]> {
const out: PersistedSessionListing[] = []
for (const [sessionKey, conv] of this.map) {
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 d6810b3f1..a18812837 100644
--- a/mcp-host/src/core/conversation/persistence/__tests__/sqliteConversationStore.test.ts
+++ b/mcp-host/src/core/conversation/persistence/__tests__/sqliteConversationStore.test.ts
@@ -232,6 +232,88 @@ describe('SqliteConversationStore — session token counters', () => {
})
})
+describe('SqliteConversationStore — session summary listing', () => {
+ it('pages summaries from durable rows without hydrating full transcripts', async () => {
+ const handle = await freshStore({ cacheSize: 8 })
+ try {
+ const manager = new ConversationManager(handle.store)
+ const sessions = [
+ { key: 'u-1:rpc:agent-x:chat-1', timestamp: 100 },
+ { key: 'u-1:rpc:agent-x:chat-2', timestamp: 200 },
+ { key: 'u-1:rpc:agent-y:chat-3', timestamp: 300, awaitingApproval: true },
+ ]
+
+ for (const session of sessions) {
+ const conv = await manager.getOrCreate(session.key)
+ await manager.startTurn(conv, `hello ${session.key}`, `task-${session.timestamp}`)
+ if (session.awaitingApproval) {
+ await manager.suspendForApproval(conv, {
+ request_id: 'req-chat-3',
+ tool_name: 'shell_exec',
+ tool_call_id: 'tc-chat-3',
+ parameters: {},
+ description: 'approve test',
+ context_snapshot: [],
+ })
+ } else {
+ manager.recordSessionUsage(conv, {
+ input_tokens: session.timestamp,
+ output_tokens: session.timestamp / 2,
+ cache_read_tokens: 0,
+ cache_write_tokens: 0,
+ })
+ await manager.completeTurn(conv, `done ${session.key}`)
+ }
+ await handle.persistQueue.drainSessionKey(session.key)
+ handle.worker.db
+ .prepare('UPDATE sessions SET started_at = ? WHERE id = ?')
+ .run(session.timestamp - 1, conv.id)
+ handle.worker.db
+ .prepare('UPDATE messages SET timestamp = ? WHERE session_id = ?')
+ .run(session.timestamp, conv.id)
+ }
+
+ handle.store['cache'].clear()
+ handle.store['ordinals'].clear()
+ handle.store['sessionKeyById'].clear()
+
+ const firstPage = await handle.store.listSessionSummariesByPrefix('u-1:rpc:', { limit: 2 })
+ expect(firstPage.map(session => session.chatId)).toEqual(['chat-3', 'chat-2'])
+ expect(firstPage[0]).toMatchObject({
+ agent: 'agent-y',
+ state: ConversationState.AwaitingApproval,
+ activeTaskId: 'task-300',
+ pendingApproval: {
+ request_id: 'req-chat-3',
+ tool_name: 'shell_exec',
+ },
+ turnCount: 1,
+ })
+ expect(firstPage[1]).toMatchObject({
+ agent: 'agent-x',
+ state: ConversationState.Idle,
+ turnCount: 1,
+ input_tokens: 200,
+ output_tokens: 100,
+ cacheTokensReported: true,
+ })
+ expect(handle.store['cache'].size()).toBe(0)
+
+ const secondPage = await handle.store.listSessionSummariesByPrefix('u-1:rpc:', {
+ limit: 2,
+ cursor: {
+ updatedAt: firstPage[1]!.lastActivityAt,
+ key: firstPage[1]!.key,
+ },
+ })
+ expect(secondPage.map(session => session.chatId)).toEqual(['chat-1'])
+ expect(handle.store['cache'].size()).toBe(0)
+ } finally {
+ await handle.shutdown()
+ }
+ })
+})
+
describe('SqliteConversationStore — cold-start rehydration', () => {
it('rehydrates an active session with pending_approval', async () => {
const handle = await freshStore({ cacheSize: 4 })
diff --git a/mcp-host/src/core/conversation/persistence/dualConversationStore.ts b/mcp-host/src/core/conversation/persistence/dualConversationStore.ts
index 19ff63567..fe4972843 100644
--- a/mcp-host/src/core/conversation/persistence/dualConversationStore.ts
+++ b/mcp-host/src/core/conversation/persistence/dualConversationStore.ts
@@ -11,10 +11,12 @@ import { Counter } from 'prom-client'
import type { ReapedSession } from '../../../db/worker/protocol'
import type { Conversation, PendingApproval, TurnToolCall } from '../../types'
import type {
+ ConversationSessionSummary,
ConversationStore,
EvictCallback,
GetOrCreateOptions,
PersistedSessionListing,
+ SessionListQuery,
SessionTokenUsage,
} from '../conversationStore'
@@ -125,6 +127,18 @@ export class DualConversationStore implements ConversationStore {
])
}
+ async listSessionSummariesByPrefix(
+ prefix: string,
+ query: SessionListQuery = {}
+ ): Promise<ConversationSessionSummary[]> {
+ const [memList, sqlList] = await Promise.all([
+ this.memory.listSessionSummariesByPrefix(prefix, query),
+ this.sqlite.listSessionSummariesByPrefix(prefix, query),
+ ])
+ this.recordParity('listSessionSummariesByPrefix', memList.length === sqlList.length)
+ return sqlList.length ? sqlList : memList
+ }
+
async loadAllPendingApprovals(): Promise<PersistedSessionListing[]> {
const [memList, sqlList] = await Promise.all([
this.memory.loadAllPendingApprovals(),
diff --git a/mcp-host/src/core/conversation/persistence/sqliteConversationStore.ts b/mcp-host/src/core/conversation/persistence/sqliteConversationStore.ts
index 552e0e4f1..83615af41 100644
--- a/mcp-host/src/core/conversation/persistence/sqliteConversationStore.ts
+++ b/mcp-host/src/core/conversation/persistence/sqliteConversationStore.ts
@@ -18,16 +18,25 @@ import type {
LoadAllPendingApprovalsRow,
PendingApprovalRow,
PersistedSession,
+ PersistedSessionSummary,
ReapedSession,
SessionRow,
} from '../../../db/worker/protocol'
import { parseSessionKey } from '../../../session/types'
-import type { ChatMessage, Conversation, PendingApproval, TurnToolCall } from '../../types'
import {
+ type ChatMessage,
+ type Conversation,
+ ConversationState,
+ type PendingApproval,
+ type TurnToolCall,
+} from '../../types'
+import {
+ type ConversationSessionSummary,
type ConversationStore,
type EvictCallback,
type GetOrCreateOptions,
type PersistedSessionListing,
+ type SessionListQuery,
type SessionTokenUsage,
} from '../conversationStore'
import type { PersistQueue } from './persistQueue'
@@ -327,6 +336,55 @@ export class SqliteConversationStore implements ConversationStore {
this.prefetchedPrefixes.add(prefix)
}
+ async listSessionSummariesByPrefix(
+ prefix: string,
+ query: SessionListQuery = {}
+ ): Promise<ConversationSessionSummary[]> {
+ await this.persistQueue.drainPrefix(prefix)
+ const rows = await this.persistQueue.enqueueSync<PersistedSessionSummary[]>({
+ kind: 'list_session_summaries_by_prefix',
+ sessionKeyPrefix: prefix,
+ limit: query.limit,
+ cursorUpdatedAt: query.cursor ? query.cursor.updatedAt.getTime() / 1000 : undefined,
+ cursorKey: query.cursor?.key,
+ })
+
+ const out: ConversationSessionSummary[] = []
+ for (const row of rows) {
+ const key = row.session.session_key
+ const rest = key.slice(prefix.length)
+ const colonIdx = rest.indexOf(':')
+ if (colonIdx < 0) continue
+ const state =
+ row.session.state === ConversationState.Processing
+ ? ConversationState.Processing
+ : row.session.state === ConversationState.AwaitingApproval
+ ? ConversationState.AwaitingApproval
+ : ConversationState.Idle
+ out.push({
+ key,
+ agent: rest.slice(0, colonIdx),
+ chatId: rest.slice(colonIdx + 1),
+ state,
+ activeTaskId: row.session.active_task_id ?? undefined,
+ pendingApproval: row.pending_approval
+ ? {
+ request_id: row.pending_approval.request_id,
+ tool_name: row.pending_approval.tool_name,
+ }
+ : undefined,
+ turnCount: Math.max(0, Math.floor(row.turn_count ?? 0)),
+ lastActivityAt: new Date(row.last_activity_at * 1000),
+ input_tokens: row.session.input_tokens,
+ output_tokens: row.session.output_tokens,
+ cache_read_tokens: row.session.cache_read_tokens,
+ cache_write_tokens: row.session.cache_write_tokens,
+ cacheTokensReported: row.session.cache_tokens_reported === 1,
+ })
+ }
+ return out
+ }
+
async loadAllPendingApprovals(): Promise<PersistedSessionListing[]> {
const rows = await this.persistQueue.enqueueSync<LoadAllPendingApprovalsRow[]>({
kind: 'load_all_pending_approvals',
diff --git a/mcp-host/src/db/statements.ts b/mcp-host/src/db/statements.ts
index 4d9fdbcc8..901274283 100644
--- a/mcp-host/src/db/statements.ts
+++ b/mcp-host/src/db/statements.ts
@@ -25,6 +25,7 @@ export interface PreparedStatements {
updateSessionModelSelections: Statement
selectSessionBySessionKey: Statement
selectSessionsByPrefix: Statement
+ selectSessionSummariesByPrefix: Statement
insertMessage: Statement
selectMessagesBySession: Statement
@@ -184,6 +185,43 @@ export function prepareStatements(db: Database): PreparedStatements {
selectSessionsByPrefix: db.prepare(`
SELECT * FROM sessions WHERE session_key LIKE ? ORDER BY started_at DESC
`),
+ selectSessionSummariesByPrefix: db.prepare(`
+ WITH session_summaries AS (
+ SELECT s.*,
+ COALESCE(
+ (SELECT MAX(m.timestamp) FROM messages m WHERE m.session_id = s.id),
+ s.started_at
+ ) AS last_activity_at,
+ COALESCE(
+ (SELECT MAX(m.turn_number) FROM messages m WHERE m.session_id = s.id),
+ 0
+ ) AS turn_count,
+ (
+ SELECT pa.request_id
+ FROM pending_approvals pa
+ WHERE pa.session_id = s.id
+ LIMIT 1
+ ) AS pending_request_id,
+ (
+ SELECT pa.tool_name
+ FROM pending_approvals pa
+ WHERE pa.session_id = s.id
+ LIMIT 1
+ ) AS pending_tool_name
+ FROM sessions s
+ WHERE s.session_key LIKE @pattern
+ )
+ 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
+ `),
insertMessage: db.prepare(`
INSERT INTO messages (
diff --git a/mcp-host/src/db/worker/dispatcher.ts b/mcp-host/src/db/worker/dispatcher.ts
index 2d0555b7a..20313151e 100644
--- a/mcp-host/src/db/worker/dispatcher.ts
+++ b/mcp-host/src/db/worker/dispatcher.ts
@@ -12,6 +12,7 @@ import type {
LoadAllPendingApprovalsRow,
PendingApprovalRow,
PersistedSession,
+ PersistedSessionSummary,
ReapedSession,
SessionRow,
WorkerOp,
@@ -560,6 +561,36 @@ export async function dispatch(op: WorkerOp, deps: DispatcherDeps): Promise<unkn
return result
}
+ case 'list_session_summaries_by_prefix': {
+ const pattern = `${op.sessionKeyPrefix}%`
+ const rows = s.selectSessionSummariesByPrefix.all({
+ pattern,
+ limit: op.limit ?? -1,
+ cursor_updated_at: op.cursorUpdatedAt ?? null,
+ cursor_key: op.cursorKey ?? null,
+ }) as Array<
+ SessionRow & {
+ last_activity_at: number
+ 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
+ return {
+ session: session as SessionRow,
+ last_activity_at,
+ turn_count,
+ pending_approval:
+ pending_request_id && pending_tool_name
+ ? { request_id: pending_request_id, tool_name: pending_tool_name }
+ : null,
+ } satisfies PersistedSessionSummary
+ })
+ }
+
case 'load_all_pending_approvals': {
const rows = s.selectPendingApprovalsAll.all() as Array<
PendingApprovalRow & { session_key: string }
diff --git a/mcp-host/src/db/worker/protocol.ts b/mcp-host/src/db/worker/protocol.ts
index 0efd44633..5286e7c7e 100644
--- a/mcp-host/src/db/worker/protocol.ts
+++ b/mcp-host/src/db/worker/protocol.ts
@@ -111,6 +111,13 @@ export interface PersistedSession {
pending_approval: PendingApprovalRow | null
}
+export interface PersistedSessionSummary {
+ session: SessionRow
+ last_activity_at: number
+ turn_count: number
+ pending_approval: Pick<PendingApprovalRow, 'request_id' | 'tool_name'> | null
+}
+
export interface LoadAllPendingApprovalsRow {
approval: PendingApprovalRow
session_key: string
@@ -209,6 +216,13 @@ export type WorkerOp =
| { kind: 'delete_pending_approval'; requestId: string }
| { kind: 'load_active_session'; sessionKey: string }
| { kind: 'list_sessions_by_prefix'; sessionKeyPrefix: string }
+ | {
+ kind: 'list_session_summaries_by_prefix'
+ sessionKeyPrefix: string
+ limit?: number
+ cursorUpdatedAt?: number
+ cursorKey?: string
+ }
| { kind: 'load_all_pending_approvals' }
| { kind: 'sweep_expired'; nowEpoch: number; ttlSeconds: number }
| { kind: 'fts_search'; query: string; limit: number; userId?: string }
diff --git a/mcp-host/src/main.ts b/mcp-host/src/main.ts
index 58759acb6..5f4dcd486 100644
--- a/mcp-host/src/main.ts
+++ b/mcp-host/src/main.ts
@@ -33,6 +33,7 @@ import {
resolveSessionModel,
} from './config/modelResolution'
import { ContextMapperClient, getContextMapperClient } from './contextMapperClient'
+import type { ConversationSessionSummary } from './core/conversation/conversationStore'
import {
type ConversationStoreHandle,
SqliteColdStartLoader,
@@ -2020,25 +2021,29 @@ async function startRPCServer(): Promise<void> {
// approve button without waiting for the SSE. `displayName` is derived
// server-side (the `tool_name` itself is NOT leaked over the wire — security
// patch P1-1).
- const sessionStateView = (conversation: Conversation) => {
+ const sessionStateView = (session: Conversation | ConversationSessionSummary) => {
const state =
- conversation.state === ConversationState.Processing
+ session.state === ConversationState.Processing
? ('processing' as const)
- : conversation.state === ConversationState.AwaitingApproval
+ : session.state === ConversationState.AwaitingApproval
? ('awaiting_approval' as const)
: ('idle' as const)
- const activeTaskId = state === 'idle' ? undefined : conversation.activeTaskId
+ const activeTaskId = state === 'idle' ? undefined : session.activeTaskId
+ const approval =
+ 'pendingApproval' in session
+ ? session.pendingApproval
+ : (session as Conversation).pending_approval
const pendingApproval =
- conversation.state === ConversationState.AwaitingApproval && conversation.pending_approval
+ session.state === ConversationState.AwaitingApproval && approval
? {
- requestId: conversation.pending_approval.request_id,
- displayName: getDisplayName(conversation.pending_approval.tool_name),
+ requestId: approval.request_id,
+ displayName: getDisplayName(approval.tool_name),
}
: undefined
// Lifetime token totals — projected to the wire shape (omitted until the
// session has had an LLM call; cache breakdown included only when the model
// reports it). See `projectSessionTokens`.
- const tokens = projectSessionTokens(conversation)
+ const tokens = projectSessionTokens(session)
return { state, activeTaskId, pendingApproval, tokens }
}
@@ -2076,37 +2081,26 @@ async function startRPCServer(): Promise<void> {
query: { limit?: number; cursor?: string }
) => {
const convManager = agent!.getConversationManager()
- const entries = (await convManager.listSessionsForUserAsync(`${userSub}:rpc:`)).sort(
- (left, right) => {
- const byUpdated =
- right.conversation.updated_at.getTime() - left.conversation.updated_at.getTime()
- return byUpdated || left.key.localeCompare(right.key)
- }
- )
+ const keyPrefix = `${userSub}:rpc:`
const cursor = decodeSessionsCursor(query.cursor)
- const afterCursor = cursor
- ? entries.filter(entry => {
- const updatedAt = entry.conversation.updated_at.toISOString()
- return (
- updatedAt < cursor.updatedAt ||
- (updatedAt === cursor.updatedAt && entry.key > cursor.key)
- )
- })
- : entries
- const page = query.limit ? afterCursor.slice(0, query.limit) : afterCursor
- const hasMore = query.limit !== undefined && afterCursor.length > page.length
+ const entries = await convManager.listSessionSummariesForUserAsync(keyPrefix, {
+ limit: query.limit === undefined ? undefined : query.limit + 1,
+ cursor: cursor ? { updatedAt: new Date(cursor.updatedAt), key: cursor.key } : undefined,
+ })
+ const page = query.limit ? entries.slice(0, query.limit) : entries
+ const hasMore = query.limit !== undefined && entries.length > page.length
const last = page.at(-1)
return {
- items: page.map(({ conversation, agent: agentName, chatId }) => ({
- agent: agentName,
- chatId,
- turnCount: conversation.turns.length,
- lastActivityAt: conversation.updated_at.toISOString(),
- ...sessionStateView(conversation),
+ items: page.map(summary => ({
+ agent: summary.agent,
+ chatId: summary.chatId,
+ turnCount: summary.turnCount,
+ lastActivityAt: summary.lastActivityAt.toISOString(),
+ ...sessionStateView(summary),
})),
...(hasMore && last
? {
- nextCursor: encodeSessionsCursor(last.conversation.updated_at.toISOString(), last.key),
+ nextCursor: encodeSessionsCursor(last.lastActivityAt.toISOString(), last.key),
}
: {}),
}
diff --git a/mcp-host/src/server/wireProjections.ts b/mcp-host/src/server/wireProjections.ts
index 6717a424b..3126db14a 100644
--- a/mcp-host/src/server/wireProjections.ts
+++ b/mcp-host/src/server/wireProjections.ts
@@ -6,6 +6,15 @@ import type { ContextBreakdownWire, SessionTokensWire, TurnToolStepWire } from '
// by `/v1/runtime/sessions` and `/messages` (per-session + per-turn token
// usage, and per-turn tool steps). Pure functions, unit-tested in isolation.
+type SessionTokenSource = Pick<
+ Conversation,
+ | 'input_tokens'
+ | 'output_tokens'
+ | 'cache_read_tokens'
+ | 'cache_write_tokens'
+ | 'cacheTokensReported'
+>
+
/**
* Project a Conversation's lifetime token mirror into the wire shape served by
* `/v1/runtime/sessions` and `/messages`.
@@ -16,7 +25,9 @@ import type { ContextBreakdownWire, SessionTokensWire, TurnToolStepWire } from '
* cache hit" (Anthropic) from "absent because the provider doesn't report
* cache" (OpenAI / zai / bailian).
*/
-export function projectSessionTokens(conversation: Conversation): SessionTokensWire | undefined {
+export function projectSessionTokens(
+ conversation: SessionTokenSource
+): SessionTokensWire | undefined {
const hasTokens =
!!conversation.input_tokens ||
!!conversation.output_tokens ||