Skip to content

The ultimate harness for coding agents and beyond. All your agents. All your machines. One command center. Start with code, then follow your curiosity and build across disciplines: CAD, circuits, robots, games and music.

Specs that failed under load wait on what they test; the suite runs in a throwaway home (#965)

Dee14a744e55c93
diff --git a/cli/src/config/envIsolation.spec.ts b/cli/src/config/envIsolation.spec.ts
index 5cc90cbdd..f77aa87b8 100644
--- a/cli/src/config/envIsolation.spec.ts
+++ b/cli/src/config/envIsolation.spec.ts
@@ -7,8 +7,9 @@
* managed runtime BEFORE PATH, by design), so the suite would measure this machine's managed
* binaries instead of the code under test.
*/
-import { homedir } from 'node:os'
-import { join } from 'node:path'
+import { realpathSync } from 'node:fs'
+import { homedir, tmpdir } from 'node:os'
+import { join, sep } from 'node:path'
import { describe, expect, it } from 'vitest'
import { env } from './env.js'
import { AUTH_DIR } from '../lib/authSession.js'
@@ -16,6 +17,16 @@ import { AUTH_DIR } from '../lib/authSession.js'
const productRoot = join(homedir(), '.harness')
describe('test environment isolation', () => {
+ // The home folder is the suite's own (vitest.setup.ts), so every default rooted there is too: a spec that
+ // named no folder of its own read the developer's ~/.claude, ~/.codex and ~/.harness before it was.
+ it('runs in a throwaway home folder, so no default folder of an engine or of Harness is the developer\'s', () => {
+ const inTemp = (path: string) => realpathSync(path).startsWith(realpathSync(tmpdir()) + sep)
+ expect(inTemp(homedir())).toBe(true)
+ for (const folder of [env.CLAUDE_PROJECTS_DIR, env.CODEX_HOME, env.CURSOR_HOME, env.GROK_HOME, env.COPILOT_HOME, env.HERMES_HOME, env.OPENCODE_DATA_DIR]) {
+ expect(folder.startsWith(homedir() + sep), folder).toBe(true)
+ }
+ })
+
it('keeps the data dir off the developer\'s ~/.harness', () => {
expect(env.ADAPTER_DATA_DIR.startsWith(productRoot)).toBe(false)
})
diff --git a/cli/src/harnessd/master.spec.ts b/cli/src/harnessd/master.spec.ts
index d8aca1559..ebe0ac9bc 100644
--- a/cli/src/harnessd/master.spec.ts
+++ b/cli/src/harnessd/master.spec.ts
@@ -290,6 +290,11 @@ describe('runMaster', { timeout: 60_000 }, () => {
afterEach(() => { rmSync(dir, { recursive: true, force: true }); process.title = title })
/** Wait for [test] to hold. The deadline only names what never came, well before the test's own. */
+ /** What the children appended to [path] so far, one JSON line each: whole lines only. Polled while they
+ * run, so a line still being appended is not read half-written (and thrown on as JSON). */
+ const jsonLines = <T = Record<string, any>>(path: string): T[] =>
+ existsSync(path) ? readFileSync(path, 'utf8').split('\n').slice(0, -1).map((line) => JSON.parse(line) as T) : []
+
const until = async (what: string, test: () => boolean, ms = 30_000) => {
const deadline = Date.now() + ms
while (!test()) {
@@ -307,8 +312,12 @@ describe('runMaster', { timeout: 60_000 }, () => {
const ran = join(dir, 'ran')
const core = join(dir, 'core.cjs')
writeFileSync(core, `
- // The services run this script too (as \`__service <name>\`); each records its own.
- require('node:fs').writeFileSync(${JSON.stringify(ran)} + (process.argv[3] ?? ''), process.execPath)
+ // The services run this script too (as \`__service <name>\`); each records its own. Written whole, then
+ // renamed: the test waits for the file to exist, and once read it empty, a service caught between the
+ // write's create and its bytes on a loaded machine.
+ const fs = require('node:fs'), mine = ${JSON.stringify(ran)} + (process.argv[3] ?? '')
+ fs.writeFileSync(mine + '.tmp', process.execPath)
+ fs.renameSync(mine + '.tmp', mine)
process.send({ type: 'harnessd:bound', protocol: ${HARNESSD_PROTOCOL}, port: 1 })
process.send({ type: 'harnessd:ready' })
// A device: the core asks for the devices' process, which runs only on demand.
@@ -476,7 +485,7 @@ describe('runMaster', { timeout: 60_000 }, () => {
env: { ...process.env, HARNESSD_SERVICES: 'search,unknown,monitor,usage', HARNESSD_SERVICE_INITIAL_BACKOFF_MS: '10' },
exit: (code) => exits.push(code), onSignal: (signal, listener) => signals.set(signal, listener),
})
- const lines = (): Array<Record<string, any>> => existsSync(seen) ? readFileSync(seen, 'utf8').trim().split('\n').map((line) => JSON.parse(line)) : []
+ const lines = (): Array<Record<string, any>> => jsonLines(seen)
await until('the crashed service to be restarted', () => lines().filter((line) => line.role === 'service:search').length === 2)
// The light services share one process, the edge host, which runs each of those named.
await until('the edge host to start', () => lines().some((line) => line.role === 'service:usage,monitor'))
@@ -523,7 +532,7 @@ describe('runMaster', { timeout: 60_000 }, () => {
env: { ...process.env, HARNESSD_SERVICES: 'none', HARNESSD_UPDATE_PROBATION_MS: '50' },
exit: (code) => exits.push(code), onSignal: (signal, listener) => signals.set(signal, listener),
})
- const said = (): Array<Record<string, string>> => existsSync(seen) ? readFileSync(seen, 'utf8').trim().split('\n').map((line) => JSON.parse(line)) : []
+ const said = (): Array<Record<string, string>> => jsonLines(seen)
await until('the core to hand over and a new one to start', () => said().filter((line) => line.role === '__run' && line.what === 'started').length === 2)
expect(said().filter((line) => line.role.startsWith('service:')).map((line) => line.role)).toEqual(['service:updater'])
expect(said()).toContainEqual({ role: '__run', what: 'asked for 9.9.9', restarts: '0' })
@@ -605,7 +614,7 @@ describe('runMaster', { timeout: 60_000 }, () => {
env: { ...process.env, HARNESSD_SERVICES: 'search' },
exit: (code) => exits.push(code), onSignal: (signal, listener) => signals.set(signal, listener),
})
- const roles = (): Array<Record<string, string>> => existsSync(seen) ? readFileSync(seen, 'utf8').trim().split('\n').map((line) => JSON.parse(line)) : []
+ const roles = (): Array<Record<string, string>> => jsonLines(seen)
await until('the core and the service', () => roles().length >= 2)
expect(roles().sort((a, b) => a.role.localeCompare(b.role))).toEqual([{ role: '__run', from: 'lean core', cli }, { role: 'service:search', from: 'lean', cli: null }])
expect(lines.some((line) => line.endsWith(`[harnessd] services run from ${lean}`))).toBe(true)
@@ -679,7 +688,7 @@ describe('runMaster', { timeout: 60_000 }, () => {
const log = vi.spyOn(console, 'log').mockImplementation((line: string) => { lines.push(line) })
const exits: number[] = []
const signals = new Map<string, () => void>()
- const services = (): Array<{ from: string; pid: number }> => (existsSync(seen) ? readFileSync(seen, 'utf8').trim().split('\n').map((line) => JSON.parse(line)) : [])
+ const services = (): Array<{ from: string; pid: number }> => jsonLines<{ role: string; from: string; pid: number }>(seen)
.filter((line) => line.role === 'service:search')
/** End the service running now, and wait for the master to start the next: where it started it from. */
const restart = async (): Promise<string> => {
diff --git a/cli/src/lib/autonomous-device/direct.spec.ts b/cli/src/lib/autonomous-device/direct.spec.ts
index fc34fce0a..342704f17 100644
--- a/cli/src/lib/autonomous-device/direct.spec.ts
+++ b/cli/src/lib/autonomous-device/direct.spec.ts
@@ -53,19 +53,33 @@ describe('direct Autonomous device endpoint selection', () => {
await expect(f.direct.pair(f.row.id, 'CODE12')).rejects.toThrow('session did not authenticate')
expect(f.direct.connected()).toBe(0)
})
+ // The link's idle deadline runs on a fake clock, moved only here: the sockets and the pings stay real. Against
+ // the real clock, pings every 30 ms missed a 100 ms deadline under load (12 busy loops, load 40), and the
+ // pinged link was torn down as silent.
it('terminates a silent link and reconnects, while a pinged link stays open', async () => {
const f = await fixture(); await f.direct.pair(f.row.id, 'CODE12'); f.direct.stop()
await new Promise(resolve => setTimeout(resolve, 20))
const sockets: import('ws').WebSocket[] = []
f.wss.removeAllListeners('connection'); f.wss.on('connection', ws => sockets.push(ws))
+ const settled = async (test: () => boolean) => { while (!test()) await new Promise(resolve => setImmediate(resolve)) }
+ vi.useFakeTimers({ toFake: ['setTimeout', 'clearTimeout'] }); clean.push(() => vi.useRealTimers())
const quiet = new AutonomousDeviceDirect(f.host, f.dir, f.discovery, 100); clean.unshift(() => quiet.stop()); quiet.start()
- await vi.waitFor(() => expect(sockets).toHaveLength(1))
- await vi.waitFor(() => expect(sockets[0].readyState).toBe(sockets[0].CLOSED), { timeout: 1000 })
- expect(quiet.connected()).toBe(0)
+ await settled(() => sockets.length === 1 && quiet.connected() === 1)
+ // Silent: nothing heard for the idle time, and the link is torn down.
+ vi.advanceTimersByTime(99)
+ expect(quiet.connected()).toBe(1)
+ vi.advanceTimersByTime(1)
+ await once(sockets[0], 'close')
+ await settled(() => quiet.connected() === 0)
;(quiet as unknown as { reconnect: () => Promise<void> }).reconnect()
- await vi.waitFor(() => expect(sockets).toHaveLength(2))
- const ping = setInterval(() => { for (const ws of sockets) if (ws.readyState === ws.OPEN) ws.ping() }, 30); clean.push(() => clearInterval(ping))
- await new Promise(resolve => setTimeout(resolve, 400))
+ await settled(() => sockets.length === 2 && quiet.connected() === 1)
+ // Pinged: each ping heard (its pong back) before 60 ms pass, ten times over, 600 ms in all; the link stays.
+ for (let n = 0; n < 10; n++) {
+ const pong = once(sockets[1], 'pong')
+ sockets[1].ping()
+ await pong
+ vi.advanceTimersByTime(60)
+ }
expect(sockets[1].readyState).toBe(sockets[1].OPEN)
expect(quiet.connected()).toBe(1)
})
diff --git a/cli/src/lib/codexProfiles.test.ts b/cli/src/lib/codexProfiles.test.ts
index 6a9ac7b0e..4b8325571 100644
--- a/cli/src/lib/codexProfiles.test.ts
+++ b/cli/src/lib/codexProfiles.test.ts
@@ -1,5 +1,5 @@
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
-import { mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'fs'
+import { mkdirSync, mkdtempSync, readFileSync, realpathSync, rmSync, writeFileSync } from 'fs'
import { homedir, tmpdir } from 'os'
import { join } from 'path'
import type * as CodexProfilesModule from './codexProfiles.js'
@@ -18,10 +18,11 @@ const emptyDiscovery = { home: '/nonexistent-empty-home', environment: {} }
describe('codexProfiles', () => {
beforeEach(() => {
dataDir = mkdtempSync(join(tmpdir(), 'codex-profiles-data-'))
- // Under the real home, not os.tmpdir(): resolveCodexProfilePath realpath-resolves everything it
- // returns, and macOS's tmpdir sits behind a /var → /private/var symlink that would otherwise
- // make the resolved path disagree with the literal folder these tests just created.
- home = mkdtempSync(join(homedir(), '.codex-profiles-test-'))
+ // By its real path: resolveCodexProfilePath realpath-resolves everything it returns, and macOS's
+ // tmpdir sits behind a /var → /private/var symlink that would otherwise make the resolved path
+ // disagree with the literal folder these tests just created. In the suite's own home folder
+ // (vitest.setup.ts): this once made and removed folders in the developer's.
+ home = realpathSync(mkdtempSync(join(homedir(), '.codex-profiles-test-')))
})
afterEach(() => {
diff --git a/cli/src/lib/e2ee/relayLink.spec.ts b/cli/src/lib/e2ee/relayLink.spec.ts
index 46d0ab995..fa84302e7 100644
--- a/cli/src/lib/e2ee/relayLink.spec.ts
+++ b/cli/src/lib/e2ee/relayLink.spec.ts
@@ -11,6 +11,10 @@ import type { AddressInfo } from 'net'
// above exists to keep out until ADAPTER_DATA_DIR is set.
import { PW_SCRYPT_TEST_TIMEOUT_MS } from './passwordPake.js'
+/** How long a joiner waits for its claim: its own scrypt and the manager's both run inside it. No case is
+ * about this deadline; at 5 s the two scrypts ran past it under load. Inside each case's budget. */
+const CLAIM_TIMEOUT_MS = 20_000
+
// Same reason as manager.test.ts: ADAPTER_DATA_DIR must be set before any transitive import of
// config/env.js, so every module under test is dynamically imported after the temp dir is set.
type Frame = Record<string, unknown>
@@ -56,7 +60,10 @@ describe('MachinePeerStore', () => {
})
})
-describe('remote-password link + relay session crypto (interop with the real E2eeManager)', () => {
+// Every password case runs at least two real scrypts, the manager's (`setRemotePassword`) and the joiner's
+// (`connectWithPassword`): PW_SCRYPT_TEST_TIMEOUT_MS for all of them, as manager.test.ts gives its own.
+// The ones without it timed out at vitest's 5 s under load (the full unit suite at load 36 and 100).
+describe('remote-password link + relay session crypto (interop with the real E2eeManager)', { timeout: PW_SCRYPT_TEST_TIMEOUT_MS }, () => {
it('connectWithPassword pins the correct adapter pubkey, then hello/welcome + frame/terminal round-trip succeed', async () => {
const inbox: Frame[] = []
// Fakes just enough of backend's `/api/web-ws` (machine_select -> connected, then generic e2e_*
@@ -102,7 +109,7 @@ describe('remote-password link + relay session crypto (interop with the real E2e
accessToken: 'unused-in-this-fake',
backendWsBase: wsBase,
autonomousEnv: 'prod',
- timeoutMs: 5_000,
+ timeoutMs: CLAIM_TIMEOUT_MS,
})
expect(result.ok).toBe(true)
@@ -289,7 +296,7 @@ describe('remote-password link + relay session crypto (interop with the real E2e
accessToken: 'unused',
backendWsBase: await wsBase,
autonomousEnv: 'prod',
- timeoutMs: 5_000,
+ timeoutMs: CLAIM_TIMEOUT_MS,
self: { kind: 'machine', machineId: JOINER_ID, label: 'studio-mac' },
})
expect(result.ok).toBe(true)
@@ -316,7 +323,7 @@ describe('remote-password link + relay session crypto (interop with the real E2e
accessToken: 'unused',
backendWsBase: await wsBase,
autonomousEnv: 'prod',
- timeoutMs: 5_000,
+ timeoutMs: CLAIM_TIMEOUT_MS,
})
expect(result.ok).toBe(true)
expect(linked).toEqual([{ pub: C.b64e(joiner.pub), kind: undefined, machineId: undefined, label: 'harness link' }])
@@ -340,7 +347,7 @@ describe('remote-password link + relay session crypto (interop with the real E2e
accessToken: 'unused',
backendWsBase: await wsBase,
autonomousEnv: 'prod',
- timeoutMs: 5_000,
+ timeoutMs: CLAIM_TIMEOUT_MS,
self: { kind: 'machine', machineId: '../../etc/passwd' },
})
expect(result.ok).toBe(true)
@@ -400,7 +407,7 @@ describe('remote-password link + relay session crypto (interop with the real E2e
accessToken: 'unused',
backendWsBase: await wsBase,
autonomousEnv: 'prod',
- timeoutMs: 5_000,
+ timeoutMs: CLAIM_TIMEOUT_MS,
})
expect(result).toEqual({ ok: false, error: 'NO_REMOTE_PASSWORD' })
expect(manager.remotePasswordStatus().hasPassword).toBe(false)
@@ -420,7 +427,7 @@ describe('remote-password link + relay session crypto (interop with the real E2e
accessToken: 'unused',
backendWsBase: await wsBase,
autonomousEnv: 'prod',
- timeoutMs: 5_000,
+ timeoutMs: CLAIM_TIMEOUT_MS,
})
expect(result.ok).toBe(false)
if (result.ok) return
@@ -444,7 +451,7 @@ describe('remote-password link + relay session crypto (interop with the real E2e
accessToken: 'unused',
backendWsBase: base,
autonomousEnv: 'prod',
- timeoutMs: 5_000,
+ timeoutMs: CLAIM_TIMEOUT_MS,
})
expect(attempt.ok).toBe(false)
}
@@ -457,7 +464,7 @@ describe('remote-password link + relay session crypto (interop with the real E2e
accessToken: 'unused',
backendWsBase: base,
autonomousEnv: 'prod',
- timeoutMs: 5_000,
+ timeoutMs: CLAIM_TIMEOUT_MS,
})
expect(locked.ok).toBe(false)
expect((locked as { error: string }).error).toBe('RATE_LIMITED')
@@ -481,12 +488,12 @@ describe('remote-password link + relay session crypto (interop with the real E2e
accessToken: 'unused',
backendWsBase: base,
autonomousEnv: 'prod',
- timeoutMs: 5_000,
+ timeoutMs: CLAIM_TIMEOUT_MS,
})
}
const stillLocked = await connectWithPassword({
targetMachineId: MACHINE_ID, password: REMOTE_PASSWORD, selfIdentity: C.newIdentity(),
- accessToken: 'unused', backendWsBase: base, autonomousEnv: 'prod', timeoutMs: 5_000,
+ accessToken: 'unused', backendWsBase: base, autonomousEnv: 'prod', timeoutMs: CLAIM_TIMEOUT_MS,
})
expect(stillLocked.ok).toBe(false)
expect((stillLocked as { error: string }).error).toBe('RATE_LIMITED')
@@ -495,7 +502,7 @@ describe('remote-password link + relay session crypto (interop with the real E2e
await manager.setRemotePassword(NEW_PASSWORD)
const result = await connectWithPassword({
targetMachineId: MACHINE_ID, password: NEW_PASSWORD, selfIdentity: C.newIdentity(),
- accessToken: 'unused', backendWsBase: base, autonomousEnv: 'prod', timeoutMs: 5_000,
+ accessToken: 'unused', backendWsBase: base, autonomousEnv: 'prod', timeoutMs: CLAIM_TIMEOUT_MS,
})
expect(result.ok).toBe(true)
} finally {
@@ -505,7 +512,7 @@ describe('remote-password link + relay session crypto (interop with the real E2e
}, PW_SCRYPT_TEST_TIMEOUT_MS)
})
-describe('RemoteRelayPool drops a peer the responder no longer trusts', () => {
+describe('RemoteRelayPool drops a peer the responder no longer trusts', { timeout: PW_SCRYPT_TEST_TIMEOUT_MS }, () => {
// A fake AuthSessionManager — RemoteRelayPool only ever calls .accessToken({force}).
const fakeAuth = { accessToken: async () => 'unused-in-this-fake' } as unknown as import('../authSession.js').AuthSessionManager
@@ -534,7 +541,7 @@ describe('RemoteRelayPool drops a peer the responder no longer trusts', () => {
const base = `ws://127.0.0.1:${(wss.address() as AddressInfo).port}`
const identity = C.newIdentity()
await manager.setRemotePassword(REMOTE_PASSWORD)
- const claim = await connectWithPassword({ targetMachineId: MACHINE_ID, password: REMOTE_PASSWORD, selfIdentity: identity, accessToken: 'unused', backendWsBase: base, autonomousEnv: 'prod', timeoutMs: 5000 })
+ const claim = await connectWithPassword({ targetMachineId: MACHINE_ID, password: REMOTE_PASSWORD, selfIdentity: identity, accessToken: 'unused', backendWsBase: base, autonomousEnv: 'prod', timeoutMs: CLAIM_TIMEOUT_MS })
expect(claim.ok).toBe(true)
if (!claim.ok) throw new Error('pairing failed')
const peers = new MachinePeerStore(); peers.pin(MACHINE_ID, C.b64e(claim.peerPub), 'test')
@@ -667,7 +674,7 @@ describe('RemoteRelayPool drops a peer the responder no longer trusts', () => {
accessToken: 'unused-in-this-fake',
backendWsBase: `ws://127.0.0.1:${port}`,
autonomousEnv: 'prod',
- timeoutMs: 5_000,
+ timeoutMs: CLAIM_TIMEOUT_MS,
})
expect(claim.ok).toBe(true)
if (!claim.ok) return
@@ -739,7 +746,7 @@ describe('RemoteRelayPool drops a peer the responder no longer trusts', () => {
accessToken: 'unused-in-this-fake',
backendWsBase: `ws://127.0.0.1:${port}`,
autonomousEnv: 'prod',
- timeoutMs: 5_000,
+ timeoutMs: CLAIM_TIMEOUT_MS,
})
expect(claim.ok).toBe(true)
if (!claim.ok) return
@@ -935,9 +942,10 @@ describe('a client\'s sessions with one machine never open the same broadcast tw
const inbox: Frame[] = []
const sink = { sendFrame: (frame: Frame) => { inbox.push(frame); return true }, sendBinary: () => true }
const select = { type: 'machine_select', payload: { machineId: MACHINE_ID } }
- const arrived = async (type: string, count: number) => {
- for (let n = 0; n < 100 && inbox.filter((frame) => frame.type === type).length < count; n++) await new Promise((resolve) => setTimeout(resolve, 20))
- }
+ // Until it is there, however long the machine takes: a count of 100 waits of 20 ms is a clock, and ran out
+ // under load in this file's other session test.
+ const arrived = (type: string, count: number) =>
+ vi.waitFor(() => expect(inbox.filter((frame) => frame.type === type).length).toBeGreaterThanOrEqual(count), { timeout: 20_000, interval: 20 })
try {
await pool.acquire(MACHINE_ID, 'prod', select, sink, () => {})
const started = manager.wrapUp({ type: 'turn_started', agentId: 'a', payload: { userMessage: 'once' } })
@@ -956,7 +964,7 @@ describe('a client\'s sessions with one machine never open the same broadcast tw
for (const ws of wss.clients) ws.terminate()
await new Promise<void>((resolve) => wss.close(() => resolve()))
}
- })
+ }, 30_000)
})
describe('RemoteRelayPool retires a session the machine no longer has', () => {
@@ -986,7 +994,9 @@ describe('RemoteRelayPool retires a session the machine no longer has', () => {
const sink = { sendFrame: () => true, sendBinary: () => true }
try {
const closed = new Promise<number>((resolve) => { void pool.acquire(MACHINE_ID, 'prod', select, sink, (code) => resolve(code)) })
- for (let n = 0; n < 100 && !manager.hasSession('conn-1'); n++) await new Promise((resolve) => setTimeout(resolve, 20))
+ // Until the session is there, however long the machine takes: 100 waits of 20 ms ran out under load (the
+ // six-file run at load 95), and the send below found no socket.
+ await vi.waitFor(() => expect(manager.hasSession('conn-1')).toBe(true), { timeout: 20_000, interval: 20 })
sockets.get('conn-1')!.send(JSON.stringify({ type: 'e2e_session_unknown', payload: { refused: { type: 'message', n: 4 } } }))
expect(await closed).toBe(1012)
expect(peers.get(MACHINE_ID)).toBeDefined()
@@ -998,5 +1008,5 @@ describe('RemoteRelayPool retires a session the machine no longer has', () => {
for (const ws of wss.clients) ws.terminate()
await new Promise<void>((resolve) => wss.close(() => resolve()))
}
- })
+ }, 30_000)
})
diff --git a/cli/src/lib/hookAuth.spec.ts b/cli/src/lib/hookAuth.spec.ts
index 433d0455c..6aabb20f7 100644
--- a/cli/src/lib/hookAuth.spec.ts
+++ b/cli/src/lib/hookAuth.spec.ts
@@ -41,6 +41,10 @@ describe('hook channel credential', () => {
expect(() => loadOrCreateHookCredential(dir)).toThrow('unsafe owner, mode, or type')
})
+ // In a child, because a read that blocked on the FIFO would block this worker for good. The child's
+ // start (node and tsx, compiling hookAuth.ts) is not what is measured: a 1.5 s limit on the whole child
+ // timed it out under load (the full unit suite at load 100) while the read itself returned at once. A
+ // blocked read never returns, so any answer is the proof; the limit only ends a child that blocked.
it('rejects a credential FIFO without blocking', () => {
const dir = mkdtempSync(join(tmpdir(), 'hook-auth-'))
dirs.push(dir)
@@ -50,11 +54,11 @@ describe('hook channel credential', () => {
const result = spawnSync(process.execPath, ['--import', 'tsx', '--eval', script], {
cwd: process.cwd(),
encoding: 'utf8',
- timeout: 1_500,
+ timeout: 60_000,
})
expect(result.error).toBeUndefined()
expect(result.status).toBe(0)
expect(statSync(hookCredentialPath(dir)).isFIFO()).toBe(true)
- })
+ }, 90_000)
})
diff --git a/cli/src/lib/sessionSearch/externals/cursor.spec.ts b/cli/src/lib/sessionSearch/externals/cursor.spec.ts
index c4e45af4c..217cac869 100644
--- a/cli/src/lib/sessionSearch/externals/cursor.spec.ts
+++ b/cli/src/lib/sessionSearch/externals/cursor.spec.ts
@@ -1,12 +1,12 @@
-import { existsSync, mkdirSync, mkdtempSync, readdirSync, realpathSync, rmSync, utimesSync, writeFileSync } from 'node:fs'
+import { existsSync, mkdirSync, mkdtempSync, readdirSync, realpathSync, rmSync, utimesSync, writeFileSync, type Dirent } from 'node:fs'
import { tmpdir } from 'node:os'
-import { join } from 'node:path'
+import { basename, dirname, join } from 'node:path'
import { afterEach, describe, expect, it } from 'vitest'
import { builtinSqlite } from '../../sqliteRead.js'
import { cursorBucket, cursorProvider, cursorSlug, cursorTurnOpen, readChat, type CursorDatabase } from './cursor.js'
-import { scanMemo } from './support.js'
+import { entries, scanMemo } from './support.js'
import type { ProcessView, RunningProcess, ScanContext } from './types.js'
const dirs: string[] = []
@@ -75,10 +75,21 @@ function fakeDatabase(value: unknown, opened: Array<string | URL> = []): CursorD
const hex = (value: unknown) => Buffer.from(JSON.stringify(value)).toString('hex')
+/**
+ * The file system as the walk for a lost folder lists it, with the shared temp folder showing only this
+ * file's own folders. The walk starts at `/`, and on one Mac that folder held 407,422 entries (every run's
+ * leftovers): listing it took the walking cases past 5 s under load. Every other folder is listed as it is.
+ */
+const TMP = realpathSync(tmpdir())
+const listFolder = async (dir: string): Promise<Dirent[]> => dir !== TMP
+ ? entries(dir)
+ // Not listed and filtered: listing it is the cost. This file's folders there are folders, by temp().
+ : dirs.filter((path) => dirname(path) === TMP).map((path) => ({ name: basename(path), isDirectory: () => true }) as Dirent)
+
function roots() {
const config = temp()
const data = temp()
- return { config, data, provider: (database: CursorDatabase | null = null) => cursorProvider({ configDir: config, dataDir: data, database }) }
+ return { config, data, provider: (database: CursorDatabase | null = null) => cursorProvider({ configDir: config, dataDir: data, database, listFolder }) }
}
describe('cursor naming', () => {
diff --git a/cli/src/lib/sessionSearch/externals/cursor.ts b/cli/src/lib/sessionSearch/externals/cursor.ts
index 8d445bc4a..93abaa35c 100644
--- a/cli/src/lib/sessionSearch/externals/cursor.ts
+++ b/cli/src/lib/sessionSearch/externals/cursor.ts
@@ -19,6 +19,7 @@
*/
import { createHash } from 'node:crypto'
+import type { Dirent } from 'node:fs'
import { readFile, realpath, stat } from 'node:fs/promises'
import { basename, dirname, join, resolve } from 'node:path'
import { pathToFileURL } from 'node:url'
@@ -39,6 +40,9 @@ export interface CursorOptions {
dataDir: string
/** How a chat with no `meta.json` has its store read; null when this Node has no SQLite. Tests set it. */
database?: CursorDatabase | null
+ /** How the walk for a lost folder lists a folder; the file system's own (`entries`) unless a test shows it
+ * less: the walk starts at `/`, and a test's folders sit beside every other in a shared temp folder. */
+ listFolder?: (dir: string) => Promise<Dirent[]>
}
/** A chat's own account of itself, from `meta.json` or, when that is missing, its store. */
@@ -191,14 +195,14 @@ async function transcriptOf(
* The folder whose bucket is [bucket] and whose slug is [slug], walked down to from `/` through real
* folders whose slugs lead to it. The md5 decides: a slug alone never names a folder.
*/
-async function walkToFolder(slug: string, bucket: string): Promise<string | null> {
+async function walkToFolder(slug: string, bucket: string, list: (dir: string) => Promise<Dirent[]> = entries): Promise<string | null> {
let reads = WALK_READS
const walk = async (dir: string): Promise<string | null> => {
const own = cursorSlug(dir)
if (own === slug && cursorBucket(dir) === bucket) return dir
if (own && own !== slug && !slug.startsWith(`${own}-`)) return null
if (reads-- <= 0) return null
- for (const entry of await entries(dir)) {
+ for (const entry of await list(dir)) {
if (!entry.isDirectory()) continue
const found = await walk(join(dir, entry.name))
if (found) return found
@@ -292,7 +296,7 @@ export function cursorProvider(options: CursorOptions): ExternalProvider {
const project = (await transcriptOf(options.dataDir, chat.sessionId, null, index))?.project
if (!project || tried.has(project)) continue
tried.add(project)
- const folder = await walkToFolder(project, bucket.name)
+ const folder = await walkToFolder(project, bucket.name, options.listFolder)
if (folder) return folder
}
return null
diff --git a/cli/src/machinesCommand.spec.ts b/cli/src/machinesCommand.spec.ts
index d6488f0a4..a72f03085 100644
--- a/cli/src/machinesCommand.spec.ts
+++ b/cli/src/machinesCommand.spec.ts
@@ -3,7 +3,7 @@ import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from 'fs'
import { tmpdir } from 'os'
import { join } from 'path'
import { fileURLToPath } from 'url'
-import { afterEach, describe, expect, it } from 'vitest'
+import { afterEach, describe, expect, it, vi } from 'vitest'
const CLI_ROOT = fileURLToPath(new URL('..', import.meta.url))
const CLI_SOURCE = join(CLI_ROOT, 'src', 'cli.ts')
@@ -11,6 +11,11 @@ const TSX = join(CLI_ROOT, 'node_modules', 'tsx', 'dist', 'cli.mjs')
const dirs: string[] = []
const MACHINE_ID = 'a'.repeat(32)
+// Each case runs the CLI itself, as a person types it: node, with tsx compiling cli.ts and everything it
+// imports, before the command runs. That start took 1.5 to 2.2 s on a quiet Mac and past vitest's 5 s under
+// 12 busy loops (load 45). cliCommand.spec.ts and loginForceRace.spec.ts give their CLI runs the same room.
+vi.setConfig({ testTimeout: 30_000 })
+
afterEach(() => { for (const dir of dirs.splice(0)) rmSync(dir, { recursive: true, force: true }) })
/**
diff --git a/cli/vitest.setup.ts b/cli/vitest.setup.ts
index 43d30cbcb..21f23a9b3 100644
--- a/cli/vitest.setup.ts
+++ b/cli/vitest.setup.ts
@@ -22,6 +22,22 @@ import { join } from 'node:path'
delete process.env.npm_config_prefix
delete process.env.NPM_CONFIG_PREFIX
+// The home folder itself is a throwaway one, before any module asks for it. Every engine's home, the Harness
+// folder and the machine's identity default to a folder in it (config/env.ts: ~/.claude, ~/.codex, ~/.cursor,
+// ~/.harness/computer-id, …), and a spec that did not name its own read the developer's. Traced on one Mac,
+// 2026-10-06: specs read ~/.claude/settings.json (attachTranscript, runtimeProfile), walked 27 GB of
+// ~/.codex/sessions (homes, sessionRepair), read ~/.codex/config.toml (dsh/runtime), ~/.harness/computer-id
+// (serviceProcess) and ~/.harness/runtime/current-node (hooks). CI's runner has an empty home, so nothing
+// there showed it. A spec that wants a home of its own still sets one.
+process.env.HOME = mkdtempSync(join(tmpdir(), 'adapter-test-home-'))
+// And no engine's or desktop's folder handed down from the shell that ran the suite (a Codex or Claude Code
+// session sets some of these for its own children), which would outrank that home.
+for (const name of [
+ 'CODEX_HOME', 'CLAUDE_CONFIG_DIR', 'CLAUDE_PROJECTS_DIR', 'GROK_HOME', 'COPILOT_HOME', 'CURSOR_HOME', 'CURSOR_CONFIG_DIR',
+ 'CURSOR_DATA_DIR', 'HERMES_HOME', 'PI_HOME', 'PI_CODING_AGENT_DIR', 'PI_CODING_AGENT_SESSION_DIR', 'COMMANDCODE_HOME',
+ 'AGY_HOME', 'AGY_CONFIG_DIR', 'OPENCODE_DB', 'KILO_DB', 'XDG_CONFIG_HOME', 'XDG_DATA_HOME', 'XDG_STATE_HOME',
+]) delete process.env[name]
+
process.env.ADAPTER_DATA_DIR = mkdtempSync(join(tmpdir(), 'adapter-test-data-'))
process.env.ADAPTER_RUNTIME_DIR = mkdtempSync(join(tmpdir(), 'adapter-test-runtime-'))
// Real zsh subprocesses must not load a developer's prompts, plugins, updates,