Skip to content

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

TypeScript

fix(desktop): R1-H1 fail closed on invalid chat indexes

Josuéb3a5cce554ff
diff --git a/desktop-app/src/__tests__/chatStore.test.ts b/desktop-app/src/__tests__/chatStore.test.ts
index 177b6d141..c323e6094 100644
--- a/desktop-app/src/__tests__/chatStore.test.ts
+++ b/desktop-app/src/__tests__/chatStore.test.ts
@@ -1432,13 +1432,71 @@ describe('onboarding', () => {
// ── corrupt/missing files ────────────────────────────────────────────────────
describe('corrupt/missing files', () => {
- it('recovers from corrupt index.json', async () => {
+ it('fails closed and preserves a corrupt index during later mutations', async () => {
const agentDir = join(tempDir, 'agent-1')
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) // v2 remains readable by pre-paging desktop builds
- expect(index.chats).toEqual([])
+ const indexPath = join(agentDir, 'index.json')
+ const corrupt = 'NOT VALID JSON{{{'
+ await fs.writeFile(indexPath, corrupt)
+
+ await expect(store.getIndex('agent-1')).rejects.toThrow(/Unable to read chat index/)
+ await expect(store.createChat('agent-1', 'new-chat')).rejects.toThrow(
+ /Unable to read chat index/
+ )
+ expect(await fs.readFile(indexPath, 'utf8')).toBe(corrupt)
+ })
+
+ it('keeps a v3 index readable but refuses to normalize it during ordinary RMW', async () => {
+ const agentDir = join(tempDir, 'agent-1')
+ await fs.mkdir(agentDir, { recursive: true })
+ const indexPath = join(agentDir, 'index.json')
+ const future = JSON.stringify({
+ version: 3,
+ lastActiveChatId: 'kept',
+ onboardingDismissed: false,
+ chats: [
+ {
+ id: 'kept',
+ title: 'Keep',
+ createdAt: '2026-01-01T00:00:00.000Z',
+ updatedAt: '2026-01-01T00:00:00.000Z',
+ messageCount: 1,
+ },
+ ],
+ })
+ await fs.writeFile(indexPath, future)
+
+ expect((await store.getIndex('agent-1')).chats[0]?.id).toBe('kept')
+ await expect(store.renameChat('agent-1', 'kept', 'Changed')).rejects.toThrow(
+ /unsupported chat index version 3/
+ )
+ expect(await fs.readFile(indexPath, 'utf8')).toBe(future)
+ })
+
+ it('rejects structurally invalid index counters before an RMW can normalize them', async () => {
+ const agentDir = join(tempDir, 'agent-1')
+ await fs.mkdir(agentDir, { recursive: true })
+ const indexPath = join(agentDir, 'index.json')
+ const invalid = JSON.stringify({
+ version: 2,
+ lastActiveChatId: 'kept',
+ onboardingDismissed: false,
+ chats: [
+ {
+ id: 'kept',
+ title: 'Keep',
+ createdAt: '2026-01-01T00:00:00.000Z',
+ updatedAt: '2026-01-01T00:00:00.000Z',
+ messageCount: 1e309,
+ },
+ ],
+ })
+ await fs.writeFile(indexPath, invalid)
+
+ await expect(store.renameChat('agent-1', 'kept', 'Changed')).rejects.toThrow(
+ /Unable to read chat index/
+ )
+ expect(await fs.readFile(indexPath, 'utf8')).toBe(invalid)
})
it('does not overwrite an index after a transient read failure', async () => {
diff --git a/desktop-app/src/chatStore.ts b/desktop-app/src/chatStore.ts
index fa427b36a..6a5cb26c5 100644
--- a/desktop-app/src/chatStore.ts
+++ b/desktop-app/src/chatStore.ts
@@ -60,6 +60,10 @@ interface SnapshotCandidate {
mtimeMs: number
}
+function isNonNegativeSafeInteger(value: unknown): value is number {
+ return typeof value === 'number' && Number.isSafeInteger(value) && value >= 0
+}
+
function normalizePositiveInteger(value: number | undefined, fallback: number): number {
if (value === undefined) return fallback
if (!Number.isFinite(value)) return fallback
@@ -130,6 +134,40 @@ function pageEntry(file: string, messages: ChatMessage[]): ChatPageEntry {
}
}
+function parseChatIndex(raw: string): ChatIndex {
+ const parsed = JSON.parse(raw) as unknown
+ if (!parsed || typeof parsed !== 'object') {
+ throw new Error('Invalid chat index')
+ }
+ const candidate = parsed as Record<string, unknown>
+ if (
+ (candidate.version !== 2 && candidate.version !== 3) ||
+ (candidate.lastActiveChatId !== null && typeof candidate.lastActiveChatId !== 'string') ||
+ typeof candidate.onboardingDismissed !== 'boolean' ||
+ !Array.isArray(candidate.chats)
+ ) {
+ throw new Error('Invalid chat index')
+ }
+ for (const chat of candidate.chats) {
+ if (!chat || typeof chat !== 'object') throw new Error('Invalid chat index entry')
+ const metadata = chat as Record<string, unknown>
+ if (
+ typeof metadata.id !== 'string' ||
+ typeof metadata.title !== 'string' ||
+ typeof metadata.createdAt !== 'string' ||
+ typeof metadata.updatedAt !== 'string' ||
+ !isNonNegativeSafeInteger(metadata.messageCount) ||
+ (metadata.errorCount !== undefined && !isNonNegativeSafeInteger(metadata.errorCount)) ||
+ (metadata.toolCallCount !== undefined && !isNonNegativeSafeInteger(metadata.toolCallCount)) ||
+ (metadata.unreadTerminal !== undefined && typeof metadata.unreadTerminal !== 'boolean') ||
+ (metadata.lastTerminalAt !== undefined && typeof metadata.lastTerminalAt !== 'string')
+ ) {
+ throw new Error('Invalid chat index entry')
+ }
+ }
+ return candidate as unknown as ChatIndex
+}
+
/**
* Reject any path-component (agentRef / chatId) that could escape the store
* root via `path.join`. agentRefs are slugs and chatIds are UUIDs in practice,
@@ -1363,23 +1401,20 @@ export class ChatStore {
throw error
}
try {
- 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
- // paging builds back to the v2 downgrade-compatible catalog schema.
- if (parsed && Array.isArray(parsed.chats)) {
- return parsed
- }
- 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()
+ return parseChatIndex(raw)
+ } catch (error) {
+ // Bind-time migration deliberately preserves malformed and future catalogs
+ // because their paged transcripts may contain local-only work. Fail closed:
+ // treating those bytes as an empty writable index would let the next RMW
+ // silently orphan the preserved chats.
+ throw new Error(`Unable to read chat index for ${agentRef}`, { cause: error })
}
}
private async saveIndex(agentRef: string, index: ChatIndex): Promise<void> {
+ if (index.version !== INDEX_VERSION) {
+ throw new Error(`Refusing to overwrite unsupported chat index version ${index.version}`)
+ }
const dir = this.agentDir(agentRef)
await fs.mkdir(dir, { recursive: true, mode: 0o700 })
// Keep the index readable by the pre-paging desktop while the transcript