Evenfire is an intelligence layer platform for running LLM agents that take real actions, on your infrastructure
TypeScript
fix: harden desktop chat persistence and async guards
Josuéed7ff03cc8a2
diff --git a/desktop-app/src/__tests__/appService.bootstrap.test.ts b/desktop-app/src/__tests__/appService.bootstrap.test.tsindex 5ef06dca6..95c535fa3 100644--- a/desktop-app/src/__tests__/appService.bootstrap.test.ts+++ b/desktop-app/src/__tests__/appService.bootstrap.test.ts@@ -290,7 +290,10 @@ describe('AppService invitation configuration lookup', () => {process.env.RPC_PROXY_BASE_URL = 'https://rpc.example.com'vi.resetModules()- const { AppService } = await import('../appService.js')+ const [{ AppService }, { getActiveEnvKey, getActiveLegacyRestOnlyEnvKey }] = await Promise.all([+ import('../appService.js'),+ import('../config.js'),+ ])const service = new AppService() as unknown as {tokenStore: { clearSessionToken: ReturnType<typeof vi.fn> }rpcTokenManager: { clear: ReturnType<typeof vi.fn> }@@ -303,6 +306,9 @@ describe('AppService invitation configuration lookup', () => {service.rpcTokenManager = { clear: vi.fn() } as neverawait expect(service.logout()).rejects.toThrow(/keychain unavailable/)+ expect(service.tokenStore.clearSessionToken).toHaveBeenCalledWith(getActiveEnvKey(), {+ legacyEnvKeys: [getActiveLegacyRestOnlyEnvKey()],+ })expect(service.logoutInProgress).toBe(false)})@@ -425,7 +431,10 @@ describe('AppService invitation configuration lookup', () => {await expect(service.initialize()).resolves.toEqual({ authenticated: false, me: null })expect(clearSessionToken).toHaveBeenCalledWith(- resolveEnvKey('https://api.example.com', 'https://rpc.example.com')+ resolveEnvKey('https://api.example.com', 'https://rpc.example.com'),+ {+ legacyEnvKeys: [resolveEnvKey('https://api.example.com')],+ })})diff --git a/desktop-app/src/__tests__/chatStore.test.ts b/desktop-app/src/__tests__/chatStore.test.tsindex 6ef5ba7ea..177b6d141 100644--- a/desktop-app/src/__tests__/chatStore.test.ts+++ b/desktop-app/src/__tests__/chatStore.test.ts@@ -124,6 +124,27 @@ describe('createChat', () => {const chats = await store.listChats('agent-1')expect(chats).toHaveLength(1)})++ it('flushes the atomic index temp file and containing directory', async () => {+ const originalOpen = fs.open.bind(fs)+ const syncedPaths: string[] = []+ vi.spyOn(fs, 'open').mockImplementation(async (...args) => {+ const filePath = String(args[0])+ const handle = await originalOpen(...(args as Parameters<typeof fs.open>))+ return {+ sync: async () => {+ syncedPaths.push(filePath)+ await handle.sync()+ },+ close: () => handle.close(),+ } as Awaited<ReturnType<typeof fs.open>>+ })++ await store.createChat('agent-1', 'durable-index')++ expect(syncedPaths).toContain(agentPath('index.json.tmp'))+ expect(syncedPaths).toContain(agentPath())+ })})// ── renameChat ───────────────────────────────────────────────────────────────@@ -410,6 +431,31 @@ describe('messages', () => {expect(reloaded.map(message => message.id)).toEqual(['old-0', 'old-1', 'old-2', 'old-3'])})+ it('flushes both parents when promoting a staged paged snapshot', async () => {+ const originalOpen = fs.open.bind(fs)+ const syncedPaths: string[] = []+ vi.spyOn(fs, 'open').mockImplementation(async (...args) => {+ const filePath = String(args[0])+ const handle = await originalOpen(...(args as Parameters<typeof fs.open>))+ return {+ sync: async () => {+ syncedPaths.push(filePath)+ await handle.sync()+ },+ close: () => handle.close(),+ } as Awaited<ReturnType<typeof fs.open>>+ })++ await store.createChat('agent-1', 'durable-snapshot')+ await store.saveMessages('agent-1', 'durable-snapshot', [+ { id: 'm1', role: 'user', content: 'durable', timestamp: 1 },+ ])++ const encodedChatId = Buffer.from('durable-snapshot', 'utf8').toString('base64url')+ expect(syncedPaths).toContain(agentPath('chats'))+ expect(syncedPaths).toContain(agentPath('chats', '.snapshots', encodedChatId))+ })+it('aborts append instead of resetting the transcript on transient meta read failure', async () => {const pagedStore = new ChatStore(tempDir, {pageSize: 5,@@ -493,10 +539,26 @@ describe('messages', () => {const previousSnapshot = chatSnapshotDir('switch-recovery', 'previous', 'test')await fs.mkdir(dirname(previousSnapshot), { recursive: true })await fs.rename(chatCacheDir('switch-recovery'), previousSnapshot)+ const originalOpen = fs.open.bind(fs)+ const syncedPaths: string[] = []+ vi.spyOn(fs, 'open').mockImplementation(async (...args) => {+ const filePath = String(args[0])+ const handle = await originalOpen(...(args as Parameters<typeof fs.open>))+ return {+ sync: async () => {+ syncedPaths.push(filePath)+ await handle.sync()+ },+ close: () => handle.close(),+ } as Awaited<ReturnType<typeof fs.open>>+ })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()+ const encodedChatId = Buffer.from('switch-recovery', 'utf8').toString('base64url')+ expect(syncedPaths).toContain(agentPath('chats'))+ expect(syncedPaths).toContain(agentPath('chats', '.snapshots', encodedChatId))})it('completes recovery from a fully written next snapshot after a mid-swap crash', async () => {@@ -1004,6 +1066,26 @@ describe('messages', () => {).toBe(3)})+ it('recovers page data when hot metadata contains an invalid page count', async () => {+ await store.createChat('agent-1', 'invalid-page-count')+ await store.saveMessages('agent-1', 'invalid-page-count', [+ { id: 'm0', role: 'user', content: 'keep me', timestamp: 0 },+ ])+ const meta = await readJsonFile<{ pages: Array<{ count: number | null }> }>(+ chatMetaPath('invalid-page-count')+ )+ meta.pages[0]!.count = null+ await fs.writeFile(chatMetaPath('invalid-page-count'), JSON.stringify(meta))++ const recovered = await store.loadMessages('agent-1', 'invalid-page-count')++ expect(recovered.map(message => message.id)).toEqual(['m0'])+ expect(+ (await readJsonFile<{ pages: Array<{ count: number }> }>(chatMetaPath('invalid-page-count')))+ .pages[0]!.count+ ).toBe(1)+ })+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', [diff --git a/desktop-app/src/__tests__/chatStoreBinding.test.ts b/desktop-app/src/__tests__/chatStoreBinding.test.tsindex 0779b2c7e..b36088984 100644--- a/desktop-app/src/__tests__/chatStoreBinding.test.ts+++ b/desktop-app/src/__tests__/chatStoreBinding.test.ts@@ -280,14 +280,16 @@ describe('chatStoreBinding', () => {expect(await requireChatStore().listChats('agent-x')).toEqual([])})- it('wipes an agent dir with a missing/unparseable index.json', async () => {- await seedAgentDir(ENV_A, 'user-broken', 'agent-x', 'not json{', { 'c.json': '{}' })+ it('preserves agent dirs with missing or torn index.json files', async () => {+ await seedAgentDir(ENV_A, 'user-broken', 'agent-x', '{"version":2,"chats":[', {+ 'c.json': '{}',+ })await seedAgentDir(ENV_A, 'user-broken', 'agent-y', null, { 'c.json': '{}' })await bindChatStoreForUser('user-broken', ENV_A)- expect(await exists(path.join(tmpBase, ENV_A, 'user-broken', 'agent-x'))).toBe(false)- expect(await exists(path.join(tmpBase, ENV_A, 'user-broken', 'agent-y'))).toBe(false)+ expect(await exists(path.join(tmpBase, ENV_A, 'user-broken', 'agent-x', 'c.json'))).toBe(true)+ expect(await exists(path.join(tmpBase, ENV_A, 'user-broken', 'agent-y', 'c.json'))).toBe(true)})it('preserves the downgrade-compatible v2 agent index', async () => {diff --git a/desktop-app/src/__tests__/tokenStore.plainFallback.test.ts b/desktop-app/src/__tests__/tokenStore.plainFallback.test.tsindex 8ac4febc4..c8f4d24ad 100644--- a/desktop-app/src/__tests__/tokenStore.plainFallback.test.ts+++ b/desktop-app/src/__tests__/tokenStore.plainFallback.test.ts@@ -29,6 +29,7 @@ beforeEach(async () => {})afterEach(async () => {+ vi.restoreAllMocks()await fs.rm(userDataDir, { recursive: true, force: true })})@@ -47,6 +48,28 @@ describe('TokenStore plain-text fallback (no keytar, no safeStorage)', () => {).toBe(true)})+ it('preserves the legacy token when scoped persistence fails during migration', async () => {+ const legacyFile = path.join(userDataDir, 'session-token.json')+ const scopedFile = path.join(userDataDir, `session-token-${ENV_A}.json`)+ await fs.writeFile(legacyFile, JSON.stringify({ token: 'legacy-token' }))+ const originalWriteFile = fs.writeFile.bind(fs)+ vi.spyOn(fs, 'writeFile').mockImplementation(async (...args) => {+ if (String(args[0]) === scopedFile) {+ const error = new Error('disk full') as NodeJS.ErrnoException+ error.code = 'ENOSPC'+ throw error+ }+ return originalWriteFile(...(args as Parameters<typeof fs.writeFile>))+ })++ await expect(new TokenStore().getSessionToken(ENV_A)).resolves.toBeNull()++ expect(JSON.parse(await fs.readFile(legacyFile, 'utf8'))).toEqual({+ token: 'legacy-token',+ })+ await expect(fs.access(scopedFile)).rejects.toMatchObject({ code: 'ENOENT' })+ })+it('does not leak the plain-text token across environments', async () => {const store = new TokenStore()await store.setSessionToken('tok-a', ENV_A)diff --git a/desktop-app/src/__tests__/tokenStore.test.ts b/desktop-app/src/__tests__/tokenStore.test.tsindex 4fdba8a76..860e209f4 100644--- a/desktop-app/src/__tests__/tokenStore.test.ts+++ b/desktop-app/src/__tests__/tokenStore.test.ts@@ -70,6 +70,19 @@ describe('TokenStore per-environment slots (spec §5.2)', () => {expect(await store.getSessionToken(ENV_B)).toBe('tok-b')})+ it('clear removes explicitly supported legacy environment alias slots', async () => {+ const store = new TokenStore()+ await store.setSessionToken('legacy-token', ENV_A)+ await store.setSessionToken('current-token', ENV_A_WITH_RPC)++ await store.clearSessionToken(ENV_A_WITH_RPC, { legacyEnvKeys: [ENV_A] })++ expect(keychain.has(keyOf(SERVICE, `${LEGACY_ACCOUNT}::${ENV_A}`))).toBe(false)+ expect(keychain.has(keyOf(SERVICE, `${LEGACY_ACCOUNT}::${ENV_A_WITH_RPC}`))).toBe(false)+ expect(await store.getSessionToken(ENV_A_WITH_RPC)).toBeNull()+ expect(await store.getSessionToken(ENV_A)).toBeNull()+ })+it('migrates a legacy global-slot token into the active env slot, then deletes it', async () => {// Simulate a pre-per-env install: token in the single global account.keychain.set(keyOf(SERVICE, LEGACY_ACCOUNT), 'legacy-tok')diff --git a/desktop-app/src/appService.ts b/desktop-app/src/appService.tsindex b5f07cf56..3dd1a7cb1 100644--- a/desktop-app/src/appService.ts+++ b/desktop-app/src/appService.ts@@ -615,7 +615,7 @@ export class AppService {}this.clearAuthenticatedSessionState()if (AppService.isRejectedStoredSessionError(error)) {- await this.tokenStore.clearSessionToken(envKey)+ await this.tokenStore.clearSessionToken(envKey, { legacyEnvKeys })} else {console.warn('[AppService] Saved session restore failed; keeping token for retry:', error)}@@ -908,8 +908,11 @@ export class AppService {async logout(): Promise<void> {this.logoutInProgress = truetry {+ const envKey = getActiveEnvKey()+ const legacyEnvKey = getActiveLegacyRestOnlyEnvKey()+ const legacyEnvKeys = legacyEnvKey !== envKey ? [legacyEnvKey] : []this.clearAuthenticatedSessionState()- await this.tokenStore.clearSessionToken(getActiveEnvKey())+ await this.tokenStore.clearSessionToken(envKey, { legacyEnvKeys })} finally {this.logoutInProgress = false}diff --git a/desktop-app/src/chatStore.ts b/desktop-app/src/chatStore.tsindex cfe0e70b8..fa427b36a 100644--- a/desktop-app/src/chatStore.ts+++ b/desktop-app/src/chatStore.ts@@ -91,6 +91,12 @@ function isRawFilesystemError(err: unknown): boolean {return typeof (err as NodeJS.ErrnoException | undefined)?.code === 'string'}+function isUnsupportedDirectorySyncError(err: unknown): boolean {+ if (process.platform !== 'win32') return false+ const code = (err as NodeJS.ErrnoException | undefined)?.code+ return code === 'EISDIR' || code === 'EPERM' || code === 'EINVAL' || code === 'ENOTSUP'+}+function isUnsafeSegmentError(err: unknown): boolean {return err instanceof Error && /unsafe path segment/.test(err.message)}@@ -380,11 +386,51 @@ export class ChatStore {return this.chatPagePathFromPagesDir(this.chatPagesDirPath(agentRef, chatId), fileName)}- private async writeJsonAtomic(filePath: string, value: unknown): Promise<void> {+ private async syncFile(filePath: string): Promise<void> {+ const handle = await fs.open(filePath, 'r')+ try {+ await handle.sync()+ } finally {+ await handle.close()+ }+ }++ private async syncDirectory(directoryPath: string): Promise<void> {+ let handle: Awaited<ReturnType<typeof fs.open>> | null = null+ try {+ handle = await fs.open(directoryPath, 'r')+ await handle.sync()+ } catch (error) {+ // Node cannot open/fsync directories on Windows. The file itself is still+ // flushed before rename; retain directory fsync on platforms that support it.+ if (!isUnsupportedDirectorySyncError(error)) throw error+ } finally {+ await handle?.close()+ }+ }++ private async syncRenamedEntry(sourcePath: string, targetPath: string): Promise<void> {+ const sourceDir = dirname(sourcePath)+ const targetDir = dirname(targetPath)+ await this.syncDirectory(sourceDir)+ if (targetDir !== sourceDir) {+ await this.syncDirectory(targetDir)+ }+ }++ private async writeJsonAtomic(+ filePath: string,+ value: unknown,+ indentation?: number+ ): Promise<void> {const tmp = `${filePath}.tmp`try {- await fs.writeFile(tmp, JSON.stringify(value), { mode: 0o600 })+ const serialized = JSON.stringify(value, null, indentation)+ if (serialized === undefined) throw new TypeError('Unable to serialize JSON value')+ await fs.writeFile(tmp, serialized, { mode: 0o600 })+ await this.syncFile(tmp)await fs.rename(tmp, filePath)+ await this.syncRenamedEntry(tmp, filePath)} catch (err) {await fs.rm(tmp, { force: true }).catch(() => undefined)throw err@@ -426,7 +472,14 @@ export class ChatStore {) {throw new Error('Invalid paged chat metadata')}- if (parsed.pages.some(page => !PAGE_FILE_PATTERN.test(page.file))) {+ if (+ parsed.pages.some(+ page =>+ !PAGE_FILE_PATTERN.test(page.file) ||+ !Number.isSafeInteger(page.count) ||+ page.count < 1+ )+ ) {throw new Error('Invalid paged chat metadata page reference')}return this.finalizePagedMeta({@@ -980,13 +1033,17 @@ export class ChatStore {try {if (activeReadError) {corruptDir = this.chatSnapshotSiblingPath(agentRef, chatId, 'corrupt', randomUUID())- await fs.rename(activeDir, corruptDir).catch(err => {+ try {+ await fs.rename(activeDir, corruptDir)+ await this.syncRenamedEntry(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.syncRenamedEntry(snapshot.dir, activeDir)await this.removePagedChatSnapshotSiblings(agentRef, chatId)if (corruptDir) {await fs.rm(corruptDir, { recursive: true, force: true }).catch(() => undefined)@@ -995,7 +1052,12 @@ export class ChatStore {return await this.readPagedMeta(agentRef, chatId)} catch (err) {if (corruptDir) {- await fs.rename(corruptDir, activeDir).catch(() => undefined)+ try {+ await fs.rename(corruptDir, activeDir)+ await this.syncRenamedEntry(corruptDir, activeDir)+ } catch {+ // Try the next complete snapshot, if one exists.+ }}// Try the next complete snapshot, if one exists.}@@ -1011,9 +1073,12 @@ export class ChatStore {recursive: true,mode: 0o700,})- await fs.rename(activeDir, corruptDir).catch(err => {+ try {+ await fs.rename(activeDir, corruptDir)+ await this.syncRenamedEntry(activeDir, corruptDir)+ } catch (err) {if (!isNotFoundError(err)) throw err- })+ }console.warn(`[chatStore] Quarantined unreadable paged cache for "${chatId}"`)return null}@@ -1106,12 +1171,14 @@ export class ChatStore {try {await fs.rename(chatDir, backupDir)movedExistingSnapshot = true+ await this.syncRenamedEntry(chatDir, backupDir)} catch (err) {if ((err as NodeJS.ErrnoException).code !== 'ENOENT') throw err}await fs.rename(stagingDir, chatDir)primaryCommitted = true+ await this.syncRenamedEntry(stagingDir, chatDir)const cacheKey = this.chatSnapshotCleanupKey(agentRef, chatId)try {await this.writeLegacyCompatibilitySnapshot(agentRef, chatId, messages)@@ -1135,7 +1202,10 @@ export class ChatStore {} catch (err) {await fs.rm(stagingDir, { recursive: true, force: true }).catch(() => undefined)if (movedExistingSnapshot && !primaryCommitted) {- await fs.rename(backupDir, chatDir).catch(() => undefined)+ await fs+ .rename(backupDir, chatDir)+ .then(() => this.syncRenamedEntry(backupDir, chatDir))+ .catch(() => undefined)}throw err}@@ -1315,18 +1385,10 @@ export class ChatStore {// 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 paged chats.+ // Flush the temp file before rename and the containing directory afterward.+ // Visibility atomicity alone does not make the catalog durable across power loss.const target = this.indexPath(agentRef)- const tmp = `${target}.tmp`- try {- await fs.writeFile(tmp, JSON.stringify(normalized, null, 2), { mode: 0o600 })- await fs.rename(tmp, target)- } catch (error) {- await fs.rm(tmp, { force: true }).catch(() => undefined)- throw error- }+ await this.writeJsonAtomic(target, normalized, 2)}async listChats(agentRef: string): Promise<ChatMetadata[]> {diff --git a/desktop-app/src/chatStoreBinding.ts b/desktop-app/src/chatStoreBinding.tsindex 1540c14bb..658cce12f 100644--- a/desktop-app/src/chatStoreBinding.ts+++ b/desktop-app/src/chatStoreBinding.ts@@ -10,6 +10,7 @@ import { assertSafeFilesystemSegment } from './pathSafety.js'*/const SCHEMA_VERSION = 2const PREVIOUS_PAGED_INDEX_VERSION = 3+const LEGACY_INDEX_VERSIONS = new Set([1])const CORRUPT_QUARANTINE_RETENTION_MS = 30 * 24 * 60 * 60 * 1000// Default base dir derived from Electron's userData path. Tests override via@@ -221,9 +222,9 @@ async function writeMigrationMarker(markerPath: string): Promise<void> {}/**- * Scan a user's per-agent chat directories and remove any whose `index.json`- * is missing or not at the current schema version. Idempotent and best-effort- * per agent dir — a parse failure is treated as legacy and wiped.+ * Scan a user's per-agent chat directories and remove only caches whose parsed+ * catalog declares a known legacy schema. Missing, torn, or future-version+ * catalogs are not evidence that their paged transcripts are disposable.*/async function maybeWipeLegacyCache(userDir: string): Promise<void> {let entries@@ -261,8 +262,10 @@ async function maybeWipeLegacyCache(userDir: string): Promise<void> {error)}- } else {- isLegacy = parsed.version !== SCHEMA_VERSION+ } else if (LEGACY_INDEX_VERSIONS.has(parsed.version ?? Number.NaN)) {+ isLegacy = true+ } else if (parsed.version !== SCHEMA_VERSION) {+ console.warn(`[chatStore] Preserving cache for "${entry.name}" with unknown index schema`)}} catch (error) {const code = (error as NodeJS.ErrnoException | undefined)?.code@@ -271,8 +274,9 @@ async function maybeWipeLegacyCache(userDir: string): Promise<void> {// Propagate it instead of recursively deleting a live agent cache.throw error}- // index.json missing or unparseable → treat as legacy- isLegacy = true+ // Missing or unparseable catalogs can be a torn atomic write. Preserve+ // paged transcripts so server reconciliation or manual recovery can use them.+ console.warn(`[chatStore] Preserving cache for "${entry.name}" with unreadable index`)}if (isLegacy) {console.warn(diff --git a/desktop-app/src/ipc.ts b/desktop-app/src/ipc.tsindex 6a36a46e2..ed42601c5 100644--- a/desktop-app/src/ipc.ts+++ b/desktop-app/src/ipc.ts@@ -37,6 +37,14 @@ function sanitizeOptionalInteger(input: unknown): number | undefined {return input}+function sanitizeOptionalPositiveInteger(input: unknown, label: string): number | undefined {+ if (input === undefined || input === null || input === '') return undefined+ if (typeof input !== 'number' || !Number.isSafeInteger(input) || input < 1) {+ throw new Error(`Invalid ${label}`)+ }+ return input+}+export function sanitizeChatLoadWindow(limitInput: unknown,offsetInput: unknown@@ -514,9 +522,8 @@ export function registerIpcHandlers(service: AppService): void {})ipcMain.handle('approvals:listPending', async (event, payload?: { limit?: number }) => {assertTrustedSender(event)- return service.listPendingWorkflowApprovals(- typeof payload?.limit === 'number' ? payload.limit : 20- )+ const limit = sanitizeOptionalPositiveInteger(payload?.limit, 'pending approvals limit')+ return service.listPendingWorkflowApprovals(limit ?? 20)})ipcMain.handle('approvals:decide',@@ -752,8 +759,9 @@ export function registerIpcHandlers(service: AppService): void {const hostRefs = Array.isArray(payload?.hostRefs)? payload.hostRefs.map(v => String(v).trim()).filter(Boolean): undefined+ const limit = sanitizeOptionalPositiveInteger(payload?.limit, 'host activity limit')return service.getHostActivity(hostRef, {- limit: typeof payload?.limit === 'number' ? payload.limit : undefined,+ limit,sinceEventId: sanitizeString(payload?.sinceEventId) || undefined,hostRefs,})@@ -1323,7 +1331,8 @@ export function registerIpcHandlers(service: AppService): void {const ns = sanitizeString(payload?.ns)const name = sanitizeString(payload?.name)if (!ns || !name) throw new Error('ns and name are required')- return service.listWorkflowRuns(ns, name, payload?.limit)+ const limit = sanitizeOptionalPositiveInteger(payload?.limit, 'workflow runs limit')+ return service.listWorkflowRuns(ns, name, limit)})diff --git a/desktop-app/src/tokenStore.ts b/desktop-app/src/tokenStore.tsindex 10e921b3c..eaf29b5ea 100644--- a/desktop-app/src/tokenStore.ts+++ b/desktop-app/src/tokenStore.ts@@ -269,7 +269,7 @@ export class TokenStore {const data = JSON.parse(raw) as { token?: unknown }const token = typeof data.token === 'string' && data.token ? data.token : nullif (token) {- await this.setSessionToken(token, envKey).catch(() => {})+ await this.setSessionToken(token, envKey)await fs.unlink(file).catch(() => {})}return token@@ -301,15 +301,24 @@ export class TokenStore {await fs.writeFile(file, JSON.stringify({ token }), { encoding: 'utf8', mode: 0o600 })}- async clearSessionToken(envKey: string): Promise<void> {+ async clearSessionToken(+ envKey: string,+ options: { legacyEnvKeys?: readonly string[] } = {}+ ): Promise<void> {assertEnvKey(envKey)- const account = accountFor(envKey)+ const legacyEnvKeys = Array.from(+ new Set(+ (options.legacyEnvKeys ?? [])+ .map(key => String(key || '').trim())+ .filter(key => key && key !== envKey)+ )+ )+ for (const legacyEnvKey of legacyEnvKeys) assertEnvKey(legacyEnvKey)+ const scopedEnvKeys = [envKey, ...legacyEnvKeys]const keytar = await loadKeytar()if (keytar) {- try {- await keytar.deletePassword(SERVICE, account)- } catch {- // Continue cleaning up file-based storage even if keychain fails.+ for (const scopedEnvKey of scopedEnvKeys) {+ await keytar.deletePassword(SERVICE, accountFor(scopedEnvKey)).catch(() => {})}// Best-effort cleanup of the legacy global slot so it can't be migrated// into another environment later.@@ -318,12 +327,14 @@ export class TokenStore {// Always clean up file-based storage regardless of keychain result,// since prior versions may have written both stores.await Promise.all([- encryptedFilePath(envKey)- .then(file => fs.unlink(file))- .catch(() => {}),- plainFilePath(envKey)- .then(file => fs.unlink(file))- .catch(() => {}),+ ...scopedEnvKeys.flatMap(scopedEnvKey => [+ encryptedFilePath(scopedEnvKey)+ .then(file => fs.unlink(file))+ .catch(() => {}),+ plainFilePath(scopedEnvKey)+ .then(file => fs.unlink(file))+ .catch(() => {}),+ ]),legacyEncryptedFilePath().then(file => fs.unlink(file)).catch(() => {}),diff --git a/desktop-app/test/ipc.test.ts b/desktop-app/test/ipc.test.tsindex 7b7cc6411..cc41d3543 100644--- a/desktop-app/test/ipc.test.ts+++ b/desktop-app/test/ipc.test.ts@@ -96,6 +96,7 @@ describe('ipc host status stream handlers', () => {getExternalChannelsSummary: vi.fn(),listArtifacts: vi.fn(),downloadArtifact: vi.fn(),+ listWorkflowRuns: vi.fn(),listWorkflowRunArtifacts: vi.fn(),downloadWorkflowRunArtifact: vi.fn(),resolveGfsUri: vi.fn(),@@ -528,6 +529,19 @@ describe('ipc host status stream handlers', () => {expect(result).toEqual([{ id: 'approval-1' }])})+ it.each([-1, 1.5, Number.POSITIVE_INFINITY])(+ 'rejects invalid pending approval limit %s at the IPC boundary',+ async limit => {+ const { event } = makeTrustedEvent()+ const handler = testState.handlers.get('approvals:listPending')++ await expect(Promise.resolve(handler?.(event, { limit }))).rejects.toThrow(+ 'Invalid pending approvals limit'+ )+ expect(service.listPendingWorkflowApprovals).not.toHaveBeenCalled()+ }+ )+it('routes artifact listing through the IPC handler for trusted senders', async () => {service.listArtifacts.mockResolvedValue({ artifacts: [] })const { event } = makeTrustedEvent()@@ -585,6 +599,38 @@ describe('ipc host status stream handlers', () => {expect(service.downloadArtifact).not.toHaveBeenCalled()})+ it('routes workflow run listing through a validated IPC limit', async () => {+ service.listWorkflowRuns.mockResolvedValue({ items: [] })+ const { event } = makeTrustedEvent()+ const handler = testState.handlers.get('workflows:runs')++ const result = await Promise.resolve(+ handler?.(event, { ns: 'sandbox-recipes', name: 'recipe', limit: 25 })+ )++ expect(service.listWorkflowRuns).toHaveBeenCalledWith('sandbox-recipes', 'recipe', 25)+ expect(result).toEqual({ items: [] })+ })++ it.each([-1, 1.5, Number.POSITIVE_INFINITY])(+ 'rejects invalid workflow run limit %s at the IPC boundary',+ async limit => {+ const { event } = makeTrustedEvent()+ const handler = testState.handlers.get('workflows:runs')++ await expect(+ Promise.resolve(+ handler?.(event, {+ ns: 'sandbox-recipes',+ name: 'recipe',+ limit,+ })+ )+ ).rejects.toThrow('Invalid workflow runs limit')+ expect(service.listWorkflowRuns).not.toHaveBeenCalled()+ }+ )+it('saves run artifacts under Downloads with sanitized filenames', async () => {service.downloadWorkflowRunArtifact.mockResolvedValue(Buffer.from('run artifact'))const { event } = makeTrustedEvent()@@ -676,6 +722,19 @@ describe('ipc host status stream handlers', () => {})})+ it.each([-1, 1.5, Number.POSITIVE_INFINITY])(+ 'rejects invalid host activity limit %s at the IPC boundary',+ async limit => {+ const { event } = makeTrustedEvent()+ const handler = testState.handlers.get('rpc:getHostActivity')++ await expect(+ Promise.resolve(handler?.(event, { hostRef: 'chatllm', limit }))+ ).rejects.toThrow('Invalid host activity limit')+ expect(service.getHostActivity).not.toHaveBeenCalled()+ }+ )+it('rejects untrusted sender for stream stop', async () => {const handler = testState.handlers.get('rpc:hostStatusStreamStop')expect(handler).toBeDefined()diff --git a/desktop-app/ui/src/hooks/domain/__tests__/useAgentChatController.test.tsx b/desktop-app/ui/src/hooks/domain/__tests__/useAgentChatController.test.tsxindex d75799aa8..efa563dc6 100644--- a/desktop-app/ui/src/hooks/domain/__tests__/useAgentChatController.test.tsx+++ b/desktop-app/ui/src/hooks/domain/__tests__/useAgentChatController.test.tsx@@ -42,6 +42,16 @@ async function settleMount() {await waitFor(() => expect(clerum.chat.getIndex).toHaveBeenCalled())}+function deferred<T>() {+ let resolve!: (value: T) => void+ let reject!: (reason?: unknown) => void+ const promise = new Promise<T>((resolvePromise, rejectPromise) => {+ resolve = resolvePromise+ reject = rejectPromise+ })+ return { promise, resolve, reject }+}+describe('useAgentChatController — characterization (D.0)', () => {describe('switchToChat', () => {// ⚠️ Rewritten for D.4 (plan §5.3): the pre-D.4 `isRemote` dual-path was@@ -123,6 +133,68 @@ describe('useAgentChatController — characterization (D.0)', () => {expect(result.current.activeChatId).toBe('chat-2')})+ it('stops delta pagination when the active chat changes during the first page', async () => {+ clerum.chat.loadMessages.mockImplementation(async (_agentRef: string, chatId: string) =>+ chatId === 'chat-a'+ ? [+ {+ id: 'turn-1-user',+ role: 'user',+ content: 'cached',+ timestamp: 1,+ serverTurnNumber: 1,+ },+ ]+ : []+ )+ const firstPage = deferred<{+ agent: string+ chatId: string+ turns: Array<{ number: number; user_input: string }>+ latestTurnNumber: number+ hasMoreAfter: boolean+ }>()+ let chatACalls = 0+ clerum.rpc.loadSessionMessages.mockImplementation(+ async (_hostRef: string, _agentRef: string, chatId: string) => {+ if (chatId !== 'chat-a') return { agent: 'agent-x', chatId, turns: [] }+ chatACalls += 1+ if (chatACalls === 1) return firstPage.promise+ return {+ agent: 'agent-x',+ chatId,+ turns: [{ number: 3, user_input: 'stale page' }],+ latestTurnNumber: 3,+ hasMoreAfter: false,+ }+ }+ )+ const { result } = renderController()+ await settleMount()++ let staleSwitch!: Promise<void>+ await act(async () => {+ staleSwitch = result.current.switchToChat('agent-x', 'chat-a')+ await Promise.resolve()+ })+ await waitFor(() => expect(chatACalls).toBe(1))+ await act(async () => {+ await result.current.switchToChat('agent-x', 'chat-b')+ })+ await act(async () => {+ firstPage.resolve({+ agent: 'agent-x',+ chatId: 'chat-a',+ turns: [{ number: 2, user_input: 'first delta' }],+ latestTurnNumber: 2,+ hasMoreAfter: true,+ })+ await staleSwitch+ })++ expect(chatACalls).toBe(1)+ })+it('4.3 stays on the local cache and flags offline mode when the reconcile network-fails', async () => {clerum.chat.loadMessages.mockResolvedValue([])clerum.rpc.loadSessionMessages.mockRejectedValue(new Error('network unreachable'))@@ -981,6 +1053,75 @@ describe('useAgentChatController — characterization (D.0)', () => {expect(entry?.agentRef).toBe('agent-x')})+ it('does not let a stale agent index replace the selected agent sidebar', async () => {+ type Index = {+ version: number+ lastActiveChatId: null+ onboardingDismissed: boolean+ chats: Array<{+ id: string+ title: string+ createdAt: string+ updatedAt: string+ messageCount: number+ }>+ }+ const agentXIndex = deferred<Index>()+ const agentYIndex = deferred<Index>()+ clerum.chat.getIndex.mockImplementation((agentRef: string) =>+ agentRef === 'agent-x' ? agentXIndex.promise : agentYIndex.promise+ )+ const { result, rerender } = renderController({+ agentNames: ['agent-x', 'agent-y'],+ loadMenuData: false,+ })+ await waitFor(() => expect(clerum.chat.getIndex).toHaveBeenCalledWith('agent-x'))++ rerender({+ selectedAgent: 'agent-y',+ agentNames: ['agent-x', 'agent-y'],+ loadMenuData: false,+ })+ await waitFor(() => expect(clerum.chat.getIndex).toHaveBeenCalledWith('agent-y'))+ await act(async () => {+ agentYIndex.resolve({+ version: 2,+ lastActiveChatId: null,+ onboardingDismissed: false,+ chats: [+ {+ id: 'agent-y-chat',+ title: 'Agent Y chat',+ createdAt: '2026-05-02T00:00:00Z',+ updatedAt: '2026-05-02T00:00:00Z',+ messageCount: 1,+ },+ ],+ })+ })+ await waitFor(() => expect(result.current.chatList[0]?.id).toBe('agent-y-chat'))++ await act(async () => {+ agentXIndex.resolve({+ version: 2,+ lastActiveChatId: null,+ onboardingDismissed: false,+ chats: [+ {+ id: 'agent-x-chat',+ title: 'Stale agent X chat',+ createdAt: '2026-05-03T00:00:00Z',+ updatedAt: '2026-05-03T00:00:00Z',+ messageCount: 1,+ },+ ],+ })+ await Promise.resolve()+ })++ expect(result.current.chatList.map(chat => chat.id)).toEqual(['agent-y-chat'])+ })+it('renders local sessions without waiting for remote listSessions', async () => {clerum.chat.getIndex.mockResolvedValue({version: 1,diff --git a/desktop-app/ui/src/hooks/domain/useAgentChatController.ts b/desktop-app/ui/src/hooks/domain/useAgentChatController.tsindex 7a05f2494..39cc4baa9 100644--- a/desktop-app/ui/src/hooks/domain/useAgentChatController.ts+++ b/desktop-app/ui/src/hooks/domain/useAgentChatController.ts@@ -473,11 +473,7 @@ 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,- query?: SessionMessagesQuery- ) => Promise<SessionMessagesResult>+ loadSessionMessages: ReconcileChatDeps['loadSessionMessages']attachLiveTask: ReconcileChatDeps['attachLiveTask']settleIdle: ReconcileChatDeps['settleIdle']evictChat: ReconcileChatDeps['evictChat']@@ -486,8 +482,8 @@ export function useAgentChatController({if (!reconcileChatRef.current) {reconcileChatRef.current = createReconcileChat({fsm,- loadSessionMessages: (agentRef, chatId, query) =>- reconcileBranchesRef.current!.loadSessionMessages(agentRef, chatId, query),+ loadSessionMessages: (agentRef, chatId, query, stillRelevant) =>+ reconcileBranchesRef.current!.loadSessionMessages(agentRef, chatId, query, stillRelevant),attachLiveTask: (chatKey, resp, epoch, stillRelevant) =>reconcileBranchesRef.current!.attachLiveTask(chatKey, resp, epoch, stillRelevant),settleIdle: (chatKey, resp, epoch, hint, stillRelevant) =>diff --git a/desktop-app/ui/src/hooks/domain/useChatListController.ts b/desktop-app/ui/src/hooks/domain/useChatListController.tsindex 58ec252c5..9ebbc16c0 100644--- a/desktop-app/ui/src/hooks/domain/useChatListController.ts+++ b/desktop-app/ui/src/hooks/domain/useChatListController.ts@@ -174,6 +174,7 @@ export function useChatListController({}const index = await chatStore.getIndex(agentRef)const merged = [...index.chats].sort(byUpdatedDesc)+ if (selectedAgentRef.current !== agentRef) return { index, merged }setChatList(merged)const requestGeneration = requestGenerationRef.current@@ -372,7 +373,9 @@ export function useChatListController({continue}console.warn('[loadChatList] failed after retry, clearing list', { agentRef, err })- setChatList([])+ if (selectedAgentRef.current === agentRef) {+ setChatList([])+ }return null}}