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 the suite leaving temp directories behind
reviewc34ebc845bc7
diff --git a/CLAUDE.md b/CLAUDE.mdindex e7a2ba55c..b43c9fb7b 100644--- a/CLAUDE.md+++ b/CLAUDE.md@@ -7407,6 +7407,33 @@ leaves ONE directory. A test that builds its own `CorePlatform` takes its `userDdir and never a fixed `/tmp/...` literal.`platform-fake.test.ts` fails if the root is not in effect, so dropping the `globalSetup` entry is loud.+## The test suite leaves nothing in the OS temp dir++Measured 2026-09-29 on a shared dev box: `/tmp` held ~41k top-level entries, and one full run of this+suite added ~1,560 of them (`nodeterm-fake-*` alone was 1,412 — see the `fakePlatform()` paragraph+above for that half). The filesystem ran out of INODES and every session's builds and tests broke.+For every OTHER test dir, two layers, both needed:++- **Every test dir is removed where it is made.** `testTmpDir(prefix)` (`src/core/test-tmp.ts`) is+ a tracked `mkdtemp` whose removal is an `afterAll` in the setup file `test/setup/tmp-worker-env.ts`+ — a setup file's hooks sit on the file's root suite and, with vitest's default stacked hook order,+ run AFTER the file's own `afterAll` hooks, i.e. after the suite stopped whatever was writing there.+- **The run is sandboxed and FAILS on a leak.** `test/setup/tmp-sandbox.ts` (`globalSetup`, listed+ AFTER the tmux sandbox so that one keeps its short base path) points `TMPDIR` (and `TEMP`/`TMP` on+ Windows) at one private directory; teardown lists what is left, removes the sandbox anyway, and+ sets `process.exitCode = 1` naming each prefix. **Not `throw`**: vitest only LOGS a teardown error+ (`error during close`) and still exits 0, and a throw skips the other globalSetup teardowns — the+ tmux sandbox's, measured. Windows warns instead of failing (a just-exited child's file can be+ EBUSY for a moment after a correct cleanup). `NODETERM_TEST_KEEP_TMP=1` keeps it for inspection.+ `FOREIGN_TMP_ENTRIES` is the short allowlist of names nothing in this repo creates (Chrome's own+ scratch files from the headless layout tests), each with its reason.+- **Two leaks were production memos, not test bugs**: `contextLinkDir()` and+ `HookServer.endpointFilePath()` cached the FIRST platform's `userDataDir` for the life of the+ process, so a process that booted a second core (the server e2e suites) wrote `context.sh` and+ `hook-endpoint.env` into the first core's already-removed directory. `initContextLink` and+ `hookServer.stop()` now drop the memo. Found with `strace -f -e trace=mkdir,rename` — an EMPTY+ leftover dir is the signature of a late writer, not of a missing `rm`.+## Conventions- **Two docs, two audiences — keep both.** This file holds the deep invariants with theirdiff --git a/CONTRIBUTING.md b/CONTRIBUTING.mdindex a968a320f..213a5c2ea 100644--- a/CONTRIBUTING.md+++ b/CONTRIBUTING.md@@ -1066,6 +1066,16 @@ runs failed with ENOSPC. If you `mkdtemp` in a test yourself, remove it in `afte— or, for the `userDataDir` of a `CorePlatform` you build by hand, call `makeFakeUserDataDir()`,which lands under the same root.+**Beyond `fakePlatform()`, a test cleans up every temp directory it creates.** The suite once left ~1,500 directories in+`/tmp` per full run, and on a shared box that exhausted the filesystem's inodes and broke every+other session's builds. Use `testTmpDir(prefix)` from `src/core/test-tmp.ts` (removed when the file+ends, even when a test failed), or `rmSync(dir, { recursive: true, force: true })` in+`afterEach`/`afterAll`/`finally`; stop servers and children writing there first. Every run points+`os.tmpdir()` at a private sandbox (`test/setup/tmp-sandbox.ts`), and the run exits non-zero naming+each prefix still in it — `NODETERM_TEST_KEEP_TMP=1` keeps the sandbox so you can see what wrote+there. A module-level cache of `platform().userDataDir` is the other way a dir comes back: a suite+that boots two cores keeps writing into the first one's removed directory.+**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/hook-endpoint-file-sh.test.ts b/src/core/agents/hook-endpoint-file-sh.test.tsindex c30f77dcc..e489e7cab 100644--- a/src/core/agents/hook-endpoint-file-sh.test.ts+++ b/src/core/agents/hook-endpoint-file-sh.test.ts@@ -1,12 +1,12 @@import { describe, it, expect, beforeAll, afterAll } from 'vitest'import fs from 'node:fs'-import os from 'node:os'import path from 'node:path'import { spawnSync } from 'node:child_process'import { hookServer } from './hook-server'import { nodeTokenDir } from './node-token-files'import { initPlatform, resetPlatformForTests } from '../platform'import { fakePlatform } from '../platform-fake'+import { testTmpDir } from '../test-tmp'// Issue #351: on macOS the userDataDir lives under "Application Support" — a directory name WITH A// SPACE. The managed hook script SOURCES the endpoint file (`. "$file"`) under /bin/sh, so an@@ -17,7 +17,7 @@ import { fakePlatform } from '../platform-fake'// a real reader.let spaced = ''beforeAll(async () => {- const root = fs.mkdtempSync(path.join(os.tmpdir(), 'nodeterm-ep-sh-'))+ const root = testTmpDir('nodeterm-ep-sh-')// A subdir with a space in its name — the "Application Support" shape.spaced = path.join(root, 'App Support', 'node-terminal')fs.mkdirSync(spaced, { recursive: true })diff --git a/src/core/agents/hook-server.ts b/src/core/agents/hook-server.tsindex bb9033e12..9c81d8be7 100644--- a/src/core/agents/hook-server.ts+++ b/src/core/agents/hook-server.ts@@ -1453,6 +1453,11 @@ export class HookServer {}this.port = 0this.token = ''+ // Forget the memoized path only now, after removeEndpointFile() used it: the next start()+ // re-derives it from the platform it runs under. A process that boots a second core (the+ // server e2e suites do, each on its own dataDir) otherwise advertised into the FIRST core's+ // directory — recreating a dataDir its test had already removed.+ this.endpointPath = ''}}diff --git a/src/core/agents/hooks/claude-tui.test.ts b/src/core/agents/hooks/claude-tui.test.tsindex 1e6426c13..5513ec2ee 100644--- a/src/core/agents/hooks/claude-tui.test.ts+++ b/src/core/agents/hooks/claude-tui.test.ts@@ -1,8 +1,8 @@import { describe, expect, it } from 'vitest'-import { mkdtempSync, readFileSync, writeFileSync, existsSync } from 'fs'-import { tmpdir } from 'os'+import { readFileSync, writeFileSync, existsSync } from 'fs'import path from 'path'import { ensureFullscreenTui, ensureFullscreenTuiInFile, TUI_FULLSCREEN } from './claude-tui'+import { testTmpDir } from '../../test-tmp'describe('ensureFullscreenTui (pure)', () => {it('writes tui=fullscreen when the key is absent', () => {@@ -32,7 +32,7 @@ describe('ensureFullscreenTui (pure)', () => {})describe('ensureFullscreenTuiInFile (fail-open file wrapper)', () => {- const dir = mkdtempSync(path.join(tmpdir(), 'nt-tui-'))+ const dir = testTmpDir('nt-tui-')it('creates the key in a missing file (parents made, valid JSON written)', () => {const p = path.join(dir, 'nested', 'settings.json')diff --git a/src/core/agents/hooks/managed-script.test.ts b/src/core/agents/hooks/managed-script.test.tsindex 1b0ff7490..6b18f0e54 100644--- a/src/core/agents/hooks/managed-script.test.ts+++ b/src/core/agents/hooks/managed-script.test.ts@@ -8,6 +8,7 @@ import { hookServer } from '../hook-server'import { nodeAuthToken } from '../node-auth-token'import { initPlatform, resetPlatformForTests } from '../../platform'import { fakePlatform } from '../../platform-fake'+import { testTmpDir } from '../../test-tmp'describe('buildManagedScript', () => {const s = buildManagedScript('claude')@@ -193,7 +194,7 @@ describe('buildManagedScript', () => {* 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. */const run = (unameS: string, cygpath: string | null): CurlCall[] => {- const dir = mkdtempSync(join(tmpdir(), 'nt-payload-'))+ const dir = testTmpDir('nt-payload-')const bin = join(dir, 'bin')const home = join(dir, 'home')mkdirSync(bin, { recursive: true })diff --git a/src/core/agents/hooks/opencode-live-endpoint.test.ts b/src/core/agents/hooks/opencode-live-endpoint.test.tsindex 3407b98f8..5941d9d8f 100644--- a/src/core/agents/hooks/opencode-live-endpoint.test.ts+++ b/src/core/agents/hooks/opencode-live-endpoint.test.ts@@ -1,12 +1,12 @@import { describe, it, expect, beforeAll, afterAll, vi } from 'vitest'import fs from 'node:fs'-import os from 'node:os'import path from 'node:path'import { buildOpencodePlugin } from './opencode'import { hookServer } from '../hook-server'import { initPlatform, resetPlatformForTests } from '../../platform'import { fakePlatform } from '../../platform-fake'import type { NormalizedAgentEvent } from '../../../shared/agents/normalize'+import { testTmpDir } from '../../test-tmp'// Issue #351 follow-up: the plugin's `live()` re-parses the REAL endpoint file that// `writeEndpointFile()` writes — every fixture in opencode.test.ts hand-writes that file, so a@@ -16,7 +16,7 @@ import type { NormalizedAgentEvent } from '../../../shared/agents/normalize'// is 401'd and the listener below never fires.let tmp = ''beforeAll(async () => {- const root = fs.mkdtempSync(path.join(os.tmpdir(), 'nt-oc-live-'))+ const root = testTmpDir('nt-oc-live-')// Spaced userDataDir — the "Application Support" shape the quoting exists for.tmp = path.join(root, 'App Support', 'node-terminal')fs.mkdirSync(tmp, { recursive: true })diff --git a/src/core/context-link.ts b/src/core/context-link.tsindex bde486f51..d050caedc 100644--- a/src/core/context-link.ts+++ b/src/core/context-link.ts@@ -340,6 +340,10 @@ export function initContextLink(): void {pty = ptyManagerdeps = platformDeps+ // Re-derive from the platform this init runs under: a process that boots a second core (the+ // server e2e suites start several, each on its own dataDir) must not keep writing into the+ // FIRST one's directory — which is how a test's removed dataDir came back, `context.sh` and all.+ dir = ''linkRevision++linkDocs.clear()verifiedPaths.clear()diff --git a/src/core/context-tail.test.ts b/src/core/context-tail.test.tsindex 993e6f234..8afb47a66 100644--- a/src/core/context-tail.test.ts+++ b/src/core/context-tail.test.ts@@ -1,8 +1,8 @@import { 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'+import { testTmpDir } from './test-tmp'describe('parseLatestUsage', () => {it('returns the LAST assistant usage in the text (sum of input + cache tokens)', () => {@@ -83,7 +83,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 = testTmpDir('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 +108,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 = testTmpDir('ctxtail-parse-')const file = path.join(dir, 'sess.jsonl')fs.writeFileSync(file, contents)const send = vi.fn()@@ -150,7 +150,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 = testTmpDir('ctxtail-sticky-')const file = path.join(dir, 'sess.jsonl')fs.writeFileSync(file, 'first\n')const send = vi.fn()@@ -177,7 +177,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 = testTmpDir('ctxtail-claude-')const file = path.join(dir, 'sess.jsonl')fs.writeFileSync(file,@@ -252,7 +252,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 = testTmpDir('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 +279,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 = testTmpDir('nt-question-tail-')const file = path.join(dir, 'session.jsonl')const onToolResult = vi.fn()const tail = createContextTail(() => {}, { onToolResult })@@ -304,7 +304,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 = testTmpDir('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 +336,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 = testTmpDir('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 +354,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 = testTmpDir('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/github/service.pulls.test.ts b/src/core/github/service.pulls.test.tsindex 5769f31fd..334ba1034 100644--- a/src/core/github/service.pulls.test.ts+++ b/src/core/github/service.pulls.test.ts@@ -1,8 +1,8 @@import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'import { promises as fs } from 'node:fs'-import os from 'node:os'import path from 'node:path'import { GitHubIssueCache } from './cache'+import { testTmpDir } from '../test-tmp'import { GitHubIssueService, type GitHubIssueServiceContext, type GitHubIssuesClientLike } from './service'import { GitHubRequestCoordinator } from './request-coordinator'import type { PullStatusRead } from './graphql-pulls'@@ -10,9 +10,15 @@ import type { GitHubIssue, IssueHeartbeatResult, NormalisedProjectKanbanGitHub }import type { GitHubPullChecksResult, PullStatusFacts } from '../../shared/github-pull-status'let userDataDir: string-beforeEach(async () => { userDataDir = await fs.mkdtemp(path.join(os.tmpdir(), 'nt-github-pulls-')) })-// A claim persists the pull memory asynchronously, so a save can still be landing as a test ends.-afterEach(async () => { await fs.rm(userDataDir, { recursive: true, force: true, maxRetries: 10, retryDelay: 20 }) })+beforeEach(() => { userDataDir = testTmpDir('nt-github-pulls-') })+// A claim persists the pull memory asynchronously, so a save can still be landing as a test ends —+// and one that lands AFTER the rm recreates the directory (`writePrivate` mkdirs), which is how this+// file stranded a `nt-github-pulls-*` dir per run. Settle first, then remove; `testTmpDir` removes it+// again when the file ends, for a save slower than the settle.+afterEach(async () => {+ await flush()+ await fs.rm(userDataDir, { recursive: true, force: true, maxRetries: 10, retryDelay: 20 })+})const HEAD = 'a'.repeat(40)const config: NormalisedProjectKanbanGitHub = {diff --git a/src/core/pty-single-user.test.ts b/src/core/pty-single-user.test.tsindex 545b585d9..189ffb895 100644--- a/src/core/pty-single-user.test.ts+++ b/src/core/pty-single-user.test.ts@@ -1,9 +1,9 @@import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest'import fs from 'fs'-import os from 'os'import path from 'path'import { initPlatform, resetPlatformForTests } from './platform'import { fakePlatform, type FakePlatform } from './platform-fake'+import { testTmpDir } from './test-tmp'import { IPC } from '../shared/ipc'import { DEFAULT_SETTINGS } from '../shared/types'import { MODEL_GATEWAY_SECRET_REF } from '../shared/agents/model-gateway'@@ -173,7 +173,7 @@ describe('SINGLE-USER REGRESSION: co-attach must not change the solo path', () =liveTmuxSessions.clear()paneProcessReply = ''processGroupReply = ''- userDataDir = fs.mkdtempSync(path.join(os.tmpdir(), 'nt-solo-'))+ userDataDir = testTmpDir('nt-solo-')fake = fakePlatform({ userDataDir })initPlatform(fake)vi.useFakeTimers()@@ -191,7 +191,8 @@ describe('SINGLE-USER REGRESSION: co-attach must not change the solo path', () =// the last retry. The catch is what actually fixes it, and it is safe precisely because this// line is HOUSEKEEPING: the directory is per-test (`mkdtemp`) and lives in the OS temp dir, so// failing to remove it cannot indicate a defect in anything under test. A cleanup that can fail- // the suite is worse than a leftover directory.+ // the suite is worse than a leftover directory. It does not stay left over: the dir comes from+ // `testTmpDir`, which removes it again when the file ends, after the late write has landed.try {fs.rmSync(userDataDir, { recursive: true, force: true, maxRetries: 10, retryDelay: 20 })} catch {@@ -243,7 +244,7 @@ describe('SINGLE-USER REGRESSION: co-attach must not change the solo path', () =// ── The spawn itself: same tmux args, same cwd, same env ──────────────────────────────────it('spawns ONE tmux client with the unchanged attach flags, cwd and session name', async () => {const m = await tmuxManager()- const cwd = fs.mkdtempSync(path.join(os.tmpdir(), 'nt-cwd-'))+ const cwd = testTmpDir('nt-cwd-')await create(80, 24, 'solo-1', { cwd })expect(spawned).toHaveLength(1)@@ -270,7 +271,6 @@ describe('SINGLE-USER REGRESSION: co-attach must not change the solo path', () =expect(env.TMUX).toBeUndefined()expect(env.TMUX_PANE).toBeUndefined()expect(env.PATH).toBe('/usr/bin:/bin')- fs.rmSync(cwd, { recursive: true, force: true })})it('injects the shared gateway into both the PTY and its tmux session environment', async () => {diff --git a/src/core/remote-ssh/control-master.realsh.test.ts b/src/core/remote-ssh/control-master.realsh.test.tsindex 1899d84e4..baeb8de57 100644--- a/src/core/remote-ssh/control-master.realsh.test.ts+++ b/src/core/remote-ssh/control-master.realsh.test.ts@@ -13,11 +13,11 @@import { describe, expect, it, beforeAll } from 'vitest'import { execFileSync } from 'child_process'import fs from 'fs'-import os from 'os'import path from 'path'import { remoteHookEnvArgs, remoteTmuxPtyArgs } from './control-master'import { accountTmuxEnvArgs, remoteAccountConfigDirAbs } from '../claude-accounts-core'import { isSafeNodeId, isSafeRemoteHome } from '../remote-safety'+import { testTmpDir } from '../test-tmp'const conn = { host: 'h.example.com', user: 'deploy', port: 2222, identityFile: '/k/id' }@@ -25,7 +25,7 @@ let binDir: stringlet markerDir: stringbeforeAll(() => {- const root = fs.mkdtempSync(path.join(os.tmpdir(), 'ntsh-'))+ const root = testTmpDir('ntsh-')binDir = path.join(root, 'bin')markerDir = path.join(root, 'markers')fs.mkdirSync(binDir)@@ -212,10 +212,10 @@ describe('REAL sh: remote tmux PATH resolution + graceful degrade (issue #449)',// PATH must hold NO tmux at all for these — the dev/CI box's own /usr/bin/tmux would win the// `command -v` and run for real ("open terminal failed"). An empty dir is the only safe PATH;// everything the guard needs (command, printf, cd, exec) is an sh builtin.- const emptyPath = (): string => fs.mkdtempSync(path.join(os.tmpdir(), 'ntsh-nopath-'))+ const emptyPath = (): string => testTmpDir('ntsh-nopath-')it('finds a tmux that lives only in an appended dir ($HOME/.local/bin)', () => {- const home = fs.mkdtempSync(path.join(os.tmpdir(), 'ntsh-home-'))+ const home = testTmpDir('ntsh-home-')const local = path.join(home, '.local', 'bin')fs.mkdirSync(local, { recursive: true })fs.copyFileSync(path.join(binDir, 'tmux'), path.join(local, 'tmux'))@@ -229,7 +229,7 @@ describe('REAL sh: remote tmux PATH resolution + graceful degrade (issue #449)',})it('a host with NO tmux prints the explanation and execs a plain login shell', () => {- const home = fs.mkdtempSync(path.join(os.tmpdir(), 'ntsh-home-'))+ const home = testTmpDir('ntsh-home-')const shell = path.join(home, 'shell-stub')fs.writeFileSync(shell, `#!/bin/sh\nprintf 'SHELL_STUB %s\\n' "$@"\n`, { mode: 0o755 })const cmd = remoteTmuxPtyArgs(conn, '/s.sock', 'nt-n1', '/home/u').slice(-1)[0]diff --git a/src/core/remote-ssh/session-age.realsh.test.ts b/src/core/remote-ssh/session-age.realsh.test.tsindex a201f91aa..a2f09387b 100644--- a/src/core/remote-ssh/session-age.realsh.test.ts+++ b/src/core/remote-ssh/session-age.realsh.test.ts@@ -7,9 +7,9 @@import { describe, expect, it, beforeAll } from 'vitest'import { execFileSync } from 'child_process'import fs from 'fs'-import os from 'os'import path from 'path'import { remoteSessionAgeArgs, parseSessionAge } from './control-master'+import { testTmpDir } from '../test-tmp'const conn = { host: 'h.example.com', user: 'deploy' }let binDir: string@@ -29,7 +29,7 @@ function runWithTmuxAnswer(line: string, created: string): string {}beforeAll(() => {- binDir = fs.mkdtempSync(path.join(os.tmpdir(), 'ntage-'))+ binDir = testTmpDir('ntage-')})describe('remoteSessionAgeArgs (real /bin/sh)', () => {diff --git a/src/core/session-host-client-startup-wait.test.ts b/src/core/session-host-client-startup-wait.test.tsindex 968f97bff..499d702da 100644--- a/src/core/session-host-client-startup-wait.test.ts+++ b/src/core/session-host-client-startup-wait.test.ts@@ -3,9 +3,6 @@// budget left every node that mounted in the window on a permanent "could not be started" until// the user clicked Try again — and must stop waiting the moment nothing is starting any more.import { describe, it, expect, beforeEach, vi } from 'vitest'-import { mkdtempSync } from 'fs'-import os from 'os'-import path from 'path'const launcherMocks = vi.hoisted(() => ({resolveSessionHostScript: vi.fn(() => 'fake-session-host.cjs'),@@ -22,12 +19,13 @@ vi.mock('./session-host-launcher', () => launcherMocks)vi.mock('../session-host/existing-host-state', () => identityMocks)import { SessionHostClient } from './session-host-client'+import { testTmpDir } from './test-tmp'const emptyLock = (): never => {throw new Error('invalid session-host state: file is empty')}-const tempDir = (): string => mkdtempSync(path.join(os.tmpdir(), 'nt-host-wait-'))+const tempDir = (): string => testTmpDir('nt-host-wait-')beforeEach(() => {vi.clearAllMocks()diff --git a/src/core/speech/register-ipc.test.ts b/src/core/speech/register-ipc.test.tsindex 443305b86..1a6a93c4b 100644--- a/src/core/speech/register-ipc.test.ts+++ b/src/core/speech/register-ipc.test.ts@@ -1,16 +1,15 @@import { describe, expect, it, vi } from 'vitest'-import { mkdtempSync, writeFileSync } from 'node:fs'-import { tmpdir } from 'node:os'-import { join } from 'node:path'+import { writeFileSync } from 'node:fs'import { registerSpeechIpc } from './register-ipc'import { SpeechService, type WhisperEngineHandle } from './speech-service'import { WhisperModelStore } from './whisper-models'import { DEFAULT_SETTINGS } from '../../shared/types'+import { testTmpDir } from '../test-tmp'function setup(engine: 'whisper' | 'cloud' = 'whisper', language = 'auto', cloudOk = false) {const handlers = new Map<string, (payload: any) => Promise<any>>()const sent: string[] = []- const dir = mkdtempSync(join(tmpdir(), 'ipc-'))+ const dir = testTmpDir('ipc-')const models = new WhisperModelStore({ dir })writeFileSync(models.modelPath('tiny'), 'x')const factory = async (): Promise<WhisperEngineHandle> => ({diff --git a/src/core/speech/speech-service.test.ts b/src/core/speech/speech-service.test.tsindex 19c166e59..cbb065049 100644--- a/src/core/speech/speech-service.test.ts+++ b/src/core/speech/speech-service.test.ts@@ -1,9 +1,8 @@import { beforeEach, describe, expect, it, vi } from 'vitest'-import { mkdtempSync, writeFileSync } from 'node:fs'-import { tmpdir } from 'node:os'-import { join } from 'node:path'+import { writeFileSync } from 'node:fs'import { describeWhisperLoadError, isGgmlModelHeader, SpeechService, type WhisperEngineHandle } from './speech-service'import { WhisperModelStore } from './whisper-models'+import { testTmpDir } from '../test-tmp'describe('SpeechService', () => {let dir: string@@ -23,7 +22,7 @@ describe('SpeechService', () => {const pcm = new Float32Array(16000)beforeEach(() => {- dir = mkdtempSync(join(tmpdir(), 'svc-'))+ dir = testTmpDir('svc-')models = new WhisperModelStore({ dir })loads.length = 0freed.length = 0@@ -99,7 +98,7 @@ describe('SpeechService.shutdown', () => {}beforeEach(() => {- dir = mkdtempSync(join(tmpdir(), 'svc-'))+ dir = testTmpDir('svc-')models = new WhisperModelStore({ dir })freed.length = 0writeFileSync(models.modelPath('tiny'), 'x')diff --git a/src/core/subagent-tail.test.ts b/src/core/subagent-tail.test.tsindex 373f799fb..33546dcdd 100644--- a/src/core/subagent-tail.test.ts+++ b/src/core/subagent-tail.test.ts@@ -1,6 +1,5 @@import { describe, expect, it, vi } from 'vitest'import fs from 'fs'-import os from 'os'import path from 'path'import {createSubagentTail,@@ -8,6 +7,7 @@ import {splitCompleteLines,SUBAGENT_READ_CAP} from './subagent-tail'+import { testTmpDir } from './test-tmp'const assistant = (text: string): string =>JSON.stringify({ type: 'assistant', message: { content: [{ type: 'text', text }] } })@@ -63,7 +63,7 @@ describe('splitCompleteLines', () => {const wait = (ms: number): Promise<void> => new Promise((r) => setTimeout(r, ms))function setup(): { transcriptPath: string; subDir: string } {- const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'subtail-'))+ const dir = testTmpDir('subtail-')const transcriptPath = path.join(dir, 'sess.jsonl')const subDir = path.join(dir, 'sess', 'subagents')fs.mkdirSync(subDir, { recursive: true })@@ -121,7 +121,7 @@ describe('createSubagentTail', () => {describe('trackFile (codex leg: pre-resolved file + per-entry formatter)', () => {it('tails the given file directly with the injected stateful formatter', async () => {- const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'subtail-file-'))+ const dir = testTmpDir('subtail-file-')const file = path.join(dir, 'rollout-child.jsonl')// A stateful formatter (mirrors the codex fork-replay gate): suppress until 'GATE'.const newFormatter = () => {@@ -155,7 +155,7 @@ describe('trackFile (codex leg: pre-resolved file + per-entry formatter)', () =>})it('two trackFile entries do not share formatter state', async () => {- const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'subtail-file2-'))+ const dir = testTmpDir('subtail-file2-')const a = path.join(dir, 'a.jsonl')const b = path.join(dir, 'b.jsonl')const newFormatter = () => {@@ -229,7 +229,7 @@ describe('subagent-tail read cap', () => {// its tail at every stop and start it again at every start; the second start must continue.describe('a resumed subagent (same id tracked again)', () => {it('continues from where the finished tail stopped instead of re-streaming the file', async () => {- const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'subtail-resume-'))+ const dir = testTmpDir('subtail-resume-')const file = path.join(dir, 'agent-a1.jsonl')fs.writeFileSync(file, assistant('first turn') + '\n')const send = vi.fn()@@ -248,7 +248,7 @@ describe('a resumed subagent (same id tracked again)', () => {})it('a resume inside the finish grace window keeps the tail alive', async () => {- const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'subtail-revive-'))+ const dir = testTmpDir('subtail-revive-')const file = path.join(dir, 'agent-a1.jsonl')fs.writeFileSync(file, assistant('before') + '\n')const send = vi.fn()@@ -267,7 +267,7 @@ describe('a resumed subagent (same id tracked again)', () => {})it('a different file under the same id starts from its beginning', async () => {- const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'subtail-other-'))+ const dir = testTmpDir('subtail-other-')const a = path.join(dir, 'a.jsonl')const b = path.join(dir, 'b.jsonl')fs.writeFileSync(a, assistant('in a') + '\n')diff --git a/src/core/test-tmp.guard.test.ts b/src/core/test-tmp.guard.test.tsnew file mode 100644index 000000000..b630ab03a--- /dev/null+++ b/src/core/test-tmp.guard.test.ts@@ -0,0 +1,90 @@+// The run-wide temp sandbox (test/setup/tmp-sandbox.ts) is the guard against the suite stranding+// scratch directories in the shared OS temp dir — ~1,560 per full run before it existed, enough to+// exhaust /tmp's inodes on a shared box. This file pins the three things that guard depends on:+// 1. it is actually wired and in effect in this worker (a config edit that drops it would+// otherwise pass silently — every test would just write to /tmp again);+// 2. `testTmpDir` creates inside it and `removeTestTmpDirs` removes what it created, and only that;+// 3. the teardown's leak report counts what it should and names each prefix.+import fs from 'fs'+import os from 'os'+import path from 'path'+import { describe, expect, it } from 'vitest'+import {+ FOREIGN_TMP_ENTRIES,+ TMP_SANDBOX_ENV,+ leakedTmpEntries,+ removeTestTmpDirs,+ sweepTestTmpDirs,+ summarizeTmpLeaks,+ testTmpDir+} from './test-tmp'++const REPO = path.join(__dirname, '..', '..')++describe('the temp sandbox is in effect', () => {+ it('points os.tmpdir() at the run-wide sandbox', () => {+ const sandbox = process.env[TMP_SANDBOX_ENV]+ expect(sandbox, 'globalSetup did not create the temp sandbox').toBeTruthy()+ expect(fs.existsSync(sandbox!)).toBe(true)+ expect(fs.realpathSync(os.tmpdir())).toBe(fs.realpathSync(sandbox!))+ })++ it('is wired in vitest.config.ts: globalSetup AND the worker setup file', () => {+ const cfg = fs.readFileSync(path.join(REPO, 'vitest.config.ts'), 'utf8')+ expect(cfg).toMatch(/globalSetup:\s*\[[^\]]*'test\/setup\/tmp-sandbox\.ts'/)+ expect(cfg).toMatch(/setupFiles:\s*\[[^\]]*'test\/setup\/tmp-worker-env\.ts'/)+ })+})++describe('testTmpDir', () => {+ it('creates inside the sandbox and removeTestTmpDirs removes it', () => {+ const dir = testTmpDir('nt-guard-')+ fs.writeFileSync(path.join(dir, 'f'), 'x')+ expect(path.dirname(dir)).toBe(os.tmpdir())+ expect(path.basename(dir)).toMatch(/^nt-guard-/)+ removeTestTmpDirs()+ expect(fs.existsSync(dir)).toBe(false)+ })++ it('the file-end sweep removes a dir a late write recreated after the first pass', async () => {+ const dir = testTmpDir('nt-guard-late-')+ // A fire-and-forget writer whose `mkdir -p` lands just after the first pass.+ const late = setTimeout(() => fs.mkdirSync(path.join(dir, 'terminal-scrollback'), { recursive: true }), 1)+ await sweepTestTmpDirs()+ clearTimeout(late)+ expect(fs.existsSync(dir)).toBe(false)+ })++ it('leaves directories it did not create alone', () => {+ const mine = fs.mkdtempSync(path.join(os.tmpdir(), 'nt-guard-own-'))+ try {+ testTmpDir('nt-guard-')+ removeTestTmpDirs()+ expect(fs.existsSync(mine)).toBe(true)+ } finally {+ fs.rmSync(mine, { recursive: true, force: true })+ }+ })+})++describe('the leak report', () => {+ it('counts our entries and ignores the listed foreign ones', () => {+ const names = [+ 'nodeterm-fake-AbC123',+ 'com.google.Chrome.chrome_chrome_url_fetcher_.xR7FmX',+ '.com.google.Chrome.D6OnlZ',+ 'svc-q1w2e3'+ ]+ expect(leakedTmpEntries(names)).toEqual(['nodeterm-fake-AbC123', 'svc-q1w2e3'])+ })++ it('groups by prefix, most frequent first', () => {+ const out = summarizeTmpLeaks(['svc-aaaaaa', 'svc-bbbbbb', 'ssh-store-cccccc'])+ const lines = out.split('\n').map((l) => l.trim())+ expect(lines).toEqual(['2 svc-*', '1 ssh-store-*'])+ })++ it('every foreign entry says why it is allowed', () => {+ for (const f of FOREIGN_TMP_ENTRIES) expect(f.why.length).toBeGreaterThan(20)+ })+})diff --git a/src/core/test-tmp.ts b/src/core/test-tmp.tsnew file mode 100644index 000000000..9f5aee600--- /dev/null+++ b/src/core/test-tmp.ts@@ -0,0 +1,123 @@+// TEST-ONLY — the vitest run's temp-directory hygiene.+//+// The suite used to leave its scratch directories behind in the OS temp dir: every full run added+// ~1,560 top-level entries (1,412 of them `nodeterm-fake-*` from `fakePlatform()` alone), and on a+// shared dev box that accumulated to ~41k entries in `/tmp` until the filesystem ran out of INODES —+// which broke every other session's builds and tests on the machine, not just this repo's.+//+// Two layers, and both are needed:+// 1. `testTmpDir(prefix)` — a `mkdtemp` that is removed after the test FILE finishes (the+// `afterAll` lives in `test/setup/tmp-worker-env.ts`, so it runs even when a test failed, and+// after the file's own `afterAll` hooks have stopped whatever servers were writing there).+// Suites use it, or clean up their own `mkdtemp` in `afterEach`/`afterAll`/`finally`.+// 2. The run-wide sandbox: `test/setup/tmp-sandbox.ts` points `os.tmpdir()` at one private+// directory for the whole run and, at teardown, FAILS the run naming anything still in it —+// then removes it regardless. That is the regression guard: a new leak is reported by the run+// that introduced it, grouped by prefix, and it can never again reach the shared `/tmp`.+//+// Lives in `src/core` (like `platform-fake.ts` and `tmux-test-socket.ts`) because that is what the+// suites and the guard test can import — `test/` is outside every tsconfig project.+import fs from 'fs'+import os from 'os'+import path from 'path'++/** How the sandbox path reaches the workers, separately from `TMPDIR` itself: a worker must be able+ * to tell "this run set it up" from "the developer already had TMPDIR exported". */+export const TMP_SANDBOX_ENV = 'NODETERM_TEST_TMPDIR'++/**+ * Point this process — and every worker and child it spawns — at `dir` as its temp directory.+ * `os.tmpdir()` reads `TMPDIR` on POSIX and `TEMP`/`TMP` on Windows, at every call, so this also+ * redirects directories created later in the same process.+ */+export function enterTmpSandbox(dir: string): void {+ process.env[TMP_SANDBOX_ENV] = dir+ process.env.TMPDIR = dir+ if (process.platform === 'win32') {+ process.env.TEMP = dir+ process.env.TMP = dir+ }+}++const tracked = new Set<string>()++/**+ * `mkdtemp(<os.tmpdir()>/<prefix>XXXXXX)`, removed automatically when the current test file ends.+ * Use this instead of a bare `mkdtempSync(path.join(os.tmpdir(), …))` in a test.+ */+export function testTmpDir(prefix: string): string {+ const dir = fs.mkdtempSync(path.join(os.tmpdir(), prefix))+ tracked.add(dir)+ return dir+}++/** Remove every directory `testTmpDir` handed out in this module instance. Never throws. */+export function removeTestTmpDirs(): void {+ for (const dir of tracked) {+ rmQuietly(dir)+ tracked.delete(dir)+ }+}++/** How long the file-end sweep waits before its second pass. */+export const LATE_WRITE_GRACE_MS = 25++/**+ * The file-end sweep: remove, let already-queued I/O settle, remove again. The second pass is for+ * fire-and-forget writers still in flight when the file's last test ended — the scrollback+ * snapshot, an agent-status save — whose `mkdir -p` recreates a directory the first pass had just+ * removed (measured: `pty-single-user.test.ts` left one about one full run in six). The wait is paid+ * only by a file that handed out a directory.+ */+export async function sweepTestTmpDirs(): Promise<void> {+ const dirs = [...tracked]+ removeTestTmpDirs()+ if (dirs.length === 0) return+ await new Promise((resolve) => setTimeout(resolve, LATE_WRITE_GRACE_MS))+ for (const dir of dirs) rmQuietly(dir)+}++/**+ * `rm -rf` that tolerates the transient holders a temp tree meets — a child process still exiting,+ * and on Windows Defender or the indexer holding a file we just wrote (EBUSY/EPERM). Best effort:+ * a cleanup failure must not fail the test it follows; the run-wide sandbox still catches it.+ */+export function rmQuietly(target: string): void {+ try {+ fs.rmSync(target, { recursive: true, force: true, maxRetries: 5, retryDelay: 50 })+ } catch {+ /* reported, if it matters, by the sandbox's teardown */+ }+}++/**+ * Entries that are allowed to remain in the sandbox because nothing in this repo creates them.+ * Kept short, each with its reason — an entry that means "we'll fix it later" belongs in an issue.+ */+export const FOREIGN_TMP_ENTRIES: ReadonlyArray<{ pattern: RegExp; why: string }> = [+ {+ pattern: /^\.?com\.google\.Chrome\./,+ why: "Chrome's own scratch files (`com.google.Chrome.*`, hidden `.com.google.Chrome.*`), left by the headless browser `scripts/terminal-fit-layout.test.ts` drives"+ }+]++/** The sandbox entries that count as leaks: everything except `FOREIGN_TMP_ENTRIES`. */+export function leakedTmpEntries(names: readonly string[]): string[] {+ return names.filter((n) => !FOREIGN_TMP_ENTRIES.some((f) => f.pattern.test(n))).sort()+}++/**+ * Group leaked names by their prefix (the `mkdtemp` random tail stripped), most frequent first, so+ * the failure message points straight at the `mkdtemp(<prefix>)` call that needs a cleanup.+ */+export function summarizeTmpLeaks(names: readonly string[]): string {+ const counts = new Map<string, number>()+ for (const n of names) {+ const prefix = n.replace(/[A-Za-z0-9]{6}$/, '') || n+ counts.set(prefix, (counts.get(prefix) ?? 0) + 1)+ }+ return [...counts.entries()]+ .sort((a, b) => b[1] - a[1] || a[0].localeCompare(b[0]))+ .map(([prefix, n]) => ` ${String(n).padStart(5)} ${prefix}*`)+ .join('\n')+}diff --git a/src/main/codex-relay-daemon.test.ts b/src/main/codex-relay-daemon.test.tsindex eec1156ef..9d5a74726 100644--- a/src/main/codex-relay-daemon.test.ts+++ b/src/main/codex-relay-daemon.test.ts@@ -38,6 +38,7 @@ import {type RelayThreadRequest} from './codex-relay-daemon'import { posixQuote } from '../shared/ssh'+import { testTmpDir } from '../core/test-tmp'async function fakeCodexServer(socketPath: string,@@ -555,7 +556,7 @@ describe('Codex shared relay thread observation', () => {})it('reclaims a dead lock but never steals one owned by a live process', () => {- const dir = mkdtempSync(path.join(tmpdir(), 'nodeterm-relay-lock-'))+ const dir = testTmpDir('nodeterm-relay-lock-')const lock = path.join(dir, 'relay.lock')writeFileSync(lock, '99999999\n')expect(acquireProcessLock(lock)).toBe(true)@@ -564,7 +565,7 @@ describe('Codex shared relay thread observation', () => {})it('never steals a freshly created directory lock before its owner pid is written', () => {- const dir = mkdtempSync(path.join(tmpdir(), 'nodeterm-relay-lock-race-'))+ const dir = testTmpDir('nodeterm-relay-lock-race-')const lock = path.join(dir, 'relay.lock')mkdirSync(lock)expect(acquireProcessLock(lock)).toBe(false)diff --git a/src/main/peer-registry.test.ts b/src/main/peer-registry.test.tsindex bb334bc7a..6c1af3978 100644--- a/src/main/peer-registry.test.ts+++ b/src/main/peer-registry.test.ts@@ -1,6 +1,4 @@import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest'-import { mkdtempSync } from 'fs'-import os from 'os'import path from 'path'import {registerPeerSink,@@ -13,6 +11,7 @@ import { presenceHub, allocateRelayClientId } from '../core/presence/hub'import { initPlatform, resetPlatformForTests, type CorePlatform } from '../core/platform'import { IPC } from '../shared/ipc'import { decodePtyData } from '../shared/rpc'+import { testTmpDir } from '../core/test-tmp'/** A fake peer sink that records everything the core pushed at it. */function fakeSink(buffered = () => 0) {@@ -37,7 +36,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: testTmpDir('nodeterm-peer-registry-'),appVersion: '0.0.0',isPackaged: false,handle: () => {},diff --git a/src/main/remote/hosted-join.test.ts b/src/main/remote/hosted-join.test.tsindex b792cef6b..0b447285e 100644--- a/src/main/remote/hosted-join.test.ts+++ b/src/main/remote/hosted-join.test.ts@@ -5,7 +5,6 @@// 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 fs from 'node:fs'-import os from 'node:os'import path from 'node:path'import { joinHostedTeam, connectHostedTeam, removeHostedBookmark, createHostedJoinState, HostedJoinError, type HostedJoinDeps, type HostedJoinEvents, type HostedConnectOptions, type HostedJoinFailure } from './hosted-join'import { joinErrorCode, joinRetryAfterMs } from '../../shared/relay-join-errors'@@ -20,8 +19,9 @@ import type { PeerAttach } from '../../core/relay/relay-host'import type { RelayTransport } from '../../core/relay/relay-socket'import { IPC } from '../../shared/ipc'import { relayPtyDataKey } from '../../shared/relay-pty-channel'+import { testTmpDir } from '../../core/test-tmp'-const tmpDir = () => fs.mkdtempSync(path.join(os.tmpdir(), 'hosted-join-'))+const tmpDir = () => testTmpDir('hosted-join-')const pub = (k: KeyPair) => publicKeyToB64(k.publicKey)function codeFor(hostKeys: KeyPair, over: Partial<JoinCode> = {}): JoinCode {diff --git a/src/main/remote/relay-bookmarks.test.ts b/src/main/remote/relay-bookmarks.test.tsindex 6864ccefd..27fa9b3d2 100644--- a/src/main/remote/relay-bookmarks.test.ts+++ b/src/main/remote/relay-bookmarks.test.ts@@ -1,11 +1,11 @@// src/main/remote/relay-bookmarks.test.tsimport { describe, it, expect } from 'vitest'import fs from 'node:fs'-import os from 'node:os'import path from 'node:path'import { BookmarkStore, publicBookmark, type RelayBookmark } from './relay-bookmarks'+import { testTmpDir } from '../../core/test-tmp'-const tmpFile = () => path.join(fs.mkdtempSync(path.join(os.tmpdir(), 'bm-')), 'relay-bookmarks.json')+const tmpFile = () => path.join(testTmpDir('bm-'), 'relay-bookmarks.json')const b: RelayBookmark = { hostId: 'H', code: 'nodeterm://join?code=x', label: 'box', deviceToken: null, approvedAt: null, source: 'code' }describe('relay bookmarks', () => {diff --git a/src/main/ssh-store.test.ts b/src/main/ssh-store.test.tsindex 485da8b28..bb5ca3e0b 100644--- a/src/main/ssh-store.test.ts+++ b/src/main/ssh-store.test.ts@@ -1,11 +1,10 @@import { describe, expect, it } from 'vitest'-import { promises as fs } from 'node:fs'-import os from 'node:os'import path from 'node:path'import { SshStore } from './ssh-store'+import { testTmpDir } from '../core/test-tmp'async function tmpFile(): Promise<string> {- const dir = await fs.mkdtemp(path.join(os.tmpdir(), 'ssh-store-'))+ const dir = testTmpDir('ssh-store-')return path.join(dir, 'ssh-servers.json')}diff --git a/test/acceptance/open-project-chain.test.ts b/test/acceptance/open-project-chain.test.tsindex af9c09e1c..ca32f8de6 100644--- a/test/acceptance/open-project-chain.test.ts+++ b/test/acceptance/open-project-chain.test.ts@@ -1,6 +1,5 @@import { describe, it, expect, beforeEach } from 'vitest'import fs from 'node:fs'-import os from 'node:os'import path from 'node:path'import { useProjects } from '../../src/renderer/state/projects'import {@@ -21,6 +20,7 @@ import {gateOpenProject,PROJECT_TARGET_REFUSED} from '../../src/core/project-grants'+import { testTmpDir } from '../../src/core/test-tmp'/*** Issue #338 Task 2.5 — THE CHAIN, once, against real primitives on both sides of the boundary:@@ -47,7 +47,7 @@ let repoA = ''beforeEach(() => {clearAllGrants()clearAttachConsentForTests()- repoA = fs.mkdtempSync(path.join(os.tmpdir(), 'i338-chain-')) + '/repoA'+ repoA = testTmpDir('i338-chain-') + '/repoA'fs.mkdirSync(repoA)useProjects.getState().hydrate({version: 2,diff --git a/test/setup/tmp-sandbox.ts b/test/setup/tmp-sandbox.tsnew file mode 100644index 000000000..bb130992a--- /dev/null+++ b/test/setup/tmp-sandbox.ts@@ -0,0 +1,79 @@+// TEST-ONLY — the run-wide temp sandbox and the leak guard. See `src/core/test-tmp.ts` for why.+//+// `setup` runs in vitest's main process before any worker exists, so every worker — and every child+// process a test spawns with the inherited environment — sees `os.tmpdir()` resolve INSIDE one+// private directory. `teardown` runs after every worker is done: whatever is still in there is a+// directory some test created and never removed, and the run FAILS (non-zero exit) naming it by+// prefix. The sandbox+// is removed either way, so a leak costs this run a red result instead of costing the machine inodes.+//+// Registered AFTER `tmux-sandbox.ts` on purpose: that sandbox is created from the real temp dir,+// where its socket-length budget was measured, not from inside this one.+//+// Windows: the sandbox is still entered and removed, but leftovers are reported as a warning rather+// than a failure. A file a just-exited child still holds (or Defender is scanning) is EBUSY there for+// a moment after the test that created it cleaned up, which is a false leak this guard cannot tell+// apart from a real one; the POSIX runs (ubuntu CI + every dev box) carry the enforcement.+import fs from 'fs'+import os from 'os'+import path from 'path'+import {+ TMP_SANDBOX_ENV,+ enterTmpSandbox,+ leakedTmpEntries,+ rmQuietly,+ summarizeTmpLeaks+} from '../../src/core/test-tmp'++let dir: string | null = null+let saved: Record<string, string | undefined> = {}++export async function setup(): Promise<void> {+ saved = {+ TMPDIR: process.env.TMPDIR,+ TEMP: process.env.TEMP,+ TMP: process.env.TMP,+ [TMP_SANDBOX_ENV]: process.env[TMP_SANDBOX_ENV]+ }+ // Short prefix: tests bind unix sockets under os.tmpdir(), and macOS allows only 103 characters.+ dir = fs.realpathSync(fs.mkdtempSync(path.join(os.tmpdir(), 'ntvt-')))+ enterTmpSandbox(dir)+}++export async function teardown(): Promise<void> {+ if (!dir) return+ const sandbox = dir+ dir = null+ let names: string[] = []+ try {+ names = fs.readdirSync(sandbox)+ } catch {+ /* already gone */+ }+ for (const [k, v] of Object.entries(saved)) {+ if (v === undefined) delete process.env[k]+ else process.env[k] = v+ }+ // NODETERM_TEST_KEEP_TMP=1 keeps the sandbox so the leftovers can be inspected (their contents+ // usually name the writer); its path is printed with the report.+ const keep = process.env.NODETERM_TEST_KEEP_TMP === '1'+ if (!keep) rmQuietly(sandbox)+ const leaked = leakedTmpEntries(names)+ if (leaked.length === 0) return+ const message =+ `the test run left ${leaked.length} entr${leaked.length === 1 ? 'y' : 'ies'} in its temp dir ` ++ `(without the sandbox every one would have stayed in the shared OS temp dir):\n` ++ summarizeTmpLeaks(leaked) ++ (keep ? `\nKept for inspection: ${sandbox}` : '\nRe-run with NODETERM_TEST_KEEP_TMP=1 to inspect them.') ++ '\nClean each up where it is created: testTmpDir() from src/core/test-tmp.ts, or an ' ++ 'rmSync(dir, { recursive: true, force: true }) in afterEach/afterAll/finally.'+ if (process.platform === 'win32') {+ console.warn(`[tmp-sandbox] ${message}`)+ return+ }+ // Not `throw`: vitest only LOGS a teardown error ("error during close") and still exits 0, and a+ // throw here would also skip the other globalSetup teardowns (the tmux sandbox's). Setting the+ // exit code is what actually turns the run red, locally and in CI.+ console.error(`\n[tmp-sandbox] FAIL: ${message}\n`)+ process.exitCode = 1+}diff --git a/test/setup/tmp-worker-env.ts b/test/setup/tmp-worker-env.tsnew file mode 100644index 000000000..11e63a740--- /dev/null+++ b/test/setup/tmp-worker-env.ts@@ -0,0 +1,25 @@+// TEST-ONLY — the worker half of the temp sandbox; see `tmp-sandbox.ts` and `src/core/test-tmp.ts`.+//+// Re-asserts the sandbox inside each worker (the environment inheritance from `globalSetup` is+// vitest's implementation detail, not its contract — same reasoning as `tmux-worker-env.ts`), and+// registers the per-file cleanup for `testTmpDir()`. A setup file's `afterAll` sits on the file's+// root suite and — with vitest's default stacked hook order — runs AFTER the file's own `afterAll`+// hooks, i.e. after a suite has stopped the servers and children that were writing into its dirs.+// The sweep's second pass catches a fire-and-forget write that recreated a dir after the first.+import fs from 'fs'+import { afterAll } from 'vitest'+import { TMP_SANDBOX_ENV, enterTmpSandbox, sweepTestTmpDirs } from '../../src/core/test-tmp'++const sandbox = process.env[TMP_SANDBOX_ENV]+if (!sandbox || !fs.existsSync(sandbox)) {+ throw new Error(+ `temp sandbox missing (${TMP_SANDBOX_ENV}=${sandbox ?? 'unset'}). vitest.config.ts must keep ` ++ 'test/setup/tmp-sandbox.ts in `globalSetup` — without it the suite writes its scratch ' ++ 'directories straight into the shared OS temp dir.'+ )+}+enterTmpSandbox(sandbox)++afterAll(async () => {+ await sweepTestTmpDirs()+})diff --git a/vitest.config.ts b/vitest.config.tsindex 9631acb70..a037f0e8e 100644--- a/vitest.config.ts+++ b/vitest.config.ts@@ -31,9 +31,18 @@ export default defineConfig({// it inside each worker (and refuses if it is missing). See test/setup/tmux-sandbox.ts.// `fake-platform-root.ts` gives the run one parent directory for every `fakePlatform()`// userDataDir and removes it at the end — before it, each call leaked a directory in /tmp.- // Listed FIRST: teardowns run in reverse, so it tears down after the tmux sandbox.- globalSetup: ['test/setup/fake-platform-root.ts', 'test/setup/tmux-sandbox.ts'],- setupFiles: ['test/setup/tmux-worker-env.ts'],+ // Listed FIRST: teardowns run in reverse, so it tears down after the tmux sandbox — and it is+ // created before the temp sandbox exists, so its root is never counted as a leak there.+ //+ // The temp sandbox does the same for `os.tmpdir()`: the whole run writes its scratch dirs into+ // one private directory, and teardown FAILS the run naming any test dir left in it (then removes+ // it). The suite used to strand ~1,500 dirs in /tmp per run. See src/core/test-tmp.ts.+ globalSetup: [+ 'test/setup/fake-platform-root.ts',+ 'test/setup/tmux-sandbox.ts',+ 'test/setup/tmp-sandbox.ts'+ ],+ setupFiles: ['test/setup/tmux-worker-env.ts', 'test/setup/tmp-worker-env.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