Skip to content

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

TypeScript

perf(sessions): add bounded remote session APIs

Josuéa48bf81c89e8
diff --git a/desktop-app/src/appService.ts b/desktop-app/src/appService.ts
index c12948519..1fd360f08 100644
--- a/desktop-app/src/appService.ts
+++ b/desktop-app/src/appService.ts
@@ -50,9 +50,12 @@ import {
RpcScope,
SessionLifecycleState,
SessionMe,
+ SessionMessagesQuery,
SessionMessagesResult,
SessionState,
SessionTokensLite,
+ SessionsListQuery,
+ SessionsListResult,
SetHostModelResult,
TaskProgressStreamEvent,
TeamDirectoryResult,
@@ -2432,25 +2435,15 @@ export class AppService {
async listSessions(
hostRef: string,
- hostRefs?: string[]
- ): Promise<{
- items: Array<{
- agent: string
- chatId: string
- turnCount: number
- lastActivityAt: string
- state?: SessionLifecycleState
- activeTaskId?: string
- pendingApproval?: PendingApprovalLite
- tokens?: SessionTokensLite
- }>
- }> {
+ hostRefs?: string[],
+ query: SessionsListQuery = {}
+ ): Promise<SessionsListResult> {
const targetHostRef = String(hostRef || '').trim()
if (!targetHostRef) throw new Error('hostRef is required')
const effectiveHostRefs = hostRefs && hostRefs.length > 0 ? hostRefs : [targetHostRef]
const rpc = await this.issueRpcTokenForHostRefs(HOST_SESSION_SCOPES, effectiveHostRefs)
try {
- return await this.rpcClient.listSessions(rpc.token, targetHostRef)
+ return await this.rpcClient.listSessions(rpc.token, targetHostRef, query)
} catch (error) {
const message = error instanceof Error ? error.message : String(error)
if (message.includes('401') && message.toLowerCase().includes('missing token')) {
@@ -2467,7 +2460,8 @@ export class AppService {
hostRef: string,
agent: string,
chatId: string,
- hostRefs?: string[]
+ hostRefs?: string[],
+ query: SessionMessagesQuery = {}
): Promise<SessionMessagesResult> {
const targetHostRef = String(hostRef || '').trim()
if (!targetHostRef || !agent || !chatId) {
@@ -2476,14 +2470,28 @@ export class AppService {
const effectiveHostRefs = hostRefs && hostRefs.length > 0 ? hostRefs : [targetHostRef]
const rpc = await this.issueRpcTokenForHostRefs(HOST_SESSION_SCOPES, effectiveHostRefs)
try {
- return await this.rpcClient.loadSessionMessages(rpc.token, targetHostRef, agent, chatId)
+ return await this.rpcClient.loadSessionMessages(
+ rpc.token,
+ targetHostRef,
+ agent,
+ chatId,
+ query
+ )
} catch (error) {
const message = error instanceof Error ? error.message : String(error)
if (message.includes('401') && message.toLowerCase().includes('missing token')) {
console.warn(
'[AppService] Session messages unavailable because the runtime rejected the session token.'
)
- return { agent, chatId, turns: [] }
+ return {
+ agent,
+ chatId,
+ turns: [],
+ totalTurns: 0,
+ hasMoreBefore: false,
+ hasMoreAfter: false,
+ revision: '0:unavailable',
+ }
}
throw error
}
diff --git a/desktop-app/src/ipc.ts b/desktop-app/src/ipc.ts
index ee9ac25e2..9d07d1a62 100644
--- a/desktop-app/src/ipc.ts
+++ b/desktop-app/src/ipc.ts
@@ -876,11 +876,18 @@ export function registerIpcHandlers(service: AppService): void {
ipcMain.handle(
'rpc:listSessions',
- async (event, payload: { hostRef: string; hostRefs?: string[] }) => {
+ async (
+ event,
+ payload: {
+ hostRef: string
+ hostRefs?: string[]
+ query?: import('./types.js').SessionsListQuery
+ }
+ ) => {
assertTrustedSender(event)
const hostRef = sanitizeString(payload?.hostRef)
if (!hostRef) throw new Error('hostRef is required')
- return service.listSessions(hostRef, payload?.hostRefs)
+ return service.listSessions(hostRef, payload?.hostRefs, payload?.query)
}
)
@@ -888,7 +895,13 @@ export function registerIpcHandlers(service: AppService): void {
'rpc:loadSessionMessages',
async (
event,
- payload: { hostRef: string; agent: string; chatId: string; hostRefs?: string[] }
+ payload: {
+ hostRef: string
+ agent: string
+ chatId: string
+ hostRefs?: string[]
+ query?: import('./types.js').SessionMessagesQuery
+ }
) => {
assertTrustedSender(event)
const hostRef = sanitizeString(payload?.hostRef)
@@ -897,7 +910,7 @@ export function registerIpcHandlers(service: AppService): void {
if (!hostRef || !agent || !chatId) {
throw new Error('hostRef, agent, and chatId are required')
}
- return service.loadSessionMessages(hostRef, agent, chatId, payload?.hostRefs)
+ return service.loadSessionMessages(hostRef, agent, chatId, payload?.hostRefs, payload?.query)
}
)
diff --git a/desktop-app/src/preload.ts b/desktop-app/src/preload.ts
index ddee686a6..7d6f03f82 100644
--- a/desktop-app/src/preload.ts
+++ b/desktop-app/src/preload.ts
@@ -308,10 +308,18 @@ const clerum = Object.freeze({
ipcRenderer.invoke('rpc:listArtifacts', { hostRef, hostRefs }),
downloadArtifact: (hostRef: string, filename: string, hostRefs?: string[]) =>
ipcRenderer.invoke('rpc:downloadArtifact', { hostRef, filename, hostRefs }),
- listSessions: (hostRef: string, hostRefs?: string[]) =>
- ipcRenderer.invoke('rpc:listSessions', { hostRef, hostRefs }),
- loadSessionMessages: (hostRef: string, agent: string, chatId: string, hostRefs?: string[]) =>
- ipcRenderer.invoke('rpc:loadSessionMessages', { hostRef, agent, chatId, hostRefs }),
+ listSessions: (
+ hostRef: string,
+ hostRefs?: string[],
+ query?: import('./types.js').SessionsListQuery
+ ) => ipcRenderer.invoke('rpc:listSessions', { hostRef, hostRefs, query }),
+ loadSessionMessages: (
+ hostRef: string,
+ agent: string,
+ chatId: string,
+ hostRefs?: string[],
+ query?: import('./types.js').SessionMessagesQuery
+ ) => ipcRenderer.invoke('rpc:loadSessionMessages', { hostRef, agent, chatId, hostRefs, query }),
getContextBreakdown: (hostRef: string, agent: string, chatId: string, hostRefs?: string[]) =>
ipcRenderer.invoke('rpc:getContextBreakdown', { hostRef, agent, chatId, hostRefs }),
getHostModels: (hostRef: string, chatId: string, hostRefs?: string[]) =>
diff --git a/desktop-app/src/renderer.d.ts b/desktop-app/src/renderer.d.ts
index b5ce754a8..5af2e3201 100644
--- a/desktop-app/src/renderer.d.ts
+++ b/desktop-app/src/renderer.d.ts
@@ -24,9 +24,11 @@ import {
PrewarmHostResult,
ProfileSettingsOpenOptions,
RpcAllowedServersResult,
- SessionLifecycleState,
+ SessionMessagesQuery,
+ SessionMessagesResult,
SessionState,
- SessionTokensLite,
+ SessionsListQuery,
+ SessionsListResult,
SetHostModelResult,
TaskProgressStreamEvent,
TeamDirectoryResult,
@@ -378,41 +380,16 @@ declare global {
) => Promise<Buffer>
listSessions: (
hostRef: string,
- hostRefs?: string[]
- ) => Promise<{
- items: Array<{
- agent: string
- chatId: string
- turnCount: number
- lastActivityAt: string
- state?: SessionLifecycleState
- activeTaskId?: string
- pendingApproval?: PendingApprovalLite
- tokens?: SessionTokensLite
- }>
- }>
+ hostRefs?: string[],
+ query?: SessionsListQuery
+ ) => Promise<SessionsListResult>
loadSessionMessages: (
hostRef: string,
agent: string,
chatId: string,
- hostRefs?: string[]
- ) => Promise<{
- agent: string
- chatId: string
- state?: SessionLifecycleState
- activeTaskId?: string
- pendingApproval?: PendingApprovalLite
- tokens?: SessionTokensLite
- turns: Array<{
- number: number
- user_input: string
- response?: string
- started_at: string
- completed_at?: string
- tokens?: SessionTokensLite
- tool_steps?: MessageToolStep[]
- }>
- }>
+ hostRefs?: string[],
+ query?: SessionMessagesQuery
+ ) => Promise<SessionMessagesResult>
getContextBreakdown: (
hostRef: string,
agent: string,
diff --git a/desktop-app/src/rpcProxyClient.ts b/desktop-app/src/rpcProxyClient.ts
index 55ca3f544..69c771483 100644
--- a/desktop-app/src/rpcProxyClient.ts
+++ b/desktop-app/src/rpcProxyClient.ts
@@ -12,8 +12,11 @@ import {
PendingApprovalLite,
RpcAllowedServersResult,
SessionLifecycleState,
+ SessionMessagesQuery,
SessionMessagesResult,
SessionTokensLite,
+ SessionsListQuery,
+ SessionsListResult,
SetHostModelResult,
} from './types.js'
@@ -544,23 +547,13 @@ export class RpcProxyClient {
async listSessions(
rpcToken: string,
- hostRef: string
- ): Promise<{
- items: Array<{
- agent: string
- chatId: string
- turnCount: number
- lastActivityAt: string
- // V5: the wire already carries these per-session recovery fields
- // (mcp-host `main.ts` `...sessionStateView(conversation)`); only the TS
- // return type used to omit them, hiding the batch badge seeding source.
- state?: SessionLifecycleState
- activeTaskId?: string
- pendingApproval?: PendingApprovalLite
- tokens?: SessionTokensLite
- }>
- }> {
- const response = await fetch(url(`/api/v1/rpc/hosts/${encodeURIComponent(hostRef)}/sessions`), {
+ hostRef: string,
+ query: SessionsListQuery = {}
+ ): Promise<SessionsListResult> {
+ const requestUrl = new URL(url(`/api/v1/rpc/hosts/${encodeURIComponent(hostRef)}/sessions`))
+ if (query.limit !== undefined) requestUrl.searchParams.set('limit', String(query.limit))
+ if (query.cursor) requestUrl.searchParams.set('cursor', query.cursor)
+ const response = await fetch(requestUrl, {
headers: { authorization: `Bearer ${rpcToken}` },
signal: withTimeout(),
})
@@ -572,32 +565,32 @@ export class RpcProxyClient {
body
)
}
- return response.json() as Promise<{
- items: Array<{
- agent: string
- chatId: string
- turnCount: number
- lastActivityAt: string
- state?: SessionLifecycleState
- activeTaskId?: string
- pendingApproval?: PendingApprovalLite
- tokens?: SessionTokensLite
- }>
- }>
+ return response.json() as Promise<SessionsListResult>
}
async loadSessionMessages(
rpcToken: string,
hostRef: string,
agent: string,
- chatId: string
+ chatId: string,
+ query: SessionMessagesQuery = {}
): Promise<SessionMessagesResult> {
- const response = await fetch(
+ const requestUrl = new URL(
url(
`/api/v1/rpc/hosts/${encodeURIComponent(hostRef)}/sessions/${encodeURIComponent(agent)}/${encodeURIComponent(chatId)}/messages`
- ),
- { headers: { authorization: `Bearer ${rpcToken}` }, signal: withTimeout() }
+ )
)
+ if (query.limit !== undefined) requestUrl.searchParams.set('limit', String(query.limit))
+ if (query.beforeTurn !== undefined) {
+ requestUrl.searchParams.set('beforeTurn', String(query.beforeTurn))
+ }
+ if (query.afterTurn !== undefined) {
+ requestUrl.searchParams.set('afterTurn', String(query.afterTurn))
+ }
+ const response = await fetch(requestUrl, {
+ headers: { authorization: `Bearer ${rpcToken}` },
+ signal: withTimeout(),
+ })
if (response.status === 404) {
// Keep the '404' token in the message: the renderer's `isHttp404` matches on
// it to evict a stale local chat.
diff --git a/desktop-app/src/types.ts b/desktop-app/src/types.ts
index 228eff520..c4dd681f4 100644
--- a/desktop-app/src/types.ts
+++ b/desktop-app/src/types.ts
@@ -844,6 +844,12 @@ export interface ApprovalDecisionResult {
export interface SessionMessagesResult {
agent: string
chatId: string
+ totalTurns?: number
+ oldestTurnNumber?: number
+ latestTurnNumber?: number
+ hasMoreBefore?: boolean
+ hasMoreAfter?: boolean
+ revision?: string
state?: SessionLifecycleState
activeTaskId?: string
pendingApproval?: PendingApprovalLite
@@ -859,6 +865,31 @@ export interface SessionMessagesResult {
}>
}
+export interface SessionMessagesQuery {
+ limit?: number
+ beforeTurn?: number
+ afterTurn?: number
+}
+
+export interface SessionsListQuery {
+ limit?: number
+ cursor?: string
+}
+
+export interface SessionsListResult {
+ items: Array<{
+ agent: string
+ chatId: string
+ turnCount: number
+ lastActivityAt: string
+ state?: SessionLifecycleState
+ activeTaskId?: string
+ pendingApproval?: PendingApprovalLite
+ tokens?: SessionTokensLite
+ }>
+ nextCursor?: string
+}
+
// F5 compile-time guard: `SessionMessagesResult` MUST keep carrying the recovery
// fields the renderer's stream-loss reconcile depends on (P1 seed + P2 rejoin).
// This lives in `src/**` so `build:main` (tsc -p tsconfig.json) enforces it — the
@@ -978,6 +1009,8 @@ export interface ChatMessage {
role: 'user' | 'assistant' | 'system'
content: string
timestamp: number
+ /** Authoritative server turn ordinal used for delta reconciliation and paging. */
+ serverTurnNumber?: number
/** mcp-host task that produced/owns this message — used to rejoin after reload (D.3, v2). */
task_id?: string
attachments?: ChatMessageAttachment[]
diff --git a/mcp-host/src/__tests__/integration/crossDeviceSessions.test.ts b/mcp-host/src/__tests__/integration/crossDeviceSessions.test.ts
index 04a5a2e73..9d0f14f3d 100644
--- a/mcp-host/src/__tests__/integration/crossDeviceSessions.test.ts
+++ b/mcp-host/src/__tests__/integration/crossDeviceSessions.test.ts
@@ -76,10 +76,11 @@ function makeApp(convManager: ConversationManager) {
// Closures mirror main.ts — same prefix filter, same mapping shape.
const handlers = makeHandlers({
- sessionsListHandler: (userSub: string) => {
+ sessionsListHandler: (userSub: string, query) => {
const entries = convManager.listSessionsForUser(`${userSub}:rpc:`)
+ const page = query.limit ? entries.slice(0, query.limit) : entries
return {
- items: entries.map(({ conversation, agent, chatId }) => ({
+ items: page.map(({ conversation, agent, chatId }) => ({
agent,
chatId,
turnCount: conversation.turns.length,
@@ -88,16 +89,34 @@ function makeApp(convManager: ConversationManager) {
})),
}
},
- sessionMessagesHandler: (userSub: string, agentName: string, chatId: string) => {
+ sessionMessagesHandler: (userSub: string, agentName: string, chatId: string, query) => {
// Direct O(1) key lookup — mirrors the main.ts fix.
const key = `${userSub}:rpc:${agentName}:${chatId}`
const conversation = convManager.getSessionByKey(key)
if (!conversation) return null
+ const eligibleTurns =
+ query.afterTurn !== undefined
+ ? conversation.turns.filter(turn => turn.number > query.afterTurn!)
+ : query.beforeTurn !== undefined
+ ? conversation.turns.filter(turn => turn.number < query.beforeTurn!)
+ : conversation.turns
+ const turns =
+ query.limit === undefined
+ ? eligibleTurns
+ : query.afterTurn !== undefined
+ ? eligibleTurns.slice(0, query.limit)
+ : eligibleTurns.slice(-query.limit)
return {
agent: agentName,
chatId,
...stateView(conversation),
- turns: conversation.turns.map(t => ({
+ totalTurns: conversation.turns.length,
+ oldestTurnNumber: turns[0]?.number,
+ latestTurnNumber: turns.at(-1)?.number,
+ hasMoreBefore: Boolean(turns[0] && turns[0].number > 1),
+ hasMoreAfter: Boolean(turns.at(-1) && turns.at(-1)!.number < conversation.turns.length),
+ revision: `${conversation.turns.length}:${conversation.updated_at.getTime()}`,
+ turns: turns.map(t => ({
number: t.number,
user_input: t.user_input,
response: t.response,
diff --git a/mcp-host/src/main.ts b/mcp-host/src/main.ts
index 6556f52fd..58759acb6 100644
--- a/mcp-host/src/main.ts
+++ b/mcp-host/src/main.ts
@@ -2051,31 +2051,114 @@ async function startRPCServer(): Promise<void> {
const redactToolError = (toolName: string, rawError: string): string =>
sanitizeError(toolErrorSafety.sanitizeOutput(toolName, rawError).content)
- const handleSessionsList = async (userSub: string) => {
+ const decodeSessionsCursor = (
+ cursor: string | undefined
+ ): { updatedAt: string; key: string } | null => {
+ if (!cursor) return null
+ try {
+ const parsed = JSON.parse(Buffer.from(cursor, 'base64url').toString('utf8')) as {
+ updatedAt?: unknown
+ key?: unknown
+ }
+ return typeof parsed.updatedAt === 'string' && typeof parsed.key === 'string'
+ ? { updatedAt: parsed.updatedAt, key: parsed.key }
+ : null
+ } catch {
+ return null
+ }
+ }
+
+ const encodeSessionsCursor = (updatedAt: string, key: string): string =>
+ Buffer.from(JSON.stringify({ updatedAt, key }), 'utf8').toString('base64url')
+
+ const handleSessionsList = async (
+ userSub: string,
+ query: { limit?: number; cursor?: string }
+ ) => {
const convManager = agent!.getConversationManager()
- const entries = await convManager.listSessionsForUserAsync(`${userSub}:rpc:`)
+ 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 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 last = page.at(-1)
return {
- items: entries.map(({ conversation, agent: agentName, chatId }) => ({
+ items: page.map(({ conversation, agent: agentName, chatId }) => ({
agent: agentName,
chatId,
turnCount: conversation.turns.length,
lastActivityAt: conversation.updated_at.toISOString(),
...sessionStateView(conversation),
})),
+ ...(hasMore && last
+ ? {
+ nextCursor: encodeSessionsCursor(last.conversation.updated_at.toISOString(), last.key),
+ }
+ : {}),
}
}
- const handleSessionMessages = async (userSub: string, agentName: string, chatId: string) => {
+ const handleSessionMessages = async (
+ userSub: string,
+ agentName: string,
+ chatId: string,
+ query: { limit?: number; beforeTurn?: number; afterTurn?: number }
+ ) => {
const convManager = agent!.getConversationManager()
// Direct O(1) key lookup — spec §2: `conversations.get(`${auth.sub}:rpc:${agent}:${chatId}`)`.
const key = `${userSub}:rpc:${agentName}:${chatId}`
const conversation = await convManager.getSessionByKeyAsync(key)
if (!conversation) return null
+ const allTurns = conversation.turns
+ const eligibleTurns =
+ query.afterTurn !== undefined
+ ? allTurns.filter(turn => turn.number > query.afterTurn!)
+ : query.beforeTurn !== undefined
+ ? allTurns.filter(turn => turn.number < query.beforeTurn!)
+ : allTurns
+ const turns =
+ query.limit === undefined
+ ? eligibleTurns
+ : query.afterTurn !== undefined
+ ? eligibleTurns.slice(0, query.limit)
+ : eligibleTurns.slice(-query.limit)
+ const oldestTurnNumber = turns[0]?.number
+ const latestTurnNumber = turns.at(-1)?.number
+ const firstConversationTurn = allTurns[0]?.number
+ const lastConversationTurn = allTurns.at(-1)?.number
return {
agent: agentName,
chatId,
...sessionStateView(conversation),
- turns: conversation.turns.map(t => ({
+ totalTurns: allTurns.length,
+ oldestTurnNumber,
+ latestTurnNumber,
+ hasMoreBefore:
+ firstConversationTurn !== undefined &&
+ (oldestTurnNumber !== undefined
+ ? oldestTurnNumber > firstConversationTurn
+ : query.afterTurn !== undefined),
+ hasMoreAfter:
+ lastConversationTurn !== undefined &&
+ (latestTurnNumber !== undefined
+ ? latestTurnNumber < lastConversationTurn
+ : query.beforeTurn !== undefined),
+ revision: `${allTurns.length}:${conversation.updated_at.getTime()}`,
+ turns: turns.map(t => ({
number: t.number,
user_input: t.user_input,
response: t.response,
diff --git a/mcp-host/src/server/__tests__/sessionsRoutes.test.ts b/mcp-host/src/server/__tests__/sessionsRoutes.test.ts
index d1b6f2775..6450c214f 100644
--- a/mcp-host/src/server/__tests__/sessionsRoutes.test.ts
+++ b/mcp-host/src/server/__tests__/sessionsRoutes.test.ts
@@ -46,6 +46,7 @@ function makeRes(): CapturedRes {
function makeReqWithAuth(sub: string): Request {
return {
runtimeCaller: { caller: 'rpc-proxy', hostRef: 'chatllm', userId: sub },
+ query: {},
} as unknown as Request
}
@@ -65,7 +66,31 @@ describe('handleSessionsListRoute', () => {
{ agent: 'chatllm', chatId: 'c1', turnCount: 3, lastActivityAt: '2026-04-22T00:00:00Z' },
],
})
- expect(sessionsListHandler).toHaveBeenCalledWith('user-1')
+ expect(sessionsListHandler).toHaveBeenCalledWith('user-1', {
+ limit: undefined,
+ cursor: undefined,
+ })
+ })
+
+ it('normalizes pagination query parameters before calling the handler', async () => {
+ const sessionsListHandler: SessionsListHandler = vi.fn().mockReturnValue({
+ items: [],
+ nextCursor: 'next-page',
+ })
+ const req = {
+ ...makeReqWithAuth('user-1'),
+ query: { limit: '500', cursor: 'current-page' },
+ } as unknown as Request
+ const captured = makeRes()
+
+ await handleSessionsListRoute(req, captured.res, makeHandlers({ sessionsListHandler }))
+
+ expect(captured.statusCode).toBe(200)
+ expect(sessionsListHandler).toHaveBeenCalledWith('user-1', {
+ limit: 100,
+ cursor: 'current-page',
+ })
+ expect(captured.jsonBody).toEqual({ items: [], nextCursor: 'next-page' })
})
it('returns 501 when sessionsListHandler is not configured', async () => {
@@ -98,6 +123,7 @@ function makeReqWithParams(sub: string, agent: string, chatId: string): Request
return {
runtimeCaller: { caller: 'rpc-proxy', hostRef: 'chatllm', userId: sub },
params: { agent, chatId },
+ query: {},
} as unknown as Request
}
@@ -106,6 +132,12 @@ describe('handleSessionMessagesRoute', () => {
const sessionMessagesHandler: SessionMessagesHandler = vi.fn().mockReturnValue({
agent: 'chatllm',
chatId: 'c1',
+ totalTurns: 1,
+ oldestTurnNumber: 1,
+ latestTurnNumber: 1,
+ hasMoreBefore: false,
+ hasMoreAfter: false,
+ revision: '1:1776816000000',
turns: [
{ number: 1, user_input: 'hello', response: 'hi', started_at: '2026-04-22T00:00:00Z' },
],
@@ -117,11 +149,63 @@ describe('handleSessionMessagesRoute', () => {
expect(captured.jsonBody).toEqual({
agent: 'chatllm',
chatId: 'c1',
+ totalTurns: 1,
+ oldestTurnNumber: 1,
+ latestTurnNumber: 1,
+ hasMoreBefore: false,
+ hasMoreAfter: false,
+ revision: '1:1776816000000',
turns: [
{ number: 1, user_input: 'hello', response: 'hi', started_at: '2026-04-22T00:00:00Z' },
],
})
- expect(sessionMessagesHandler).toHaveBeenCalledWith('user-1', 'chatllm', 'c1')
+ expect(sessionMessagesHandler).toHaveBeenCalledWith('user-1', 'chatllm', 'c1', {
+ limit: undefined,
+ beforeTurn: undefined,
+ afterTurn: undefined,
+ })
+ })
+
+ it('normalizes bounded history pagination before calling the handler', async () => {
+ const sessionMessagesHandler: SessionMessagesHandler = vi.fn().mockReturnValue({
+ agent: 'chatllm',
+ chatId: 'c1',
+ totalTurns: 30,
+ oldestTurnNumber: 11,
+ latestTurnNumber: 20,
+ hasMoreBefore: true,
+ hasMoreAfter: true,
+ revision: '30:1776816000000',
+ turns: [],
+ })
+ const req = {
+ ...makeReqWithParams('user-1', 'chatllm', 'c1'),
+ query: { limit: '500', beforeTurn: '21' },
+ } as unknown as Request
+ const captured = makeRes()
+
+ await handleSessionMessagesRoute(req, captured.res, makeHandlers({ sessionMessagesHandler }))
+
+ expect(captured.statusCode).toBe(200)
+ expect(sessionMessagesHandler).toHaveBeenCalledWith('user-1', 'chatllm', 'c1', {
+ limit: 200,
+ beforeTurn: 21,
+ afterTurn: undefined,
+ })
+ })
+
+ it('rejects simultaneous beforeTurn and afterTurn cursors', async () => {
+ const sessionMessagesHandler: SessionMessagesHandler = vi.fn()
+ const req = {
+ ...makeReqWithParams('user-1', 'chatllm', 'c1'),
+ query: { beforeTurn: '10', afterTurn: '20' },
+ } as unknown as Request
+ const captured = makeRes()
+
+ await handleSessionMessagesRoute(req, captured.res, makeHandlers({ sessionMessagesHandler }))
+
+ expect(captured.statusCode).toBe(400)
+ expect(sessionMessagesHandler).not.toHaveBeenCalled()
})
it('returns 404 with the canonical body when the session does not exist', async () => {
@@ -149,6 +233,7 @@ describe('handleSessionMessagesRoute', () => {
const req = {
runtimeCaller: { caller: 'rpc-proxy', hostRef: 'chatllm', userId: 'user-1' },
params: { agent: '', chatId: '' },
+ query: {},
} as unknown as Request
const captured = makeRes()
await handleSessionMessagesRoute(req, captured.res, makeHandlers({ sessionMessagesHandler }))
@@ -156,7 +241,7 @@ describe('handleSessionMessagesRoute', () => {
})
it('returns 401 if req.auth is missing', async () => {
- const req = { params: { agent: 'chatllm', chatId: 'c1' } } as unknown as Request
+ const req = { params: { agent: 'chatllm', chatId: 'c1' }, query: {} } as unknown as Request
const captured = makeRes()
await handleSessionMessagesRoute(
req,
diff --git a/mcp-host/src/server/routes.ts b/mcp-host/src/server/routes.ts
index eb60ff238..5c47941ca 100644
--- a/mcp-host/src/server/routes.ts
+++ b/mcp-host/src/server/routes.ts
@@ -1090,7 +1090,16 @@ export async function handleSessionsListRoute(
json(res, 501, { error: 'Sessions handler not configured' })
return
}
- const result = await handlers.sessionsListHandler(caller.userId)
+ const rawLimit = typeof req.query.limit === 'string' ? Number(req.query.limit) : undefined
+ const limit =
+ rawLimit === undefined
+ ? undefined
+ : Math.min(Math.max(Number.isFinite(rawLimit) ? Math.floor(rawLimit) : 50, 1), 100)
+ const cursor =
+ typeof req.query.cursor === 'string' && req.query.cursor.length <= 2048
+ ? req.query.cursor
+ : undefined
+ const result = await handlers.sessionsListHandler(caller.userId, { limit, cursor })
json(res, 200, result)
} catch (error) {
console.error('[Server] Error listing sessions:', error)
@@ -1176,7 +1185,32 @@ export async function handleSessionMessagesRoute(
json(res, 501, { error: 'Sessions handler not configured' })
return
}
- const result = await handlers.sessionMessagesHandler(caller.userId, agent, chatId)
+ const rawLimit = typeof req.query.limit === 'string' ? Number(req.query.limit) : undefined
+ const rawBeforeTurn =
+ typeof req.query.beforeTurn === 'string' ? Number(req.query.beforeTurn) : undefined
+ const rawAfterTurn =
+ typeof req.query.afterTurn === 'string' ? Number(req.query.afterTurn) : undefined
+ if (rawBeforeTurn !== undefined && rawAfterTurn !== undefined) {
+ badRequest(res, 'beforeTurn and afterTurn are mutually exclusive')
+ return
+ }
+ const limit =
+ rawLimit === undefined
+ ? undefined
+ : Math.min(Math.max(Number.isFinite(rawLimit) ? Math.floor(rawLimit) : 50, 1), 200)
+ const beforeTurn =
+ rawBeforeTurn !== undefined && Number.isFinite(rawBeforeTurn)
+ ? Math.max(1, Math.floor(rawBeforeTurn))
+ : undefined
+ const afterTurn =
+ rawAfterTurn !== undefined && Number.isFinite(rawAfterTurn)
+ ? Math.max(0, Math.floor(rawAfterTurn))
+ : undefined
+ const result = await handlers.sessionMessagesHandler(caller.userId, agent, chatId, {
+ limit,
+ beforeTurn,
+ afterTurn,
+ })
if (result === null) {
// Same body regardless of "never existed" vs "belongs to someone else" — enumeration-defense.
json(res, 404, { error: 'session not found' })
diff --git a/mcp-host/src/server/types.ts b/mcp-host/src/server/types.ts
index 80b3132ac..0b35c2e56 100644
--- a/mcp-host/src/server/types.ts
+++ b/mcp-host/src/server/types.ts
@@ -491,9 +491,20 @@ export type SessionsListItem = {
lastActivityAt: string
} & SessionStateWire
+export type SessionsListQuery = {
+ limit?: number
+ cursor?: string
+}
+
+export type SessionsListResult = {
+ items: SessionsListItem[]
+ nextCursor?: string
+}
+
export type SessionsListHandler = (
- userSub: string
-) => { items: SessionsListItem[] } | Promise<{ items: SessionsListItem[] }>
+ userSub: string,
+ query: SessionsListQuery
+) => SessionsListResult | Promise<SessionsListResult>
/**
* A single tool call within a turn, projected for the desktop progress stepper
@@ -519,6 +530,12 @@ export type TurnToolStepWire = {
export type SessionMessagesResult = {
agent: string
chatId: string
+ totalTurns: number
+ oldestTurnNumber?: number
+ latestTurnNumber?: number
+ hasMoreBefore: boolean
+ hasMoreAfter: boolean
+ revision: string
turns: Array<{
number: number
user_input: string
@@ -532,10 +549,17 @@ export type SessionMessagesResult = {
}>
} & SessionStateWire
+export type SessionMessagesQuery = {
+ limit?: number
+ beforeTurn?: number
+ afterTurn?: number
+}
+
export type SessionMessagesHandler = (
userSub: string,
agent: string,
- chatId: string
+ chatId: string,
+ query: SessionMessagesQuery
) => SessionMessagesResult | null | Promise<SessionMessagesResult | null>
/**
diff --git a/rpc-proxy/src/__tests__/sessions-passthrough.test.ts b/rpc-proxy/src/__tests__/sessions-passthrough.test.ts
index 814d2bfa8..adbfc187c 100644
--- a/rpc-proxy/src/__tests__/sessions-passthrough.test.ts
+++ b/rpc-proxy/src/__tests__/sessions-passthrough.test.ts
@@ -76,6 +76,23 @@ describe('GET /rpc/hosts/:hostRef/sessions — passthrough to mcp-host', () => {
expect((init as RequestInit).headers).toMatchObject(HOST_CONNECTION.headers)
})
+ it('forwards only supported session pagination query parameters', async () => {
+ const fetchMock = vi.fn().mockResolvedValue({
+ status: 200,
+ headers: new Headers({ 'content-type': 'application/json' }),
+ text: async () => JSON.stringify({ items: [], nextCursor: 'next-page' }),
+ } as unknown as Response)
+ globalThis.fetch = fetchMock as unknown as typeof fetch
+
+ await request(makeApp())
+ .get('/rpc/hosts/chatllm/sessions?limit=25&cursor=current&userId=other')
+ .set('authorization', 'Bearer user-token')
+ .expect(200)
+
+ const [url] = fetchMock.mock.calls[0]
+ expect(String(url)).toBe('http://chatllm:8080/v1/runtime/sessions?limit=25&cursor=current')
+ })
+
it('returns 403 if the user cannot access the host', async () => {
serviceMock.resolveHostConnectionForUser.mockResolvedValue(null)
await request(makeApp())
@@ -122,6 +139,34 @@ describe('GET /rpc/hosts/:hostRef/sessions/:agent/:chatId/messages — passthrou
expect(String(url)).toBe('http://chatllm:8080/v1/runtime/sessions/chatllm/c1/messages')
})
+ it('forwards only supported message pagination query parameters', async () => {
+ const fetchMock = vi.fn().mockResolvedValue({
+ status: 200,
+ headers: new Headers({ 'content-type': 'application/json' }),
+ text: async () =>
+ JSON.stringify({
+ agent: 'chatllm',
+ chatId: 'c1',
+ totalTurns: 10,
+ hasMoreBefore: true,
+ hasMoreAfter: false,
+ revision: '10:1',
+ turns: [],
+ }),
+ } as unknown as Response)
+ globalThis.fetch = fetchMock as unknown as typeof fetch
+
+ await request(makeApp())
+ .get('/rpc/hosts/chatllm/sessions/chatllm/c1/messages?limit=5&beforeTurn=6&userId=other')
+ .set('authorization', 'Bearer user-token')
+ .expect(200)
+
+ const [url] = fetchMock.mock.calls[0]
+ expect(String(url)).toBe(
+ 'http://chatllm:8080/v1/runtime/sessions/chatllm/c1/messages?limit=5&beforeTurn=6'
+ )
+ })
+
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 90e8f1194..afbf6f802 100644
--- a/rpc-proxy/src/routes/rpc.ts
+++ b/rpc-proxy/src/routes/rpc.ts
@@ -546,7 +546,13 @@ export function createRpcRouter(): Router {
}
const baseUrl = host.url.replace(/\/+$/, '')
console.info(`[RPC_PROXY] user=${auth.sub} host=${hostRef} method=list-sessions`)
- const response = await fetch(`${baseUrl}/v1/runtime/sessions`, {
+ const upstreamUrl = new URL(`${baseUrl}/v1/runtime/sessions`)
+ for (const key of ['limit', 'cursor'] as const) {
+ if (typeof req.query[key] === 'string') {
+ upstreamUrl.searchParams.set(key, req.query[key])
+ }
+ }
+ const response = await fetch(upstreamUrl, {
method: 'GET',
headers: { ...host.headers },
})
@@ -588,10 +594,18 @@ export function createRpcRouter(): Router {
console.info(
`[RPC_PROXY] user=${auth.sub} host=${hostRef} method=get-session-messages agent=${agent} chatId=${chatId}`
)
- const response = await fetch(
- `${baseUrl}/v1/runtime/sessions/${encodeURIComponent(agent)}/${encodeURIComponent(chatId)}/messages`,
- { method: 'GET', headers: { ...host.headers } }
+ const upstreamUrl = new URL(
+ `${baseUrl}/v1/runtime/sessions/${encodeURIComponent(agent)}/${encodeURIComponent(chatId)}/messages`
)
+ for (const key of ['limit', 'beforeTurn', 'afterTurn'] as const) {
+ if (typeof req.query[key] === 'string') {
+ upstreamUrl.searchParams.set(key, req.query[key])
+ }
+ }
+ const response = await fetch(upstreamUrl, {
+ method: 'GET',
+ headers: { ...host.headers },
+ })
const body = await response.text()
res
.status(response.status)