Evenfire is an intelligence layer platform for running LLM agents that take real actions, on your infrastructure
TypeScript
feat: isolate desktop loading improvements
Josuéc11c4ab6ca0a
diff --git a/desktop-app/package-lock.json b/desktop-app/package-lock.jsonindex 9597b8544..2c8edbfe5 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.343","lockfileVersion": 3,"requires": true,"packages": {"": {"name": "evenfire",- "version": "0.1.323",+ "version": "0.1.343","license": "MPL-2.0","dependencies": {"@tanstack/react-query": "5.100.10",diff --git a/desktop-app/package.json b/desktop-app/package.jsonindex f07aa132d..31b80d921 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.343","private": true,"license": "MPL-2.0","description": "Evenfire desktop client for secure agent and workflow access",diff --git a/desktop-app/scripts/start-branded-app.mjs b/desktop-app/scripts/start-branded-app.mjsindex b1c147957..263b0d3f8 100644--- a/desktop-app/scripts/start-branded-app.mjs+++ b/desktop-app/scripts/start-branded-app.mjs@@ -70,7 +70,7 @@ async function main() {throw new Error(`The branded ${APP_NAME} executable was not created at ${executable}.`)}- const appProcess = spawn(executable, [], {+ const appProcess = spawn(executable, ['--evenfire-desktop-dev-package'], {cwd: projectDirectory,env: process.env,stdio: 'inherit',diff --git a/desktop-app/src/__tests__/appService.bootstrap.test.ts b/desktop-app/src/__tests__/appService.bootstrap.test.tsindex 779e8850d..5ef06dca6 100644--- a/desktop-app/src/__tests__/appService.bootstrap.test.ts+++ b/desktop-app/src/__tests__/appService.bootstrap.test.ts@@ -9,6 +9,7 @@ import path from 'node:path'vi.mock('../chatStoreBinding.js', () => ({bindChatStoreForUser: vi.fn(),unbindChatStore: vi.fn(),+ __setChatStoreBaseDirForTests: vi.fn(),}))describe('AppService invitation configuration lookup', () => {@@ -16,6 +17,13 @@ describe('AppService invitation configuration lookup', () => {const originalExternalRestApiBaseUrl = process.env.EXTERNAL_REST_API_BASE_URLconst originalRpcProxyBaseUrl = process.env.RPC_PROXY_BASE_URLconst originalProfileUiBaseUrl = process.env.PROFILE_UI_BASE_URL+ const tempDirs = new Set<string>()++ async function createTempConfigPath(prefix: string): Promise<string> {+ const tempDir = await fs.mkdtemp(path.join(os.tmpdir(), `${prefix}-`))+ tempDirs.add(tempDir)+ return path.join(tempDir, 'config.json')+ }afterEach(async () => {if (originalConfigPath === undefined) {@@ -39,13 +47,14 @@ describe('AppService invitation configuration lookup', () => {process.env.PROFILE_UI_BASE_URL = originalProfileUiBaseUrl}vi.resetModules()+ await Promise.all(+ [...tempDirs].map(tempDir => fs.rm(tempDir, { recursive: true, force: true }))+ )+ tempDirs.clear()})it('persists runtime config when desktop setup is completed', async () => {- const configPath = path.join(- os.tmpdir(),- `clerum-desktop-config-${Date.now()}-${Math.random().toString(16).slice(2)}.json`- )+ const configPath = await createTempConfigPath('clerum-desktop-config')process.env.CLERUM_DESKTOP_CONFIG_PATH = configPathdelete process.env.EXTERNAL_REST_API_BASE_URLdelete process.env.RPC_PROXY_BASE_URL@@ -120,7 +129,7 @@ describe('AppService invitation configuration lookup', () => {// chat:* IPC throws "Not authenticated" until something else re-binds.expect(bindChatStoreForUser).toHaveBeenCalledWith('user-1',- resolveEnvKey('https://api.example.com')+ resolveEnvKey('https://api.example.com', 'https://rpc.example.com'))expect(config.externalRestApiBaseUrl).toBe('https://api.example.com')expect(config.rpcProxyBaseUrl).toBe('https://rpc.example.com')@@ -183,12 +192,293 @@ describe('AppService invitation configuration lookup', () => {expect(service.authClient.passwordLogin).toHaveBeenCalledWith('[email protected]', 'password123')})- it('persists a manually saved runtime environment', async () => {- const configPath = path.join(- os.tmpdir(),- `clerum-desktop-manual-config-${Date.now()}-${Math.random().toString(16).slice(2)}.json`+ it('does not repeat a failed startup restore before the login screen can paint', async () => {+ const configPath = await createTempConfigPath('clerum-desktop-restore-local')+ await fs.writeFile(+ configPath,+ JSON.stringify({+ externalRestApiBaseUrl: 'http://127.0.0.1:8091',+ rpcProxyBaseUrl: 'http://127.0.0.1:8094',+ appName: 'Localhost',+ })+ )+ process.env.CLERUM_DESKTOP_CONFIG_PATH = configPath+ process.env.EXTERNAL_REST_API_BASE_URL = 'http://127.0.0.1:8091'+ process.env.RPC_PROXY_BASE_URL = 'http://127.0.0.1:8094'+ delete process.env.PROFILE_UI_BASE_URL+ vi.resetModules()++ const { AppService } = await import('../appService.js')+ const getSessionToken = vi.fn().mockResolvedValue('stored-token')+ const clearSessionToken = vi.fn().mockResolvedValue(undefined)+ const service = new AppService() as unknown as {+ authClient: { getMe: ReturnType<typeof vi.fn> }+ tokenStore: {+ getSessionToken: ReturnType<typeof vi.fn>+ clearSessionToken: ReturnType<typeof vi.fn>+ }+ rpcTokenManager: { clear: ReturnType<typeof vi.fn> }+ initialize: () => Promise<unknown>+ getSessionState: () => Promise<unknown>+ }++ service.authClient = {+ getMe: vi.fn().mockRejectedValue(new Error('fetch failed')),+ } as never+ service.tokenStore = {+ getSessionToken,+ clearSessionToken,+ } as never+ service.rpcTokenManager = {+ clear: vi.fn(),+ } as never++ const warn = vi.spyOn(console, 'warn').mockImplementation(() => undefined)+ try {+ await expect(service.initialize()).resolves.toEqual({ authenticated: false, me: null })++ expect(clearSessionToken).not.toHaveBeenCalled()++ await expect(service.getSessionState()).resolves.toEqual({+ authenticated: false,+ me: null,+ })+ expect(getSessionToken).toHaveBeenCalledTimes(1)+ expect(service.authClient.getMe).toHaveBeenCalledTimes(1)+ } finally {+ warn.mockRestore()+ }+ })++ 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(+ configPath,+ JSON.stringify({+ externalRestApiBaseUrl: 'http://127.0.0.1:8091',+ rpcProxyBaseUrl: 'http://127.0.0.1:8094',+ appName: 'Localhost',+ }))process.env.CLERUM_DESKTOP_CONFIG_PATH = configPath+ process.env.EXTERNAL_REST_API_BASE_URL = 'http://127.0.0.1:8091'+ process.env.RPC_PROXY_BASE_URL = 'http://127.0.0.1:8094'+ vi.resetModules()+ vi.doMock('electron', () => ({+ app: {+ getPath: vi.fn(() => path.dirname(configPath)),+ isPackaged: false,+ isReady: vi.fn(() => true),+ setName: vi.fn(),+ setPath: vi.fn(),+ },+ }))++ const [{ AppService }, chatStoreBinding] = await Promise.all([+ import('../appService.js'),+ import('../chatStoreBinding.js'),+ ])+ chatStoreBinding.__setChatStoreBaseDirForTests(path.dirname(configPath))+ const me = {+ id: 'user-1',+ email: '[email protected]',+ name: null,+ picture: null,+ teamId: 'team-1',+ teamName: 'Marketing',+ role: 'member',+ }+ let resolveMe!: (value: typeof me) => void+ const pendingMe = new Promise<typeof me>(resolve => {+ resolveMe = resolve+ })+ const getSessionToken = vi.fn().mockResolvedValue('stored-token')+ const getMe = vi.fn().mockReturnValue(pendingMe)+ const service = new AppService() as unknown as {+ authClient: { getMe: ReturnType<typeof vi.fn> }+ tokenStore: {+ getSessionToken: ReturnType<typeof vi.fn>+ clearSessionToken: ReturnType<typeof vi.fn>+ }+ rpcTokenManager: { clear: ReturnType<typeof vi.fn> }+ initialize: () => Promise<unknown>+ getSessionState: () => Promise<unknown>+ }+ service.authClient = { getMe } as never+ service.tokenStore = {+ getSessionToken,+ clearSessionToken: vi.fn(),+ } as never+ service.rpcTokenManager = { clear: vi.fn() } as never++ const first = service.initialize()+ const second = service.getSessionState()+ resolveMe(me)++ await expect(Promise.all([first, second])).resolves.toEqual([+ { authenticated: true, me },+ { authenticated: true, me },+ ])+ expect(getSessionToken).toHaveBeenCalledTimes(1)+ expect(getMe).toHaveBeenCalledTimes(1)+ })++ it('clears a saved token when startup session restore is rejected by the API', async () => {+ const configPath = await createTempConfigPath('clerum-desktop-restore-api')+ await fs.writeFile(+ configPath,+ JSON.stringify({+ externalRestApiBaseUrl: 'https://api.example.com',+ rpcProxyBaseUrl: 'https://rpc.example.com',+ appName: 'Example',+ })+ )+ process.env.CLERUM_DESKTOP_CONFIG_PATH = configPath+ process.env.EXTERNAL_REST_API_BASE_URL = 'https://api.example.com'+ process.env.RPC_PROXY_BASE_URL = 'https://rpc.example.com'+ delete process.env.PROFILE_UI_BASE_URL+ vi.resetModules()++ const [{ AppService }, { resolveEnvKey }, { ApiError }] = await Promise.all([+ import('../appService.js'),+ import('../config.js'),+ import('../httpClient.js'),+ ])+ const clearSessionToken = vi.fn().mockResolvedValue(undefined)+ const service = new AppService() as unknown as {+ authClient: { getMe: ReturnType<typeof vi.fn> }+ tokenStore: {+ getSessionToken: ReturnType<typeof vi.fn>+ clearSessionToken: ReturnType<typeof vi.fn>+ }+ rpcTokenManager: { clear: ReturnType<typeof vi.fn> }+ initialize: () => Promise<unknown>+ }++ service.authClient = {+ getMe: vi.fn().mockRejectedValue(new ApiError('401 Unauthorized', 401, '')),+ } as never+ service.tokenStore = {+ getSessionToken: vi.fn().mockResolvedValue('stored-token'),+ clearSessionToken,+ } as never+ service.rpcTokenManager = {+ clear: vi.fn(),+ } as never++ await expect(service.initialize()).resolves.toEqual({ authenticated: false, me: null })++ expect(clearSessionToken).toHaveBeenCalledWith(+ resolveEnvKey('https://api.example.com', 'https://rpc.example.com')+ )+ })++ it('clears a saved token when startup session restore is forbidden', async () => {+ const configPath = await createTempConfigPath('clerum-desktop-restore-forbidden')+ await fs.writeFile(+ configPath,+ JSON.stringify({+ externalRestApiBaseUrl: 'https://api.example.com',+ rpcProxyBaseUrl: 'https://rpc.example.com',+ appName: 'Example',+ })+ )+ process.env.CLERUM_DESKTOP_CONFIG_PATH = configPath+ process.env.EXTERNAL_REST_API_BASE_URL = 'https://api.example.com'+ process.env.RPC_PROXY_BASE_URL = 'https://rpc.example.com'+ delete process.env.PROFILE_UI_BASE_URL+ vi.resetModules()++ const [{ AppService }, { ApiError }] = await Promise.all([+ import('../appService.js'),+ import('../httpClient.js'),+ ])+ const clearSessionToken = vi.fn().mockResolvedValue(undefined)+ const service = new AppService() as unknown as {+ authClient: { getMe: ReturnType<typeof vi.fn> }+ tokenStore: {+ getSessionToken: ReturnType<typeof vi.fn>+ clearSessionToken: ReturnType<typeof vi.fn>+ }+ rpcTokenManager: { clear: ReturnType<typeof vi.fn> }+ initialize: () => Promise<unknown>+ }++ service.authClient = {+ getMe: vi.fn().mockRejectedValue(new ApiError('403 Forbidden', 403, '')),+ } as never+ service.tokenStore = {+ getSessionToken: vi.fn().mockResolvedValue('stored-token'),+ clearSessionToken,+ } as never+ service.rpcTokenManager = {+ clear: vi.fn(),+ } as never++ await expect(service.initialize()).resolves.toEqual({ authenticated: false, me: null })++ expect(clearSessionToken).toHaveBeenCalled()+ })++ it('persists a manually saved runtime environment', async () => {+ const configPath = await createTempConfigPath('clerum-desktop-manual-config')+ process.env.CLERUM_DESKTOP_CONFIG_PATH = configPathdelete process.env.EXTERNAL_REST_API_BASE_URLdelete process.env.RPC_PROXY_BASE_URLdelete process.env.PROFILE_UI_BASE_URLdiff --git a/desktop-app/src/__tests__/chatMessageMerge.test.ts b/desktop-app/src/__tests__/chatMessageMerge.test.tsnew file mode 100644index 000000000..f5985b4f4--- /dev/null+++ b/desktop-app/src/__tests__/chatMessageMerge.test.ts@@ -0,0 +1,857 @@+import { describe, expect, it } from 'vitest'+import { mergeAuthoritativeServerMessages } from '../chatMessageMerge.js'+import { turnsToChatMessages } from '../serverTurnAdapter.js'+import type { ChatMessage } from '../types.js'++describe('mergeAuthoritativeServerMessages', () => {+ it('replaces an image-only optimistic turn despite content and clock differences', () => {+ const existing: ChatMessage[] = [+ {+ id: 'optimistic-user',+ role: 'user',+ content: '',+ timestamp: 1,+ attachments: [+ {+ id: 'photo',+ type: 'uploaded_file',+ label: 'photo.png',+ mimeType: 'image/png',+ },+ ],+ },+ {+ id: 'optimistic-assistant',+ role: 'assistant',+ content: 'working',+ timestamp: 2,+ },+ ]+ const incoming: ChatMessage[] = [+ {+ id: 'turn-7-user',+ role: 'user',+ content: '[Image attached]',+ timestamp: 120_001,+ serverTurnNumber: 7,+ },+ {+ id: 'turn-7-assistant',+ role: 'assistant',+ content: 'done',+ timestamp: 120_002,+ serverTurnNumber: 7,+ },+ ]++ const merged = mergeAuthoritativeServerMessages(existing, incoming)++ expect(merged.map(message => message.id)).toEqual(['turn-7-user', 'turn-7-assistant'])+ expect(merged[0]?.attachments).toEqual(existing[0]?.attachments)+ })++ it('preserves a task-backed in-flight message outside the authoritative turn', () => {+ const pending: ChatMessage = {+ id: 'pending',+ role: 'assistant',+ content: 'still running',+ timestamp: 2,+ task_id: 'task-1',+ }+ const merged = mergeAuthoritativeServerMessages(+ [{ id: 'optimistic', role: 'user', content: 'old', timestamp: 1 }, pending],+ [+ {+ id: 'turn-3-user',+ role: 'user',+ content: 'server copy',+ timestamp: 100,+ serverTurnNumber: 3,+ },+ ],+ { activeTaskIds: new Set(['task-1']) }+ )++ expect(merged.map(message => message.id)).toEqual(['turn-3-user', 'pending'])+ })++ it('keeps an active optimistic message until the server identifies its task', () => {+ const serverMessages = turnsToChatMessages([+ {+ number: 2,+ user_input: 'second',+ started_at: new Date(3).toISOString(),+ },+ ])+ const merged = mergeAuthoritativeServerMessages(+ [+ {+ id: 'turn-1-user',+ role: 'user',+ content: 'first',+ timestamp: 1,+ serverTurnNumber: 1,+ },+ {+ id: 'optimistic-task-2',+ role: 'user',+ content: 'second',+ timestamp: 2,+ task_id: 'task-2',+ },+ ],+ serverMessages,+ { activeTaskIds: new Set(['task-2']) }+ )++ expect(merged).toEqual([+ expect.objectContaining({ id: 'turn-1-user' }),+ expect.objectContaining({+ id: 'optimistic-task-2',+ content: 'second',+ task_id: 'task-2',+ }),+ ])+ })++ it('replaces an active optimistic message when the server identifies the same task', () => {+ const merged = mergeAuthoritativeServerMessages(+ [+ {+ id: 'optimistic-task-2',+ role: 'user',+ content: 'second',+ timestamp: 2,+ task_id: 'task-2',+ },+ ],+ [+ {+ id: 'turn-2-user',+ role: 'user',+ content: 'second',+ timestamp: 3,+ task_id: 'task-2',+ serverTurnNumber: 2,+ },+ ],+ { activeTaskIds: new Set(['task-2']) }+ )++ expect(merged).toEqual([+ expect.objectContaining({+ id: 'turn-2-user',+ content: 'second',+ task_id: 'task-2',+ }),+ ])+ })++ it('replaces a turnless echo after the previous numbered turn', () => {+ const merged = mergeAuthoritativeServerMessages(+ [+ {+ id: 'turn-1-user',+ role: 'user',+ content: 'first',+ timestamp: 1,+ serverTurnNumber: 1,+ },+ {+ id: 'optimistic-user',+ role: 'user',+ content: 'second',+ timestamp: 2,+ },+ ],+ turnsToChatMessages([+ {+ number: 2,+ user_input: 'second',+ started_at: new Date(3).toISOString(),+ },+ ])+ )++ expect(merged.map(message => message.id)).toEqual(['turn-1-user', 'turn-2-user'])+ })++ it('replaces completed task-backed echoes inside their authoritative turn', () => {+ const merged = mergeAuthoritativeServerMessages(+ [+ {+ id: 'optimistic-user',+ role: 'user',+ content: 'hello',+ timestamp: 1,+ task_id: 'completed-task',+ },+ {+ id: 'optimistic-assistant',+ role: 'assistant',+ content: 'done',+ timestamp: 2,+ task_id: 'completed-task',+ },+ ],+ [+ {+ id: 'turn-4-user',+ role: 'user',+ content: 'hello',+ timestamp: 100,+ serverTurnNumber: 4,+ },+ {+ id: 'turn-4-assistant',+ role: 'assistant',+ content: 'done',+ timestamp: 101,+ serverTurnNumber: 4,+ },+ ]+ )++ expect(merged.map(message => message.id)).toEqual(['turn-4-user', 'turn-4-assistant'])+ expect(merged.every(message => message.task_id === 'completed-task')).toBe(true)+ })++ it('preserves turnless system messages inside an authoritative range', () => {+ const system: ChatMessage = {+ id: 'system-note',+ role: 'system',+ content: 'local diagnostic',+ timestamp: 2,+ }+ const merged = mergeAuthoritativeServerMessages(+ [+ {+ id: 'turn-1-assistant',+ role: 'assistant',+ content: 'first',+ timestamp: 1,+ serverTurnNumber: 1,+ },+ system,+ {+ id: 'turn-3-user',+ role: 'user',+ content: 'third',+ timestamp: 3,+ serverTurnNumber: 3,+ },+ ],+ [+ {+ id: 'turn-2-user',+ role: 'user',+ content: 'second',+ timestamp: 20,+ serverTurnNumber: 2,+ },+ ]+ )++ expect(merged.map(message => message.id)).toEqual([+ 'turn-1-assistant',+ 'system-note',+ 'turn-2-user',+ 'turn-3-user',+ ])+ })++ it('preserves durable turnless message positions between replaced turns', () => {+ const merged = mergeAuthoritativeServerMessages(+ [+ {+ id: 'turn-2-user-local',+ role: 'user',+ content: 'second',+ timestamp: 1,+ serverTurnNumber: 2,+ },+ {+ id: 'system-note',+ role: 'system',+ content: 'local diagnostic',+ timestamp: 2,+ },+ {+ id: 'durable-error',+ role: 'assistant',+ content: 'connection interrupted',+ timestamp: 3,+ isError: true,+ },+ {+ id: 'turn-3-user-local',+ role: 'user',+ content: 'third',+ timestamp: 4,+ serverTurnNumber: 3,+ },+ ],+ [+ {+ id: 'turn-2-user',+ role: 'user',+ content: 'second',+ timestamp: 20,+ serverTurnNumber: 2,+ },+ {+ id: 'turn-3-user',+ role: 'user',+ content: 'third',+ timestamp: 30,+ serverTurnNumber: 3,+ },+ ]+ )++ expect(merged.map(message => message.id)).toEqual([+ 'turn-2-user',+ 'system-note',+ 'durable-error',+ 'turn-3-user',+ ])+ })++ it('replaces numbered active-task rows instead of suppressing their server slot', () => {+ const merged = mergeAuthoritativeServerMessages(+ [+ {+ id: 'turn-4-user-local',+ role: 'user',+ content: 'local',+ timestamp: 1,+ serverTurnNumber: 4,+ task_id: 'task-4',+ },+ ],+ [+ {+ id: 'turn-4-user',+ role: 'user',+ content: 'server',+ timestamp: 2,+ serverTurnNumber: 4,+ },+ ],+ { activeTaskIds: new Set(['task-4']) }+ )++ expect(merged).toEqual([+ expect.objectContaining({+ id: 'turn-4-user',+ content: 'server',+ task_id: 'task-4',+ }),+ ])+ })++ it('does not reuse later exact matches when backfilling older server turns', () => {+ const existing: ChatMessage[] = Array.from({ length: 4 }, (_, index) => index + 5).flatMap(+ n => [+ {+ id: `turn-${n}-user-local`,+ role: 'user' as const,+ content: `local q${n}`,+ timestamp: n * 10,+ serverTurnNumber: n,+ task_id: `task-${n}`,+ attachments: [+ {+ id: `upload-${n}`,+ type: 'uploaded_file' as const,+ label: `file-${n}.txt`,+ },+ ],+ },+ {+ id: `turn-${n}-assistant-local`,+ role: 'assistant' as const,+ content: `local a${n}`,+ timestamp: n * 10 + 1,+ serverTurnNumber: n,+ task_id: `task-${n}`,+ },+ ]+ )+ const incoming = turnsToChatMessages(+ Array.from({ length: 8 }, (_, index) => ({+ number: index + 1,+ user_input: `q${index + 1}`,+ response: `a${index + 1}`,+ started_at: new Date(index + 1).toISOString(),+ }))+ )++ const merged = mergeAuthoritativeServerMessages(existing, incoming)++ expect(merged.map(message => message.id)).toEqual(+ Array.from({ length: 8 }, (_, index) => index + 1).flatMap(n => [+ `turn-${n}-user`,+ `turn-${n}-assistant`,+ ])+ )+ expect(+ merged+ .filter(message => message.serverTurnNumber !== undefined && message.serverTurnNumber <= 4)+ .flatMap(message => [message.task_id, message.attachments])+ .filter(Boolean)+ ).toEqual([])+ expect(+ merged+ .filter(message => message.serverTurnNumber === 5)+ .map(message => ({+ id: message.id,+ taskId: message.task_id,+ attachmentId: message.attachments?.[0]?.id,+ }))+ ).toEqual([+ { id: 'turn-5-user', taskId: 'task-5', attachmentId: 'upload-5' },+ { id: 'turn-5-assistant', taskId: 'task-5', attachmentId: undefined },+ ])+ })++ it('does not copy turnless orphan metadata onto unrelated backfilled server turns', () => {+ const existing: ChatMessage[] = [+ {+ id: 'turnless-upload-orphan',+ role: 'user',+ content: 'old local upload',+ timestamp: 1,+ task_id: 'orphan-task',+ attachments: [+ {+ id: 'orphan-upload',+ type: 'uploaded_file',+ label: 'orphan.txt',+ },+ ],+ },+ ...Array.from({ length: 4 }, (_, index) => index + 5).flatMap(n => [+ {+ id: `turn-${n}-user-local`,+ role: 'user' as const,+ content: `local q${n}`,+ timestamp: n * 10,+ serverTurnNumber: n,+ task_id: `task-${n}`,+ attachments: [+ {+ id: `upload-${n}`,+ type: 'uploaded_file' as const,+ label: `file-${n}.txt`,+ },+ ],+ },+ {+ id: `turn-${n}-assistant-local`,+ role: 'assistant' as const,+ content: `local a${n}`,+ timestamp: n * 10 + 1,+ serverTurnNumber: n,+ task_id: `task-${n}`,+ },+ ]),+ ]+ const incoming = turnsToChatMessages(+ Array.from({ length: 8 }, (_, index) => ({+ number: index + 1,+ user_input: `q${index + 1}`,+ response: `a${index + 1}`,+ started_at: new Date(index + 1).toISOString(),+ }))+ )++ const merged = mergeAuthoritativeServerMessages(existing, incoming)++ expect(+ merged+ .filter(message => message.serverTurnNumber !== undefined && message.serverTurnNumber <= 4)+ .flatMap(message => [message.task_id, message.attachments])+ .filter(Boolean)+ ).toEqual([])+ expect(+ merged+ .filter(message => message.serverTurnNumber === 5 && message.role === 'user')+ .map(message => ({+ taskId: message.task_id,+ attachmentId: message.attachments?.[0]?.id,+ }))+ ).toEqual([{ taskId: 'task-5', attachmentId: 'upload-5' }])+ })++ it('preserves local-only failed sends that the server never accepted', () => {+ const failedPrompt: ChatMessage = {+ id: 'failed-post-user',+ role: 'user',+ content: 'this prompt never reached the server',+ timestamp: 3,+ preserveLocal: true,+ }++ const merged = mergeAuthoritativeServerMessages(+ [+ {+ id: 'turn-1-user',+ role: 'user',+ content: 'q1',+ timestamp: 1,+ serverTurnNumber: 1,+ },+ {+ id: 'turn-1-assistant',+ role: 'assistant',+ content: 'a1',+ timestamp: 2,+ serverTurnNumber: 1,+ },+ failedPrompt,+ ],+ turnsToChatMessages([+ {+ number: 1,+ user_input: 'q1',+ response: 'a1',+ started_at: new Date(1).toISOString(),+ },+ {+ number: 2,+ user_input: 'server-only q2',+ response: 'server-only a2',+ started_at: new Date(2).toISOString(),+ },+ ])+ )++ expect(merged).toContainEqual(failedPrompt)+ })++ it('does not delete numbered local slots that the server window did not supply', () => {+ const existing = turnsToChatMessages(+ [3, 4, 5].map(number => ({+ number,+ user_input: `q${number}`,+ response: `a${number}`,+ started_at: new Date(number).toISOString(),+ }))+ )+ const incoming = turnsToChatMessages(+ [3, 5].map(number => ({+ number,+ user_input: `server q${number}`,+ response: `server a${number}`,+ started_at: new Date(number + 10).toISOString(),+ }))+ )++ const merged = mergeAuthoritativeServerMessages(existing, incoming)++ expect(merged.map(message => message.id)).toEqual([+ 'turn-3-user',+ 'turn-3-assistant',+ 'turn-4-user',+ 'turn-4-assistant',+ 'turn-5-user',+ 'turn-5-assistant',+ ])+ expect(+ merged.filter(message => message.serverTurnNumber === 4).map(message => message.content)+ ).toEqual(['q4', 'a4'])+ })++ it('preserves a local assistant when the server supplies only the user slot', () => {+ const merged = mergeAuthoritativeServerMessages(+ [+ {+ id: 'turn-9-user-local',+ role: 'user',+ content: 'local q9',+ timestamp: 1,+ serverTurnNumber: 9,+ },+ {+ id: 'turn-9-assistant-local',+ role: 'assistant',+ content: 'local a9',+ timestamp: 2,+ serverTurnNumber: 9,+ },+ ],+ [+ {+ id: 'turn-9-user',+ role: 'user',+ content: 'server q9',+ timestamp: 3,+ serverTurnNumber: 9,+ },+ ]+ )++ expect(merged.map(message => message.id)).toEqual(['turn-9-user', 'turn-9-assistant-local'])+ expect(merged[1]?.content).toBe('local a9')+ })++ it('does not let an active-task claim leak stale metadata onto another server turn', () => {+ const merged = mergeAuthoritativeServerMessages(+ [+ {+ id: 'live-optimistic',+ role: 'user',+ content: 'live prompt',+ timestamp: 1,+ task_id: 'live',+ },+ {+ id: 'stale-echo-turn4',+ role: 'user',+ content: 'stale turn 4',+ timestamp: 2,+ task_id: 'task-4',+ attachments: [+ {+ id: 'photo-4',+ type: 'uploaded_file',+ label: 'photo-4.png',+ },+ ],+ },+ ],+ [+ {+ id: 'turn-4-user',+ role: 'user',+ content: 'server turn 4',+ timestamp: 4,+ serverTurnNumber: 4,+ },+ {+ id: 'turn-5-user',+ role: 'user',+ content: 'server turn 5',+ timestamp: 5,+ serverTurnNumber: 5,+ },+ ],+ { activeTaskIds: new Set(['live']) }+ )++ const turnFive = merged.find(message => message.id === 'turn-5-user')+ expect(merged.map(message => message.id)).toContain('live-optimistic')+ expect(turnFive?.task_id).toBeUndefined()+ expect(turnFive?.attachments).toBeUndefined()+ })++ it('keeps active-task reconciliation idempotent when a same-turn neighbor appears', () => {+ const existing: ChatMessage[] = [+ {+ id: 'turn-1-user',+ role: 'user',+ content: 'q1',+ timestamp: 1,+ serverTurnNumber: 1,+ },+ {+ id: 'turn-1-assistant',+ role: 'assistant',+ content: 'a1',+ timestamp: 2,+ serverTurnNumber: 1,+ },+ {+ id: 'optimistic-user',+ role: 'user',+ content: 'q3',+ timestamp: 3,+ task_id: 'live',+ },+ ]+ const incoming = turnsToChatMessages([+ {+ number: 3,+ user_input: 'q3',+ response: 'a3',+ started_at: new Date(3).toISOString(),+ },+ {+ number: 4,+ user_input: 'q4',+ response: 'a4',+ started_at: new Date(4).toISOString(),+ },+ ])++ const firstPass = mergeAuthoritativeServerMessages(existing, incoming, {+ activeTaskIds: new Set(['live']),+ })+ const secondPass = mergeAuthoritativeServerMessages(firstPass, incoming, {+ activeTaskIds: new Set(['live']),+ })++ expect(secondPass.map(message => message.id)).toEqual(firstPass.map(message => message.id))+ expect(secondPass.filter(message => message.id === 'turn-3-user')).toHaveLength(1)+ })++ it('keeps authoritative turns through a renderer/main double merge with active tasks', () => {+ const existing: ChatMessage[] = [+ {+ id: 'turn-2-user',+ role: 'user',+ content: 'q2',+ timestamp: 1,+ serverTurnNumber: 2,+ },+ {+ id: 'turn-2-assistant',+ role: 'assistant',+ content: 'a2',+ timestamp: 2,+ serverTurnNumber: 2,+ },+ {+ id: 'turn-4-user',+ role: 'user',+ content: 'q4',+ timestamp: 4,+ serverTurnNumber: 4,+ },+ {+ id: 'optimistic-user',+ role: 'user',+ content: 'live q5',+ timestamp: 5,+ task_id: 'live',+ },+ {+ id: 'optimistic-assistant',+ role: 'assistant',+ content: 'working',+ timestamp: 6,+ task_id: 'live',+ },+ ]+ const serverWindow = turnsToChatMessages(+ [3, 4, 5, 6].map(number => ({+ number,+ user_input: `q${number}`,+ response: `a${number}`,+ started_at: new Date(number).toISOString(),+ }))+ )++ const rendered = mergeAuthoritativeServerMessages(existing, serverWindow, {+ activeTaskIds: new Set(['live']),+ })+ const persisted = mergeAuthoritativeServerMessages(existing, rendered, {+ activeTaskIds: new Set(['live']),+ })++ expect(persisted.map(message => message.id)).toContain('turn-6-user')+ expect(persisted.map(message => message.id)).toContain('turn-6-assistant')+ })++ it('reinjects turnless incoming messages that are present only in the replacement window', () => {+ const merged = mergeAuthoritativeServerMessages(+ [+ {+ id: 'turn-1-user',+ role: 'user',+ content: 'q1',+ timestamp: 1,+ serverTurnNumber: 1,+ },+ ],+ [+ {+ id: 'turn-1-user',+ role: 'user',+ content: 'q1',+ timestamp: 1,+ serverTurnNumber: 1,+ },+ {+ id: 'turn-2-user',+ role: 'user',+ content: 'q2',+ timestamp: 2,+ serverTurnNumber: 2,+ },+ {+ id: 'local-only-note',+ role: 'assistant',+ content: 'local note',+ timestamp: 3,+ },+ ]+ )++ expect(merged.map(message => message.id)).toEqual([+ 'turn-1-user',+ 'turn-2-user',+ 'local-only-note',+ ])+ })++ it('places a server response after the active optimistic prompt for that turn', () => {+ const merged = mergeAuthoritativeServerMessages(+ [+ {+ id: 'turn-5-user-local',+ role: 'user',+ content: 'q5',+ timestamp: 1,+ serverTurnNumber: 5,+ },+ {+ id: 'turn-5-assistant-local',+ role: 'assistant',+ content: 'a5',+ timestamp: 2,+ serverTurnNumber: 5,+ },+ {+ id: 'optimistic-turn-6-user',+ role: 'user',+ content: 'q6',+ timestamp: 3,+ task_id: 'task-live',+ },+ ],+ [+ {+ id: 'turn-5-user',+ role: 'user',+ content: 'q5',+ timestamp: 4,+ serverTurnNumber: 5,+ },+ {+ id: 'turn-5-assistant',+ role: 'assistant',+ content: 'a5',+ timestamp: 5,+ serverTurnNumber: 5,+ },+ {+ id: 'turn-6-assistant',+ role: 'assistant',+ content: 'a6',+ timestamp: 6,+ serverTurnNumber: 6,+ },+ ],+ { activeTaskIds: new Set(['task-live']) }+ )++ expect(merged.map(message => message.id)).toEqual([+ 'turn-5-user',+ 'turn-5-assistant',+ 'optimistic-turn-6-user',+ 'turn-6-assistant',+ ])+ })+})diff --git a/desktop-app/src/__tests__/chatStore.test.ts b/desktop-app/src/__tests__/chatStore.test.tsindex 714ef0125..35f88b8a0 100644--- a/desktop-app/src/__tests__/chatStore.test.ts+++ b/desktop-app/src/__tests__/chatStore.test.ts@@ -1,8 +1,9 @@-import { afterEach, beforeEach, describe, expect, it } from 'vitest'+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'import { promises as fs } from 'node:fs'import { tmpdir } from 'node:os'-import { join } from 'node:path'+import { dirname, join } from 'node:path'import { ChatStore } from '../chatStore.js'+import type { ChatMessage } from '../types.js'let tempDir: stringlet store: ChatStore@@ -13,9 +14,79 @@ beforeEach(async () => {})afterEach(async () => {+ vi.restoreAllMocks()await fs.rm(tempDir, { recursive: true, force: true })})+function agentPath(...segments: string[]): string {+ return join(tempDir, 'agent-1', ...segments)+}++function chatCacheDir(chatId: string): string {+ return agentPath('chats', chatId)+}++function chatMetaPath(chatId: string): string {+ return join(chatCacheDir(chatId), 'meta.json')+}++function chatPagesDir(chatId: string): string {+ return join(chatCacheDir(chatId), 'pages')+}++function chatSnapshotDir(+ chatId: string,+ kind: 'next' | 'previous' | 'corrupt',+ token: string+): string {+ return agentPath(+ 'chats',+ '.snapshots',+ Buffer.from(chatId, 'utf8').toString('base64url'),+ `${kind}-${token}`+ )+}++function transientFileReadError(code = 'EMFILE'): NodeJS.ErrnoException {+ const err = new Error(code) as NodeJS.ErrnoException+ err.code = code+ return err+}++async function readJsonFile<T = Record<string, unknown>>(path: string): Promise<T> {+ return JSON.parse(await fs.readFile(path, 'utf-8')) as T+}++async function writePagedSnapshotDir(chatId: string, dir: string, messages: ChatMessage[]) {+ await fs.mkdir(join(dir, 'pages'), { recursive: true })+ await fs.writeFile(+ join(dir, 'pages', '000001.json'),+ JSON.stringify({+ version: 1,+ chatId,+ pageNumber: 1,+ messages,+ })+ )+ await fs.writeFile(+ join(dir, 'meta.json'),+ JSON.stringify({+ version: 1,+ chatId,+ pageSize: 100,+ messageCount: messages.length,+ localMessageCount: messages.length,+ pages: [+ {+ file: '000001.json',+ count: messages.length,+ serverSynced: false,+ },+ ],+ })+ )+}+// ── listChats ────────────────────────────────────────────────────────────────describe('listChats', () => {@@ -71,7 +142,7 @@ describe('renameChat', () => {// ── deleteChat ───────────────────────────────────────────────────────────────describe('deleteChat', () => {- it('removes from index and deletes message file', async () => {+ it('removes from index and deletes message cache', async () => {await store.createChat('agent-1', 'del-1')await store.saveMessages('agent-1', 'del-1', [{ id: 'm1', role: 'user', content: 'hello', timestamp: Date.now() },@@ -80,9 +151,8 @@ describe('deleteChat', () => {const chats = await store.listChats('agent-1')expect(chats).toHaveLength(0)- // message file should be gone- const filePath = join(tempDir, 'agent-1', 'del-1.json')- await expect(fs.access(filePath)).rejects.toThrow()+ await expect(fs.access(join(tempDir, 'agent-1', 'del-1.json'))).rejects.toThrow()+ await expect(fs.access(chatCacheDir('del-1'))).rejects.toThrow()})it('clears lastActiveChatId when deleting active chat', async () => {@@ -132,6 +202,495 @@ describe('messages', () => {expect(offset2[2]!.content).toBe('msg-7')})+ it('stores large chats in page files and reads windows across page boundaries', async () => {+ const pagedStore = new ChatStore(tempDir, {+ pageSize: 3,+ maxLocalSyncedMessages: Number.POSITIVE_INFINITY,+ })+ await pagedStore.createChat('agent-1', 'paged-1')+ const msgs = Array.from({ length: 10 }, (_, i) => ({+ id: `m${i}`,+ role: 'user' as const,+ content: `msg-${i}`,+ timestamp: i,+ }))++ await pagedStore.saveMessages('agent-1', 'paged-1', msgs)++ expect(await fs.readdir(chatPagesDir('paged-1'))).toEqual([+ '000001.json',+ '000002.json',+ '000003.json',+ '000004.json',+ ])+ const meta = await readJsonFile<{ messageCount: number; localMessageCount: number }>(+ chatMetaPath('paged-1')+ )+ expect(meta).toMatchObject({ messageCount: 10, localMessageCount: 10 })++ const window = await pagedStore.loadMessages('agent-1', 'paged-1', 4, 2)+ expect(window.map(message => message.content)).toEqual(['msg-4', 'msg-5', 'msg-6', 'msg-7'])+ })++ it('appends into the last page before creating another page', async () => {+ const pagedStore = new ChatStore(tempDir, {+ pageSize: 2,+ maxLocalSyncedMessages: Number.POSITIVE_INFINITY,+ })+ await pagedStore.createChat('agent-1', 'append-pages')+ await pagedStore.saveMessages('agent-1', 'append-pages', [+ { id: 'm0', role: 'user', content: 'msg-0', timestamp: 0 },+ { id: 'm1', role: 'user', content: 'msg-1', timestamp: 1 },+ { id: 'm2', role: 'user', content: 'msg-2', timestamp: 2 },+ ])++ await pagedStore.appendMessages('agent-1', 'append-pages', [+ { id: 'm3', role: 'user', content: 'msg-3', timestamp: 3 },+ { id: 'm4', role: 'user', content: 'msg-4', timestamp: 4 },+ ])++ expect(await fs.readdir(chatPagesDir('append-pages'))).toEqual([+ '000001.json',+ '000002.json',+ '000003.json',+ ])+ const secondPage = await readJsonFile<{ messages: ChatMessage[] }>(+ join(chatPagesDir('append-pages'), '000002.json')+ )+ expect(secondPage.messages.map(message => message.id)).toEqual(['m2', 'm3'])++ const messages = await pagedStore.loadMessages('agent-1', 'append-pages')+ expect(messages.map(message => message.id)).toEqual(['m0', 'm1', 'm2', 'm3', 'm4'])+ })++ it('serializes paged reads behind concurrent appends', async () => {+ const pagedStore = new ChatStore(tempDir, {+ pageSize: 2,+ maxLocalSyncedMessages: Number.POSITIVE_INFINITY,+ })+ await pagedStore.createChat('agent-1', 'atomic-read')+ await pagedStore.saveMessages('agent-1', 'atomic-read', [+ { id: 'm0', role: 'user', content: 'msg-0', timestamp: 0 },+ { id: 'm1', role: 'user', content: 'msg-1', timestamp: 1 },+ ])++ const originalWriteFile = fs.writeFile.bind(fs)+ let releaseWrite: (() => void) | undefined+ let delayedWrite = false+ const appendWriteStarted = new Promise<void>(resolve => {+ vi.spyOn(fs, 'writeFile').mockImplementation(async (...args) => {+ const filePath = String(args[0])+ if (!delayedWrite && filePath.includes('atomic-read') && filePath.endsWith('.tmp')) {+ delayedWrite = true+ resolve()+ await new Promise<void>(release => {+ releaseWrite = release+ })+ }+ return originalWriteFile(...(args as Parameters<typeof fs.writeFile>))+ })+ })++ const append = pagedStore.appendMessages('agent-1', 'atomic-read', [+ { id: 'm2', role: 'assistant', content: 'msg-2', timestamp: 2 },+ ])+ await appendWriteStarted++ const loadedDuringAppend = pagedStore.loadMessages('agent-1', 'atomic-read')+ await Promise.resolve()+ releaseWrite?.()++ const [messages] = await Promise.all([loadedDuringAppend, append.then(() => undefined)])+ expect(messages.map(message => message.id)).toEqual(['m0', 'm1', 'm2'])+ })++ it('does not block paged reads behind writes to another chat', async () => {+ const pagedStore = new ChatStore(tempDir, {+ pageSize: 2,+ maxLocalSyncedMessages: Number.POSITIVE_INFINITY,+ })+ await pagedStore.createChat('agent-1', 'busy-chat')+ await pagedStore.createChat('agent-1', 'readable-chat')+ await pagedStore.saveMessages('agent-1', 'busy-chat', [+ { id: 'busy-0', role: 'user', content: 'busy', timestamp: 0 },+ ])+ await pagedStore.saveMessages('agent-1', 'readable-chat', [+ { id: 'readable-0', role: 'user', content: 'readable', timestamp: 0 },+ ])++ const originalWriteFile = fs.writeFile.bind(fs)+ const originalReadFile = fs.readFile.bind(fs)+ let releaseWrite: (() => void) | undefined+ let delayedWrite = false+ let readableChatReadStarted = false+ const busyWriteStarted = new Promise<void>(resolve => {+ vi.spyOn(fs, 'writeFile').mockImplementation(async (...args) => {+ const filePath = String(args[0])+ if (!delayedWrite && filePath.includes('busy-chat') && filePath.endsWith('.tmp')) {+ delayedWrite = true+ resolve()+ await new Promise<void>(release => {+ releaseWrite = release+ })+ }+ return originalWriteFile(...(args as Parameters<typeof fs.writeFile>))+ })+ })+ vi.spyOn(fs, 'readFile').mockImplementation(async (...args) => {+ if (String(args[0]).includes('readable-chat')) readableChatReadStarted = true+ return originalReadFile(...(args as Parameters<typeof fs.readFile>))+ })++ const append = pagedStore.appendMessages('agent-1', 'busy-chat', [+ { id: 'busy-1', role: 'assistant', content: 'still busy', timestamp: 1 },+ ])+ await busyWriteStarted++ const readableMessages = pagedStore.loadMessages('agent-1', 'readable-chat')+ try {+ await vi.waitFor(() => expect(readableChatReadStarted).toBe(true))+ } finally {+ releaseWrite?.()+ }++ const [messages] = await Promise.all([readableMessages, append.then(() => undefined)])+ 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(+ join('.snapshots', Buffer.from('rewrite-failure').toString('base64url'))+ ) &&+ filePath.includes('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('aborts append instead of resetting the transcript on transient meta read failure', async () => {+ const pagedStore = new ChatStore(tempDir, {+ pageSize: 5,+ maxLocalSyncedMessages: Number.POSITIVE_INFINITY,+ })+ await pagedStore.createChat('agent-1', 'meta-read-failure')+ await pagedStore.saveMessages('agent-1', 'meta-read-failure', [+ { id: 'old-0', role: 'user', content: 'old-0', timestamp: 0 },+ { id: 'old-1', role: 'assistant', content: 'old-1', timestamp: 1 },+ ])++ const originalReadFile = fs.readFile.bind(fs)+ let injected = false+ vi.spyOn(fs, 'readFile').mockImplementation(async (...args) => {+ const filePath = String(args[0])+ if (!injected && filePath.endsWith(join('meta-read-failure', 'meta.json'))) {+ injected = true+ throw transientFileReadError()+ }+ return originalReadFile(...(args as Parameters<typeof fs.readFile>))+ })++ await expect(+ pagedStore.appendMessages('agent-1', 'meta-read-failure', [+ { id: 'new-0', role: 'user', content: 'new-0', timestamp: 2 },+ ])+ ).rejects.toThrow()++ vi.restoreAllMocks()+ const reloaded = await pagedStore.loadMessages('agent-1', 'meta-read-failure')+ expect(reloaded.map(message => message.id)).toEqual(['old-0', 'old-1'])+ })++ it('aborts append instead of truncating the last page on transient page read failure', async () => {+ const pagedStore = new ChatStore(tempDir, {+ pageSize: 10,+ maxLocalSyncedMessages: Number.POSITIVE_INFINITY,+ })+ await pagedStore.createChat('agent-1', 'page-read-failure')+ const originalMessages = Array.from({ length: 5 }, (_, i) => ({+ id: `old-${i}`,+ role: 'user' as const,+ content: `old-${i}`,+ timestamp: i,+ }))+ await pagedStore.saveMessages('agent-1', 'page-read-failure', originalMessages)++ const originalReadFile = fs.readFile.bind(fs)+ let injected = false+ vi.spyOn(fs, 'readFile').mockImplementation(async (...args) => {+ const filePath = String(args[0])+ if (!injected && filePath.includes('page-read-failure') && filePath.endsWith('000001.json')) {+ injected = true+ throw transientFileReadError()+ }+ return originalReadFile(...(args as Parameters<typeof fs.readFile>))+ })++ await expect(+ pagedStore.appendMessages('agent-1', 'page-read-failure', [+ { id: 'new-0', role: 'assistant', content: 'new-0', timestamp: 6 },+ ])+ ).rejects.toThrow()++ vi.restoreAllMocks()+ const reloaded = await pagedStore.loadMessages('agent-1', 'page-read-failure')+ expect(reloaded.map(message => message.id)).toEqual(originalMessages.map(message => message.id))+ })++ it('recovers the previous paged snapshot after an interrupted directory switch', async () => {+ const pagedStore = new ChatStore(tempDir, {+ pageSize: 2,+ 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 },+ ])++ const previousSnapshot = chatSnapshotDir('switch-recovery', 'previous', 'test')+ await fs.mkdir(dirname(previousSnapshot), { recursive: true })+ await fs.rename(chatCacheDir('switch-recovery'), previousSnapshot)++ 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('completes recovery from a fully written next snapshot after a mid-swap crash', async () => {+ const pagedStore = new ChatStore(tempDir, {+ pageSize: 2,+ maxLocalSyncedMessages: Number.POSITIVE_INFINITY,+ })+ await pagedStore.createChat('agent-1', 'next-recovery')+ await pagedStore.saveMessages('agent-1', 'next-recovery', [+ { id: 'old-0', role: 'user', content: 'old-0', timestamp: 0 },+ ])++ const nextDir = chatSnapshotDir('next-recovery', 'next', 'test')+ await writePagedSnapshotDir('next-recovery', nextDir, [+ { id: 'new-0', role: 'user', content: 'new-0', timestamp: 1 },+ { id: 'new-1', role: 'assistant', content: 'new-1', timestamp: 2 },+ ])+ await fs.rename(+ chatCacheDir('next-recovery'),+ chatSnapshotDir('next-recovery', 'previous', 'test')+ )++ const reloaded = await pagedStore.loadMessages('agent-1', 'next-recovery')+ expect(reloaded.map(message => message.id)).toEqual(['new-0', 'new-1'])+ await expect(fs.access(chatSnapshotDir('next-recovery', 'next', 'test'))).rejects.toThrow()+ await expect(fs.access(chatSnapshotDir('next-recovery', 'previous', 'test'))).rejects.toThrow()+ })++ it('uses the newest valid snapshot group instead of preferring stale next snapshots', async () => {+ const pagedStore = new ChatStore(tempDir, {+ pageSize: 2,+ maxLocalSyncedMessages: Number.POSITIVE_INFINITY,+ })+ await pagedStore.createChat('agent-1', 'snapshot-order')+ await pagedStore.saveMessages('agent-1', 'snapshot-order', [+ { id: 'active-0', role: 'user', content: 'active-0', timestamp: 0 },+ ])++ const staleNext = chatSnapshotDir('snapshot-order', 'next', 'old')+ const freshPrevious = chatSnapshotDir('snapshot-order', 'previous', 'new')+ await writePagedSnapshotDir('snapshot-order', staleNext, [+ { id: 'stale-0', role: 'user', content: 'stale-0', timestamp: 1 },+ ])+ await writePagedSnapshotDir('snapshot-order', freshPrevious, [+ { id: 'fresh-0', role: 'assistant', content: 'fresh-0', timestamp: 2 },+ ])+ const oldTime = new Date('2026-01-01T00:00:00Z')+ const freshTime = new Date('2026-01-02T00:00:00Z')+ await fs.utimes(staleNext, oldTime, oldTime)+ await fs.utimes(freshPrevious, freshTime, freshTime)+ await fs.writeFile(chatMetaPath('snapshot-order'), 'not-json')++ const reloaded = await pagedStore.loadMessages('agent-1', 'snapshot-order')+ expect(reloaded.map(message => message.id)).toEqual(['fresh-0'])+ })++ it('does not promote an incomplete snapshot whose page files are missing', async () => {+ const pagedStore = new ChatStore(tempDir, {+ pageSize: 2,+ maxLocalSyncedMessages: Number.POSITIVE_INFINITY,+ })+ await pagedStore.createChat('agent-1', 'incomplete-snapshot')+ const incomplete = chatSnapshotDir('incomplete-snapshot', 'previous', 'test')+ await writePagedSnapshotDir('incomplete-snapshot', incomplete, [+ { id: 'backup-0', role: 'user', content: 'backup-0', timestamp: 0 },+ ])+ await fs.rm(join(incomplete, 'pages', '000001.json'), { force: true })++ const reloaded = await pagedStore.loadMessages('agent-1', 'incomplete-snapshot')+ expect(reloaded).toEqual([])+ await expect(fs.access(chatMetaPath('incomplete-snapshot'))).rejects.toThrow()+ })++ it('cleans stale snapshot siblings when the active paged snapshot is healthy', async () => {+ const pagedStore = new ChatStore(tempDir, {+ pageSize: 2,+ maxLocalSyncedMessages: Number.POSITIVE_INFINITY,+ })+ await pagedStore.createChat('agent-1', 'stale-snapshots')+ await pagedStore.saveMessages('agent-1', 'stale-snapshots', [+ { id: 'm0', role: 'user', content: 'msg-0', timestamp: 0 },+ ])++ await fs.mkdir(chatSnapshotDir('stale-snapshots', 'next', 'stale'), { recursive: true })+ await fs.mkdir(chatSnapshotDir('stale-snapshots', 'previous', 'stale'), { recursive: true })++ const restartedStore = new ChatStore(tempDir, {+ pageSize: 2,+ maxLocalSyncedMessages: Number.POSITIVE_INFINITY,+ })+ const reloaded = await restartedStore.loadMessages('agent-1', 'stale-snapshots')+ expect(reloaded.map(message => message.id)).toEqual(['m0'])+ await expect(fs.access(chatSnapshotDir('stale-snapshots', 'next', 'stale'))).rejects.toThrow()+ await expect(+ fs.access(chatSnapshotDir('stale-snapshots', 'previous', 'stale'))+ ).rejects.toThrow()+ })++ it('deletes snapshot siblings so removed chats cannot be recovered later', async () => {+ const pagedStore = new ChatStore(tempDir, {+ pageSize: 2,+ maxLocalSyncedMessages: Number.POSITIVE_INFINITY,+ })+ await pagedStore.createChat('agent-1', 'delete-siblings')+ await pagedStore.saveMessages('agent-1', 'delete-siblings', [+ { id: 'm0', role: 'user', content: 'msg-0', timestamp: 0 },+ ])+ await writePagedSnapshotDir(+ 'delete-siblings',+ chatSnapshotDir('delete-siblings', 'previous', 'test'),+ [{ id: 'backup-0', role: 'user', content: 'backup-0', timestamp: 1 }]+ )++ await pagedStore.deleteChat('agent-1', 'delete-siblings')++ expect(await pagedStore.loadMessages('agent-1', 'delete-siblings')).toEqual([])+ await expect(+ fs.access(chatSnapshotDir('delete-siblings', 'previous', 'test'))+ ).rejects.toThrow()+ })++ it('prunes only old pages whose messages are known to exist on the server', async () => {+ const prunedStore = new ChatStore(tempDir, {+ pageSize: 2,+ maxLocalSyncedMessages: 4,+ })+ await prunedStore.createChat('agent-1', 'pruned')+ const msgs = Array.from({ length: 6 }, (_, i) => ({+ id: `m${i}`,+ role: 'user' as const,+ content: `msg-${i}`,+ timestamp: i,+ serverTurnNumber: i + 1,+ }))++ await prunedStore.saveMessages('agent-1', 'pruned', msgs)++ expect(await fs.readdir(chatPagesDir('pruned'))).toEqual(['000002.json', '000003.json'])+ await expect(fs.access(join(chatPagesDir('pruned'), '000001.json'))).rejects.toThrow()+ const meta = await readJsonFile<{+ messageCount: number+ localMessageCount: number+ prunedBeforeCount: number+ }>(chatMetaPath('pruned'))+ expect(meta).toMatchObject({+ messageCount: 6,+ localMessageCount: 4,+ prunedBeforeCount: 2,+ })++ const chat = (await prunedStore.listChats('agent-1')).find(item => item.id === 'pruned')+ expect(chat?.messageCount).toBe(6)+ const localMessages = await prunedStore.loadMessages('agent-1', 'pruned')+ expect(localMessages.map(message => message.id)).toEqual(['m2', 'm3', 'm4', 'm5'])+ })++ it('keeps a contiguous transcript when an older local-only page blocks pruning', async () => {+ const prunedStore = new ChatStore(tempDir, {+ pageSize: 2,+ maxLocalSyncedMessages: 4,+ })+ await prunedStore.createChat('agent-1', 'local-only')+ const msgs = Array.from({ length: 6 }, (_, i) => ({+ id: `m${i}`,+ role: 'user' as const,+ content: `msg-${i}`,+ timestamp: i,+ ...(i >= 2 ? { serverTurnNumber: i + 1 } : {}),+ }))++ await prunedStore.saveMessages('agent-1', 'local-only', msgs)++ expect(await fs.readdir(chatPagesDir('local-only'))).toEqual([+ '000001.json',+ '000002.json',+ '000003.json',+ ])+ const meta = await readJsonFile<{ localMessageCount: number; prunedBeforeCount?: number }>(+ chatMetaPath('local-only')+ )+ expect(meta.localMessageCount).toBe(6)+ expect(meta.prunedBeforeCount).toBeUndefined()+ expect(+ (await prunedStore.loadMessages('agent-1', 'local-only')).map(message => message.id)+ ).toEqual(msgs.map(message => message.id))+ })++ it('recognizes legacy turn-N-role ids as server-synced for safe prefix pruning', async () => {+ const prunedStore = new ChatStore(tempDir, {+ pageSize: 2,+ maxLocalSyncedMessages: 2,+ })+ await prunedStore.createChat('agent-1', 'legacy-turn-ids')+ const msgs = [+ { id: 'turn-1-user', role: 'user' as const, content: 'q1', timestamp: 1 },+ { id: 'turn-1-assistant', role: 'assistant' as const, content: 'a1', timestamp: 2 },+ { id: 'turn-2-user', role: 'user' as const, content: 'q2', timestamp: 3 },+ { id: 'turn-2-assistant', role: 'assistant' as const, content: 'a2', timestamp: 4 },+ ]++ await prunedStore.saveMessages('agent-1', 'legacy-turn-ids', msgs)++ expect(await fs.readdir(chatPagesDir('legacy-turn-ids'))).toEqual(['000002.json'])+ expect(+ (await prunedStore.loadMessages('agent-1', 'legacy-turn-ids')).map(message => message.id)+ ).toEqual(['turn-2-user', 'turn-2-assistant'])+ })+it('updates messageCount in index after save', async () => {await store.createChat('agent-1', 'mc-1')await store.saveMessages('agent-1', 'mc-1', [@@ -143,14 +702,299 @@ describe('messages', () => {expect(chat!.messageCount).toBe(2)})- it('persists task_id and writes the v2 chat file (D.3)', async () => {+ it('persists activity aggregates in the chat index', async () => {+ await store.createChat('agent-1', 'activity-1')+ await store.saveMessages('agent-1', 'activity-1', [+ { id: 'm1', role: 'user', content: 'a', timestamp: 1 },+ {+ id: 'm2',+ role: 'assistant',+ content: 'failed',+ timestamp: 2,+ isError: true,+ toolSteps: [+ { toolName: 'search', displayName: 'Search', state: 'completed' },+ { toolName: 'write', displayName: 'Write', state: 'error' },+ ],+ },+ ])++ const chat = (await store.listChats('agent-1')).find(item => item.id === 'activity-1')+ expect(chat).toMatchObject({+ messageCount: 2,+ errorCount: 1,+ toolCallCount: 2,+ })+ })++ it('preserves aggregate counters when replaceMessages writes a bounded server window', async () => {+ await store.createChat('agent-1', 'bounded-replace')+ await store.saveMessages('agent-1', 'bounded-replace', [+ { id: 'm1', role: 'user', content: 'a', timestamp: 1 },+ {+ id: 'm2',+ role: 'assistant',+ content: 'failed',+ timestamp: 2,+ isError: true,+ toolSteps: [+ { toolName: 'search', displayName: 'Search', state: 'completed' },+ { toolName: 'write', displayName: 'Write', state: 'error' },+ ],+ },+ { id: 'm3', role: 'user', content: 'b', timestamp: 3 },+ ])++ await store.replaceMessages('agent-1', 'bounded-replace', [+ { id: 'm3', role: 'user', content: 'b', timestamp: 3 },+ ])++ const chat = (await store.listChats('agent-1')).find(item => item.id === 'bounded-replace')+ expect(chat).toMatchObject({+ messageCount: 3,+ errorCount: 1,+ toolCallCount: 2,+ })+ const meta = await readJsonFile<{ messageCount: number; localMessageCount: number }>(+ chatMetaPath('bounded-replace')+ )+ expect(meta).toMatchObject({ messageCount: 3, localMessageCount: 3 })+ expect(+ (await store.loadMessages('agent-1', 'bounded-replace')).map(message => message.id)+ ).toEqual(['m1', 'm2', 'm3'])+ })++ it('preserves local history around a bounded reconciliation fallback', async () => {+ await store.createChat('agent-1', 'bounded-window')+ await store.saveMessages('agent-1', 'bounded-window', [+ {+ id: 'local-note',+ role: 'assistant',+ content: 'local-only message outside the server window',+ timestamp: 0,+ },+ {+ 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',+ 'bounded-window',+ [+ {+ id: 'turn-999-user',+ role: 'user',+ content: 'newest',+ timestamp: 999,+ serverTurnNumber: 999,+ },+ ],+ { replaceLocalWindow: true }+ )++ expect(+ (await store.loadMessages('agent-1', 'bounded-window')).map(message => message.id)+ ).toEqual(['local-note', 'turn-1-user', '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', [+ {+ id: 'turn-1-user',+ role: 'user',+ content: 'old',+ timestamp: 1,+ serverTurnNumber: 1,+ },+ {+ id: 'local-only',+ role: 'assistant',+ content: 'not on the server',+ timestamp: 2,+ task_id: 'local-task',+ },+ {+ id: 'turn-2-user',+ role: 'user',+ content: 'new',+ timestamp: 3,+ serverTurnNumber: 2,+ },+ ])++ await store.replaceMessages('agent-1', 'reconcile-upsert', [+ {+ id: 'turn-2-user',+ role: 'user',+ content: 'new',+ timestamp: 3,+ serverTurnNumber: 2,+ },+ {+ id: 'turn-2-assistant',+ role: 'assistant',+ content: 'reply',+ timestamp: 4,+ serverTurnNumber: 2,+ },+ ])++ expect(+ (await store.loadMessages('agent-1', 'reconcile-upsert')).map(message => message.id)+ ).toEqual(['turn-1-user', 'turn-2-user', 'turn-2-assistant'])+ })++ it('repairs a missing page from surviving pages and the compatibility snapshot', async () => {+ const pagedStore = new ChatStore(tempDir, {+ pageSize: 2,+ maxLocalSyncedMessages: Number.POSITIVE_INFINITY,+ })+ await pagedStore.createChat('agent-1', 'missing-page')+ await pagedStore.saveMessages(+ 'agent-1',+ 'missing-page',+ Array.from({ length: 6 }, (_, index) => ({+ id: `m${index}`,+ role: 'user' as const,+ content: `message-${index}`,+ timestamp: index,+ serverTurnNumber: index + 1,+ }))+ )+ await fs.rm(join(chatPagesDir('missing-page'), '000002.json'))+ const staleIndex = await readJsonFile<{+ chats: Array<{ id: string; messageCount: number }>+ }>(agentPath('index.json'))+ staleIndex.chats.find(chat => chat.id === 'missing-page')!.messageCount = 1+ await fs.writeFile(agentPath('index.json'), JSON.stringify(staleIndex))++ const restartedStore = new ChatStore(tempDir, {+ pageSize: 2,+ maxLocalSyncedMessages: Number.POSITIVE_INFINITY,+ })+ const recovered = await restartedStore.loadMessages('agent-1', 'missing-page')++ expect(recovered.map(message => message.id)).toEqual(['m0', 'm1', 'm2', 'm3', 'm4', 'm5'])+ const repairedMeta = await readJsonFile<{ localMessageCount: number }>(+ chatMetaPath('missing-page')+ )+ expect(repairedMeta.localMessageCount).toBe(6)+ expect(+ (await restartedStore.listChats('agent-1')).find(chat => chat.id === 'missing-page')+ ?.messageCount+ ).toBe(6)+ })++ it('adopts a fully written orphan page left by an interrupted append', async () => {+ const pagedStore = new ChatStore(tempDir, {+ pageSize: 2,+ maxLocalSyncedMessages: Number.POSITIVE_INFINITY,+ })+ await pagedStore.createChat('agent-1', 'orphan-append')+ await pagedStore.saveMessages('agent-1', 'orphan-append', [+ { id: 'm0', role: 'user', content: 'zero', timestamp: 0 },+ { id: 'm1', role: 'assistant', content: 'one', timestamp: 1 },+ ])+ await fs.writeFile(+ join(chatPagesDir('orphan-append'), '000002.json'),+ JSON.stringify({+ version: 1,+ chatId: 'orphan-append',+ pageNumber: 2,+ messages: [{ id: 'm2', role: 'user', content: 'durable local', timestamp: 2 }],+ })+ )++ const restartedStore = new ChatStore(tempDir, {+ pageSize: 2,+ maxLocalSyncedMessages: Number.POSITIVE_INFINITY,+ })+ const recovered = await restartedStore.loadMessages('agent-1', 'orphan-append')++ expect(recovered.map(message => message.id)).toEqual(['m0', 'm1', 'm2'])+ const repairedMeta = await readJsonFile<{ localMessageCount: number; pages: unknown[] }>(+ chatMetaPath('orphan-append')+ )+ expect(repairedMeta).toMatchObject({ localMessageCount: 3 })+ expect(repairedMeta.pages).toHaveLength(2)+ expect(+ (await restartedStore.listChats('agent-1')).find(chat => chat.id === 'orphan-append')+ ?.messageCount+ ).toBe(3)+ })++ it('persists task_id and writes the paged chat cache', async () => {await store.createChat('agent-1', 'v2-1')await store.saveMessages('agent-1', 'v2-1', [{ id: 'm1', role: 'user', content: 'hi', timestamp: 1, task_id: 'task-abc' },])- const raw = await fs.readFile(join(tempDir, 'agent-1', 'v2-1.json'), 'utf-8')- const parsed = JSON.parse(raw)- expect(parsed.version).toBe(2)+ const meta = await readJsonFile<{ version: number; pages: Array<{ file: string }> }>(+ chatMetaPath('v2-1')+ )+ expect(meta.version).toBe(1)+ expect(meta.pages.map(page => page.file)).toEqual(['000001.json'])+ const page = await readJsonFile<{ messages: ChatMessage[] }>(+ join(chatPagesDir('v2-1'), '000001.json')+ )+ expect(page.messages[0]!.task_id).toBe('task-abc')+ const compatibility = await readJsonFile<{ version: number; messages: ChatMessage[] }>(+ join(tempDir, 'agent-1', 'v2-1.json')+ )+ expect(compatibility.version).toBe(2)+ expect(compatibility.messages[0]!.task_id).toBe('task-abc')+const messages = await store.loadMessages('agent-1', 'v2-1')expect(messages[0]!.task_id).toBe('task-abc')})@@ -169,6 +1013,244 @@ describe('messages', () => {const messages = await store.loadMessages('agent-1', 'legacy')expect(messages).toHaveLength(1)expect(messages[0]!.task_id).toBeUndefined()+ await expect(fs.access(join(agentDir, 'legacy.json'))).resolves.toBeUndefined()+ await expect(fs.access(chatMetaPath('legacy'))).resolves.toBeUndefined()+ })++ it('backfills stale index counters while migrating a legacy chat file', async () => {+ const agentDir = join(tempDir, 'agent-1')+ await fs.mkdir(agentDir, { recursive: true })+ await fs.writeFile(+ agentPath('index.json'),+ JSON.stringify({+ version: 2,+ lastActiveChatId: null,+ onboardingDismissed: false,+ chats: [+ {+ id: 'legacy-counters',+ title: 'Legacy counters',+ createdAt: '2026-01-01T00:00:00.000Z',+ updatedAt: '2026-01-01T00:00:00.000Z',+ messageCount: 0,+ errorCount: 0,+ toolCallCount: 0,+ },+ ],+ })+ )+ await fs.writeFile(+ join(agentDir, 'legacy-counters.json'),+ JSON.stringify({+ version: 1,+ chatId: 'legacy-counters',+ messages: [+ { id: 'm1', role: 'user', content: 'old', timestamp: 1 },+ {+ id: 'm2',+ role: 'assistant',+ content: 'failed',+ timestamp: 2,+ isError: true,+ toolSteps: [{ toolName: 'read', displayName: 'Read', state: 'completed' }],+ },+ ],+ })+ )++ const messages = await store.loadMessages('agent-1', 'legacy-counters')++ expect(messages).toHaveLength(2)+ const chat = (await store.listChats('agent-1')).find(item => item.id === 'legacy-counters')+ expect(chat).toMatchObject({+ messageCount: 2,+ errorCount: 1,+ toolCallCount: 1,+ })+ const migratedIndex = await readJsonFile<{ version: number }>(agentPath('index.json'))+ expect(migratedIndex.version).toBe(2)+ })++ it('keeps the downgrade snapshot bounded and current after appends', async () => {+ await store.createChat('agent-1', 'downgrade-window')+ const messages = Array.from({ length: 105 }, (_, index) => ({+ id: `m${index}`,+ role: 'user' as const,+ content: `message-${index}`,+ timestamp: index,+ }))++ await store.saveMessages('agent-1', 'downgrade-window', messages)++ const initial = await readJsonFile<{ version: number; messages: ChatMessage[] }>(+ agentPath('downgrade-window.json')+ )+ expect(initial.version).toBe(2)+ expect(initial.messages).toHaveLength(100)+ expect(initial.messages[0]!.id).toBe('m5')+ expect(initial.messages.at(-1)!.id).toBe('m104')++ await store.appendMessages('agent-1', 'downgrade-window', [+ { id: 'm105', role: 'assistant', content: 'message-105', timestamp: 105 },+ ])++ const appended = await readJsonFile<{ messages: ChatMessage[] }>(+ agentPath('downgrade-window.json')+ )+ expect(appended.messages).toHaveLength(100)+ expect(appended.messages[0]!.id).toBe('m6')+ 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 }+ await store.saveMessages('agent-1', 'downgraded-write', [original])++ const downgradedMessage = {+ id: 'm2',+ role: 'user' as const,+ content: 'written while downgraded',+ timestamp: 2,+ }+ await fs.writeFile(+ agentPath('downgraded-write.json'),+ JSON.stringify({+ version: 2,+ chatId: 'downgraded-write',+ messages: [original, downgradedMessage],+ })+ )++ const restartedStore = new ChatStore(tempDir)+ const recovered = await restartedStore.loadMessages('agent-1', 'downgraded-write')++ expect(recovered.map(message => message.id)).toEqual(['m1', 'm2'])+ const compatibility = await readJsonFile<{ messages: ChatMessage[] }>(+ agentPath('downgraded-write.json')+ )+ expect(compatibility.messages.map(message => message.id)).toEqual(['m1', 'm2'])+ })++ it('repairs a corrupt downgrade snapshot from the valid paged history', async () => {+ await store.createChat('agent-1', 'corrupt-downgrade-snapshot')+ await store.saveMessages('agent-1', 'corrupt-downgrade-snapshot', [+ { id: 'm1', role: 'user', content: 'still durable', timestamp: 1 },+ ])+ await fs.writeFile(agentPath('corrupt-downgrade-snapshot.json'), 'not json{')++ const restartedStore = new ChatStore(tempDir)+ const recovered = await restartedStore.loadMessages('agent-1', 'corrupt-downgrade-snapshot')++ expect(recovered.map(message => message.id)).toEqual(['m1'])+ const compatibility = await readJsonFile<{ messages: ChatMessage[] }>(+ agentPath('corrupt-downgrade-snapshot.json')+ )+ expect(compatibility.messages.map(message => message.id)).toEqual(['m1'])+ })++ it('does not retry an unreadable auxiliary downgrade snapshot on every hot read', async () => {+ await store.createChat('agent-1', 'unreadable-downgrade-snapshot')+ await store.saveMessages('agent-1', 'unreadable-downgrade-snapshot', [+ { id: 'm1', role: 'user', content: 'still durable', timestamp: 1 },+ ])+ const restartedStore = new ChatStore(tempDir)+ const originalReadFile = fs.readFile.bind(fs)+ let compatibilityReadAttempts = 0+ vi.spyOn(fs, 'readFile').mockImplementation(async (...args) => {+ if (String(args[0]) === agentPath('unreadable-downgrade-snapshot.json')) {+ compatibilityReadAttempts += 1+ const error = new Error('permission denied') as NodeJS.ErrnoException+ error.code = 'EACCES'+ throw error+ }+ return originalReadFile(...(args as Parameters<typeof fs.readFile>))+ })++ await expect(+ restartedStore.loadMessages('agent-1', 'unreadable-downgrade-snapshot')+ ).resolves.toHaveLength(1)+ await expect(+ restartedStore.loadMessages('agent-1', 'unreadable-downgrade-snapshot')+ ).resolves.toHaveLength(1)++ expect(compatibilityReadAttempts).toBe(1)+ })++ it('does not hide a failed legacy migration as an empty chat', async () => {+ const agentDir = join(tempDir, 'agent-1')+ await fs.mkdir(agentDir, { recursive: true })+ await fs.writeFile(+ join(agentDir, 'migration-failure.json'),+ JSON.stringify({+ version: 1,+ chatId: 'migration-failure',+ messages: [{ id: 'm1', role: 'user', content: 'old', timestamp: 1 }],+ })+ )++ const originalWriteFile = fs.writeFile.bind(fs)+ let injected = false+ vi.spyOn(fs, 'writeFile').mockImplementation(async (...args) => {+ const filePath = String(args[0])+ if (+ !injected &&+ filePath.includes(+ join('.snapshots', Buffer.from('migration-failure').toString('base64url'))+ ) &&+ filePath.includes('next-')+ ) {+ injected = true+ throw transientFileReadError('ENOSPC')+ }+ return originalWriteFile(...(args as Parameters<typeof fs.writeFile>))+ })++ await expect(store.loadMessages('agent-1', 'migration-failure')).rejects.toThrow()++ vi.restoreAllMocks()+ await expect(fs.access(join(agentDir, 'migration-failure.json'))).resolves.toBeUndefined()+ const messages = await store.loadMessages('agent-1', 'migration-failure')+ expect(messages.map(message => message.id)).toEqual(['m1'])})})@@ -211,7 +1293,7 @@ describe('corrupt/missing files', () => {await fs.mkdir(agentDir, { recursive: true })await fs.writeFile(join(agentDir, 'index.json'), 'NOT VALID JSON{{{')const index = await store.getIndex('agent-1')- expect(index.version).toBe(2) // empty index is created at the current schema (D.4)+ expect(index.version).toBe(2) // v2 remains readable by pre-paging desktop buildsexpect(index.chats).toEqual([])})@@ -219,6 +1301,84 @@ describe('corrupt/missing files', () => {const messages = await store.loadMessages('agent-1', 'nonexistent')expect(messages).toEqual([])})++ it('quarantines a corrupt legacy chat and allows it to become writable again', async () => {+ const chatId = 'corrupt-legacy'+ await store.createChat('agent-1', chatId)+ await fs.writeFile(agentPath(`${chatId}.json`), '{"version":2,"messages":[')++ await expect(store.loadMessages('agent-1', chatId)).resolves.toEqual([])+ const encodedChatId = Buffer.from(chatId, 'utf8').toString('base64url')+ const quarantined = await fs.readdir(agentPath('.corrupt', encodedChatId))+ expect(quarantined).toHaveLength(1)+ await expect(fs.stat(agentPath(`${chatId}.json`))).rejects.toMatchObject({ code: 'ENOENT' })++ const replacement = {+ id: 'turn-1-user',+ role: 'user' as const,+ content: 'rehydrated',+ timestamp: 1,+ }+ 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'+ const otherChatId = `${chatId}-other`+ await store.createChat('agent-1', chatId)+ const corruptDir = agentPath('.corrupt')+ const encodedChatId = Buffer.from(chatId, 'utf8').toString('base64url')+ const otherEncodedChatId = Buffer.from(otherChatId, 'utf8').toString('base64url')+ const legacyUuid = '00000000-0000-4000-8000-000000000000'+ await fs.mkdir(join(corruptDir, encodedChatId), { recursive: true })+ await fs.writeFile(join(corruptDir, encodedChatId, 'nested.json'), '{}')+ await fs.writeFile(join(corruptDir, `${encodedChatId}-${legacyUuid}.json`), '{}')+ await fs.writeFile(join(corruptDir, `${otherEncodedChatId}-${legacyUuid}.json`), '{}')++ await store.deleteChat('agent-1', chatId)++ await expect(fs.access(join(corruptDir, encodedChatId))).rejects.toMatchObject({+ code: 'ENOENT',+ })+ await expect(+ fs.access(join(corruptDir, `${encodedChatId}-${legacyUuid}.json`))+ ).rejects.toMatchObject({+ code: 'ENOENT',+ })+ await expect(+ fs.access(join(corruptDir, `${otherEncodedChatId}-${legacyUuid}.json`))+ ).resolves.toBeUndefined()+ })})// ── unreadTerminal flag (D.5) ────────────────────────────────────────────────@@ -286,6 +1446,11 @@ describe('path-segment validation', () => {/unsafe path segment/)await expect(store.saveMessages('agent-1', 'a/b', [])).rejects.toThrow(/unsafe path segment/)+ await expect(store.saveMessages('agent-1', 'other.next-shadow', [])).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 keydiff --git a/desktop-app/src/__tests__/chatStoreBinding.test.ts b/desktop-app/src/__tests__/chatStoreBinding.test.tsindex ba247ad4e..b46251868 100644--- a/desktop-app/src/__tests__/chatStoreBinding.test.ts+++ b/desktop-app/src/__tests__/chatStoreBinding.test.ts@@ -1,4 +1,4 @@-import { afterEach, beforeEach, describe, expect, it } from 'vitest'+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'import { promises as fs } from 'node:fs'import os from 'node:os'import path from 'node:path'@@ -38,6 +38,66 @@ describe('chatStoreBinding', () => {expect(() => requireChatStore()).toThrow(/Not authenticated/)})+ it('does not publish a stale store when logout interrupts an in-flight bind', async () => {+ await bindChatStoreForUser('seed-user', ENV_A)+ unbindChatStore()++ const originalReadDir = fs.readdir.bind(fs)+ let releaseRead: (() => void) | undefined+ const readBlocked = new Promise<void>(resolve => {+ releaseRead = resolve+ })+ let readStarted: (() => void) | undefined+ const started = new Promise<void>(resolve => {+ readStarted = resolve+ })+ vi.spyOn(fs, 'readdir').mockImplementation(async (...args) => {+ if (String(args[0]).endsWith(path.join(ENV_A, 'user-b'))) {+ readStarted?.()+ await readBlocked+ }+ return originalReadDir(...(args as Parameters<typeof fs.readdir>))+ })++ const binding = bindChatStoreForUser('user-b', ENV_A)+ await started+ unbindChatStore()+ releaseRead?.()+ await binding++ 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()@@ -63,6 +123,20 @@ describe('chatStoreBinding', () => {expect((await requireChatStore().listChats('agent-x')).map(c => c.id)).toEqual(['chat-in-b'])})+ it('migrates a legacy env-scoped user cache into the active env key when empty', async () => {+ await bindChatStoreForUser('user-a', ENV_A)+ await requireChatStore().createChat('agent-x', 'chat-from-legacy-env')+ unbindChatStore()++ await bindChatStoreForUser('user-a', ENV_B, { legacyEnvKeys: [ENV_A] })++ expect((await requireChatStore().listChats('agent-x')).map(c => c.id)).toEqual([+ 'chat-from-legacy-env',+ ])+ expect(await exists(path.join(tmpBase, ENV_A, 'user-a'))).toBe(false)+ expect(await exists(path.join(tmpBase, ENV_B, 'user-a', 'agent-x', 'index.json'))).toBe(true)+ })+it('re-binds when the envKey changes for the same user', async () => {await bindChatStoreForUser('user-a', ENV_A)const storeA = requireChatStore()@@ -110,6 +184,42 @@ describe('chatStoreBinding', () => {expect(() => requireChatStore()).toThrow(/Not authenticated/)})+ it('sweeps expired corrupt transcript quarantines while retaining recent recovery data', async () => {+ const agentDir = path.join(tmpBase, ENV_A, 'user-retention', 'agent-x')+ const legacyCorruptDir = path.join(agentDir, '.corrupt')+ const snapshotRoot = path.join(agentDir, 'chats', '.snapshots', 'encoded-chat')+ const oldPagedCorrupt = path.join(snapshotRoot, 'corrupt-old')+ const recentPagedCorrupt = path.join(snapshotRoot, 'corrupt-recent')+ const oldLegacyCorrupt = path.join(legacyCorruptDir, 'old.json')+ const recentLegacyCorrupt = path.join(legacyCorruptDir, 'recent.json')+ await fs.mkdir(legacyCorruptDir, { recursive: true })+ await fs.mkdir(oldPagedCorrupt, { recursive: true })+ await fs.mkdir(recentPagedCorrupt, { recursive: true })+ await fs.writeFile(+ path.join(agentDir, 'index.json'),+ JSON.stringify({+ version: 2,+ chats: [],+ lastActiveChatId: null,+ onboardingDismissed: false,+ })+ )+ await fs.writeFile(oldLegacyCorrupt, 'old legacy transcript')+ await fs.writeFile(recentLegacyCorrupt, 'recent legacy transcript')+ await fs.writeFile(path.join(oldPagedCorrupt, 'meta.json'), 'old paged transcript')+ await fs.writeFile(path.join(recentPagedCorrupt, 'meta.json'), 'recent paged transcript')+ const expiredAt = new Date(Date.now() - 31 * 24 * 60 * 60 * 1000)+ await fs.utimes(oldLegacyCorrupt, expiredAt, expiredAt)+ await fs.utimes(oldPagedCorrupt, expiredAt, expiredAt)++ await bindChatStoreForUser('user-retention', ENV_A)++ expect(await exists(oldLegacyCorrupt)).toBe(false)+ expect(await exists(oldPagedCorrupt)).toBe(false)+ expect(await exists(recentLegacyCorrupt)).toBe(true)+ expect(await exists(recentPagedCorrupt)).toBe(true)+ })+// §5.2 / §7.1 — bootstrap wipes any pre-v2 (legacy schema) per-agent cache dir// WITHIN the env-scoped user directory.describe('legacy schema wipe on bind', () => {@@ -154,7 +264,7 @@ describe('chatStoreBinding', () => {expect(await exists(path.join(tmpBase, ENV_A, 'user-broken', 'agent-y'))).toBe(false)})- it('preserves a v2 agent dir', async () => {+ it('preserves the downgrade-compatible v2 agent index', async () => {const v2Index = JSON.stringify({version: 2,chats: [{ id: 'keep', title: 'Keep', createdAt: 'x', updatedAt: 'x', messageCount: 1 }],@@ -171,6 +281,72 @@ describe('chatStoreBinding', () => {expect((await requireChatStore().listChats('agent-x')).find(c => c.id === 'keep')).toBeDefined()+ const preserved = JSON.parse(+ await fs.readFile(+ path.join(tmpBase, ENV_A, 'user-current', 'agent-x', 'index.json'),+ 'utf-8'+ )+ ) as { version: number }+ expect(preserved.version).toBe(2)+ })++ it('normalizes an earlier paging v3 index back to downgrade-compatible v2', async () => {+ const v3Index = JSON.stringify({+ version: 3,+ chats: [{ id: 'keep', title: 'Keep', createdAt: 'x', updatedAt: 'x', messageCount: 1 }],+ lastActiveChatId: 'keep',+ onboardingDismissed: false,+ })+ await seedAgentDir(ENV_A, 'user-v3', 'agent-x', v3Index, {+ 'keep.json': JSON.stringify({+ version: 2,+ chatId: 'keep',+ messages: [{ id: 'm1', role: 'user', content: 'keep me', timestamp: 1 }],+ }),+ })++ await bindChatStoreForUser('user-v3', ENV_A)++ const normalized = JSON.parse(+ await fs.readFile(path.join(tmpBase, ENV_A, 'user-v3', 'agent-x', 'index.json'), 'utf-8')+ ) as { version: number }+ expect(normalized.version).toBe(2)+ expect(await exists(path.join(tmpBase, ENV_A, 'user-v3', 'agent-x', 'keep.json'))).toBe(true)+ })++ it('preserves a valid v3 cache when its index normalization cannot be renamed', async () => {+ const v3Index = JSON.stringify({+ version: 3,+ chats: [{ id: 'keep', title: 'Keep', createdAt: 'x', updatedAt: 'x', messageCount: 1 }],+ lastActiveChatId: 'keep',+ onboardingDismissed: false,+ })+ await seedAgentDir(ENV_A, 'user-v3-failure', 'agent-x', v3Index, {+ 'keep.json': '{"version":2,"chatId":"keep","messages":[]}',+ })+ const originalRename = fs.rename.bind(fs)+ vi.spyOn(fs, 'rename').mockImplementation(async (from, to) => {+ if (String(from).endsWith('index.json.v2.tmp')) {+ const error = new Error('read only') as NodeJS.ErrnoException+ error.code = 'EACCES'+ throw error+ }+ return originalRename(from, to)+ })++ await bindChatStoreForUser('user-v3-failure', ENV_A)++ expect(+ await exists(path.join(tmpBase, ENV_A, 'user-v3-failure', 'agent-x', 'keep.json'))+ ).toBe(true)+ expect(+ JSON.parse(+ await fs.readFile(+ path.join(tmpBase, ENV_A, 'user-v3-failure', 'agent-x', 'index.json'),+ 'utf-8'+ )+ ).version+ ).toBe(3)})it('is a no-op when the user has no cache directory yet', async () => {diff --git a/desktop-app/src/__tests__/config.envKey.test.ts b/desktop-app/src/__tests__/config.envKey.test.tsindex a142d2659..6eaba6926 100644--- a/desktop-app/src/__tests__/config.envKey.test.ts+++ b/desktop-app/src/__tests__/config.envKey.test.ts@@ -12,7 +12,7 @@ vi.mock('electron', () => ({},}))-let resolveEnvKey: (url: string) => string+let resolveEnvKey: (url: string, rpcProxyBaseUrl?: string) => stringbeforeEach(async () => {const mod = await import('../config.js')@@ -53,6 +53,12 @@ describe('resolveEnvKey (spec §5.1, D1)', () => {)})+ it('keys apart when the external REST origin matches but the RPC origin differs', () => {+ expect(resolveEnvKey('https://api.example.com', 'https://rpc.dev.example.com')).not.toBe(+ resolveEnvKey('https://api.example.com', 'https://rpc.example.com')+ )+ })+it('produces a valid, stable key for the Localhost sentinel origin', () => {const key = resolveEnvKey('http://127.0.0.1:8091')expect(key).toMatch(/^http_127_0_0_1_8091-[0-9a-f]{12}$/)diff --git a/desktop-app/src/__tests__/config.runtimeConfig.test.ts b/desktop-app/src/__tests__/config.runtimeConfig.test.tsindex 188399c6f..69dabdf1e 100644--- a/desktop-app/src/__tests__/config.runtimeConfig.test.ts+++ b/desktop-app/src/__tests__/config.runtimeConfig.test.ts@@ -1,4 +1,4 @@-import { afterEach, describe, expect, it, vi } from 'vitest'+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'import fsp from 'node:fs/promises'import os from 'node:os'import path from 'node:path'@@ -8,8 +8,15 @@ describe('desktop runtime config', () => {const originalExternalRestApiBaseUrl = process.env.EXTERNAL_REST_API_BASE_URLconst originalRpcProxyBaseUrl = process.env.RPC_PROXY_BASE_URLconst originalDesktopAppName = process.env.DESKTOP_APP_NAME+ const originalArgv = [...process.argv]+ const originalRendererUrl = process.env.EVENFIRE_RENDERER_URLlet tempUserDataDir: string | null = null+ beforeEach(() => {+ vi.doUnmock('electron')+ vi.resetModules()+ })+afterEach(async () => {if (originalConfigPath === undefined) {delete process.env.CLERUM_DESKTOP_CONFIG_PATH@@ -31,6 +38,12 @@ describe('desktop runtime config', () => {} else {process.env.DESKTOP_APP_NAME = originalDesktopAppName}+ process.argv.splice(0, process.argv.length, ...originalArgv)+ if (originalRendererUrl === undefined) {+ delete process.env.EVENFIRE_RENDERER_URL+ } else {+ process.env.EVENFIRE_RENDERER_URL = originalRendererUrl+ }if (tempUserDataDir) {await fsp.rm(tempUserDataDir, { recursive: true, force: true })@@ -85,6 +98,155 @@ describe('desktop runtime config', () => {expect(config.rpcProxyBaseUrl).toBe('http://127.0.0.1:8094')})+ it('ignores CLERUM_DESKTOP_CONFIG_PATH in packaged builds', async () => {+ tempUserDataDir = await fsp.mkdtemp(path.join(os.tmpdir(), 'evenfire-user-data-'))+ const explicitConfigPath = path.join(tempUserDataDir, 'explicit-runtime-config.json')+ await fsp.writeFile(+ explicitConfigPath,+ JSON.stringify({+ externalRestApiBaseUrl: 'https://explicit-api.example.com',+ rpcProxyBaseUrl: 'https://explicit-rpc.example.com',+ appName: 'Explicit',+ })+ )+ process.env.CLERUM_DESKTOP_CONFIG_PATH = explicitConfigPath+ process.env.EXTERNAL_REST_API_BASE_URL = 'https://packaged-api.example.com'+ process.env.RPC_PROXY_BASE_URL = 'https://packaged-rpc.example.com'++ vi.doMock('electron', () => ({+ app: {+ getPath: vi.fn((name: string) =>+ name === 'userData' ? tempUserDataDir : path.dirname(tempUserDataDir || os.tmpdir())+ ),+ isPackaged: true,+ isReady: vi.fn(() => true),+ setName: vi.fn(),+ setPath: vi.fn(),+ },+ }))++ const { config, getDesktopRuntimeConfigState } = await import('../config.js')++ expect(config.externalRestApiBaseUrl).toBe('https://packaged-api.example.com')+ expect(config.rpcProxyBaseUrl).toBe('https://packaged-rpc.example.com')+ expect(getDesktopRuntimeConfigState().storagePath).toBe(+ path.join(tempUserDataDir, 'runtime-configs')+ )+ })++ it('selects localhost for the packaged development app used by npm run ui', async () => {+ tempUserDataDir = await fsp.mkdtemp(path.join(os.tmpdir(), 'evenfire-user-data-'))+ const runtimeConfigDir = path.join(tempUserDataDir, 'runtime-configs')+ await fsp.mkdir(runtimeConfigDir, { recursive: true })+ await fsp.writeFile(+ path.join(runtimeConfigDir, 'index.json'),+ JSON.stringify({+ version: 1,+ activeProfileId: 'prod',+ profiles: [+ {+ id: 'prod',+ appName: 'Production',+ fileName: 'runtime-config-prod.json',+ createdAt: '2026-01-01T00:00:00.000Z',+ updatedAt: '2026-01-01T00:00:00.000Z',+ },+ ],+ })+ )+ await fsp.writeFile(+ path.join(runtimeConfigDir, 'runtime-config-prod.json'),+ JSON.stringify({+ externalRestApiBaseUrl: 'https://api.example.com',+ rpcProxyBaseUrl: 'https://rpc.example.com',+ appName: 'Production',+ })+ )+ delete process.env.CLERUM_DESKTOP_CONFIG_PATH+ delete process.env.DESKTOP_APP_NAME+ process.env.EXTERNAL_REST_API_BASE_URL = 'http://127.0.0.1:8091'+ process.env.RPC_PROXY_BASE_URL = 'http://127.0.0.1:8094'+ process.env.EVENFIRE_RENDERER_URL = 'http://127.0.0.1:5173'+ process.argv.push('--evenfire-desktop-dev-package')++ vi.doMock('electron', () => ({+ app: {+ getPath: vi.fn((name: string) =>+ name === 'userData' ? tempUserDataDir : path.dirname(tempUserDataDir || os.tmpdir())+ ),+ isPackaged: true,+ isReady: vi.fn(() => true),+ setName: vi.fn(),+ setPath: vi.fn(),+ },+ }))++ const { config, getDesktopRuntimeConfigState } = await import('../config.js')++ expect(config.externalRestApiBaseUrl).toBe('http://127.0.0.1:8091')+ expect(config.rpcProxyBaseUrl).toBe('http://127.0.0.1:8094')++ expect(getDesktopRuntimeConfigState()).toMatchObject({+ configured: true,+ isLocalhost: true,+ activeOptionId: '__localhost__',+ })+ })++ it('does not let the packaged-development escape hatch activate remote endpoints', async () => {+ tempUserDataDir = await fsp.mkdtemp(path.join(os.tmpdir(), 'evenfire-user-data-'))+ delete process.env.CLERUM_DESKTOP_CONFIG_PATH+ process.env.EXTERNAL_REST_API_BASE_URL = 'https://attacker.example.com'+ process.env.RPC_PROXY_BASE_URL = 'https://rpc.attacker.example.com'+ process.argv.push('--evenfire-desktop-dev-package')++ vi.doMock('electron', () => ({+ app: {+ getPath: vi.fn((name: string) =>+ name === 'userData' ? tempUserDataDir : path.dirname(tempUserDataDir || os.tmpdir())+ ),+ isPackaged: true,+ isReady: vi.fn(() => true),+ setName: vi.fn(),+ setPath: vi.fn(),+ },+ }))++ const { getDesktopRuntimeConfigState } = await import('../config.js')++ expect(getDesktopRuntimeConfigState()).toMatchObject({+ configured: false,+ activeOptionId: null,+ })+ })++ it('does not let the packaged-development escape hatch select arbitrary loopback ports', async () => {+ tempUserDataDir = await fsp.mkdtemp(path.join(os.tmpdir(), 'evenfire-user-data-'))+ delete process.env.CLERUM_DESKTOP_CONFIG_PATH+ process.env.EXTERNAL_REST_API_BASE_URL = 'http://127.0.0.1:21770'+ process.env.RPC_PROXY_BASE_URL = 'http://127.0.0.1:21773'+ process.argv.push('--evenfire-desktop-dev-package')++ vi.doMock('electron', () => ({+ app: {+ getPath: vi.fn((name: string) =>+ name === 'userData' ? tempUserDataDir : path.dirname(tempUserDataDir || os.tmpdir())+ ),+ isPackaged: true,+ isReady: vi.fn(() => true),+ setName: vi.fn(),+ setPath: vi.fn(),+ },+ }))++ const { getDesktopRuntimeConfigState } = await import('../config.js')++ expect(getDesktopRuntimeConfigState()).toMatchObject({+ configured: false,+ activeOptionId: null,+ })+ })+it('preserves env-provided localhost runtime ports without selecting the fixed localhost profile', async () => {tempUserDataDir = await fsp.mkdtemp(path.join(os.tmpdir(), 'evenfire-user-data-'))delete process.env.CLERUM_DESKTOP_CONFIG_PATHdiff --git a/desktop-app/src/__tests__/rpcProxyClient.test.ts b/desktop-app/src/__tests__/rpcProxyClient.test.tsindex f823f5e59..ba3130362 100644--- a/desktop-app/src/__tests__/rpcProxyClient.test.ts+++ b/desktop-app/src/__tests__/rpcProxyClient.test.ts@@ -12,6 +12,26 @@ vi.mock('../config.js', () => ({},}))+describe('RpcProxyClient.listSessions', () => {+ let client: RpcProxyClient++ beforeEach(() => {+ client = new RpcProxyClient()+ vi.restoreAllMocks()+ })++ it.each(['.', '..', 'host/name', 'host\\name'])(+ 'rejects an unsafe host path before issuing a request: %s',+ async hostRef => {+ const fetchMock = vi.fn()+ vi.stubGlobal('fetch', fetchMock)++ await expect(client.listSessions('rpc-token', hostRef)).rejects.toThrow(/unsafe path segment/)+ expect(fetchMock).not.toHaveBeenCalled()+ }+ )+})+describe('RpcProxyClient.cancelTask', () => {let client: RpcProxyClientdiff --git a/desktop-app/src/__tests__/tokenStore.test.ts b/desktop-app/src/__tests__/tokenStore.test.tsindex 6ca10143d..4fdba8a76 100644--- a/desktop-app/src/__tests__/tokenStore.test.ts+++ b/desktop-app/src/__tests__/tokenStore.test.ts@@ -31,6 +31,7 @@ const LEGACY_ACCOUNT = 'session-token'// hash separator.const ENV_A = 'env_a-000000000000'const ENV_B = 'env_b-111111111111'+const ENV_A_WITH_RPC = 'env_a_rpc-222222222222'let TokenStore: typeof import('../tokenStore.js').TokenStore@@ -84,6 +85,19 @@ describe('TokenStore per-environment slots (spec §5.2)', () => {expect(await store.getSessionToken(ENV_B)).toBeNull()})+ it('migrates an older env-scoped token into the active env slot, then deletes it', async () => {+ keychain.set(keyOf(SERVICE, `${LEGACY_ACCOUNT}::${ENV_A}`), 'rest-only-tok')+ const store = new TokenStore()++ const migrated = await store.getSessionToken(ENV_A_WITH_RPC, { legacyEnvKeys: [ENV_A] })+ expect(migrated).toBe('rest-only-tok')+ expect(keychain.get(keyOf(SERVICE, `${LEGACY_ACCOUNT}::${ENV_A_WITH_RPC}`))).toBe(+ 'rest-only-tok'+ )+ expect(keychain.has(keyOf(SERVICE, `${LEGACY_ACCOUNT}::${ENV_A}`))).toBe(false)+ expect(await store.getSessionToken(ENV_A)).toBeNull()+ })+it('clear removes the legacy global slot too (defense against later migration)', async () => {keychain.set(keyOf(SERVICE, LEGACY_ACCOUNT), 'legacy-tok')const store = new TokenStore()diff --git a/desktop-app/src/appService.ts b/desktop-app/src/appService.tsindex 9e3e6d3f4..b5f07cf56 100644--- a/desktop-app/src/appService.ts+++ b/desktop-app/src/appService.ts@@ -7,6 +7,7 @@ import {config,deleteDesktopRuntimeConfigOption,getActiveEnvKey,+ getActiveLegacyRestOnlyEnvKey,getDesktopRuntimeConfigState,hydrateDesktopRuntimeConfig,isDesktopRuntimeConfigured,@@ -51,9 +52,12 @@ import {RpcScope,SessionLifecycleState,SessionMe,+ SessionMessagesQuery,SessionMessagesResult,SessionState,SessionTokensLite,+ SessionsListQuery,+ SessionsListResult,SetHostModelResult,TaskProgressStreamEvent,TeamDirectoryResult,@@ -266,6 +270,10 @@ export class AppService {private accessCatalog: AccessCatalog | null = nullprivate teamDirectoryCache: TeamDirectoryResult | null = nullprivate teamContextQueue: Promise<void> = Promise.resolve()+ private restoreSavedSessionInFlight: Promise<SessionState> | null = null+ private savedSessionRestoreAttemptedEnvKey: string | null = null+ private logoutInProgress = false+ private sessionGeneration = 0private workflowApprovalTeamById = new Map<string, string>()private workflowTeamByKey = new Map<string, string>()private readonly prewarmAttemptAtByHostRef = new Map<string, number>()@@ -326,6 +334,13 @@ export class AppService {)}+ private static isRejectedStoredSessionError(error: unknown): boolean {+ return (+ error instanceof ApiError &&+ (error.status === 401 || error.status === 403 || error.status === 410)+ )+ }+/*** Maps rpc-proxy's structured host-availability 503s ({code:'host_waking'}* from the wake-and-hold subsystem, {code:'host_draining'} from the mcp-host@@ -374,6 +389,7 @@ export class AppService {options: { refreshMe?: boolean } = {}): Promise<void> {const tokenChanged = token !== this.sessionToken+ if (tokenChanged) this.sessionGeneration += 1this.sessionToken = tokenif (tokenChanged) {this.rpcTokenManager.clear()@@ -509,15 +525,79 @@ export class AppService {)}- async initialize(): Promise<SessionState> {+ private clearAuthenticatedSessionState(): void {+ this.sessionGeneration += 1+ this.stopAllStreams()+ this.sessionToken = null+ this.me = null+ this.accessCatalog = null+ this.teamDirectoryCache = null+ this.workflowApprovalTeamById.clear()+ this.workflowTeamByKey.clear()+ this.rpcTokenManager.clear()+ unbindChatStore()+ }++ private async restoreSavedSession(options: { runLaunchMaintenance?: boolean } = {}) {+ if (this.restoreSavedSessionInFlight) {+ return await this.restoreSavedSessionInFlight+ }+ const restore = this.restoreSavedSessionOnce(options)+ this.restoreSavedSessionInFlight = restore+ try {+ return await restore+ } finally {+ // No newer restore can start while this promise is installed, so the+ // single-flight slot can be cleared unconditionally after it settles.+ this.restoreSavedSessionInFlight = null+ }+ }++ private async restoreSavedSessionOnce(options: { runLaunchMaintenance?: boolean } = {}) {+ if (this.logoutInProgress) return { authenticated: false, me: null }+ const restoreGeneration = this.sessionGenerationhydrateDesktopRuntimeConfig()- this.sessionToken = await this.tokenStore.getSessionToken(getActiveEnvKey())- if (!this.sessionToken) {+ const envKey = getActiveEnvKey()+ const legacyEnvKey = getActiveLegacyRestOnlyEnvKey()+ const legacyEnvKeys = legacyEnvKey !== envKey ? [legacyEnvKey] : []+ this.savedSessionRestoreAttemptedEnvKey = envKey+ let token: string | null+ try {+ token = await this.tokenStore.getSessionToken(envKey, { legacyEnvKeys })+ } 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) {+ this.clearAuthenticatedSessionState()+ }+ return { authenticated: false, me: null }+ }++ if (this.sessionGeneration !== restoreGeneration) {+ return { authenticated: Boolean(this.sessionToken && this.me), me: this.me }+ }+ this.sessionToken = tokentry {- this.me = await this.authClient.getMe(this.sessionToken)- await bindChatStoreForUser(this.me.id, getActiveEnvKey())+ const restoredMe = await this.authClient.getMe(token)+ if (this.sessionGeneration !== restoreGeneration || this.sessionToken !== token) {+ return { authenticated: Boolean(this.sessionToken && this.me), me: this.me }+ }+ await bindChatStoreForUser(restoredMe.id, envKey, { legacyEnvKeys })+ if (this.sessionGeneration !== restoreGeneration || this.sessionToken !== token) {+ if (this.me) {+ await bindChatStoreForUser(this.me.id, getActiveEnvKey(), { legacyEnvKeys })+ } else {+ unbindChatStore()+ }+ return { authenticated: Boolean(this.sessionToken && this.me), me: this.me }+ }+ this.me = restoredMethis.accessCatalog = nullthis.teamDirectoryCache = nullthis.workflowApprovalTeamById.clear()@@ -525,14 +605,28 @@ export class AppService {// Launch-time sandbox-ui partition GC. Fire-and-forget: a failure// here must not block the user from logging in. Any network or fs// error is logged inside the module.- void this.runSandboxUiPartitionGcSafely()+ if (options.runLaunchMaintenance) {+ void this.runSandboxUiPartitionGcSafely()+ }return { authenticated: true, me: this.me }- } catch {- await this.logout()+ } catch (error) {+ if (this.sessionGeneration !== restoreGeneration || this.sessionToken !== token) {+ return { authenticated: Boolean(this.sessionToken && this.me), me: this.me }+ }+ this.clearAuthenticatedSessionState()+ if (AppService.isRejectedStoredSessionError(error)) {+ await this.tokenStore.clearSessionToken(envKey)+ } else {+ console.warn('[AppService] Saved session restore failed; keeping token for retry:', error)+ }return { authenticated: false, me: null }}}+ async initialize(): Promise<SessionState> {+ return this.restoreSavedSession({ runLaunchMaintenance: true })+ }+private async runSandboxUiPartitionGcSafely(): Promise<void> {try {const { app } = await import('electron')@@ -555,6 +649,8 @@ export class AppService {private async completePasswordLogin(email: string, password: string): Promise<SessionState> {const result = await this.authClient.passwordLogin(email, password)+ this.logoutInProgress = false+ this.sessionGeneration += 1this.sessionToken = result.tokenthis.me = result.meawait bindChatStoreForUser(result.me.id, getActiveEnvKey())@@ -624,6 +720,8 @@ export class AppService {async googleLogin(idToken: string): Promise<SessionState> {const result = await this.authClient.googleLogin(idToken)+ this.logoutInProgress = false+ this.sessionGeneration += 1this.sessionToken = result.tokenthis.me = result.meawait bindChatStoreForUser(result.me.id, getActiveEnvKey())@@ -808,16 +906,13 @@ export class AppService {}async logout(): Promise<void> {- this.stopAllStreams()- this.sessionToken = null- this.me = null- this.accessCatalog = null- this.teamDirectoryCache = null- this.workflowApprovalTeamById.clear()- this.workflowTeamByKey.clear()- this.rpcTokenManager.clear()- await this.tokenStore.clearSessionToken(getActiveEnvKey())- unbindChatStore()+ this.logoutInProgress = true+ 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). */@@ -960,7 +1055,17 @@ export class AppService {}async getSessionState(): Promise<SessionState> {- if (!this.sessionToken || !this.me) return { authenticated: false, me: null }+ if (!this.sessionToken || !this.me) {+ if (this.restoreSavedSessionInFlight) return this.restoreSavedSession()+ // createWindow() already performs the saved-token restore before showing+ // the renderer. Do not immediately repeat a failed 60-second network+ // attempt from the renderer bootstrap; a new app launch or environment+ // selection gets a fresh attempt because its service/env key is new.+ if (this.savedSessionRestoreAttemptedEnvKey === getActiveEnvKey()) {+ return { authenticated: false, me: null }+ }+ return this.restoreSavedSession()+ }return { authenticated: true, me: this.me }}@@ -2516,25 +2621,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')) {@@ -2551,7 +2646,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) {@@ -2560,14 +2656,27 @@ 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,+ }}throw error}diff --git a/desktop-app/src/chatMessageMerge.ts b/desktop-app/src/chatMessageMerge.tsnew file mode 100644index 000000000..b513ee2b7--- /dev/null+++ b/desktop-app/src/chatMessageMerge.ts@@ -0,0 +1,296 @@+import type { ChatMessage } from './types.js'++export function messageServerTurnNumber(message: Pick<ChatMessage, 'id' | 'serverTurnNumber'>) {+ if (message.serverTurnNumber !== undefined) return message.serverTurnNumber+ const match = /^turn-(\d+)-(?:user|assistant)$/.exec(message.id)+ return match ? Number(match[1]) : undefined+}++function roleRank(message: Pick<ChatMessage, 'role'>): number {+ return message.role === 'user' ? 0 : message.role === 'assistant' ? 1 : 2+}++function serverSlotKey(message: Pick<ChatMessage, 'id' | 'role' | 'serverTurnNumber'>): string {+ return `${messageServerTurnNumber(message)}\u0000${message.role}`+}++function preferredServerMessage(+ server: ChatMessage,+ local: ChatMessage | undefined,+ options: { copyLocalMetadata: boolean }+): ChatMessage {+ if (!local || !options.copyLocalMetadata) return server+ return {+ ...server,+ task_id: local.task_id ?? server.task_id,+ attachments: server.attachments?.length ? server.attachments : local.attachments,+ toolSteps: server.toolSteps?.length ? server.toolSteps : local.toolSteps,+ }+}++function insertUnmatchedTurnlessIncoming(+ mergedMessages: ChatMessage[],+ incoming: ChatMessage[],+ removedIds: ReadonlySet<string>+): ChatMessage[] {+ const merged = [...mergedMessages]+ const mergedIds = new Set(merged.map(message => message.id))++ for (const [incomingIndex, message] of incoming.entries()) {+ if (+ messageServerTurnNumber(message) !== undefined ||+ mergedIds.has(message.id) ||+ removedIds.has(message.id)+ ) {+ continue+ }++ let previousTurn: number | undefined+ for (let index = incomingIndex - 1; index >= 0; index -= 1) {+ previousTurn = messageServerTurnNumber(incoming[index]!)+ if (previousTurn !== undefined) break+ }++ let nextTurn: number | undefined+ for (let index = incomingIndex + 1; index < incoming.length; index += 1) {+ nextTurn = messageServerTurnNumber(incoming[index]!)+ if (nextTurn !== undefined) break+ }++ let insertionIndex = merged.length+ if (previousTurn !== undefined) {+ for (let index = merged.length - 1; index >= 0; index -= 1) {+ if (messageServerTurnNumber(merged[index]!) === previousTurn) {+ insertionIndex = index + 1+ break+ }+ }+ } else if (nextTurn !== undefined) {+ const nextIndex = merged.findIndex(item => messageServerTurnNumber(item) === nextTurn)+ if (nextIndex >= 0) insertionIndex = nextIndex+ }++ merged.splice(insertionIndex, 0, message)+ mergedIds.add(message.id)+ }++ return merged+}++/**+ * Replace the authoritative server-turn range as a unit.+ *+ * Turnless optimistic messages positioned inside that range are paired by role+ * and replaced even when content or clocks differ. Only task IDs explicitly+ * reported as active remain; a persisted task_id alone does not prove liveness+ * because completed local echoes retain it. Orphaned optimistic messages are+ * evicted, while non-turn roles and durable errors remain untouched.+ */+export function mergeAuthoritativeServerMessages(+ existing: ChatMessage[],+ incoming: ChatMessage[],+ options: { activeTaskIds?: ReadonlySet<string> } = {}+): ChatMessage[] {+ const authoritative = incoming+ .filter(message => messageServerTurnNumber(message) !== undefined)+ .sort((left, right) => {+ const turnDelta =+ (messageServerTurnNumber(left) ?? Number.MAX_SAFE_INTEGER) -+ (messageServerTurnNumber(right) ?? Number.MAX_SAFE_INTEGER)+ return turnDelta || roleRank(left) - roleRank(right)+ })+ if (!authoritative.length) {+ const incomingIds = new Set(incoming.map(message => message.id))+ return [...existing.filter(message => !incomingIds.has(message.id)), ...incoming]+ }++ const previousNumberedMessages: Array<ChatMessage | undefined> = []+ let previousNumberedMessage: ChatMessage | undefined+ for (const message of existing) {+ previousNumberedMessages.push(previousNumberedMessage)+ if (messageServerTurnNumber(message) !== undefined) previousNumberedMessage = message+ }+ const nextNumberedMessages: Array<ChatMessage | undefined> = new Array(existing.length)+ let nextNumberedMessage: ChatMessage | undefined+ for (let index = existing.length - 1; index >= 0; index -= 1) {+ nextNumberedMessages[index] = nextNumberedMessage+ if (messageServerTurnNumber(existing[index]!) !== undefined) {+ nextNumberedMessage = existing[index]+ }+ }++ const removed: ChatMessage[] = []+ const removedIndexes = new Set<number>()+ const removedIndexByMessage = new Map<ChatMessage, number>()+ const localByServerMessage = new Map<ChatMessage, ChatMessage>()+ const consumedLocalMessages = new Set<ChatMessage>()+ const suppressedServerMessages = new Set<ChatMessage>()++ const markLocalReplacement = (serverMessage: ChatMessage, localMessage: ChatMessage) => {+ const index = existing.indexOf(localMessage)+ if (index < 0 || consumedLocalMessages.has(localMessage)) return+ consumedLocalMessages.add(localMessage)+ removed.push(localMessage)+ removedIndexes.add(index)+ removedIndexByMessage.set(localMessage, index)+ localByServerMessage.set(serverMessage, localMessage)+ }++ for (const serverMessage of authoritative) {+ const slot = serverSlotKey(serverMessage)+ const sameSlot = existing.find(+ local =>+ !consumedLocalMessages.has(local) &&+ messageServerTurnNumber(local) !== undefined &&+ serverSlotKey(local) === slot+ )+ if (sameSlot) markLocalReplacement(serverMessage, sameSlot)+ }++ const serverTurnAllowedForTurnlessLocal = (+ serverMessage: ChatMessage,+ localMessage: ChatMessage,+ localIndex: number+ ): boolean => {+ const serverTurn = messageServerTurnNumber(serverMessage)!+ const previous = previousNumberedMessages[localIndex]+ const previousTurn =+ previous !== undefined+ ? (messageServerTurnNumber(previous) ?? Number.NEGATIVE_INFINITY)+ : Number.NEGATIVE_INFINITY+ const next = nextNumberedMessages[localIndex]+ const nextTurn =+ next !== undefined+ ? (messageServerTurnNumber(next) ?? Number.POSITIVE_INFINITY)+ : Number.POSITIVE_INFINITY+ const lowerBoundAllows =+ serverTurn > previousTurn ||+ (serverTurn === previousTurn && previous?.role !== localMessage.role)+ const upperBoundAllows =+ serverTurn < nextTurn || (serverTurn === nextTurn && next?.role !== localMessage.role)+ return lowerBoundAllows && upperBoundAllows+ }++ for (const [index, message] of existing.entries()) {+ if (+ messageServerTurnNumber(message) !== undefined ||+ message.task_id === undefined ||+ options.activeTaskIds?.has(message.task_id) !== true+ ) {+ continue+ }+ if (message.role !== 'user' && message.role !== 'assistant') continue+ if (message.isError || message.preserveLocal || consumedLocalMessages.has(message)) continue+ const eligibleServerMessages = authoritative.filter(+ serverMessage =>+ !localByServerMessage.has(serverMessage) &&+ !suppressedServerMessages.has(serverMessage) &&+ serverMessage.role === message.role &&+ serverTurnAllowedForTurnlessLocal(serverMessage, message, index)+ )+ // A live local bubble remains authoritative for the UI until the server can+ // identify the same task. Current server history rows are usually unscoped,+ // so suppress one only when its role and position identify a single slot.+ const exactTaskMatches = eligibleServerMessages.filter(+ serverMessage => serverMessage.task_id === message.task_id+ )+ if (exactTaskMatches.length === 1) {+ markLocalReplacement(exactTaskMatches[0]!, message)+ continue+ }++ const unscopedCandidates = eligibleServerMessages.filter(+ serverMessage => serverMessage.task_id === undefined+ )+ const candidateTurns = new Set(+ unscopedCandidates.map(serverMessage => messageServerTurnNumber(serverMessage)!)+ )+ if (candidateTurns.size === 1 && unscopedCandidates.length === 1) {+ suppressedServerMessages.add(unscopedCandidates[0]!)+ }+ }++ for (const [index, message] of existing.entries()) {+ if (messageServerTurnNumber(message) !== undefined) continue+ if (message.role !== 'user' && message.role !== 'assistant') continue+ if (message.isError || message.preserveLocal || consumedLocalMessages.has(message)) continue+ if (message.task_id && options.activeTaskIds?.has(message.task_id)) continue++ const authoritativeCandidates = authoritative.filter(+ serverMessage =>+ serverMessage.role === message.role &&+ serverTurnAllowedForTurnlessLocal(serverMessage, message, index)+ )+ const candidateTurns = new Set<number>()+ for (const candidate of authoritativeCandidates) {+ candidateTurns.add(messageServerTurnNumber(candidate)!)+ }+ if (candidateTurns.size !== 1) continue++ const candidates = authoritativeCandidates.filter(+ serverMessage =>+ !localByServerMessage.has(serverMessage) &&+ serverTurnAllowedForTurnlessLocal(serverMessage, message, index)+ )+ if (!candidates.length) continue+ markLocalReplacement(candidates[0]!, message)+ }++ const hydratedReplacements = authoritative+ .filter(message => !suppressedServerMessages.has(message))+ .map(message => {+ const local = localByServerMessage.get(message)+ return {+ message: preferredServerMessage(message, local, { copyLocalMetadata: Boolean(local) }),+ localAnchorIndex: local ? removedIndexByMessage.get(local) : undefined,+ }+ })++ const replacementAnchorByTurn = new Map<number, number>()+ for (const replacement of hydratedReplacements) {+ const replacementTurn = messageServerTurnNumber(replacement.message)!+ if (replacement.localAnchorIndex === undefined) continue+ const currentAnchor = replacementAnchorByTurn.get(replacementTurn)+ if (currentAnchor === undefined || replacement.localAnchorIndex < currentAnchor) {+ replacementAnchorByTurn.set(replacementTurn, replacement.localAnchorIndex)+ }+ }+ const replacementBuckets = new Map<number, ChatMessage[]>()+ let minimumAnchorIndex = 0+ for (const replacement of hydratedReplacements) {+ const replacementTurn = messageServerTurnNumber(replacement.message)!+ const exactTurnAnchor = existing.findIndex(+ message => messageServerTurnNumber(message) === replacementTurn+ )+ let anchorIndex = exactTurnAnchor+ if (anchorIndex < 0) {+ anchorIndex = replacementAnchorByTurn.get(replacementTurn) ?? -1+ }+ if (anchorIndex < 0) {+ anchorIndex = existing.findIndex(message => {+ const existingTurn = messageServerTurnNumber(message)+ return existingTurn !== undefined && existingTurn > replacementTurn+ })+ }+ if (anchorIndex < 0) anchorIndex = existing.length+ anchorIndex = Math.max(anchorIndex, minimumAnchorIndex)+ minimumAnchorIndex = anchorIndex+ replacementAnchorByTurn.set(replacementTurn, anchorIndex)+ const bucket = replacementBuckets.get(anchorIndex) ?? []+ bucket.push(replacement.message)+ replacementBuckets.set(anchorIndex, bucket)+ }++ const merged: ChatMessage[] = []+ for (let index = 0; index <= existing.length; index += 1) {+ merged.push(...(replacementBuckets.get(index) ?? []))+ if (index < existing.length && !removedIndexes.has(index)) {+ merged.push(existing[index]!)+ }+ }+ return insertUnmatchedTurnlessIncoming(+ merged,+ incoming,+ new Set(removed.map(message => message.id))+ )+}diff --git a/desktop-app/src/chatStore.ts b/desktop-app/src/chatStore.tsindex 1a5db8347..57c380db8 100644--- a/desktop-app/src/chatStore.ts+++ b/desktop-app/src/chatStore.ts@@ -1,8 +1,127 @@+import { createHash, 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'+import { dirname, join } from 'node:path'+import { mergeAuthoritativeServerMessages, messageServerTurnNumber } from './chatMessageMerge.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.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$/++export interface ChatStoreOptions {+ pageSize?: number+ maxLocalSyncedMessages?: number+}++interface ChatPageEntry {+ file: string+ count: number+ serverSynced: boolean+ firstServerTurnNumber?: number+ lastServerTurnNumber?: number+}++interface PagedChatMeta {+ version: typeof PAGED_CHAT_VERSION+ chatId: string+ pageSize: number+ messageCount: number+ localMessageCount: number+ prunedBeforeCount?: number+ legacyCompatibilitySignature?: string+ pages: ChatPageEntry[]+}++interface ChatPageFile {+ version: typeof PAGED_CHAT_VERSION+ chatId: string+ pageNumber: number+ messages: ChatMessage[]+}++interface SnapshotCandidate {+ dir: string+ kind: 'next' | 'previous'+ token: string+ mtimeMs: number+}++function normalizePositiveInteger(value: number | undefined, fallback: number): number {+ if (value === undefined) return fallback+ if (!Number.isFinite(value)) return fallback+ const normalized = Math.floor(value)+ return normalized > 0 ? normalized : fallback+}++function normalizeMaxLocalSyncedMessages(value: number | undefined): number {+ if (value === undefined) return DEFAULT_MAX_LOCAL_SYNCED_MESSAGES+ if (value === Number.POSITIVE_INFINITY) return Number.POSITIVE_INFINITY+ if (!Number.isFinite(value)) return DEFAULT_MAX_LOCAL_SYNCED_MESSAGES+ return Math.max(0, Math.floor(value))+}++function pageFileName(pageNumber: number): string {+ return `${pageNumber.toString().padStart(6, '0')}.json`+}++function pageNumberFromFileName(fileName: string): number {+ if (!PAGE_FILE_PATTERN.test(fileName)) return 0+ return Number(fileName.slice(0, 6))+}++function isNotFoundError(err: unknown): boolean {+ return (err as NodeJS.ErrnoException | undefined)?.code === 'ENOENT'+}++function isRawFilesystemError(err: unknown): boolean {+ return typeof (err as NodeJS.ErrnoException | undefined)?.code === 'string'+}++function isUnsafeSegmentError(err: unknown): boolean {+ return err instanceof Error && /unsafe path segment/.test(err.message)+}++function aggregateMessages(+ messages: ChatMessage[]+): Pick<ChatMetadata, 'errorCount' | 'toolCallCount'> {+ return {+ errorCount: messages.reduce((total, message) => total + (message.isError ? 1 : 0), 0),+ toolCallCount: messages.reduce((total, message) => total + (message.toolSteps?.length ?? 0), 0),+ }+}++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)+ .filter((turn): turn is number => turn !== undefined)+ return {+ file,+ count: messages.length,+ serverSynced: messages.length > 0 && serverTurns.length === messages.length,+ firstServerTurnNumber: serverTurns.length ? Math.min(...serverTurns) : undefined,+ lastServerTurnNumber: serverTurns.length ? Math.max(...serverTurns) : undefined,+ }+}/*** Reject any path-component (agentRef / chatId) that could escape the store@@ -12,11 +131,85 @@ const INDEX_VERSION = 2* 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`)}}+function encodedChatId(chatId: string): string {+ return Buffer.from(chatId, 'utf8').toString('base64url')+}++function legacyCorruptFileBelongsToChat(fileName: string, chatId: string): boolean {+ const encoded = encodedChatId(chatId)+ const match =+ /^(.*)-[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}\.json$/i.exec(+ fileName+ )+ return match?.[1] === encoded+}++function sameReconciledMessage(local: ChatMessage, server: ChatMessage): boolean {+ if (local.id === server.id) return true+ const localTurn = messageServerTurnNumber(local)+ const serverTurn = messageServerTurnNumber(server)+ if (+ localTurn !== undefined &&+ serverTurn !== undefined &&+ localTurn === serverTurn &&+ local.role === server.role+ ) {+ return true+ }+ if (+ localTurn === undefined &&+ serverTurn !== undefined &&+ local.role === server.role &&+ ((local.task_id && server.task_id && local.task_id === server.task_id) ||+ (local.content.trim() === server.content.trim() &&+ Math.abs(local.timestamp - server.timestamp) <= 60_000))+ ) {+ return true+ }+ return false+}++function reconciledMessageRoleRank(message: ChatMessage): number {+ return message.role === 'user' ? 0 : message.role === 'assistant' ? 1 : 2+}++function mergeReconciledMessages(existing: ChatMessage[], incoming: ChatMessage[]): ChatMessage[] {+ const merged = [...existing]+ for (const serverMessage of incoming) {+ const matchIndex = merged.findIndex(message => sameReconciledMessage(message, serverMessage))+ if (matchIndex >= 0) {+ merged[matchIndex] = {+ ...serverMessage,+ task_id: merged[matchIndex]?.task_id ?? serverMessage.task_id,+ }+ continue+ }++ const serverTurn = messageServerTurnNumber(serverMessage)+ const insertionIndex =+ serverTurn === undefined+ ? -1+ : merged.findIndex(message => {+ const messageTurn = messageServerTurnNumber(message)+ if (messageTurn === undefined) return false+ return (+ messageTurn > serverTurn ||+ (messageTurn === serverTurn &&+ reconciledMessageRoleRank(message) > reconciledMessageRoleRank(serverMessage))+ )+ })+ if (insertionIndex < 0) merged.push(serverMessage)+ else merged.splice(insertionIndex, 0, serverMessage)+ }+ return merged+}+function emptyIndex(): ChatIndex {return {version: INDEX_VERSION,@@ -27,32 +220,83 @@ function emptyIndex(): ChatIndex {}export class ChatStore {- constructor(private readonly baseDir: string) {}+ private readonly pageSize: number+ private readonly maxLocalSyncedMessages: number++ constructor(+ private readonly baseDir: string,+ options: ChatStoreOptions = {}+ ) {+ this.pageSize = normalizePositiveInteger(options.pageSize, DEFAULT_PAGE_SIZE)+ this.maxLocalSyncedMessages = normalizeMaxLocalSyncedMessages(options.maxLocalSyncedMessages)+ }/**- * Per-agent serialization of index read-modify-write sequences. The index is- * a single shared `index.json`, so concurrent mutators (e.g. two chats of one- * agent terminating at once — a first-class case post-D.4 fire-and-forget)- * could interleave getIndex→saveIndex and drop one update (e.g. an- * `unreadTerminal` flag). Chaining per agentRef makes each RMW atomic w.r.t.- * the others. Reads (getIndex/loadMessages) are not serialized.+ * Index read-modify-write sequences are serialized per agent because every+ * chat shares one `index.json`. Paged transcript operations use a separate+ * per-chat chain so reads stay atomic with writes for the same chat without+ * queuing behind unrelated chat activity.*/private indexChains = new Map<string, Promise<unknown>>()+ private chatChains = new Map<string, Promise<unknown>>()+ 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 serializeIndex<T>(agentRef: string, fn: () => Promise<T>): Promise<T> {- const prev = this.indexChains.get(agentRef) ?? Promise.resolve()+ 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])+ 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.dropCompatibilityWindow(oldestKey)+ }+ }++ private serialize<T>(+ chains: Map<string, Promise<unknown>>,+ key: string,+ fn: () => Promise<T>+ ): Promise<T> {+ const prev = chains.get(key) ?? Promise.resolve()const run = prev.then(fn, fn)- // Keep the chain alive regardless of individual outcomes.- this.indexChains.set(- agentRef,- run.then(- () => undefined,- () => undefined- )+ const settled = run.then(+ () => undefined,+ () => undefined)+ chains.set(key, settled)+ void settled.then(() => {+ if (chains.get(key) === settled) chains.delete(key)+ })return run}+ private serializeIndex<T>(agentRef: string, fn: () => Promise<T>): Promise<T> {+ return this.serialize(this.indexChains, agentRef, fn)+ }++ private serializeChat<T>(agentRef: string, chatId: string, fn: () => Promise<T>): Promise<T> {+ return this.serialize(this.chatChains, JSON.stringify([agentRef, chatId]), fn)+ }++ private chatSnapshotCleanupKey(agentRef: string, chatId: string): string {+ return JSON.stringify([agentRef, chatId])+ }+private agentDir(agentRef: string): string {assertSafeSegment('agentRef', agentRef)return join(this.baseDir, agentRef)@@ -67,13 +311,952 @@ export class ChatStore {return join(this.agentDir(agentRef), `${chatId}.json`)}+ private chatCompatibilitySignaturePath(agentRef: string, chatId: string): string {+ assertSafeSegment('chatId', chatId)+ return join(this.agentDir(agentRef), `${chatId}.compat`)+ }++ private corruptLegacyChatFilePath(agentRef: string, chatId: string): string {+ assertSafeSegment('chatId', chatId)+ return join(this.agentDir(agentRef), '.corrupt', encodedChatId(chatId), `${randomUUID()}.json`)+ }++ private chatDirPath(agentRef: string, chatId: string): string {+ assertSafeSegment('chatId', chatId)+ return join(this.agentDir(agentRef), 'chats', chatId)+ }++ private chatSnapshotSiblingPath(+ agentRef: string,+ chatId: string,+ kind: 'next' | 'previous' | 'corrupt',+ token: string+ ): string {+ assertSafeSegment('chatId', chatId)+ return join(+ this.agentDir(agentRef),+ 'chats',+ '.snapshots',+ encodedChatId(chatId),+ `${kind}-${token}`+ )+ }++ private chatSnapshotRootPath(agentRef: string, chatId: string): string {+ assertSafeSegment('chatId', chatId)+ return join(this.agentDir(agentRef), 'chats', '.snapshots', encodedChatId(chatId))+ }++ private chatPagesDirPath(agentRef: string, chatId: string): string {+ return this.chatPagesDirFromChatDir(this.chatDirPath(agentRef, chatId))+ }++ private chatMetaPath(agentRef: string, chatId: string): string {+ return this.chatMetaPathFromChatDir(this.chatDirPath(agentRef, chatId))+ }++ 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(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> {+ const tmp = `${filePath}.tmp`+ try {+ await fs.writeFile(tmp, JSON.stringify(value), { mode: 0o600 })+ await fs.rename(tmp, filePath)+ } catch (err) {+ await fs.rm(tmp, { force: true }).catch(() => undefined)+ throw err+ }+ }++ private finalizePagedMeta(meta: PagedChatMeta): PagedChatMeta {+ const localMessageCount = meta.pages.reduce((total, page) => total + page.count, 0)++ return {+ ...meta,+ pageSize: this.pageSize,+ localMessageCount,+ }+ }++ 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> {+ let raw: string+ try {+ raw = await fs.readFile(metaPath, 'utf-8')+ } catch (err) {+ if (isNotFoundError(err)) return null+ throw err+ }++ try {+ const parsed = JSON.parse(raw) as PagedChatMeta+ if (+ parsed?.version !== PAGED_CHAT_VERSION ||+ parsed.chatId !== chatId ||+ !Array.isArray(parsed.pages)+ ) {+ throw new Error('Invalid paged chat metadata')+ }+ if (parsed.pages.some(page => !PAGE_FILE_PATTERN.test(page.file))) {+ throw new Error('Invalid paged chat metadata page reference')+ }+ return this.finalizePagedMeta({+ ...parsed,+ pageSize: normalizePositiveInteger(parsed.pageSize, this.pageSize),+ messageCount: Math.max(0, Math.floor(parsed.messageCount ?? 0)),+ localMessageCount: Math.max(0, Math.floor(parsed.localMessageCount ?? 0)),+ })+ } catch (err) {+ throw new Error(`Unable to read paged chat metadata for ${chatId}`, { cause: err })+ }+ }++ private async readLegacyMessages(+ agentRef: string,+ chatId: string+ ): Promise<ChatMessage[] | null> {+ let raw: string+ try {+ raw = await fs.readFile(this.chatFilePath(agentRef, chatId), 'utf-8')+ } catch (err) {+ if (isNotFoundError(err)) return null+ throw err+ }++ try {+ const file = JSON.parse(raw) as ChatFile+ if (!file || !Array.isArray(file.messages)) {+ throw new Error('Invalid legacy chat file')+ }+ return file.messages+ } catch (err) {+ // Old flat chat files were written in place, so a crash could leave+ // 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.+ const corruptPath = this.corruptLegacyChatFilePath(agentRef, chatId)+ await fs.mkdir(dirname(corruptPath), { recursive: true, mode: 0o700 })+ await fs.rename(this.chatFilePath(agentRef, chatId), corruptPath)+ return null+ }+ }++ /**+ * Keep a bounded v2 flat-file window for pre-paging desktop builds.+ *+ * Rewriting this fixed-size window preserves downgrade readability without+ * restoring the old unbounded whole-conversation write cost. The server+ * remains the source of truth for older synced turns.+ */+ private legacyCompatibilitySnapshot(+ chatId: string,+ messages: ChatMessage[]+ ): { file: ChatFile; signature: string } {+ const compatibilityMessages = messages.slice(-LEGACY_COMPATIBILITY_MESSAGE_LIMIT)+ const file: ChatFile = {+ version: 2,+ chatId,+ messages: compatibilityMessages,+ }+ const signature = createHash('sha256')+ .update(JSON.stringify([chatId, compatibilityMessages]))+ .digest('hex')+ return { file, signature }+ }++ private async writeLegacyCompatibilitySnapshot(+ agentRef: string,+ chatId: string,+ messages: ChatMessage[]+ ): Promise<string> {+ const { file, signature } = this.legacyCompatibilitySnapshot(chatId, messages)+ await this.writeJsonAtomic(this.chatFilePath(agentRef, chatId), file)+ await this.writeJsonAtomic(this.chatCompatibilitySignaturePath(agentRef, chatId), {+ signature,+ })+ this.cacheCompatibilityWindow(this.chatSnapshotCleanupKey(agentRef, chatId), file.messages)+ return signature+ }++ private async readLegacyCompatibilitySignature(+ agentRef: string,+ chatId: string+ ): Promise<string | null> {+ try {+ const raw = await fs.readFile(this.chatCompatibilitySignaturePath(agentRef, chatId), 'utf-8')+ const parsed = JSON.parse(raw) as { signature?: unknown }+ return typeof parsed.signature === 'string' ? parsed.signature : null+ } catch {+ return null+ }+ }++ private async refreshLegacyCompatibilitySnapshotUnlocked(+ agentRef: string,+ chatId: string,+ meta: PagedChatMeta+ ): Promise<PagedChatMeta> {+ const compatibilityMessages = await this.readMessagesFromPagedMeta(+ agentRef,+ chatId,+ meta,+ LEGACY_COMPATIBILITY_MESSAGE_LIMIT+ )+ const signature = await this.writeLegacyCompatibilitySnapshot(+ agentRef,+ chatId,+ compatibilityMessages+ )+ const refreshed = { ...meta, legacyCompatibilitySignature: signature }+ await this.writePagedMeta(agentRef, chatId, refreshed)+ return refreshed+ }++ /**+ * A downgraded build may append local messages to the v2 compatibility file.+ * Import only messages missing from the paged snapshot before refreshing the+ * bounded window, so upgrading again cannot discard offline work.+ */+ private async importDowngradedLocalMessagesUnlocked(+ agentRef: string,+ chatId: string,+ meta: PagedChatMeta+ ): Promise<PagedChatMeta> {+ const compatibilityKey = this.chatSnapshotCleanupKey(agentRef, chatId)+ let legacyMessages: ChatMessage[] | null+ try {+ legacyMessages = await this.readLegacyMessages(agentRef, chatId)+ } catch (error) {+ if (isRawFilesystemError(error)) {+ console.warn(`[chatStore] Downgrade snapshot unavailable for ${chatId}:`, error)+ this.compatibilityCheckedKeys.add(compatibilityKey)+ return meta+ }+ const refreshed = await this.refreshLegacyCompatibilitySnapshotUnlocked(+ agentRef,+ chatId,+ meta+ )+ this.compatibilityCheckedKeys.add(compatibilityKey)+ return refreshed+ }+ if (!legacyMessages) {+ const refreshed = await this.refreshLegacyCompatibilitySnapshotUnlocked(+ agentRef,+ chatId,+ meta+ )+ this.compatibilityCheckedKeys.add(compatibilityKey)+ return refreshed+ }+ this.cacheCompatibilityWindow(compatibilityKey, legacyMessages)++ const legacySignature = this.legacyCompatibilitySnapshot(chatId, legacyMessages).signature+ if (legacySignature === meta.legacyCompatibilitySignature) {+ this.compatibilityCheckedKeys.add(compatibilityKey)+ return meta+ }+ const recordedSignature = await this.readLegacyCompatibilitySignature(agentRef, chatId)+ if (legacySignature === recordedSignature) {+ const refreshed = await this.refreshLegacyCompatibilitySnapshotUnlocked(+ agentRef,+ chatId,+ meta+ )+ this.compatibilityCheckedKeys.add(compatibilityKey)+ return refreshed+ }++ const existing = await this.readMessagesFromPagedMeta(agentRef, chatId, meta)+ const missing = legacyMessages.filter(+ candidate =>+ !existing.some(+ message =>+ sameReconciledMessage(candidate, message) || sameReconciledMessage(message, candidate)+ )+ )+ if (!missing.length) {+ const refreshed = await this.refreshLegacyCompatibilitySnapshotUnlocked(+ agentRef,+ chatId,+ meta+ )+ this.compatibilityCheckedKeys.add(compatibilityKey)+ return refreshed+ }++ const merged = mergeReconciledMessages(existing, missing)+ const indexedCount = await this.indexedMessageCount(agentRef, chatId)+ const imported = await this.writePagedChatUnlocked(agentRef, chatId, merged, {+ messageCount: Math.max(meta.messageCount, merged.length, indexedCount ?? 0),+ })+ await this.updateChatIndexFromMessages(agentRef, chatId, merged, {+ preserveExistingTotals: true,+ touchUpdatedAt: false,+ })+ this.compatibilityCheckedKeys.add(compatibilityKey)+ return imported+ }++ private async readPageMessages(+ agentRef: string,+ chatId: string,+ page: ChatPageEntry+ ): Promise<ChatMessage[]> {+ return this.readPageMessagesAtPath(+ chatId,+ pageNumberFromFileName(page.file),+ this.chatPagePath(agentRef, chatId, page.file)+ )+ }++ private async readPageMessagesAtPath(+ chatId: string,+ pageNumber: number,+ pagePath: string+ ): Promise<ChatMessage[]> {+ const raw = await fs.readFile(pagePath, 'utf-8')++ try {+ const parsed = JSON.parse(raw) as ChatPageFile+ if (+ parsed?.version !== PAGED_CHAT_VERSION ||+ parsed.chatId !== chatId ||+ parsed.pageNumber !== pageNumber ||+ !Array.isArray(parsed.messages)+ ) {+ throw new Error('Invalid chat page file')+ }+ return parsed.messages+ } catch (err) {+ throw new Error(`Unable to read paged chat page for ${chatId}`, { cause: err })+ }+ }++ private async writePageMessages(+ agentRef: string,+ 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 = {+ version: PAGED_CHAT_VERSION,+ chatId,+ pageNumber,+ messages,+ }+ await this.writeJsonAtomic(this.chatPagePathFromPagesDir(pagesDir, file), page)+ return pageEntry(file, messages)+ }++ private async writePagedMeta(+ agentRef: string,+ chatId: string,+ meta: PagedChatMeta+ ): Promise<void> {+ 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(+ meta: PagedChatMeta+ ): Promise<{ meta: PagedChatMeta; removedFiles: string[] }> {+ if (this.maxLocalSyncedMessages === Number.POSITIVE_INFINITY) {+ return { meta: this.finalizePagedMeta(meta), removedFiles: [] }+ }++ let localCount = meta.pages.reduce((total, page) => total + page.count, 0)+ let prunedBeforeCount = meta.prunedBeforeCount ?? 0+ const retained: ChatPageEntry[] = []+ const removedFiles: string[] = []+ for (const page of meta.pages) {+ const canPrunePage =+ page.serverSynced && localCount - page.count >= this.maxLocalSyncedMessages++ if (canPrunePage) {+ removedFiles.push(page.file)+ localCount -= page.count+ prunedBeforeCount += page.count+ continue+ }++ retained.push(page)+ // Pruning must remove only a contiguous prefix. Once a legacy/local-only+ // page is retained, deleting a later synced page would punch a permanent+ // hole in the middle of the transcript and make load-older cursors lie.+ retained.push(...meta.pages.slice(retained.length + removedFiles.length))+ break+ }++ return {+ meta: this.finalizePagedMeta({+ ...meta,+ pages: retained,+ prunedBeforeCount: prunedBeforeCount > 0 ? prunedBeforeCount : undefined,+ }),+ removedFiles,+ }+ }++ /**+ * Finish page writes that reached disk before their metadata update.+ *+ * Existing pages may contain a durable append beyond the count recorded in+ * meta.json, and newly-created pages may exist after the last referenced page.+ * Both are safe to adopt because page files are themselves written atomically.+ */+ private async adoptDurablePageWritesUnlocked(+ agentRef: string,+ chatId: string,+ meta: PagedChatMeta+ ): Promise<PagedChatMeta | null> {+ const pagesDir = this.chatPagesDirPath(agentRef, chatId)+ const repairedPages: ChatPageEntry[] = []+ let changed = false++ for (const [index, page] of meta.pages.entries()) {+ let messages: ChatMessage[]+ try {+ messages = await this.readPageMessages(agentRef, chatId, page)+ } catch (error) {+ if (isRawFilesystemError(error) && !isNotFoundError(error)) throw error+ return null+ }+ if (messages.length < page.count) return null+ if (messages.length > page.count && index !== meta.pages.length - 1) return null+ const repaired = pageEntry(page.file, messages)+ repairedPages.push(repaired)+ changed ||= repaired.count !== page.count+ }++ const referenced = new Set(repairedPages.map(page => page.file))+ const lastReferencedNumber = pageNumberFromFileName(repairedPages.at(-1)?.file ?? '')+ const entries = await fs.readdir(pagesDir).catch(() => [])+ const durableOrphans = entries+ .filter(+ file =>+ PAGE_FILE_PATTERN.test(file) &&+ !referenced.has(file) &&+ pageNumberFromFileName(file) > lastReferencedNumber+ )+ .sort((a, b) => pageNumberFromFileName(a) - pageNumberFromFileName(b))++ for (const file of durableOrphans) {+ try {+ const messages = await this.readPageMessagesAtPath(+ chatId,+ pageNumberFromFileName(file),+ this.chatPagePathFromPagesDir(pagesDir, file)+ )+ if (!messages.length) continue+ repairedPages.push(pageEntry(file, messages))+ referenced.add(file)+ changed = true+ } catch (error) {+ if (isRawFilesystemError(error) && !isNotFoundError(error)) throw error+ // Leave an invalid orphan untouched. It is not referenced by metadata,+ // so it cannot break reads and may still be useful for manual recovery.+ }+ }++ if (!changed) return meta+ const previousLocalCount = meta.pages.reduce((total, page) => total + page.count, 0)+ const nextLocalCount = repairedPages.reduce((total, page) => total + page.count, 0)+ const repaired = this.finalizePagedMeta({+ ...meta,+ messageCount: Math.max(+ meta.messageCount + Math.max(0, nextLocalCount - previousLocalCount),+ nextLocalCount + (meta.prunedBeforeCount ?? 0)+ ),+ pages: repairedPages,+ })+ await this.writePagedMeta(agentRef, chatId, repaired)+ await this.updateIndexedMessageCount(agentRef, chatId, repaired.messageCount)+ return repaired+ }++ private async updateIndexedMessageCount(+ agentRef: string,+ chatId: string,+ messageCount: number+ ): Promise<void> {+ await this.serializeIndex(agentRef, async () => {+ const index = await this.getIndex(agentRef)+ const chat = index.chats.find(candidate => candidate.id === chatId)+ if (!chat || chat.messageCount >= messageCount) return+ chat.messageCount = messageCount+ await this.saveIndex(agentRef, index)+ })+ }++ private async rebuildPagedChatFromSurvivingFilesUnlocked(+ agentRef: string,+ chatId: string+ ): Promise<boolean> {+ const pagesDir = this.chatPagesDirPath(agentRef, chatId)+ const entries = await fs.readdir(pagesDir).catch(() => [])+ const surviving: ChatMessage[] = []+ for (const file of entries+ .filter(candidate => PAGE_FILE_PATTERN.test(candidate))+ .sort((a, b) => pageNumberFromFileName(a) - pageNumberFromFileName(b))) {+ try {+ surviving.push(+ ...(await this.readPageMessagesAtPath(+ chatId,+ pageNumberFromFileName(file),+ this.chatPagePathFromPagesDir(pagesDir, file)+ ))+ )+ } catch (error) {+ if (isRawFilesystemError(error) && !isNotFoundError(error)) throw error+ // Skip only the unreadable page; readable siblings are still valuable.+ }+ }++ const legacy = await this.readLegacyMessages(agentRef, chatId).catch(error => {+ if (isRawFilesystemError(error) && !isNotFoundError(error)) throw error+ return null+ })+ const recovered = mergeReconciledMessages(surviving, legacy ?? [])+ if (!recovered.length) return false+ await this.writePagedChatUnlocked(agentRef, chatId, recovered, {+ messageCount: recovered.length,+ })+ await this.updateIndexedMessageCount(agentRef, chatId, recovered.length)+ return true+ }++ private async recoverPagedChatUnlocked(+ agentRef: string,+ chatId: string+ ): Promise<PagedChatMeta | null> {+ const activeDir = this.chatDirPath(agentRef, chatId)+ const snapshotRoot = this.chatSnapshotRootPath(agentRef, chatId)+ const cleanupKey = this.chatSnapshotCleanupKey(agentRef, chatId)+ let activeMeta: PagedChatMeta | null = null+ let activeReadError: unknown++ try {+ activeMeta = await this.readPagedMeta(agentRef, chatId)+ } catch (err) {+ if (isRawFilesystemError(err) && !isNotFoundError(err)) throw err+ activeReadError = err+ }++ if (activeMeta) {+ if (this.cleanedSnapshotSiblingKeys.has(cleanupKey)) return activeMeta+ const repaired = await this.adoptDurablePageWritesUnlocked(agentRef, chatId, activeMeta)+ if (repaired) {+ await this.removePagedChatSnapshotSiblings(agentRef, chatId)+ this.cleanedSnapshotSiblingKeys.add(cleanupKey)+ return repaired+ }+ activeReadError = new Error(`Paged chat snapshot is incomplete for ${chatId}`)+ activeMeta = null+ }++ if (!activeReadError) {+ const activeStat = await fs.stat(activeDir).catch(() => null)+ if (activeStat?.isDirectory()) {+ activeReadError = new Error(`Paged chat metadata missing for ${chatId}`)+ }+ }++ let entries: Array<{ name: string; isDirectory: () => boolean }>+ try {+ entries = await fs.readdir(snapshotRoot, { withFileTypes: true })+ } catch {+ entries = []+ }+ if (!activeReadError && entries.length === 0) return null++ const snapshots = await Promise.all(+ entries+ .filter(entry => entry.isDirectory())+ .map(async entry => {+ const nextPrefix = 'next-'+ const previousPrefix = 'previous-'+ const kind = entry.name.startsWith(nextPrefix)+ ? 'next'+ : entry.name.startsWith(previousPrefix)+ ? 'previous'+ : null+ if (!kind) return null+ const token =+ kind === 'next'+ ? entry.name.slice(nextPrefix.length)+ : entry.name.slice(previousPrefix.length)+ if (!token) return null+ const dir = join(snapshotRoot, entry.name)+ const meta = await this.readPagedMetaAtPath(+ this.chatMetaPathFromChatDir(dir),+ chatId+ ).catch(() => null)+ if (!meta || !(await this.isCompletePagedSnapshot(dir, chatId, meta))) return null+ const stat = await fs.stat(dir).catch(() => null)+ return {+ dir,+ kind,+ token,+ mtimeMs: stat?.mtimeMs ?? 0,+ }+ })+ )+ const validSnapshots = snapshots+ .filter((snapshot): snapshot is SnapshotCandidate => snapshot !== null)+ .sort((a, b) => b.mtimeMs - a.mtimeMs)++ const groups = new Map<+ string,+ { next?: SnapshotCandidate; previous?: SnapshotCandidate; mtimeMs: number }+ >()+ for (const snapshot of validSnapshots) {+ const group = groups.get(snapshot.token) ?? { mtimeMs: 0 }+ group[snapshot.kind] = snapshot+ group.mtimeMs = Math.max(group.mtimeMs, snapshot.mtimeMs)+ groups.set(snapshot.token, group)+ }+ const candidates = [...groups.values()]+ .sort((a, b) => b.mtimeMs - a.mtimeMs)+ .map(group => group.next ?? group.previous)+ .filter((snapshot): snapshot is SnapshotCandidate => Boolean(snapshot))++ for (const snapshot of candidates) {+ let corruptDir: string | null = null+ try {+ if (activeReadError) {+ corruptDir = this.chatSnapshotSiblingPath(agentRef, chatId, 'corrupt', randomUUID())+ await fs.rename(activeDir, corruptDir).catch(err => {+ if (!isNotFoundError(err)) throw err+ })+ } else {+ await fs.rm(activeDir, { recursive: true, force: true })+ }+ await fs.rename(snapshot.dir, activeDir)+ await this.removePagedChatSnapshotSiblings(agentRef, chatId)+ if (corruptDir) {+ await fs.rm(corruptDir, { recursive: true, force: true }).catch(() => undefined)+ }+ this.cleanedSnapshotSiblingKeys.add(cleanupKey)+ return await this.readPagedMeta(agentRef, chatId)+ } catch (err) {+ if (corruptDir) {+ await fs.rename(corruptDir, activeDir).catch(() => undefined)+ }+ // Try the next complete snapshot, if one exists.+ }+ }++ if (await this.rebuildPagedChatFromSurvivingFilesUnlocked(agentRef, chatId)) {+ this.cleanedSnapshotSiblingKeys.add(cleanupKey)+ return await this.readPagedMeta(agentRef, chatId)+ }+ 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+ }++ private async removePagedChatSnapshotSiblings(agentRef: string, chatId: string): Promise<void> {+ await fs.rm(this.chatSnapshotRootPath(agentRef, chatId), {+ recursive: true,+ force: true,+ })+ }++ private async isCompletePagedSnapshot(+ chatDir: string,+ chatId: string,+ meta: PagedChatMeta+ ): Promise<boolean> {+ const pagesDir = this.chatPagesDirFromChatDir(chatDir)+ for (const page of meta.pages) {+ try {+ const messages = await this.readPageMessagesAtPath(+ chatId,+ pageNumberFromFileName(page.file),+ this.chatPagePathFromPagesDir(pagesDir, page.file)+ )+ if (messages.length !== page.count) return false+ } catch {+ return false+ }+ }+ return true+ }++ private async writePagedChatUnlocked(+ agentRef: string,+ chatId: string,+ messages: ChatMessage[],+ options: { messageCount?: number } = {}+ ): Promise<PagedChatMeta> {+ const chatDir = this.chatDirPath(agentRef, chatId)+ 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++ this.cleanedSnapshotSiblingKeys.delete(this.chatSnapshotCleanupKey(agentRef, chatId))+ 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, mode: 0o700 })++ 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 pruned = await this.pruneSyncedPages(+ this.finalizePagedMeta({+ version: PAGED_CHAT_VERSION,+ chatId,+ pageSize: this.pageSize,+ messageCount: Math.max(messages.length, options.messageCount ?? 0),+ localMessageCount: messages.length,+ pages,+ })+ )+ const compatibility = this.legacyCompatibilitySnapshot(chatId, messages)+ pruned.meta.legacyCompatibilitySignature = compatibility.signature+ await this.writePagedMetaToDir(chatId, stagingDir, pruned.meta)+ await Promise.all(+ pruned.removedFiles.map(file =>+ fs.rm(this.chatPagePathFromPagesDir(pagesDir, file), { 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)+ }+ await this.writeLegacyCompatibilitySnapshot(agentRef, chatId, messages)+ const cacheKey = this.chatSnapshotCleanupKey(agentRef, chatId)+ this.cleanedSnapshotSiblingKeys.add(cacheKey)+ this.compatibilityCheckedKeys.add(cacheKey)++ return pruned.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> {+ const paged = await this.recoverPagedChatUnlocked(agentRef, chatId)+ if (paged) {+ if (this.compatibilityCheckedKeys.has(this.chatSnapshotCleanupKey(agentRef, chatId))) {+ return paged+ }+ return this.importDowngradedLocalMessagesUnlocked(agentRef, chatId, paged)+ }++ const legacyMessages = await this.readLegacyMessages(agentRef, chatId)+ if (!legacyMessages) return null++ const migrated = await this.writePagedChatUnlocked(agentRef, chatId, legacyMessages)+ await this.updateChatIndexFromMessages(agentRef, chatId, legacyMessages, {+ touchUpdatedAt: false,+ })+ return migrated+ }++ private async readMessagesFromPagedMeta(+ agentRef: string,+ chatId: string,+ meta: PagedChatMeta,+ limit?: number,+ offset?: number+ ): Promise<ChatMessage[]> {+ const localCount = meta.pages.reduce((total, page) => total + page.count, 0)+ if (localCount === 0) return []++ const effectiveOffset = Math.max(0, Math.floor(offset ?? 0))+ const end = Math.max(0, localCount - effectiveOffset)+ if (end === 0) return []++ const effectiveLimit = limit === undefined ? end : Math.max(0, Math.floor(limit))+ if (effectiveLimit === 0) return []++ const start = Math.max(0, end - effectiveLimit)+ const result: ChatMessage[] = []+ let cursor = 0++ for (const page of meta.pages) {+ const pageStart = cursor+ const pageEnd = cursor + page.count+ cursor = pageEnd++ const overlapStart = Math.max(start, pageStart)+ const overlapEnd = Math.min(end, pageEnd)+ if (overlapStart >= overlapEnd) continue++ const pageMessages = await this.readPageMessages(agentRef, chatId, page)+ result.push(...pageMessages.slice(overlapStart - pageStart, overlapEnd - pageStart))+ }++ return result+ }++ private async appendPagedMessagesUnlocked(+ agentRef: string,+ chatId: string,+ meta: PagedChatMeta,+ newMessages: ChatMessage[]+ ): Promise<PagedChatMeta> {+ if (!newMessages.length) return meta++ const cacheKey = this.chatSnapshotCleanupKey(agentRef, chatId)+ this.cleanedSnapshotSiblingKeys.delete(cacheKey)+ const pages = [...meta.pages]+ let remaining = [...newMessages]++ const lastPage = pages.at(-1)+ if (lastPage && lastPage.count < this.pageSize) {+ const currentMessages = await this.readPageMessages(agentRef, chatId, lastPage)+ const capacity = Math.max(0, this.pageSize - currentMessages.length)+ if (capacity > 0) {+ const added = remaining.slice(0, capacity)+ remaining = remaining.slice(added.length)+ pages[pages.length - 1] = await this.writePageMessages(+ agentRef,+ chatId,+ pageNumberFromFileName(lastPage.file),+ [...currentMessages, ...added]+ )+ }+ }++ let nextPageNumber = pageNumberFromFileName(pages.at(-1)?.file ?? '') + 1+ while (remaining.length) {+ const pageMessages = remaining.slice(0, this.pageSize)+ remaining = remaining.slice(pageMessages.length)+ pages.push(await this.writePageMessages(agentRef, chatId, nextPageNumber, pageMessages))+ nextPageNumber += 1+ }++ const messageCount =+ Math.max(meta.messageCount, meta.localMessageCount ?? 0) + newMessages.length+ const pruned = await this.pruneSyncedPages({+ ...meta,+ messageCount,+ pages,+ })+ const cachedCompatibilityMessages = this.compatibilityWindows.get(cacheKey)+ const compatibilityMessages = cachedCompatibilityMessages+ ? [...cachedCompatibilityMessages, ...newMessages].slice(-LEGACY_COMPATIBILITY_MESSAGE_LIMIT)+ : await this.readMessagesFromPagedMeta(+ agentRef,+ chatId,+ pruned.meta,+ LEGACY_COMPATIBILITY_MESSAGE_LIMIT+ )+ const compatibility = this.legacyCompatibilitySnapshot(chatId, compatibilityMessages)+ pruned.meta.legacyCompatibilitySignature = compatibility.signature+ await this.writePagedMeta(agentRef, chatId, pruned.meta)+ await Promise.all(+ pruned.removedFiles.map(file =>+ fs.rm(this.chatPagePath(agentRef, chatId, file), { force: true })+ )+ )+ if (compatibility.signature !== meta.legacyCompatibilitySignature) {+ await this.writeLegacyCompatibilitySnapshot(agentRef, chatId, compatibilityMessages)+ }+ this.cleanedSnapshotSiblingKeys.add(cacheKey)+ this.compatibilityCheckedKeys.add(cacheKey)+ return pruned.meta+ }+async getIndex(agentRef: string): Promise<ChatIndex> {try {const raw = await fs.readFile(this.indexPath(agentRef), 'utf-8')const parsed = JSON.parse(raw) as ChatIndex- // Version-agnostic read: legacy (v1) dirs are removed at bind time by the- // bootstrap wipe (chatStoreBinding), so any index we read here is current;- // saveIndex normalizes the stored version to v2 on the next write.+ // Version-agnostic read: legacy directories are handled at bind time by+ // chatStoreBinding. saveIndex normalizes v3 indexes produced by earlier+ // paging builds back to the v2 downgrade-compatible catalog schema.if (parsed && Array.isArray(parsed.chats)) {return parsed}@@ -85,12 +1268,13 @@ export class ChatStore {private async saveIndex(agentRef: string, index: ChatIndex): Promise<void> {const dir = this.agentDir(agentRef)- await fs.mkdir(dir, { recursive: true })- // Always persist at the current schema version so a read-back never looks legacy.+ 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 }// Atomic write (temp + rename): a crash mid-write must never leave a// truncated index.json, because the bootstrap wipe treats an unparseable- // index as legacy and would delete live v2 chats.+ // index as legacy and would delete live paged chats.const target = this.indexPath(agentRef)const tmp = `${target}.tmp`await fs.writeFile(tmp, JSON.stringify(normalized, null, 2), { mode: 0o600 })@@ -155,18 +1339,33 @@ export class ChatStore {}async deleteChat(agentRef: string, chatId: string): Promise<void> {- return this.serializeIndex(agentRef, async () => {- const index = await this.getIndex(agentRef)- index.chats = index.chats.filter(c => c.id !== chatId)- if (index.lastActiveChatId === chatId) {- index.lastActiveChatId = null- }- await this.saveIndex(agentRef, index)- try {- await fs.unlink(this.chatFilePath(agentRef, chatId))- } catch {- // file may not exist- }+ return this.serializeChat(agentRef, chatId, async () => {+ await this.serializeIndex(agentRef, async () => {+ const index = await this.getIndex(agentRef)+ index.chats = index.chats.filter(c => c.id !== chatId)+ if (index.lastActiveChatId === chatId) {+ index.lastActiveChatId = null+ }+ await this.saveIndex(agentRef, index)+ })+ await fs.rm(this.chatFilePath(agentRef, chatId), { force: true })+ const corruptLegacyDir = join(this.agentDir(agentRef), '.corrupt')+ await fs.rm(join(corruptLegacyDir, encodedChatId(chatId)), { recursive: true, force: true })+ const corruptLegacyEntries = await fs.readdir(corruptLegacyDir).catch(() => [])+ await Promise.all(+ corruptLegacyEntries+ .filter(name => legacyCorruptFileBelongsToChat(name, chatId))+ .map(name => fs.rm(join(corruptLegacyDir, name), { force: true }))+ )+ await fs.rm(`${this.chatFilePath(agentRef, chatId)}.tmp`, { force: true })+ await fs.rm(this.chatCompatibilitySignaturePath(agentRef, chatId), { force: true })+ await fs.rm(`${this.chatCompatibilitySignaturePath(agentRef, chatId)}.tmp`, { 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.dropCompatibilityWindow(cacheKey)})}@@ -177,55 +1376,145 @@ export class ChatStore {offset?: number): Promise<ChatMessage[]> {try {- const raw = await fs.readFile(this.chatFilePath(agentRef, chatId), 'utf-8')- const file = JSON.parse(raw) as ChatFile- if (!file || !Array.isArray(file.messages)) return []-- const messages = file.messages- if (limit === undefined && offset === undefined) return messages-- const effectiveOffset = offset ?? 0- const start = Math.max(0, messages.length - effectiveOffset - (limit ?? messages.length))- const end = messages.length - effectiveOffset- return messages.slice(start, end)- } catch {- return []+ return await this.serializeChat(agentRef, chatId, async () => {+ const meta = await this.readOrMigratePagedChatUnlocked(agentRef, chatId)+ if (!meta) return []+ return this.readMessagesFromPagedMeta(agentRef, chatId, meta, limit, offset)+ })+ } catch (err) {+ if (isUnsafeSegmentError(err)) return []+ throw err}}- async saveMessages(agentRef: string, chatId: string, messages: ChatMessage[]): Promise<void> {- return this.serializeIndex(agentRef, async () => {- const dir = this.agentDir(agentRef)- await fs.mkdir(dir, { recursive: true })- const file: ChatFile = { version: 2, chatId, messages }- await fs.writeFile(this.chatFilePath(agentRef, chatId), JSON.stringify(file), { mode: 0o600 })-+ private async updateChatIndexFromMessages(+ agentRef: string,+ chatId: string,+ messages: ChatMessage[],+ options: { preserveExistingTotals?: boolean; touchUpdatedAt?: boolean } = {}+ ): Promise<void> {+ await this.serializeIndex(agentRef, async () => {const index = await this.getIndex(agentRef)const chat = index.chats.find(c => c.id === chatId)- if (chat) {- chat.messageCount = messages.length+ if (!chat) return++ const aggregate = aggregateMessages(messages)+ const displayMessageCount = visibleMessageCount(messages)+ if (options.preserveExistingTotals) {+ 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 = displayMessageCount+ Object.assign(chat, aggregate)+ }+ if (options.touchUpdatedAt !== false) {chat.updatedAt = new Date().toISOString()- await this.saveIndex(agentRef, index)}+ await this.saveIndex(agentRef, index)})}- async appendMessages(+ private async indexedMessageCount(agentRef: string, chatId: string): Promise<number | undefined> {+ try {+ const index = await this.getIndex(agentRef)+ return index.chats.find(chat => chat.id === chatId)?.messageCount+ } catch {+ return undefined+ }+ }++ private async saveMessagesInternal(agentRef: string,chatId: string,- newMessages: ChatMessage[]+ messages: ChatMessage[],+ options: { preserveExistingTotals?: boolean } = {}): Promise<void> {- const existing = await this.loadMessages(agentRef, chatId)- await this.saveMessages(agentRef, chatId, [...existing, ...newMessages])+ return this.serializeChat(agentRef, chatId, async () => {+ const indexedCount = options.preserveExistingTotals+ ? await this.indexedMessageCount(agentRef, chatId)+ : undefined+ await this.writePagedChatUnlocked(agentRef, chatId, messages, {+ messageCount: Math.max(messages.length, indexedCount ?? 0),+ })++ await this.updateChatIndexFromMessages(agentRef, chatId, messages, {+ preserveExistingTotals: options.preserveExistingTotals,+ })+ })+ }++ async saveMessages(agentRef: string, chatId: string, messages: ChatMessage[]): Promise<void> {+ return this.saveMessagesInternal(agentRef, chatId, messages)}/**- * Overwrite a chat's entire history (D.4 reconcile: the server is the source- * of truth, so on a diff the server's turns replace the local cache). Same- * on-disk effect as `saveMessages`, named for the reconcile intent.+ * Upsert a server reconciliation window without truncating unseen history.+ *+ * Reconciliation is intentionally bounded, while the local store may contain+ * older pages or optimistic messages that are not present in that window.+ * Merge the window into the complete local snapshot before publishing a new+ * generation so a background reconcile cannot discard either category.*/- async replaceMessages(agentRef: string, chatId: string, messages: ChatMessage[]): Promise<void> {- await this.saveMessages(agentRef, chatId, messages)+ 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, {+ 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),+ })+ await this.updateChatIndexFromMessages(agentRef, chatId, merged, {+ preserveExistingTotals: true,+ })+ })+ }++ async backfillChatCounters(+ agentRef: string,+ chatId: string,+ messages: ChatMessage[]+ ): Promise<void> {+ await this.updateChatIndexFromMessages(agentRef, chatId, messages, {+ preserveExistingTotals: true,+ touchUpdatedAt: false,+ })+ }++ async appendMessages(+ agentRef: string,+ chatId: string,+ newMessages: ChatMessage[]+ ): Promise<void> {+ return this.serializeChat(agentRef, chatId, async () => {+ const existing =+ (await this.readOrMigratePagedChatUnlocked(agentRef, chatId)) ??+ (await this.writePagedChatUnlocked(agentRef, chatId, []))+ const meta = await this.appendPagedMessagesUnlocked(agentRef, chatId, existing, newMessages)++ await this.serializeIndex(agentRef, async () => {+ const index = await this.getIndex(agentRef)+ const chat = index.chats.find(c => c.id === chatId)+ if (chat) {+ const delta = aggregateMessages(newMessages)+ chat.messageCount = meta.messageCount+ chat.errorCount = (chat.errorCount ?? 0) + (delta.errorCount ?? 0)+ chat.toolCallCount = (chat.toolCallCount ?? 0) + (delta.toolCallCount ?? 0)+ chat.updatedAt = new Date().toISOString()+ await this.saveIndex(agentRef, index)+ }+ })+ })}/**diff --git a/desktop-app/src/chatStoreBinding.ts b/desktop-app/src/chatStoreBinding.tsindex 15a96f197..6e4e3c016 100644--- a/desktop-app/src/chatStoreBinding.ts+++ b/desktop-app/src/chatStoreBinding.ts@@ -3,8 +3,13 @@ import { promises as fs } from 'node:fs'import { join } from 'node:path'import { ChatStore } from './chatStore.js'-/** Current persisted chat schema. Anything older is wiped on bind (§7.1). */+/**+ * Keep the shared catalog at v2 so pre-paging desktop builds can read the+ * bounded compatibility snapshots. Paged transcripts version their own files.+ */const SCHEMA_VERSION = 2+const PREVIOUS_PAGED_INDEX_VERSION = 3+const CORRUPT_QUARANTINE_RETENTION_MS = 30 * 24 * 60 * 60 * 1000// Default base dir derived from Electron's userData path. Tests override via// __setChatStoreBaseDirForTests to point at a tmpdir, which means the@@ -19,6 +24,7 @@ let activeChatStore: ChatStore | null = nulllet activeUserId: string | null = nulllet activeEnvKey: string | null = nulllet bindInFlight: { key: string; promise: Promise<void> } | null = null+let bindingGeneration = 0/** Marker file (per base dir) that records the pre-`envKey` legacy wipe ran. */const PRE_ENV_MIGRATION_MARKER = '.env-scoped'@@ -44,9 +50,16 @@ function assertSafeSegment(label: string, value: string): void {* first; the desktop is a cache of the server (spec §3.5, §7.1), so a stale* directory is dropped and re-hydrated from the source of truth.*/-export async function bindChatStoreForUser(userId: string, envKey: string): Promise<void> {+export async function bindChatStoreForUser(+ userId: string,+ envKey: string,+ options: { legacyEnvKeys?: readonly string[] } = {}+): Promise<void> {assertSafeSegment('userId', userId)assertSafeSegment('envKey', envKey)+ for (const legacyEnvKey of options.legacyEnvKeys ?? []) {+ assertSafeSegment('legacyEnvKey', legacyEnvKey)+ }// Re-binding the same (env, user) is a no-op. Team switches and access-catalog// refreshes re-call this with an unchanged `me.id`; tearing the store down// just to rebuild it opens a window where every concurrent chat IPC fails@@ -54,6 +67,7 @@ export async function bindChatStoreForUser(userId: string, envKey: string): Promif (activeChatStore && activeUserId === userId && activeEnvKey === envKey) returnconst bindKey = `${envKey}::${userId}`if (bindInFlight?.key === bindKey) return bindInFlight.promise+ const generation = ++bindingGenerationconst promise = (async () => {// bind is async (it awaits a directory wipe); until it completes,@@ -65,8 +79,11 @@ export async function bindChatStoreForUser(userId: string, envKey: string): Prom// One-shot: drop the pre-`envKey` cache tree (no env level) before rooting// the env-scoped store. Safe to discard — the server rebuilds it (spec §5.5).await maybeWipePreEnvLegacyCache(baseDir)+ await maybeMigrateEnvScopedCache(baseDir, userId, envKey, options.legacyEnvKeys ?? [])const userDir = join(baseDir, envKey, userId)await maybeWipeLegacyCache(userDir)+ await sweepExpiredCorruptQuarantines(userDir)+ if (generation !== bindingGeneration) returnactiveChatStore = new ChatStore(userDir)activeUserId = userIdactiveEnvKey = envKey@@ -79,6 +96,49 @@ export async function bindChatStoreForUser(userId: string, envKey: string): Prom}}+/**+ * One-shot rename from older env-key namespaces into the current env-key+ * namespace. This preserves local chat pages when only the env-key derivation+ * changed, e.g. REST-only key → REST+RPC key.+ */+async function maybeMigrateEnvScopedCache(+ baseDir: string,+ userId: string,+ envKey: string,+ legacyEnvKeys: readonly string[]+): Promise<void> {+ const candidates = Array.from(+ new Set(legacyEnvKeys.map(key => String(key || '').trim()).filter(key => key && key !== envKey))+ )+ if (!candidates.length) return++ const targetDir = join(baseDir, envKey, userId)+ try {+ await fs.access(targetDir)+ return+ } catch {+ // target absent → a legacy env-scoped cache may be migrated below+ }++ for (const legacyEnvKey of candidates) {+ const sourceDir = join(baseDir, legacyEnvKey, userId)+ try {+ await fs.access(sourceDir)+ } catch {+ continue+ }+ await fs.mkdir(join(baseDir, envKey), { recursive: true, mode: 0o700 })+ try {+ await fs.rename(sourceDir, targetDir)+ console.info(`[chatStore] Migrated chat cache from legacy env key "${legacyEnvKey}"`)+ return+ } catch (err) {+ if ((err as NodeJS.ErrnoException).code === 'EEXIST') return+ throw err+ }+ }+}+/*** One-shot wipe of the pre-`envKey` cache layout (spec §5.5, D3). Before this* feature the tree was `<base>/<userId>/<agentRef>/index.json`; it is now@@ -107,7 +167,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}@@ -177,7 +237,28 @@ async function maybeWipeLegacyCache(userDir: string): Promise<void> {try {const raw = await fs.readFile(indexPath, 'utf-8')const parsed = JSON.parse(raw) as { version?: number }- isLegacy = parsed.version !== SCHEMA_VERSION+ if (parsed.version === PREVIOUS_PAGED_INDEX_VERSION) {+ // A parsed v3 catalog is valid even if the compatibility-marker rewrite+ // fails. Keep the cache and retry the atomic normalization next launch.+ isLegacy = false+ const migratedIndexPath = `${indexPath}.v2.tmp`+ try {+ await fs.writeFile(+ migratedIndexPath,+ JSON.stringify({ ...parsed, version: SCHEMA_VERSION }, null, 2),+ { mode: 0o600 }+ )+ await fs.rename(migratedIndexPath, indexPath)+ } catch (error) {+ await fs.rm(migratedIndexPath, { force: true }).catch(() => undefined)+ console.warn(+ `[chatStore] Failed to normalize v3 index for "${entry.name}"; retrying next launch`,+ error+ )+ }+ } else {+ isLegacy = parsed.version !== SCHEMA_VERSION+ }} catch {// index.json missing or unparseable → treat as legacyisLegacy = true@@ -191,7 +272,58 @@ async function maybeWipeLegacyCache(userDir: string): Promise<void> {}}+/**+ * Corrupt snapshots preserve recoverable local work, but they also retain full+ * transcript content. Keep recent quarantines for downgrade/crash recovery and+ * remove abandoned copies after a bounded retention window on each bind.+ */+async function sweepExpiredCorruptQuarantines(userDir: string, nowMs = Date.now()): Promise<void> {+ const agentEntries = await fs.readdir(userDir, { withFileTypes: true }).catch(() => [])+ await Promise.all(+ agentEntries+ .filter(entry => entry.isDirectory())+ .map(async entry => {+ const agentDir = join(userDir, entry.name)+ await removeExpiredQuarantineEntries(join(agentDir, '.corrupt'), () => true, nowMs)++ const snapshotRoot = join(agentDir, 'chats', '.snapshots')+ const chatEntries = await fs.readdir(snapshotRoot, { withFileTypes: true }).catch(() => [])+ await Promise.all(+ chatEntries+ .filter(chatEntry => chatEntry.isDirectory())+ .map(chatEntry =>+ removeExpiredQuarantineEntries(+ join(snapshotRoot, chatEntry.name),+ name => name.startsWith('corrupt-'),+ nowMs+ )+ )+ )+ })+ )+}++async function removeExpiredQuarantineEntries(+ directory: string,+ shouldRemove: (name: string) => boolean,+ nowMs: number+): Promise<void> {+ const entries = await fs.readdir(directory, { withFileTypes: true }).catch(() => [])+ await Promise.all(+ entries+ .filter(entry => shouldRemove(entry.name))+ .map(async entry => {+ const target = join(directory, entry.name)+ const stat = await fs.lstat(target).catch(() => null)+ if (!stat || nowMs - stat.mtimeMs < CORRUPT_QUARANTINE_RETENTION_MS) return+ await fs.rm(target, { recursive: entry.isDirectory(), force: true }).catch(() => undefined)+ })+ )+}+export function unbindChatStore(): void {+ bindingGeneration += 1+ bindInFlight = nullactiveChatStore = nullactiveUserId = nullactiveEnvKey = nulldiff --git a/desktop-app/src/config.ts b/desktop-app/src/config.tsindex e749daf3e..b3c072fc1 100644--- a/desktop-app/src/config.ts+++ b/desktop-app/src/config.ts@@ -120,6 +120,11 @@ function loadPackagedEnv(): void {loadPackagedEnv()+function explicitRuntimeConfigPath(): string {+ if (app?.isPackaged) return ''+ return process.env.CLERUM_DESKTOP_CONFIG_PATH?.trim() || ''+}+function requiredOrDefault(name: string, fallback: string): string {const value = process.env[name]?.trim()return value || fallback@@ -164,7 +169,7 @@ function deriveProfileUiBaseUrl(externalRestApiBaseUrl: string): string {}function runtimeConfigDirectoryPath(): string {- const explicit = process.env.CLERUM_DESKTOP_CONFIG_PATH?.trim()+ const explicit = explicitRuntimeConfigPath()if (explicit) return path.dirname(explicit)if (app?.isReady()) {@@ -277,7 +282,7 @@ function loadStoredProfilesSync(): {profiles: StoredRuntimeProfile[]activeProfileId: string | null} {- const explicitPath = process.env.CLERUM_DESKTOP_CONFIG_PATH?.trim()+ const explicitPath = explicitRuntimeConfigPath()if (explicitPath) {const configFromFile = readRuntimeConfigFileSync(explicitPath)if (!configFromFile) return { profiles: [], activeProfileId: null }@@ -337,12 +342,17 @@ function loadStoredProfilesSync(): {function configsMatch(a: DesktopRuntimeConfig, b: DesktopRuntimeConfig): boolean {return (- a.externalRestApiBaseUrl === b.externalRestApiBaseUrl &&- a.rpcProxyBaseUrl === b.rpcProxyBaseUrl &&+ runtimeEndpointsMatch(a, b) &&(a.appName?.trim() || DEFAULT_APP_NAME) === (b.appName?.trim() || DEFAULT_APP_NAME))}+function runtimeEndpointsMatch(a: DesktopRuntimeConfig, b: DesktopRuntimeConfig): boolean {+ return (+ a.externalRestApiBaseUrl === b.externalRestApiBaseUrl && a.rpcProxyBaseUrl === b.rpcProxyBaseUrl+ )+}+function isLocalhostUrl(value: string): boolean {try {const parsed = new URL(value)@@ -407,6 +417,7 @@ function resolveActiveProfile(profiles: StoredRuntimeProfile[],activeProfileId: string | null): StoredRuntimeProfile | null {+ if (activeProfileId === LOCALHOST_OPTION_ID) return nullif (activeProfileId) {const direct = profiles.find(profile => profile.id === activeProfileId)if (direct) return direct@@ -419,7 +430,7 @@ async function persistProfilesIndex(profiles: StoredRuntimeProfile[],activeProfileId: string | null): Promise<void> {- if (process.env.CLERUM_DESKTOP_CONFIG_PATH?.trim()) return+ if (explicitRuntimeConfigPath()) returnconst directoryPath = runtimeConfigDirectoryPath()const nextIndex: RuntimeConfigIndex = {version: 1,@@ -475,25 +486,31 @@ const envRuntimeConfig = validateRuntimeConfig({rpcProxyBaseUrl: requiredOrDefault('RPC_PROXY_BASE_URL', LOCALHOST_RPC_PROXY_BASE_URL),appName: requiredOrDefault('DESKTOP_APP_NAME', DEFAULT_APP_NAME),})+const desktopDevPackageRuntimeConfigEnabled =+ process.argv.includes('--evenfire-desktop-dev-package') &&+ runtimeEndpointsMatch(envRuntimeConfig, localhostRuntimeConfig)+const canUseEnvRuntimeConfig = !app?.isPackaged || desktopDevPackageRuntimeConfigEnabledconst envRuntimeConfigured = Boolean(- !app?.isPackaged &&+ canUseEnvRuntimeConfig &&process.env.EXTERNAL_REST_API_BASE_URL?.trim() &&process.env.RPC_PROXY_BASE_URL?.trim())-const envMatchesLocalhostOption = configsMatch(envRuntimeConfig, localhostRuntimeConfig)+const envMatchesLocalhostOption = runtimeEndpointsMatch(envRuntimeConfig, localhostRuntimeConfig)function shouldPreferLocalhostByDefault(): boolean {- return (- !app?.isPackaged &&- Boolean(process.env.EVENFIRE_RENDERER_URL?.trim()) &&- envMatchesLocalhostOption- )+ return canUseEnvRuntimeConfig && envRuntimeConfigured && envMatchesLocalhostOption}const loadedProfilesState = loadStoredProfilesSync()let storedProfiles = loadedProfilesState.profiles-let activeRuntimeOptionId = loadedProfilesState.activeProfileId-const activeStoredProfile = resolveActiveProfile(storedProfiles, activeRuntimeOptionId)+const preferLocalhostRuntimeByDefault = shouldPreferLocalhostByDefault()+let activeRuntimeOptionId = preferLocalhostRuntimeByDefault+ ? LOCALHOST_OPTION_ID+ : loadedProfilesState.activeProfileId+const activeStoredProfile = preferLocalhostRuntimeByDefault+ ? null+ : resolveActiveProfile(storedProfiles, activeRuntimeOptionId)if (+ !preferLocalhostRuntimeByDefault &&!activeStoredProfile &&activeRuntimeOptionId !== LOCALHOST_OPTION_ID &&envRuntimeConfigured &&@@ -549,7 +566,12 @@ export function hydrateDesktopRuntimeConfig(): void {const loaded = loadStoredProfilesSync()storedProfiles = loaded.profiles- activeRuntimeOptionId = loaded.activeProfileId+ const preserveLocalhostRuntime =+ preferLocalhostRuntimeByDefault ||+ (desktopDevPackageRuntimeConfigEnabled &&+ envMatchesLocalhostOption &&+ isLocalhostRuntimeConfig(currentRuntimeConfig()))+ activeRuntimeOptionId = preserveLocalhostRuntime ? LOCALHOST_OPTION_ID : loaded.activeProfileIdconst selectedProfile = resolveActiveProfile(storedProfiles, activeRuntimeOptionId)if (selectedProfile) {@@ -592,7 +614,7 @@ export function isDesktopRuntimeConfigured(): boolean {export async function saveDesktopRuntimeConfig(next: DesktopRuntimeConfig): Promise<void> {hydrateDesktopRuntimeConfig()const validated = validateRuntimeConfig(next)- const explicitPath = process.env.CLERUM_DESKTOP_CONFIG_PATH?.trim()+ const explicitPath = explicitRuntimeConfigPath()if (explicitPath) {const timestamp = new Date().toISOString()const existing = storedProfiles.find(profile => profile.id === 'custom-file')@@ -650,36 +672,49 @@ export async function saveDesktopRuntimeConfig(next: DesktopRuntimeConfig): Prom/*** Derive the environment namespacing key from a runtime config's external-rest-api- * base URL (spec §5.1, D1). Semantically "one environment = one external-rest-api- * origin": `new URL(url).origin` includes scheme + host + port, so- * `https://api.dev…` and `https://api.prod…` (or `:8091` vs `:8092`) key apart- * automatically, and `rpcProxyBaseUrl` is deliberately NOT mixed in.+ * and rpc-proxy base origins (spec §5.1, D1). Same REST origin + different RPC+ * origin is a different runtime boundary because desktop session tokens are+ * accepted by the RPC proxy, not by external-rest-api alone.*- * The raw origin is not filesystem/keychain-safe (it carries `://`, `:`), so we+ * The raw identity is not filesystem/keychain-safe (it carries `://`, `:`), so we* emit a stable, collision-resistant slug: a lowercase `scheme_host_port`- * fragment for human debuggability, suffixed with a 12-hex sha256 of the origin- * so distinct origins can never collide even when the slug is truncated. Purely a- * function of the origin ⇒ deterministic and stable across restarts.+ * fragment for human debuggability, suffixed with a 12-hex sha256 of the full+ * identity so distinct origins can never collide even when the slug is truncated.*/-export function resolveEnvKey(externalRestApiBaseUrl: string): string {- const raw = String(externalRestApiBaseUrl || '').trim()- let origin: string+function resolveOriginKeyPart(value: string): string {+ const raw = String(value || '').trim()try {- origin = new URL(raw).origin+ return new URL(raw).origin} catch {- origin = raw || 'unknown'+ return raw || 'unknown'}- const slug = origin+}++export function resolveEnvKey(externalRestApiBaseUrl: string, rpcProxyBaseUrl = ''): string {+ const restOrigin = resolveOriginKeyPart(externalRestApiBaseUrl)+ const rpcOrigin = rpcProxyBaseUrl.trim() ? resolveOriginKeyPart(rpcProxyBaseUrl) : ''+ const identity = rpcOrigin ? `${restOrigin}|rpc=${rpcOrigin}` : restOrigin+ const slugSource = rpcOrigin ? `${restOrigin}_${rpcOrigin}` : restOrigin+ const slug = slugSource.toLowerCase().replace(/[^a-z0-9]+/g, '_').replace(/^_+|_+$/g, '').slice(0, 48)- const hash = createHash('sha256').update(origin).digest('hex').slice(0, 12)+ const hash = createHash('sha256').update(identity).digest('hex').slice(0, 12)return `${slug || 'env'}-${hash}`}/** Env key for the CURRENTLY active runtime config (main-process surfaces). */export function getActiveEnvKey(): string {+ hydrateDesktopRuntimeConfig()+ return resolveEnvKey(config.externalRestApiBaseUrl, config.rpcProxyBaseUrl)+}++/**+ * Legacy env key from the pre-RPC-origin namespace. Used only for one-shot+ * upgrade migration into the current REST+RPC namespace.+ */+export function getActiveLegacyRestOnlyEnvKey(): string {hydrateDesktopRuntimeConfig()return resolveEnvKey(config.externalRestApiBaseUrl)}@@ -703,8 +738,8 @@ export function getDesktopRuntimeConfigState(): DesktopRuntimeConfigState {isLocalhost,selectorVisible,activeOptionId,- envKey: resolveEnvKey(current.externalRestApiBaseUrl),- storagePath: process.env.CLERUM_DESKTOP_CONFIG_PATH?.trim() || runtimeConfigDirectoryPath(),+ envKey: resolveEnvKey(current.externalRestApiBaseUrl, current.rpcProxyBaseUrl),+ storagePath: explicitRuntimeConfigPath() || runtimeConfigDirectoryPath(),options,}}diff --git a/desktop-app/src/ipc.ts b/desktop-app/src/ipc.tsindex 70a911a01..8f09897fe 100644--- a/desktop-app/src/ipc.ts+++ b/desktop-app/src/ipc.ts@@ -36,6 +36,43 @@ function sanitizeOptionalInteger(input: unknown): number | undefined {return value}+function sanitizeSessionsListQuery(+ input: import('./types.js').SessionsListQuery | undefined+): import('./types.js').SessionsListQuery {+ const agent = sanitizeString(input?.agent)+ const cursor = sanitizeString(input?.cursor)+ if (agent && (agent.length > 200 || agent.includes(':'))) {+ throw new Error('Invalid session agent')+ }+ 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 {+ ...(agent ? { agent } : {}),+ ...(rawLimit !== undefined ? { limit: Math.min(rawLimit, 100) } : {}),+ ...(cursor ? { cursor } : {}),+ }+}++function sanitizeSessionMessagesQuery(+ input: import('./types.js').SessionMessagesQuery | undefined+): import('./types.js').SessionMessagesQuery {+ const rawLimit = sanitizeOptionalInteger(input?.limit)+ const beforeTurn = sanitizeOptionalInteger(input?.beforeTurn)+ const afterTurn = sanitizeOptionalInteger(input?.afterTurn)+ if (rawLimit !== undefined && rawLimit < 1) throw new Error('Invalid messages limit')+ if (beforeTurn !== undefined && beforeTurn < 1) throw new Error('Invalid beforeTurn')+ if (afterTurn !== undefined && afterTurn < 0) throw new Error('Invalid afterTurn')+ if (beforeTurn !== undefined && afterTurn !== undefined) {+ throw new Error('beforeTurn and afterTurn are mutually exclusive')+ }+ return {+ ...(rawLimit !== undefined ? { limit: Math.min(rawLimit, 200) } : {}),+ ...(beforeTurn !== undefined ? { beforeTurn } : {}),+ ...(afterTurn !== undefined ? { afterTurn } : {}),+ }+}+function runScopedArtifactDownloadName(runId: string, artifactName: string): string {const rawName = path.basename(artifactName).replace(/[\\/:*?"<>|\u0000-\u001f]/g, '_')const safeName = rawName || 'artifact'@@ -918,11 +955,22 @@ 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,+ sanitizeSessionsListQuery(payload?.query)+ )})@@ -930,7 +978,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)@@ -939,7 +993,13 @@ 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,+ sanitizeSessionMessagesQuery(payload?.query)+ )})@@ -1067,13 +1127,46 @@ 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)+ : undefinedawait requireChatStore().replaceMessages(+ agentRef,+ chatId,+ messages as import('./types.js').ChatMessage[],+ {+ activeTaskIds,+ replaceLocalWindow: payload?.options?.replaceLocalWindow === true,+ }+ )+ }+ )++ ipcMain.handle(+ 'chat:backfillCounters',+ async (event, payload: { agentRef: string; chatId: string; messages: unknown[] }) => {+ 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 : []+ await requireChatStore().backfillChatCounters(agentRef,chatId,messages as import('./types.js').ChatMessage[]diff --git a/desktop-app/src/preload.ts b/desktop-app/src/preload.tsindex 378744057..24c176c54 100644--- a/desktop-app/src/preload.ts+++ b/desktop-app/src/preload.ts@@ -319,10 +319,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[]) =>@@ -392,8 +400,14 @@ 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) =>ipcRenderer.invoke('chat:markUnreadTerminal', { agentRef, chatId }),clearUnreadTerminal: (agentRef: string, chatId: string) =>diff --git a/desktop-app/src/renderer.d.ts b/desktop-app/src/renderer.d.tsindex a56efa389..49a5bf60c 100644--- a/desktop-app/src/renderer.d.ts+++ b/desktop-app/src/renderer.d.ts@@ -18,16 +18,17 @@ import {HostModelsResult,HostRuntimeStatus,HostStatusStreamEvent,- MessageToolStep,PasswordLoginResult,- PendingApprovalLite,PendingWorkflowApproval,PrewarmHostResult,ProfileSettingsOpenOptions,+ ReplaceChatMessagesOptions,RpcAllowedServersResult,- SessionLifecycleState,+ SessionMessagesQuery,+ SessionMessagesResult,SessionState,- SessionTokensLite,+ SessionsListQuery,+ SessionsListResult,SetHostModelResult,TaskProgressStreamEvent,TeamDirectoryResult,@@ -397,41 +398,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,@@ -515,6 +491,12 @@ declare global {) => Promise<ChatMessage[]>appendMessages: (agentRef: string, chatId: string, messages: ChatMessage[]) => Promise<void>replaceMessages: (+ agentRef: string,+ chatId: string,+ messages: ChatMessage[],+ options?: ReplaceChatMessagesOptions+ ) => Promise<void>+ backfillCounters?: (agentRef: string,chatId: string,messages: ChatMessage[]diff --git a/desktop-app/src/rpcProxyClient.ts b/desktop-app/src/rpcProxyClient.tsindex 55ca3f544..09b267213 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'@@ -26,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@@ -544,23 +553,15 @@ 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> {+ assertSafePathSegment('hostRef', hostRef)+ const requestUrl = new URL(url(`/api/v1/rpc/hosts/${encodeURIComponent(hostRef)}/sessions`))+ if (query.agent) requestUrl.searchParams.set('agent', query.agent)+ 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 +573,35 @@ 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(+ 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`- ),- { 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.@@ -632,6 +636,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.tsnew file mode 100644index 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/tokenStore.ts b/desktop-app/src/tokenStore.tsindex d78199899..7a880717d 100644--- a/desktop-app/src/tokenStore.ts+++ b/desktop-app/src/tokenStore.ts@@ -102,14 +102,18 @@ async function legacyFilePath(): Promise<string> {export class TokenStore {/*** Read the session token for `envKey`. Falls back keytar → safeStorage file,- * then does a one-time best-effort migration of the pre-per-env GLOBAL slot- * into this environment's slot. Migrating the legacy token is safe: it was- * issued for whatever environment was last active (which is the environment- * being restored at startup), and an env mismatch simply fails `getMe` and- * drops the user back to login — never a cross-env leak, since after the- * migration the legacy slot is deleted.+ * optional older env-key aliases, then does a one-time best-effort migration+ * of the pre-per-env GLOBAL slot into this environment's slot.+ *+ * The legacy env-key aliases are explicit caller-provided upgrade paths, such+ * as REST-only `resolveEnvKey(rest)` → REST+RPC `resolveEnvKey(rest, rpc)`.+ * When one is found, it is copied to the new slot and deleted from the old+ * slot so it cannot be read into another runtime boundary later.*/- async getSessionToken(envKey: string): Promise<string | null> {+ async getSessionToken(+ envKey: string,+ options: { legacyEnvKeys?: readonly string[] } = {}+ ): Promise<string | null> {assertEnvKey(envKey)const account = accountFor(envKey)const keytar = await loadKeytar()@@ -145,9 +149,79 @@ export class TokenStore {// No per-env plain-text token — fall through to legacy migration.}+ const migratedScopedToken = await this.migrateLegacyEnvToken(+ envKey,+ options.legacyEnvKeys ?? [],+ keytar+ )+ if (migratedScopedToken) return migratedScopedToken+return this.migrateLegacyGlobalToken(envKey, keytar)}+ /**+ * One-time migration from older environment-scoped account/file names into+ * the current env key. Used when the env-key derivation changes but the REST+ * origin still matches the token issuer.+ */+ private async migrateLegacyEnvToken(+ envKey: string,+ legacyEnvKeys: readonly string[],+ keytar: KeytarModule | null+ ): Promise<string | null> {+ const candidates = Array.from(+ new Set(+ legacyEnvKeys.map(key => String(key || '').trim()).filter(key => key && key !== envKey)+ )+ )+ for (const legacyEnvKey of candidates) {+ assertEnvKey(legacyEnvKey)+ const legacyAccount = accountFor(legacyEnvKey)+ if (keytar) {+ try {+ const token = await keytar.getPassword(SERVICE, legacyAccount)+ if (token) {+ await this.setSessionToken(token, envKey)+ await keytar.deletePassword(SERVICE, legacyAccount).catch(() => {})+ return token+ }+ } catch {+ // keychain unavailable — try file fallbacks below.+ }+ }++ if (app?.isReady() && safeStorage.isEncryptionAvailable()) {+ try {+ const file = await encryptedFilePath(legacyEnvKey)+ const encrypted = await fs.readFile(file)+ const token = safeStorage.decryptString(encrypted)+ if (token) {+ await this.setSessionToken(token, envKey)+ await fs.unlink(file).catch(() => {})+ return token+ }+ } catch {+ // no legacy encrypted file — fall through to plain-text.+ }+ }++ try {+ const file = await plainFilePath(legacyEnvKey)+ const raw = await fs.readFile(file, 'utf8')+ const data = JSON.parse(raw) as { token?: unknown }+ const token = typeof data.token === 'string' && data.token ? data.token : null+ if (token) {+ await this.setSessionToken(token, envKey)+ await fs.unlink(file).catch(() => {})+ return token+ }+ } catch {+ // no legacy plain-text file — try next candidate.+ }+ }+ return null+ }+/*** One-time migration of the legacy global slot (keytar `session-token`, then* the plain-text/enc files) into this environment's slot. Returns the tokendiff --git a/desktop-app/src/types.ts b/desktop-app/src/types.tsindex a46feca02..ff409cef0 100644--- a/desktop-app/src/types.ts+++ b/desktop-app/src/types.ts@@ -796,6 +796,9 @@ export interface ChatMetadata {createdAt: string // ISO 8601updatedAt: string // ISO 8601messageCount: number+ /** Persisted activity aggregates keep dashboards from opening complete chat files. */+ errorCount?: number+ toolCallCount?: number/** D.5: a task terminated while this chat was NOT the active view. Drives the* sidebar "completed_unread" badge; persisted so it survives an app restart. */unreadTerminal?: boolean@@ -804,8 +807,8 @@ export interface ChatMetadata {}export interface ChatIndex {- /** v2 aligns with ChatFile v2; bootstrap wipes any v1/missing-version dir (D.4 §7.1). */- version: 1 | 2+ /** v2 remains readable by pre-paging builds; v3 is accepted and normalized for compatibility. */+ version: 1 | 2 | 3lastActiveChatId: string | nullonboardingDismissed: booleanchats: ChatMetadata[]@@ -848,6 +851,13 @@ export interface ApprovalDecisionResult {export interface SessionMessagesResult {agent: stringchatId: string+ totalTurns?: number+ oldestTurnNumber?: number+ latestTurnNumber?: number+ /** True only when older turns exist before the returned non-empty window. */+ hasMoreBefore?: boolean+ /** True only when newer turns exist after the returned non-empty window. */+ hasMoreAfter?: booleanstate?: SessionLifecycleStateactiveTaskId?: stringpendingApproval?: PendingApprovalLite@@ -863,6 +873,33 @@ export interface SessionMessagesResult {}>}+export interface SessionMessagesQuery {+ limit?: number+ beforeTurn?: number+ afterTurn?: number+}++export interface SessionsListQuery {+ agent?: string+ limit?: number+ cursor?: string+}++export interface SessionsListResult {+ items: Array<{+ agent: string+ chatId: string+ turnCount: number+ messageCount?: 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@@ -982,11 +1019,15 @@ export interface ChatMessage {role: 'user' | 'assistant' | 'system'content: stringtimestamp: 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?: stringattachments?: ChatMessageAttachment[]/** True when this message represents a structured error returned by mcp-host. */isError?: boolean+ /** Local-only durable message that must not be evicted by server window reconciliation. */+ preserveLocal?: boolean/** LLM error code, e.g. "LLM_AUTHENTICATION_FAILED". Present when isError is true. */errorCode?: string/** LLM provider name, e.g. "zai". Present when isError is true. */@@ -1001,6 +1042,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` marks the bounded latest-page fallback;+ * it still merges into local history rather than truncating the whole chat.+ */+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/App.tsx b/desktop-app/ui/src/App.tsxindex 0178b9e78..59f0b648a 100644--- a/desktop-app/ui/src/App.tsx+++ b/desktop-app/ui/src/App.tsx@@ -494,8 +494,11 @@ export function App() {activeChatId: vm.activeChatId,chatList: vm.chatList,chatListLoading: vm.chatListLoading,+ chatListMoreLoading: vm.chatListMoreLoading,+ chatListHasMoreRemoteSessions: vm.chatListHasMoreRemoteSessions,latestChatSessions: vm.latestChatSessions,latestChatSessionsLoading: vm.latestChatSessionsLoading,+ loadMoreChatSessions: vm.loadMoreChatSessions,sessionStateByChatId: vm.sessionStateByChatId,sessionStateByChatKey: vm.sessionStateByChatKey,}),@@ -503,8 +506,11 @@ export function App() {vm.activeChatId,vm.chatList,vm.chatListLoading,+ vm.chatListMoreLoading,+ vm.chatListHasMoreRemoteSessions,vm.latestChatSessions,vm.latestChatSessionsLoading,+ vm.loadMoreChatSessions,vm.sessionStateByChatId,vm.sessionStateByChatKey,]@@ -537,6 +543,9 @@ export function App() {activeMessages: vm.activeMessages,groupedMessages: vm.groupedMessages,chatMessagesLoading: vm.chatMessagesLoading,+ hasOlderMessages: vm.hasOlderMessages,+ olderMessagesLoading: vm.olderMessagesLoading,+ handleLoadOlderMessages: vm.handleLoadOlderMessages,activityByMessageId: vm.activityByMessageId,progressByMessageId: vm.progressByMessageId,}),@@ -545,6 +554,9 @@ export function App() {vm.activeMessages,vm.groupedMessages,vm.chatMessagesLoading,+ vm.hasOlderMessages,+ vm.olderMessagesLoading,+ vm.handleLoadOlderMessages,vm.activityByMessageId,vm.progressByMessageId,]diff --git a/desktop-app/ui/src/components/agents/ChatThread.tsx b/desktop-app/ui/src/components/agents/ChatThread.tsxindex 8c9485362..145f64da8 100644--- a/desktop-app/ui/src/components/agents/ChatThread.tsx+++ b/desktop-app/ui/src/components/agents/ChatThread.tsx@@ -55,6 +55,45 @@ type RenderableChatMessage = AgentChatMessage & {messageKey: string}+const VIRTUAL_MESSAGE_GROUPS_PER_CHUNK = 8++type ChunkableMessageGroup = {+ groupKey: string+ items: Array<Pick<RenderableChatMessage, 'serverTurnNumber'>>+}++export function buildMessageGroupChunks<T extends ChunkableMessageGroup>(+ groupedWithKeys: T[]+): Array<{+ chunkKey: string+ groups: Array<{ group: T; groupIndex: number }>+}> {+ const chunks: Array<{+ chunkKey: string+ groups: Array<{ group: T; groupIndex: number }>+ }> = []+ const occurrencesByBaseKey = new Map<string, number>()+ let lastBaseKey: string | null = null+ for (const [groupIndex, group] of groupedWithKeys.entries()) {+ const firstTurn = group.items[0]?.serverTurnNumber+ const baseKey =+ firstTurn !== undefined+ ? `server-turns-${Math.floor((firstTurn - 1) / (VIRTUAL_MESSAGE_GROUPS_PER_CHUNK / 2))}`+ : `local-${group.groupKey}`+ const current = chunks.at(-1)+ if (current && lastBaseKey === baseKey) {+ current.groups.push({ group, groupIndex })+ } else {+ const occurrence = (occurrencesByBaseKey.get(baseKey) ?? 0) + 1+ occurrencesByBaseKey.set(baseKey, occurrence)+ const chunkKey = occurrence === 1 ? baseKey : `${baseKey}#${occurrence}`+ chunks.push({ chunkKey, groups: [{ group, groupIndex }] })+ lastBaseKey = baseKey+ }+ }+ return chunks+}+type WorkflowArtifactScope = {namespace: stringname: string@@ -180,11 +219,21 @@ export function ChatThread({ showAgentLabel = false }: ChatThreadProps) {activeMessages,groupedMessages,chatMessagesLoading,+ hasOlderMessages,+ olderMessagesLoading,+ handleLoadOlderMessages,activeChatId,activityByMessageId,progressByMessageId,} = useChatThreadStateContext()- const { chatList, chatListLoading, sessionStateByChatId } = useChatListContext()+ const {+ chatList,+ chatListLoading,+ chatListMoreLoading = false,+ chatListHasMoreRemoteSessions = false,+ loadMoreChatSessions,+ sessionStateByChatId,+ } = useChatListContext()const {chatEndRef,handleSelectChat: onSelectChat,@@ -210,16 +259,26 @@ export function ChatThread({ showAgentLabel = false }: ChatThreadProps) {const groupedWithKeys = useMemo(() =>- groupedMessages.map((group, groupIndex) => ({- ...group,- groupKey: `${group.role}-${groupIndex}`,- items: group.items.map((message, messageIndex) => ({- ...message,- messageKey: `${message.timestamp}-${groupIndex}-${messageIndex}`,- })),- })),+ groupedMessages.map((group, groupIndex) => {+ const first = group.items[0]+ const last = group.items.at(-1)+ const firstKey = first?.id ?? first?.timestamp ?? groupIndex+ const lastKey = last?.id ?? last?.timestamp ?? groupIndex+ return {+ ...group,+ groupKey: `${group.role}-${firstKey}-${lastKey}-${group.items.length}`,+ items: group.items.map(message => ({+ ...message,+ messageKey: message.id,+ })),+ }+ }),[groupedMessages])+ const messageGroupChunks = useMemo(+ () => buildMessageGroupChunks(groupedWithKeys),+ [groupedWithKeys]+ )const localMessageIds = useMemo(() => new Set(activeMessages.map(message => message.id)),@@ -233,7 +292,8 @@ export function ChatThread({ showAgentLabel = false }: ChatThreadProps) {),[chatList])- const hasMoreSessions = sortedChats.length > SESSION_PREVIEW_LIMIT+ const hasMoreSessions =+ sortedChats.length > SESSION_PREVIEW_LIMIT || chatListHasMoreRemoteSessionsconst visibleChats = showAllSessions ? sortedChats : sortedChats.slice(0, SESSION_PREVIEW_LIMIT)const isDedicatedAgentView = !activeChatId@@ -258,7 +318,11 @@ export function ChatThread({ showAgentLabel = false }: ChatThreadProps) {}, [])useEffect(() => {- if (chatList.length <= SESSION_PREVIEW_LIMIT && showAllSessions) {+ if (+ chatList.length <= SESSION_PREVIEW_LIMIT &&+ !chatListHasMoreRemoteSessions &&+ showAllSessions+ ) {setShowAllSessions(false)}if (sessionMenuChatId && !chatList.some(chat => chat.id === sessionMenuChatId)) {@@ -268,7 +332,13 @@ export function ChatThread({ showAgentLabel = false }: ChatThreadProps) {setRenamingSessionId(null)setSessionRenameValue('')}- }, [chatList, renamingSessionId, sessionMenuChatId, showAllSessions])+ }, [+ chatList,+ chatListHasMoreRemoteSessions,+ renamingSessionId,+ sessionMenuChatId,+ showAllSessions,+ ])useEffect(() => {if (!sessionMenuChatId) return@@ -448,182 +518,206 @@ export function ChatThread({ showAgentLabel = false }: ChatThreadProps) {data-testid="message-list"className={`chat-thread ${isDedicatedAgentView ? 'chat-thread-dedicated' : ''}`}>+ {activeChatId && hasOlderMessages && (+ <div className="chat-history-page-control">+ <Button+ type="button"+ variant="outline"+ size="sm"+ disabled={olderMessagesLoading}+ onClick={() => void handleLoadOlderMessages()}+ >+ {olderMessagesLoading ? 'Loading older messages…' : 'Load older messages'}+ </Button>+ </div>+ )}{activeChatId &&- groupedWithKeys.map((group, groupIndex) => {- const prevGroup = groupIndex > 0 ? groupedWithKeys[groupIndex - 1] : null-- return (- <Fragment key={group.groupKey}>- <section className={`chat-group ${group.role}`}>- {group.items.map((message, messageIndex) => {- const parsedUserMessage =- message.role === 'user' ? parseChatMessageDisplay(message.content) : null- const displayContent = parsedUserMessage?.content ?? message.content- const displayAttachments =- message.role === 'user'- ? message.attachments && message.attachments.length- ? message.attachments- : (parsedUserMessage?.attachments ?? [])- : message.attachments && message.attachments.length- ? message.attachments- : []- const hasResponseFileAttachment = displayAttachments.some(- attachment => attachment.type === 'response_file'- )- const isJson = looksLikeJson(displayContent)- const htmlPreview =- message.role === 'assistant' ? extractHtmlVisualization(displayContent) : null- const hasHtmlArtifactMention =- message.role === 'assistant' &&- /\b[a-zA-Z0-9][a-zA-Z0-9._-]*\.html?\b/i.test(displayContent)- const showMetaRow = message.role === 'assistant' || message.role === 'user'- const copyContent = message.role === 'user' ? displayContent : message.content- const metaRowRoleClass =- message.role === 'user'- ? 'chat-message-meta-row--user'- : message.role === 'assistant'- ? 'chat-message-meta-row--assistant'- : ''- const isLastAssistantMessage =- group.role === 'assistant' && messageIndex === group.items.length - 1- const workflowArtifactScopeForAssistant =- message.role === 'assistant' && prevGroup?.role === 'user'- ? (prevGroup.items- .map(prevMessage =>- extractWorkflowArtifactScopeFromProgress(- progressByMessageId[prevMessage.id]- )- )- .find((scope): scope is WorkflowArtifactScope => scope !== null) ?? null)- : null- return (- <article- key={message.messageKey}- data-testid={message.role === 'assistant' ? 'agent-response' : undefined}- className={`chat-bubble ${message.role}${message.isError ? ' chat-bubble--error' : ''}${- htmlPreview || hasHtmlArtifactMention ? ' chat-bubble--wide' : ''- }`}- >- {message.isError ? (- <div className="error-bubble-content">- <div className="error-bubble-icon">✕</div>- <div className="error-bubble-body">- <div className="error-bubble-label">- {AGENT_ERROR_CODE_LABELS[message.errorCode ?? ''] ?? 'Error'}- {message.errorProvider- ? ` · ${message.errorProvider.toUpperCase()}`- : ''}- </div>- <div className="error-bubble-message">- {message.content.length > 180- ? `${message.content.slice(0, 177)}...`- : message.content}+ messageGroupChunks.map(chunk => (+ <div key={chunk.chunkKey} className="virtualized-message-chunk">+ {chunk.groups.map(({ group, groupIndex }) => {+ const prevGroup = groupIndex > 0 ? groupedWithKeys[groupIndex - 1] : null++ return (+ <Fragment key={group.groupKey}>+ <section className={`chat-group ${group.role}`}>+ {group.items.map((message, messageIndex) => {+ const parsedUserMessage =+ message.role === 'user' ? parseChatMessageDisplay(message.content) : null+ const displayContent = parsedUserMessage?.content ?? message.content+ const displayAttachments =+ message.role === 'user'+ ? message.attachments && message.attachments.length+ ? message.attachments+ : (parsedUserMessage?.attachments ?? [])+ : message.attachments && message.attachments.length+ ? message.attachments+ : []+ const hasResponseFileAttachment = displayAttachments.some(+ attachment => attachment.type === 'response_file'+ )+ const isJson = looksLikeJson(displayContent)+ const htmlPreview =+ message.role === 'assistant'+ ? extractHtmlVisualization(displayContent)+ : null+ const hasHtmlArtifactMention =+ message.role === 'assistant' &&+ /\b[a-zA-Z0-9][a-zA-Z0-9._-]*\.html?\b/i.test(displayContent)+ const showMetaRow = message.role === 'assistant' || message.role === 'user'+ const copyContent = message.role === 'user' ? displayContent : message.content+ const metaRowRoleClass =+ message.role === 'user'+ ? 'chat-message-meta-row--user'+ : message.role === 'assistant'+ ? 'chat-message-meta-row--assistant'+ : ''+ const isLastAssistantMessage =+ group.role === 'assistant' && messageIndex === group.items.length - 1+ const workflowArtifactScopeForAssistant =+ message.role === 'assistant' && prevGroup?.role === 'user'+ ? (prevGroup.items+ .map(prevMessage =>+ extractWorkflowArtifactScopeFromProgress(+ progressByMessageId[prevMessage.id]+ )+ )+ .find((scope): scope is WorkflowArtifactScope => scope !== null) ??+ null)+ : null+ return (+ <article+ key={message.messageKey}+ data-testid={message.role === 'assistant' ? 'agent-response' : undefined}+ className={`chat-bubble ${message.role}${message.isError ? ' chat-bubble--error' : ''}${+ htmlPreview || hasHtmlArtifactMention ? ' chat-bubble--wide' : ''+ }`}+ >+ {message.isError ? (+ <div className="error-bubble-content">+ <div className="error-bubble-icon">✕</div>+ <div className="error-bubble-body">+ <div className="error-bubble-label">+ {AGENT_ERROR_CODE_LABELS[message.errorCode ?? ''] ?? 'Error'}+ {message.errorProvider+ ? ` · ${message.errorProvider.toUpperCase()}`+ : ''}+ </div>+ <div className="error-bubble-message">+ {message.content.length > 180+ ? `${message.content.slice(0, 177)}...`+ : message.content}+ </div>+ <details className="error-bubble-details">+ <summary>Details</summary>+ <pre className="error-bubble-details-text">{message.content}</pre>+ </details>+ </div></div>- <details className="error-bubble-details">- <summary>Details</summary>- <pre className="error-bubble-details-text">{message.content}</pre>- </details>- </div>- </div>- ) : (- <>- {htmlPreview && (- <SecureHtmlPreview- html={htmlPreview}- previewId={message.messageKey}- title="HTML visualization"- maxBytes={HTML_PREVIEW_INLINE_MAX_BYTES}- />- )}- {isJson ? (- <pre className="message-block json-content">{displayContent}</pre>- ) : message.role === 'assistant' ? (- <div className="message-block markdown-content">- <ReactMarkdown remarkPlugins={[remarkGfm]}>- {displayContent}- </ReactMarkdown>- {selectedAgent && !hasResponseFileAttachment && (- <MessageArtifactActions- hostRef={selectedAgent}- content={displayContent}+ ) : (+ <>+ {htmlPreview && (+ <SecureHtmlPreview+ html={htmlPreview}+ previewId={message.messageKey}+ title="HTML visualization"+ maxBytes={HTML_PREVIEW_INLINE_MAX_BYTES}/>)}- {workflowArtifactScopeForAssistant ? (- <WorkflowRunArtifactActions- workflow={workflowArtifactScopeForAssistant}- />+ {isJson ? (+ <pre className="message-block json-content">{displayContent}</pre>+ ) : message.role === 'assistant' ? (+ <div className="message-block markdown-content">+ <ReactMarkdown remarkPlugins={[remarkGfm]}>+ {displayContent}+ </ReactMarkdown>+ {selectedAgent && !hasResponseFileAttachment && (+ <MessageArtifactActions+ hostRef={selectedAgent}+ content={displayContent}+ />+ )}+ {workflowArtifactScopeForAssistant ? (+ <WorkflowRunArtifactActions+ workflow={workflowArtifactScopeForAssistant}+ />+ ) : null}+ </div>+ ) : displayContent ? (+ <p className="message-block">{displayContent}</p>) : null}- </div>- ) : displayContent ? (- <p className="message-block">{displayContent}</p>- ) : null}- <MessageAttachmentList attachments={displayAttachments} />- </>- )}- {isLastAssistantMessage &&- prevGroup?.role === 'user' &&- (() => {- // Prefer the live progress (keyed by the user message);- // fall back to the assistant's persisted toolSteps after- // a reload, when the live map is empty (#582).- const liveNodes = prevGroup.items- .map(msg => renderProgressStepper(msg, 'completed'))- .filter((node): node is ReactElement => node != null)- if (liveNodes.length > 0) return liveNodes- return renderHydratedToolSteps(message)- })()}- {showMetaRow && (- <footer className={`chat-message-meta-row ${metaRowRoleClass}`.trim()}>- <div className="chat-message-meta-main">- <span className="chat-time-label">- {formatChatTimestamp(message.timestamp || Date.now())}- </span>- {message.role === 'assistant' && message.tokens && (- <MessageTokens tokens={message.tokens} />- )}- </div>- <IconButton- className={`message-copy-button message-copy-button--inline${- copiedMessageKey === message.messageKey ? ' copied' : ''- }`}- onClick={() => void handleCopyMessage(message.messageKey, copyContent)}- aria-label={- copiedMessageKey === message.messageKey ? 'Copied' : 'Copy text'- }- label={copiedMessageKey === message.messageKey ? 'Copied' : 'Copy text'}- size="xs"- variant="ghost"- >- <svg viewBox="0 0 24 24" aria-hidden="true">- <path fill="none" d="M0 0h24v24H0V0z" />- <path d="M16 1H4c-1.1 0-2 .9-2 2v14h2V3h12V1zm3 4H8c-1.1 0-2 .9-2 2v14c0 1.1.9 2 2 2h11c1.1 0 2-.9 2-2V7c0-1.1-.9-2-2-2zm0 16H8V7h11v14z" />- </svg>- {copiedMessageKey === message.messageKey && (- <span className="copy-tooltip">Copied!</span>- )}- </IconButton>- </footer>- )}- </article>- )- })}- </section>- {group.role === 'user' &&- group.items.map(message => {- const node = renderProgressStepper(message, 'non-completed')- if (!node) return null- return (- <section- key={`progress-${message.messageKey}`}- className="chat-group assistant"- >- <div className="chat-bubble assistant">{node}</div>- </section>- )- })}- </Fragment>- )- })}+ <MessageAttachmentList attachments={displayAttachments} />+ </>+ )}+ {isLastAssistantMessage &&+ prevGroup?.role === 'user' &&+ (() => {+ // Prefer the live progress (keyed by the user message);+ // fall back to the assistant's persisted toolSteps after+ // a reload, when the live map is empty (#582).+ const liveNodes = prevGroup.items+ .map(msg => renderProgressStepper(msg, 'completed'))+ .filter((node): node is ReactElement => node != null)+ if (liveNodes.length > 0) return liveNodes+ return renderHydratedToolSteps(message)+ })()}+ {showMetaRow && (+ <footer className={`chat-message-meta-row ${metaRowRoleClass}`.trim()}>+ <div className="chat-message-meta-main">+ <span className="chat-time-label">+ {formatChatTimestamp(message.timestamp || Date.now())}+ </span>+ {message.role === 'assistant' && message.tokens && (+ <MessageTokens tokens={message.tokens} />+ )}+ </div>+ <IconButton+ className={`message-copy-button message-copy-button--inline${+ copiedMessageKey === message.messageKey ? ' copied' : ''+ }`}+ onClick={() =>+ void handleCopyMessage(message.messageKey, copyContent)+ }+ aria-label={+ copiedMessageKey === message.messageKey ? 'Copied' : 'Copy text'+ }+ label={+ copiedMessageKey === message.messageKey ? 'Copied' : 'Copy text'+ }+ size="xs"+ variant="ghost"+ >+ <svg viewBox="0 0 24 24" aria-hidden="true">+ <path fill="none" d="M0 0h24v24H0V0z" />+ <path d="M16 1H4c-1.1 0-2 .9-2 2v14h2V3h12V1zm3 4H8c-1.1 0-2 .9-2 2v14c0 1.1.9 2 2 2h11c1.1 0 2-.9 2-2V7c0-1.1-.9-2-2-2zm0 16H8V7h11v14z" />+ </svg>+ {copiedMessageKey === message.messageKey && (+ <span className="copy-tooltip">Copied!</span>+ )}+ </IconButton>+ </footer>+ )}+ </article>+ )+ })}+ </section>+ {group.role === 'user' &&+ group.items.map(message => {+ const node = renderProgressStepper(message, 'non-completed')+ if (!node) return null+ return (+ <section+ key={`progress-${message.messageKey}`}+ className="chat-group assistant"+ >+ <div className="chat-bubble assistant">{node}</div>+ </section>+ )+ })}+ </Fragment>+ )+ })}+ </div>+ ))}{activeChatId && chatMessagesLoading && groupedWithKeys.length === 0 && (<section className="chat-group assistant" aria-label="Loading conversation"><div className="chat-bubble assistant chat-loading-bubble">@@ -788,14 +882,37 @@ export function ChatThread({ showAgentLabel = false }: ChatThreadProps) {<span className="agent-dedicated-sessions-meta">{sortedChats.length} {sortedChats.length === 1 ? 'session' : 'sessions'}</span>- {hasMoreSessions && (+ {hasMoreSessions && !showAllSessions && (+ <Button+ color="neutral"+ onClick={() => setShowAllSessions(true)}+ size="xs"+ variant="text"+ >+ Show more+ </Button>+ )}+ {showAllSessions && sortedChats.length > SESSION_PREVIEW_LIMIT && (+ <Button+ color="neutral"+ onClick={() => setShowAllSessions(false)}+ size="xs"+ variant="text"+ >+ Show less+ </Button>+ )}+ {showAllSessions && chatListHasMoreRemoteSessions && loadMoreChatSessions && (<Buttoncolor="neutral"- onClick={() => setShowAllSessions(previous => !previous)}+ disabled={chatListMoreLoading}+ onClick={() => {+ void loadMoreChatSessions()+ }}size="xs"variant="text">- {showAllSessions ? 'Show less' : 'Show more'}+ {chatListMoreLoading ? 'Loading…' : 'Load more'}</Button>)}</div>diff --git a/desktop-app/ui/src/components/agents/__tests__/chatThread.chunking.test.ts b/desktop-app/ui/src/components/agents/__tests__/chatThread.chunking.test.tsnew file mode 100644index 000000000..4acea1549--- /dev/null+++ b/desktop-app/ui/src/components/agents/__tests__/chatThread.chunking.test.ts@@ -0,0 +1,63 @@+import { describe, expect, it } from 'vitest'+import { buildMessageGroupChunks } from '../ChatThread'++function group(turn: number, role: 'user' | 'assistant') {+ return {+ groupKey: `${role}-${turn}`,+ items: [{ serverTurnNumber: turn }],+ }+}++function turnGroups(start: number, end: number) {+ return Array.from({ length: end - start + 1 }, (_, index) => {+ const turn = start + index+ return [group(turn, 'user'), group(turn, 'assistant')]+ }).flat()+}++describe('buildMessageGroupChunks', () => {+ it('keeps existing server-turn chunk keys stable when a new turn is appended', () => {+ const before = buildMessageGroupChunks(turnGroups(1, 8))+ const after = buildMessageGroupChunks(turnGroups(1, 9))++ expect(before.map(chunk => chunk.chunkKey)).toEqual(['server-turns-0', 'server-turns-1'])+ expect(after.map(chunk => chunk.chunkKey)).toEqual([+ 'server-turns-0',+ 'server-turns-1',+ 'server-turns-2',+ ])+ expect(after.slice(0, before.length).map(chunk => chunk.chunkKey)).toEqual(+ before.map(chunk => chunk.chunkKey)+ )+ expect(after[0]?.groups.map(({ group }) => group.groupKey)).toEqual(+ before[0]?.groups.map(({ group }) => group.groupKey)+ )+ expect(after[1]?.groups.map(({ group }) => group.groupKey)).toEqual(+ before[1]?.groups.map(({ group }) => group.groupKey)+ )+ })++ it('keeps existing server-turn chunks stable when older turns are prepended', () => {+ const before = buildMessageGroupChunks(turnGroups(5, 12))+ const after = buildMessageGroupChunks(turnGroups(1, 12))+ const afterByKey = new Map(after.map(chunk => [chunk.chunkKey, chunk]))++ expect(before.map(chunk => chunk.chunkKey)).toEqual(['server-turns-1', 'server-turns-2'])+ for (const chunk of before) {+ expect(afterByKey.get(chunk.chunkKey)?.groups.map(({ group }) => group.groupKey)).toEqual(+ chunk.groups.map(({ group }) => group.groupKey)+ )+ }+ })++ it('suffixes repeated server buckets separated by a local-only group', () => {+ const local = { groupKey: 'local-message', items: [{}] }+ const chunks = buildMessageGroupChunks([group(1, 'user'), local, group(2, 'assistant')])++ expect(chunks.map(chunk => chunk.chunkKey)).toEqual([+ 'server-turns-0',+ 'local-local-message',+ 'server-turns-0#2',+ ])+ })+})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.tsxindex 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 | nullactivityByMessageId: 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/contexts/ChatListContext/types.ts b/desktop-app/ui/src/contexts/ChatListContext/types.tsindex 6684c5db0..bf185d2e7 100644--- a/desktop-app/ui/src/contexts/ChatListContext/types.ts+++ b/desktop-app/ui/src/contexts/ChatListContext/types.ts@@ -14,8 +14,11 @@ export interface ChatListContextValue {activeChatId: string | nullchatList: SidebarChatEntry[]chatListLoading: boolean+ chatListMoreLoading?: boolean+ chatListHasMoreRemoteSessions?: booleanlatestChatSessions: LatestSidebarChatEntry[]latestChatSessionsLoading: boolean+ loadMoreChatSessions?: () => Promise<void>/** Per-chat session lifecycle, keyed by chatId. Drives D.5 badges/banners. */sessionStateByChatId: Record<string, SessionStateLite>/**diff --git a/desktop-app/ui/src/contexts/ChatThreadStateContext/types.ts b/desktop-app/ui/src/contexts/ChatThreadStateContext/types.tsindex 9ead00fad..13be252eb 100644--- a/desktop-app/ui/src/contexts/ChatThreadStateContext/types.ts+++ b/desktop-app/ui/src/contexts/ChatThreadStateContext/types.ts@@ -12,6 +12,9 @@ export interface ChatThreadStateContextValue {activeMessages: AgentChatMessage[]groupedMessages: Array<{ role: 'user' | 'assistant' | 'system'; items: AgentChatMessage[] }>chatMessagesLoading: boolean+ hasOlderMessages: boolean+ olderMessagesLoading: boolean+ handleLoadOlderMessages: () => Promise<void>activityByMessageId: Record<string, AgentMessageActivity>progressByMessageId: Record<string, TaskProgress>}diff --git a/desktop-app/ui/src/hooks/__tests__/useAppController.test.tsx b/desktop-app/ui/src/hooks/__tests__/useAppController.test.tsxindex fade56da5..74e712324 100644--- a/desktop-app/ui/src/hooks/__tests__/useAppController.test.tsx+++ b/desktop-app/ui/src/hooks/__tests__/useAppController.test.tsx@@ -1,8 +1,10 @@// @vitest-environment jsdomimport { afterEach, describe, expect, it, vi } from 'vitest'+import { scheduleAfterFirstPaint } from '../scheduleAfterFirstPaint'import {loadWorkflowRunsWithArtifactsForApprovalRefresh,loadWorkflowRunsWithArtifactsForWorkflowTarget,+ scheduleAfterFirstPaintForSession,} from '../useAppController'function installWorkflowHarness(runsResult: unknown) {@@ -119,3 +121,79 @@ describe('loadWorkflowRunsWithArtifactsForWorkflowTarget', () => {})})})++describe('scheduleAfterFirstPaint', () => {+ afterEach(() => {+ vi.restoreAllMocks()+ vi.unstubAllGlobals()+ })++ it('waits for two animation frames before running deferred startup work', async () => {+ const frames: FrameRequestCallback[] = []+ vi.stubGlobal('requestAnimationFrame', (callback: FrameRequestCallback) => {+ frames.push(callback)+ return frames.length+ })+ const task = vi.fn(async () => undefined)++ scheduleAfterFirstPaint(task)+ expect(task).not.toHaveBeenCalled()++ frames.shift()?.(1)+ expect(task).not.toHaveBeenCalled()++ frames.shift()?.(2)+ expect(task).toHaveBeenCalledTimes(1)+ })++ it('falls back to a timeout when animation frames are throttled', async () => {+ vi.useFakeTimers()+ const frames: FrameRequestCallback[] = []+ vi.stubGlobal('requestAnimationFrame', (callback: FrameRequestCallback) => {+ frames.push(callback)+ return frames.length+ })+ const task = vi.fn(async () => undefined)++ scheduleAfterFirstPaint(task)+ expect(task).not.toHaveBeenCalled()++ await vi.advanceTimersByTimeAsync(1000)++ expect(frames).toHaveLength(1)+ expect(task).toHaveBeenCalledTimes(1)+ })++ it('runs session-bound deferred startup work when identity is unchanged', async () => {+ const frames: FrameRequestCallback[] = []+ vi.stubGlobal('requestAnimationFrame', (callback: FrameRequestCallback) => {+ frames.push(callback)+ return frames.length+ })+ const identityRef: { current: string | null } = { 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: string | null } = { 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/__tests__/useChatStore.test.tsx b/desktop-app/ui/src/hooks/__tests__/useChatStore.test.tsxnew file mode 100644index 000000000..0b00366c5--- /dev/null+++ b/desktop-app/ui/src/hooks/__tests__/useChatStore.test.tsx@@ -0,0 +1,74 @@+// @vitest-environment jsdom+import { afterEach, describe, expect, it, vi } from 'vitest'+import { renderHook } from '@testing-library/react'+import { useChatStore } from '../useChatStore'++describe('useChatStore remote request cache', () => {+ afterEach(() => {+ vi.restoreAllMocks()+ delete (window as { clerum?: unknown }).clerum+ })++ it('shares an in-flight session page and clears it at an identity boundary', async () => {+ const listSessions = vi.fn(async () => ({ items: [] }))+ Object.defineProperty(window, 'clerum', {+ configurable: true,+ value: { rpc: { listSessions } },+ })+ const { result } = renderHook(() => useChatStore())++ await Promise.all([+ result.current.listSessions('cache-test-host', { limit: 50 }),+ result.current.listSessions('cache-test-host', { limit: 50 }),+ ])+ expect(listSessions).toHaveBeenCalledTimes(1)++ result.current.clearCachedRemoteData()+ await result.current.listSessions('cache-test-host', { limit: 50 })+ expect(listSessions).toHaveBeenCalledTimes(2)+ })++ it('does not reuse remote session or model cache entries across cache scopes', async () => {+ const listSessions = vi.fn(async () => ({ items: [] }))+ const getHostModels = vi.fn(async () => ({ models: [] }))+ Object.defineProperty(window, 'clerum', {+ configurable: true,+ value: { rpc: { listSessions, getHostModels } },+ })+ const { result } = renderHook(() => useChatStore())++ result.current.setRemoteCacheScope('authenticated:team-a')+ await result.current.listSessions('cache-test-host', { limit: 50 })+ await result.current.getHostModels('cache-test-host', 'chat-1')+ await result.current.listSessions('cache-test-host', { limit: 50 })+ await result.current.getHostModels('cache-test-host', 'chat-1')++ expect(listSessions).toHaveBeenCalledTimes(1)+ expect(getHostModels).toHaveBeenCalledTimes(1)++ result.current.setRemoteCacheScope('authenticated:team-b')+ await result.current.listSessions('cache-test-host', { limit: 50 })+ await result.current.getHostModels('cache-test-host', 'chat-1')++ expect(listSessions).toHaveBeenCalledTimes(2)+ expect(getHostModels).toHaveBeenCalledTimes(2)+ })++ it('invalidates the scoped host-model cache after changing a model', async () => {+ const getHostModels = vi.fn(async () => ({ models: [] }))+ const setHostModel = vi.fn(async () => ({ success: true }))+ Object.defineProperty(window, 'clerum', {+ configurable: true,+ value: { rpc: { getHostModels, setHostModel } },+ })+ const { result } = renderHook(() => useChatStore())++ result.current.setRemoteCacheScope('authenticated:team-a')+ await result.current.getHostModels('cache-test-host', 'chat-1')+ await result.current.setHostModel('cache-test-host', 'chat-1', 'model-b')+ await result.current.getHostModels('cache-test-host', 'chat-1')++ expect(setHostModel).toHaveBeenCalledTimes(1)+ expect(getHostModels).toHaveBeenCalledTimes(2)+ })+})diff --git a/desktop-app/ui/src/hooks/domain/__tests__/__fixtures__/controllerHarness.tsx b/desktop-app/ui/src/hooks/domain/__tests__/__fixtures__/controllerHarness.tsxindex 69935d899..cb8bfdd3d 100644--- a/desktop-app/ui/src/hooks/domain/__tests__/__fixtures__/controllerHarness.tsx+++ b/desktop-app/ui/src/hooks/domain/__tests__/__fixtures__/controllerHarness.tsx@@ -49,6 +49,7 @@ export function renderController(currentTeamId: 'team-1',currentTeamName: 'Team 1',isAuthenticated: true,+ loadMenuData: true,navItem: 'agents',pushToast: spies.pushToast,pushNotification: spies.pushNotification,diff --git a/desktop-app/ui/src/hooks/domain/__tests__/backOnlineDispatcher.test.tsx b/desktop-app/ui/src/hooks/domain/__tests__/backOnlineDispatcher.test.tsxindex 12464c0b9..63de6a9eb 100644--- a/desktop-app/ui/src/hooks/domain/__tests__/backOnlineDispatcher.test.tsx+++ b/desktop-app/ui/src/hooks/domain/__tests__/backOnlineDispatcher.test.tsx@@ -51,7 +51,9 @@ describe('BACK_ONLINE dispatcher (§4.1)', () => {expect(clerum.rpc.loadSessionMessages).toHaveBeenCalledWith('agent-x','agent-x',- 'chat-offline'+ 'chat-offline',+ undefined,+ { 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.tsxindex e6bf35a00..470ba685a 100644--- a/desktop-app/ui/src/hooks/domain/__tests__/chatSelectionAcrossRouteChange.test.tsx+++ b/desktop-app/ui/src/hooks/domain/__tests__/chatSelectionAcrossRouteChange.test.tsx@@ -143,14 +143,22 @@ describe('selecting a chat session across a route change', () => {})await waitFor(() =>- expect(clerum.rpc.loadSessionMessages).toHaveBeenCalledWith('agent-x', 'agent-x', 'c-old')+ expect(clerum.rpc.loadSessionMessages).toHaveBeenCalledWith(+ 'agent-x',+ 'agent-x',+ 'c-old',+ undefined,+ { limit: 40 }+ ))expect(result.current.activeChatId).toBe('c-old')// It must not fall back to the most recently updated chat.expect(clerum.rpc.loadSessionMessages).not.toHaveBeenCalledWith('agent-x','agent-x',- 'c-newest'+ 'c-newest',+ undefined,+ { limit: 40 })})@@ -169,7 +177,13 @@ describe('selecting a chat session across a route change', () => {await waitFor(() => expect(result.current.chatMessagesLoading).toBe(false))expect(result.current.activeChatId).toBe('c-old')- expect(clerum.rpc.loadSessionMessages).toHaveBeenCalledWith('agent-x', 'agent-x', 'c-old')+ expect(clerum.rpc.loadSessionMessages).toHaveBeenCalledWith(+ 'agent-x',+ 'agent-x',+ 'c-old',+ undefined,+ { limit: 40 }+ )})it('notification -> session from another route opens the notified chat', async () => {@@ -194,13 +208,21 @@ describe('selecting a chat session across a route change', () => {expect(result.current.activeChatId).toBe('c-old')await waitFor(() =>- expect(clerum.rpc.loadSessionMessages).toHaveBeenCalledWith('agent-x', 'agent-x', 'c-old')+ expect(clerum.rpc.loadSessionMessages).toHaveBeenCalledWith(+ 'agent-x',+ 'agent-x',+ 'c-old',+ undefined,+ { limit: 40 }+ ))expect(result.current.activeChatId).toBe('c-old')expect(clerum.rpc.loadSessionMessages).not.toHaveBeenCalledWith('agent-x','agent-x',- 'c-newest'+ 'c-newest',+ undefined,+ { limit: 40 })})@@ -339,7 +361,13 @@ describe('chat-route guard on the real selection entry points', () => {)await waitFor(() =>- expect(clerum.rpc.loadSessionMessages).toHaveBeenCalledWith('agent-x', 'agent-x', 'c-old'),+ expect(clerum.rpc.loadSessionMessages).toHaveBeenCalledWith(+ 'agent-x',+ 'agent-x',+ 'c-old',+ undefined,+ { limit: 40 }+ ),SLOW)expect(result.current.activeChatId).toBe('c-old')@@ -377,7 +405,13 @@ describe('chat-route guard on the real selection entry points', () => {await waitFor(() =>- expect(clerum.rpc.loadSessionMessages).toHaveBeenCalledWith('agent-x', 'agent-x', 'c-old'),+ expect(clerum.rpc.loadSessionMessages).toHaveBeenCalledWith(+ 'agent-x',+ 'agent-x',+ 'c-old',+ undefined,+ { limit: 40 }+ ),SLOW)expect(result.current.activeChatId).toBe('c-old')@@ -432,7 +466,13 @@ describe('chat-route guard on the real selection entry points', () => {)await waitFor(() =>- expect(clerum.rpc.loadSessionMessages).toHaveBeenCalledWith('agent-x', 'agent-x', 'c-old'),+ expect(clerum.rpc.loadSessionMessages).toHaveBeenCalledWith(+ 'agent-x',+ 'agent-x',+ 'c-old',+ undefined,+ { limit: 40 }+ ),SLOW)expect(result.current.activeChatId).toBe('c-old')diff --git a/desktop-app/ui/src/hooks/domain/__tests__/pendingChatSelection.characterization.test.tsx b/desktop-app/ui/src/hooks/domain/__tests__/pendingChatSelection.characterization.test.tsxindex 82ba91753..2584ab806 100644--- a/desktop-app/ui/src/hooks/domain/__tests__/pendingChatSelection.characterization.test.tsx+++ b/desktop-app/ui/src/hooks/domain/__tests__/pendingChatSelection.characterization.test.tsx@@ -52,6 +52,62 @@ function deferred<T>() {}describe('pendingChatSelection effect', () => {+ it('opens the newest server session after first paint when the local index is empty', async () => {+ clerum.chat.getIndex.mockResolvedValue({+ version: 3,+ lastActiveChatId: null,+ onboardingDismissed: false,+ chats: [],+ })+ clerum.rpc.listSessions.mockResolvedValue({+ items: [+ {+ agent: 'agent-x',+ chatId: 'server-latest',+ turnCount: 2,+ messageCount: 4,+ lastActivityAt: '2026-05-01T00:00:00Z',+ },+ ],+ })++ const { result } = renderController({ navItem: 'chat' })++ await waitFor(() => expect(result.current.activeChatId).toBe('server-latest'))+ })++ it('does not fabricate message totals for summaries from older servers', async () => {+ clerum.chat.getIndex.mockResolvedValue({+ version: 3,+ lastActiveChatId: null,+ onboardingDismissed: false,+ chats: [],+ })+ clerum.rpc.listSessions.mockResolvedValue({+ items: [+ {+ agent: 'agent-x',+ chatId: 'legacy-summary',+ turnCount: 7,+ lastActivityAt: '2026-05-01T00:00:00Z',+ },+ ],+ })++ const { result } = renderController({ navItem: 'chat' })++ await waitFor(() =>+ expect(result.current.chatList).toEqual(+ expect.arrayContaining([+ expect.objectContaining({+ id: 'legacy-summary',+ messageCount: 0,+ }),+ ])+ )+ )+ })+it('latest → switches to the most recent chat', async () => {clerum.chat.getIndex.mockResolvedValue({version: 1,@@ -71,7 +127,13 @@ describe('pendingChatSelection effect', () => {})await waitFor(() => expect(result.current.activeChatId).toBe('c-latest'))- expect(clerum.rpc.loadSessionMessages).toHaveBeenCalledWith('agent-x', 'agent-x', 'c-latest')+ expect(clerum.rpc.loadSessionMessages).toHaveBeenCalledWith(+ 'agent-x',+ 'agent-x',+ 'c-latest',+ undefined,+ { limit: 40 }+ )})it('latest → overrides an older visible chat when explicitly requested', async () => {@@ -99,7 +161,13 @@ describe('pendingChatSelection effect', () => {})await waitFor(() => expect(result.current.activeChatId).toBe('c-newest'))- expect(clerum.rpc.loadSessionMessages).toHaveBeenCalledWith('agent-x', 'agent-x', 'c-newest')+ expect(clerum.rpc.loadSessionMessages).toHaveBeenCalledWith(+ 'agent-x',+ 'agent-x',+ 'c-newest',+ undefined,+ { limit: 40 }+ )})it('latest → does not override a chat auto-created while the list load is in flight', async () => {@@ -155,6 +223,17 @@ describe('pendingChatSelection effect', () => {})it('none → selects nothing and clears the spinner', async () => {+ clerum.rpc.listSessions.mockResolvedValue({+ items: [+ {+ agent: 'agent-x',+ chatId: 'must-not-auto-select',+ turnCount: 1,+ messageCount: 2,+ lastActivityAt: '2026-05-01T00:00:00Z',+ },+ ],+ })const { result, rerender } = renderController({ navItem: 'agents' })await settleMount()@@ -166,6 +245,7 @@ describe('pendingChatSelection effect', () => {})await waitFor(() => expect(result.current.chatMessagesLoading).toBe(false))+ await waitFor(() => expect(clerum.rpc.listSessions).toHaveBeenCalled())expect(result.current.activeChatId).toBeNull()})@@ -190,7 +270,9 @@ describe('pendingChatSelection effect', () => {expect(clerum.rpc.loadSessionMessages).toHaveBeenCalledWith('agent-x','agent-x',- 'c-specific'+ 'c-specific',+ undefined,+ { 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.tsxindex 07e598060..e2e121f4e 100644--- a/desktop-app/ui/src/hooks/domain/__tests__/switchToChat.unified.test.tsx+++ b/desktop-app/ui/src/hooks/domain/__tests__/switchToChat.unified.test.tsx@@ -8,6 +8,7 @@* registered progress handler for the task is the observable proof of rejoin.*/import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'+import { makeTaskKey } from '@contexts/AgentTaskTrackerContext/types'import { act, waitFor } from '@testing-library/react'import { renderController } from './__fixtures__/controllerHarness'import { type MockClerum, installMockClerum, uninstallMockClerum } from './__fixtures__/mockClerum'@@ -63,8 +64,14 @@ describe('switchToChat (unified, D.4)', () => {await result.current.switchToChat('agent-x', 'c1')})- expect(clerum.chat.loadMessages).toHaveBeenCalledWith('agent-x', 'c1', undefined, undefined)- expect(clerum.rpc.loadSessionMessages).toHaveBeenCalledWith('agent-x', 'agent-x', 'c1')+ expect(clerum.chat.loadMessages).toHaveBeenCalledWith('agent-x', 'c1', 80, undefined)+ expect(clerum.rpc.loadSessionMessages).toHaveBeenCalledWith(+ 'agent-x',+ 'agent-x',+ 'c1',+ undefined,+ { limit: 40, afterTurn: 1 }+ )expect(clerum.chat.replaceMessages).not.toHaveBeenCalled()expect(result.current.chatMessages).toHaveLength(2)})@@ -100,7 +107,7 @@ describe('switchToChat (unified, D.4)', () => {expect(result.current.chatMessages).toHaveLength(60)})- it('Phase 2 overwrites a stale cache when the server has more turns and persists via replace', async () => {+ it('Phase 2 persists the merged server delta to a durable-ID cache', async () => {clerum.chat.loadMessages.mockResolvedValue([{ id: 'turn-1-user', role: 'user' as const, content: 'q1', timestamp: 1 },])@@ -125,6 +132,728 @@ describe('switchToChat (unified, D.4)', () => {)})+ it('follows server delta pages until the active chat reaches the latest turn', async () => {+ clerum.chat.loadMessages.mockResolvedValue([+ { id: 'turn-1-user', role: 'user' as const, content: 'q1', timestamp: 1 },+ { id: 'turn-1-assistant', role: 'assistant' as const, content: 'a1', timestamp: 2 },+ ])+ clerum.rpc.loadSessionMessages+ .mockResolvedValueOnce({+ agent: 'agent-x',+ chatId: 'delta-pages',+ state: 'idle',+ totalTurns: 3,+ latestTurnNumber: 2,+ hasMoreAfter: true,+ turns: [turn(2, 'q2', 'a2')],+ })+ .mockResolvedValueOnce({+ agent: 'agent-x',+ chatId: 'delta-pages',+ state: 'idle',+ totalTurns: 3,+ latestTurnNumber: 3,+ hasMoreAfter: false,+ turns: [turn(3, 'q3', 'a3')],+ })+ const { result } = renderController()+ await settleMount()++ await act(async () => {+ await result.current.switchToChat('agent-x', 'delta-pages')+ })++ expect(clerum.rpc.loadSessionMessages).toHaveBeenNthCalledWith(+ 1,+ 'agent-x',+ 'agent-x',+ 'delta-pages',+ undefined,+ { limit: 40, afterTurn: 1 }+ )+ expect(clerum.rpc.loadSessionMessages).toHaveBeenNthCalledWith(+ 2,+ 'agent-x',+ 'agent-x',+ 'delta-pages',+ undefined,+ { limit: 40, afterTurn: 2 }+ )+ expect(result.current.chatMessages).toHaveLength(6)+ expect(clerum.chat.replaceMessages).toHaveBeenCalledWith(+ 'agent-x',+ 'delta-pages',+ expect.arrayContaining([+ expect.objectContaining({ id: 'turn-2-assistant' }),+ expect.objectContaining({ id: 'turn-3-assistant' }),+ ])+ )+ })++ it('keeps durable local bubbles in place and deduplicates trimmed server echoes', async () => {+ const turnTwoStartedAt = Date.parse('2026-05-28T10:02:00Z')+ clerum.chat.loadMessages.mockResolvedValue([+ {+ id: 'turn-1-user',+ role: 'user' as const,+ content: 'q1',+ timestamp: 1,+ serverTurnNumber: 1,+ },+ {+ id: 'turn-1-assistant',+ role: 'assistant' as const,+ content: 'a1',+ timestamp: 2,+ serverTurnNumber: 1,+ },+ {+ id: 'durable-error',+ role: 'assistant' as const,+ content: 'Recovered warning',+ timestamp: 3,+ isError: true,+ },+ {+ id: 'local-turn-2-user',+ role: 'user' as const,+ content: 'q2',+ timestamp: turnTwoStartedAt,+ },+ {+ id: 'local-turn-2-assistant',+ role: 'assistant' as const,+ content: 'a2 ',+ timestamp: turnTwoStartedAt + 5_000,+ },+ ])+ clerum.rpc.loadSessionMessages.mockResolvedValue({+ agent: 'agent-x',+ chatId: 'stable-local-order',+ state: 'idle',+ totalTurns: 2,+ hasMoreBefore: false,+ hasMoreAfter: false,+ turns: [turn(2, 'q2', 'a2')],+ })+ const { result } = renderController()+ await settleMount()++ await act(async () => {+ await result.current.switchToChat('agent-x', 'stable-local-order')+ })++ expect(result.current.chatMessages.map(message => message.id)).toEqual([+ 'turn-1-user',+ 'turn-1-assistant',+ 'durable-error',+ 'turn-2-user',+ 'turn-2-assistant',+ ])+ })++ it('caps server delta pagination so reconcile cannot walk an unbounded cursor chain', async () => {+ clerum.chat.loadMessages.mockResolvedValue([+ { id: 'turn-1-user', role: 'user' as const, content: 'q1', timestamp: 1 },+ { id: 'turn-1-assistant', role: 'assistant' as const, content: 'a1', timestamp: 2 },+ ])+ clerum.rpc.loadSessionMessages.mockImplementation(+ async (_hostRef, _agent, chatId, _teamId, query?: { afterTurn?: number }) => {+ if (query?.afterTurn === undefined) {+ return {+ agent: 'agent-x',+ chatId,+ state: 'idle',+ latestTurnNumber: 999,+ hasMoreBefore: true,+ hasMoreAfter: false,+ turns: [turn(999, 'newest question', 'newest answer')],+ }+ }+ const nextTurn = (query?.afterTurn ?? 1) + 1+ return {+ agent: 'agent-x',+ chatId,+ state: 'idle',+ latestTurnNumber: nextTurn,+ hasMoreAfter: true,+ turns: [turn(nextTurn, `q${nextTurn}`, `a${nextTurn}`)],+ }+ }+ )+ const { result } = renderController()+ await settleMount()++ await act(async () => {+ await result.current.switchToChat('agent-x', 'delta-cap')+ })++ expect(clerum.rpc.loadSessionMessages).toHaveBeenCalledTimes(6)+ expect(clerum.rpc.loadSessionMessages).toHaveBeenLastCalledWith(+ 'agent-x',+ 'agent-x',+ 'delta-cap',+ undefined,+ { limit: 40 }+ )+ expect(result.current.chatMessages.map(message => message.id)).toEqual([+ 'turn-1-user',+ 'turn-1-assistant',+ 'turn-2-user',+ 'turn-2-assistant',+ 'turn-3-user',+ 'turn-3-assistant',+ 'turn-4-user',+ 'turn-4-assistant',+ 'turn-5-user',+ 'turn-5-assistant',+ 'turn-6-user',+ 'turn-6-assistant',+ '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-2-user' }),+ expect.objectContaining({ id: 'turn-999-assistant' }),+ ]),+ {+ activeTaskIds: undefined,+ replaceLocalWindow: true,+ }+ )+ })++ it('loads older history into the first server-turn gap after a delta-cap fallback', async () => {+ const serverTurn = (n: number) => ({+ number: n,+ user_input: `q${n}`,+ response: `a${n}`,+ started_at: '2026-05-28T10:00:00Z',+ completed_at: '2026-05-28T10:00:05Z',+ })+ const localTail = [+ {+ id: 'turn-1-user',+ role: 'user' as const,+ content: 'q1',+ timestamp: 1,+ serverTurnNumber: 1,+ },+ {+ id: 'turn-1-assistant',+ role: 'assistant' as const,+ content: 'a1',+ timestamp: 2,+ serverTurnNumber: 1,+ },+ ]+ const latestWindow = Array.from({ length: 40 }, (_, index) => serverTurn(960 + index))+ const gapPage = Array.from({ length: 40 }, (_, index) => serverTurn(920 + index))+ clerum.chat.loadMessages.mockImplementation(+ async (_agentRef: string, _chatId: string, _limit?: number, offset?: number) =>+ offset ? [] : localTail+ )+ clerum.rpc.loadSessionMessages.mockImplementation(+ async (+ _hostRef: string,+ _agent: string,+ chatId: string,+ _teamId?: string,+ query?: { afterTurn?: number; beforeTurn?: number; limit?: number }+ ) => {+ if (query?.beforeTurn === 960) {+ return {+ agent: 'agent-x',+ chatId,+ state: 'idle',+ totalTurns: 999,+ oldestTurnNumber: 920,+ latestTurnNumber: 959,+ hasMoreBefore: true,+ hasMoreAfter: true,+ turns: gapPage,+ }+ }+ if (query?.afterTurn !== undefined) {+ const nextTurn = query.afterTurn + 1+ return {+ agent: 'agent-x',+ chatId,+ state: 'idle',+ latestTurnNumber: nextTurn,+ hasMoreAfter: true,+ turns: [serverTurn(nextTurn)],+ }+ }+ return {+ agent: 'agent-x',+ chatId,+ state: 'idle',+ totalTurns: 999,+ oldestTurnNumber: 960,+ latestTurnNumber: 999,+ hasMoreBefore: true,+ hasMoreAfter: false,+ turns: latestWindow,+ }+ }+ )+ const { result } = renderController()+ await settleMount()++ await act(async () => {+ await result.current.switchToChat('agent-x', 'delta-gap')+ })++ expect(result.current.hasOlderMessages).toBe(true)+ expect(result.current.chatMessages.map(message => message.serverTurnNumber)).toContain(960)++ await act(async () => {+ await result.current.handleLoadOlderMessages()+ })++ expect(clerum.rpc.loadSessionMessages).toHaveBeenLastCalledWith(+ 'agent-x',+ 'agent-x',+ 'delta-gap',+ undefined,+ { limit: 40, beforeTurn: 960 }+ )+ expect(result.current.chatMessages.map(message => message.id)).toContain('turn-920-user')+ expect(result.current.hasOlderMessages).toBe(true)+ })++ it('skips an unfillable server-turn gap after a no-progress older-page response', async () => {+ const serverTurn = (n: number) => ({+ number: n,+ user_input: `q${n}`,+ response: `a${n}`,+ started_at: '2026-05-28T10:00:00Z',+ completed_at: '2026-05-28T10:00:05Z',+ })+ clerum.chat.loadMessages.mockResolvedValue([])+ clerum.rpc.loadSessionMessages.mockImplementation(+ async (+ _hostRef: string,+ _agent: string,+ chatId: string,+ _teamId?: string,+ query?: { beforeTurn?: number; limit?: number }+ ) => {+ if (query?.beforeTurn === 61) {+ return {+ agent: 'agent-x',+ chatId,+ state: 'idle',+ totalTurns: 99,+ oldestTurnNumber: 58,+ latestTurnNumber: 60,+ hasMoreBefore: true,+ hasMoreAfter: true,+ turns: [58, 59, 60].map(serverTurn),+ }+ }+ if (query?.beforeTurn === 58) {+ return {+ agent: 'agent-x',+ chatId,+ state: 'idle',+ totalTurns: 99,+ oldestTurnNumber: 17,+ latestTurnNumber: 56,+ hasMoreBefore: true,+ hasMoreAfter: true,+ turns: Array.from({ length: 40 }, (_, index) => serverTurn(17 + index)),+ }+ }+ if (query?.beforeTurn === 17) {+ return {+ agent: 'agent-x',+ chatId,+ state: 'idle',+ totalTurns: 99,+ oldestTurnNumber: 1,+ latestTurnNumber: 16,+ hasMoreBefore: false,+ hasMoreAfter: true,+ turns: Array.from({ length: 16 }, (_, index) => serverTurn(1 + index)),+ }+ }+ return {+ agent: 'agent-x',+ chatId,+ state: 'idle',+ totalTurns: 99,+ oldestTurnNumber: 61,+ latestTurnNumber: 100,+ hasMoreBefore: true,+ hasMoreAfter: false,+ turns: Array.from({ length: 40 }, (_, index) => serverTurn(61 + index)),+ }+ }+ )+ const { result } = renderController()+ await settleMount()++ await act(async () => {+ await result.current.switchToChat('agent-x', 'missing-turn-gap')+ })+ await act(async () => {+ await result.current.handleLoadOlderMessages()+ })+ await act(async () => {+ await result.current.handleLoadOlderMessages()+ })+ await act(async () => {+ await result.current.handleLoadOlderMessages()+ })+ await act(async () => {+ await result.current.handleLoadOlderMessages()+ })++ const beforeTurns = clerum.rpc.loadSessionMessages.mock.calls+ .map(call => (call[4] as { beforeTurn?: number } | undefined)?.beforeTurn)+ .filter((turn): turn is number => turn !== undefined)+ expect(beforeTurns).toEqual([61, 58, 58, 17])+ expect(result.current.chatMessages.map(message => message.id)).toContain('turn-1-user')+ expect(result.current.hasOlderMessages).toBe(false)+ })++ it('loads older history on demand and prepends it without blocking first render', async () => {+ const newestLocalPage = Array.from({ length: 80 }, (_, index) => ({+ id: `turn-${index + 21}-user`,+ role: 'user' as const,+ content: `q${index + 21}`,+ timestamp: index + 21,+ }))+ clerum.chat.loadMessages.mockImplementation(+ async (_agentRef: string, _chatId: string, _limit?: number, offset?: number) =>+ offset ? [] : newestLocalPage+ )+ clerum.rpc.loadSessionMessages+ .mockResolvedValueOnce({+ agent: 'agent-x',+ chatId: 'older-pages',+ state: 'idle',+ totalTurns: 100,+ hasMoreBefore: true,+ hasMoreAfter: false,+ turns: [],+ })+ .mockResolvedValueOnce({+ agent: 'agent-x',+ chatId: 'older-pages',+ state: 'idle',+ totalTurns: 100,+ oldestTurnNumber: 1,+ latestTurnNumber: 20,+ hasMoreBefore: false,+ hasMoreAfter: true,+ turns: Array.from({ length: 20 }, (_, index) =>+ turn(index + 1, `q${index + 1}`, `a${index + 1}`)+ ),+ })+ const { result } = renderController()+ await settleMount()++ await act(async () => {+ await result.current.switchToChat('agent-x', 'older-pages')+ })++ expect(result.current.chatMessages).toHaveLength(80)+ expect(result.current.hasOlderMessages).toBe(true)++ await act(async () => {+ await result.current.handleLoadOlderMessages()+ })++ expect(clerum.rpc.loadSessionMessages).toHaveBeenLastCalledWith(+ 'agent-x',+ 'agent-x',+ 'older-pages',+ undefined,+ { limit: 40, beforeTurn: 21 }+ )+ expect(result.current.chatMessages).toHaveLength(120)+ expect(result.current.chatMessages[0]?.id).toBe('turn-1-user')+ expect(result.current.hasOlderMessages).toBe(false)+ expect(clerum.chat.replaceMessages).toHaveBeenCalledWith(+ 'agent-x',+ 'older-pages',+ expect.arrayContaining([expect.objectContaining({ id: 'turn-1-assistant' })])+ )++ clerum.rpc.loadSessionMessages.mockResolvedValueOnce({+ agent: 'agent-x',+ chatId: 'older-pages',+ state: 'idle',+ totalTurns: 101,+ oldestTurnNumber: 101,+ latestTurnNumber: 101,+ hasMoreBefore: true,+ hasMoreAfter: false,+ turns: [turn(101, 'q101', 'a101')],+ })+ await act(async () => {+ await result.current.reconcileChat(makeTaskKey('agent-x', 'older-pages'), {+ reason: 'system_resume',+ })+ })++ expect(result.current.chatMessages[0]?.id).toBe('turn-1-user')+ expect(result.current.chatMessages.at(-1)?.id).toBe('turn-101-assistant')+ })++ it('does not show older history for a complete exact-page-size local chat', async () => {+ const cached = Array.from({ length: 40 }, (_, index) =>+ turn(index + 1, `q${index + 1}`, `a${index + 1}`)+ ).flatMap(t => [+ { id: `turn-${t.number}-user`, role: 'user' as const, content: t.user_input, timestamp: 1 },+ {+ id: `turn-${t.number}-assistant`,+ role: 'assistant' as const,+ content: t.response!,+ timestamp: 2,+ },+ ])+ clerum.chat.loadMessages.mockImplementation(+ async (_agentRef: string, _chatId: string, _limit?: number, offset?: number) =>+ offset ? [] : cached+ )+ clerum.rpc.loadSessionMessages.mockResolvedValue({+ agent: 'agent-x',+ chatId: 'exact-page',+ state: 'idle',+ turns: [],+ hasMoreBefore: false,+ hasMoreAfter: false,+ })+ const { result } = renderController()+ await settleMount()++ await act(async () => {+ await result.current.switchToChat('agent-x', 'exact-page')+ })++ expect(clerum.chat.loadMessages).toHaveBeenCalledWith('agent-x', 'exact-page', 1, 80)+ expect(result.current.chatMessages).toHaveLength(80)+ expect(result.current.hasOlderMessages).toBe(false)+ })++ it('ignores hasMoreBefore from an empty afterTurn reconciliation response', async () => {+ const cached = [+ {+ id: 'turn-1-user',+ role: 'user' as const,+ content: 'q1',+ timestamp: 1,+ serverTurnNumber: 1,+ },+ {+ id: 'turn-1-assistant',+ role: 'assistant' as const,+ content: 'a1',+ timestamp: 2,+ serverTurnNumber: 1,+ },+ ]+ clerum.chat.loadMessages.mockResolvedValue(cached)+ clerum.rpc.loadSessionMessages.mockResolvedValue({+ agent: 'agent-x',+ chatId: 'synced-chat',+ state: 'idle',+ turns: [],+ hasMoreBefore: true,+ hasMoreAfter: false,+ })+ const { result } = renderController()+ await settleMount()++ await act(async () => {+ await result.current.switchToChat('agent-x', 'synced-chat')+ })++ expect(clerum.rpc.loadSessionMessages).toHaveBeenCalledWith(+ 'agent-x',+ 'agent-x',+ 'synced-chat',+ undefined,+ { limit: 40, afterTurn: 1 }+ )+ expect(result.current.chatMessages.map(message => message.id)).toEqual([+ 'turn-1-user',+ 'turn-1-assistant',+ ])+ expect(result.current.hasOlderMessages).toBe(false)+ })++ it('does not keep older history visible after loading an exact multiple of local pages', async () => {+ const allMessages = Array.from({ length: 160 }, (_, index) => ({+ id: `turn-${index + 1}-user`,+ role: 'user' as const,+ content: `q${index + 1}`,+ timestamp: index + 1,+ }))+ const firstVisiblePage = allMessages.slice(80)+ const olderPage = allMessages.slice(0, 80)+ clerum.chat.loadMessages.mockImplementation(+ async (_agentRef: string, chatId: string, _limit?: number, offset?: number) => {+ if (chatId !== 'exact-local-pages') return []+ if (offset === undefined) return firstVisiblePage+ if (offset === 80) return olderPage+ return []+ }+ )+ clerum.rpc.loadSessionMessages.mockResolvedValue({+ agent: 'agent-x',+ chatId: 'exact-local-pages',+ state: 'idle',+ turns: [],+ hasMoreBefore: false,+ hasMoreAfter: false,+ })+ const { result } = renderController()+ await settleMount()++ await act(async () => {+ await result.current.switchToChat('agent-x', 'exact-local-pages')+ })+ expect(result.current.hasOlderMessages).toBe(true)++ await act(async () => {+ await result.current.handleLoadOlderMessages()+ })++ expect(clerum.chat.loadMessages).toHaveBeenCalledWith('agent-x', 'exact-local-pages', 1, 160)+ expect(result.current.chatMessages).toHaveLength(160)+ expect(result.current.hasOlderMessages).toBe(false)+ expect(clerum.rpc.loadSessionMessages).toHaveBeenCalledTimes(1)+ })++ it('cancels an in-flight older-page request when switching chats', async () => {+ let resolveOlder!: (messages: unknown[]) => void+ const olderPage = new Promise<unknown[]>(resolve => {+ resolveOlder = resolve+ })+ clerum.chat.loadMessages.mockImplementation(+ async (_agentRef: string, chatId: string, _limit?: number, offset?: number) => {+ if (chatId === 'chat-a' && offset === 1) return olderPage+ if (chatId === 'chat-a') {+ return [+ {+ id: 'turn-10-user',+ role: 'user' as const,+ content: 'q10',+ timestamp: 10,+ serverTurnNumber: 10,+ },+ ]+ }+ return []+ }+ )+ clerum.rpc.loadSessionMessages.mockResolvedValue({+ agent: 'agent-x',+ chatId: 'chat-a',+ state: 'idle',+ turns: [],+ hasMoreBefore: true,+ hasMoreAfter: false,+ })+ const { result } = renderController()+ await settleMount()+ await act(async () => {+ await result.current.switchToChat('agent-x', 'chat-a')+ })++ let pendingOlder!: Promise<void>+ act(() => {+ pendingOlder = result.current.handleLoadOlderMessages()+ })+ await waitFor(() => expect(result.current.olderMessagesLoading).toBe(true))++ await act(async () => {+ await result.current.switchToChat('agent-x', 'chat-b')+ })+ expect(result.current.olderMessagesLoading).toBe(false)++ resolveOlder([])+ await act(async () => {+ await pendingOlder+ })+ expect(result.current.olderMessagesLoading).toBe(false)+ })++ it('ignores an older-page response when switching away and back before it resolves', async () => {+ let resolveOlder!: (messages: unknown[]) => void+ const olderPage = new Promise<unknown[]>(resolve => {+ resolveOlder = resolve+ })+ clerum.chat.loadMessages.mockImplementation(+ async (_agentRef: string, chatId: string, _limit?: number, offset?: number) => {+ if (chatId === 'chat-a' && offset === 1) return olderPage+ if (chatId === 'chat-a') {+ return [+ {+ id: 'turn-10-user',+ role: 'user' as const,+ content: 'q10',+ timestamp: 10,+ serverTurnNumber: 10,+ },+ ]+ }+ return []+ }+ )+ clerum.rpc.loadSessionMessages.mockImplementation(+ async (_hostRef: string, _agent: string, chatId: string) => ({+ agent: 'agent-x',+ chatId,+ state: 'idle',+ turns: [],+ hasMoreBefore: false,+ hasMoreAfter: false,+ })+ )+ const { result } = renderController()+ await settleMount()+ await act(async () => {+ await result.current.switchToChat('agent-x', 'chat-a')+ })++ let pendingOlder!: Promise<void>+ act(() => {+ pendingOlder = result.current.handleLoadOlderMessages()+ })+ await waitFor(() => expect(result.current.olderMessagesLoading).toBe(true))++ await act(async () => {+ await result.current.switchToChat('agent-x', 'chat-b')+ await result.current.switchToChat('agent-x', 'chat-a')+ })++ resolveOlder([+ {+ id: 'turn-1-user',+ role: 'user',+ content: 'stale q1',+ timestamp: 1,+ serverTurnNumber: 1,+ },+ ])+ await act(async () => {+ await pendingOlder+ })++ expect(result.current.chatMessages.map(message => message.id)).toEqual(['turn-10-user'])+ expect(result.current.olderMessagesLoading).toBe(false)+ })+it('adds a server-only chat to the sidebar when switched to directly (S4)', async () => {// chatList starts empty (default getIndex → no chats); simulate opening a// notification for a chat the local list doesn't know about.@@ -292,6 +1021,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 () => {@@ -436,7 +1174,7 @@ describe('switchToChat (unified, D.4)', () => {await result.current.switchToChat('agent-x', 'z1')})- // With the zombie acked, the replace lands and both messages render.+ // With the zombie acked, the missing durable assistant message is persisted.expect(result.current.chatMessages).toHaveLength(2)expect(clerum.chat.replaceMessages).toHaveBeenCalledWith('agent-x',@@ -527,7 +1265,7 @@ describe('switchToChat (unified, D.4)', () => {await result.current.switchToChat('agent-x', 'pa')})- // The retry landed the durable reply: replace fired, zombie acked, NOT offline.+ // The retry landed the durable reply: merged window persisted, zombie acked, NOT offline.expect(result.current.chatMessages).toHaveLength(2)expect(clerum.chat.replaceMessages).toHaveBeenCalledWith('agent-x',@@ -649,7 +1387,7 @@ describe('switchToChat (unified, D.4)', () => {await sw})- // The residual (task-pb) was acked and the durable reply replaced the cache.+ // The residual was acked and the durable reply was persisted to the cache.expect(result.current.chatMessages).toHaveLength(2)expect(clerum.chat.replaceMessages).toHaveBeenCalledWith('agent-x',diff --git a/desktop-app/ui/src/hooks/domain/__tests__/useActivityController.test.tsx b/desktop-app/ui/src/hooks/domain/__tests__/useActivityController.test.tsxnew file mode 100644index 000000000..c8835c9ce--- /dev/null+++ b/desktop-app/ui/src/hooks/domain/__tests__/useActivityController.test.tsx@@ -0,0 +1,250 @@+// @vitest-environment jsdom+import { afterEach, describe, expect, it, vi } from 'vitest'+import { renderHook, waitFor } from '@testing-library/react'+import { useActivityController } from '../useActivityController'++const AGENT_A = ['agent-a']+const TWO_AGENTS = ['agent-a', 'agent-b']+const EMPTY_CHAT_LIST: [] = []+const EMPTY_PROGRESS = {}++function installChatIndexMock() {+ const getIndex = vi.fn(async (agentRef: string) => ({+ version: 2,+ lastActiveChatId: null,+ onboardingDismissed: false,+ chats: [+ {+ id: `${agentRef}-chat`,+ title: 'Chat',+ createdAt: '2026-07-20T00:00:00.000Z',+ updatedAt: '2026-07-22T00:00:00.000Z',+ messageCount: 3,+ },+ ],+ }))+ Object.defineProperty(window, 'clerum', {+ configurable: true,+ value: {+ chat: { getIndex },+ },+ })+ return getIndex+}++describe('useActivityController', () => {+ afterEach(() => {+ vi.restoreAllMocks()+ delete (window as { clerum?: unknown }).clerum+ })++ it('computes activity from index metadata without reading conversation histories', () => {+ installChatIndexMock()+ const { result } = renderHook(() =>+ useActivityController({+ selectedAgent: 'agent-a',+ isAuthenticated: true,+ loadMenuData: false,+ chatList: [+ {+ id: 'chat-1',+ title: 'One',+ createdAt: '2026-07-22T00:00:00.000Z',+ updatedAt: '2026-07-22T00:00:00.000Z',+ messageCount: 12,+ errorCount: 2,+ toolCallCount: 4,+ },+ ],+ progressByAgentMessage: EMPTY_PROGRESS,+ agentNames: AGENT_A,+ })+ )++ expect(result.current.selectedAgentActivitySummary).toMatchObject({+ conversations: 1,+ messages: 12,+ errors: 2,+ toolCalls: 4,+ })+ })++ it('waits until after first paint before loading agent menu metadata', async () => {+ const getIndex = installChatIndexMock()+ const initialProps = { loadMenuData: false }+ const { rerender } = renderHook(+ ({ loadMenuData }: typeof initialProps) =>+ useActivityController({+ selectedAgent: null,+ isAuthenticated: true,+ loadMenuData,+ chatList: EMPTY_CHAT_LIST,+ progressByAgentMessage: EMPTY_PROGRESS,+ agentNames: TWO_AGENTS,+ }),+ { initialProps }+ )++ expect(getIndex).not.toHaveBeenCalled()+ rerender({ loadMenuData: true })++ await waitFor(() => expect(getIndex).toHaveBeenCalledTimes(2))+ })++ it('backfills missing activity counters for chats created before metadata counters existed', async () => {+ const getIndex = vi.fn(async () => ({+ version: 3,+ lastActiveChatId: null,+ onboardingDismissed: false,+ chats: [],+ }))+ const loadMessages = vi.fn(async () => [+ { id: 'm1', role: 'user', content: 'hello', timestamp: 1 },+ {+ id: 'm2',+ role: 'assistant',+ content: 'failed',+ timestamp: 2,+ isError: true,+ toolSteps: [{ toolName: 'read', displayName: 'Read', state: 'completed' }],+ },+ ])+ const backfillCounters = vi.fn().mockResolvedValue(undefined)+ Object.defineProperty(window, 'clerum', {+ configurable: true,+ value: { chat: { getIndex, loadMessages, backfillCounters } },+ })++ const { result } = renderHook(() =>+ useActivityController({+ selectedAgent: 'agent-a',+ isAuthenticated: true,+ loadMenuData: true,+ chatList: [+ {+ id: 'legacy-chat',+ title: 'Legacy',+ createdAt: '2026-07-22T00:00:00.000Z',+ updatedAt: '2026-07-22T00:00:00.000Z',+ messageCount: 2,+ },+ ],+ progressByAgentMessage: EMPTY_PROGRESS,+ agentNames: AGENT_A,+ })+ )++ await waitFor(() =>+ expect(result.current.selectedAgentActivitySummary).toMatchObject({+ errors: 1,+ toolCalls: 1,+ })+ )+ expect(loadMessages).toHaveBeenCalledWith('agent-a', 'legacy-chat', 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.crossChat.test.tsx b/desktop-app/ui/src/hooks/domain/__tests__/useAgentChatController.crossChat.test.tsxindex 11d8d9e47..6c827f126 100644--- a/desktop-app/ui/src/hooks/domain/__tests__/useAgentChatController.crossChat.test.tsx+++ b/desktop-app/ui/src/hooks/domain/__tests__/useAgentChatController.crossChat.test.tsx@@ -104,6 +104,7 @@ function AgentChatHarness() {currentTeamId: 'team-1',currentTeamName: 'Team One',isAuthenticated: true,+ loadMenuData: true,navItem: 'chat',pushToast: vi.fn(),pushNotification: vi.fn(),@@ -132,9 +133,9 @@ function AgentChatHarness() {<button type="button" onClick={() => void vm.handleSendAgentMessage('hello')}>Send message</button>- {vm.chatList.map((chat, index) => (+ {vm.chatList.map(chat => (<button key={chat.id} type="button" onClick={() => void vm.handleSelectChat(chat.id)}>- Select chat {index + 1}+ Select chat {chat.id}</button>))}</div>@@ -224,6 +225,8 @@ describe('useAgentChatController (cross-chat, migrated)', () => {await waitFor(() =>expect(screen.getByTestId('active-chat-id').textContent).not.toBe(firstChatId))+ const secondChatId = screen.getByTestId('active-chat-id').textContent || ''+ expect(secondChatId).not.toBe('')expect(getDraftInputValue()).toBe('')fireEvent.change(screen.getByTestId('draft-input'), {@@ -231,14 +234,12 @@ describe('useAgentChatController (cross-chat, migrated)', () => {})expect(getDraftInputValue()).toBe('draft for session B')- fireEvent.click(screen.getByRole('button', { name: 'Select chat 1' }))+ fireEvent.click(screen.getByRole('button', { name: `Select chat ${firstChatId}` }))await waitFor(() => expect(screen.getByTestId('active-chat-id').textContent).toBe(firstChatId))expect(getDraftInputValue()).toBe('draft for session A')- fireEvent.click(screen.getByRole('button', { name: 'Select chat 2' }))- await waitFor(() =>- expect(screen.getByTestId('active-chat-id').textContent).not.toBe(firstChatId)- )+ fireEvent.click(screen.getByRole('button', { name: `Select chat ${secondChatId}` }))+ await waitFor(() => expect(screen.getByTestId('active-chat-id').textContent).toBe(secondChatId))expect(getDraftInputValue()).toBe('draft for session B')})})diff --git a/desktop-app/ui/src/hooks/domain/__tests__/useAgentChatController.pendingModel.test.tsx b/desktop-app/ui/src/hooks/domain/__tests__/useAgentChatController.pendingModel.test.tsxindex e49afafd3..fe3c27a50 100644--- a/desktop-app/ui/src/hooks/domain/__tests__/useAgentChatController.pendingModel.test.tsx+++ b/desktop-app/ui/src/hooks/domain/__tests__/useAgentChatController.pendingModel.test.tsx@@ -96,6 +96,7 @@ function AgentChatHarness() {currentTeamId: 'team-1',currentTeamName: 'Team One',isAuthenticated: true,+ loadMenuData: true,navItem: 'chat',pushToast: vi.fn(),pushNotification: vi.fn(),diff --git a/desktop-app/ui/src/hooks/domain/__tests__/useAgentChatController.test.tsx b/desktop-app/ui/src/hooks/domain/__tests__/useAgentChatController.test.tsxindex ebc376dbe..d75799aa8 100644--- a/desktop-app/ui/src/hooks/domain/__tests__/useAgentChatController.test.tsx+++ b/desktop-app/ui/src/hooks/domain/__tests__/useAgentChatController.test.tsx@@ -70,7 +70,13 @@ describe('useAgentChatController — characterization (D.0)', () => {expect(clerum.chat.setLastActive).toHaveBeenCalledWith('agent-x', 'chat-1')// Phase 2 now always reconciles with the server.- expect(clerum.rpc.loadSessionMessages).toHaveBeenCalledWith('agent-x', 'agent-x', 'chat-1')+ expect(clerum.rpc.loadSessionMessages).toHaveBeenCalledWith(+ 'agent-x',+ 'agent-x',+ 'chat-1',+ undefined,+ { limit: 40 }+ )// Cache was up to date → no overwrite, no rejoin.expect(clerum.chat.replaceMessages).not.toHaveBeenCalled()expect(result.current.chatMessages).toHaveLength(3)@@ -100,7 +106,13 @@ describe('useAgentChatController — characterization (D.0)', () => {await result.current.switchToChat('agent-x', 'chat-2')})- expect(clerum.rpc.loadSessionMessages).toHaveBeenCalledWith('agent-x', 'agent-x', 'chat-2')+ expect(clerum.rpc.loadSessionMessages).toHaveBeenCalledWith(+ 'agent-x',+ 'agent-x',+ 'chat-2',+ undefined,+ { limit: 40 }+ )expect(clerum.chat.create).toHaveBeenCalledWith('agent-x', 'chat-2')// Server is source of truth → replace, not append.expect(clerum.chat.replaceMessages).toHaveBeenCalled()@@ -725,8 +737,8 @@ describe('useAgentChatController — characterization (D.0)', () => {})})- // The durable reply lands; no error/resend, no zombie blocking the replace.- await waitFor(() => expect(clerum.chat.replaceMessages).toHaveBeenCalled())+ // The durable reply lands as a delta; no error/resend and no zombie block.+ await waitFor(() => expect(clerum.chat.appendMessages).toHaveBeenCalled())expect(spies.pushToast).not.toHaveBeenCalledWith(expect.stringContaining('failed'), 'error')expect(result.current.failedAgentSend).toBeNull()await sendPromise@@ -931,6 +943,23 @@ describe('useAgentChatController — characterization (D.0)', () => {* the D.3 reweave (the behaviors survive; only the lifecycle plumbing moves).*/describe('dev behaviors (must survive the D.3 reweave)', () => {+ it('defers cross-agent menu sessions until the first screen has painted', async () => {+ const { rerender } = renderController({+ selectedAgent: null,+ loadMenuData: false,+ })+ await act(async () => {+ await Promise.resolve()+ })++ expect(clerum.chat.getIndex).not.toHaveBeenCalled()+ expect(clerum.rpc.listSessions).not.toHaveBeenCalled()++ rerender({ selectedAgent: null, loadMenuData: true })++ await waitFor(() => expect(clerum.chat.getIndex).toHaveBeenCalled())+ })+it('GAP-D populates latestChatSessions from chat.getIndex on mount', async () => {clerum.chat.getIndex.mockResolvedValue({version: 1,@@ -952,6 +981,274 @@ describe('useAgentChatController — characterization (D.0)', () => {expect(entry?.agentRef).toBe('agent-x')})+ it('renders local sessions without waiting for remote listSessions', async () => {+ clerum.chat.getIndex.mockResolvedValue({+ version: 1,+ lastActiveChatId: null,+ onboardingDismissed: false,+ chats: [+ {+ id: 'local-chat',+ title: 'Local chat',+ createdAt: '2026-05-01T00:00:00Z',+ updatedAt: '2026-05-01T00:00:00Z',+ messageCount: 2,+ },+ ],+ })+ clerum.rpc.listSessions.mockImplementation(() => new Promise(() => undefined))++ const { result } = renderController()++ await waitFor(() =>+ expect(result.current.chatList.some(chat => chat.id === 'local-chat')).toBe(true)+ )+ expect(result.current.chatListLoading).toBe(false)++ await waitFor(() =>+ expect(result.current.latestChatSessions.some(chat => chat.id === 'local-chat')).toBe(true)+ )+ 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 }) => {+ if (query?.cursor === 'cursor-2') {+ return {+ items: [+ {+ agent: 'agent-x',+ chatId: 'remote-page-2',+ turnCount: 3,+ lastActivityAt: '2026-05-02T00:00:00Z',+ },+ ],+ }+ }+ return {+ items: [+ {+ agent: 'agent-x',+ chatId: 'remote-page-1',+ turnCount: 2,+ lastActivityAt: '2026-05-03T00:00:00Z',+ },+ ],+ nextCursor: 'cursor-2',+ }+ }+ )++ const { result } = renderController()++ await waitFor(() =>+ expect(result.current.chatList.some(chat => chat.id === 'remote-page-1')).toBe(true)+ )+ expect(result.current.chatListHasMoreRemoteSessions).toBe(true)+ expect(+ clerum.rpc.listSessions.mock.calls.some(+ call => (call[2] as { cursor?: string } | undefined)?.cursor === 'cursor-2'+ )+ ).toBe(false)++ await act(async () => {+ await result.current.loadMoreChatSessions()+ })++ await waitFor(() =>+ expect(result.current.chatList.some(chat => chat.id === 'remote-page-2')).toBe(true)+ )+ expect(result.current.chatListHasMoreRemoteSessions).toBe(false)+ expect(+ clerum.rpc.listSessions.mock.calls.some(+ call => (call[2] as { cursor?: string } | undefined)?.cursor === 'cursor-2'+ )+ ).toBe(true)+ })++ it('keeps the remote session cursor after a transient load-more failure', async () => {+ let cursorTwoCalls = 0+ clerum.rpc.listSessions.mockImplementation(+ async (_hostRef: string, _teamId: string | undefined, query?: { cursor?: string }) => {+ if (query?.cursor === 'cursor-2') {+ cursorTwoCalls += 1+ if (cursorTwoCalls === 1) throw new Error('fetch failed')+ return {+ items: [+ {+ agent: 'agent-x',+ chatId: 'remote-page-2-after-retry',+ turnCount: 3,+ lastActivityAt: '2026-05-02T00:00:00Z',+ },+ ],+ }+ }+ return {+ items: [+ {+ agent: 'agent-x',+ chatId: 'remote-page-1',+ turnCount: 2,+ lastActivityAt: '2026-05-03T00:00:00Z',+ },+ ],+ nextCursor: 'cursor-2',+ }+ }+ )++ const { result } = renderController()++ await waitFor(() =>+ expect(result.current.chatList.some(chat => chat.id === 'remote-page-1')).toBe(true)+ )+ expect(result.current.chatListHasMoreRemoteSessions).toBe(true)++ await act(async () => {+ await result.current.loadMoreChatSessions()+ })++ expect(result.current.chatListHasMoreRemoteSessions).toBe(true)++ await act(async () => {+ await result.current.loadMoreChatSessions()+ })++ await waitFor(() =>+ expect(result.current.chatList.some(chat => chat.id === 'remote-page-2-after-retry')).toBe(+ true+ )+ )+ expect(cursorTwoCalls).toBe(2)+ expect(result.current.chatListHasMoreRemoteSessions).toBe(false)+ })++ it('does not advance a session cursor from a stale load-more result', async () => {+ let resolveStalePage:+ | ((value: {+ items: Array<{+ agent: string+ chatId: string+ turnCount: number+ lastActivityAt: string+ }>+ nextCursor?: string+ }) => void)+ | undefined+ const stalePage = new Promise<{+ items: Array<{+ agent: string+ chatId: string+ turnCount: number+ lastActivityAt: string+ }>+ nextCursor?: string+ }>(resolve => {+ resolveStalePage = resolve+ })+ let cursorTwoCalls = 0+ clerum.rpc.listSessions.mockImplementation(+ async (hostRef: string, _teamId: string | undefined, query?: { cursor?: string }) => {+ if (hostRef === 'agent-y') return { items: [] }+ if (query?.cursor === 'cursor-2') {+ cursorTwoCalls += 1+ if (cursorTwoCalls === 1) return stalePage+ return {+ items: [+ {+ agent: 'agent-x',+ chatId: 'remote-page-2-retry',+ turnCount: 3,+ lastActivityAt: '2026-05-02T00:00:00Z',+ },+ ],+ }+ }+ return {+ items: [+ {+ agent: 'agent-x',+ chatId: 'remote-page-1',+ turnCount: 2,+ lastActivityAt: '2026-05-03T00:00:00Z',+ },+ ],+ nextCursor: 'cursor-2',+ }+ }+ )++ const { result, rerender } = renderController({ agentNames: ['agent-x', 'agent-y'] })+ await waitFor(() =>+ expect(result.current.chatList.some(chat => chat.id === 'remote-page-1')).toBe(true)+ )++ let pendingLoad: Promise<void> | undefined+ await act(async () => {+ pendingLoad = result.current.loadMoreChatSessions()+ await Promise.resolve()+ })+ rerender({ selectedAgent: 'agent-y', agentNames: ['agent-x', 'agent-y'] })+ resolveStalePage?.({+ items: [+ {+ agent: 'agent-x',+ chatId: 'stale-remote-page',+ turnCount: 4,+ lastActivityAt: '2026-05-04T00:00:00Z',+ },+ ],+ nextCursor: 'cursor-3',+ })+ await act(async () => {+ await pendingLoad+ })++ expect(cursorTwoCalls).toBe(1)+ expect(+ clerum.rpc.listSessions.mock.calls.some(+ call => (call[2] as { cursor?: string } | undefined)?.cursor === 'cursor-3'+ )+ ).toBe(false)+ expect(result.current.chatList.some(chat => chat.id === 'stale-remote-page')).toBe(false)+ })+it('GAP-A persists the outgoing user message to the chat store on send', async () => {// Eager user-message persistence (dev) → D.3 must keep persisting it// (post-D.3 it carries task_id; here we only pin that it IS persisted).diff --git a/desktop-app/ui/src/hooks/domain/__tests__/useHostPrewarmController.chatIntegration.test.tsx b/desktop-app/ui/src/hooks/domain/__tests__/useHostPrewarmController.chatIntegration.test.tsxindex 1749fe602..b7a4f5829 100644--- a/desktop-app/ui/src/hooks/domain/__tests__/useHostPrewarmController.chatIntegration.test.tsx+++ b/desktop-app/ui/src/hooks/domain/__tests__/useHostPrewarmController.chatIntegration.test.tsx@@ -90,6 +90,7 @@ function useBothControllers({ selectedAgent, agentNames, isAuthenticated, navItecurrentTeamId: 'team-1',currentTeamName: 'Team 1',isAuthenticated,+ loadMenuData: true,navItem,...stableCallbacks,})diff --git a/desktop-app/ui/src/hooks/domain/reconcileChat.ts b/desktop-app/ui/src/hooks/domain/reconcileChat.tsindex 404a1f0fc..57fa7ab90 100644--- a/desktop-app/ui/src/hooks/domain/reconcileChat.ts+++ b/desktop-app/ui/src/hooks/domain/reconcileChat.ts@@ -1,5 +1,5 @@import { parseTaskKey } from '@contexts/AgentTaskTrackerContext'-import type { SessionMessagesResult } from '../../../../src/types'+import type { SessionMessagesQuery, SessionMessagesResult } from '../../../../src/types'import type { SessionFsmStore } from './sessionFsm'/**@@ -38,7 +38,11 @@ export type ReconcileOutcome =export interface ReconcileChatDeps {fsm: SessionFsmStore/** Fetch the durable server session state (turns + recovery fields). */- loadSessionMessages: (agentRef: string, chatId: string) => Promise<SessionMessagesResult>+ loadSessionMessages: (+ agentRef: string,+ chatId: string,+ query?: SessionMessagesQuery+ ) => Promise<SessionMessagesResult>/*** Server reports a live (`processing`/`awaiting_approval`) task: seed the* snapshot and attach a stream via the coordinator. Returns the outcome@@ -87,6 +91,8 @@ export interface ReconcileChatArgs {reason: string/** The task this reconcile is settling — drives the idle durable fallback. */taskIdHint?: string+ /** Bounded page or delta request used by the authoritative transcript fetch. */+ messagesQuery?: SessionMessagesQuery/*** Per-call relevance guard (in addition to the dep-level `isStillRelevant` and* the `reset()` generation). A `switchToChat`-initiated reconcile passes the@@ -147,12 +153,13 @@ export function createReconcileChat(deps: ReconcileChatDeps): ReconcileChat {async function fetchWithRetry(agentRef: string,chatId: string,- stillRelevant: () => boolean+ stillRelevant: () => boolean,+ query?: SessionMessagesQuery): Promise<SessionMessagesResult | undefined> {for (let attempt = 0; attempt < attempts; attempt++) {if (!stillRelevant()) return undefinedtry {- return await deps.loadSessionMessages(agentRef, chatId)+ return await deps.loadSessionMessages(agentRef, chatId, query)} catch (err) {// Non-network (404, etc.) rethrows to the branch handler; a network blip// is retried with backoff up to the cap (mirrors switchToChat P2-A).@@ -179,7 +186,7 @@ export function createReconcileChat(deps: ReconcileChatDeps): ReconcileChat {deps.fsm.dispatch(chatKey, { type: 'RECONCILE_STARTED' })let outcome: ReconcileOutcome = 'noop'try {- const resp = await fetchWithRetry(agentRef, chatId, stillRelevant)+ const resp = await fetchWithRetry(agentRef, chatId, stillRelevant, args.messagesQuery)if (!resp) {outcome = 'noop'return outcomediff --git a/desktop-app/ui/src/hooks/domain/useActivityController.ts b/desktop-app/ui/src/hooks/domain/useActivityController.tsindex 09e9db677..af01c00d0 100644--- a/desktop-app/ui/src/hooks/domain/useActivityController.ts+++ b/desktop-app/ui/src/hooks/domain/useActivityController.ts@@ -1,26 +1,28 @@-import { useEffect, useState } from 'react'+import { useEffect, useMemo, useState } from 'react'import type { TaskProgress } from '../../uiTypes'import { useChatStore } from '../useChatStore'import type { SidebarChatEntry } from './useAgentChatController'-const ACTIVITY_SUMMARY_CHAT_SCAN_LIMIT = 20--function getChatUpdatedTimestamp(chat: { updatedAt: string }): number {- const timestamp = Date.parse(chat.updatedAt)- return Number.isNaN(timestamp) ? 0 : timestamp-}-interface UseActivityControllerParams {selectedAgent: string | nullisAuthenticated: boolean+ loadMenuData: booleanchatList: SidebarChatEntry[]progressByAgentMessage: Record<string, Record<string, TaskProgress>>agentNames: string[]}+const ACTIVITY_SUMMARY_CHAT_SCAN_LIMIT = 20+const ACTIVITY_SUMMARY_MESSAGE_SCAN_LIMIT = 1000++function activityCounterKey(agentRef: string, chatId: string): string {+ return `${agentRef}\u0000${chatId}`+}+export function useActivityController({selectedAgent,isAuthenticated,+ loadMenuData,chatList,progressByAgentMessage,agentNames,@@ -30,17 +32,136 @@ export function useActivityController({const [agentLastActiveByAgent, setAgentLastActiveByAgent] = useState<Record<string, string | null>>({})- const [selectedAgentActivitySummary, setSelectedAgentActivitySummary] = useState({- conversations: 0,- messages: 0,- toolCalls: 0,- errors: 0,- conversationsPerDay: [] as Array<{ dayLabel: string; count: number }>,- })+ const [backfilledCountersByChat, setBackfilledCountersByChat] = useState<+ Record<string, { errors: number; toolCalls: number }>+ >({})+ const selectedAgentActivitySummary = useMemo(() => {+ if (!selectedAgent) {+ return {+ conversations: 0,+ messages: 0,+ toolCalls: 0,+ errors: 0,+ conversationsPerDay: [] as Array<{ dayLabel: string; count: number }>,+ }+ }++ const dateCursor = new Date()+ const dayKeys: string[] = []+ for (let index = 6; index >= 0; index -= 1) {+ const day = new Date(dateCursor)+ day.setDate(day.getDate() - index)+ dayKeys.push(day.toISOString().slice(0, 10))+ }++ const conversationsPerDayMap = new Map<string, number>(dayKeys.map(key => [key, 0]))+ let totalMessages = 0+ let totalErrors = 0+ let persistedToolCalls = 0++ for (const chat of chatList) {+ const backfilledCounters =+ backfilledCountersByChat[activityCounterKey(selectedAgent, chat.id)]+ totalMessages += chat.messageCount || 0+ totalErrors += chat.errorCount ?? backfilledCounters?.errors ?? 0+ persistedToolCalls += chat.toolCallCount ?? backfilledCounters?.toolCalls ?? 0++ const chatTimestamp = Date.parse(chat.updatedAt)+ if (Number.isNaN(chatTimestamp)) continue+ const chatDateKey = new Date(chatTimestamp).toISOString().slice(0, 10)+ if (conversationsPerDayMap.has(chatDateKey)) {+ conversationsPerDayMap.set(chatDateKey, (conversationsPerDayMap.get(chatDateKey) || 0) + 1)+ }+ }++ const liveToolCalls = Object.values(progressByAgentMessage[selectedAgent] || {}).reduce(+ (total, progress) => total + progress.steps.length,+ 0+ )+ const formatter = new Intl.DateTimeFormat(undefined, { month: 'short', day: 'numeric' })++ return {+ conversations: chatList.length,+ messages: totalMessages,+ toolCalls: Math.max(persistedToolCalls, liveToolCalls),+ errors: totalErrors,+ conversationsPerDay: [...conversationsPerDayMap.entries()].map(([dayKey, count]) => ({+ dayLabel: formatter.format(new Date(dayKey)),+ count,+ })),+ }+ }, [backfilledCountersByChat, chatList, progressByAgentMessage, selectedAgent])++ const missingCounterChatIds = JSON.stringify(+ chatList+ .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)+ )++ useEffect(() => {+ if (!isAuthenticated || !loadMenuData || !selectedAgent) {+ setBackfilledCountersByChat({})+ return+ }+ const chatIds = JSON.parse(missingCounterChatIds) as string[]+ if (!chatIds.length) return++ let cancelled = false+ void Promise.all(+ chatIds.map(async chatId => {+ const messages = await chatStore+ .loadMessages(selectedAgent, chatId, ACTIVITY_SUMMARY_MESSAGE_SCAN_LIMIT)+ .catch(() => [])+ try {+ await chatStore.backfillCounters(selectedAgent, chatId, messages)+ } catch {+ // Older preload bridges cannot persist the backfill; keep the computed+ // renderer value for this session and retry after the app upgrades.+ }+ return [+ activityCounterKey(selectedAgent, chatId),+ {+ errors: messages.reduce((total, message) => total + (message.isError ? 1 : 0), 0),+ toolCalls: messages.reduce(+ (total, message) => total + (message.toolSteps?.length ?? 0),+ 0+ ),+ },+ ] as const+ })+ ).then(entries => {+ if (!cancelled) {+ setBackfilledCountersByChat(previous => ({+ ...previous,+ ...Object.fromEntries(entries),+ }))+ }+ })++ return () => {+ cancelled = true+ }+ }, [+ chatStore.backfillCounters,+ chatStore.loadMessages,+ isAuthenticated,+ loadMenuData,+ missingCounterChatIds,+ selectedAgent,+ ])// Compute agentLastActiveByAgent for all agentsuseEffect(() => {- if (!isAuthenticated || !agentNames.length) {+ if (!isAuthenticated || !loadMenuData || !agentNames.length) {setAgentLastActiveByAgent({})return}@@ -71,85 +192,7 @@ export function useActivityController({return () => {cancelled = true}- }, [agentNames, chatStore.getIndex, isAuthenticated])-- // Compute selectedAgentActivitySummary- useEffect(() => {- if (!selectedAgent) {- setSelectedAgentActivitySummary({- conversations: 0,- messages: 0,- toolCalls: 0,- errors: 0,- conversationsPerDay: [],- })- return- }-- let cancelled = false- ;(async () => {- const dateCursor = new Date()- const dayKeys: string[] = []- for (let index = 6; index >= 0; index -= 1) {- const day = new Date(dateCursor)- day.setDate(day.getDate() - index)- dayKeys.push(day.toISOString().slice(0, 10))- }- const conversationsPerDayMap = new Map<string, number>(dayKeys.map(key => [key, 0]))- for (const chat of chatList) {- const chatTimestamp = Date.parse(chat.updatedAt)- if (Number.isNaN(chatTimestamp)) continue- const chatDateKey = new Date(chatTimestamp).toISOString().slice(0, 10)- if (conversationsPerDayMap.has(chatDateKey)) {- conversationsPerDayMap.set(- chatDateKey,- (conversationsPerDayMap.get(chatDateKey) || 0) + 1- )- }- }-- let totalMessages = 0- let totalErrors = 0- if (chatList.length > 0) {- const chatsToScan = [...chatList]- .sort((left, right) => getChatUpdatedTimestamp(right) - getChatUpdatedTimestamp(left))- .slice(0, ACTIVITY_SUMMARY_CHAT_SCAN_LIMIT)- const messageLists = await Promise.all(- chatsToScan.map(chat => chatStore.loadMessages(selectedAgent, chat.id).catch(() => []))- )- for (const messages of messageLists) {- totalMessages += messages.length- totalErrors += messages.filter((message: any) => message.isError).length- }- }-- const progressByMessage = progressByAgentMessage[selectedAgent] || {}- let totalToolCalls = 0- for (const progress of Object.values(progressByMessage)) {- totalToolCalls += progress.steps.length- }-- const formatter = new Intl.DateTimeFormat(undefined, { month: 'short', day: 'numeric' })- const conversationsPerDay = [...conversationsPerDayMap.entries()].map(([dayKey, count]) => ({- dayLabel: formatter.format(new Date(dayKey)),- count,- }))-- if (!cancelled) {- setSelectedAgentActivitySummary({- conversations: chatList.length,- messages: totalMessages,- toolCalls: totalToolCalls,- errors: totalErrors,- conversationsPerDay,- })- }- })()-- return () => {- cancelled = true- }- }, [chatList, chatStore.loadMessages, progressByAgentMessage, selectedAgent])+ }, [agentNames, chatStore.getIndex, isAuthenticated, loadMenuData])return {agentLastActiveByAgent,diff --git a/desktop-app/ui/src/hooks/domain/useAgentChatController.ts b/desktop-app/ui/src/hooks/domain/useAgentChatController.tsindex a3cd94806..c7adb2c1f 100644--- a/desktop-app/ui/src/hooks/domain/useAgentChatController.ts+++ b/desktop-app/ui/src/hooks/domain/useAgentChatController.ts@@ -11,12 +11,17 @@ import {buildResponseFileAttachments,} from '@lib/chatMessageAttachments'import { buildComposerRequestContent } from '@lib/composerReferencesPrompt'+import {+ mergeAuthoritativeServerMessages,+ messageServerTurnNumber,+} from '../../../../src/chatMessageMerge'import type {ChatMessageAttachment,HostActivityEvent,HostActivityStreamEvent,HostMessageAttachment,MessageToolStep,+ SessionMessagesQuery,} from '../../../../src/types'import type { SessionMessagesResult } from '../../../../src/types'import { DESKTOP_ROUTES } from '../../constants/navigation'@@ -98,6 +103,124 @@ const MAX_ACTIVITY_EVENTS_PER_MESSAGE = 100* persisted `toolSteps` (#582 fallback in ChatThread).*/const MAX_MESSAGES_WITH_ACTIVITY_PER_AGENT = 50+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')+const DELTA_RECONCILIATION_WINDOW = Symbol('delta-reconciliation-window')+type ReconciliationMessagesResult = SessionMessagesResult & {+ [REPLACE_LOCAL_RECONCILIATION_WINDOW]?: true+ [DELTA_RECONCILIATION_WINDOW]?: true+}++function serverTurnNumber(message: AgentChatMessage): number | undefined {+ return messageServerTurnNumber(message)+}++function oldestServerTurnNumber(messages: AgentChatMessage[]): number | undefined {+ return messages.reduce<number | undefined>((oldest, message) => {+ const current = serverTurnNumber(message)+ return current === undefined ? oldest : Math.min(oldest ?? current, current)+ }, undefined)+}++function latestServerTurnNumber(messages: AgentChatMessage[]): number | undefined {+ return messages.reduce<number | undefined>((latest, message) => {+ const current = serverTurnNumber(message)+ return current === undefined ? latest : Math.max(latest ?? current, current)+ }, undefined)+}++function sortedUniqueServerTurnNumbers(messages: AgentChatMessage[]): number[] {+ return Array.from(+ new Set(messages.map(serverTurnNumber).filter((turn): turn is number => turn !== undefined))+ ).sort((left, right) => left - right)+}++function mergeUniqueSessionTurns(+ ...turnPages: Array<SessionMessagesResult['turns']>+): SessionMessagesResult['turns'] {+ const byNumber = new Map<number, SessionMessagesResult['turns'][number]>()+ for (const turns of turnPages) {+ for (const turn of turns) {+ byNumber.set(turn.number, turn)+ }+ }+ return Array.from(byNumber.values()).sort((left, right) => left.number - right.number)+}++function firstServerTurnGapUpperBound(+ messages: AgentChatMessage[],+ ignoredGapUpperBounds?: ReadonlySet<number>+): number | undefined {+ const turns = sortedUniqueServerTurnNumbers(messages)+ for (let index = 1; index < turns.length; index += 1) {+ const previous = turns[index - 1]!+ const current = turns[index]!+ if (current > previous + 1 && !ignoredGapUpperBounds?.has(current)) return current+ }+ return undefined+}++function nextServerBackfillBeforeTurn(+ messages: AgentChatMessage[],+ ignoredGapUpperBounds?: ReadonlySet<number>+): number | undefined {+ const gapUpperBound = firstServerTurnGapUpperBound(messages, ignoredGapUpperBounds)+ if (gapUpperBound !== undefined) return gapUpperBound+ const oldestTurn = oldestServerTurnNumber(messages)+ return oldestTurn !== undefined && oldestTurn > 1 ? oldestTurn : undefined+}++type ChatStoreClient = ReturnType<typeof useChatStore>++async function hasLocalMessagesBeyond(+ chatStore: ChatStoreClient,+ agentRef: string,+ chatId: string,+ offset: number+): Promise<boolean> {+ return chatStore+ .loadMessages(agentRef, chatId, 1, offset)+ .then(messages => messages.length > 0)+ .catch(() => false)+}++function mergeUniqueMessages(+ existing: AgentChatMessage[],+ incoming: AgentChatMessage[],+ position: 'before' | 'after' = 'after'+): AgentChatMessage[] {+ const source = position === 'before' ? [...incoming, ...existing] : [...existing, ...incoming]+ const seen = new Set<string>()+ return source.filter(message => {+ if (seen.has(message.id)) return false+ seen.add(message.id)+ return true+ })+}++function mergeServerMessages(+ existing: AgentChatMessage[],+ incoming: AgentChatMessage[],+ activeTaskIds?: ReadonlySet<string>+): AgentChatMessage[] {+ return mergeAuthoritativeServerMessages(existing, incoming, { activeTaskIds })+}++function sameMessageSequence(a: AgentChatMessage[], b: AgentChatMessage[]): boolean {+ return (+ a.length === b.length &&+ a.every((message, index) => {+ const other = b[index]+ return (+ other !== undefined &&+ message.id === other.id &&+ serverTurnNumber(message) === serverTurnNumber(other)+ )+ })+ )+}/** Keep only the last `n` insertion-ordered keys of a per-message map. Returns the* same reference when already within the cap (so React state stays identity-stable). */@@ -173,9 +296,11 @@ const EMPTY_PROGRESS_MAP: Record<string, TaskProgress> = Object.freeze({})interface UseAgentChatControllerParams {selectedAgent: string | nullagentNames: string[]+ currentUserId?: stringcurrentTeamId: stringcurrentTeamName: stringisAuthenticated: boolean+ loadMenuData: booleannavItem: NavItempushToast: (msg: string, tone: Tone) => voidpushNotification: (n: PushNotificationInput) => void@@ -195,9 +320,11 @@ interface UseAgentChatControllerParams {export function useAgentChatController({selectedAgent,agentNames,+ currentUserId,currentTeamId,currentTeamName,isAuthenticated,+ loadMenuData,navItem,pushToast,pushNotification,@@ -207,6 +334,13 @@ export function useAgentChatController({decideApprovalFromNotification,}: UseAgentChatControllerParams) {const chatStore = useChatStore()+ const authenticatedScope = `${currentUserId ?? 'unknown-user'}:${currentTeamId}`++ useEffect(() => {+ chatStore.setRemoteCacheScope(+ isAuthenticated ? `authenticated:${authenticatedScope}` : 'signed-out'+ )+ }, [authenticatedScope, chatStore.setRemoteCacheScope, isAuthenticated])const tracker = useAgentTaskTracker()const [activeChatId, setActiveChatId] = useState<string | null>(null)@@ -227,10 +361,13 @@ export function useAgentChatController({// activeChatId) are injected through `chatListHostRef`, filled each render once// those parent callbacks are defined (created here so the hook can receive it).const chatListHostRef = useRef<ChatListControllerHost | null>(null)+ const autoSelectedChatIdRef = useRef<string | null>(null)const chatListCtl = useChatListController({selectedAgent,agentNames,isAuthenticated,+ scopeKey: authenticatedScope,+ loadMenuData,chatStore,fsm,host: chatListHostRef,@@ -238,9 +375,12 @@ export function useAgentChatController({const {chatList,chatListLoading,+ chatListMoreLoading,+ chatListHasMoreRemoteSessions,latestChatSessions,latestChatSessionsLoading,loadChatList,+ loadMoreChatSessions,setChatListLoading,clearList,markUnreadInList,@@ -258,6 +398,31 @@ export function useAgentChatController({} = chatListCtlconst [chatMessages, setChatMessages] = useState<AgentChatMessage[]>([])const [chatMessagesLoading, setChatMessagesLoading] = useState(false)+ const [hasOlderMessages, setHasOlderMessages] = useState(false)+ const [olderMessagesLoading, setOlderMessagesLoading] = useState(false)+ const chatMessagesRef = useRef<AgentChatMessage[]>([])+ const loadedLocalMessageCountRef = useRef(0)+ const olderMessagesRequestRef = useRef<symbol | null>(null)+ const unfillableServerGapUpperBoundsRef = useRef<Map<string, Set<number>>>(new Map())++ const cancelOlderMessagesLoad = useCallback(() => {+ olderMessagesRequestRef.current = null+ setOlderMessagesLoading(false)+ }, [])++ const ignoredServerGapUpperBounds = useCallback((agentRef: string, chatId: string) => {+ return unfillableServerGapUpperBoundsRef.current.get(makeTaskKey(agentRef, chatId))+ }, [])++ const markServerGapUnfillable = useCallback(+ (agentRef: string, chatId: string, beforeTurn: number) => {+ const key = makeTaskKey(agentRef, chatId)+ const gaps = unfillableServerGapUpperBoundsRef.current.get(key) ?? new Set<number>()+ gaps.add(beforeTurn)+ unfillableServerGapUpperBoundsRef.current.set(key, gaps)+ },+ []+ )const [activityByAgentMessage, setActivityByAgentMessage] = useState<Record<string, Record<string, AgentMessageActivity>>@@ -266,6 +431,10 @@ export function useAgentChatController({Record<string, Record<string, TaskProgress>>>({})+ useEffect(() => {+ chatMessagesRef.current = chatMessages+ }, [chatMessages])+const [agentSending, setAgentSending] = useState(false)const [agentError, setAgentError] = useState<string | null>(null)const [failedAgentSend, setFailedAgentSend] = useState<FailedAgentSend | null>(null)@@ -304,7 +473,11 @@ export function useAgentChatController({// (assigned in an effect, not the render body — R-F12) so the instance stays// stable while the closures it calls track the latest state.const reconcileBranchesRef = useRef<{- loadSessionMessages: (agentRef: string, chatId: string) => Promise<SessionMessagesResult>+ loadSessionMessages: (+ agentRef: string,+ chatId: string,+ query?: SessionMessagesQuery+ ) => Promise<SessionMessagesResult>attachLiveTask: ReconcileChatDeps['attachLiveTask']settleIdle: ReconcileChatDeps['settleIdle']evictChat: ReconcileChatDeps['evictChat']@@ -313,8 +486,8 @@ export function useAgentChatController({if (!reconcileChatRef.current) {reconcileChatRef.current = createReconcileChat({fsm,- loadSessionMessages: (agentRef, chatId) =>- reconcileBranchesRef.current!.loadSessionMessages(agentRef, chatId),+ loadSessionMessages: (agentRef, chatId, query) =>+ reconcileBranchesRef.current!.loadSessionMessages(agentRef, chatId, query),attachLiveTask: (chatKey, resp, epoch, stillRelevant) =>reconcileBranchesRef.current!.attachLiveTask(chatKey, resp, epoch, stillRelevant),settleIdle: (chatKey, resp, epoch, hint, stillRelevant) =>@@ -562,6 +735,7 @@ export function useAgentChatController({...activeChatVisibilityRef.current,activeChatId: null,}+ autoSelectedChatIdRef.current = nullsetActiveChatId(null)clearList()// R-F13 renderer half (spec §4.5-3): tear down EVERY tracked task so a late@@ -578,13 +752,25 @@ export function useAgentChatController({// Clear the reply-notification dedupe set so taskIds don't accumulate across// login/logout / team-switch cycles (security review, hygiene).resetReplyNotificationDedupe()+ chatStore.clearCachedRemoteData()setChatMessages([])setChatMessagesLoading(false)+ setHasOlderMessages(false)+ cancelOlderMessagesLoad()+ loadedLocalMessageCountRef.current = 0// The error/resend banner is per-chat view state — drop it when the active// chat is torn down (logout / unauth boot) so it can't survive into the next.setAgentError(null)setFailedAgentSend(null)- }, [resetComposerAttachments, clearList, tracker, fsm, resetReplyNotificationDedupe])+ }, [+ resetComposerAttachments,+ clearList,+ tracker,+ fsm,+ resetReplyNotificationDedupe,+ chatStore.clearCachedRemoteData,+ cancelOlderMessagesLoad,+ ])// Unified switch (post-D.4): cache-first render → server reconcile → tracker// rejoin. No `isRemote` branch — the server is the source of truth for every@@ -600,6 +786,9 @@ export function useAgentChatController({setActiveChatId(chatId)setChatMessages([])setChatMessagesLoading(true)+ setHasOlderMessages(false)+ cancelOlderMessagesLoad()+ loadedLocalMessageCountRef.current = 0// The error/resend banner is per-chat view state, not global: clear it on// every chat switch (same-agent switches don't trip the selectedAgent// cleanup effect, so without this a stream error from chat A would bleed@@ -609,6 +798,7 @@ export function useAgentChatController({await chatStore.setLastActive(agentRef, chatId)const key = makeTaskKey(agentRef, chatId)+ unfillableServerGapUpperBoundsRef.current.delete(key)// Renderer-local relevance guard for a fast A→B→A switch: THIS switch's// reconcile is aborted the moment the user switches away. Passed into@@ -617,11 +807,23 @@ export function useAgentChatController({// approval on a NON-visible chat — is never subject to an active-chat guard.const isStillActive = () => activeChatVisibilityRef.current.activeChatId === chatId- // PHASE 1 — local cache (instant render, no RPC). Load the full cache (no- // cap): the reconcile compares its length against the full server history,- // so a windowed slice would falsely look "stale" on long chats.- const cached = await chatStore.loadMessages(agentRef, chatId).catch(() => [])+ // PHASE 1 — render only the newest local page. The authoritative reconcile+ // below requests a delta after the newest cached server turn.+ let cached: Awaited<ReturnType<typeof chatStore.loadMessages>> = []+ try {+ cached = await chatStore.loadMessages(agentRef, chatId, LOCAL_MESSAGE_PAGE_SIZE)+ } catch (error) {+ console.warn('[chat-history] failed to load local messages', { agentRef, chatId, error })+ }+ const hasOlderServerMessages =+ nextServerBackfillBeforeTurn(cached as AgentChatMessage[]) !== undefined+ const hasOlderLocalMessages =+ !hasOlderServerMessages &&+ 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)setChatMessages(cached as AgentChatMessage[])// Phase 1 rendered the cache → clear the blocking spinner. The reconcile// runs under the `syncing` indicator (RECONCILE_STARTED, dispatched by the@@ -653,19 +855,23 @@ export function useAgentChatController({// itself no longer needs a taskId to match (R2's epoch replaces the old// `recoveringTaskIdByKeyRef` bookkeeping).//- // Note (accepted): the gate re-reads `loadMessages` inside its hydrate, so a- // switch reads the cache twice (Phase 1 + hydrate). The extra IPC is cheap- // and the hydrate's length-compare self-heals if an SSE terminal appended- // between the two reads (the next reconcile lands the fuller view). Note+ // The gate re-reads the same bounded local page inside hydrate so an SSE+ // terminal that lands between Phase 1 and reconciliation is included+ // without transferring the complete local transcript over IPC. Note// (best-effort): `reconcileChat` is single-flight per key — if a background// reconcile is already in flight for THIS key, this call coalesces onto it// and its `isRelevant`/`taskIdHint` are ignored; `hydrateActiveChatFromServer`'s// own `isActive()` guard still prevents rendering into the wrong chat.const zombieBefore = tracker.get(key)+ const latestCachedTurn = latestServerTurnNumber(cached as AgentChatMessage[])await reconcileChat(key, {reason: 'switch_to_chat',taskIdHint: zombieBefore?.taskId,isRelevant: isStillActive,+ messagesQuery: {+ limit: SERVER_TURN_PAGE_SIZE,+ ...(latestCachedTurn !== undefined ? { afterTurn: latestCachedTurn } : {}),+ },})},[@@ -675,6 +881,7 @@ export function useAgentChatController({reconcileChat,scrollChatToBottom,clearUnreadInList,+ cancelOlderMessagesLoad,chatStore.setLastActive,chatStore.loadMessages,chatStore.clearUnreadTerminal,@@ -700,20 +907,152 @@ export function useAgentChatController({dispatchSession,clearComposerDraft,getActiveChatId: () => activeChatId,+ getAutoSelectedChatId: () => autoSelectedChatIdRef.current,+ markAutoSelectedChat: chatId => {+ autoSelectedChatIdRef.current = chatId+ },+ shouldAutoSelectLatest: () => navItem === DESKTOP_ROUTES.chat,}})const handleSelectChat = useCallback(async (chatId: string) => {if (!selectedAgent) return+ autoSelectedChatIdRef.current = nullawait switchToChat(selectedAgent, chatId)},[selectedAgent, switchToChat])+ const handleLoadOlderMessages = useCallback(async () => {+ if (!selectedAgent || !activeChatId || olderMessagesRequestRef.current) return+ const requestAgent = selectedAgent+ const requestChatId = activeChatId+ const requestToken = Symbol(`${requestAgent}:${requestChatId}`)+ olderMessagesRequestRef.current = requestToken+ const isStillRelevant = () => {+ const visible = activeChatVisibilityRef.current+ return (+ olderMessagesRequestRef.current === requestToken &&+ visible.selectedAgent === requestAgent &&+ visible.activeChatId === requestChatId+ )+ }+ setOlderMessagesLoading(true)+ try {+ const visibleIds = new Set(chatMessages.map(message => message.id))+ const localPage = (await chatStore+ .loadMessages(+ requestAgent,+ requestChatId,+ LOCAL_MESSAGE_PAGE_SIZE,+ loadedLocalMessageCountRef.current+ )+ .catch(() => [])) as AgentChatMessage[]+ if (!isStillRelevant()) return+ const unseenLocal = localPage.filter(message => !visibleIds.has(message.id))+ if (unseenLocal.length) {+ const nextLoadedLocalMessageCount = loadedLocalMessageCountRef.current + localPage.length+ const currentMessages = chatMessagesRef.current+ const previewMerged = mergeUniqueMessages(currentMessages, unseenLocal, 'before')+ const hasOlderServerMessages = nextServerBackfillBeforeTurn(previewMerged) !== undefined+ const hasOlderLocalMessages =+ !hasOlderServerMessages &&+ localPage.length === LOCAL_MESSAGE_PAGE_SIZE &&+ (await hasLocalMessagesBeyond(+ chatStore,+ requestAgent,+ requestChatId,+ nextLoadedLocalMessageCount+ ))+ if (!isStillRelevant()) return+ loadedLocalMessageCountRef.current = nextLoadedLocalMessageCount+ const merged = mergeUniqueMessages(chatMessagesRef.current, unseenLocal, 'before')+ chatMessagesRef.current = merged+ setChatMessages(merged)+ setHasOlderMessages(hasOlderLocalMessages || hasOlderServerMessages)+ return+ }++ const beforeBackfillMessages = chatMessagesRef.current+ const beforeBackfillOldestTurn = oldestServerTurnNumber(beforeBackfillMessages)+ const beforeTurn = nextServerBackfillBeforeTurn(+ beforeBackfillMessages,+ ignoredServerGapUpperBounds(requestAgent, requestChatId)+ )+ if (beforeTurn === undefined) {+ setHasOlderMessages(false)+ return+ }++ const response = await chatStore.loadSessionMessages(+ requestAgent,+ requestAgent,+ requestChatId,+ { limit: SERVER_TURN_PAGE_SIZE, beforeTurn }+ )+ if (!isStillRelevant()) return+ const older = turnsToChatMessages(response.turns) as AgentChatMessage[]+ const activeTaskId = tracker.get(makeTaskKey(requestAgent, requestChatId))?.taskId+ const merged = mergeServerMessages(+ chatMessagesRef.current,+ older,+ activeTaskId ? new Set([activeTaskId]) : undefined+ )+ chatMessagesRef.current = merged+ setChatMessages(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+ const nextBackfillBeforeTurn = nextServerBackfillBeforeTurn(merged)+ const oldestMergedTurn = oldestServerTurnNumber(merged)+ const loweredOldestTurn =+ oldestMergedTurn !== undefined &&+ (beforeBackfillOldestTurn === undefined || oldestMergedTurn < beforeBackfillOldestTurn)+ if (nextBackfillBeforeTurn === beforeTurn && !loweredOldestTurn) {+ markServerGapUnfillable(requestAgent, requestChatId, beforeTurn)+ }+ const ignoredGaps = ignoredServerGapUpperBounds(requestAgent, requestChatId)+ setHasOlderMessages(+ nextServerBackfillBeforeTurn(merged, ignoredGaps) !== undefined ||+ (Boolean(response.hasMoreBefore) &&+ oldestMergedTurn !== undefined &&+ oldestMergedTurn > 1)+ )+ } catch (error) {+ console.warn('[chat-history] failed to load older messages', {+ agentRef: requestAgent,+ chatId: requestChatId,+ error,+ })+ } finally {+ if (olderMessagesRequestRef.current === requestToken) {+ olderMessagesRequestRef.current = null+ setOlderMessagesLoading(false)+ }+ }+ }, [+ activeChatId,+ chatMessages,+ chatStore.loadMessages,+ chatStore.loadSessionMessages,+ chatStore.replaceMessages,+ ignoredServerGapUpperBounds,+ markServerGapUnfillable,+ selectedAgent,+ tracker,+ ])+// Agent selection → load chatsuseEffect(() => {if (!selectedAgent) {+ autoSelectedChatIdRef.current = nullactiveChatVisibilityRef.current = {...activeChatVisibilityRef.current,activeChatId: null,@@ -725,6 +1064,9 @@ export function useAgentChatController({setChatListLoading(false)setChatMessages([])setChatMessagesLoading(false)+ setHasOlderMessages(false)+ cancelOlderMessagesLoad()+ loadedLocalMessageCountRef.current = 0return}@@ -740,6 +1082,9 @@ export function useAgentChatController({setActiveChatId(requestedSelection.chatId)setChatMessages([])setChatMessagesLoading(true)+ setHasOlderMessages(false)+ cancelOlderMessagesLoad()+ loadedLocalMessageCountRef.current = 0if (requestedSelection.title) {upsertProvisionalEntry(requestedSelection.chatId,@@ -757,6 +1102,9 @@ export function useAgentChatController({setActiveChatId(null)setChatMessages([])setChatMessagesLoading(false)+ setHasOlderMessages(false)+ cancelOlderMessagesLoad()+ loadedLocalMessageCountRef.current = 0}setChatListLoading(true);(async () => {@@ -798,29 +1146,24 @@ export function useAgentChatController({if (requestedSelection?.mode === 'latest') {const latest = merged[0]if (latest) {+ autoSelectedChatIdRef.current = latest.idawait switchToChat(selectedAgent, latest.id)}setChatMessagesLoading(false)return}if (requestedSelection?.mode === 'specific') {- const requested = merged.find(chat => chat.id === requestedSelection.chatId)- if (requested) {- await switchToChat(selectedAgent, requestedSelection.chatId)- } else {- // B9: the pending `specific` selection never appeared in the merged- // list (e.g. a server-only chat surfaced by a notification while- // `listSessions` silently failed → items:[]). The spinner was turned- // on above (`setChatMessagesLoading(true)`); switchToChat — the only- // thing that clears it — never runs, so the chat pane would spin- // forever. Clear it here so the consistent empty-state renders instead.- setChatMessagesLoading(false)- }+ autoSelectedChatIdRef.current = null+ // 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) {const latest = merged[0]if (latest) {+ autoSelectedChatIdRef.current = latest.idawait switchToChat(selectedAgent, latest.id)}}@@ -830,7 +1173,7 @@ export function useAgentChatController({return () => {cancelled = true}- }, [currentTeamId, navItem, selectedAgent])+ }, [cancelOlderMessagesLoad, currentTeamId, navItem, selectedAgent])const mapComposerAttachmentsToHostRequest = (attachments: ComposerImageAttachment[]@@ -1033,9 +1376,10 @@ export function useAgentChatController({// `reconcileBranchesRef` (assigned in the effect below), keeping the gate// instance — and its coalescing state — stable across renders.- // Shared hydration (§4.3 / A.4.4): materialize the server's turns into the- // active view + persist (replace-never-append, D.4 §6.2), auto-title a fresh- // hydration from the first user turn (empty cache), and upsert the sidebar (S4).+ // Shared hydration (§4.3 / A.4.4): materialize the server's page into the+ // active view, append a delta when the cache has durable server turn IDs, and+ // merge server windows into legacy/random-ID caches. It also auto-titles a+ // fresh hydration from turn one and upserts the sidebar (S4).// Both reconcile branches use it: `settleIdle` (idle replace) and// `attachLiveTask` (render in-flight turns so a rejoin can anchor to the// rendered user bubble — P1-A). Returns the rendered set + whether it replaced,@@ -1055,23 +1399,80 @@ export function useAgentChatController({return v.selectedAgent === agentRef && v.activeChatId === chatId}const cached = (await chatStore- .loadMessages(agentRef, chatId)- .catch(() => [])) as AgentChatMessage[]- if (!isActive() || tracker.get(chatKey)) return { rendered: cached, replaced: false, cached }+ .loadMessages(agentRef, chatId, LOCAL_MESSAGE_PAGE_SIZE)+ .catch(error => {+ console.warn('[chat-history] failed to read local reconciliation window', {+ agentRef,+ chatId,+ error,+ })+ return []+ })) as AgentChatMessage[]+ const visible = isActive() ? chatMessagesRef.current : []+ const replaceLocalWindow =+ (resp as ReconciliationMessagesResult)[REPLACE_LOCAL_RECONCILIATION_WINDOW] === true+ const deltaWindow =+ (resp as ReconciliationMessagesResult)[DELTA_RECONCILIATION_WINDOW] === true+ const hasOlderFromServer = !deltaWindow && Boolean(resp.hasMoreBefore)+ const localMessages = mergeUniqueMessages(visible, cached)+ if (!isActive() || tracker.get(chatKey)) {+ return { rendered: localMessages, replaced: false, cached: localMessages }+ }const hydrated = turnsToChatMessages(resp.turns) as AgentChatMessage[]- if (hydrated.length <= cached.length) return { rendered: cached, replaced: false, cached }+ if (!hydrated.length) {+ return { rendered: localMessages, replaced: false, cached: localMessages }+ }+ const localHasServerTurns = localMessages.some(+ message => serverTurnNumber(message) !== undefined+ )+ if (!localHasServerTurns && localMessages.length > 0) {+ const responseContainsAllTurns =+ resp.totalTurns === undefined || resp.totalTurns === resp.turns.length+ if (responseContainsAllTurns && hydrated.length <= localMessages.length) {+ return { rendered: localMessages, replaced: false, cached: localMessages }+ }+ }const hydratedWithAttachments = withResponseFileAttachments(hydrated,taskIdHint ? await loadTaskResultResponseFileAttachments(agentRef, taskIdHint) : [])- if (!isActive() || tracker.get(chatKey)) return { rendered: cached, replaced: false, cached }- setChatMessages(hydratedWithAttachments)+ if (!isActive() || tracker.get(chatKey)) {+ return { rendered: localMessages, replaced: false, cached: localMessages }+ }+ const rendered = localMessages.length+ ? mergeServerMessages(+ localMessages,+ hydratedWithAttachments,+ resp.activeTaskId ? new Set([resp.activeTaskId]) : undefined+ )+ : hydratedWithAttachments+ const hasOlderAfterMerge =+ hasOlderFromServer || nextServerBackfillBeforeTurn(rendered) !== undefined+ if (replaceLocalWindow) {+ setHasOlderMessages(hasOlderAfterMerge)+ } else {+ setHasOlderMessages(previous => previous || hasOlderAfterMerge)+ }+ if (sameMessageSequence(rendered, localMessages)) {+ return { rendered: localMessages, replaced: false, cached: localMessages }+ }+ chatMessagesRef.current = rendered+ setChatMessages(rendered)const meta = await chatStore.createChat(agentRef, chatId)- await chatStore.replaceMessages(agentRef, chatId, hydratedWithAttachments)+ 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// server-only chat doesn't keep its "Chat <id>" placeholder (A.4.4 / S4).let title = meta.title- if (cached.length === 0) {+ if (localMessages.length === 0 && (resp.oldestTurnNumber ?? resp.turns[0]?.number) === 1) {const firstUserInput = resp.turns.find(t => t.user_input?.trim())?.user_input?.trim() || ''const hydratedTitle =firstUserInput.length > 60@@ -1086,7 +1487,7 @@ export function useAgentChatController({// S4: upsert into the sidebar. A chat opened via a notification for the// already-selected agent may not be in chatList yet; a bare `.map` drops it.upsertHydratedEntry(meta, title)- return { rendered: hydratedWithAttachments, replaced: true, cached }+ return { rendered, replaced: true, cached: localMessages }},[tracker,@@ -1259,6 +1660,7 @@ export function useAgentChatController({})tracker.release(chatKey as TaskKey)await chatStore.deleteChat(agentRef, chatId).catch(() => undefined)+ chatStore.clearCachedRemoteData()removeFromList(chatId)const view = activeChatVisibilityRef.currentif (view.selectedAgent === agentRef && view.activeChatId === chatId) {@@ -1267,19 +1669,116 @@ export function useAgentChatController({setChatMessages([])}},- [tracker, chatStore.deleteChat, removeFromList]+ [tracker, chatStore.deleteChat, chatStore.clearCachedRemoteData, removeFromList])useEffect(() => {reconcileBranchesRef.current = {- loadSessionMessages: (agentRef, chatId) =>- chatStore.loadSessionMessages(agentRef, agentRef, chatId),+ loadSessionMessages: async (agentRef, chatId, query) => {+ let requestedQuery = query ?? { limit: SERVER_TURN_PAGE_SIZE }+ if (requestedQuery.beforeTurn === undefined && requestedQuery.afterTurn === undefined) {+ const cached = (await chatStore+ .loadMessages(agentRef, chatId, LOCAL_MESSAGE_PAGE_SIZE)+ .catch(error => {+ console.warn('[chat-history] failed to read local delta cursor', {+ agentRef,+ chatId,+ error,+ })+ return []+ })) as AgentChatMessage[]+ const latestCachedTurn = latestServerTurnNumber(cached)+ requestedQuery = {+ ...requestedQuery,+ ...(latestCachedTurn !== undefined ? { afterTurn: latestCachedTurn } : {}),+ }+ }+ let response = await chatStore.loadSessionMessages(+ agentRef,+ agentRef,+ chatId,+ requestedQuery+ )+ if (requestedQuery.afterTurn === undefined || !response.hasMoreAfter) {+ if (requestedQuery.afterTurn !== undefined) {+ return {+ ...response,+ [DELTA_RECONCILIATION_WINDOW]: true,+ } satisfies ReconciliationMessagesResult+ }+ return response+ }++ 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,+ [DELTA_RECONCILIATION_WINDOW]: true,+ } satisfies ReconciliationMessagesResult+ }+ let pagesLoaded = 1+ while (+ response.hasMoreAfter &&+ cursor !== undefined &&+ !seenCursors.has(cursor) &&+ pagesLoaded < MAX_RECONCILE_DELTA_PAGES+ ) {+ seenCursors.add(cursor)+ const previousCursor = cursor+ response = await chatStore.loadSessionMessages(agentRef, agentRef, chatId, {+ 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,+ [DELTA_RECONCILIATION_WINDOW]: true,+ }+ }+ }+ if (response.hasMoreAfter) {+ const latest = await chatStore.loadSessionMessages(agentRef, agentRef, chatId, {+ limit: requestedQuery.limit ?? SERVER_TURN_PAGE_SIZE,+ })+ const combinedTurns = mergeUniqueSessionTurns(turns, latest.turns)+ return {+ ...latest,+ turns: combinedTurns,+ oldestTurnNumber: combinedTurns[0]?.number ?? latest.oldestTurnNumber,+ latestTurnNumber: combinedTurns.at(-1)?.number ?? latest.latestTurnNumber,+ [REPLACE_LOCAL_RECONCILIATION_WINDOW]: true,+ } satisfies ReconciliationMessagesResult+ }+ return {+ ...response,+ turns,+ oldestTurnNumber: turns[0]?.number,+ latestTurnNumber: turns.at(-1)?.number,+ hasMoreAfter: false,+ [DELTA_RECONCILIATION_WINDOW]: true,+ }+ },attachLiveTask: reconcileAttachLiveTask,settleIdle: reconcileSettleIdle,evictChat: reconcileEvictChat,}}, [chatStore.loadSessionMessages,+ chatStore.loadMessages,reconcileAttachLiveTask,reconcileSettleIdle,reconcileEvictChat,@@ -1840,6 +2339,7 @@ export function useAgentChatController({try {const chatId = crypto.randomUUID()const meta = await chatStore.createChat(sendAgent, chatId)+ chatStore.clearCachedRemoteData()autoCreatedMeta = metaappendNewEntry(sendAgent, meta)sendChatId = chatId@@ -1976,6 +2476,9 @@ export function useAgentChatController({async: true,})+ // A successful send creates or updates the durable server session. Do not+ // let the short-lived sidebar cache hide that new catalog state.+ chatStore.clearCachedRemoteData()// The runtime accepted the POST (sync reply or async task) — it received// the piggybacked model, so drop the pending entry. A thrown POST skips// this (the catch below leaves it set) so the next attempt retries it.@@ -2121,7 +2624,11 @@ export function useAgentChatController({// typed input on reload — matches pre-D.3 eager-persist. Best-effort.if (sendChatId) {try {- await chatStore.appendMessages(sendAgent, sendChatId, [userMessage])+ const failedUserMessage: AgentChatMessage = { ...userMessage, preserveLocal: true }+ setChatMessages(prev =>+ prev.map(message => (message.id === userMessageId ? failedUserMessage : message))+ )+ await chatStore.appendMessages(sendAgent, sendChatId, [failedUserMessage])} catch {// persistence is best-effort; the in-memory view still shows it}@@ -2274,11 +2781,14 @@ export function useAgentChatController({setActiveChatId(chatId)setChatMessages([])setChatMessagesLoading(true)+ setHasOlderMessages(false)+ cancelOlderMessagesLoad()+ loadedLocalMessageCountRef.current = 0if (options.title) {upsertProvisionalEntry(chatId, options.title, options.isRemote === true)}},- [currentTeamId, writePendingSelection, upsertProvisionalEntry]+ [cancelOlderMessagesLoad, currentTeamId, writePendingSelection, upsertProvisionalEntry])const clearActiveChat = useCallback(() => {@@ -2286,14 +2796,18 @@ export function useAgentChatController({...activeChatVisibilityRef.current,activeChatId: null,}+ autoSelectedChatIdRef.current = nullsetActiveChatId(null)setChatMessages([])setChatMessagesLoading(false)+ setHasOlderMessages(false)+ cancelOlderMessagesLoad()+ loadedLocalMessageCountRef.current = 0// Deselecting the active chat (e.g. team switch) must also drop its per-chat// error/resend banner so it doesn't bleed into the next active chat.setAgentError(null)setFailedAgentSend(null)- }, [])+ }, [cancelOlderMessagesLoad])const groupedMessages = useMemo(() => {const groups: Array<{ role: 'user' | 'assistant' | 'system'; items: AgentChatMessage[] }> = []@@ -2322,10 +2836,14 @@ export function useAgentChatController({activeChatId,chatList,chatListLoading,+ chatListMoreLoading,+ chatListHasMoreRemoteSessions,latestChatSessions,latestChatSessionsLoading,chatMessages,chatMessagesLoading,+ hasOlderMessages,+ olderMessagesLoading,sessionStateByChatKey,sessionStateByChatId,// Fase 2b (§4.7.4): the app-shell builds the central `decideApproval` bound to@@ -2353,6 +2871,8 @@ export function useAgentChatController({handleDeleteChat,handleDeleteChatForAgent,handleSelectChat,+ handleLoadOlderMessages,+ loadMoreChatSessions,handleSendAgentMessage,handleRetryFailedAgentSend,clearComposerSendError,diff --git a/desktop-app/ui/src/hooks/domain/useChatListController.ts b/desktop-app/ui/src/hooks/domain/useChatListController.tsindex f9cf379d6..58ec252c5 100644--- a/desktop-app/ui/src/hooks/domain/useChatListController.ts+++ b/desktop-app/ui/src/hooks/domain/useChatListController.ts@@ -1,9 +1,12 @@import { type MutableRefObject, useCallback, useEffect, useRef, useState } from 'react'import { makeTaskKey } from '@contexts/AgentTaskTrackerContext'-import type { ChatIndex, ChatMetadata } from '../../../../src/types'+import type { ChatIndex, ChatMetadata, SessionsListResult } from '../../../../src/types'+import { scheduleAfterFirstPaint } from '../scheduleAfterFirstPaint'import type { useChatStore } from '../useChatStore'import { type SessionFsmEvent, type SessionFsmStore, seedSessionSnapshots } from './sessionFsm'+const SESSION_CATALOG_PAGE_LIMIT = 50+/*** useChatListController (spec-v2 §4.4) — owns the whole sidebar chat-list* subsystem extracted from the god-hook:@@ -30,7 +33,6 @@ import { type SessionFsmEvent, type SessionFsmStore, seedSessionSnapshots } fromexport interface SidebarChatEntry extends ChatMetadata {remote?: boolean- turnCount?: number}/** Cross-agent sidebar entry (dev's `latestChatSessions`): a chat plus its owning agent. */@@ -55,12 +57,17 @@ export interface ChatListControllerHost {dispatchSession: (chatKey: string, event: SessionFsmEvent) => voidclearComposerDraft: (chatId: string) => voidgetActiveChatId: () => string | null+ getAutoSelectedChatId: () => string | null+ markAutoSelectedChat: (chatId: string | null) => void+ shouldAutoSelectLatest: () => boolean}interface UseChatListControllerParams {selectedAgent: string | nullagentNames: string[]isAuthenticated: boolean+ scopeKey: string+ loadMenuData: booleanchatStore: ReturnType<typeof useChatStore>fsm: SessionFsmStorehost: MutableRefObject<ChatListControllerHost | null>@@ -69,10 +76,31 @@ interface UseChatListControllerParams {const byUpdatedDesc = (a: { updatedAt: string }, b: { updatedAt: string }) =>new Date(b.updatedAt).getTime() - new Date(a.updatedAt).getTime()+function isRecoverableCatalogCursorError(error: unknown): boolean {+ const message = error instanceof Error ? error.message : String(error)+ return /\b4\d\d\b/.test(message) || message.toLowerCase().includes('invalid')+}++function dedupeSidebarChats<T extends SidebarChatEntry>(chats: T[]): T[] {+ const seen = new Set<string>()+ return chats.filter(chat => {+ if (seen.has(chat.id)) return false+ seen.add(chat.id)+ return true+ })+}++function knownServerMessageCount(session: SessionsListResult['items'][number]): number {+ const count = session.messageCount+ return typeof count === 'number' && Number.isFinite(count) ? Math.max(0, Math.floor(count)) : 0+}+export function useChatListController({selectedAgent,agentNames,isAuthenticated,+ scopeKey,+ loadMenuData,chatStore,fsm,host,@@ -80,12 +108,23 @@ export function useChatListController({// Per-agent list for the SELECTED agent (the sidebar's chat list).const [chatList, setChatList] = useState<SidebarChatEntry[]>([])const [chatListLoading, setChatListLoading] = useState(false)+ const [chatListMoreLoading, setChatListMoreLoading] = useState(false)+ const [chatListHasMoreRemoteSessions, setChatListHasMoreRemoteSessions] = useState(false)// Cross-agent "Latest sessions" list (badges live in the FSM, seeded below).const [latestChatSessions, setLatestChatSessions] = useState<LatestSidebarChatEntry[]>([])const [latestChatSessionsLoading, setLatestChatSessionsLoading] = useState(false)// Selection requested for an agent before its chats have loaded, consumed by// the parent's agent-selection effect. Ref (not state): imperative, per-agent.const pendingChatSelectionByAgentRef = useRef<Record<string, PendingChatSelection>>({})+ const suppressAutoSelectionByAgentRef = useRef<Map<string, number>>(new Map())+ const suppressAutoSelectionSequenceRef = useRef(0)+ const chatListNextCursorByAgentRef = useRef<Record<string, string | null | undefined>>({})+ const chatListLoadingMoreByAgentRef = useRef<Set<string>>(new Set())+ const requestGenerationRef = useRef(0)++ useEffect(() => {+ requestGenerationRef.current += 1+ }, [isAuthenticated, scopeKey])// Live `selectedAgent` for the stable callbacks below (they gate a chatList// write on "is this the selected agent"). A ref keeps the callbacks stable@@ -93,6 +132,17 @@ export function useChatListController({const selectedAgentRef = useRef(selectedAgent)useEffect(() => {selectedAgentRef.current = selectedAgent+ setChatListHasMoreRemoteSessions(+ Boolean(selectedAgent && chatListNextCursorByAgentRef.current[selectedAgent])+ )+ setChatListMoreLoading(+ Boolean(selectedAgent && chatListLoadingMoreByAgentRef.current.has(selectedAgent))+ )+ return () => {+ if (selectedAgentRef.current === selectedAgent) {+ selectedAgentRef.current = null+ }+ }}, [selectedAgent])// ─── Cross-agent latest-sessions mutators ───@@ -117,42 +167,177 @@ export function useChatListController({const loadChatListOnce = useCallback(async (agentRef: string): Promise<{ index: ChatIndex; merged: SidebarChatEntry[] }> => {- const [index, serverResult] = await Promise.all([- chatStore.getIndex(agentRef),- chatStore.listSessions(agentRef).catch(() => ({ items: [] })),- ])+ chatListNextCursorByAgentRef.current[agentRef] = null+ if (selectedAgentRef.current === agentRef) {+ setChatListHasMoreRemoteSessions(false)+ setChatListMoreLoading(false)+ }+ const index = await chatStore.getIndex(agentRef)+ const merged = [...index.chats].sort(byUpdatedDesc)+ setChatList(merged)- const localChats: SidebarChatEntry[] = index.chats- const localIds = new Set(localChats.map(c => c.id))- const serverSessions = serverResult.items.filter(s => s.agent === agentRef)+ const requestGeneration = requestGenerationRef.current+ const suppressionMarkerAtRequest = suppressAutoSelectionByAgentRef.current.get(agentRef)+ scheduleAfterFirstPaint(async () => {+ const serverResult = await chatStore+ .listSessions(agentRef, { agent: agentRef, limit: SESSION_CATALOG_PAGE_LIMIT })+ .catch((): SessionsListResult => ({ items: [] }))+ if (+ selectedAgentRef.current !== agentRef ||+ requestGenerationRef.current !== requestGeneration+ ) {+ if (+ suppressionMarkerAtRequest !== undefined &&+ suppressAutoSelectionByAgentRef.current.get(agentRef) === suppressionMarkerAtRequest+ ) {+ suppressAutoSelectionByAgentRef.current.delete(agentRef)+ }+ return+ }- // Seed sidebar session state (state/activeTaskId/pendingApproval/tokens) for- // badges via SERVER_SNAPSHOT (D4 / §4.1 R2 owns "never degrade a live task").- seedSessionSnapshots(fsm, agentRef, serverSessions)+ // 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))++ // Seed sidebar session state (state/activeTaskId/pendingApproval/tokens)+ // for badges via SERVER_SNAPSHOT (D4 / §4.1 R2 owns "never degrade a live+ // task").+ seedSessionSnapshots(fsm, agentRef, serverSessions)++ // Chats the server knows but the local cache doesn't (e.g. created on+ // another device). Post-§7.1 wipe these are normal entries — no+ // "Remote ·" label, no isRemote branch; switchToChat's unified path+ // hydrates them.+ setChatList(previous => {+ const dedupedPrevious = dedupeSidebarChats(previous)+ const knownIds = new Set(dedupedPrevious.map(c => c.id))+ const fromServerOnly: SidebarChatEntry[] = serverSessions+ .filter(s => !knownIds.has(s.chatId))+ .map(s => ({+ id: s.chatId,+ title: `Chat ${s.chatId.slice(0, 8)}`,+ createdAt: s.lastActivityAt,+ updatedAt: s.lastActivityAt,+ // Older hosts omit messageCount. Keep that unknown value at zero+ // instead of fabricating two messages per turn and overstating+ // Activity totals when tool/system messages vary by session.+ messageCount: knownServerMessageCount(s),+ remote: true,+ }))+ return [...dedupedPrevious, ...fromServerOnly].sort(byUpdatedDesc)+ })++ const latestServerSession = serverSessions[0]+ // A mode:none request suppresses this one deferred catalog result. Consume+ // 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 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 &&+ serverIsNewerThanSelection &&+ currentHost.shouldAutoSelectLatest() &&+ !suppressAutoSelection+ ) {+ currentHost.markAutoSelectedChat(latestServerSession.chatId)+ void currentHost.switchToChat(agentRef, latestServerSession.chatId)+ }- // Chats the server knows but the local cache doesn't (e.g. created on- // another device). Post-§7.1 wipe these are normal entries — no "Remote ·"- // label, no isRemote branch; switchToChat's unified path hydrates them.- const fromServerOnly: SidebarChatEntry[] = serverSessions- .filter(s => !localIds.has(s.chatId))- .map(s => ({- id: s.chatId,- title: `Chat ${s.chatId.slice(0, 8)}`,- createdAt: s.lastActivityAt,- updatedAt: s.lastActivityAt,- messageCount: 0,- }))+ // 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.+ try {+ void chatStore+ .reconcileServerSessions(+ agentRef,+ serverSessions.map(s => ({ chatId: s.chatId, lastActivityAt: s.lastActivityAt }))+ )+ .catch(() => undefined)+ } catch {+ // ignore — reconciliation is best-effort freshness only+ }+ })- const merged = [...localChats, ...fromServerOnly].sort(byUpdatedDesc)- setChatList(merged)+ return { index, merged }+ },+ [chatStore.getIndex, chatStore.listSessions, chatStore.reconcileServerSessions, fsm]+ )++ const loadMoreChatSessions = useCallback(async () => {+ const agentRef = selectedAgentRef.current+ if (!agentRef) return++ const cursor = chatListNextCursorByAgentRef.current[agentRef]+ if (!cursor) {+ setChatListHasMoreRemoteSessions(false)+ return+ }+ if (chatListLoadingMoreByAgentRef.current.has(agentRef)) return++ chatListLoadingMoreByAgentRef.current.add(agentRef)+ const requestGeneration = requestGenerationRef.current+ setChatListMoreLoading(true)+ try {+ let serverResult: SessionsListResult+ try {+ serverResult = await chatStore.listSessions(+ agentRef,+ { agent: agentRef, limit: SESSION_CATALOG_PAGE_LIMIT, cursor },+ { force: true }+ )+ } catch (error) {+ if (+ requestGenerationRef.current === requestGeneration &&+ selectedAgentRef.current === agentRef+ ) {+ if (isRecoverableCatalogCursorError(error)) {+ chatListNextCursorByAgentRef.current[agentRef] = null+ setChatListHasMoreRemoteSessions(false)+ } else {+ setChatListHasMoreRemoteSessions(true)+ }+ }+ return+ }+ if (requestGenerationRef.current !== requestGeneration) return++ const serverSessions = serverResult.items.filter(s => s.agent === agentRef)+ if (selectedAgentRef.current !== agentRef) return++ chatListNextCursorByAgentRef.current[agentRef] = serverResult.nextCursor ?? null+ setChatListHasMoreRemoteSessions(Boolean(serverResult.nextCursor))+ seedSessionSnapshots(fsm, agentRef, serverSessions)+ setChatList(previous => {+ const dedupedPrevious = dedupeSidebarChats(previous)+ const knownIds = new Set(dedupedPrevious.map(c => c.id))+ const fromServerOnly: SidebarChatEntry[] = serverSessions+ .filter(s => !knownIds.has(s.chatId))+ .map(s => ({+ id: s.chatId,+ title: `Chat ${s.chatId.slice(0, 8)}`,+ createdAt: s.lastActivityAt,+ updatedAt: s.lastActivityAt,+ messageCount: knownServerMessageCount(s),+ remote: true,+ }))+ return [...dedupedPrevious, ...fromServerOnly].sort(byUpdatedDesc)+ })- // Persist server freshness into the local index (spec §5.3): keeps the- // durable sidebar order aligned with the source of truth. A pure tail- // effect that does NOT affect this render — the merge above sorts local- // chats by their (possibly stale) local `updatedAt`, so a chat whose- // server `lastActivityAt` is newer only re-sorts on the next cold start- // from this persisted reconcile. Best-effort: must never block or fail the- // load (fully swallowed).try {void chatStore.reconcileServerSessions(@@ -163,11 +348,13 @@ export function useChatListController({} catch {// ignore — reconciliation is best-effort freshness only}-- return { index, merged }- },- [chatStore.getIndex, chatStore.listSessions, chatStore.reconcileServerSessions, fsm]- )+ } finally {+ chatListLoadingMoreByAgentRef.current.delete(agentRef)+ if (selectedAgentRef.current === agentRef) {+ setChatListMoreLoading(false)+ }+ }+ }, [chatStore.listSessions, chatStore.reconcileServerSessions, fsm])const loadChatList = useCallback(async (agentRef: string): Promise<{ index: ChatIndex; merged: SidebarChatEntry[] } | null> => {@@ -196,7 +383,14 @@ export function useChatListController({// ─── Narrow chatList mutation API (called by the parent's remaining flows) ───/** Reset the selected agent's list (logout teardown / load failure). */- const clearList = useCallback(() => setChatList([]), [])+ const clearList = useCallback(() => {+ chatListNextCursorByAgentRef.current = {}+ chatListLoadingMoreByAgentRef.current.clear()+ suppressAutoSelectionByAgentRef.current.clear()+ setChatList([])+ setChatListMoreLoading(false)+ setChatListHasMoreRemoteSessions(false)+ }, [])/** Sidebar badge mirror: mark/clear the `unreadTerminal` flag by chat id. */const markUnreadInList = useCallback((chatId: string) => {@@ -257,7 +451,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 }])}, [])@@ -292,7 +486,10 @@ export function useChatListController({/** Append a freshly-created chat to both lists (create / send auto-create). */const appendNewEntry = useCallback((agentRef: string, meta: ChatMetadata) => {- setChatList(prev => [...prev, meta])+ setChatList(prev => {+ const next = prev.some(chat => chat.id === meta.id) ? prev : [...prev, meta]+ return dedupeSidebarChats(next)+ })upsertLatestChatSession(agentRef, meta)},[upsertLatestChatSession]@@ -308,6 +505,15 @@ export function useChatListController({const writePendingSelection = useCallback((agentName: string, selection: PendingChatSelection) => {pendingChatSelectionByAgentRef.current[agentName] = selection+ if (selection.mode === 'none') {+ suppressAutoSelectionSequenceRef.current += 1+ suppressAutoSelectionByAgentRef.current.set(+ agentName,+ suppressAutoSelectionSequenceRef.current+ )+ } else {+ suppressAutoSelectionByAgentRef.current.delete(agentName)+ }},[])@@ -322,7 +528,9 @@ export function useChatListController({if (!agentRef) returnconst chatId = crypto.randomUUID()const meta = await chatStore.createChat(agentRef, chatId)+ chatStore.clearCachedRemoteData()appendNewEntry(agentRef, meta)+ host.current?.markAutoSelectedChat(null)await host.current?.switchToChat(agentRef, chatId)host.current?.scrollChatToBottom()}, [chatStore, appendNewEntry, host])@@ -372,6 +580,7 @@ export function useChatListController({// FIRST (before the delete), preserving the ack-before-delete ordering.host.current?.dispatchSession(deletedKey, { type: 'CHAT_DELETED' })await chatStore.deleteChat(agentRef, chatId)+ chatStore.clearCachedRemoteData()host.current?.clearComposerDraft(chatId)removeLatestChatSession(agentRef, chatId)// Post-await guards read the LIVE committed values (selectedAgentRef /@@ -410,7 +619,7 @@ export function useChatListController({// ─── Cross-agent latest-sessions loader (seeds badges via SERVER_SNAPSHOT) ───useEffect(() => {- if (!isAuthenticated || !agentNames.length) {+ if (!isAuthenticated || !loadMenuData || !agentNames.length) {setLatestChatSessions([])setLatestChatSessionsLoading(false)return@@ -420,51 +629,71 @@ export function useChatListController({setLatestChatSessionsLoading(true);(async () => {try {- const sessionGroups = await Promise.all(+ const localGroups = await Promise.all(agentNames.map(async agentRef => {try {- const [index, serverResult] = await Promise.all([- chatStore.getIndex(agentRef),- chatStore.listSessions(agentRef).catch(() => ({ items: [] })),- ])- const localChats: LatestSidebarChatEntry[] = index.chats.map(chat => ({- ...chat,+ const index = await chatStore.getIndex(agentRef)+ return {agentRef,- }))- const localIds = new Set(localChats.map(chat => chat.id))- const remoteOnly: LatestSidebarChatEntry[] = serverResult.items- .filter(session => session.agent === agentRef && !localIds.has(session.chatId))- .map(session => ({- id: session.chatId,- title: `Remote · ${session.chatId.slice(0, 8)}`,- createdAt: session.lastActivityAt,- updatedAt: session.lastActivityAt,- messageCount: 0,- remote: true,- turnCount: session.turnCount,+ entries: index.chats.map(chat => ({+ ...chat,agentRef,- }))- // Seed this agent's session state from its server snapshot; the outer- // agentNames.map gives the cross-agent coverage the navbar badges- // (Running / Awaiting approval / Completed-unread) need.- // D4 (§4.1 R2): the "snapshot never degrades a live task" rule that- // used to live in `mergeSeededSessionStates` is now the reducer's.- const sessions = serverResult.items.filter(session => session.agent === agentRef)- return { agentRef, entries: [...localChats, ...remoteOnly], sessions }+ })),+ }} catch {return {agentRef,entries: [] as LatestSidebarChatEntry[],- sessions: [] as Awaited<ReturnType<typeof chatStore.listSessions>>['items'],}}}))if (cancelled) return- setLatestChatSessions(sessionGroups.flatMap(group => group.entries).sort(byUpdatedDesc))+ setLatestChatSessions(localGroups.flatMap(group => group.entries).sort(byUpdatedDesc))+ setLatestChatSessionsLoading(false)++ const sessionGroups = await Promise.all(+ agentNames.map(async agentRef => {+ // This feeds only the cross-agent sidebar preview. Do not follow+ // cursors here; the selected-agent session list exposes explicit+ // on-demand pagination through `loadMoreChatSessions`.+ const serverResult: SessionsListResult = await chatStore+ .listSessions(agentRef, {+ agent: agentRef,+ limit: SESSION_CATALOG_PAGE_LIMIT,+ })+ .catch((): SessionsListResult => ({ items: [] }))+ return {+ agentRef,+ sessions: serverResult.items.filter(session => session.agent === agentRef),+ }+ })+ )+ if (cancelled) returnfor (const group of sessionGroups) {seedSessionSnapshots(fsm, group.agentRef, group.sessions)}+ setLatestChatSessions(previous => {+ const knownKeys = new Set(previous.map(item => `${item.agentRef}:${item.id}`))+ const remoteOnly: LatestSidebarChatEntry[] = []+ for (const group of sessionGroups) {+ for (const session of group.sessions) {+ const key = `${group.agentRef}:${session.chatId}`+ if (knownKeys.has(key)) continue+ knownKeys.add(key)+ remoteOnly.push({+ id: session.chatId,+ title: `Remote · ${session.chatId.slice(0, 8)}`,+ createdAt: session.lastActivityAt,+ updatedAt: session.lastActivityAt,+ messageCount: knownServerMessageCount(session),+ remote: true,+ agentRef: group.agentRef,+ })+ }+ }+ return [...previous, ...remoteOnly].sort(byUpdatedDesc)+ })} finally {if (!cancelled) {setLatestChatSessionsLoading(false)@@ -475,12 +704,22 @@ export function useChatListController({return () => {cancelled = true}- }, [agentNames, chatStore.getIndex, chatStore.listSessions, isAuthenticated, fsm])+ }, [+ agentNames,+ chatStore.getIndex,+ chatStore.listSessions,+ isAuthenticated,+ loadMenuData,+ scopeKey,+ fsm,+ ])return {// State (public contract, re-exported unchanged by the parent).chatList,chatListLoading,+ chatListMoreLoading,+ chatListHasMoreRemoteSessions,latestChatSessions,latestChatSessionsLoading,// CRUD (public contract).@@ -491,6 +730,7 @@ export function useChatListController({handleDeleteChatForAgent,// Loader + list-loading control (parent agent-selection effect).loadChatList,+ loadMoreChatSessions,setChatListLoading,clearList,// Narrow chatList ops (parent flows).diff --git a/desktop-app/ui/src/hooks/scheduleAfterFirstPaint.ts b/desktop-app/ui/src/hooks/scheduleAfterFirstPaint.tsnew file mode 100644index 000000000..7ff089cfd--- /dev/null+++ b/desktop-app/ui/src/hooks/scheduleAfterFirstPaint.ts@@ -0,0 +1,16 @@+export function scheduleAfterFirstPaint(task: () => Promise<unknown>): void {+ let didRun = false+ let fallbackTimer: ReturnType<typeof setTimeout> | undefined+ const run = () => {+ if (didRun) return+ didRun = true+ if (fallbackTimer !== undefined) clearTimeout(fallbackTimer)+ void task().catch(() => undefined)+ }+ if (typeof requestAnimationFrame === 'function') {+ fallbackTimer = setTimeout(run, 1000)+ requestAnimationFrame(() => requestAnimationFrame(run))+ return+ }+ setTimeout(run, 0)+}diff --git a/desktop-app/ui/src/hooks/sessionAdapter.ts b/desktop-app/ui/src/hooks/sessionAdapter.tsindex 321dfee09..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,30 +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),- ...(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),- ...(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/useAppController.ts b/desktop-app/ui/src/hooks/useAppController.tsindex af4b194e9..37c76770f 100644--- a/desktop-app/ui/src/hooks/useAppController.ts+++ b/desktop-app/ui/src/hooks/useAppController.ts@@ -46,6 +46,7 @@ import {type WorkflowSelectionState,createResetWorkflowSelection,} from './domain/useWorkflowController.types'+import { scheduleAfterFirstPaint } from './scheduleAfterFirstPaint'const DENY_REASON_BY_SOURCE: Record<ApprovalDecisionTarget['source'], string> = {desktop_notification: 'Denied from desktop notification',@@ -94,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()@@ -104,6 +120,7 @@ export function useAppController() {// ─── Global status state (owned by coordinator, not auth) ───const [statusText, setStatusText] = useState('Ready.')const [statusTone, setStatusTone] = useState<Tone>('info')+ const [postPaintDataReady, setPostPaintDataReady] = useState(false)// Build fullSetStatus using refs to avoid circular dependenciesconst setStatusTextRef = useRef(setStatusText)@@ -136,6 +153,7 @@ export function useAppController() {// Use a ref so the stable onSessionNeedsLoad callback can call the real loadSession// without creating a circular dependency (loadSession is defined after auth+session).const loadSessionRef = useRef(async (_options?: { preserveNav?: boolean }) => {})+ const activeAuthenticatedSessionIdentityRef = useRef<string | null>(null)const authenticatedSessionIdentityRef = useRef<string | null>(null)const catalogRefreshPromiseRef = useRef<Promise<AccessCatalog> | null>(null)@@ -228,9 +246,11 @@ export function useAppController() {const chat = useAgentChatController({selectedAgent: nav.selectedAgent,agentNames: agentsData.agentNames,+ currentUserId: auth.me?.id,currentTeamId,currentTeamName,isAuthenticated: auth.isAuthenticated,+ loadMenuData: postPaintDataReady,navItem: nav.navItem,pushToast,pushNotification: notif.pushNotification,@@ -291,7 +311,7 @@ export function useAppController() {// ─── Host pre-warm (authenticated catalog only — see the hook's anti-flapping doc) ───useHostPrewarmController({agentNames: agentsData.agentNames,- isAuthenticated: auth.isAuthenticated,+ isAuthenticated: auth.isAuthenticated && postPaintDataReady,})// ─── Desktop ───@@ -304,6 +324,7 @@ export function useAppController() {const activity = useActivityController({selectedAgent: nav.selectedAgent,isAuthenticated: auth.isAuthenticated,+ loadMenuData: postPaintDataReady,chatList: chat.chatList,progressByAgentMessage: chat.progressByAgentMessage,agentNames: agentsData.agentNames,@@ -353,10 +374,37 @@ export function useAppController() {}, [queryClient])const refreshAuthenticatedData = useCallback(- async (options: { initialLoad?: boolean } = {}) => {+ async (options: { initialLoad?: boolean; sessionIdentity?: string } = {}) => {const refreshTeams = options.initialLoad? teamsData.refreshInitialDirectory: teamsData.refresh+ if (options.initialLoad) {+ const scheduledIdentity = options.sessionIdentity+ if (!scheduledIdentity) return false+ let agentsLoaded = false+ try {+ await refreshAgentsData()+ agentsLoaded = true+ } catch (error) {+ console.warn('[startup] failed to load the initial agent catalog', error)+ } finally {+ scheduleAfterFirstPaintForSession(+ activeAuthenticatedSessionIdentityRef,+ scheduledIdentity,+ async () => {+ setPostPaintDataReady(true)+ await Promise.all([+ refreshContextsData(),+ refreshMcpServersData(),+ refreshTeams(),+ refreshWorkflowsData(),+ notif.handleRefreshPendingApprovals({ silent: true }),+ ])+ }+ )+ }+ return agentsLoaded+ }return Promise.all([refreshAgentsData(),refreshContextsData(),@@ -372,6 +420,7 @@ export function useAppController() {refreshContextsData,refreshMcpServersData,refreshWorkflowsData,+ setPostPaintDataReady,teamsData.refresh,teamsData.refreshInitialDirectory,]@@ -379,26 +428,21 @@ export function useAppController() {const refreshWorkspaceDataForRoute = useCallback(async (route: NavItem) => {- let cycleCatalogPromise: Promise<AccessCatalog> | null = null- const getCycleCatalogPromise = () => {- if (!cycleCatalogPromise) {- cycleCatalogPromise = getCatalogRefreshPromise()- }- return cycleCatalogPromise- }-+ // Route refreshes deliberately update only the visible section. Hidden+ // route data remains deferred until that route becomes visible; shared+ // menu/composer data is loaded by the post-paint bootstrap instead.const refreshers = [{route: DESKTOP_ROUTES.agents,- refresh: () => agentsData.refreshWithCatalog(getCycleCatalogPromise()),+ refresh: () => agentsData.refreshWithCatalog(getCatalogRefreshPromise()),},{route: DESKTOP_ROUTES.contexts,- refresh: () => contextsData.refreshWithCatalog(getCycleCatalogPromise()),+ refresh: () => contextsData.refreshWithCatalog(getCatalogRefreshPromise()),},{route: DESKTOP_ROUTES.connectors,- refresh: () => mcpServersData.refreshWithCatalog(getCycleCatalogPromise()),+ refresh: () => mcpServersData.refreshWithCatalog(getCatalogRefreshPromise()),},{ route: DESKTOP_ROUTES.teams, refresh: teamsData.refresh },{ route: DESKTOP_ROUTES.plugins, refresh: refreshWorkflowsData },@@ -411,10 +455,8 @@ export function useAppController() {? DESKTOP_ROUTES.teams: routeconst current = refreshers.find(entry => entry.route === activeRoute)- const remaining = refreshers.filter(entry => entry.route !== activeRoute)if (current) await current.refresh()- await Promise.all(remaining.map(entry => entry.refresh()))},[agentsData.refreshWithCatalog,@@ -496,7 +538,12 @@ export function useAppController() {auth.setMe(sessionState.me)auth.setEmail(sessionState.me.email || '')currentTeamIdRef.current = sessionState.me.teamId || teamId- authenticatedSessionIdentityRef.current = `${sessionState.me.id}:${sessionState.me.email}:${sessionState.me.teamId || ''}`+ const switchedIdentity = `${sessionState.me.id}:${sessionState.me.email}:${sessionState.me.teamId || ''}`+ activeAuthenticatedSessionIdentityRef.current = switchedIdentity+ authenticatedSessionIdentityRef.current = switchedIdentity+ // Team switching owns a complete foreground refresh. If it invalidated+ // the login-time post-paint callback, re-enable deferred menu data here.+ setPostPaintDataReady(true)await refreshAuthenticatedData()if (announce) {const teamName =@@ -517,6 +564,7 @@ export function useAppController() {chat.resetChat,fullSetStatus,refreshAuthenticatedData,+ setPostPaintDataReady,teamsData.teams,])@@ -577,6 +625,7 @@ export function useAppController() {auth.setMe(sessionState.me)if (!authenticated || !sessionState.me) {+ setPostPaintDataReady(false)auth.setDesktopReleaseStatus(null)await chat.stopAllActivityStreams()agentsData.reset()@@ -587,6 +636,7 @@ export function useAppController() {queryClient.removeQueries({ queryKey: desktopQueryKeys.gfsRoot })chat.resetChat()notif.resetNotifications()+ activeAuthenticatedSessionIdentityRef.current = nullauthenticatedSessionIdentityRef.current = nullif (!preserveNav) nav.handleNavSelect(DESKTOP_ROUTES.chat)return@@ -596,9 +646,20 @@ export function useAppController() {auth.setEmail(sessionState.me.email || '')void auth.refreshDesktopReleaseStatus()const sessionIdentity = `${sessionState.me.id}:${sessionState.me.email}:${sessionState.me.teamId || ''}`+ activeAuthenticatedSessionIdentityRef.current = sessionIdentityif (authenticatedSessionIdentityRef.current !== sessionIdentity) {- authenticatedSessionIdentityRef.current = sessionIdentity- await refreshAuthenticatedData({ initialLoad: true })+ setPostPaintDataReady(false)+ const loaded = await refreshAuthenticatedData({+ initialLoad: true,+ sessionIdentity,+ })+ if (loaded && activeAuthenticatedSessionIdentityRef.current === sessionIdentity) {+ authenticatedSessionIdentityRef.current = sessionIdentity+ }+ } else {+ // A prior post-paint callback may have been invalidated by an identity+ // transition. An already-initialized matching session is ready now.+ setPostPaintDataReady(true)}if (!preserveNav) {nav.handleNavSelect(DESKTOP_ROUTES.chat)@@ -628,6 +689,7 @@ export function useAppController() {queryClient,refreshAuthenticatedData,resetWorkflowsData,+ setPostPaintDataReady,teamsData.reset,])@@ -652,6 +714,7 @@ export function useAppController() {// in cache would otherwise bleed into the next login (possibly a different// environment, since the env is chosen pre-login).queryClient.clear()+ activeAuthenticatedSessionIdentityRef.current = nullauthenticatedSessionIdentityRef.current = nullawait window.clerum.auth.logout()chat.resetChat()@@ -1123,10 +1186,14 @@ export function useAppController() {sessionStateByChatId: chat.sessionStateByChatId,sessionStateByChatKey: chat.sessionStateByChatKey,chatListLoading: chat.chatListLoading,+ chatListMoreLoading: chat.chatListMoreLoading,+ chatListHasMoreRemoteSessions: chat.chatListHasMoreRemoteSessions,latestChatSessions: chat.latestChatSessions,latestChatSessionsLoading: chat.latestChatSessionsLoading,chatMessages: chat.chatMessages,chatMessagesLoading: chat.chatMessagesLoading,+ hasOlderMessages: chat.hasOlderMessages,+ olderMessagesLoading: chat.olderMessagesLoading,composerImageAttachments: chat.composerImageAttachments,composerReferenceAttachments: chat.composerReferenceAttachments,agentSending: chat.agentSending,@@ -1143,6 +1210,8 @@ export function useAppController() {handleDeleteChat: chat.handleDeleteChat,handleDeleteChatForAgent: chat.handleDeleteChatForAgent,handleSelectChat: chat.handleSelectChat,+ handleLoadOlderMessages: chat.handleLoadOlderMessages,+ loadMoreChatSessions: chat.loadMoreChatSessions,handleSendAgentMessage: chat.handleSendAgentMessage,handleRetryFailedAgentSend: chat.handleRetryFailedAgentSend,clearComposerSendError: chat.clearComposerSendError,diff --git a/desktop-app/ui/src/hooks/useChatStore.ts b/desktop-app/ui/src/hooks/useChatStore.tsindex 95e593c77..9c81ecb90 100644--- a/desktop-app/ui/src/hooks/useChatStore.ts+++ b/desktop-app/ui/src/hooks/useChatStore.ts@@ -1,5 +1,12 @@import { useCallback } from 'react'-import type { ChatMessage } from '../../../src/types'+import type {+ ChatMessage,+ HostModelsResult,+ ReplaceChatMessagesOptions,+ SessionMessagesQuery,+ SessionsListQuery,+ SessionsListResult,+} from '../../../src/types'// The session lifecycle types live in the shared `src/types` (they cross the// IPC bridge from the server). Re-exported here so existing UI imports from@@ -44,12 +51,37 @@ const pendingModelByChat: Record<string, string> = {}* `pendingModelByChat`.*/const preChatModelByAgent: Record<string, string> = {}+const SESSION_CATALOG_TTL_MS = 5_000+const HOST_MODELS_TTL_MS = 30_000++type CachedRequest<T> = {+ expiresAt: number+ promise: Promise<T>+}++const sessionCatalogRequests = new Map<string, CachedRequest<SessionsListResult>>()+const hostModelRequests = new Map<string, CachedRequest<HostModelsResult | null>>()+let sessionCatalogSource: typeof window.clerum.rpc.listSessions | null = null+let hostModelsSource: typeof window.clerum.rpc.getHostModels | null = null+let remoteCacheScope = 'unknown'/** Composite key mirroring the session `chatKey` convention (`agentRef::chatId`). */function pendingModelKey(agentRef: string, chatId: string): string {return `${agentRef}::${chatId}`}+function hostModelKey(hostRef: string, chatId: string): string {+ return `${remoteCacheScope}:${hostRef}:${chatId}`+}++function pruneExpiredSessionCatalogRequests(now = Date.now()): void {+ for (const [key, cached] of sessionCatalogRequests) {+ if (cached.expiresAt <= now) {+ sessionCatalogRequests.delete(key)+ }+ }+}+/*** Hook providing typed access to the chat persistence IPC layer.* All methods are stable (useCallback) and safe to use in dependency arrays.@@ -79,9 +111,25 @@ export function useChatStore() {window.clerum.chat.appendMessages(agentRef, chatId, messages),[])+ const backfillCounters = useCallback(+ (agentRef: string, chatId: string, messages: ChatMessage[]) => {+ const backfill = window.clerum.chat.backfillCounters+ return typeof backfill === 'function'+ ? backfill(agentRef, chatId, messages)+ : Promise.resolve()+ },+ []+ )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(@@ -111,10 +159,39 @@ export function useChatStore() {[])- const listSessions = useCallback((hostRef: string) => window.clerum.rpc.listSessions(hostRef), [])+ const listSessions = useCallback(+ (hostRef: string, query: SessionsListQuery = {}, options: { force?: boolean } = {}) => {+ const source = window.clerum.rpc.listSessions+ if (sessionCatalogSource !== source) {+ sessionCatalogRequests.clear()+ sessionCatalogSource = source+ }+ const key = [+ remoteCacheScope,+ hostRef,+ query.agent ?? '',+ query.limit ?? 'all',+ query.cursor ?? '',+ ].join(':')+ pruneExpiredSessionCatalogRequests()+ const cached = sessionCatalogRequests.get(key)+ if (!options.force && cached && cached.expiresAt > Date.now()) return cached.promise++ const promise = source(hostRef, undefined, query).catch(error => {+ sessionCatalogRequests.delete(key)+ throw error+ })+ sessionCatalogRequests.set(key, {+ expiresAt: Date.now() + SESSION_CATALOG_TTL_MS,+ promise,+ })+ return promise+ },+ []+ )const loadSessionMessages = useCallback(- (hostRef: string, agent: string, chatId: string) =>- window.clerum.rpc.loadSessionMessages(hostRef, agent, chatId),+ (hostRef: string, agent: string, chatId: string, query: SessionMessagesQuery = {}) =>+ window.clerum.rpc.loadSessionMessages(hostRef, agent, chatId, undefined, query),[])const getContextBreakdown = useCallback(@@ -122,15 +199,40 @@ export function useChatStore() {window.clerum.rpc.getContextBreakdown(hostRef, agent, chatId),[])- const getHostModels = useCallback(- (hostRef: string, chatId: string) => window.clerum.rpc.getHostModels(hostRef, chatId),- []- )- const setHostModel = useCallback(- (hostRef: string, chatId: string, model: string) =>- window.clerum.rpc.setHostModel(hostRef, chatId, model),- []- )+ const getHostModels = useCallback((hostRef: string, chatId: string) => {+ const source = window.clerum.rpc.getHostModels+ if (hostModelsSource !== source) {+ hostModelRequests.clear()+ hostModelsSource = source+ }+ const key = hostModelKey(hostRef, chatId)+ const cached = hostModelRequests.get(key)+ if (cached && cached.expiresAt > Date.now()) return cached.promise++ const promise = source(hostRef, chatId).catch(error => {+ hostModelRequests.delete(key)+ throw error+ })+ hostModelRequests.set(key, { expiresAt: Date.now() + HOST_MODELS_TTL_MS, promise })+ return promise+ }, [])+ const setHostModel = useCallback(async (hostRef: string, chatId: string, model: string) => {+ const result = await window.clerum.rpc.setHostModel(hostRef, chatId, model)+ hostModelRequests.delete(hostModelKey(hostRef, chatId))+ return result+ }, [])+ const clearCachedRemoteData = useCallback(() => {+ sessionCatalogRequests.clear()+ hostModelRequests.clear()+ sessionCatalogSource = null+ hostModelsSource = null+ }, [])+ const setRemoteCacheScope = useCallback((scope: string) => {+ if (remoteCacheScope === scope) return+ remoteCacheScope = scope+ sessionCatalogRequests.clear()+ hostModelRequests.clear()+ }, [])// --- Pending (unpersisted) model selections — R2 "Option A" (see the// `pendingModelByChat` note above). Only UNPERSISTED selections are tracked:@@ -175,6 +277,7 @@ export function useChatStore() {loadMessages,appendMessages,replaceMessages,+ backfillCounters,markUnreadTerminal,clearUnreadTerminal,getLastActive,@@ -187,6 +290,8 @@ export function useChatStore() {getContextBreakdown,getHostModels,setHostModel,+ clearCachedRemoteData,+ setRemoteCacheScope,setPendingModel,getPendingModel,clearPendingModel,diff --git a/desktop-app/ui/src/pages/AuthPage/index.tsx b/desktop-app/ui/src/pages/AuthPage/index.tsxindex 4810036c6..a55f105e4 100644--- a/desktop-app/ui/src/pages/AuthPage/index.tsx+++ b/desktop-app/ui/src/pages/AuthPage/index.tsx@@ -3,10 +3,7 @@ import { useEffect, useRef, useState } from 'react'import { useAuthContext } from '@contexts/AuthContext'import { Button, Field, IconButton, MenuItem, TextInput } from '@components/Common'import { ConfirmDialog } from '@components/ConfirmDialog'-import {- LOCALHOST_RUNTIME_CONFIG_OPTION_ID,- createLocalhostRuntimeConfigOption,-} from '@constants/runtimeConfig'+import { createLocalhostRuntimeConfigOption } from '@constants/runtimeConfig'import { formatDesktopAppVersionTooltip, useDesktopAppInfo } from '@hooks/useDesktopAppInfo'import type { DesktopRuntimeConfigOption } from '../../../../src/types'@@ -36,9 +33,6 @@ export function AuthPage() {const runtimeConfigOptions = runtimeConfigState?.options || []const activeRuntimeConfigId = runtimeConfigState?.activeOptionId ?? null- const selectedRuntimeConfig = runtimeConfigOptions.find(- option => option.id === activeRuntimeConfigId- )const hasPasswordLoginCredentials = Boolean(email.trim()) && Boolean(password)const [runtimeSetupVisible, setRuntimeSetupVisible] = useState(false)const hasRuntimeSetupValues =@@ -101,12 +95,11 @@ export function AuthPage() {const handleRuntimeOptionSelect = (optionId: string) => {setRuntimeMenuOpen(false)- if (- optionId === activeRuntimeConfigId &&- (selectedRuntimeConfig?.source === 'localhost' ||- optionId === LOCALHOST_RUNTIME_CONFIG_OPTION_ID)- ) {- handleClearRuntimeConfigSelection()+ if (optionId === activeRuntimeConfigId) {+ 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.tsxindex 643781d9f..3f00d4553 100644--- a/desktop-app/ui/src/pages/__tests__/AuthPage.test.tsx+++ b/desktop-app/ui/src/pages/__tests__/AuthPage.test.tsx@@ -157,4 +157,76 @@ describe('AuthPage', () => {expect(handleSelectRuntimeConfig).toHaveBeenCalledWith(LOCALHOST_RUNTIME_CONFIG_OPTION_ID)})++ it('clears the selected localhost environment when clicked again', async () => {+ const user = userEvent.setup()+ const handleSelectRuntimeConfig = vi.fn()+ const handleClearRuntimeConfigSelection = vi.fn()++ renderAuthPage({+ runtimeConfigState: {+ configured: true,+ isLocalhost: true,+ selectorVisible: true,+ activeOptionId: LOCALHOST_RUNTIME_CONFIG_OPTION_ID,+ envKey: 'http_127_0_0_1_8091-eaf18b680d58',+ storagePath: '/tmp/evenfire-runtime-config',+ options: [+ {+ id: LOCALHOST_RUNTIME_CONFIG_OPTION_ID,+ label: 'Localhost',+ source: 'localhost',+ configPath: null,+ externalRestApiBaseUrl: 'http://127.0.0.1:8091',+ rpcProxyBaseUrl: 'http://127.0.0.1:8094',+ appName: 'Localhost',+ },+ ],+ },+ handleSelectRuntimeConfig,+ handleClearRuntimeConfigSelection,+ })++ await user.click(screen.getByLabelText('Open environment selector'))+ await user.click(screen.getByRole('button', { name: 'Localhost' }))++ 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/desktop-app/ui/src/styles.css b/desktop-app/ui/src/styles.cssindex d1826f7c9..1fd4d9ae5 100644--- a/desktop-app/ui/src/styles.css+++ b/desktop-app/ui/src/styles.css@@ -6057,6 +6057,24 @@ h3 {gap: var(--space-2-5);}+.chat-history-page-control {+ display: flex;+ justify-content: center;+ padding-block: var(--space-1);+}++.virtualized-message-chunk {+ display: grid;+ gap: var(--space-2);+ min-width: 0;+ content-visibility: auto;+ contain-intrinsic-size: auto 720px;+}++.chat-thread-dedicated .virtualized-message-chunk {+ gap: var(--space-2-5);+}+.chat-empty-state {align-content: center;justify-items: center;diff --git a/desktop-app/ui/src/uiTypes.ts b/desktop-app/ui/src/uiTypes.tsindex 0139d11b1..b5745a6b9 100644--- a/desktop-app/ui/src/uiTypes.ts+++ b/desktop-app/ui/src/uiTypes.ts@@ -62,11 +62,15 @@ export type AgentChatMessage = {role: AgentChatRolecontent: stringtimestamp: 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?: stringattachments?: ChatMessageAttachment[]/** True when this message represents a structured error returned by mcp-host. */isError?: boolean+ /** Local-only durable message that must not be evicted by server window reconciliation. */+ preserveLocal?: boolean/** LLM error code, e.g. "LLM_AUTHENTICATION_FAILED". Present when isError is true. */errorCode?: string/** LLM provider name, e.g. "zai". Present when isError is true. */