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.

refactor: add concurrency and queueing directly to AttachTracker

0xken1500b9ef5322c6
diff --git a/cli/src/cli.ts b/cli/src/cli.ts
index 1e85183db..bfd71b800 100644
--- a/cli/src/cli.ts
+++ b/cli/src/cli.ts
@@ -32,7 +32,7 @@ import { homedir, hostname } from 'os'
import { env } from './config/env.js'
import { VERSION } from './version.js'
import { sqlitePreflightMessage } from './lib/sqliteAvailability.js'
-import { AttachTracker, forEachBounded } from './lib/attachTracker.js'
+import { AttachTracker } from './lib/attachTracker.js'
import { binaryOnPath } from './lib/binaryOnPath.js'
import { warmLoginShellEnvironment } from './lib/loginShellEnv.js'
import { ensureUtf8Locale } from './lib/childLocale.js'
@@ -287,8 +287,9 @@ const KILO_DB = join(env.KILO_DATA_DIR, 'kilo.db')
const HERMES_DB = join(env.HERMES_HOME, 'state.db')
// Devin likewise keeps all history in one SQLite store (WAL) — polled per session by DevinReader.
const DEVIN_DB = join(env.DEVIN_HOME, 'sessions.db')
-/** How many agents' histories a daemon boot reads at once — see hydrateOnBoot. */
-const BOOT_ATTACH_CONCURRENCY = 4
+/** How many agents' histories are read at once — the first reconcile pass after a boot asks for every
+ * agent's, and each read is a tmux probe, a `ps`, and the whole transcript or store (see `attaches`). */
+const ATTACH_CONCURRENCY = 4
// How long a control-plane call the daemon proxies for a local client (`/api/machines`, `/api/auth/me`)
// may wait on the backend. Under the desktop app's own 30s receive timeout, so a slow backend is
@@ -1398,19 +1399,21 @@ async function runForeground(session: AuthSession): Promise<void> {
}
const sqliteWarning = sqlitePreflightMessage()
if (sqliteWarning) console.warn(sqliteWarning)
- // Capture the user's shell environment NOW, not on the first recap — paying it here, where the
- // daemon is already doing blocking startup work, keeps it off the path of a live turn, where a
- // slow profile (nvm, conda, …) would stall frame handling instead. Started above, alongside the
- // tmux PATH probe, so this is usually just picking up an already-finished (or nearly so) capture
- // rather than paying for it here — the logged "…ms" is residual wait, not the full capture time.
- // See lib/loginShellEnv.ts: this is what lets a recap reach a credential the user exports from
- // their rc file, which a launchd/systemd-parented daemon never read.
+ // The user's shell environment is captured at startup, not on the first recap — a slow profile
+ // (nvm, conda, …) then stalls nothing live. Started above alongside the tmux PATH probe, and LOGGED
+ // when it lands, never waited on: nothing before the control port binds needs it (lib/loginShellEnv
+ // caches the capture; engine one-shots read it through `loginShellEnvironment()`), and a second
+ // login shell held the port — and with it the app's "Starting local service…" — for as long as the
+ // slower of the two shells took. See lib/loginShellEnv.ts: this is what lets a recap reach a
+ // credential the user exports from their rc file, which a launchd/systemd-parented daemon never read.
{
const t0 = Date.now()
- const captured = Object.keys(await loginShellEnvPromise).length
- console.log(captured
- ? `[env] read ${captured} variables from the login shell in ${Date.now() - t0}ms (engine one-shots only)`
- : '[env] could not read a login shell environment — engine one-shots use the daemon environment only')
+ void loginShellEnvPromise.then((captured) => {
+ const count = Object.keys(captured).length
+ console.log(count
+ ? `[env] read ${count} variables from the login shell in ${Date.now() - t0}ms (engine one-shots only)`
+ : '[env] could not read a login shell environment — engine one-shots use the daemon environment only')
+ })
}
for (const target of herdrStartup) {
console.log(target.state === 'available'
@@ -2147,8 +2150,9 @@ async function runForeground(session: AuthSession): Promise<void> {
return true
}
- /** One attach per session at a time, and a record of what is being read — see lib/attachTracker. */
+ /** One attach per session, a few sessions at a time, and a record of what is being read — see lib/attachTracker. */
const attaches = new AttachTracker<AgentEngine>({
+ concurrency: ATTACH_CONCURRENCY,
onSlow: (session, elapsedMs) => console.warn(
`[agent] ${sid(session.agentId)} attach still running · engine=${session.engine} · session=${sid(session.sessionId)} · ${Math.round(elapsedMs / 1000)}s`,
),
@@ -2957,7 +2961,7 @@ async function runForeground(session: AuthSession): Promise<void> {
}
// Not awaited: the attach reads this agent's whole history, and this callback runs inside the
// reconcile pass whose completion is what publishes `discoveryReady`. One agent's slow store
- // must not hold the pass — or, at boot, the app — see the boot hydration below for the same rule.
+ // must not hold the pass — or, at boot, the app. The tracker runs a few of these at a time.
void attachSession(active).then((attached) => {
if (!attached) {
registry.setActive(active.agentId, false)
@@ -3478,9 +3482,10 @@ async function runForeground(session: AuthSession): Promise<void> {
restarting,
discoveryReady,
discoveryError,
- // Agents whose history is being read right now (see hydrateOnBoot). Normally empty or gone in a
- // second; one that stays here names the store that is slow, which no other field does.
+ // Agents whose history is being read right now, and how many wait their turn. Normally empty or
+ // gone in a second; one that stays here names the store that is slow, which no other field does.
attaching: attaches.attaching(),
+ attachQueue: attaches.queued(),
fingerprint: backend.e2eeFingerprint(),
config: {
watching: `${terminalConfig.backends.join(' + ')} terminals across all supported engines`,
@@ -3904,47 +3909,11 @@ async function runForeground(session: AuthSession): Promise<void> {
console.error(`[cli] history handler error (session ${batch.sessionId}):`, err instanceof Error ? err.message : err)
}
})
- /**
- * Re-attach every agent the registry kept — in the BACKGROUND, a few at a time.
- *
- * An attach reads the agent's whole history (the transcript to EOF, or every row of its SQLite
- * session) to rebuild the live normalizer's state. It used to run here as an awaited loop, one agent
- * after another, before the first reconcile pass — so the daemon reported `discoveryReady:false`,
- * and the desktop app sat on "still scanning for agents", until the LAST agent's history had been
- * read. One agent was enough to hold every other: measured, an opencode session whose store the
- * `sqlite3` CLI never finished reading kept a machine's app out of every agent it had, for good.
- *
- * What the app needs at ready is the registry (which agents, on which panes), and that is already
- * authoritative. What the attach produces is per-agent: its own live stream, its own open-turn
- * replay, its own chips. So readiness no longer waits for it, and a slow or stuck read costs that
- * one agent its history — visible in `/api/status` as `attaching`, and in the log after 15s — never
- * the app. A pane that turns out dead is put dormant when its attach says so, which is also what the
- * reconcile pass would do on its own.
- *
- * Bounded, not unbounded: four at a time keeps the disk and the engines' stores from being hit by
- * every session at once on a machine with many, and still means one slow one delays at most the
- * three behind it rather than all of them. Called after restore has put every pane back (below), so
- * the pane an attach validates is the one the agent will keep.
- *
- * An UNBOUND process agent has no transcript to attach to yet. Discovery keeps it visible and the
- * hook/store repair path binds it as soon as the engine reports a session. Attaching an empty
- * session id here would tear down an agent the user can see running in their pane, which is exactly
- * what a self-update restart must never do.
- */
- const hydrateOnBoot = async (): Promise<void> => {
- const sessions = registry.list().filter((session) => session.active && session.sessionId)
- if (!sessions.length) return
- const startedAt = Date.now()
- await forEachBounded(sessions, BOOT_ATTACH_CONCURRENCY, async (session) => {
- try {
- if (!await attachSession(session)) registry.setActive(session.agentId, false)
- else input.setTurnOpen(session.agentId, sessionTurnOpen(session.sessionId))
- } catch (err) {
- console.error(`[agent] ${sid(session.agentId)} attach failed:`, err instanceof Error ? err.message : err)
- }
- })
- console.log(`[agent] re-attached ${sessions.length} agent(s) · ${Date.now() - startedAt}ms`)
- }
+ // Nothing re-attaches the registry's agents here. Every one of them is dormant from the moment the
+ // registry loads (see the `setActive(false)` transaction at the top of this function), and the first
+ // reconcile pass is what reactivates each one it finds a live process for — and attaches it, in the
+ // background and a few at a time (`onObserved` above, `attaches` below). Readiness never waits on an
+ // agent's history being read: one slow store used to hold the app out of every agent on the machine.
/**
* What the launch builder needs to know about THIS machine, read at launch time.
*
@@ -4020,6 +3989,7 @@ async function runForeground(session: AuthSession): Promise<void> {
}
if (tmuxBackend) {
const backend = tmuxBackend
+ let paneInventory: ReturnType<typeof listTmuxPanes> | null = null
const summary = await restoreAgents({
retainStopped: retainExitedSession,
registry,
@@ -4029,7 +3999,10 @@ async function runForeground(session: AuthSession): Promise<void> {
// engine, which a second pane resuming the same session would collide with.
liveProcess: (entry, runtime) => resolvePaneEngineProcess(runtime.paneId, entry.engine),
livePane: async (runtime) => {
- const inventory = await listTmuxPanes()
+ // One inventory for the whole restore, not one `tmux list-panes` per row: this runs between
+ // the control port binding and the first reconcile pass, i.e. on the app's "starting" screen.
+ paneInventory ??= listTmuxPanes()
+ const inventory = await paneInventory
// Only a harness pane counts (the inventory is already that whitelist): a new tmux server
// hands out `%N` from zero again, and a stale id can name somebody's own shell.
return inventory.ok && inventory.panes.some((pane) => pane.tmuxPane === runtime.paneId)
@@ -4096,10 +4069,6 @@ async function runForeground(session: AuthSession): Promise<void> {
// Every DSH agent the registry kept gets its viewer and verdict watch back — restored or not, an
// agent whose pane is still up is still that harness.
for (const session of registry.list()) if (session.dsh) attachDsh(session)
- // After restore, deliberately: an attach validates the pane it finds, and one that looked at a dead
- // pane a moment before restore rebuilt it would put the restored agent dormant on its way out. Not
- // awaited, also deliberately — see hydrateOnBoot.
- void hydrateOnBoot()
await agentReconciler.start(env.TERMINAL_RECONCILE_INTERVAL_MS ?? env.TMUX_REAP_INTERVAL_MS)
for (const task of await loadCursorPendingTasks(env.ADAPTER_DATA_DIR)) {
onCursorTaskStart(task.sessionId, task.toolUseId, task.input)
diff --git a/cli/src/lib/attachTracker.spec.ts b/cli/src/lib/attachTracker.spec.ts
index cda399552..41d4ddc16 100644
--- a/cli/src/lib/attachTracker.spec.ts
+++ b/cli/src/lib/attachTracker.spec.ts
@@ -1,5 +1,5 @@
import { describe, expect, it, vi } from 'vitest'
-import { AttachTracker, forEachBounded } from './attachTracker.js'
+import { AttachTracker } from './attachTracker.js'
type Engine = 'opencode' | 'claude'
const subject = (sessionId: string, engine: Engine = 'claude') => ({ sessionId, agentId: `agent-${sessionId}`, engine })
@@ -82,11 +82,60 @@ describe('AttachTracker', () => {
{ sessionId: 'ses_fast', agentId: 'agent-ses_fast', engine: 'claude', sinceMs: 500 },
])
fast.resolve(true)
- await Promise.resolve()
- expect(tracker.attaching().map((a) => a.sessionId)).toEqual(['ses_slow'])
+ await vi.waitFor(() => expect(tracker.attaching().map((a) => a.sessionId)).toEqual(['ses_slow']))
slow.resolve(true)
})
+ it('runs at most `concurrency` at once, in the order asked, and a stuck one holds only its own slot', async () => {
+ const tracker = new AttachTracker<Engine>({ concurrency: 2 })
+ const gates = new Map<string, ReturnType<typeof deferred<boolean>>>()
+ const started: string[] = []
+ const results = ['a', 'b', 'c', 'd'].map((id) => tracker.attach(subject(id), false, () => {
+ started.push(id)
+ const gate = deferred<boolean>()
+ gates.set(id, gate)
+ return gate.promise
+ }))
+ await Promise.resolve()
+ expect(started).toEqual(['a', 'b'])
+ expect(tracker.queued()).toBe(2)
+ expect(tracker.attaching().map((a) => a.sessionId).sort()).toEqual(['a', 'b'])
+ // 'a' is the agent whose store hangs. Everything behind it still gets read, through b's slot.
+ gates.get('b')!.resolve(true)
+ await vi.waitFor(() => expect(started).toEqual(['a', 'b', 'c']))
+ expect(tracker.queued()).toBe(1)
+ gates.get('c')!.resolve(true)
+ await vi.waitFor(() => expect(started).toEqual(['a', 'b', 'c', 'd']))
+ expect(tracker.queued()).toBe(0)
+ gates.get('d')!.resolve(false)
+ expect(await Promise.all(results.slice(1))).toEqual([true, true, false])
+ expect(tracker.attaching().map((a) => a.sessionId)).toEqual(['a'])
+ gates.get('a')!.resolve(true)
+ expect(await results[0]).toBe(true)
+ })
+
+ it('a joiner takes no slot, and a newcomer cannot jump the queue', async () => {
+ const tracker = new AttachTracker<Engine>({ concurrency: 1 })
+ const first = deferred<boolean>()
+ const started: string[] = []
+ const run = (id: string) => tracker.attach(subject(id), false, () => {
+ started.push(id)
+ return id === 'a' ? first.promise : Promise.resolve(true)
+ })
+ const a = run('a')
+ const b = run('b')
+ const joiner = run('a')
+ await Promise.resolve()
+ expect(started).toEqual(['a'])
+ expect(tracker.queued()).toBe(1)
+ first.resolve(true)
+ // 'c' asks the instant 'a' finishes; 'b' was first in line.
+ await a
+ const c = run('c')
+ await Promise.all([b, c, joiner])
+ expect(started).toEqual(['a', 'b', 'c'])
+ })
+
it('names an attach that runs long, once, and not one that finished', async () => {
vi.useFakeTimers()
try {
@@ -109,39 +158,3 @@ describe('AttachTracker', () => {
}
})
})
-
-describe('forEachBounded', () => {
- it('runs at most `limit` at a time, in order, and one that never finishes holds only its own slot', async () => {
- const gates = new Map<number, ReturnType<typeof deferred<void>>>()
- const started: number[] = []
- const all = forEachBounded([1, 2, 3, 4, 5], 2, async (n) => {
- started.push(n)
- const gate = deferred<void>()
- gates.set(n, gate)
- await gate.promise
- })
- await Promise.resolve()
- expect(started).toEqual([1, 2])
- // 1 is the agent whose store hangs: it never resolves. Everything else still gets read.
- gates.get(2)!.resolve()
- await vi.waitFor(() => expect(started).toEqual([1, 2, 3]))
- gates.get(3)!.resolve()
- await vi.waitFor(() => expect(started).toEqual([1, 2, 3, 4]))
- gates.get(4)!.resolve()
- await vi.waitFor(() => expect(started).toEqual([1, 2, 3, 4, 5]))
- gates.get(5)!.resolve()
- let settled = false
- void all.then(() => { settled = true })
- await new Promise((r) => setTimeout(r, 20))
- expect(settled).toBe(false)
- gates.get(1)!.resolve()
- await all
- })
-
- it('handles an empty list and a limit larger than the list', async () => {
- const seen: number[] = []
- await forEachBounded([], 4, async () => { seen.push(0) })
- await forEachBounded([1, 2], 10, async (n) => { seen.push(n) })
- expect(seen).toEqual([1, 2])
- })
-})
diff --git a/cli/src/lib/attachTracker.ts b/cli/src/lib/attachTracker.ts
index 21b8ec9ad..791eb341a 100644
--- a/cli/src/lib/attachTracker.ts
+++ b/cli/src/lib/attachTracker.ts
@@ -3,11 +3,13 @@
* normalizer (cli.ts `attachSessionNow`). Two jobs, both born of the same incident: a daemon whose
* boot sat on ONE agent's store for good, with nothing in any log to say which.
*
- * - ONE attach per session at a time. Boot hydrates every agent in the background, and the first
- * reconcile pass, a hook, or a cursor discovery can ask for the same session while that is still
- * running. A second fold on top of the first is the duplicate-turn class of bug (a turn opened,
- * closed after 44ms and opened again), so a plain attach JOINS the one in flight, and a `reset`
- * waits for it and then folds afresh.
+ * - ONE attach per session at a time. The first reconcile pass after a boot starts one for every
+ * agent it reactivates, and a hook or a cursor discovery can ask for the same session while that
+ * is still running. A second fold on top of the first is the duplicate-turn class of bug (a turn
+ * opened, closed after 44ms and opened again), so a plain attach JOINS the one in flight, and a
+ * `reset` waits for it and then folds afresh.
+ * - A FEW sessions at a time. Each attach is a tmux probe, a `ps` over the whole machine and the
+ * agent's entire transcript or store; a boot with twenty agents must not start twenty at once.
* - Saying what the daemon is busy with. `/api/status` lists the attaches in flight, and one that
* runs long is logged by name.
*/
@@ -27,29 +29,38 @@ export interface AttachInFlight<E> {
}
export interface AttachTrackerOptions<E> {
- /** After this long, `onSlow` is told once about the attach. */
+ /** How many attaches may run at once; the rest wait their turn, in the order they asked. */
+ concurrency?: number
+ /** After this long RUNNING (waiting for a slot does not count), `onSlow` is told once about the attach. */
slowMs?: number
onSlow?: (subject: AttachSubject<E>, elapsedMs: number) => void
now?: () => number
}
const DEFAULT_SLOW_MS = 15_000
+const DEFAULT_CONCURRENCY = 4
export class AttachTracker<E> {
- private readonly inFlight = new Map<string, { run: Promise<boolean>; subject: AttachSubject<E>; since: number }>()
+ /** Every attach that has been asked for and not finished — waiting for a slot or running. */
+ private readonly inFlight = new Map<string, { run: Promise<boolean>; subject: AttachSubject<E>; since: number | null }>()
+ private readonly waiting: Array<() => void> = []
+ private running = 0
+ private readonly concurrency: number
private readonly slowMs: number
private readonly onSlow?: (subject: AttachSubject<E>, elapsedMs: number) => void
private readonly now: () => number
constructor(options: AttachTrackerOptions<E> = {}) {
+ this.concurrency = Math.max(1, options.concurrency ?? DEFAULT_CONCURRENCY)
this.slowMs = options.slowMs ?? DEFAULT_SLOW_MS
this.onSlow = options.onSlow
this.now = options.now ?? Date.now
}
/**
- * Run `start` for this session — unless one is already running, in which case a plain attach
+ * Run `start` for this session — unless one is already in flight, in which case a plain attach
* returns THAT one's result and `start` is never called; a `reset` waits for it, then runs `start`.
+ * Either way `start` runs only once a slot is free.
*/
async attach(session: AttachSubject<E>, reset: boolean, start: () => Promise<boolean>): Promise<boolean> {
// A loop, not an if: two resets waiting on the same attach would otherwise both start at once.
@@ -57,40 +68,50 @@ export class AttachTracker<E> {
if (!reset) return pending.run
await pending.run.catch(() => false)
}
- const since = this.now()
- const slow = setTimeout(() => this.onSlow?.(session, this.now() - since), this.slowMs)
+ const entry = { run: Promise.resolve(false), subject: session, since: null as number | null }
+ entry.run = this.runWhenFree(entry, start).finally(() => {
+ if (this.inFlight.get(session.sessionId) === entry) this.inFlight.delete(session.sessionId)
+ })
+ this.inFlight.set(session.sessionId, entry)
+ return entry.run
+ }
+
+ private async runWhenFree(
+ entry: { subject: AttachSubject<E>; since: number | null },
+ start: () => Promise<boolean>,
+ ): Promise<boolean> {
+ // A finishing attach hands its slot straight to the next in line (below) rather than freeing it:
+ // a newcomer arriving in that gap would otherwise slip in ahead of the queue and push it past `concurrency`.
+ if (this.running < this.concurrency) this.running++
+ else await new Promise<void>((resolve) => this.waiting.push(resolve))
+ entry.since = this.now()
+ const since = entry.since
+ const slow = setTimeout(() => this.onSlow?.(entry.subject, this.now() - since), this.slowMs)
slow.unref?.()
- // A `start` that throws before it returns a promise must still clear the timer and the slot.
- let started: Promise<boolean>
- try { started = start() } catch (err) { started = Promise.reject(err) }
- const run = started.finally(() => {
+ try {
+ // A `start` that throws before it returns a promise is a failed attach, not a lost slot.
+ return await start()
+ } finally {
clearTimeout(slow)
- if (this.inFlight.get(session.sessionId)?.run === run) this.inFlight.delete(session.sessionId)
- })
- this.inFlight.set(session.sessionId, { run, subject: session, since })
- return run
+ const next = this.waiting.shift()
+ if (next) next()
+ else this.running--
+ }
}
- /** What is being read right now, longest-running first. */
+ /** What is being read right now, longest-running first. Attaches still waiting for a slot are not here. */
attaching(): Array<AttachInFlight<E>> {
const now = this.now()
return [...this.inFlight.values()]
+ .filter((entry): entry is typeof entry & { since: number } => entry.since !== null)
.map(({ subject, since }) => ({
sessionId: subject.sessionId, agentId: subject.agentId, engine: subject.engine, sinceMs: now - since,
}))
.sort((a, b) => b.sinceMs - a.sinceMs)
}
-}
-/**
- * `fn` over every item, at most `limit` at a time, in order of the list. A rejection is the caller's
- * to catch inside `fn`; here it would stop that worker's share of the list, which is not what a boot
- * wants, so `fn` is expected to swallow its own.
- */
-export async function forEachBounded<T>(items: readonly T[], limit: number, fn: (item: T) => Promise<void>): Promise<void> {
- const queue = [...items]
- const worker = async (): Promise<void> => {
- for (let item = queue.shift(); item !== undefined; item = queue.shift()) await fn(item)
+ /** How many attaches are waiting for a slot. */
+ queued(): number {
+ return this.waiting.length
}
- await Promise.all(Array.from({ length: Math.max(1, Math.min(limit, queue.length)) }, worker))
}
diff --git a/cli/src/lib/processRows.spec.ts b/cli/src/lib/processRows.spec.ts
new file mode 100644
index 000000000..cf26798a4
--- /dev/null
+++ b/cli/src/lib/processRows.spec.ts
@@ -0,0 +1,55 @@
+import { chmodSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs'
+import { tmpdir } from 'node:os'
+import { join } from 'node:path'
+import { afterEach, beforeEach, describe, expect, it } from 'vitest'
+import { processRows } from './tmux.js'
+
+/**
+ * A `ps` on PATH that records every spawn and answers one well-formed row after a short pause — long
+ * enough for concurrent callers to pile up behind the first read.
+ */
+describe('processRows', () => {
+ let dir = ''
+ let calls = ''
+ let previousPath: string | undefined
+ beforeEach(() => {
+ dir = mkdtempSync(join(tmpdir(), 'ps-coalesce-'))
+ calls = join(dir, 'calls')
+ writeFileSync(join(dir, 'ps'), `#!/bin/sh
+echo x >> "${calls}"
+if [ -f "${join(dir, 'fail')}" ]; then exit 1; fi
+sleep 0.15
+printf ' 123 1 claude Mon Sep 21 10:00:00 2026 claude --resume\\n'
+`)
+ chmodSync(join(dir, 'ps'), 0o700)
+ previousPath = process.env.PATH
+ process.env.PATH = `${dir}:${previousPath ?? ''}`
+ })
+ afterEach(() => {
+ if (previousPath === undefined) delete process.env.PATH
+ else process.env.PATH = previousPath
+ rmSync(dir, { recursive: true, force: true })
+ })
+ const spawns = (): number => { try { return readFileSync(calls, 'utf8').split('\n').filter(Boolean).length } catch { return 0 } }
+
+ // The first reconcile pass after a boot attaches a few agents at once, and each validates its pane
+ // against the table; a hook burst does the same. One `ps` for the burst, not one per caller.
+ it('callers that overlap share one ps, callers that follow get a fresh one', async () => {
+ const burst = await Promise.all([processRows(), processRows(), processRows(), processRows(), processRows()])
+ expect(spawns()).toBe(1)
+ for (const rows of burst) expect(rows?.map((row) => row.pid)).toEqual([123])
+ // Identity, not just equality: nobody was handed a copy of a table read for someone else earlier.
+ expect(new Set(burst).size).toBe(1)
+ const later = await processRows()
+ expect(spawns()).toBe(2)
+ expect(later?.map((row) => row.pid)).toEqual([123])
+ })
+
+ it('a failed read is not remembered', async () => {
+ writeFileSync(join(dir, 'fail'), '')
+ expect(await processRows()).toBeNull()
+ rmSync(join(dir, 'fail'))
+ expect((await processRows())?.length).toBe(1)
+ expect(spawns()).toBe(2)
+ })
+})
diff --git a/cli/src/lib/tmux.ts b/cli/src/lib/tmux.ts
index 2d4de2e18..9348c6dd8 100644
--- a/cli/src/lib/tmux.ts
+++ b/cli/src/lib/tmux.ts
@@ -179,8 +179,24 @@ function readProcField(pid: number, field: 'cmdline' | 'comm'): string | null {
try { return readFileSync(`/proc/${pid}/${field}`, 'utf8') } catch { return null }
}
+/**
+ * A `ps` that is already running answers everyone who asks while it runs. The first reconcile pass
+ * after a boot attaches a few agents at once and every attach validates its pane against the table,
+ * as does each hook that arrives in the same burst — one table serves them all. There is no cache,
+ * only the read in flight: the oldest table anyone is handed began a `ps` ago (tens of ms), never
+ * one that finished before they asked. Callers get the SAME array; none of them mutates it (every
+ * consumer maps or filters into its own), and any new one must not either.
+ */
+let processRowsInFlight: Promise<ProcessRow[] | null> | null = null
+
/** The process table, or null when `ps` itself failed — "we could not look" is not "nothing is there". */
-export async function processRows(): Promise<ProcessRow[] | null> {
+export function processRows(): Promise<ProcessRow[] | null> {
+ if (processRowsInFlight) return processRowsInFlight
+ processRowsInFlight = readProcessRows().finally(() => { processRowsInFlight = null })
+ return processRowsInFlight
+}
+
+async function readProcessRows(): Promise<ProcessRow[] | null> {
const rows = await new Promise<ProcessRow[] | null>((resolve) => {
execFile('ps', ['-axo', 'pid=,ppid=,comm=,lstart=,args='], { timeout: 3000, env: psEnv() }, (err, stdout) => {
if (err) { resolve(null); return }