Skip to content

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.

fix(terminal): snapshot agent state at park time; review fixes (#126)

enes044361009ae4
diff --git a/src/core/pty-manager.ts b/src/core/pty-manager.ts
index 9bde21371..5ab3cb56d 100644
--- a/src/core/pty-manager.ts
+++ b/src/core/pty-manager.ts
@@ -174,13 +174,20 @@ bind -T copy-mode-vi TripleClick1Pane send-keys -X select-line \\; send-keys -X
* through the now-resolved tmux.
*/
function findTmux(): string | null {
+ // BOTH lookups inside the guard: `os.homedir()` throws the same SystemError as `userInfo()` when
+ // there is no passwd entry and no $HOME (some containers), and a thrown probe here would take
+ // out tmux discovery entirely — degrading a machine that HAS tmux to the plain-shell fallback,
+ // which is the failure this whole function is being hardened against. Unknown home/user simply
+ // drops the candidates derived from them.
+ let home: string | null = null
let user: string | null = null
try {
+ home = os.homedir()
user = os.userInfo().username
} catch {
- // no passwd entry (some containers) — findFixedTmux falls back to the home basename
+ // no home / no passwd entry — the fixed system paths below are still checked
}
- const fixed = findFixedTmux((p) => fs.existsSync(p), os.homedir(), user)
+ const fixed = findFixedTmux((p) => fs.existsSync(p), home, user)
if (fixed) return fixed
return findInPathString('tmux', shellPathNow() ?? process.env.PATH)
}
diff --git a/src/renderer/nodes/TerminalNode.tsx b/src/renderer/nodes/TerminalNode.tsx
index 895961f3f..78c1cc47b 100644
--- a/src/renderer/nodes/TerminalNode.tsx
+++ b/src/renderer/nodes/TerminalNode.tsx
@@ -62,7 +62,7 @@ import { loseWebglContexts, registerWebglClient, type WebglClientHandle } from '
import {
PARK_MAX,
armParkExpiry,
- canDisposePark,
+ canDisposeParkedEntry,
disposableParks,
planParkEviction,
type ParkTimer
@@ -125,7 +125,8 @@ import { isZoomModifierHeld } from '../lib/zoomModifier'
import { isHidden } from '../lib/ui-visibility'
import { readsClaudeTranscript } from '../lib/transcriptGates'
import { useSettings } from '../state/settings'
-import { useAgentStatus, inferInterruptAfterSettle } from '../state/agentStatus'
+import { useAgentStatus, agentStatusForApi, inferInterruptAfterSettle } from '../state/agentStatus'
+import type { AgentState } from '@shared/agents/normalize'
import type { ClientId } from '@shared/presence'
import { PresenceChips } from '../components/PresenceChips'
import { useAgentNodes } from '../state/agentNodes'
@@ -286,12 +287,18 @@ interface ParkedTerminal {
search: SearchAddon
transport: TerminalTransport
sessionId: string
- /** The node this park belongs to — the key into `agentStatus.byId` the protection reads. (The
- * map's own key is session-scoped, `terminalKey(sessionId, nodeId)`, so it is not the node id.) */
- nodeId: string
/** `PtyCreateResult.persistent`: the session survives a client kill (tmux, local or remote).
* False = plain shell, where disposing this park ends the session for real. */
tmuxBacked: boolean
+ /** The node's agent state AT PARK TIME — the protection FLOOR. The unmount that parks is also
+ * the one that CLEARS this node's agent status (TerminalNode's departure effect), and every
+ * lever reads later than that, so without this snapshot every park looks agent-less. See
+ * `effectiveAgentState`. */
+ parkedAgentState?: AgentState
+ /** The node's agent state RIGHT NOW, read from the store of the session this node belongs to
+ * (a relay tab's status lives in its own instance, not the default one). Closed over at park
+ * time because the module-level levers have no access to the component's session. */
+ readAgentState: () => AgentState | undefined
/** Session-scoped teardown (transport/xterm listeners) — run only at final dispose. */
cleanups: Array<() => void>
/**
@@ -307,20 +314,17 @@ interface ParkedTerminal {
const parkedTerminals = new Map<string, ParkedTerminal>()
const TERM_PARK_MS = 5 * 60 * 1000
-/** May the BUDGET levers dispose this park? Reads the node's live agent state the way the
- * hibernation sweep does (the same store, non-reactively) and pairs it with the session's
- * tmux-backedness. An unknown key is disposable — there is nothing there to protect.
- *
- * `useAgentStatus` is the DEFAULT (local-core) store, like every other status read in this file.
- * A relay tab's status lives in its own session-scoped store, so a remote node reads as "no
- * agent" here — which changes nothing: a remote session is tmux-backed on the remote host, so it
- * is disposable either way. */
+/** May the BUDGET levers dispose this park? The entry carries both halves of the answer: the
+ * session's tmux-backedness, and a live read of the node's OWN agent-status store with the
+ * park-time snapshot as a floor under it (see `canDisposeParkedEntry`). An unknown key is
+ * disposable — there is nothing there to protect. */
function parkDisposable(key: string): boolean {
const p = parkedTerminals.get(key)
if (!p) return true
- return canDisposePark({
+ return canDisposeParkedEntry({
tmuxBacked: p.tmuxBacked,
- agentState: useAgentStatus.getState().byId[p.nodeId]?.state
+ parkedAgentState: p.parkedAgentState,
+ liveAgentState: p.readAgentState()
})
}
@@ -841,6 +845,28 @@ export function TerminalNode({
// `defaultPresence` (byte-identical to before). Stable for the node's lifetime (a tab switch
// unmounts the node), so capturing it in the once-mounted lifecycle effect below is safe, like `api`.
const presence = useActiveSessionPresence()
+ /**
+ * THIS node's agent-status store, for the memory levers that must not kill live work.
+ *
+ * Resolved the way the session registry resolves it — memoized by api identity — so a relay
+ * tab's node reads the RELAY core's status table rather than the local one. That matters now
+ * that `persistent:false` can arrive from a tmux-less relay HOST: such a node is exactly a
+ * plain-shell agent session, and against the default store its state would always read
+ * `undefined` (= disposable), i.e. unprotected. For the local session this IS `useAgentStatus`
+ * (the WeakMap is seeded with `window.nodeTerminal`), so nothing about local behavior changes.
+ *
+ * Scoped deliberately to the protection paths. The other status reads in this file predate
+ * per-session stores and are left exactly as they were; widening them is a separate change.
+ */
+ const agentStatusStore = agentStatusForApi(api).store
+ const readAgentState = useCallback(
+ (): AgentState | undefined => agentStatusStore.getState().byId[id]?.state,
+ [agentStatusStore, id]
+ )
+ /** Mirror for the mount-stable visibility observer, which is keyed on `termKey` alone and takes
+ * everything mutable through a ref (see its docblock). */
+ const readAgentStateRef = useRef(readAgentState)
+ readAgentStateRef.current = readAgentState
// Session-scope the module-global node-keyed maps (parkedTerminals / coStates / coSubs /
// restartSubs / noParkIds): a relay tab adopts the host's project KEEPING node ids, so a local
// node and a relay node can share a bare id. `session.id` is stable for this node's lifetime
@@ -3087,8 +3113,11 @@ export function TerminalNode({
search: searchAddon,
transport,
sessionId,
- nodeId: id,
tmuxBacked: sessionPersistent,
+ // Snapshot NOW, because the departure effect declared below this one clears this node's
+ // agent status on this very unmount — every lever reads later and would see nothing.
+ parkedAgentState: readAgentState(),
+ readAgentState,
cleanups,
life,
// The window RE-ARMS (PARK_RECHECK_MS) while this park is protected, instead of killing a
@@ -3253,9 +3282,16 @@ export function TerminalNode({
if (
shouldDeferReleaseForLiveWork({
tmuxBacked: sessionPersistentRef.current,
- agentState: useAgentStatus.getState().byId[id]?.state
+ agentState: readAgentStateRef.current()
})
) {
+ // Re-stamp the offscreen clock: this node is not RELEASABLE yet, and the Eco
+ // deferral's cap is measured from the start of the releasable stretch. Without this
+ // a long live-work wait would blow that cap outright, so the release that finally
+ // runs would skip the hibernate-first ordering and forfeit the CLI's hundreds of MB
+ // at the exact moment they became reclaimable. The stretch effectively begins when
+ // the work ends.
+ offscreenSinceRef.current = Date.now()
offscreenTimerRef.current = setTimeout(fireRelease, OFFSCREEN_DEFER_RETRY_MS)
return
}
diff --git a/src/renderer/terminal/live-work.test.ts b/src/renderer/terminal/live-work.test.ts
index 9b09a6b2e..6371d99b2 100644
--- a/src/renderer/terminal/live-work.test.ts
+++ b/src/renderer/terminal/live-work.test.ts
@@ -1,5 +1,5 @@
import { describe, it, expect } from 'vitest'
-import { wouldKillLiveWork } from './live-work'
+import { effectiveAgentState, wouldKillLiveWork } from './live-work'
describe('wouldKillLiveWork', () => {
it('is true only for a NON-tmux session whose agent is working/waiting/blocked', () => {
@@ -18,3 +18,23 @@ describe('wouldKillLiveWork', () => {
expect(wouldKillLiveWork({ tmuxBacked: false })).toBe(false)
})
})
+
+describe('effectiveAgentState — the snapshot FLOOR under a live store read', () => {
+ it('falls back to the snapshot when the store has forgotten the node', () => {
+ // THE #126 REPRO. TerminalNode's departure effect clears agent status on the very unmount that
+ // parks the terminal, so every later reader — the LRU in a microtask, the expiry minutes on —
+ // sees `undefined` and calls a working agent disposable. The snapshot is what survives it.
+ expect(effectiveAgentState(undefined, 'working')).toBe('working')
+ expect(effectiveAgentState(undefined, 'waiting')).toBe('waiting')
+ })
+ it('lets a LIVE state override the snapshot in both directions', () => {
+ // Hook events keep landing for a parked node (Canvas's listener is keyed by node id, not by
+ // mount), so a turn that ends while parked must be able to RELEASE the protection…
+ expect(effectiveAgentState('done', 'working')).toBe('done')
+ // …and one that starts must be able to add it.
+ expect(effectiveAgentState('working', 'done')).toBe('working')
+ })
+ it('is undefined only when neither knows anything', () => {
+ expect(effectiveAgentState(undefined, undefined)).toBeUndefined()
+ })
+})
diff --git a/src/renderer/terminal/live-work.ts b/src/renderer/terminal/live-work.ts
index 26ac90e0c..7edb9e5b3 100644
--- a/src/renderer/terminal/live-work.ts
+++ b/src/renderer/terminal/live-work.ts
@@ -50,3 +50,29 @@ export interface LiveWorkInput {
export function wouldKillLiveWork(i: LiveWorkInput): boolean {
return !i.tmuxBacked && !!i.agentState && LIVE_AGENT_STATES.has(i.agentState)
}
+
+/**
+ * The state to judge a PARKED terminal by: the live store read, with the state captured at park
+ * time as a FLOOR under it.
+ *
+ * A snapshot alone would be stale and a live read alone is not available — because the unmount
+ * that parks a terminal is the same unmount that CLEARS its agent status. TerminalNode's
+ * departure-only effect exists so a project switch doesn't leave a stale RUNNING badge behind, and
+ * it runs right after the lifecycle cleanup that created the park. Every park lever reads the
+ * store later than that — the LRU in a microtask, the expiry minutes on — so every one of them saw
+ * `undefined` and called a working agent disposable. That is the reported #126 case (a project
+ * switch past `PARK_MAX`) and, worse, it made `waiting`/`blocked` parks unprotectable in
+ * principle: an agent holding a question open emits no further hook events, so nothing would ever
+ * repopulate the store for it.
+ *
+ * The floor is only a floor, never a latch: hook events for a parked node still land in the store
+ * (Canvas's `agent:status` listener is keyed by node id, not by what is mounted), so a turn that
+ * ENDS while parked releases the protection on the next re-check, and one that starts adds it.
+ * Live truth always wins; the snapshot only answers when there is no live truth to have.
+ */
+export function effectiveAgentState(
+ live: AgentState | undefined,
+ atParkTime: AgentState | undefined
+): AgentState | undefined {
+ return live ?? atParkTime
+}
diff --git a/src/renderer/terminal/offscreen-policy.test.ts b/src/renderer/terminal/offscreen-policy.test.ts
index db1c2bd8c..704103b63 100644
--- a/src/renderer/terminal/offscreen-policy.test.ts
+++ b/src/renderer/terminal/offscreen-policy.test.ts
@@ -1,4 +1,6 @@
import { describe, it, expect } from 'vitest'
+import fs from 'fs'
+import path from 'path'
import {
OFFSCREEN_DISPOSE_MS_DEFAULT,
offscreenDisposeMs,
@@ -177,17 +179,30 @@ describe('shouldDeferReleaseForLiveWork — the fourth kill lever behind issue #
expect(shouldDeferReleaseForLiveWork({ tmuxBacked: false })).toBe(false)
})
- it('is UNCAPPED, unlike the Eco deferral — there is no elapsed time that makes the kill safe', () => {
- // shouldDeferReleaseForEco takes `offscreenElapsedMs` and gives up at the cap because it waits
- // for a hibernation that may never come. This one waits for the user's own turn to end, and
- // "give up and kill it anyway" is precisely the reported bug — so time is not an input at all.
- // Pinned structurally: the input carries no clock, so no caller can grow a cap by passing one.
- const input: Parameters<typeof shouldDeferReleaseForLiveWork>[0] = {
- tmuxBacked: false,
- agentState: 'working'
- }
- expect(Object.keys(input).sort()).toEqual(['agentState', 'tmuxBacked'])
- expect(shouldDeferReleaseForLiveWork(input)).toBe(true)
+ /**
+ * UNCAPPED, unlike the Eco deferral one screen up — and that is a decision, not an oversight, so
+ * it is pinned rather than described. `shouldDeferReleaseForEco` takes `offscreenElapsedMs` and
+ * gives up at a cap because it waits for a hibernation that may never come; this one waits for
+ * the user's own turn to end, and "give up and release anyway" is precisely the bug (#126).
+ *
+ * A behavioural test cannot state this: the claim is about an input that must NOT exist, and any
+ * argument object a test writes itself passes trivially. So it is pinned over the source — the
+ * same move `canvas/agent-status-rescue.test.ts` and `core/no-electron.test.ts` make for
+ * invariants no call can express — and it fails the moment someone threads a clock through.
+ */
+ it('is UNCAPPED: no clock reaches the predicate, so no caller can grow a cap', () => {
+ const src = fs.readFileSync(path.resolve(__dirname, 'offscreen-policy.ts'), 'utf8')
+ const start = src.indexOf('export function shouldDeferReleaseForLiveWork')
+ expect(start, 'the predicate must still exist').toBeGreaterThan(-1)
+ const body = src.slice(start, src.indexOf('\n}', start))
+ // Its whole input is LiveWorkInput (tmuxBacked + agentState). Nothing time-shaped may appear:
+ // an elapsed reading, a deadline, a Date.now() — each of those is a cap in the making.
+ expect(body).toMatch(/shouldDeferReleaseForLiveWork\(\s*i: LiveWorkInput\s*\)/)
+ expect(body).not.toMatch(/elapsed|Ms\b|Date\.now|cap|minutes/i)
+ // …and the shared input type itself carries no clock either (the other end of the same claim).
+ const live = fs.readFileSync(path.resolve(__dirname, 'live-work.ts'), 'utf8')
+ const iface = live.slice(live.indexOf('export interface LiveWorkInput'))
+ expect(iface.slice(0, iface.indexOf('\n}'))).not.toMatch(/elapsed|Date\.now|cap|minutes/i)
})
})
diff --git a/src/renderer/terminal/offscreen-policy.ts b/src/renderer/terminal/offscreen-policy.ts
index 9a754a875..4928bd564 100644
--- a/src/renderer/terminal/offscreen-policy.ts
+++ b/src/renderer/terminal/offscreen-policy.ts
@@ -83,10 +83,23 @@ export const OFFSCREEN_DEFER_RETRY_MS = 60_000
*
* UNCAPPED, and that is the one place it deliberately differs from the Eco deferral above. That
* one caps because it waits for a hibernation that may never come, and stranding a viewer forever
- * for an event that cannot happen would be worse than the memory it saves. This one waits for the
- * user's own turn to end — a thing that always ends — and "give up and release anyway" is
- * precisely the reported bug. So no clock is an input here at all. The exposure is bounded by
- * what it protects: only non-tmux sessions, only while an agent is actually mid-task.
+ * for an event that cannot happen would be worse than the memory it saves. Here the thing waited
+ * for is the user's own session ending, and "give up and release anyway" IS the reported bug — a
+ * cap would just be the same kill with a delay in front of it. So no clock is an input at all.
+ *
+ * BE HONEST ABOUT WHAT THAT COSTS. `working` always resolves — the stale-working sweep
+ * (`shared/agents/stale.ts`, 20 minutes) fires a synthetic end edge for a session that died
+ * without saying so, and that reaches this store like any other event. `waiting`/`blocked` has no
+ * such sweep, and legitimately so: a question held open for the user is not stale, it is waiting
+ * for them. A user who never answers therefore holds this node's viewer for as long as the app
+ * runs.
+ *
+ * That is accepted, because the exposure is bounded in the dimension that matters. It is not
+ * unbounded growth: it is at most one held viewer (~15 MB) per non-tmux node that is actually
+ * sitting on an unanswered prompt — a count the user creates by hand and can see on the canvas,
+ * where the badge is telling them the node needs them. Bounded by node count, not by time. The
+ * alternative is trading a bounded amount of memory for the user's running work, which is the
+ * trade this whole change exists to stop making.
*/
export function shouldDeferReleaseForLiveWork(i: LiveWorkInput): boolean {
return wouldKillLiveWork(i)
diff --git a/src/renderer/terminal/park-budget.test.ts b/src/renderer/terminal/park-budget.test.ts
index 7289b5d00..e4919a979 100644
--- a/src/renderer/terminal/park-budget.test.ts
+++ b/src/renderer/terminal/park-budget.test.ts
@@ -1,11 +1,13 @@
-import { describe, it, expect } from 'vitest'
+import { describe, it, expect, beforeEach } from 'vitest'
import {
PARK_MAX,
PARK_RECHECK_MS,
armParkExpiry,
canDisposePark,
+ canDisposeParkedEntry,
disposableParks,
- planParkEviction
+ planParkEviction,
+ type ParkedEntryState
} from './park-budget'
describe('planParkEviction', () => {
@@ -51,6 +53,94 @@ describe('canDisposePark', () => {
})
})
+/**
+ * THE REPRO, at the level the logic lives on.
+ *
+ * The park levers do not read a state, they read a REGISTRY of parked entries; so does the real
+ * `parkDisposable` in TerminalNode. This fakes that registry and drives all three levers through
+ * the same predicate they use in production, because the bug was never in any one lever — it was
+ * in what they all read.
+ *
+ * Sequence: a plain-shell terminal parks while its agent is WORKING, then TerminalNode's departure
+ * effect clears the node's agent status (the unmount that parks is the same unmount that clears),
+ * so every later live read answers `undefined`.
+ */
+describe('a parked plain-shell agent survives the departure clear (#126)', () => {
+ const registry = new Map<string, ParkedEntryState>()
+ const disposable = (key: string): boolean => {
+ const e = registry.get(key)
+ return e ? canDisposeParkedEntry(e) : true
+ }
+ /** Park `key`, snapshotting the state the node had at that moment. */
+ const park = (key: string, e: ParkedEntryState): void => void registry.set(key, e)
+ /** What the departure effect does: the store forgets the node entirely. */
+ const departureClear = (key: string): void => {
+ const e = registry.get(key)
+ if (e) registry.set(key, { ...e, liveAgentState: undefined })
+ }
+
+ beforeEach(() => registry.clear())
+
+ it('LRU eviction: the just-parked working terminal is not evicted past the cap', () => {
+ park('victim', { tmuxBacked: false, parkedAgentState: 'working', liveAgentState: 'working' })
+ departureClear('victim')
+ for (let i = 0; i < PARK_MAX; i++) park(`other${i}`, { tmuxBacked: true })
+ // 13 parks against a cap of 12, oldest ('victim') first — the exact >PARK_MAX project switch.
+ const plan = planParkEviction([...registry.keys()], PARK_MAX, disposable)
+ expect(plan).not.toContain('victim')
+ expect(plan).toEqual(['other0']) // the cap still holds, paid by the next-oldest disposable park
+ })
+
+ it('window expiry: re-arms instead of disposing, then disposes when the agent reports done', () => {
+ park('victim', { tmuxBacked: false, parkedAgentState: 'working', liveAgentState: 'working' })
+ departureClear('victim')
+ const armed: Array<{ fn: () => void; ms: number }> = []
+ let disposed = 0
+ armParkExpiry(() => disposable('victim'), () => disposed++, 5000, {
+ set: (fn, ms) => armed.push({ fn, ms }) - 1,
+ clear: () => {}
+ })
+ armed[0].fn()
+ expect(disposed).toBe(0)
+ expect(armed[1].ms).toBe(PARK_RECHECK_MS)
+ // A `done` hook event lands while the node is still parked — Canvas's listener is keyed by
+ // node id, not by mount, so the store CAN learn this — and the live read overrides the floor.
+ registry.set('victim', { ...registry.get('victim')!, liveAgentState: 'done' })
+ armed[1].fn()
+ expect(disposed).toBe(1)
+ })
+
+ it('memory-pressure lever: drops every other park and leaves this one', () => {
+ park('victim', { tmuxBacked: false, parkedAgentState: 'working', liveAgentState: 'working' })
+ departureClear('victim')
+ park('plain', { tmuxBacked: false })
+ park('tmux-working', { tmuxBacked: true, parkedAgentState: 'working' })
+ expect(disposableParks([...registry.keys()], disposable)).toEqual(['plain', 'tmux-working'])
+ })
+
+ it('protects a WAITING park, which no later hook event would ever repopulate', () => {
+ // `waiting`/`blocked` is a question held open for the user: the agent emits nothing more until
+ // they answer, so the store clear is permanent and the snapshot is the ONLY evidence left.
+ park('ask', { tmuxBacked: false, parkedAgentState: 'waiting', liveAgentState: 'waiting' })
+ departureClear('ask')
+ expect(disposable('ask')).toBe(false)
+ })
+
+ it('still disposes the cases that were always disposable, snapshot or not', () => {
+ expect(canDisposeParkedEntry({ tmuxBacked: true, parkedAgentState: 'working' })).toBe(true)
+ expect(canDisposeParkedEntry({ tmuxBacked: false, parkedAgentState: 'done' })).toBe(true)
+ expect(canDisposeParkedEntry({ tmuxBacked: false })).toBe(true)
+ // A live `done` overrides a `working` snapshot — the protection must not be one-way.
+ expect(
+ canDisposeParkedEntry({
+ tmuxBacked: false,
+ parkedAgentState: 'working',
+ liveAgentState: 'done'
+ })
+ ).toBe(true)
+ })
+})
+
describe('disposableParks', () => {
it('drops everything except the protected parks', () => {
expect(disposableParks(['a', 'b', 'c'], (k) => k !== 'b')).toEqual(['a', 'c'])
diff --git a/src/renderer/terminal/park-budget.ts b/src/renderer/terminal/park-budget.ts
index 6c314f6a5..bac1f60da 100644
--- a/src/renderer/terminal/park-budget.ts
+++ b/src/renderer/terminal/park-budget.ts
@@ -1,4 +1,5 @@
-import { wouldKillLiveWork, type LiveWorkInput } from './live-work'
+import { effectiveAgentState, wouldKillLiveWork, type LiveWorkInput } from './live-work'
+import type { AgentState } from '@shared/agents/normalize'
/**
* Count cap for parked terminals (see TerminalNode's parkedTerminals). The park window
@@ -23,6 +24,14 @@ export const PARK_MAX = 12
* event (an agent turn ending), so a faster poll would only pay for an answer that cannot have
* changed. The cost of the coarseness is bounded and small — one already-parked xterm held at
* most a minute past the moment it became disposable.
+ *
+ * How long a protected park can live in the worst case: a `working` one resolves within the
+ * stale-working sweep's window (`shared/agents/stale.ts`, 20 minutes) even if the CLI died without
+ * saying so, because that sweep's synthetic end edge reaches the store like any other event. A
+ * `waiting`/`blocked` one has no such sweep and is held until the user answers the question the
+ * badge is showing them — possibly for the whole run. Accepted, and bounded by NODE COUNT rather
+ * than by time: at most one held xterm buffer per non-tmux node actually sitting on an unanswered
+ * prompt. See `offscreen-policy.ts`'s live-work deferral for the same argument at more length.
*/
export const PARK_RECHECK_MS = 60_000
@@ -43,6 +52,26 @@ export function canDisposePark(p: LiveWorkInput): boolean {
return !wouldKillLiveWork(p)
}
+export interface ParkedEntryState {
+ /** `PtyCreateResult.persistent` for the parked session. */
+ tmuxBacked: boolean
+ /** The node's agent state AT PARK TIME. The floor — see `effectiveAgentState` for why a park
+ * cannot rely on a live read alone. */
+ parkedAgentState?: AgentState
+ /** The node's agent state RIGHT NOW, read from that node's own agent-status store. */
+ liveAgentState?: AgentState
+}
+
+/** `canDisposePark` for a park entry: the live read with the park-time snapshot under it. This is
+ * the form all three park levers actually ask (they hold entries, not states), and the one place
+ * the floor is applied — a lever that assembled the state itself could forget it. */
+export function canDisposeParkedEntry(e: ParkedEntryState): boolean {
+ return canDisposePark({
+ tmuxBacked: e.tmuxBacked,
+ agentState: effectiveAgentState(e.liveAgentState, e.parkedAgentState)
+ })
+}
+
/** Keys to dispose so the park stays within `max`, oldest first. Caller passes keys in park
* order (Map insertion order — TerminalNode always deletes before re-inserting on re-park).
*
@@ -103,6 +132,9 @@ export function armParkExpiry<H>(
clear: (h) => clearTimeout(h as unknown as ReturnType<typeof setTimeout>)
}
): ParkTimer {
+ // Declared BEFORE `tick` closes over it: a `timers.set` that ran its callback synchronously
+ // (a fake, a shimmed scheduler) would otherwise hit the temporal dead zone and throw.
+ let handle: H | undefined
const tick = (): void => {
if (canDispose()) {
dispose()
@@ -110,6 +142,10 @@ export function armParkExpiry<H>(
}
handle = timers.set(tick, PARK_RECHECK_MS)
}
- let handle = timers.set(tick, windowMs)
- return { cancel: () => timers.clear(handle) }
+ handle = timers.set(tick, windowMs)
+ return {
+ cancel: () => {
+ if (handle !== undefined) timers.clear(handle)
+ }
+ }
}