Node-based terminal manager for AI coding agents — tmux-backed terminals and parallel agent sessions as draggable nodes on an infinite pan/zoom canvas. macOS, Linux, and a browser Server Edition.
TypeScript adhdagent-orchestrationai-agentscanvasclaude-codecodexcoding-agentsdeveloper-toolselectrongeminilinuxmacosmultiplexeropencodeparallel-agentsterminalterminal-emulatorterminal-multiplexertmuxworkspace-manager
test(transcript-index): pin the dirty flag and the one-refresh-at-a-time rule
reviewe107511823d0
diff --git a/src/core/transcript-index.test.ts b/src/core/transcript-index.test.tsindex a9705e0e6..813b6da13 100644--- a/src/core/transcript-index.test.ts+++ b/src/core/transcript-index.test.ts@@ -1,11 +1,13 @@-// Persistence of the transcript index (audit #7). Only the path-explicit helpers are exercised:-// `initTranscriptIndex` walks the real ~/.claude/projects, which a unit test must never read.+// Persistence of the transcript index. The path-explicit helpers are exercised directly; the+// refresh loop runs against a LINKED account's config dir in a temp dir. Its other root,+// `~/.claude/projects`, is the run's private home (test/setup/home-sandbox.ts), never the real one.import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'import { promises as fs } from 'fs'import { mkdtemp, readFile, rm, stat, writeFile } from 'fs/promises'import { tmpdir } from 'os'import { join } from 'path'+import { fakePlatform } from './platform-fake'import { loadPersistedIndex, persistIndex } from './transcript-index'import type { TranscriptIndexEntry } from './transcript-index-core'@@ -81,3 +83,94 @@ describe('loadPersistedIndex', () => {expect(loadPersistedIndex(file)).toEqual([])})})++describe('the refresh loop', () => {+ const SID = '0123abcd-0000-4000-8000-00000000000a'+ let cfg: string+ let indexFile: string+ let mod: typeof import('./transcript-index')+ let core: typeof import('./platform')++ /** Writes of the index file's temp: one per persist attempt, landed or not. */+ let indexWrites: string[]+ beforeEach(async () => {+ vi.resetModules() // fresh module state: entries, dirty, the in-flight refresh+ vi.useFakeTimers({ toFake: ['setInterval', 'clearInterval'] }) // the 5-minute timer stays inert+ const platform = fakePlatform()+ core = await import('./platform') // the instance the freshly imported index module will read+ core.initPlatform(platform)+ indexFile = join(platform.userDataDir, 'transcript-index.json')+ cfg = join(dir, 'claude-cfg')+ await fs.mkdir(join(cfg, 'projects', '-proj'), { recursive: true })+ await writeFile(join(cfg, 'projects', '-proj', `${SID}.jsonl`), '{"type":"user","cwd":"/c"}\n')+ indexWrites = []+ const realWriteFile = fs.writeFile.bind(fs)+ vi.spyOn(fs, 'writeFile').mockImplementation((async (target: string, ...rest: unknown[]) => {+ if (String(target).includes('transcript-index.json')) indexWrites.push(String(target))+ return (realWriteFile as (...a: unknown[]) => Promise<void>)(target, ...rest)+ }) as unknown as typeof fs.writeFile)+ mod = await import('./transcript-index')+ })+ afterEach(() => {+ vi.useRealTimers()+ core.resetPlatformForTests()+ })+ const accounts = () => [{ id: 'linked1', label: 'L', createdAt: 1, configDir: cfg }]++ it('a refresh that changed nothing does not rewrite the index', async () => {+ mod.initTranscriptIndex(accounts)+ await mod.refreshTranscriptIndex()+ expect(indexWrites).toHaveLength(1)+ const ino = (await stat(indexFile)).ino+ await mod.refreshTranscriptIndex()+ await mod.refreshTranscriptIndex()+ expect(indexWrites).toHaveLength(1)+ expect((await stat(indexFile)).ino).toBe(ino)+ })++ it('a write that failed stays owed and is retried on the next refresh, then not again', async () => {+ let failNext = true+ const realRename = fs.rename.bind(fs)+ vi.spyOn(fs, 'rename').mockImplementation((async (from: string, to: string) => {+ if (failNext && String(to).endsWith('transcript-index.json')) {+ failNext = false+ throw errWithCode('EIO')+ }+ return realRename(from, to)+ }) as unknown as typeof fs.rename)+ mod.initTranscriptIndex(accounts)+ await mod.refreshTranscriptIndex()+ expect(indexWrites).toHaveLength(1)+ expect(loadPersistedIndex(indexFile)).toEqual([])+ // Nothing on disk changed, but the index the file is missing is still owed to it.+ await mod.refreshTranscriptIndex()+ expect(indexWrites).toHaveLength(2)+ expect(loadPersistedIndex(indexFile).map((e) => e.sessionId)).toEqual([SID])+ await mod.refreshTranscriptIndex()+ expect(indexWrites).toHaveLength(2)+ })++ it('a refresh asked for while one is running joins it instead of scanning again', async () => {+ const root = join(cfg, 'projects')+ let release!: () => void+ const gate = new Promise<void>((r) => (release = r))+ const realReaddir = fs.readdir.bind(fs)+ let rootScans = 0+ vi.spyOn(fs, 'readdir').mockImplementation((async (p: string, ...rest: unknown[]) => {+ if (String(p) === root) {+ rootScans+++ await gate+ }+ return (realReaddir as (...a: unknown[]) => Promise<unknown>)(p, ...rest)+ }) as unknown as typeof fs.readdir)+ mod.initTranscriptIndex(accounts) // starts the launch refresh, held at the linked root+ await vi.waitFor(() => expect(rootScans).toBe(1))+ const a = mod.refreshTranscriptIndex()+ const b = mod.refreshTranscriptIndex()+ vi.advanceTimersByTime(5 * 60 * 1000) // the interval firing mid-scan joins it too+ release()+ await Promise.all([a, b])+ expect(rootScans).toBe(1)+ expect(indexWrites).toHaveLength(1)+ })+})diff --git a/src/core/transcript-index.ts b/src/core/transcript-index.tsindex 92ad8fd72..cef0c4bee 100644--- a/src/core/transcript-index.ts+++ b/src/core/transcript-index.ts@@ -154,7 +154,9 @@ export async function persistIndex(// One refresh at a time. A cold scan of a large tree can outlast the interval, and two overlapping// runs would race their persists (and the `dirty` flag) as well as reading every file twice.let refreshing: Promise<void> | undefined-function refresh(): Promise<void> {+/** Rescan and persist if owed — what launch and the 5-minute timer run. A call while a refresh is+ * in flight joins it rather than starting a second scan. */+export function refreshTranscriptIndex(): Promise<void> {refreshing ??= refreshOnce().finally(() => {refreshing = undefined})@@ -198,7 +200,7 @@ export function initTranscriptIndex(getAccounts?: () => ClaudeAccount[]): void {// a crash inside writeFileAtomic is deliberately NOT collected (fs-atomic cannot prove its writer// dead across PID namespaces), so such an orphan stays until removed by hand.void sweepStaleTempFiles(indexFilePath())- void refresh()- timer = setInterval(() => void refresh(), TRANSCRIPT_INDEX_REFRESH_MS)+ void refreshTranscriptIndex()+ timer = setInterval(() => void refreshTranscriptIndex(), TRANSCRIPT_INDEX_REFRESH_MS)if (timer.unref) timer.unref()}