Skip to content

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

TypeScript

fix: harden desktop chat recovery and reconciliation

Josuéfb67e5122eef
diff --git a/desktop-app/package-lock.json b/desktop-app/package-lock.json
index 2c8edbfe5..add53f1c5 100644
--- a/desktop-app/package-lock.json
+++ b/desktop-app/package-lock.json
@@ -1,12 +1,12 @@
{
"name": "evenfire",
- "version": "0.1.343",
+ "version": "0.1.344",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "evenfire",
- "version": "0.1.343",
+ "version": "0.1.344",
"license": "MPL-2.0",
"dependencies": {
"@tanstack/react-query": "5.100.10",
diff --git a/desktop-app/package.json b/desktop-app/package.json
index 31b80d921..af25e835a 100644
--- a/desktop-app/package.json
+++ b/desktop-app/package.json
@@ -1,7 +1,7 @@
{
"name": "evenfire",
"productName": "Evenfire",
- "version": "0.1.343",
+ "version": "0.1.344",
"private": true,
"license": "MPL-2.0",
"description": "Evenfire desktop client for secure agent and workflow access",
diff --git a/desktop-app/src/__tests__/chatStore.test.ts b/desktop-app/src/__tests__/chatStore.test.ts
index 35f88b8a0..6ef5ba7ea 100644
--- a/desktop-app/src/__tests__/chatStore.test.ts
+++ b/desktop-app/src/__tests__/chatStore.test.ts
@@ -137,6 +137,20 @@ describe('renameChat', () => {
expect(chat!.title).toBe('Renamed Chat')
expect(chat!.updatedAt >= created.updatedAt).toBe(true)
})
+
+ it('removes the index temp file when its atomic rename fails', async () => {
+ await store.createChat('agent-1', 'r1')
+ const originalRename = fs.rename.bind(fs)
+ vi.spyOn(fs, 'rename').mockImplementation(async (from, to) => {
+ if (String(from) === agentPath('index.json.tmp')) {
+ throw transientFileReadError('EACCES')
+ }
+ return originalRename(from, to)
+ })
+
+ await expect(store.renameChat('agent-1', 'r1', 'Renamed Chat')).rejects.toThrow()
+ await expect(fs.access(agentPath('index.json.tmp'))).rejects.toMatchObject({ code: 'ENOENT' })
+ })
})
// ── deleteChat ───────────────────────────────────────────────────────────────
@@ -702,6 +716,21 @@ describe('messages', () => {
expect(chat!.messageCount).toBe(2)
})
+ it('keeps sidebar messageCount in visible user/assistant units after appends', async () => {
+ await store.createChat('agent-1', 'visible-count')
+ await store.saveMessages('agent-1', 'visible-count', [
+ { id: 'm1', role: 'user', content: 'question', timestamp: 1 },
+ { id: 's1', role: 'system', content: 'local status', timestamp: 2 },
+ ])
+ await store.appendMessages('agent-1', 'visible-count', [
+ { id: 'm2', role: 'assistant', content: 'answer', timestamp: 3 },
+ { id: 's2', role: 'system', content: 'another status', timestamp: 4 },
+ ])
+
+ const chat = (await store.listChats('agent-1')).find(item => item.id === 'visible-count')
+ expect(chat?.messageCount).toBe(2)
+ })
+
it('persists activity aggregates in the chat index', async () => {
await store.createChat('agent-1', 'activity-1')
await store.saveMessages('agent-1', 'activity-1', [
@@ -1252,6 +1281,39 @@ describe('messages', () => {
const messages = await store.loadMessages('agent-1', 'migration-failure')
expect(messages.map(message => message.id)).toEqual(['m1'])
})
+
+ it('keeps a committed paged rewrite successful when the downgrade snapshot write fails', async () => {
+ const chatId = 'compatibility-write-failure'
+ await store.createChat('agent-1', chatId)
+ await store.saveMessages('agent-1', chatId, [
+ { id: 'old', role: 'user', content: 'old', timestamp: 1 },
+ ])
+
+ const originalWriteFile = fs.writeFile.bind(fs)
+ let injected = false
+ vi.spyOn(fs, 'writeFile').mockImplementation(async (...args) => {
+ if (!injected && String(args[0]) === agentPath(`${chatId}.json.tmp`)) {
+ injected = true
+ throw transientFileReadError('ENOSPC')
+ }
+ return originalWriteFile(...(args as Parameters<typeof fs.writeFile>))
+ })
+
+ await expect(
+ store.saveMessages('agent-1', chatId, [
+ { id: 'new', role: 'assistant', content: 'new', timestamp: 2 },
+ ])
+ ).resolves.toBeUndefined()
+
+ expect((await store.loadMessages('agent-1', chatId)).map(message => message.id)).toEqual([
+ 'new',
+ ])
+ expect(
+ (await readJsonFile<{ messages: ChatMessage[] }>(agentPath(`${chatId}.json`))).messages.map(
+ message => message.id
+ )
+ ).toEqual(['new'])
+ })
})
// ── lastActiveChatId ─────────────────────────────────────────────────────────
@@ -1297,6 +1359,26 @@ describe('corrupt/missing files', () => {
expect(index.chats).toEqual([])
})
+ it('does not overwrite an index after a transient read failure', async () => {
+ await store.createChat('agent-1', 'kept')
+ const originalReadFile = fs.readFile.bind(fs)
+ let injected = false
+ vi.spyOn(fs, 'readFile').mockImplementation(async (...args) => {
+ if (!injected && String(args[0]) === agentPath('index.json')) {
+ injected = true
+ throw transientFileReadError('EACCES')
+ }
+ return originalReadFile(...(args as Parameters<typeof fs.readFile>))
+ })
+
+ await expect(store.renameChat('agent-1', 'kept', 'Lost')).rejects.toThrow()
+
+ vi.restoreAllMocks()
+ expect((await store.listChats('agent-1')).find(chat => chat.id === 'kept')?.title).toBe(
+ 'New Chat'
+ )
+ })
+
it('returns empty messages for missing chat file', async () => {
const messages = await store.loadMessages('agent-1', 'nonexistent')
expect(messages).toEqual([])
@@ -1436,6 +1518,8 @@ describe('path-segment validation', () => {
await expect(store.createChat('../escape', 'c1')).rejects.toThrow(/unsafe path segment/)
await expect(store.createChat('a/b', 'c1')).rejects.toThrow(/unsafe path segment/)
await expect(store.createChat('.', 'c1')).rejects.toThrow(/unsafe path segment/)
+ await expect(store.createChat('agent\nforged', 'c1')).rejects.toThrow(/unsafe path segment/)
+ await expect(store.createChat('CON', 'c1')).rejects.toThrow(/unsafe path segment/)
})
it('rejects a traversing chatId on replace/append', async () => {
@@ -1451,6 +1535,9 @@ describe('path-segment validation', () => {
/unsafe path segment/
)
await expect(store.saveMessages('agent-1', 'index', [])).rejects.toThrow(/unsafe path segment/)
+ for (const chatId of ['INDEX', 'chat:1', 'chat.', 'chat ', 'NUL.txt', 'chat\u0007id']) {
+ await expect(store.saveMessages('agent-1', chatId, [])).rejects.toThrow(/unsafe path segment/)
+ }
})
// Read verbs are tolerant-by-contract (return empty on any failure) — the key
diff --git a/desktop-app/src/__tests__/chatStoreBinding.test.ts b/desktop-app/src/__tests__/chatStoreBinding.test.ts
index b46251868..0779b2c7e 100644
--- a/desktop-app/src/__tests__/chatStoreBinding.test.ts
+++ b/desktop-app/src/__tests__/chatStoreBinding.test.ts
@@ -177,13 +177,39 @@ describe('chatStoreBinding', () => {
})
it('rejects an unsafe userId or envKey before touching the filesystem (no wipe escape)', async () => {
- for (const bad of ['', '.', '..', '../../etc', 'a/b', 'a\\b']) {
+ for (const bad of [
+ '',
+ '.',
+ '..',
+ '../../etc',
+ 'a/b',
+ 'a\\b',
+ 'user:name',
+ 'user.',
+ 'NUL',
+ 'line\nbreak',
+ ]) {
await expect(bindChatStoreForUser(bad, ENV_A)).rejects.toThrow(/unsafe path segment/)
await expect(bindChatStoreForUser('user-a', bad)).rejects.toThrow(/unsafe path segment/)
}
expect(() => requireChatStore()).toThrow(/Not authenticated/)
})
+ it('backfills owner-only permissions on existing cache ancestry', async () => {
+ const envDir = path.join(tmpBase, ENV_A)
+ const userDir = path.join(envDir, 'user-permissions')
+ await fs.mkdir(userDir, { recursive: true })
+ await fs.chmod(tmpBase, 0o777)
+ await fs.chmod(envDir, 0o777)
+ await fs.chmod(userDir, 0o777)
+
+ await bindChatStoreForUser('user-permissions', ENV_A)
+
+ for (const directory of [tmpBase, envDir, userDir]) {
+ expect((await fs.stat(directory)).mode & 0o777).toBe(0o700)
+ }
+ })
+
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')
@@ -349,6 +375,33 @@ describe('chatStoreBinding', () => {
).toBe(3)
})
+ it('does not delete a current cache after a transient index read failure', async () => {
+ const v2Index = JSON.stringify({
+ version: 2,
+ chats: [{ id: 'keep', title: 'Keep', createdAt: 'x', updatedAt: 'x', messageCount: 1 }],
+ lastActiveChatId: 'keep',
+ onboardingDismissed: false,
+ })
+ await seedAgentDir(ENV_A, 'user-read-failure', 'agent-x', v2Index, {
+ 'keep.json': '{"version":2,"chatId":"keep","messages":[]}',
+ })
+ const indexPath = path.join(tmpBase, ENV_A, 'user-read-failure', 'agent-x', 'index.json')
+ const originalReadFile = fs.readFile.bind(fs)
+ vi.spyOn(fs, 'readFile').mockImplementation(async (...args) => {
+ if (String(args[0]) === indexPath) {
+ const error = new Error('temporarily unreadable') as NodeJS.ErrnoException
+ error.code = 'EACCES'
+ throw error
+ }
+ return originalReadFile(...(args as Parameters<typeof fs.readFile>))
+ })
+
+ await expect(bindChatStoreForUser('user-read-failure', ENV_A)).rejects.toThrow()
+ expect(
+ await exists(path.join(tmpBase, ENV_A, 'user-read-failure', 'agent-x', 'keep.json'))
+ ).toBe(true)
+ })
+
it('is a no-op when the user has no cache directory yet', async () => {
await expect(bindChatStoreForUser('brand-new-user', ENV_A)).resolves.toBeUndefined()
expect(await requireChatStore().listChats('agent-x')).toEqual([])
diff --git a/desktop-app/src/__tests__/rpcProxyClient.test.ts b/desktop-app/src/__tests__/rpcProxyClient.test.ts
index ba3130362..2dfc18cd4 100644
--- a/desktop-app/src/__tests__/rpcProxyClient.test.ts
+++ b/desktop-app/src/__tests__/rpcProxyClient.test.ts
@@ -20,7 +20,7 @@ describe('RpcProxyClient.listSessions', () => {
vi.restoreAllMocks()
})
- it.each(['.', '..', 'host/name', 'host\\name'])(
+ it.each(['.', '..', 'host/name', 'host\\name', 'host\nforged', 'x'.repeat(501)])(
'rejects an unsafe host path before issuing a request: %s',
async hostRef => {
const fetchMock = vi.fn()
@@ -30,6 +30,19 @@ describe('RpcProxyClient.listSessions', () => {
expect(fetchMock).not.toHaveBeenCalled()
}
)
+
+ it.each(['agent:rpc', 'agent\nforged', 'x'.repeat(201)])(
+ 'rejects an unsafe session agent before issuing a request: %s',
+ async agent => {
+ const fetchMock = vi.fn()
+ vi.stubGlobal('fetch', fetchMock)
+
+ await expect(client.loadSessionMessages('rpc-token', 'host', agent, 'chat')).rejects.toThrow(
+ /unsafe path segment/
+ )
+ expect(fetchMock).not.toHaveBeenCalled()
+ }
+ )
})
describe('RpcProxyClient.cancelTask', () => {
diff --git a/desktop-app/src/chatStore.ts b/desktop-app/src/chatStore.ts
index 57c380db8..cfe0e70b8 100644
--- a/desktop-app/src/chatStore.ts
+++ b/desktop-app/src/chatStore.ts
@@ -2,6 +2,7 @@ import { createHash, randomUUID } from 'node:crypto'
import { promises as fs } from 'node:fs'
import { dirname, join } from 'node:path'
import { mergeAuthoritativeServerMessages, messageServerTurnNumber } from './chatMessageMerge.js'
+import { assertSafeFilesystemSegment } from './pathSafety.js'
import type {
ChatFile,
ChatIndex,
@@ -130,13 +131,6 @@ function pageEntry(file: string, messages: ChatMessage[]): ChatPageEntry {
* (wholesale overwrite) and `deleteChat` (unlink) make traversal high-impact,
* so we guard centrally where the on-disk path is built.
*/
-function assertSafeSegment(label: string, value: string): void {
- 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')
}
@@ -298,7 +292,7 @@ export class ChatStore {
}
private agentDir(agentRef: string): string {
- assertSafeSegment('agentRef', agentRef)
+ assertSafeFilesystemSegment('agentRef', agentRef)
return join(this.baseDir, agentRef)
}
@@ -307,22 +301,30 @@ export class ChatStore {
}
private chatFilePath(agentRef: string, chatId: string): string {
- assertSafeSegment('chatId', chatId)
+ assertSafeFilesystemSegment('chatId', chatId, {
+ reservedNames: ['index', 'chats'],
+ })
return join(this.agentDir(agentRef), `${chatId}.json`)
}
private chatCompatibilitySignaturePath(agentRef: string, chatId: string): string {
- assertSafeSegment('chatId', chatId)
+ assertSafeFilesystemSegment('chatId', chatId, {
+ reservedNames: ['index', 'chats'],
+ })
return join(this.agentDir(agentRef), `${chatId}.compat`)
}
private corruptLegacyChatFilePath(agentRef: string, chatId: string): string {
- assertSafeSegment('chatId', chatId)
+ assertSafeFilesystemSegment('chatId', chatId, {
+ reservedNames: ['index', 'chats'],
+ })
return join(this.agentDir(agentRef), '.corrupt', encodedChatId(chatId), `${randomUUID()}.json`)
}
private chatDirPath(agentRef: string, chatId: string): string {
- assertSafeSegment('chatId', chatId)
+ assertSafeFilesystemSegment('chatId', chatId, {
+ reservedNames: ['index', 'chats'],
+ })
return join(this.agentDir(agentRef), 'chats', chatId)
}
@@ -332,7 +334,9 @@ export class ChatStore {
kind: 'next' | 'previous' | 'corrupt',
token: string
): string {
- assertSafeSegment('chatId', chatId)
+ assertSafeFilesystemSegment('chatId', chatId, {
+ reservedNames: ['index', 'chats'],
+ })
return join(
this.agentDir(agentRef),
'chats',
@@ -343,7 +347,9 @@ export class ChatStore {
}
private chatSnapshotRootPath(agentRef: string, chatId: string): string {
- assertSafeSegment('chatId', chatId)
+ assertSafeFilesystemSegment('chatId', chatId, {
+ reservedNames: ['index', 'chats'],
+ })
return join(this.agentDir(agentRef), 'chats', '.snapshots', encodedChatId(chatId))
}
@@ -1054,6 +1060,7 @@ export class ChatStore {
const backupDir = this.chatSnapshotSiblingPath(agentRef, chatId, 'previous', snapshotToken)
const pagesDir = this.chatPagesDirFromChatDir(stagingDir)
let movedExistingSnapshot = false
+ let primaryCommitted = false
this.cleanedSnapshotSiblingKeys.delete(this.chatSnapshotCleanupKey(agentRef, chatId))
await fs.mkdir(join(this.agentDir(agentRef), 'chats'), { recursive: true, mode: 0o700 })
@@ -1104,18 +1111,30 @@ export class ChatStore {
}
await fs.rename(stagingDir, chatDir)
+ primaryCommitted = true
+ const cacheKey = this.chatSnapshotCleanupKey(agentRef, chatId)
+ try {
+ await this.writeLegacyCompatibilitySnapshot(agentRef, chatId, messages)
+ this.compatibilityCheckedKeys.add(cacheKey)
+ } catch (error) {
+ // The paged snapshot is the durable source of truth and has already
+ // committed. Keep the successful write visible to the caller; a later
+ // read repairs the auxiliary downgrade window from the paged data.
+ this.compatibilityCheckedKeys.delete(cacheKey)
+ console.warn(
+ `[chatStore] Failed to refresh downgrade snapshot for ${chatId}; retrying on read`,
+ error
+ )
+ }
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) {
+ if (movedExistingSnapshot && !primaryCommitted) {
await fs.rename(backupDir, chatDir).catch(() => undefined)
}
throw err
@@ -1242,17 +1261,38 @@ export class ChatStore {
fs.rm(this.chatPagePath(agentRef, chatId, file), { force: true })
)
)
- if (compatibility.signature !== meta.legacyCompatibilitySignature) {
- await this.writeLegacyCompatibilitySnapshot(agentRef, chatId, compatibilityMessages)
+ let compatibilityCurrent = compatibility.signature === meta.legacyCompatibilitySignature
+ if (!compatibilityCurrent) {
+ try {
+ await this.writeLegacyCompatibilitySnapshot(agentRef, chatId, compatibilityMessages)
+ compatibilityCurrent = true
+ } catch (error) {
+ // The page and metadata writes above are already durable. Do not turn an
+ // auxiliary downgrade-window failure into a false append failure.
+ console.warn(
+ `[chatStore] Failed to refresh downgrade snapshot for ${chatId}; retrying on read`,
+ error
+ )
+ }
}
this.cleanedSnapshotSiblingKeys.add(cacheKey)
- this.compatibilityCheckedKeys.add(cacheKey)
+ if (compatibilityCurrent) {
+ this.compatibilityCheckedKeys.add(cacheKey)
+ } else {
+ this.compatibilityCheckedKeys.delete(cacheKey)
+ }
return pruned.meta
}
async getIndex(agentRef: string): Promise<ChatIndex> {
+ let raw: string
+ try {
+ raw = await fs.readFile(this.indexPath(agentRef), 'utf-8')
+ } catch (error) {
+ if (isNotFoundError(error)) return emptyIndex()
+ throw error
+ }
try {
- const raw = await fs.readFile(this.indexPath(agentRef), 'utf-8')
const parsed = JSON.parse(raw) as ChatIndex
// Version-agnostic read: legacy directories are handled at bind time by
// chatStoreBinding. saveIndex normalizes v3 indexes produced by earlier
@@ -1262,6 +1302,9 @@ export class ChatStore {
}
return emptyIndex()
} catch {
+ // A malformed catalog can be rebuilt from the server and the transcript
+ // files. Raw filesystem failures above must propagate so a later RMW
+ // cannot overwrite a temporarily unreadable live index with an empty one.
return emptyIndex()
}
}
@@ -1277,8 +1320,13 @@ export class ChatStore {
// 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 })
- await fs.rename(tmp, target)
+ 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
+ }
}
async listChats(agentRef: string): Promise<ChatMetadata[]> {
@@ -1507,7 +1555,7 @@ export class ChatStore {
const chat = index.chats.find(c => c.id === chatId)
if (chat) {
const delta = aggregateMessages(newMessages)
- chat.messageCount = meta.messageCount
+ chat.messageCount = (chat.messageCount ?? 0) + visibleMessageCount(newMessages)
chat.errorCount = (chat.errorCount ?? 0) + (delta.errorCount ?? 0)
chat.toolCallCount = (chat.toolCallCount ?? 0) + (delta.toolCallCount ?? 0)
chat.updatedAt = new Date().toISOString()
diff --git a/desktop-app/src/chatStoreBinding.ts b/desktop-app/src/chatStoreBinding.ts
index 6e4e3c016..1540c14bb 100644
--- a/desktop-app/src/chatStoreBinding.ts
+++ b/desktop-app/src/chatStoreBinding.ts
@@ -2,6 +2,7 @@ import { app } from 'electron'
import { promises as fs } from 'node:fs'
import { join } from 'node:path'
import { ChatStore } from './chatStore.js'
+import { assertSafeFilesystemSegment } from './pathSafety.js'
/**
* Keep the shared catalog at v2 so pre-paging desktop builds can read the
@@ -36,12 +37,6 @@ const PRE_ENV_MIGRATION_MARKER = '.env-scoped'
* empty/`.`/`..`/separator-bearing value could make the wipe escape its subdir
* or target the whole base dir.
*/
-function assertSafeSegment(label: string, value: string): void {
- if (!value || value === '.' || value === '..' || /[/\\\0]/.test(value)) {
- throw new Error(`Invalid ${label}: unsafe path segment`)
- }
-}
-
/**
* Bind the chat store to a `(envKey, user)` directory (spec §5.2). The path is
* namespaced by environment — `<base>/<envKey>/<userId>/…` — so switching
@@ -55,10 +50,10 @@ export async function bindChatStoreForUser(
envKey: string,
options: { legacyEnvKeys?: readonly string[] } = {}
): Promise<void> {
- assertSafeSegment('userId', userId)
- assertSafeSegment('envKey', envKey)
+ assertSafeFilesystemSegment('userId', userId)
+ assertSafeFilesystemSegment('envKey', envKey)
for (const legacyEnvKey of options.legacyEnvKeys ?? []) {
- assertSafeSegment('legacyEnvKey', legacyEnvKey)
+ assertSafeFilesystemSegment('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
@@ -81,6 +76,9 @@ export async function bindChatStoreForUser(
await maybeWipePreEnvLegacyCache(baseDir)
await maybeMigrateEnvScopedCache(baseDir, userId, envKey, options.legacyEnvKeys ?? [])
const userDir = join(baseDir, envKey, userId)
+ await ensurePrivateDirectory(baseDir)
+ await ensurePrivateDirectory(join(baseDir, envKey))
+ await ensurePrivateDirectory(userDir)
await maybeWipeLegacyCache(userDir)
await sweepExpiredCorruptQuarantines(userDir)
if (generation !== bindingGeneration) return
@@ -96,6 +94,13 @@ export async function bindChatStoreForUser(
}
}
+async function ensurePrivateDirectory(directoryPath: string): Promise<void> {
+ await fs.mkdir(directoryPath, { recursive: true, mode: 0o700 })
+ // mkdir's mode does not update an existing directory. Tighten legacy
+ // permissions at the three ancestry boundaries that protect the full cache.
+ await fs.chmod(directoryPath, 0o700)
+}
+
/**
* 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
@@ -259,7 +264,13 @@ async function maybeWipeLegacyCache(userDir: string): Promise<void> {
} else {
isLegacy = parsed.version !== SCHEMA_VERSION
}
- } catch {
+ } catch (error) {
+ const code = (error as NodeJS.ErrnoException | undefined)?.code
+ if (code !== undefined && code !== 'ENOENT') {
+ // A transient permission/I/O failure is not evidence of an old schema.
+ // Propagate it instead of recursively deleting a live agent cache.
+ throw error
+ }
// index.json missing or unparseable → treat as legacy
isLegacy = true
}
diff --git a/desktop-app/src/ipc.ts b/desktop-app/src/ipc.ts
index 8f09897fe..6a36a46e2 100644
--- a/desktop-app/src/ipc.ts
+++ b/desktop-app/src/ipc.ts
@@ -31,9 +31,28 @@ function sanitizeSubjectKeys(input: unknown): string[] {
function sanitizeOptionalInteger(input: unknown): number | undefined {
if (input === undefined || input === null || input === '') return undefined
- const value = Number(input)
- if (!Number.isInteger(value)) throw new Error('Invalid integer')
- return value
+ if (typeof input !== 'number' || !Number.isSafeInteger(input)) {
+ throw new Error('Invalid integer')
+ }
+ return input
+}
+
+export function sanitizeChatLoadWindow(
+ limitInput: unknown,
+ offsetInput: unknown
+): { limit?: number; offset?: number } {
+ const limit = sanitizeOptionalInteger(limitInput)
+ const offset = sanitizeOptionalInteger(offsetInput)
+ if (limit !== undefined && (limit < 1 || limit > 1000)) {
+ throw new Error('Invalid chat message limit')
+ }
+ if (offset !== undefined && offset < 0) {
+ throw new Error('Invalid chat message offset')
+ }
+ return {
+ ...(limit !== undefined ? { limit } : {}),
+ ...(offset !== undefined ? { offset } : {}),
+ }
}
function sanitizeSessionsListQuery(
@@ -1105,7 +1124,8 @@ export function registerIpcHandlers(service: AppService): void {
const agentRef = sanitizeString(payload?.agentRef)
const chatId = sanitizeString(payload?.chatId)
if (!agentRef || !chatId) throw new Error('agentRef and chatId are required')
- return requireChatStore().loadMessages(agentRef, chatId, payload?.limit, payload?.offset)
+ const { limit, offset } = sanitizeChatLoadWindow(payload?.limit, payload?.offset)
+ return requireChatStore().loadMessages(agentRef, chatId, limit, offset)
}
)
diff --git a/desktop-app/src/pathSafety.ts b/desktop-app/src/pathSafety.ts
new file mode 100644
index 000000000..086cc3cd7
--- /dev/null
+++ b/desktop-app/src/pathSafety.ts
@@ -0,0 +1,55 @@
+const ROUTE_CONTROL_OR_SEPARATOR = /[/\\\u0000-\u001f\u007f]/
+const WINDOWS_INVALID_FILENAME_CHARACTER = /[<>:"|?*]/
+const WINDOWS_RESERVED_FILENAME = /^(?:con|prn|aux|nul|com[1-9]|lpt[1-9])(?:\.|$)/i
+
+export interface SafeRouteSegmentOptions {
+ maxLength?: number
+ allowColon?: boolean
+}
+
+/**
+ * Keep desktop-side route validation aligned with rpc-proxy and mcp-host.
+ * Encoding a segment is not sufficient: control characters still create
+ * ambiguous logs and overlong values are rejected by the upstream services.
+ */
+export function assertSafeRouteSegment(
+ label: string,
+ value: string,
+ options: SafeRouteSegmentOptions = {}
+): void {
+ const maxLength = options.maxLength ?? 500
+ if (
+ !value ||
+ value === '.' ||
+ value === '..' ||
+ value.length > maxLength ||
+ ROUTE_CONTROL_OR_SEPARATOR.test(value) ||
+ (options.allowColon === false && value.includes(':'))
+ ) {
+ throw new Error(`Invalid ${label}: unsafe path segment`)
+ }
+}
+
+/**
+ * Validate a value before using it as a directory or file-name component.
+ * These rules intentionally use the Windows-compatible subset so a cache made
+ * on one platform remains portable and cannot alias device names or trimmed
+ * trailing characters on another.
+ */
+export function assertSafeFilesystemSegment(
+ label: string,
+ value: string,
+ options: { reservedNames?: readonly string[] } = {}
+): void {
+ assertSafeRouteSegment(label, value, { maxLength: 200, allowColon: false })
+ const normalized = value.toLowerCase()
+ if (
+ value.startsWith('.') ||
+ /[ .]$/.test(value) ||
+ WINDOWS_INVALID_FILENAME_CHARACTER.test(value) ||
+ WINDOWS_RESERVED_FILENAME.test(value) ||
+ options.reservedNames?.some(name => normalized === name.toLowerCase())
+ ) {
+ throw new Error(`Invalid ${label}: unsafe path segment`)
+ }
+}
diff --git a/desktop-app/src/rpcProxyClient.ts b/desktop-app/src/rpcProxyClient.ts
index 09b267213..eab89804f 100644
--- a/desktop-app/src/rpcProxyClient.ts
+++ b/desktop-app/src/rpcProxyClient.ts
@@ -1,5 +1,6 @@
import { config } from './config.js'
import { ApiError, requestJson, withTimeout } from './httpClient.js'
+import { assertSafeRouteSegment } from './pathSafety.js'
import {
ApprovalDecisionResult,
ContextBreakdownResult,
@@ -29,12 +30,6 @@ 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
@@ -556,7 +551,7 @@ export class RpcProxyClient {
hostRef: string,
query: SessionsListQuery = {}
): Promise<SessionsListResult> {
- assertSafePathSegment('hostRef', hostRef)
+ assertSafeRouteSegment('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))
@@ -583,9 +578,9 @@ export class RpcProxyClient {
chatId: string,
query: SessionMessagesQuery = {}
): Promise<SessionMessagesResult> {
- assertSafePathSegment('hostRef', hostRef)
- assertSafePathSegment('agent', agent)
- assertSafePathSegment('chatId', chatId)
+ assertSafeRouteSegment('hostRef', hostRef)
+ assertSafeRouteSegment('agent', agent, { maxLength: 200, allowColon: false })
+ assertSafeRouteSegment('chatId', chatId)
const requestUrl = new URL(
url(
`/api/v1/rpc/hosts/${encodeURIComponent(hostRef)}/sessions/${encodeURIComponent(agent)}/${encodeURIComponent(chatId)}/messages`
@@ -636,9 +631,9 @@ export class RpcProxyClient {
agent: string,
chatId: string
): Promise<ContextBreakdownResult> {
- assertSafePathSegment('hostRef', hostRef)
- assertSafePathSegment('agent', agent)
- assertSafePathSegment('chatId', chatId)
+ assertSafeRouteSegment('hostRef', hostRef)
+ assertSafeRouteSegment('agent', agent, { maxLength: 200, allowColon: false })
+ assertSafeRouteSegment('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/tokenStore.ts b/desktop-app/src/tokenStore.ts
index 7a880717d..10e921b3c 100644
--- a/desktop-app/src/tokenStore.ts
+++ b/desktop-app/src/tokenStore.ts
@@ -15,7 +15,7 @@ const LEGACY_ACCOUNT = 'session-token'
* `-` separator, and a 12-hex sha256 suffix. Every call site feeds `envKey`
* straight into keychain account names and on-disk file names, so validate the
* shape before interpolating — defense in depth mirroring the
- * `assertSafeSegment` guard in chatStore/chatStoreBinding. Today all callers
+ * `assertSafeFilesystemSegment` guard in chatStore/chatStoreBinding. Today all callers
* pass sanitized `getActiveEnvKey()` output, so a mismatch signals a bug (or a
* tampered value), never a normal input.
*/
diff --git a/desktop-app/test/ipc.test.ts b/desktop-app/test/ipc.test.ts
index 24f516e82..7b7cc6411 100644
--- a/desktop-app/test/ipc.test.ts
+++ b/desktop-app/test/ipc.test.ts
@@ -1,7 +1,7 @@
import { beforeEach, describe, expect, it, vi } from 'vitest'
import { promises as fs } from 'node:fs'
import path from 'node:path'
-import { registerIpcHandlers } from '../src/ipc.js'
+import { registerIpcHandlers, sanitizeChatLoadWindow } from '../src/ipc.js'
import type { HostStatusStreamEvent } from '../src/types.js'
const testState = vi.hoisted(() => {
@@ -39,6 +39,24 @@ function makeTrustedEvent(senderId = 77) {
}
}
+describe('chat IPC pagination validation', () => {
+ it('accepts bounded safe-integer windows', () => {
+ expect(sanitizeChatLoadWindow(100, 200)).toEqual({ limit: 100, offset: 200 })
+ expect(sanitizeChatLoadWindow(undefined, undefined)).toEqual({})
+ })
+
+ it.each([
+ ['10', 0],
+ [1.5, 0],
+ [0, 0],
+ [1001, 0],
+ [10, -1],
+ [Number.MAX_SAFE_INTEGER + 1, 0],
+ ])('rejects an invalid limit/offset pair: %s, %s', (limit, offset) => {
+ expect(() => sanitizeChatLoadWindow(limit, offset)).toThrow()
+ })
+})
+
describe('ipc host status stream handlers', () => {
const service = {
getSessionState: vi.fn(),
diff --git a/desktop-app/ui/src/hooks/__tests__/useChatStore.test.tsx b/desktop-app/ui/src/hooks/__tests__/useChatStore.test.tsx
index 0b00366c5..2a4493a9e 100644
--- a/desktop-app/ui/src/hooks/__tests__/useChatStore.test.tsx
+++ b/desktop-app/ui/src/hooks/__tests__/useChatStore.test.tsx
@@ -71,4 +71,20 @@ describe('useChatStore remote request cache', () => {
expect(setHostModel).toHaveBeenCalledTimes(1)
expect(getHostModels).toHaveBeenCalledTimes(2)
})
+
+ it('does not carry pending model selections across an identity scope change', () => {
+ Object.defineProperty(window, 'clerum', {
+ configurable: true,
+ value: { rpc: {} },
+ })
+ const { result } = renderHook(() => useChatStore())
+ result.current.setRemoteCacheScope('authenticated:user-a:team-a')
+ result.current.setPendingModel('agent', 'chat', 'model-a')
+ result.current.setPreChatModel('agent', 'model-b')
+
+ result.current.setRemoteCacheScope('authenticated:user-b:team-b')
+
+ expect(result.current.getPendingModel('agent', 'chat')).toBeUndefined()
+ expect(result.current.getPreChatModel('agent')).toBeUndefined()
+ })
})
diff --git a/desktop-app/ui/src/hooks/domain/__tests__/reconcileChat.test.ts b/desktop-app/ui/src/hooks/domain/__tests__/reconcileChat.test.ts
index 51c1625dd..feade5b0b 100644
--- a/desktop-app/ui/src/hooks/domain/__tests__/reconcileChat.test.ts
+++ b/desktop-app/ui/src/hooks/domain/__tests__/reconcileChat.test.ts
@@ -162,12 +162,68 @@ describe('reconcileChat — single-flight', () => {
const p = reconcile(chatKey, { reason: 'stream_lost' })
expect(reconcile.isInFlight(chatKey)).toBe(true)
reconcile.reset() // logout / team-switch mid-fetch
+ deps.fsm.reset()
expect(reconcile.isInFlight(chatKey)).toBe(false) // coalescing map cleared
resolveLoad(liveResp()) // fetch resolves AFTER the reset
await p
// The run bailed at the post-fetch relevance check → no attach/settle ran.
expect(deps.attachLiveTask).not.toHaveBeenCalled()
expect(deps.settleIdle).not.toHaveBeenCalled()
+ expect(deps.fsm.getState(chatKey)).toBeUndefined()
+ })
+
+ it('an old post-reset completion does not clear a newer reconcile for the same chat', async () => {
+ let resolveOld: (value: SessionMessagesResult) => void = () => {}
+ let resolveNew: (value: SessionMessagesResult) => void = () => {}
+ const load = vi
+ .fn<() => Promise<SessionMessagesResult>>()
+ .mockImplementationOnce(
+ () => new Promise<SessionMessagesResult>(resolve => (resolveOld = resolve))
+ )
+ .mockImplementationOnce(
+ () => new Promise<SessionMessagesResult>(resolve => (resolveNew = resolve))
+ )
+ const deps = buildDeps({
+ loadSessionMessages: load as unknown as ReconcileChatDeps['loadSessionMessages'],
+ })
+ const reconcile = createReconcileChat(deps)
+ const oldRun = reconcile(chatKey, { reason: 'old-session' })
+ reconcile.reset()
+ deps.fsm.reset()
+ const newRun = reconcile(chatKey, { reason: 'new-session' })
+
+ resolveOld(idleResp())
+ await oldRun
+ expect(reconcile.isInFlight(chatKey)).toBe(true)
+
+ resolveNew(idleResp())
+ await newRun
+ expect(reconcile.isInFlight(chatKey)).toBe(false)
+ })
+
+ it('drops a late 404 after reset instead of evicting the next session cache', async () => {
+ let rejectLoad: (reason: unknown) => void = () => {}
+ const load = vi.fn(
+ (_agentRef: string, _chatId: string, _query: unknown, stillRelevant?: () => boolean) => {
+ expect(stillRelevant).toEqual(expect.any(Function))
+ return new Promise<SessionMessagesResult>((_resolve, reject) => {
+ rejectLoad = reject
+ })
+ }
+ )
+ const deps = buildDeps({
+ loadSessionMessages: load as ReconcileChatDeps['loadSessionMessages'],
+ })
+ const reconcile = createReconcileChat(deps)
+ const pending = reconcile(chatKey, { reason: 'old-session' })
+
+ reconcile.reset()
+ deps.fsm.reset()
+ rejectLoad(new NotFound('late response'))
+
+ await expect(pending).resolves.toBe('noop')
+ expect(deps.evictChat).not.toHaveBeenCalled()
+ expect(deps.fsm.getState(chatKey)).toBeUndefined()
})
it('a coalesced caller donates its taskIdHint to a hint-less in-flight run (M6)', async () => {
diff --git a/desktop-app/ui/src/hooks/domain/reconcileChat.ts b/desktop-app/ui/src/hooks/domain/reconcileChat.ts
index 57fa7ab90..96a6e2048 100644
--- a/desktop-app/ui/src/hooks/domain/reconcileChat.ts
+++ b/desktop-app/ui/src/hooks/domain/reconcileChat.ts
@@ -41,8 +41,9 @@ export interface ReconcileChatDeps {
loadSessionMessages: (
agentRef: string,
chatId: string,
- query?: SessionMessagesQuery
- ) => Promise<SessionMessagesResult>
+ query?: SessionMessagesQuery,
+ stillRelevant?: () => boolean
+ ) => Promise<SessionMessagesResult | undefined>
/**
* Server reports a live (`processing`/`awaiting_approval`) task: seed the
* snapshot and attach a stream via the coordinator. Returns the outcome
@@ -159,8 +160,9 @@ export function createReconcileChat(deps: ReconcileChatDeps): ReconcileChat {
for (let attempt = 0; attempt < attempts; attempt++) {
if (!stillRelevant()) return undefined
try {
- return await deps.loadSessionMessages(agentRef, chatId, query)
+ return await deps.loadSessionMessages(agentRef, chatId, query, stillRelevant)
} catch (err) {
+ if (!stillRelevant()) return undefined
// Non-network (404, etc.) rethrows to the branch handler; a network blip
// is retried with backoff up to the cap (mirrors switchToChat P2-A).
if (!deps.isNetworkError(err) || attempt === attempts - 1) throw err
@@ -209,6 +211,10 @@ export function createReconcileChat(deps: ReconcileChatDeps): ReconcileChat {
)
return outcome
} catch (err) {
+ if (!stillRelevant()) {
+ outcome = 'stale_drop'
+ return outcome
+ }
if (deps.isHttp404(err)) {
await deps.evictChat(chatKey)
deps.fsm.dispatch(chatKey, { type: 'RESET' })
@@ -230,7 +236,9 @@ export function createReconcileChat(deps: ReconcileChatDeps): ReconcileChat {
} finally {
// RESET already tore the entry down on 404; re-dispatching FINISHED would
// resurrect an empty entry, so skip the finalizer in that case.
- if (outcome !== '404') deps.fsm.dispatch(chatKey, { type: 'RECONCILE_FINISHED' })
+ if (outcome !== '404' && generation === startGeneration) {
+ deps.fsm.dispatch(chatKey, { type: 'RECONCILE_FINISHED' })
+ }
deps.telemetry('stream_recovery', { reason: args.reason, outcome })
}
}
@@ -249,8 +257,12 @@ export function createReconcileChat(deps: ReconcileChatDeps): ReconcileChat {
}
inFlightHint.set(chatKey, args.taskIdHint)
const promise = run(chatKey, args).finally(() => {
- inFlight.delete(chatKey)
- inFlightHint.delete(chatKey)
+ // reset() permits a fresh reconcile for the same key while this older
+ // promise is still settling. Only clear the entry we actually own.
+ if (inFlight.get(chatKey) === promise) {
+ inFlight.delete(chatKey)
+ inFlightHint.delete(chatKey)
+ }
})
inFlight.set(chatKey, promise)
return promise
diff --git a/desktop-app/ui/src/hooks/domain/useAgentChatController.ts b/desktop-app/ui/src/hooks/domain/useAgentChatController.ts
index c7adb2c1f..7a05f2494 100644
--- a/desktop-app/ui/src/hooks/domain/useAgentChatController.ts
+++ b/desktop-app/ui/src/hooks/domain/useAgentChatController.ts
@@ -1354,6 +1354,7 @@ export function useAgentChatController({
if (chatId) {
try {
await chatStore.appendMessages(agentName, chatId, [message])
+ bumpActivity(agentName, chatId, new Date(message.timestamp).toISOString())
} catch {
// persistence is best-effort; the in-memory view already updated
}
@@ -1367,7 +1368,7 @@ export function useAgentChatController({
// notification delivery is best-effort
}
},
- [chatStore, pushAssistantReplyNotification]
+ [bumpActivity, chatStore, pushAssistantReplyNotification]
)
// ─── reconcileChat branch callbacks (§4.3) ───
@@ -1674,7 +1675,7 @@ export function useAgentChatController({
useEffect(() => {
reconcileBranchesRef.current = {
- loadSessionMessages: async (agentRef, chatId, query) => {
+ loadSessionMessages: async (agentRef, chatId, query, stillRelevant = () => true) => {
let requestedQuery = query ?? { limit: SERVER_TURN_PAGE_SIZE }
if (requestedQuery.beforeTurn === undefined && requestedQuery.afterTurn === undefined) {
const cached = (await chatStore
@@ -1699,6 +1700,7 @@ export function useAgentChatController({
chatId,
requestedQuery
)
+ if (!stillRelevant()) return undefined
if (requestedQuery.afterTurn === undefined || !response.hasMoreAfter) {
if (requestedQuery.afterTurn !== undefined) {
return {
@@ -1723,6 +1725,7 @@ export function useAgentChatController({
}
let pagesLoaded = 1
while (
+ stillRelevant() &&
response.hasMoreAfter &&
cursor !== undefined &&
!seenCursors.has(cursor) &&
@@ -1734,6 +1737,7 @@ export function useAgentChatController({
limit: requestedQuery.limit ?? SERVER_TURN_PAGE_SIZE,
afterTurn: cursor,
})
+ if (!stillRelevant()) return undefined
turns.push(...response.turns)
cursor = response.latestTurnNumber ?? response.turns.at(-1)?.number
pagesLoaded += 1
@@ -1750,10 +1754,12 @@ export function useAgentChatController({
}
}
}
+ if (!stillRelevant()) return undefined
if (response.hasMoreAfter) {
const latest = await chatStore.loadSessionMessages(agentRef, agentRef, chatId, {
limit: requestedQuery.limit ?? SERVER_TURN_PAGE_SIZE,
})
+ if (!stillRelevant()) return undefined
const combinedTurns = mergeUniqueSessionTurns(turns, latest.turns)
return {
...latest,
diff --git a/desktop-app/ui/src/hooks/useChatStore.ts b/desktop-app/ui/src/hooks/useChatStore.ts
index 9c81ecb90..cd2aa91a0 100644
--- a/desktop-app/ui/src/hooks/useChatStore.ts
+++ b/desktop-app/ui/src/hooks/useChatStore.ts
@@ -232,6 +232,11 @@ export function useChatStore() {
remoteCacheScope = scope
sessionCatalogRequests.clear()
hostModelRequests.clear()
+ // Pending selections are session-owned even though they are not remote
+ // responses. Never carry an unpersisted model choice across logout, user,
+ // or team boundaries where the same agent/chat identifiers may reappear.
+ for (const key of Object.keys(pendingModelByChat)) delete pendingModelByChat[key]
+ for (const key of Object.keys(preChatModelByAgent)) delete preChatModelByAgent[key]
}, [])
// --- Pending (unpersisted) model selections — R2 "Option A" (see the
diff --git a/desktop-app/ui/src/pages/AuthPage/index.tsx b/desktop-app/ui/src/pages/AuthPage/index.tsx
index a55f105e4..4810036c6 100644
--- a/desktop-app/ui/src/pages/AuthPage/index.tsx
+++ b/desktop-app/ui/src/pages/AuthPage/index.tsx
@@ -3,7 +3,10 @@ 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 { createLocalhostRuntimeConfigOption } from '@constants/runtimeConfig'
+import {
+ LOCALHOST_RUNTIME_CONFIG_OPTION_ID,
+ createLocalhostRuntimeConfigOption,
+} from '@constants/runtimeConfig'
import { formatDesktopAppVersionTooltip, useDesktopAppInfo } from '@hooks/useDesktopAppInfo'
import type { DesktopRuntimeConfigOption } from '../../../../src/types'
@@ -33,6 +36,9 @@ 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 =
@@ -95,11 +101,12 @@ export function AuthPage() {
const handleRuntimeOptionSelect = (optionId: string) => {
setRuntimeMenuOpen(false)
- if (optionId === activeRuntimeConfigId) {
- const selectedOption = runtimeConfigOptions.find(option => option.id === optionId)
- if (selectedOption?.source === 'localhost') {
- handleClearRuntimeConfigSelection()
- }
+ if (
+ optionId === activeRuntimeConfigId &&
+ (selectedRuntimeConfig?.source === 'localhost' ||
+ optionId === LOCALHOST_RUNTIME_CONFIG_OPTION_ID)
+ ) {
+ handleClearRuntimeConfigSelection()
return
}
handleSelectRuntimeConfig(optionId)
diff --git a/desktop-app/ui/src/pages/__tests__/AuthPage.test.tsx b/desktop-app/ui/src/pages/__tests__/AuthPage.test.tsx
index 3f00d4553..643781d9f 100644
--- a/desktop-app/ui/src/pages/__tests__/AuthPage.test.tsx
+++ b/desktop-app/ui/src/pages/__tests__/AuthPage.test.tsx
@@ -157,76 +157,4 @@ 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()
- })
})