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: stop leaking temp directories into /tmp
review380d6c37c0e6
diff --git a/CONTRIBUTING.md b/CONTRIBUTING.mdindex c328ad85a..42699b2be 100644--- a/CONTRIBUTING.md+++ b/CONTRIBUTING.md@@ -1030,6 +1030,15 @@ tmux without carrying `TMUX_TMPDIR` into it, which is the one way left to escape`src/core/tmux-socket-isolation.guard.test.ts` holds the short allowlist of suites that name aproduction socket on purpose; adding a third is a review conversation, not a checkbox.+**A test removes every temp directory it creates.** Many sessions run `npm test` on one shared+host, and a leaked `mkdtemp` directory costs an inode forever: `/tmp` on that host reached 100%+inode use, about 395,000 of them empty `nodeterm-fake-*` directories from `fakePlatform()`. Those+are now swept by `test/setup/fake-platform-cleanup.ts` once each test file finishes (see+`src/core/platform-fake-dirs.ts`), so use a `fakePlatform()` directory freely inside its file, but+never across files. For your own `mkdtempSync`, record the path and remove it in an `afterEach` or+`afterAll` with `rmSync(dir, { recursive: true, force: true })`; prefer `afterAll` when something+you started (a tail, a backgrounded script) can still be writing into it after the test returns.+**An `infinite` CSS animation is a frame loop, and it runs whether or not anyone is looking.** Arunning animation makes the compositor produce a frame every vsync — 120/s on a ProMotion display —and re-raster the window each time; measured on a 40-terminal canvas, ONE visible pulsing node tookdiff --git a/src/core/agents/hooks/managed-script.test.ts b/src/core/agents/hooks/managed-script.test.tsindex 1b0ff7490..837bb0fb8 100644--- a/src/core/agents/hooks/managed-script.test.ts+++ b/src/core/agents/hooks/managed-script.test.ts@@ -192,8 +192,16 @@ describe('buildManagedScript', () => {/** Runs the generated script with a fake curl, a fake cygpath, and a fake `uname` that decides* which branch of the gate is taken. `uname` rather than an env var on purpose: that is what* the script reads, and it is what keeps working when a caller replaces the environment. */+ // Every run's directory is removed when this block finishes — they used to leak, one per run+ // (see src/core/platform-fake-dirs.ts for what that did to a shared /tmp). Not per test: the+ // script backgrounds its POST, which can still be writing curl.log when spawnSync returns.+ const payloadDirs: string[] = []+ afterAll(() => {+ for (const dir of payloadDirs.splice(0)) rmSync(dir, { recursive: true, force: true })+ })const run = (unameS: string, cygpath: string | null): CurlCall[] => {const dir = mkdtempSync(join(tmpdir(), 'nt-payload-'))+ payloadDirs.push(dir)const bin = join(dir, 'bin')const home = join(dir, 'home')mkdirSync(bin, { recursive: true })diff --git a/src/core/canvas-sync.test.ts b/src/core/canvas-sync.test.tsindex 7da931db1..e49fafa46 100644--- a/src/core/canvas-sync.test.ts+++ b/src/core/canvas-sync.test.ts@@ -1,5 +1,5 @@import { describe, it, expect, beforeEach, afterEach } from 'vitest'-import { mkdtempSync } from 'fs'+import { mkdtempSync, rmSync } from 'fs'import os from 'os'import path from 'path'import { initPlatform, resetPlatformForTests, type CorePlatform } from './platform'@@ -68,7 +68,12 @@ beforeEach(() => {initPlatform(t.p)initCanvasSync()})-afterEach(() => resetPlatformForTests())+afterEach(() => {+ resetPlatformForTests()+ // Every test mints a fresh mkdtemp dir above; nothing removed them, so each run leaked one per+ // test into the shared temp dir (see src/core/platform-fake-dirs.ts for what that did to /tmp).+ rmSync(t.p.userDataDir, { recursive: true, force: true })+})describe('reflectTargets', () => {// The sender IS a target: its copy is the ACK that tells it where its own edit landed in thediff --git a/src/core/context-tail.test.ts b/src/core/context-tail.test.tsindex 993e6f234..c8beede8a 100644--- a/src/core/context-tail.test.ts+++ b/src/core/context-tail.test.ts@@ -1,9 +1,23 @@-import { describe, expect, it, vi } from 'vitest'+import { afterAll, describe, expect, it, vi } from 'vitest'import fs from 'fs'import os from 'os'import path from 'path'import { createContextTail, parseLatestUsage, parseTaskNotifications, hasToolResult } from './context-tail'+// Every transcript directory this file makes is removed when it finishes. Most tests never removed+// theirs, so each run leaked seven `ctxtail-*` directories into the shared temp dir (see+// src/core/platform-fake-dirs.ts for what that did to a shared /tmp). File-level, not per test:+// a tail that is still polling when its test fails must not race the removal.+const madeDirs: string[] = []+function tmpDir(prefix: string): string {+ const dir = fs.mkdtempSync(path.join(os.tmpdir(), prefix))+ madeDirs.push(dir)+ return dir+}+afterAll(() => {+ for (const dir of madeDirs.splice(0)) fs.rmSync(dir, { recursive: true, force: true })+})+describe('parseLatestUsage', () => {it('returns the LAST assistant usage in the text (sum of input + cache tokens)', () => {const text = [@@ -83,7 +97,7 @@ describe('parseTaskNotifications', () => {describe('createContextTail — task notifications', () => {it('fires onTaskNotification even when the line lands torn across two reads', async () => {- const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'ctxtail-'))+ const dir = tmpDir('ctxtail-')const file = path.join(dir, 'sess.jsonl')const line = notificationLine('tu-torn')fs.writeFileSync(file, line.slice(0, 40)) // first half, no newline@@ -108,7 +122,7 @@ describe('createContextTail — the `parse` dep (gemini/codex)', () => {contents: string,parse: NonNullable<Parameters<typeof createContextTail>[1]>['parse']): Promise<unknown[]> {- const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'ctxtail-parse-'))+ const dir = tmpDir('ctxtail-parse-')const file = path.join(dir, 'sess.jsonl')fs.writeFileSync(file, contents)const send = vi.fn()@@ -150,7 +164,7 @@ describe('createContextTail — the `parse` dep (gemini/codex)', () => {it('keeps the last window/model when a later chunk carries usage only', async () => {// codex writes `turn_context` (the model) and `token_count` (the usage) on separate lines, so a// chunk can hold one without the other. The sticky fields are what stop the meter flickering.- const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'ctxtail-sticky-'))+ const dir = tmpDir('ctxtail-sticky-')const file = path.join(dir, 'sess.jsonl')fs.writeFileSync(file, 'first\n')const send = vi.fn()@@ -177,7 +191,7 @@ describe('createContextTail — the `parse` dep (gemini/codex)', () => {it('claude keeps its model-family window when NO parser is injected', async () => {// The regression guard for the byte-identical claim: same file, no `parse`, and the denominator// is still cachedWindowFor's 1M for an opus id.- const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'ctxtail-claude-'))+ const dir = tmpDir('ctxtail-claude-')const file = path.join(dir, 'sess.jsonl')fs.writeFileSync(file,@@ -252,7 +266,7 @@ describe('createContextTail — `wholeFile` (grok: a document rewritten, not app}async function pushesAfterRewrite(opts: { wholeFile?: boolean }): Promise<unknown[]> {- const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'ctxtail-whole-'))+ const dir = tmpDir('ctxtail-whole-')const file = path.join(dir, 'signals.json')// First document, then a LONGER one — longer matters: a shorter file trips the existing// truncation reset and would re-read from zero by accident, hiding the bug.@@ -279,7 +293,7 @@ describe('createContextTail — `wholeFile` (grok: a document rewritten, not app})it('delivers each tool result ID across a torn local transcript read', async () => {- const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'nt-question-tail-'))+ const dir = tmpDir('nt-question-tail-')const file = path.join(dir, 'session.jsonl')const onToolResult = vi.fn()const tail = createContextTail(() => {}, { onToolResult })@@ -304,7 +318,7 @@ it('delivers each tool result ID across a torn local transcript read', async ()}, 8000)describe('session-scoped context configuration (#818)', () => {it('overrides even a sonnet guess, isolates equal model ids, and invalidates changed/removed env', async () => {- const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'context-env-'))+ const dir = tmpDir('context-env-')const file = path.join(dir, 'session.jsonl')fs.writeFileSync(file, JSON.stringify({ type: 'assistant', message: { model: 'vendor-sonnet', usage: { input_tokens: 16000 } } }) + '\n')const send = vi.fn()@@ -336,7 +350,7 @@ describe('session-scoped context configuration (#818)', () => {describe('createContextTail — effort (the ⌘M composer label)', () => {it('pushes the recorded effort, and pushes again when ONLY the effort changed (a `/effort` pick)', async () => {- const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'ctxtail-effort-'))+ const dir = tmpDir('ctxtail-effort-')const file = path.join(dir, 'sess.jsonl')const rec = (effort: string) =>JSON.stringify({ type: 'assistant', effort, message: { model: 'claude-opus-5', usage: { input_tokens: 100 } } }) + '\n'@@ -354,7 +368,7 @@ describe('createContextTail — effort (the ⌘M composer label)', () => {}, 6000)it('omits the field when the transcript records none (older CLI / other agent)', async () => {- const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'ctxtail-noeffort-'))+ const dir = tmpDir('ctxtail-noeffort-')const file = path.join(dir, 'sess.jsonl')fs.writeFileSync(file, JSON.stringify({ type: 'assistant', message: { model: 'claude-opus-5', usage: { input_tokens: 100 } } }) + '\n')const send = vi.fn()diff --git a/src/core/platform-fake-dirs.ts b/src/core/platform-fake-dirs.tsnew file mode 100644index 000000000..3beb08d3d--- /dev/null+++ b/src/core/platform-fake-dirs.ts@@ -0,0 +1,72 @@+// TEST-ONLY: the registry of temp directories `fakePlatform()` creates, and the sweep that removes+// them once a test file has finished.+//+// Why it exists: `fakePlatform()` mkdtemp'd a fresh `nodeterm-fake-*` directory on EVERY call and+// nothing ever removed one. On a shared host where many sessions run `npm test`, those empty+// directories reached ~395,000 entries and took `/tmp` to 100% inode use (655,181 of 655,360) —+// at which point every program on the machine that needed a temp file failed.+//+// How it is wired: `fakePlatform()` records each directory it creates here, and+// `test/setup/fake-platform-cleanup.ts` (a vitest `setupFiles` entry) registers an `afterAll` that+// calls `removeFakePlatformDirs()`. A setup file's hooks attach to every test file, and with the+// default `sequence.hooks: 'stack'` its `afterAll` runs LAST, after the test file's own teardown —+// so no directory is removed while any test in the file (or its own `afterAll`) can still use it,+// and a test that inspects the directory mid-file keeps working.+//+// Why a module of its own, rather than living in platform-fake.ts: setup files are evaluated in the+// SAME module graph as the test file, BEFORE the test file's hoisted `vi.mock(...)` calls apply.+// Importing platform-fake.ts from the setup file would pre-load it with the real `fs`/`os`, silently+// changing what a test that mocks either module gets back from `fakePlatform()`. This module holds+// nothing a test would want to mock — and it is exactly right that its `rmSync` is the real one.+//+// Why `globalThis` instead of a module-level Set: `vi.resetModules()` re-evaluates modules, so a+// test that resets and re-imports platform-fake would record into a second Set the sweep never sees.+import { rmSync } from 'fs'++const REGISTRY = Symbol.for('nodeterm.test.fakePlatformDirs')++/** The live set of directories `fakePlatform()` created in this worker and has not yet removed. */+export function fakePlatformDirs(): Set<string> {+ const g = globalThis as unknown as Record<symbol, Set<string> | undefined>+ let dirs = g[REGISTRY]+ if (!dirs) {+ dirs = new Set()+ g[REGISTRY] = dirs+ }+ return dirs+}++/** Record a directory `fakePlatform()` created, so the per-file sweep removes it. Returns `dir`. */+export function trackFakePlatformDir(dir: string): string {+ fakePlatformDirs().add(dir)+ return dir+}++export interface FakeDirSweep {+ removed: string[]+ failed: Array<{ dir: string; error: unknown }>+}++/**+ * Remove every tracked directory and empty the registry.+ *+ * Best effort by design: one directory that cannot be removed (a test left something locked on+ * Windows, say) must not stop the rest from going, and must not fail a test file whose tests all+ * passed. Failures are returned so the caller can say so. A directory a test already removed+ * itself is fine (`force`).+ */+export function removeFakePlatformDirs(): FakeDirSweep {+ const dirs = fakePlatformDirs()+ const sweep: FakeDirSweep = { removed: [], failed: [] }+ for (const dir of [...dirs]) {+ dirs.delete(dir)+ try {+ // maxRetries covers a handle that is still closing on Windows (EBUSY/EPERM/ENOTEMPTY).+ rmSync(dir, { recursive: true, force: true, maxRetries: 3, retryDelay: 20 })+ sweep.removed.push(dir)+ } catch (error) {+ sweep.failed.push({ dir, error })+ }+ }+ return sweep+}diff --git a/src/core/platform-fake.test.ts b/src/core/platform-fake.test.tsnew file mode 100644index 000000000..401449b45--- /dev/null+++ b/src/core/platform-fake.test.ts@@ -0,0 +1,93 @@+// fakePlatform()'s temp directories must not outlive the test file that made them.+//+// They used to: every call mkdtemp'd a `nodeterm-fake-*` directory and nothing removed it, until a+// shared host's /tmp hit 100% inode use (~395,000 of them). The mechanism is platform-fake-dirs.ts+// (the registry + sweep) and test/setup/fake-platform-cleanup.ts (the per-file `afterAll`).+import { execFile } from 'child_process'+import fs from 'fs'+import os from 'os'+import path from 'path'+import { describe, expect, it, vi } from 'vitest'+import { fakePlatform } from './platform-fake'+import { fakePlatformDirs, removeFakePlatformDirs } from './platform-fake-dirs'++const repoRoot = path.resolve(__dirname, '../..')++describe('fakePlatform temp directories', () => {+ it('records every directory it creates', () => {+ const a = fakePlatform()+ const b = fakePlatform()+ expect(a.userDataDir).not.toBe(b.userDataDir)+ for (const dir of [a.userDataDir, b.userDataDir]) {+ expect(fs.statSync(dir).isDirectory()).toBe(true)+ expect(fakePlatformDirs().has(dir)).toBe(true)+ }+ })++ it('makes and records nothing when the caller brings its own userDataDir', () => {+ const before = [...fakePlatformDirs()]+ const p = fakePlatform({ userDataDir: '/fixture-data' })+ expect(p.userDataDir).toBe('/fixture-data')+ expect([...fakePlatformDirs()]).toEqual(before)+ })++ it('records into the same registry after vi.resetModules (it lives on globalThis)', async () => {+ vi.resetModules()+ const fresh = await import('./platform-fake')+ const dir = fresh.fakePlatform().userDataDir+ expect(fakePlatformDirs().has(dir)).toBe(true)+ })++ it('the sweep removes every recorded directory, contents included, and empties the registry', () => {+ const used = fakePlatform().userDataDir+ const alreadyGone = fakePlatform().userDataDir+ fs.mkdirSync(path.join(used, 'nested'))+ fs.writeFileSync(path.join(used, 'nested', 'state.json'), '{}')+ fs.rmSync(alreadyGone, { recursive: true }) // a test that cleaned up after itself+ const { removed, failed } = removeFakePlatformDirs()+ expect(failed).toEqual([])+ expect(removed).toEqual(expect.arrayContaining([used, alreadyGone]))+ expect(fs.existsSync(used)).toBe(false)+ expect(fakePlatformDirs().size).toBe(0)+ })++ // The end-to-end check: a real child vitest, on the repo's real config (only `include` swapped),+ // runs a file that makes directories through fakePlatform(). They must exist throughout that file+ // (the fixture asserts it, in a later test and in its own afterAll) and be gone once it has ended.+ // This is what fails if the setup file is dropped from vitest.config.ts, if it stops registering+ // the sweep, or if fakePlatform() stops recording what it makes.+ it('removes them once the test file that made them has finished (real vitest run)', async () => {+ const scratch = fs.mkdtempSync(path.join(os.tmpdir(), 'nt-fake-cleanup-'))+ try {+ const out = path.join(scratch, 'dirs.json')+ // Strip the parent run's worker identity so the child is a vitest run of its own.+ const env: NodeJS.ProcessEnv = { NT_FAKE_DIRS_OUT: out }+ for (const [k, v] of Object.entries(process.env)) if (!k.startsWith('VITEST')) env[k] ??= v+ const result = await new Promise<{ code: number; output: string }>((resolve) => {+ execFile(+ process.execPath,+ [+ path.join(repoRoot, 'node_modules', 'vitest', 'vitest.mjs'),+ 'run',+ '--config',+ 'test/fixtures/fake-platform-cleanup/vitest.config.ts'+ ],+ { cwd: repoRoot, env, timeout: 90_000 },+ (err, stdout, stderr) => {+ const code = err ? (typeof err.code === 'number' ? err.code : 1) : 0+ resolve({ code, output: `${stdout}\n${stderr}` })+ }+ )+ })+ expect(result.code, result.output).toBe(0)+ const dirs = JSON.parse(fs.readFileSync(out, 'utf8')) as string[]+ expect(dirs).toHaveLength(3)+ for (const dir of dirs) {+ expect(path.basename(dir)).toMatch(/^nodeterm-fake-/)+ expect(fs.existsSync(dir), `${dir} outlived its test file`).toBe(false)+ }+ } finally {+ fs.rmSync(scratch, { recursive: true, force: true })+ }+ }, 100_000)+})diff --git a/src/core/platform-fake.ts b/src/core/platform-fake.tsindex f9435c7db..d34b47c10 100644--- a/src/core/platform-fake.ts+++ b/src/core/platform-fake.ts@@ -2,6 +2,7 @@ import { mkdtempSync } from 'fs'import os from 'os'import path from 'path'import type { CorePlatform } from './platform'+import { trackFakePlatformDir } from './platform-fake-dirs'export interface FakePlatform extends CorePlatform {handlers: Record<string, (...args: any[]) => unknown>@@ -23,10 +24,17 @@ export interface FakePlatform extends CorePlatform {* store, context-link, the token files — statically reads as a write to a PREDICTABLE temp path,* which is a real symlink-attack shape and which CodeQL flags as `js/insecure-temporary-file`.* Tests that want their own directory still pass one in; this only fixes what they inherit.+ *+ * The directory is REMOVED when the test file finishes — see platform-fake-dirs.ts. It used to be+ * made on every call and never removed, which is how `/tmp` on a shared host ran out of inodes.+ * A caller that passes its own `userDataDir` gets no directory made at all (one used to be created+ * and immediately shadowed by the override); that caller owns its directory's lifetime.*/export function fakePlatform(overrides: Partial<CorePlatform> = {}): FakePlatform {+ const userDataDir =+ overrides.userDataDir ?? trackFakePlatformDir(mkdtempSync(path.join(os.tmpdir(), 'nodeterm-fake-')))const f: FakePlatform = {- userDataDir: mkdtempSync(path.join(os.tmpdir(), 'nodeterm-fake-')),+ userDataDir,appVersion: '0.0.0-test',isPackaged: false,handlers: {},diff --git a/src/main/peer-registry.test.ts b/src/main/peer-registry.test.tsindex bb334bc7a..caeeb4119 100644--- a/src/main/peer-registry.test.ts+++ b/src/main/peer-registry.test.ts@@ -1,5 +1,5 @@import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest'-import { mkdtempSync } from 'fs'+import { mkdtempSync, rmSync } from 'fs'import os from 'os'import path from 'path'import {@@ -37,7 +37,7 @@ function fakePlatformWithPeers(wc: { sent: Array<{ id: number; channel: string;const p: CorePlatform = {// mkdtemp, not a '/tmp/ud' literal: registered via initPlatform below, so a fixed temp path// taints every platform().userDataDir write as js/insecure-temporary-file (see platform-fake.ts).- userDataDir: mkdtempSync(path.join(os.tmpdir(), 'nodeterm-peer-registry-')),+ userDataDir: madeDir(mkdtempSync(path.join(os.tmpdir(), 'nodeterm-peer-registry-'))),appVersion: '0.0.0',isPackaged: false,handle: () => {},@@ -65,6 +65,14 @@ function fakePlatformWithPeers(wc: { sent: Array<{ id: number; channel: string;let gone: number[]let flow: Array<[number, string, boolean, string]>+// Every platform above mints a fresh mkdtemp dir, removed after each test (they used to leak one per+// test on every run — see src/core/platform-fake-dirs.ts for what that did to a shared /tmp).+const madeDirs: string[] = []+function madeDir(dir: string): string {+ madeDirs.push(dir)+ return dir+}+beforeEach(() => {gone = []flow = []@@ -80,6 +88,7 @@ afterEach(() => {for (const id of peerRegistry().ids()) unregisterPeerSink(id)resetPlatformForTests()vi.useRealTimers()+ for (const dir of madeDirs.splice(0)) rmSync(dir, { recursive: true, force: true })})describe('peer sink registry', () => {diff --git a/src/main/remote/hosted-join.test.ts b/src/main/remote/hosted-join.test.tsindex 91b5ae835..938c3e05b 100644--- a/src/main/remote/hosted-join.test.ts+++ b/src/main/remote/hosted-join.test.ts@@ -3,7 +3,7 @@// function: mint discipline, the joiner-side pin, auto-confirm, and the denial reason. The first// block drives a fake connect so every option handed to the relay client is observable; the second// runs the real core client against the real hosted service over an in-process transport.-import { describe, it, expect, vi, afterEach, beforeEach } from 'vitest'+import { describe, it, expect, vi, afterAll, afterEach, beforeEach } from 'vitest'import fs from 'node:fs'import os from 'node:os'import path from 'node:path'@@ -20,7 +20,18 @@ import type { PeerAttach } from '../../core/relay/relay-host'import type { RelayTransport } from '../../core/relay/relay-socket'import { IPC } from '../../shared/ipc'-const tmpDir = () => fs.mkdtempSync(path.join(os.tmpdir(), 'hosted-join-'))+// Every directory this file makes is removed when it finishes: `setup()` never removed its own, and+// one leaked per test on every run of the suite (see src/core/platform-fake-dirs.ts for what that+// did to a shared host's /tmp). `hostedWorld()` still removes its own early, in `afterEach`.+const madeDirs: string[] = []+const tmpDir = () => {+ const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'hosted-join-'))+ madeDirs.push(dir)+ return dir+}+afterAll(() => {+ for (const dir of madeDirs.splice(0)) fs.rmSync(dir, { recursive: true, force: true })+})const pub = (k: KeyPair) => publicKeyToB64(k.publicKey)function codeFor(hostKeys: KeyPair, over: Partial<JoinCode> = {}): JoinCode {diff --git a/test/fixtures/fake-platform-cleanup/leak.fixture.ts b/test/fixtures/fake-platform-cleanup/leak.fixture.tsnew file mode 100644index 000000000..3f7c27ea3--- /dev/null+++ b/test/fixtures/fake-platform-cleanup/leak.fixture.ts@@ -0,0 +1,33 @@+// Run ONLY by src/core/platform-fake.test.ts, in a child vitest through ./vitest.config.ts. The+// `.fixture.ts` name keeps it out of the normal suite's `include`.+//+// Makes directories through `fakePlatform()`, writes their paths to $NT_FAKE_DIRS_OUT, and asserts+// they stay alive for as long as this file is running — later tests AND this file's own `afterAll`+// can still use them. The parent then checks they are gone once this file has finished.+import fs from 'fs'+import path from 'path'+import { afterAll, expect, it } from 'vitest'+import { fakePlatform } from '../../../src/core/platform-fake'++const out = process.env.NT_FAKE_DIRS_OUT+if (!out) throw new Error('NT_FAKE_DIRS_OUT is unset — this fixture is run by platform-fake.test.ts')++let dirs: string[] = []++it('creates directories through fakePlatform()', () => {+ dirs = [fakePlatform(), fakePlatform(), fakePlatform()].map((p) => p.userDataDir)+ for (const dir of dirs) expect(fs.statSync(dir).isDirectory()).toBe(true)+ fs.writeFileSync(out, JSON.stringify(dirs))+})++it('keeps them, writable, for a later test in the same file', () => {+ for (const dir of dirs) expect(fs.existsSync(dir)).toBe(true)+ // Non-empty on purpose: the sweep must remove a directory a test actually used.+ fs.mkdirSync(path.join(dirs[0], 'nested'))+ fs.writeFileSync(path.join(dirs[0], 'nested', 'state.json'), '{}')+})++afterAll(() => {+ // The file's own teardown runs BEFORE the sweep (setup-file hooks run last under 'stack').+ for (const dir of dirs) expect(fs.existsSync(dir)).toBe(true)+})diff --git a/test/fixtures/fake-platform-cleanup/vitest.config.ts b/test/fixtures/fake-platform-cleanup/vitest.config.tsnew file mode 100644index 000000000..30cc00bd9--- /dev/null+++ b/test/fixtures/fake-platform-cleanup/vitest.config.ts@@ -0,0 +1,16 @@+// Child-run config for src/core/platform-fake.test.ts ONLY — not part of the normal suite.+//+// It IS the repo's real vitest config with one change: `include` names the fixture below instead+// of the real tests. Everything the regression test is about — `setupFiles` (the per-file+// fakePlatform sweep), `globalSetup`, the hook order — comes from the real config unchanged, so+// dropping the sweep from vitest.config.ts turns that test red.+import base from '../../../vitest.config'++export default {+ ...base,+ test: {+ ...base.test,+ include: ['test/fixtures/fake-platform-cleanup/*.fixture.ts'],+ maxWorkers: 1+ }+}diff --git a/test/setup/fake-platform-cleanup.ts b/test/setup/fake-platform-cleanup.tsnew file mode 100644index 000000000..fc0246b06--- /dev/null+++ b/test/setup/fake-platform-cleanup.ts@@ -0,0 +1,21 @@+// TEST-ONLY — the per-file sweep of the temp directories `fakePlatform()` creates. See+// `src/core/platform-fake-dirs.ts` for why (a shared host's `/tmp` ran out of inodes) and why the+// registry lives in a module of its own (this file must not pre-load platform-fake.ts with the real+// `fs`/`os` ahead of a test file's `vi.mock`).+//+// A `setupFiles` entry runs before EVERY test file, and a hook registered here attaches to that+// file. With vitest's default `sequence.hooks: 'stack'`, this `afterAll` — registered before any of+// the test file's own hooks — runs after all of them: every test has finished and the file's own+// teardown has closed whatever it had open inside the directory.+//+// Not a `process.on('exit')` sweep: vitest stops a forks-pool worker with SIGTERM, which ends the+// process without running `exit` listeners, so that sweep would almost never run.+import { afterAll } from 'vitest'+import { removeFakePlatformDirs } from '../../src/core/platform-fake-dirs'++afterAll(() => {+ const { failed } = removeFakePlatformDirs()+ for (const { dir, error } of failed) {+ console.warn(`fakePlatform: could not remove ${dir}: ${String(error)}`)+ }+})diff --git a/vitest.config.ts b/vitest.config.tsindex 2bb2415a9..f9864c702 100644--- a/vitest.config.ts+++ b/vitest.config.ts@@ -30,7 +30,10 @@ export default defineConfig({// this machine runs nodeterm on. `globalSetup` creates and removes it, the setup file re-asserts// it inside each worker (and refuses if it is missing). See test/setup/tmux-sandbox.ts.globalSetup: ['test/setup/tmux-sandbox.ts'],- setupFiles: ['test/setup/tmux-worker-env.ts'],+ // fake-platform-cleanup: removes every temp dir `fakePlatform()` made once each test file ends.+ // Without it they were never removed, and a shared host's /tmp ran out of inodes. See+ // src/core/platform-fake-dirs.ts; src/core/platform-fake.test.ts proves the wiring end to end.+ setupFiles: ['test/setup/tmux-worker-env.ts', 'test/setup/fake-platform-cleanup.ts'],// Issue #160: with the default (one worker per core), a 10-core Mac runs ~10 fs-heavy suites// at once and transient fd exhaustion (EMFILE) turns into silent test flakiness — probes like// `fs.existsSync` swallow the error and answer false, so whole files fail in ways that never