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
fix(windows): hook process cost, inherited session markers, pane-read budget and Codex trust key (#1180)
priitkustalabe54e62d15dd
diff --git a/CLAUDE.md b/CLAUDE.mdindex d52edec82..f09d5fba6 100644--- a/CLAUDE.md+++ b/CLAUDE.md@@ -117,6 +117,18 @@ await, and the emulator's paste mode is checked again immediately before the synthe installed build (2026-09-14): with the `\r` in the same write as the paste, Codex rendered thewhole envelope in its composer and never submitted it, so the delivery reported `stalled`; aseparate Enter moments later sent it. A pane that never shows the envelope gets no Enter at all.+**Both Windows owner reads get a longer budget than the 2 s `PANE_PROBE_TIMEOUT_MS`.** The session+host's `messageOwnerV1` and `NativeWindowsPane.owner()` run the same PowerShell console/CIM probe+(`readWindowsConsoleOwner`, its own child bounded at 4 s), measured at ~2.4 s on a loaded Windows 11+machine — so under the 2 s bound every Windows target read `unknown` and refused as+`targetPaneUnreadable`, permanently, behind an error that invites a retry. `PtyManager.+paneProbeTimeoutMs` answers `WINDOWS_PANE_PROBE_TIMEOUT_MS` (8 s) for exactly the backends+`paneOwner` routes to that probe, and both shells forward it as the optional+`AgentMessagingDeps.paneProbeTimeoutMs` through ONE helper, `ptyPaneProbeDeps`, which binds the read+and its budget together (an optional dep that is not forwarded fails silently). SSH and tmux keep 2 s: that bound exists because+a lapsed ssh probe leaves a child alive that can turn into a full login against a dead master, a+hazard a local `powershell.exe` does not have. The verdict rules are unchanged; only the deadline+moves.An older live host refuses these unknown commands while keeping the v1/v2 terminal contract intact;never replace it automatically or fall back to name-only input to enable messaging. Windows OpenCodecontext exports go through `directExecutableInvocation` like every other app-owned subprocess (see@@ -1088,6 +1100,13 @@ unreachable there by construction; a Linux host is expected to have its own. Und`electron-vite dev` the last candidate resolves against `process.cwd()`, which is where`scripts/build-tmux.mjs` writes its artifact. If tmux is unavailable from all three,`PtyManager` still falls back to a plain shell; `TMUX`/`TMUX_PANE` are stripped from the child env to avoid nesting refusal.+The same strip, one layer up, applies to a LAUNCHER that was itself an agent session: started from a+Claude Code terminal, the app used to hand `CLAUDE_CODE_CHILD_SESSION` and its siblings to every pane,+and the Claude CLI there then turned transcript saving off (no ⌘M view, no context meter, nothing for+`--resume`). `buildPtyEnv` deletes the explicit, measured `NESTED_AGENT_ENV_STRIP` list+(`core/nested-agent-env.ts`) and `ACCOUNT_SCOPE_UPDATE_ENV` lists the same names, so a tmux server+seeded from such an environment does not hand them back (the #419 mechanism). Explicit names, never a+`CLAUDE*` prefix sweep: `CLAUDE_CONFIG_DIR` and `CODEX_HOME` are how a managed account is selected.**A session-host session follows its most recently ACTIVE viewer, like tmux's `window-sizelatest`** (issue #914). Under tmux a relay-mirrored phone is its own tmux client, so dismissing itsdiff --git a/CONTRIBUTING.md b/CONTRIBUTING.mdindex 2ebb54386..9f4cc522f 100644--- a/CONTRIBUTING.md+++ b/CONTRIBUTING.md@@ -63,6 +63,9 @@ Do not replace that read with a stored `agentId` or the restart heuristic's deepAn interpreter such as `node` is named by its script's package `bin` entry, never as `node`, sonpm-installed CLIs such as Codex are recognized. A session released by park expiry or offscreenrelease is still messageable: existence and routing ask the backend, not the attached client.+Both Windows owner reads (session host and direct ConPTY) shell out to PowerShell and take ~2.4 s, so+they get their own `WINDOWS_PANE_PROBE_TIMEOUT_MS` through `PtyManager.paneProbeTimeoutMs`; ssh and+tmux keep the 2 s bound. A shell that wires agent messaging must forward that optional dep.Never put the submitting Enter in the same write as a message paste: `core/settled-submit.ts`pastes, waits for the envelope to render, then submits separately, on every backend.The persistent session-host transport has its own versioned messaging extension: the host checks@@ -525,6 +528,10 @@ anything else. Board-level fields survive every transform — `pullLinks` is oneonly used cells; an xterm buffer (the renderer, the Windows session host's headless emulator,`NativeWindowsPane`) allocates every line at full width. Size them with `xtermScrollback` from`src/shared/scrollback.ts` (≤ 10k), so the host never keeps history the renderer cannot show.+- **The app's own environment is not the panes' environment.** Whatever launched nodeterm (often an+ agent CLI's shell) leaves markers in `process.env` that describe THAT session. `buildPtyEnv` strips+ an explicit list (`TMUX`, `NESTED_AGENT_ENV_STRIP`); add a name there, with its measurement, rather+ than a prefix sweep — `CLAUDE_CONFIG_DIR`/`CODEX_HOME` select managed accounts and must survive.- **A new session-host push frame must be negotiated at `hello`, never just sent.** An older`SessionHostClient` treats EVERY push frame whose `type` is not `data` as an exit, and adiff --git a/src/core/agents/agent-message.test.ts b/src/core/agents/agent-message.test.tsindex 029a20b6f..0cd3e0d0d 100644--- a/src/core/agents/agent-message.test.ts+++ b/src/core/agents/agent-message.test.ts@@ -1,4 +1,5 @@import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest'+import { PANE_PROBE_TIMEOUT_MS } from './pane-probe'import {awaitReceipt,deliverAgentMessage,@@ -57,6 +58,9 @@ function recorder(over: Partial<DeliveryDeps> = {}, entry: MirrorEntry | undefinlocked: false,emit: (e) => listeners.forEach((l) => l(e)),deps: {+ // Declared because `deliverAgentMessage` reads it (optionally) on every delivery — the G5+ // proxy below treats an undeclared read as a failure, which is how a new dep is caught.+ paneProbeTimeoutMs: () => PANE_PROBE_TIMEOUT_MS,paneOwner: async (id) => {order.push(`paneOwner:${id}`)return claudePane@@ -584,3 +588,36 @@ describe('deliverAgentMessage — outcomes carry the receipt and the trace', ()expect(out).toMatchObject({ kind: 'delivered', traced: 'memory' })})})++describe('deliverAgentMessage — the per-target pane-read budget (paneProbeTimeoutMs)', () => {+ // A Windows pane read (PowerShell console/CIM probe) was measured at ~2.4 s. The 2 s default+ // abandons it; the backend-chosen budget must reach BOTH the pre-write and the post-write probe.+ beforeEach(() => vi.useFakeTimers())+ afterEach(() => vi.useRealTimers())+ const slowPane = (ms: number) => async (): Promise<typeof claudePane> => {+ await new Promise((r) => setTimeout(r, ms))+ return claudePane+ }++ it('without the dep, a 3 s read is abandoned at the 2 s default — exactly as before', async () => {+ const r = recorder({ paneProbeTimeoutMs: undefined, paneOwner: slowPane(3000) })+ const p = deliverAgentMessage(req(), r.deps)+ await vi.advanceTimersByTimeAsync(PANE_PROBE_TIMEOUT_MS)+ await expect(p).resolves.toEqual({ kind: 'targetPaneUnreadable' })+ expect(r.sends).toEqual([])+ })++ it('with an 8 s budget a 3 s read answers on both probes, so the write is neither refused nor called replaced', async () => {+ const r = recorder({ paneProbeTimeoutMs: () => 8000, paneOwner: slowPane(3000) })+ const p = deliverAgentMessage(req(), r.deps)+ await vi.advanceTimersByTimeAsync(3000) // the pre-write probe answers+ expect(r.sends).toHaveLength(1)+ await vi.advanceTimersByTimeAsync(3000) // the post-write probe answers+ r.emit({ nodeId: 'n-dst', newTurn: true, verified: true })+ await vi.advanceTimersByTimeAsync(0)+ const out = await p+ expect(out.kind).not.toBe('targetPaneUnreadable')+ // A lapsed second probe reads as "a different pane" — that is what this budget must prevent.+ expect(out.kind).not.toBe('deliveredToReplacedTarget')+ })+})diff --git a/src/core/agents/agent-message.ts b/src/core/agents/agent-message.tsindex 667d72b35..d165a950b 100644--- a/src/core/agents/agent-message.ts+++ b/src/core/agents/agent-message.ts@@ -116,6 +116,15 @@ export interface DeliveryRequest {export interface DeliveryDeps {/** Kernel truth about the target's pane. Unbounded by contract — this module bounds it. */paneOwner(nodeId: string): Promise<PaneOwner | null>+ /**+ * How long THIS target's pane read may take before it is abandoned as unreadable. Optional:+ * absent ⇒ `PANE_PROBE_TIMEOUT_MS`, i.e. byte-identical to before this existed.+ *+ * It is per TARGET, not global, because the backends differ by an order of magnitude and the 2s+ * default encodes an ssh-specific hazard (see `WINDOWS_PANE_PROBE_TIMEOUT_MS`). A Windows+ * session-host pane is read by enumerating the process table and simply cannot answer in 2s.+ */+ paneProbeTimeoutMs?(nodeId: string): number/*** Did the target's pane request bracketed paste? UNIMPLEMENTED — nothing wires this yet, and* `PtyManager.bracketPasteRequested` (which read `#{bracket_paste_flag}`, a tmux-3.7+ format) was@@ -380,7 +389,8 @@ export async function deliverAgentMessage(// ssh-controlmaster-fallback). This module probes AT MOST TWICE per delivery and never loops;// any caller that wants to retry an `unknown` needs backoff plus a per-target cap BEFORE its// second attempt, not after the incident.- const before = await probeWithin(() => deps.paneOwner(req.targetNodeId), PANE_PROBE_TIMEOUT_MS)+ const probeMs = deps.paneProbeTimeoutMs?.(req.targetNodeId) ?? PANE_PROBE_TIMEOUT_MS+ const before = await probeWithin(() => deps.paneOwner(req.targetNodeId), probeMs)const verdict = isAgentPane(before, req.targetAgentId, req.targetBinaries)const facts: DeliveryFacts = {notPermitted: req.notPermitted,@@ -473,7 +483,7 @@ export async function deliverAgentMessage(// stranger's shell. The post-check CANNOT un-send the bytes; the residual window is unchanged.// What it buys is that the sender is TOLD and the trace records it, and that// `deliveredToReplacedTarget` is never reported as success.- const after = await probeWithin(() => deps.paneOwner(req.targetNodeId), PANE_PROBE_TIMEOUT_MS)+ const after = await probeWithin(() => deps.paneOwner(req.targetNodeId), probeMs)if (!samePane(owner, after, req.targetAgentId, req.targetBinaries)) {watch.cancel()const t = await trace('deliveredToReplacedTarget')diff --git a/src/core/agents/agent-messaging.ts b/src/core/agents/agent-messaging.tsindex 6b300df2d..131e683f6 100644--- a/src/core/agents/agent-messaging.ts+++ b/src/core/agents/agent-messaging.ts@@ -121,8 +121,28 @@ export interface MessagingStoredNode {* Every side effect and every store read, injected — same reasoning as `DeliveryDeps`: the suite* tests the SERVICE (scope→switch→flow→deps→reply) without a pty, a workspace file or a window.*/+/**+ * The pane-identity half of `AgentMessagingDeps`, bound to the PtyManager that owns the panes: the+ * owner read AND the budget that read gets, as one unit. Both shells spread this rather than each+ * wiring the two methods by hand — `paneProbeTimeoutMs` is optional, so a shell that forwarded the+ * read but not its budget would typecheck, pass every other test, and quietly put every Windows+ * target back behind the 2 s bound that refuses it as `targetPaneUnreadable`.+ */+export function ptyPaneProbeDeps(pty: {+ paneOwner(nodeId: string): Promise<PaneOwner | null>+ paneProbeTimeoutMs(nodeId: string): number+}): Pick<AgentMessagingDeps, 'paneOwner' | 'paneProbeTimeoutMs'> {+ return {+ paneOwner: (nodeId) => pty.paneOwner(nodeId),+ paneProbeTimeoutMs: (nodeId) => pty.paneProbeTimeoutMs(nodeId)+ }+}+export interface AgentMessagingDeps {paneOwner(nodeId: string): Promise<PaneOwner | null>+ /** Per-target pane-read budget; see `DeliveryDeps.paneProbeTimeoutMs`. Optional — absent keeps+ * the 2s default for every target, i.e. exactly the pre-existing behaviour. */+ paneProbeTimeoutMs?(nodeId: string): numbersendEnvelope(nodeId: string, envelope: string, expected?: PaneOwner): Promise<boolean>envelopePasteReady?(nodeId: string): Promise<boolean>/**@@ -619,10 +639,12 @@ export function renderMessageOutcome(o: AgentMessageOutcome): AgentMessageReplyreturn {ok: false,error:- `targetPaneUnreadable: the target's pane could not be read in time (the ssh/tmux probe ` +- `failed or timed out) — this says nothing about what is running in it. On an SSH project ` +- `this usually means the host link is saturated or reconnecting; the message was refused ` +- `rather than sent blind. ${advice}`,+ `targetPaneUnreadable: the target's pane could not be read — this says nothing about ` ++ `what is running in it, and the message was refused rather than sent blind. On an SSH ` ++ `project this usually means the host link is saturated or reconnecting. On Windows it ` ++ `can also mean the session host predates the pane-identity verb (messageOwnerV1), in ` ++ `which case it resolves when that process next restarts and retrying now will not help. ` ++ `${advice}`,result: o}case 'targetNotAgentPane':@@ -783,6 +805,9 @@ export async function runDelivery(const delivery: DeliveryDeps = {paneOwner: (id) => deps.paneOwner(id),+ paneProbeTimeoutMs: deps.paneProbeTimeoutMs+ ? (id) => deps.paneProbeTimeoutMs!(id)+ : undefined,// #210 retired the `#{bracket_paste_flag}` probe with a "do not reintroduce" note// (pty-manager.ts): pre-3.7 tmux cannot distinguish "the app did not ask" from "I cannot// ask". So the dep answers true and the gate never refuses on it. Since #453 the deliverydiff --git a/src/core/agents/hook-curl-config-sh.test.ts b/src/core/agents/hook-curl-config-sh.test.tsnew file mode 100644index 000000000..597836b31--- /dev/null+++ b/src/core/agents/hook-curl-config-sh.test.ts@@ -0,0 +1,53 @@+// The two emitters of the curl-config escaping rule must agree byte for byte: `headerLine` (POSIX+// sh, inside every generated hook client) and `curlHeaderConfigLine` (Node). The sh one has a fast+// path that skips its `tr -d` strip when the value is made only of [A-Za-z0-9._-] — the strip is+// the identity there, and skipping it saves a command substitution and a pipeline on every hook+// event. Using the Node emitter as the oracle proves both branches apply the one rule.+import { describe, it, expect } from 'vitest'+import { spawnSync } from 'node:child_process'+import { curlHeaderConfigLine, curlHeaderConfigSh } from './hook-curl-config-sh'++const HAS_SH = !spawnSync('sh', ['-c', 'exit 0']).error++/** Run the generated emitter for one value, passed through the environment like the real ones. */+function shEmit(value: string): string {+ const fn = curlHeaderConfigSh('nt_test_headers', [{ name: 'X-Test', valueRef: '$NT_TEST_VALUE' }], '# test')+ const res = spawnSync('sh', ['-c', `${fn}\nnt_test_headers`], {+ encoding: 'utf8',+ env: { PATH: process.env.PATH ?? '', NT_TEST_VALUE: value }+ })+ expect(res.status).toBe(0)+ return res.stdout+}++/** Values that must take the STRIP path, each holding the one character its label names. */+const STRIP_CASES: [string, string, string][] = [+ ['a double quote', 'abc"def', '"'],+ ['a backslash', 'abc\\def', '\\'],+ ['a carriage return', 'abc\rdef', '\r'],+ ['a line feed', 'abc\ndef', '\n'],+ ['a trailing CRLF', 'token\r\n', '\r']+]++describe.skipIf(!HAS_SH)('curl header config: the sh emitter matches the Node oracle', () => {+ it.each([+ ['a real node token (fast path)', 'kid1.mac-ABC_def'],+ ['a UUID bearer (fast path)', '3f2a9c1e-77b0-4c1d-9a51-0f5e2d8b6c43'],+ ['an empty value', ''],+ ['a space and other punctuation', 'a b;c$d'],+ ['non-ASCII letters', 'tökén']+ ])('%s', (_label, value) => {+ expect(shEmit(value)).toBe(curlHeaderConfigLine('X-Test', value))+ })++ it.each(STRIP_CASES)('%s is stripped exactly as the Node emitter strips it', (_label, value, ch) => {+ // A fixture that silently lost its character (an unescaped backslash, a normalised CRLF) would+ // take the fast path and prove nothing about the strip.+ expect(value).toContain(ch)+ const out = shEmit(value)+ expect(out).toBe(curlHeaderConfigLine('X-Test', value))+ // The value BETWEEN the config line's own quotes must not keep the character.+ const emitted = out.slice('header = "X-Test: '.length, -'"\n'.length)+ expect(emitted).not.toContain(ch)+ })+})diff --git a/src/core/agents/hook-curl-config-sh.ts b/src/core/agents/hook-curl-config-sh.tsindex cda847079..f877a18ac 100644--- a/src/core/agents/hook-curl-config-sh.ts+++ b/src/core/agents/hook-curl-config-sh.ts@@ -48,9 +48,26 @@ const TR_STRIP_SET = CURL_CONFIG_STRIP.map((c) =>** `valueRef` is the sh expression holding the value, e.g. `$NODETERM_HOOK_TOKEN` — it is expanded* inside double quotes here, so it is never word-split or globbed.+ *+ * THE FAST PATH, and why it is not a second copy of the rule. The strip costs a command+ * substitution plus a two-stage pipeline — three processes per header, nine per POST — and a hook+ * fires on every tool call of every agent. On Windows each of those is an MSYS fork that the+ * antivirus scans, and a handful of busy sessions was measured creating ~10 processes a second+ * from this one function. So a value made ONLY of `[A-Za-z0-9._-]` skips the strip: none of the+ * four stripped characters is in that alphabet, so stripping such a value is the identity, and+ * that alphabet is exactly what every real value is drawn from (`kid.mac`, a UUID, an integer+ * revision, or empty). Anything else — i.e. anything that COULD hold one of the four — still goes+ * through the one `tr -d` below, unchanged. The gate only decides whether the rule can matter; it+ * never restates it. (A locale that widens `A-Z` admits more letters, never a quote, a backslash+ * or a line break.)*/function headerLine(name: string, valueRef: string): string {- return ` printf 'header = "${name}: %s"\\n' "$(printf %s "${valueRef}" | tr -d '${TR_STRIP_SET}')"`+ return [+ ` case "${valueRef}" in`,+ ` *[!A-Za-z0-9._-]*) printf 'header = "${name}: %s"\\n' "$(printf %s "${valueRef}" | tr -d '${TR_STRIP_SET}')" ;;`,+ ` *) printf 'header = "${name}: %s"\\n' "${valueRef}" ;;`,+ ' esac'+ ].join('\n')}/**diff --git a/src/core/agents/hook-endpoint-failover-sh.ts b/src/core/agents/hook-endpoint-failover-sh.tsindex d6ac56aa1..6d04e6c80 100644--- a/src/core/agents/hook-endpoint-failover-sh.ts+++ b/src/core/agents/hook-endpoint-failover-sh.ts@@ -157,7 +157,11 @@ export const OWNED_ENDPOINT_FALLBACK_SH = `# neither names an existing directory: the unknown-owner case. Never the global dirs (see above).nt_token_dir_of() {nt_otd="$NODETERM_NODE_TOKEN_DIR"- [ -n "$nt_otd" ] || nt_otd=$(nt_token_dir_beside "$1")+ # nt_token_dir_beside SETS $nt_tdb_dir (no subshell on the per-event path); it prints nothing.+ if [ -z "$nt_otd" ]; then+ nt_token_dir_beside "$1"+ nt_otd="$nt_tdb_dir"+ fi[ -n "$nt_otd" ] && [ -d "$nt_otd" ] || return 1(cd "$nt_otd" 2>/dev/null && pwd -P)}diff --git a/src/core/agents/hooks/antigravity-script.test.ts b/src/core/agents/hooks/antigravity-script.test.tsindex 572809604..d983fad36 100644--- a/src/core/agents/hooks/antigravity-script.test.ts+++ b/src/core/agents/hooks/antigravity-script.test.ts@@ -182,30 +182,35 @@ describe('the managed script for antigravity', () => {// antigravity code — and compared equal to this branch's output before being pinned here.// If the SHARED script legitimately changes, recompute these deliberately from the base// commit's builder — a silent diff here is exactly the regression to catch.+ //+ // RECOMPUTED deliberately for the Windows hook-cost change (no subshell/mkdir on the pending+ // dir once it exists, token read by `read` instead of `head`, the `[A-Za-z0-9._-]` curl-config+ // header fast path): the shared script changed for every agent, so every pin moved. Each+ // change is pinned behaviourally in managed-script / node-token-sh / hook-curl-config tests.const expected: Record<string, [string, string]> = {claude: [- '26e5dd697ee602a053c6a8ec054128dfb1fad0255b63d65efefed82106660ecc',- '6d7202781175407bc84d6831b1e1d5aba44574212ceb1c2e506aef5e9d9dac3d'+ '0c160e0081608c44e327bb22f394aa51e17e852bc277523d0edee9c6d867711d',+ 'e0fd180e49fd26fca4b74b281f1357c8d26eea6338b39dc20e6a38e266ced42f'],codex: [- '9b47a045193b8e434139215d8c6992bda1926e86eaa7078d666eb2fac254d660',- '736e0076437ff236673664d1d3c44807e9a0f54fe8cc49676f1a8a5978c787e1'+ '592fe88ee069db002c9f5c385a2e0465f9659bade3f0bd18c86b5b51f7644e59',+ '3a09c15cb7a3ce6ba71f8bc695a50e58346f05c8015b2eb8812b8003a2e384ea'],gemini: [- '06d6c8ef62ae425c6aa253afc1536cb0913dc5ef4a173b1ce66c8a163849ec73',- 'bc1a805b3ceb015f61bdf2bc66fa5c9b8f6b0c236f4cfd761cba20db4dd0bafc'+ 'c3fb01424ff2a78012ffd6e87200430badfe60b05f603731bf205ee3b791f988',+ '23d62f97dc80483fba92ef760c0dc6a5b3e2f923ce706915739baee1b76579d8'],opencode: [- 'ee9c4a9a35e0456d1f5853a0737efe6d1064ad47942ab40cb79d3305fb232161',- 'b2935b048eb450759c9652eb1fb8b5047fc5816e28150f446eb2aeccc8941e51'+ '910dc7bc71c9af9043f05509d72584c633a790c0dee66d621baeee1db671845f',+ '89d5b0c9b9fc083befb429493093af76d48c5ff5782b6f9cfdb2cdb1adf44344'],grok: [- '000363fb622b1fbe65579763557596ff4d0cab972cb61fb6c184e340ba1263ef',- '42c5f271ba8656a161dd1e06b05309b020fd4b92c95064c1ed70a6b9dab72672'+ 'fe9636e0e6e961109a3d96079a5f10d0304d77e751a6d1de57aa2810b2075b6c',+ '313c0e80dd5160d61b893d8438c952d8a40a1d13bb9ff5280730df507ae910b2'],copilot: [- '3e21c72e394caa5c703cf1f06c017e82b3aedb6502f15c9ca7324e3e956c9678',- '766e961c8138cb1d2ade63be3fa420eeb1af7f53dbcfa658def6e09bd189b390'+ '8907ee6ac3274cc92f3aa44f55119cc3d42b5a2446fcbd4a847fe42064c1f015',+ '27117418faf66ab0c5960cdec22d0bf2594058df0874910b5da16cb56c10c528']}const sha = (s: string): string => createHash('sha256').update(s).digest('hex')diff --git a/src/core/agents/hooks/antigravity.test.ts b/src/core/agents/hooks/antigravity.test.tsindex 09aaa2797..bcb8c46ea 100644--- a/src/core/agents/hooks/antigravity.test.ts+++ b/src/core/agents/hooks/antigravity.test.ts@@ -467,12 +467,15 @@ describe('the Windows wrapper (content)', () => {if (line === 'if not defined NT_SH goto :nt_drain') continueexpect(w).toContain(line)}- // Pinned bytes of the codex wrapper as it was before the probe lines were shared.+ // Pinned bytes of the codex wrapper as it was before the probe lines were shared, plus the+ // deliberate no-nodeterm-env early exit added since.expect(codex).toBe(['@echo off','rem Managed by nodeterm (agent-hooks). Regenerated on every app launch; edits are lost.','setlocal EnableExtensions',+ // The no-nodeterm-env early exit: a codex run outside nodeterm drains without a shell.+ 'if not defined NODETERM_NODE_ID if not defined CODEX_THREAD_ID goto :nt_drain','set "NT_SCRIPT=%~dp0codex.sh"','if not exist "%NT_SCRIPT%" goto :nt_drain','set "NT_SH="',diff --git a/src/core/agents/hooks/codex-trust.test.ts b/src/core/agents/hooks/codex-trust.test.tsindex 0fea07163..089cb4338 100644--- a/src/core/agents/hooks/codex-trust.test.ts+++ b/src/core/agents/hooks/codex-trust.test.ts@@ -1,6 +1,13 @@-import { describe, expect, it } from 'vitest'+import { readFileSync, writeFileSync } from 'fs'+import path from 'path'+import { beforeEach, describe, expect, it } from 'vitest'+import { testTmpDir } from '../../test-tmp'import {assertTomlTablesUnique,+ computeTrustKey,+ computeTrustedHash,+ readHookTrustEntries,+ removeHookTrustEntries,tableHeaderPath,upsertHookTrustEntriesInContent,type CodexTrustEntry@@ -62,3 +69,49 @@ describe('upsertHookTrustEntriesInContent', () => {expect(() => upsertHookTrustEntriesInContent(before, [entry])).toThrow(/defined twice/)})})++// Why: Codex's own /hooks flow writes the table key as a TOML literal string+// ([hooks.state.'C:\x\hooks.json:stop:0:0']) while we write a basic string+// ([hooks.state."C:\\x\\hooks.json:stop:0:0"]). Both spell the same key, so+// missing one form made install() append a second table and Codex refused the+// whole config.toml with a duplicate-key error on the next launch.+describe('codex trust blocks written as TOML literal-string keys', () => {+ let dir: string+ let entry: CodexTrustEntry+ let key: string+ let hash: string++ beforeEach(() => {+ dir = testTmpDir('nt-codex-trust-')+ const sourcePath = path.join(dir, 'hooks.json')+ writeFileSync(sourcePath, '{}')+ entry = { sourcePath, eventLabel: 'stop', groupIndex: 0, handlerIndex: 0, command: 'hook' }+ key = computeTrustKey(entry)+ hash = computeTrustedHash(entry)+ })++ const literalBlock = (enabled: boolean): string =>+ `[hooks.state.'${key}']\nenabled = ${enabled}\ntrusted_hash = "${hash}"\n`++ const headerCount = (content: string): number =>+ content.split('\n').filter((line) => line.startsWith('[hooks.state.')).length++ it('upsert collapses a literal and a basic copy of the same key into one block', () => {+ const basic = upsertHookTrustEntriesInContent('', [entry])+ const updated = upsertHookTrustEntriesInContent(`${literalBlock(true)}\n${basic}`, [entry])+ expect(headerCount(updated)).toBe(1)+ })++ it('readHookTrustEntries reports a literal-key block', () => {+ const configPath = path.join(dir, 'config.toml')+ writeFileSync(configPath, literalBlock(true))+ expect(readHookTrustEntries(configPath).get(key)).toEqual({ trustedHash: hash, enabled: true })+ })++ it('removeHookTrustEntries removes a literal-key block', () => {+ const configPath = path.join(dir, 'config.toml')+ writeFileSync(configPath, `[tui]\nx = 1\n\n${literalBlock(true)}`)+ removeHookTrustEntries(configPath, [key])+ expect(headerCount(readFileSync(configPath, 'utf8').replace(/\r\n/g, '\n'))).toBe(0)+ })+})diff --git a/src/core/agents/hooks/codex-windows-wrapper.ts b/src/core/agents/hooks/codex-windows-wrapper.tsindex d022a2987..d47b029b0 100644--- a/src/core/agents/hooks/codex-windows-wrapper.ts+++ b/src/core/agents/hooks/codex-windows-wrapper.ts@@ -50,10 +50,18 @@ import { buildWindowsHookWrapper } from './windows-hook-wrapper'export { WINDOWS_SH_CANDIDATES, windowsShProbeBatch } from './windows-hook-wrapper'+/**+ * The variables codex.sh needs to do anything: its gate needs NODETERM_NODE_ID, its+ * thread-identity prelude needs CODEX_THREAD_ID. With neither, the script drains and exits 0.+ */+export const CODEX_SESSION_ENV = ['NODETERM_NODE_ID', 'CODEX_THREAD_ID'] as const+/** The wrapper's file name, beside the managed script it runs. */export const CODEX_WINDOWS_WRAPPER_FILE = 'codex-hook.cmd'/** The batch wrapper's content: `codex.sh`, found beside the wrapper, run by the first POSIX shell. */export function buildCodexWindowsWrapper(): string {- return buildWindowsHookWrapper('codex.sh', 'codex')+ // The script's own gate, answered before paying for a shell: with neither variable set,+ // codex.sh can only drain stdin and exit 0 (see buildWindowsHookWrapper's `skipUnlessAnyEnv`).+ return buildWindowsHookWrapper('codex.sh', 'codex', { skipUnlessAnyEnv: CODEX_SESSION_ENV })}diff --git a/src/core/agents/hooks/managed-script.ts b/src/core/agents/hooks/managed-script.tsindex 1684cf99c..b6d5bc1d8 100644--- a/src/core/agents/hooks/managed-script.ts+++ b/src/core/agents/hooks/managed-script.ts@@ -350,7 +350,10 @@ export function buildManagedScript('# event is dropped SILENTLY (a lost Stop leaves the node stuck RUNNING). A 0600 temp file read','# back with `payload@file` fixes both; it is deleted by whichever POST last reads it (below).','nt_payload_file="$HOME/.nodeterm/pending/payload-$$.tmp"',- '(umask 077; mkdir -p "$HOME/.nodeterm/pending") 2>/dev/null || :',+ '# `mkdir -p` on a directory that exists changes nothing — not even its mode — so the test is',+ '# the same outcome without the subshell and the mkdir: two processes on every event after the',+ '# first one this host ever ran.',+ '[ -d "$HOME/.nodeterm/pending" ] || (umask 077; mkdir -p "$HOME/.nodeterm/pending") 2>/dev/null || :','(umask 077; printf %s "$payload" > "$nt_payload_file") 2>/dev/null || :','# ...but hand curl a path IT can open. Under Git Bash / MSYS this script runs in a POSIX shell','# while `curl` is a NATIVE Windows binary (System32, or the one shipped with git), so `$HOME`',diff --git a/src/core/agents/hooks/windows-hook-wrapper.test.ts b/src/core/agents/hooks/windows-hook-wrapper.test.tsindex 04261506e..28fea6adc 100644--- a/src/core/agents/hooks/windows-hook-wrapper.test.ts+++ b/src/core/agents/hooks/windows-hook-wrapper.test.ts@@ -11,7 +11,8 @@ import {WINDOWS_SH_REQUIRED_MESSAGE,windowsHookWrapperFile} from './windows-hook-wrapper'-import { buildCodexWindowsWrapper } from './codex-windows-wrapper'+import { buildCodexWindowsWrapper, CODEX_SESSION_ENV } from './codex-windows-wrapper'+import { buildAntigravityWindowsWrapper } from './antigravity-windows-wrapper'// These pin what the generators CONSTRUCT. Whether cmd.exe runs them is a device fact (the codex// wrapper's was measured for #567/#685; the new agents' rows are in the docs' device checklists).@@ -47,7 +48,38 @@ describe('buildWindowsHookWrapper', () => {})it('keeps the codex wrapper byte-identical (it is the same template)', () => {- expect(buildWindowsHookWrapper('codex.sh', 'codex')).toBe(buildCodexWindowsWrapper())+ expect(buildWindowsHookWrapper('codex.sh', 'codex', { skipUnlessAnyEnv: CODEX_SESSION_ENV })).toBe(+ buildCodexWindowsWrapper()+ )+ })+})++describe('buildWindowsHookWrapper — the no-session early exit is opt-in', () => {+ const EARLY = 'if not defined NODETERM_NODE_ID if not defined CODEX_THREAD_ID goto :nt_drain'++ it('drains before locating a shell when none of the named variables is set', () => {+ const lines = buildWindowsHookWrapper('codex.sh', 'codex', { skipUnlessAnyEnv: CODEX_SESSION_ENV }).split('\r\n')+ // Right after setlocal, before the script/shell search costs anything.+ expect(lines[3]).toBe(EARLY)+ expect(lines.indexOf(EARLY)).toBeLessThan(lines.indexOf('set "NT_SH="'))+ })++ it('is on for codex only — never for the shared wrappers installed for other agents', () => {+ expect(buildCodexWindowsWrapper()).toContain(EARLY)+ for (const agent of ['gemini', 'grok', 'copilot']) {+ expect(buildWindowsHookWrapper(`${agent}.sh`, agent)).not.toContain('if not defined NODETERM_NODE_ID')+ }+ })++ it('never reaches antigravity, where silence means "run the tool"', () => {+ expect(buildAntigravityWindowsWrapper()).not.toContain('if not defined NODETERM_NODE_ID')+ expect(buildAntigravityWindowsWrapper()).not.toContain('CODEX_THREAD_ID')+ })++ it('refuses a variable name cmd.exe could read as anything but a name', () => {+ for (const bad of ['', 'A B', 'X&calc', '%PATH%', '1X']) {+ expect(() => buildWindowsHookWrapper('codex.sh', 'codex', { skipUnlessAnyEnv: [bad] })).toThrow()+ }})})diff --git a/src/core/agents/hooks/windows-hook-wrapper.ts b/src/core/agents/hooks/windows-hook-wrapper.tsindex 5b8e61ea3..1beb9f278 100644--- a/src/core/agents/hooks/windows-hook-wrapper.ts+++ b/src/core/agents/hooks/windows-hook-wrapper.ts@@ -62,12 +62,30 @@ export function windowsHookWrapperFile(scriptFileName: string): string {* CRLF: batch files are line-oriented and cmd.exe is not reliably tolerant of LF, so this is CRLF* regardless of the host that generated it. `writer` names the agent in the bail comment only; the* codex wrapper's bytes are pinned by a test and must not move.+ *+ * `skipUnlessAnyEnv` (opt-in) drains and exits before locating a shell when NONE of the named+ * variables is set — for a script whose own gate would do exactly that after starting one, so an+ * agent run outside nodeterm costs one findstr per event instead of a Git launcher stub, a bash+ * and a cat. `if not defined` reads an empty value as undefined, the same answer sh's `-z` gives.+ * Anything that COULD be a nodeterm session still reaches the script, which stays the only place+ * that decides what one is. Codex only: NEVER antigravity, whose hooks are synchronous gates where+ * silence means "run the tool" — a drain there would change the decision (antigravity-decision.ts).*/-export function buildWindowsHookWrapper(scriptFileName: string, writer = 'the agent'): string {+export function buildWindowsHookWrapper(+ scriptFileName: string,+ writer = 'the agent',+ opts: { skipUnlessAnyEnv?: readonly string[] } = {}+): string {+ const skip = opts.skipUnlessAnyEnv ?? []+ for (const name of skip) {+ // Interpolated into a batch line: a plain identifier, never anything cmd.exe would parse.+ if (!/^[A-Za-z_][A-Za-z0-9_]*$/.test(name)) throw new Error(`invalid env name: ${name}`)+ }const lines = ['@echo off','rem Managed by nodeterm (agent-hooks). Regenerated on every app launch; edits are lost.','setlocal EnableExtensions',+ ...(skip.length ? [`${skip.map((n) => `if not defined ${n} `).join('')}goto :nt_drain`] : []),`set "NT_SCRIPT=%~dp0${scriptFileName}"`,'if not exist "%NT_SCRIPT%" goto :nt_drain','set "NT_SH="',diff --git a/src/core/agents/node-token-sh.test.ts b/src/core/agents/node-token-sh.test.tsnew file mode 100644index 000000000..97de4cca5--- /dev/null+++ b/src/core/agents/node-token-sh.test.ts@@ -0,0 +1,116 @@+// `nt_read_node_token`, run by a real `sh`. Every generated hook client calls it on every event, so+// it reads the token with the shell's own `read` rather than `$(head -n 1 …)` — a process saved per+// event. These pin that the builtin reads a token file the way `head -n 1` did: first line only, a+// last line with no newline still counts, and one trailing CR (a CRLF file) is dropped.+import { describe, it, expect, beforeEach, afterEach } from 'vitest'+import { spawnSync } from 'node:child_process'+import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs'+import { tmpdir } from 'node:os'+import { join } from 'node:path'+import { NODE_TOKEN_READ_SH } from './node-token-sh'+import { OWNED_ENDPOINT_FALLBACK_SH } from './hook-endpoint-failover-sh'++const HAS_SH = !spawnSync('sh', ['-c', 'exit 0']).error+/** A path the POSIX shell can open (Git for Windows' sh understands /c/… as well as C:/…). */+const shPath = (p: string): string => p.replace(/\\/g, '/')++describe.skipIf(!HAS_SH)('nt_read_node_token under a real sh', () => {+ let dir = ''+ let tokens = ''+ beforeEach(() => {+ dir = mkdtempSync(join(tmpdir(), 'nt-token-read-'))+ tokens = join(dir, 'node-tokens')+ mkdirSync(tokens)+ })+ afterEach(() => rmSync(dir, { recursive: true, force: true }))++ /** Read the token for `node-1`, the way a client does: from the dir beside the endpoint file. */+ function read(env: Record<string, string> = {}): string {+ const res = spawnSync(+ 'sh',+ ['-c', `${NODE_TOKEN_READ_SH}\nnt_read_node_token\nprintf '[%s]' "$nt_node_token"`],+ {+ encoding: 'utf8',+ env: {+ PATH: process.env.PATH ?? '',+ HOME: shPath(join(dir, 'home')),+ NODETERM_NODE_ID: 'node-1',+ NODETERM_HOOK_ENDPOINT: shPath(join(dir, 'hook-endpoint.env')),+ ...env+ }+ }+ )+ expect(res.status).toBe(0)+ return res.stdout+ }+ const token = (body: string): void => writeFileSync(join(tokens, 'node-1'), body)++ it('reads the first line of an LF file', () => {+ token('kid1.mac-abc\nsecond-line\n')+ expect(read()).toBe('[kid1.mac-abc]')+ })++ it('reads a file whose only line has no newline', () => {+ token('kid1.mac-abc')+ expect(read()).toBe('[kid1.mac-abc]')+ })++ it('drops the CR of a CRLF file', () => {+ const body = 'kid1.mac-abc\r\n'+ expect(body).toContain('\r')+ token(body)+ expect(read()).toBe('[kid1.mac-abc]')+ })++ it('presents nothing when there is no token file', () => {+ expect(read()).toBe('[]')+ })++ it('presents nothing without a node id, even when a file exists', () => {+ token('kid1.mac-abc\n')+ expect(read({ NODETERM_NODE_ID: '' })).toBe('[]')+ })++ it('prefers an explicitly advertised token dir over the one beside the endpoint file', () => {+ token('beside\n')+ const advertised = join(dir, 'advertised')+ mkdirSync(advertised)+ writeFileSync(join(advertised, 'node-1'), 'advertised\n')+ expect(read({ NODETERM_NODE_TOKEN_DIR: shPath(advertised) })).toBe('[advertised]')+ })+})++// `nt_token_dir_beside` has a SECOND caller: the owned-endpoint walk the canvas-control and+// context-link shims run (`nt_token_dir_of`). It decides which nodeterm instance owns the node by+// the token dir an endpoint keeps, so a helper that stops answering there silently drops the+// "never fall back to a foreign instance" rule for an endpoint that does not advertise its dir.+describe.skipIf(!HAS_SH)('nt_token_dir_of (the failover walk) under a real sh', () => {+ let dir = ''+ beforeEach(() => {+ dir = mkdtempSync(join(tmpdir(), 'nt-token-dir-of-'))+ })+ afterEach(() => rmSync(dir, { recursive: true, force: true }))++ function tokenDirOf(endpointFile: string, env: Record<string, string> = {}): { code: number | null; out: string } {+ const start = OWNED_ENDPOINT_FALLBACK_SH.indexOf('nt_token_dir_of() {')+ const end = OWNED_ENDPOINT_FALLBACK_SH.indexOf('\n}\n', start) + 3+ expect(start).toBeGreaterThan(-1)+ const fn = OWNED_ENDPOINT_FALLBACK_SH.slice(start, end)+ const res = spawnSync('sh', ['-c', `${NODE_TOKEN_READ_SH}\n${fn}\nnt_token_dir_of "$1"`, 'sh', shPath(endpointFile)], {+ encoding: 'utf8',+ env: { PATH: process.env.PATH ?? '', NODETERM_NODE_TOKEN_DIR: '', ...env }+ })+ return { code: res.status, out: res.stdout.trim() }+ }++ it('finds the token dir BESIDE an endpoint file that advertises none', () => {+ mkdirSync(join(dir, 'node-tokens'))+ const r = tokenDirOf(join(dir, 'hook-endpoint.env'))+ expect(r.code).toBe(0)+ expect(r.out.replace(/\\/g, '/').toLowerCase()).toMatch(/\/node-tokens$/)+ })++ it('reports an unknown owner when there is no such directory', () => {+ expect(tokenDirOf(join(dir, 'hook-endpoint.env')).code).toBe(1)+ })+})diff --git a/src/core/agents/node-token-sh.ts b/src/core/agents/node-token-sh.tsindex 2eaeb9909..bd89be568 100644--- a/src/core/agents/node-token-sh.ts+++ b/src/core/agents/node-token-sh.ts@@ -47,8 +47,8 @@* already gave. It can never read as `forged` (that needs OUR kid over another node's mac, and* the filename forbids it) and it can never read as a different node.*- * So each candidate can turn `legacy` into `verified` and nothing else. The happy path costs- * exactly one `head`, as before: only a miss walks.+ * So each candidate can turn `legacy` into `verified` and nothing else. The happy path costs one+ * file read by the shell's own `read` and no process at all: only a miss walks.** NOT USED BY the codex launcher (`core/codex-identity-proxy.ts`), deliberately. That client* REFUSES outright when the endpoint file is unreadable (`nt_fail hook-endpoint-unavailable`) and@@ -68,13 +68,16 @@* anchors to `$NODETERM_HOOK_ENDPOINT`.*/export const NODE_TOKEN_READ_SH = [- '# `<dir of $1>/node-tokens`, or nothing when $1 names no directory. The endpoint file and the',- '# token dir are siblings on every surface we ship, so this needs no per-platform knowledge.',+ '# Sets $nt_tdb_dir to `<dir of $1>/node-tokens`, or to nothing when $1 names no directory. The',+ '# endpoint file and the token dir are siblings on every surface we ship, so this needs no',+ '# per-platform knowledge. It SETS A VARIABLE rather than printing so the caller needs no command',+ '# substitution: this runs on every hook event, and a subshell there is a whole process.','nt_token_dir_beside() {',+ ' nt_tdb_dir=""',' case "$1" in */*) ;; *) return 0 ;; esac',' nt_tdb=${1%/*}',' [ -n "$nt_tdb" ] || return 0',- " printf '%s/node-tokens' \"$nt_tdb\"",+ ' nt_tdb_dir="$nt_tdb/node-tokens"','}','# nt_read_node_token [endpoint-file] — sets $nt_node_token. See node-token-sh.ts for why the','# fallbacks below can only ever turn `legacy` into `verified`, and never anything into anything',@@ -85,15 +88,30 @@ export const NODE_TOKEN_READ_SH = [' [ -n "$NODETERM_NODE_ID" ] || return 0',' nt_ntep="$1"',' [ -n "$nt_ntep" ] || nt_ntep="$NODETERM_HOOK_ENDPOINT"',+ ' nt_token_dir_beside "$nt_ntep"',' for nt_ntd in \\',' "$NODETERM_NODE_TOKEN_DIR" \\',- ' "$(nt_token_dir_beside "$nt_ntep")" \\',+ ' "$nt_tdb_dir" \\',' "$HOME/.nodeterm/node-tokens" \\',' "$HOME/.nodeterm-server/node-tokens" \\',' "$HOME/.config/node-terminal/node-tokens" \\',' "$HOME/Library/Application Support/node-terminal/node-tokens"; do',' [ -n "$nt_ntd" ] || continue',- ' nt_node_token=$(head -n 1 "$nt_ntd/$NODETERM_NODE_ID" 2>/dev/null) || nt_node_token=""',+ ' # The first line, read by the shell itself: what `head -n 1` in a command substitution gave,',+ ' # without the process. `read` answers non-zero at EOF, which is also what an unterminated',+ ' # last line looks like — and it has ALREADY assigned that line by then, so the status is',+ ' # ignored and only an unopenable file (the redirection fails, nothing is assigned) stays',+ ' # empty. The braces are what put a missing file\'s "cannot open" behind 2>/dev/null.',+ ' nt_node_token=""',+ ' { IFS= read -r nt_node_token < "$nt_ntd/$NODETERM_NODE_ID"; } 2>/dev/null || :',+ ' # A CRLF token file. Git for Windows\' bash drops the CR inside a command substitution, so the',+ ' # `head` form read such a file clean there; `read` keeps it. Drop one trailing CR so the two',+ ' # agree. It costs a process ONLY when the value really ends in a control character — never',+ ' # for a token we wrote — and the wire was never at risk either way: the header emitter',+ ' # strips CR from anything outside the token alphabet.',+ ' case "$nt_node_token" in',+ ' *[[:cntrl:]]) nt_cr=$(printf \'\\r\'); nt_node_token=${nt_node_token%"$nt_cr"} ;;',+ ' esac',' [ -n "$nt_node_token" ] && return 0',' done',' nt_node_token=""',diff --git a/src/core/agents/pane-probe.ts b/src/core/agents/pane-probe.tsindex 4c02805a3..f6c0feebd 100644--- a/src/core/agents/pane-probe.ts+++ b/src/core/agents/pane-probe.ts@@ -36,6 +36,32 @@*/export const PANE_PROBE_TIMEOUT_MS = 2000+/**+ * The budget for a pane read on Windows, where there is no tmux and no ssh: both Windows backends+ * read the pane through the same PowerShell console/CIM probe (`readWindowsConsoleOwner`, which+ * bounds its own child at 4 s) — the session host to answer `messageOwnerV1` for a persistent+ * pane, and `NativeWindowsPane.owner()` for a non-persistent one.+ *+ * MEASURED on Windows 11 (26200), on a loaded machine: `powershell.exe -NoProfile` ++ * `Get-CimInstance Win32_Process` costs ~2.4s, of which ~1.4s is PowerShell STARTUP alone. Under+ * `PANE_PROBE_TIMEOUT_MS` (2s) that read can never answer, so every Windows pane read `unknown` and+ * every agent-to-agent delivery refused as `targetPaneUnreadable` — a permanent failure wearing a+ * transient error's clothes. This budget must stay ABOVE the probe's own 4 s child timeout plus+ * the host IPC hop, or the outer bound fires first and discards an answer that was on its way.+ *+ * Larger is SAFE here in a way it would not be on the ssh leg, and the difference is the whole+ * reason this is a separate constant rather than a bigger `PANE_PROBE_TIMEOUT_MS`:+ * - The hazard the 2s bound protects against is ssh-specific — a lapsed probe leaves its `ssh`+ * child alive to `runAsync`'s 15s reap, and with `ControlMaster=auto` against a dead master each+ * of those is a full LOGIN (the 72k-logins shape). There is no ssh here: the child is one local+ * `powershell.exe` that exits on its own.+ * - Waiting longer cannot admit anything extra. The verdict is unchanged; only the deadline moves.+ * The cost is latency on a refusal: a delivery to a pane that genuinely cannot be read now takes+ * this long to say so, twice. Agent-to-agent messaging is not a hot path, and the per-pair rate+ * limiter still sits in front of it.+ */+export const WINDOWS_PANE_PROBE_TIMEOUT_MS = 8000+/*** Run `fn`, but never wait longer than `timeoutMs`.*diff --git a/src/core/agents/phone-spawned-identity.test.ts b/src/core/agents/phone-spawned-identity.test.tsindex 20aca9749..937e72db2 100644--- a/src/core/agents/phone-spawned-identity.test.ts+++ b/src/core/agents/phone-spawned-identity.test.ts@@ -246,8 +246,10 @@ describe('a phone-spawned session presents its per-node token', () => {// byte-identical to a script that never had the line — while the generated sh stays valid// (deleting the assignment would leave an empty `if … then fi`, and a script that fails to// parse proves nothing about what a real old script sent).- .replace(/nt_node_token=\$\(head -n 1[^\n]*/, 'nt_node_token=""')+ // The token read is a `read` redirect now (no `head` process); blank that line the same way.+ .replace(/\{ IFS= read -r nt_node_token <[^\n]*/, 'nt_node_token=""').replace(/nt_client_rev=\d+\n/, '')+ expect(old).not.toContain('IFS= read -r nt_node_token')expect(old).not.toContain('nt_client_rev=')expect(old).not.toContain('$NODETERM_NODE_TOKEN_DIR/$NODETERM_NODE_ID')const script = writeScript('hook-5.sh', old)diff --git a/src/core/codex-thread-identity-sh.test.ts b/src/core/codex-thread-identity-sh.test.tsindex 77d70761d..86100f153 100644--- a/src/core/codex-thread-identity-sh.test.ts+++ b/src/core/codex-thread-identity-sh.test.ts@@ -260,3 +260,39 @@ describe('codex thread identity prelude — the exported agent label and grant',await expect(run('/bin/sh', ['-n', agentScript])).resolves.toBeTruthy()})})++// The record is parsed by ONE `read` loop rather than a `sed | head` pair per field (a process+// budget: this prelude runs on every hook event). These pin that the loop reads it the way the+// pipelines did: the FIRST line per key wins, even when its value is empty, and a last line with+// no newline still counts. The one deliberate difference is CRLF, asserted on its own below.+describe('codex thread identity prelude — record parsing edge cases', () => {+ const endpoint = (): string => `${dir}/hook-endpoint.env`++ it('takes the FIRST line of a repeated key', async () => {+ record('thread-dup', `nodeId=node-first\nnodeId=node-second\nendpoint=${endpoint()}\n`)+ expect(await resolve({ CODEX_THREAD_ID: 'thread-dup' })).toBe(`node-first|${endpoint()}|1`)+ })++ it('an EMPTY first occurrence still wins, so the record resolves nothing', async () => {+ record('thread-empty', `nodeId=\nnodeId=node-late\nendpoint=${endpoint()}\n`)+ expect(await resolve({ CODEX_THREAD_ID: 'thread-empty' })).toBe('||')+ })++ it('reads a last line that has no trailing newline', async () => {+ const body = `nodeId=node-u\nendpoint=${endpoint()}`+ expect(body.endsWith('\n')).toBe(false)+ record('thread-unterminated', body)+ expect(await resolve({ CODEX_THREAD_ID: 'thread-unterminated' })).toBe(`node-u|${endpoint()}|1`)+ })++ it('accepts a CRLF record — the one deliberate widening', async () => {+ // Git for Windows' text-mode `sed` dropped the CR, so the old pipelines resolved a CRLF record+ // there; GNU/BSD `sed` kept it and the charset checks refused the value. One trailing CR per+ // line is now dropped on every platform, BEFORE the same checks run, so nothing outside the+ // value alphabets can get through — a record otherwise valid simply resolves everywhere.+ const body = `nodeId=node-c\r\nendpoint=${endpoint()}\r\nsignature=x\r\n`+ expect(body.split('\r\n')).toHaveLength(4) // the fixture really is CRLF+ record('thread-crlf', body)+ expect(await resolve({ CODEX_THREAD_ID: 'thread-crlf' })).toBe(`node-c|${endpoint()}|1`)+ })+})diff --git a/src/core/codex-thread-identity-sh.ts b/src/core/codex-thread-identity-sh.tsindex 5aab2bf1f..ee11f9e5e 100644--- a/src/core/codex-thread-identity-sh.ts+++ b/src/core/codex-thread-identity-sh.ts@@ -7,7 +7,7 @@* node it belongs to, and the node's badge/status would simply never move. This recovers the node* binding from the thread id.*- * The mapping file is parsed as DATA (`sed`), never sourced as shell code, and both recovered+ * The mapping file is parsed as DATA (a `read` loop — no process per field), never sourced as shell code, and both recovered* fields are re-validated before they are exported. The record itself is HMAC-signed by* `codex-identity-proxy.ts`; this prelude cannot verify that signature (no key in an agent's* shell), which is why the charset re-validation below is not redundant.@@ -75,17 +75,41 @@ if [ -z "\${NODETERM_NODE_ID-}" ] && [ -n "\${CODEX_THREAD_ID-}" ]; then# ('' = system).nt_codex_try() {[ -r "$1" ] || return 0- nt_a=$(sed -n 's/^accountId=//p' "$1" | head -n 1)+ # ONE PASS, by the shell itself. This used to be five \`sed | head\` command substitutions —+ # fifteen processes per record, on every hook event of every tool shell — and it is the+ # same read: the FIRST line that starts with each key wins (what \`head -n 1\` took, and what+ # \`codex-identity-proxy.ts\` matches on the TypeScript side), the value is everything after+ # the first \`=\`, and a record whose last line has no newline still counts (\`read\` answers+ # non-zero there but has already assigned the line, hence the \`|| [ -n … ]\`). \`IFS=\` and+ # \`-r\` keep the value byte-for-byte: no trimming, no backslash processing. Still DATA, never+ # sourced. The \`nt_s*\` flags are what make "first" mean first even for an empty value.+ nt_a='' nt_n='' nt_e='' nt_g='' nt_c=''+ nt_sa='' nt_sn='' nt_se='' nt_sg='' nt_sc=''+ while IFS= read -r nt_l || [ -n "$nt_l" ]; do+ # A CRLF record. Git for Windows' \`sed\` reads in text mode and dropped the CR, so the old+ # pipeline resolved such a record on Windows; \`read\` keeps it and every charset check+ # below would then refuse the value. Drop ONE trailing CR to keep that working. (On+ # Linux/macOS the old \`sed\` kept the CR and the record was refused, so this is the one+ # place the rewrite is more lenient — harmlessly: the values are validated AFTER the+ # strip, exactly as before.) The \`printf\` costs a process only for a line that really+ # ends in a control character, which no record we write does.+ case "$nt_l" in+ *[[:cntrl:]]) nt_cr=$(printf '\\r'); nt_l=\${nt_l%"$nt_cr"} ;;+ esac+ case "$nt_l" in+ accountId=*) [ -n "$nt_sa" ] || { nt_a=\${nt_l#accountId=}; nt_sa=1; } ;;+ nodeId=*) [ -n "$nt_sn" ] || { nt_n=\${nt_l#nodeId=}; nt_sn=1; } ;;+ endpoint=*) [ -n "$nt_se" ] || { nt_e=\${nt_l#endpoint=}; nt_se=1; } ;;+ agentId=*) [ -n "$nt_sg" ] || { nt_g=\${nt_l#agentId=}; nt_sg=1; } ;;+ canvasControl=*) [ -n "$nt_sc" ] || { nt_c=\${nt_l#canvasControl=}; nt_sc=1; } ;;+ esac+ done < "$1" 2>/dev/null# The record's own account line must AGREE with the directory it was found in. A system# record's line is empty or the reserved word 'system'; a managed record's line is its id.case "$2" in'') case "$nt_a" in ''|system) ;; *) return 0 ;; esac ;;*) [ "$nt_a" = "$2" ] || return 0 ;;esac- nt_n=$(sed -n 's/^nodeId=//p' "$1" | head -n 1)- nt_e=$(sed -n 's/^endpoint=//p' "$1" | head -n 1)- nt_g=$(sed -n 's/^agentId=//p' "$1" | head -n 1)- nt_c=$(sed -n 's/^canvasControl=//p' "$1" | head -n 1)case "$nt_n" in ''|*[!A-Za-z0-9._-]*) return 0 ;; esaccase "$nt_e" in /*) ;; *) return 0 ;; esac# SPACES ARE ADMITTED DELIBERATELY, and this line is the reason to say so. The endpoint is@@ -96,7 +120,11 @@ if [ -z "\${NODETERM_NODE_ID-}" ] && [ -n "\${CODEX_THREAD_ID-}" ]; then# socket it names then reaches curl --unix-socket "$NODETERM_HOOK_SOCK" — every expansion# inside double quotes, so a space cannot split into extra arguments. The charset is what# keeps quoting and command substitution out; the leading slash above keeps it absolute.- [ "$(printf %s "$nt_e" | tr -cd 'A-Za-z0-9._/ -')" = "$nt_e" ] || return 0+ # The same alphabet as a negated \`case\` class — the idiom the node id and the agent id use+ # two lines away — instead of a \`tr -cd\` round-trip compared with the original: identical+ # verdict, no command substitution and no pipeline. The space is the one character that+ # needs quoting inside the class.+ case "$nt_e" in *[!A-Za-z0-9._/\\ -]*) return 0 ;; esac# A PRE-AGENT record (no agentId line, or an empty one) means codex with canvas control:# every record written before the agent fields existed was written by this same Codex# spine, and codex is unconditionally canvas-control-capable, so the implied pairdiff --git a/src/core/nested-agent-env.test.ts b/src/core/nested-agent-env.test.tsnew file mode 100644index 000000000..64060337f--- /dev/null+++ b/src/core/nested-agent-env.test.ts@@ -0,0 +1,27 @@+import { describe, expect, it } from 'vitest'+import { NESTED_AGENT_ENV_STRIP } from './nested-agent-env'+import { ACCOUNT_SCOPE_UPDATE_ENV } from './pty-manager'++describe('NESTED_AGENT_ENV_STRIP', () => {+ it('carries the marker that actually turned transcript saving off', () => {+ // The measured culprit (see the module docblock). Losing this entry restores the bug in full.+ expect(NESTED_AGENT_ENV_STRIP).toContain('CLAUDE_CODE_CHILD_SESSION')+ })++ it('never strips a variable this app SETS to bind an account', () => {+ // The whole reason this is an explicit list and not a `CLAUDE*` / `CODEX*` prefix sweep: these+ // are how a managed-account node selects its config dir. Sweeping them would silently run every+ // managed-account session as the system account — a much worse bug than the one being fixed.+ for (const kept of ['CLAUDE_CONFIG_DIR', 'CODEX_HOME', 'NODETERM_CODEX_ACCOUNT_ID']) {+ expect(NESTED_AGENT_ENV_STRIP).not.toContain(kept)+ }+ })++ it('is also listed for tmux update-environment, or a seeded server re-adds them', () => {+ // The #419 rule: a shared tmux server inherits the env of the client that starts it, so a+ // per-client delete alone does not reach sessions created later through that server.+ for (const name of NESTED_AGENT_ENV_STRIP) {+ expect(ACCOUNT_SCOPE_UPDATE_ENV).toContain(name)+ }+ })+})diff --git a/src/core/nested-agent-env.ts b/src/core/nested-agent-env.tsnew file mode 100644index 000000000..041dcf7a0--- /dev/null+++ b/src/core/nested-agent-env.ts@@ -0,0 +1,37 @@+/**+ * Markers that say "this process IS an agent CLI session", inherited from whatever launched the+ * app — stripped from every pty nodeterm spawns.+ *+ * The same reasoning as the `TMUX` strip beside it in `buildPtyEnv`: launching the app from inside+ * a session must not make the sessions it spawns believe they are nested inside that one. Both are+ * one hazard — an environment describing the LAUNCHER, inherited by children that are not it.+ *+ * MEASURED (2026-09-11, this repo, which is developed from inside nodeterm): with nodeterm started+ * from a Claude Code terminal, every canvas terminal inherited `CLAUDE_CODE_CHILD_SESSION=1`, and+ * the Claude CLI in each pane correctly concluded it was a nested child session and turned+ * TRANSCRIPT SAVING OFF. That is not cosmetic — a session with no transcript has no ⌘M chat view,+ * no context meter, no find-bar index and nothing for `claude --resume` to resume, i.e. most of+ * what this app reads about an agent node. The pane reported it (`⚠ Transcript saving is off —+ * inherited CLAUDE_CODE_CHILD_SESSION marker`); nothing else did.+ *+ * EXPLICIT NAMES, NEVER A `CLAUDE*` PREFIX SWEEP. `CLAUDE_CONFIG_DIR` is set BY this app to select+ * a managed account (see `ACCOUNT_SCOPE_UPDATE_ENV`), and `CODEX_HOME` likewise — a prefix sweep+ * would delete the very variable the account binding rides on and silently run every managed-account+ * node as the system account. Credential names are a different hazard with its own list+ * (`AUTH_ENV_STRIP`); this one is only about identity markers.+ *+ * Claude Code only, deliberately. These eight are measured from a real session. Codex's own+ * `CODEX_THREAD_ID` is the obvious analogue, but it is also load-bearing for the shared-identity+ * prelude (`codexThreadIdentityResolverSh`, see CLAUDE.md), so it needs its own reasoning and its+ * own measurement rather than being swept in here by symmetry — follow-up.+ */+export const NESTED_AGENT_ENV_STRIP: readonly string[] = [+ 'CLAUDECODE',+ 'CLAUDE_CODE_CHILD_SESSION',+ 'CLAUDE_CODE_ENTRYPOINT',+ 'CLAUDE_CODE_SESSION_ID',+ 'CLAUDE_CODE_BRIDGE_SESSION_ID',+ 'CLAUDE_CODE_MESSAGING_SOCKET',+ 'CLAUDE_CODE_MESSAGING_TOKEN',+ 'CLAUDE_PID'+]diff --git a/src/core/pty-manager.pane-owner.test.ts b/src/core/pty-manager.pane-owner.test.tsindex ceab4071f..dacb6460f 100644--- a/src/core/pty-manager.pane-owner.test.ts+++ b/src/core/pty-manager.pane-owner.test.ts@@ -660,3 +660,47 @@ describe('PtyManager.backgroundWrite — released session-host node', () => {expect(hostMessaging.writeDetached).not.toHaveBeenCalled()})})++describe('PtyManager.paneProbeTimeoutMs — the budget follows the backend that answers', () => {+ // Both Windows backends read the pane through a PowerShell console/CIM probe (~2.4 s measured);+ // tmux and ssh keep the 2 s bound that exists for ssh's sake. Asked in `paneOwner`'s own order.+ type Mgr = {+ sessions: Map<string, unknown>+ byPersistKey: Map<string, string>+ released: Map<string, unknown>+ paneProbeTimeoutMs(id: string): number+ }+ beforeEach(() => {+ vi.resetModules()+ initPlatform(fakePlatform())+ })+ afterEach(() => resetPlatformForTests())++ it('keeps 2 s for a local tmux pane and for an SSH pane', async () => {+ const { PANE_PROBE_TIMEOUT_MS } = await import('./agents/pane-probe')+ expect(((await manager()) as unknown as Mgr).paneProbeTimeoutMs(NODE)).toBe(PANE_PROBE_TIMEOUT_MS)+ const ssh = (await manager({ sshRemote: { conn: {}, controlPath: '/tmp/cm' } })) as unknown as Mgr+ expect(ssh.paneProbeTimeoutMs(NODE)).toBe(PANE_PROBE_TIMEOUT_MS)+ })++ it('gives an attached and a RELEASED session-host pane the Windows budget', async () => {+ const { WINDOWS_PANE_PROBE_TIMEOUT_MS } = await import('./agents/pane-probe')+ const mgr = (await manager()) as unknown as Mgr+ mgr.sessions.clear()+ mgr.sessions.set('host-session', { persistKey: NODE, indexKey: NODE, sessionHost: true })+ mgr.byPersistKey.set(NODE, 'host-session')+ expect(mgr.paneProbeTimeoutMs(NODE)).toBe(WINDOWS_PANE_PROBE_TIMEOUT_MS)+ mgr.sessions.clear()+ mgr.byPersistKey.clear()+ mgr.released.set(NODE, { sessionId: 'host-session', remote: false, sessionHost: true })+ expect(mgr.paneProbeTimeoutMs(NODE)).toBe(WINDOWS_PANE_PROBE_TIMEOUT_MS)+ })++ it('gives a non-persistent native Windows pane the Windows budget too — same probe', async () => {+ const { WINDOWS_PANE_PROBE_TIMEOUT_MS } = await import('./agents/pane-probe')+ const mgr = (await manager({ tmux: null })) as unknown as Mgr+ mgr.sessions.set('plain-session', { indexKey: 'plain-node', nativeWindowsPane: {} })+ mgr.byPersistKey.set('plain-node', 'plain-session')+ expect(mgr.paneProbeTimeoutMs('plain-node')).toBe(WINDOWS_PANE_PROBE_TIMEOUT_MS)+ })+})diff --git a/src/core/pty-manager.ts b/src/core/pty-manager.tsindex cd38d44ed..74f3fb195 100644--- a/src/core/pty-manager.ts+++ b/src/core/pty-manager.ts@@ -103,6 +103,7 @@ import {} from './agents/pane-ownership'import { PANE_OWNER_FMT, foregroundArgvArgs, paneOwnerFrom, parseCombinedPaneOwner, parsePaneOwner } from './agents/pane-owner'import { binariesFor, isAgentPane, type PaneOwner } from '../shared/agents/pane-owner-predicate'+import { PANE_PROBE_TIMEOUT_MS, WINDOWS_PANE_PROBE_TIMEOUT_MS } from './agents/pane-probe'import { readSpawnResources, spawnResourceNote } from './spawn-resources'import {primePtyCeiling,@@ -145,6 +146,7 @@ import {import { normalizeSessionBackend } from '../shared/session-backend'import { releasePty, type ReleasablePty } from './pty-release'import { terminateWindowsProcessTree } from '../session-host/windows-process-tree'+import { NESTED_AGENT_ENV_STRIP } from './nested-agent-env'import { effectiveSize, type PtySize } from './pty-size'import { machOArch, archMismatch } from './macho-arch'import { writeScrollback, readScrollback, deleteScrollback } from './scrollback-store'@@ -429,7 +431,12 @@ export const ACCOUNT_SCOPE_UPDATE_ENV: readonly string[] = [...AUTH_ENV_STRIP,'CODEX_HOME','NODETERM_CODEX_ACCOUNT_ID',- ...CODEX_AUTH_ENV_STRIP+ ...CODEX_AUTH_ENV_STRIP,+ // The nested-session markers ride along for exactly the auth-strip reason stated above: the+ // shared tmux server inherits the env of the client that STARTS it, so deleting these from each+ // client env alone would leave a server seeded by an app launched inside a Claude Code session+ // handing them back to every session created afterwards.+ ...NESTED_AGENT_ENV_STRIP]// LEAD-PANE WIDTH (issue #119): `leadPaneWidth` (settings.tmuxLeadPaneWidth) is OPT-IN and 0 by@@ -4202,6 +4209,12 @@ export class PtyManager {delete env.NODETERM_SERVER_PASSWORDdelete env.TMUXdelete env.TMUX_PANE+ // Same shape as the TMUX strip above, one layer up: markers saying the LAUNCHER was itself an+ // agent CLI session must not be inherited by the sessions this app spawns. See+ // `NESTED_AGENT_ENV_STRIP` for the measurement (an inherited CLAUDE_CODE_CHILD_SESSION turned+ // transcript saving OFF in every pane, which costs the ⌘M view, the context meter, the+ // find-bar index and `--resume`).+ for (const k of NESTED_AGENT_ENV_STRIP) delete env[k]// A GUI app launched from Finder/Dock inherits only a minimal PATH, so spawned terminals// couldn't find tools in /usr/local/bin, Homebrew, ~/.local/bin, nvm, bun, etc. (the classic@@ -6697,6 +6710,23 @@ export class PtyManager {}}+ /**+ * How long a `paneOwner` read for this node may take, for callers that bound it.+ *+ * The backend decides, because they differ by an order of magnitude: a tmux/ssh read is one or+ * two round-trips, while both Windows backends shell out to PowerShell + CIM, measured at ~2.4 s+ * on a loaded Windows 11 machine. Asks the same two questions `paneOwner` asks, in its order+ * (a native pane first, then `sessionHostOwns`), so the budget and the backend that answers can+ * never disagree. SSH and tmux keep `PANE_PROBE_TIMEOUT_MS`: that bound exists for ssh's sake.+ */+ paneProbeTimeoutMs(persistKey: string): number {+ const live = this.liveSessionForPersistKey(persistKey)+ if (this.isZellij(persistKey, live)) return PANE_PROBE_TIMEOUT_MS+ return live?.nativeWindowsPane || (!live?.sshRemote && this.sessionHostOwns(persistKey, live))+ ? WINDOWS_PANE_PROBE_TIMEOUT_MS+ : PANE_PROBE_TIMEOUT_MS+ }+/*** WHO owns a node's pane right now, read from the kernel: the pane's pid and tty from tmux, then* the full argv of the tty's FOREGROUND PROCESS GROUP. `paneCommand` above answers one name —diff --git a/src/core/pty-nested-agent-env-spawn.test.ts b/src/core/pty-nested-agent-env-spawn.test.tsnew file mode 100644index 000000000..7d5854ee8--- /dev/null+++ b/src/core/pty-nested-agent-env-spawn.test.ts@@ -0,0 +1,142 @@+/**+ * A launcher's Claude Code session markers must not reach the panes nodeterm spawns+ * (`NESTED_AGENT_ENV_STRIP`). Started from a Claude Code terminal, the app inherits+ * CLAUDE_CODE_CHILD_SESSION and friends; every pane then believed it was a nested child session and+ * the Claude CLI there turned transcript saving off.+ *+ * Asserted on the environment node-pty is actually handed, not on the list: the list alone stays+ * green when the deletion in `buildPtyEnv` is removed.+ *+ * MUTATION: delete the `for (const k of NESTED_AGENT_ENV_STRIP) delete env[k]` line in+ * pty-manager.ts → the fresh-spawn case reddens. Drop `...NESTED_AGENT_ENV_STRIP` from+ * `ACCOUNT_SCOPE_UPDATE_ENV` → the tmux.conf case reddens.+ */+import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest'+import { mkdirSync, mkdtempSync, rmSync } from 'fs'+import os from 'os'+import path from 'path'+import { initPlatform, resetPlatformForTests } from './platform'+import { fakePlatform, type FakePlatform } from './platform-fake'+import { IPC } from '../shared/ipc'+import { DEFAULT_SETTINGS } from '../shared/types'+import type { PtyCreateOptions, PtyCreateResult, Settings } from '../shared/types'+import { accountConfigDir } from './claude-accounts-core'+import { NESTED_AGENT_ENV_STRIP } from './nested-agent-env'++const spawned: Array<{ file: string; args: string[]; env: Record<string, string> }> = []+/** Every tmux side-call and every spawn, in order — the long-lived-server case is about ORDER. */+const events: string[] = []++vi.mock('node-pty', () => ({+ spawn: (file: string, args: string[], options: { env: Record<string, string> }) => {+ spawned.push({ file, args, env: options?.env ?? {} })+ events.push(`spawn ${args.includes('new-session') ? 'new-session' : file}`)+ return {+ onData: () => {}, onExit: () => {}, write: () => {}, resize: () => {},+ pause: () => {}, resume: () => {}, kill: () => {}, pid: 4321+ }+ }+}))+// A tmux server that is ALREADY running, started by a build that predates the marker list: its+// `update-environment` array lacks every marker, and it does not reread the conf.+vi.mock('child_process', async (importOriginal) => {+ const actual = await importOriginal<typeof import('child_process')>()+ type Cb = (err: Error | null, res?: { stdout: string; stderr: string }) => void+ return {+ ...actual,+ execFile: (_file: string, _args: string[], a?: unknown, b?: unknown): unknown => {+ const cb = (typeof a === 'function' ? a : b) as Cb | undefined+ cb?.(null, { stdout: '', stderr: '' })+ return {}+ },+ execFileSync: (_file: string, args: string[]): string => {+ if (args.includes('show-options')) return 'update-environment[0] DISPLAY\n'+ if (args.includes('set-option')) events.push(`set-option ${args[args.length - 1]}`)+ return ''+ }+ }+})+vi.mock('./pty-devices', async (importOriginal) => ({+ ...(await importOriginal<typeof import('./pty-devices')>()),+ readPtyDevices: () => ({ ceiling: 511, inUse: 8 })+}))++const ALICE = 1+const CLAUDE_ACCT = 'claudeacct1'++describe('launcher session markers are stripped from spawned panes', () => {+ let fake: FakePlatform+ let userDataDir: string++ beforeEach(async () => {+ spawned.length = 0+ events.length = 0+ userDataDir = mkdtempSync(path.join(os.tmpdir(), 'nodeterm-nested-env-'))+ fake = fakePlatform({ userDataDir })+ initPlatform(fake)+ for (const name of NESTED_AGENT_ENV_STRIP) vi.stubEnv(name, `launcher-${name}`)+ vi.stubEnv('NODETERM_TEST_UNRELATED', 'kept')+ const { PtyManager } = await import('./pty-manager')+ // The plain in-process backend, on every platform: it runs the same `buildPtyEnv` as tmux and+ // the Windows session host, and is the one whose spawn env node-pty receives in this process.+ const settings: Settings = { ...DEFAULT_SETTINGS, tmuxEnabled: false }+ const mgr = new PtyManager()+ mgr.init(() => settings)+ mgr.registerIpc()+ })+ afterEach(() => {+ vi.unstubAllEnvs()+ resetPlatformForTests()+ rmSync(userDataDir, { recursive: true, force: true })+ })++ const create = (options: Partial<PtyCreateOptions>) =>+ fake.handlers[IPC.ptyCreate](ALICE, {+ cols: 80, rows: 24, persistKey: 'node-1', cwd: os.tmpdir(), ...options+ }) as Promise<PtyCreateResult>++ it('a fresh pane gets none of them, and keeps the account selector and unrelated env', async () => {+ mkdirSync(accountConfigDir(userDataDir, CLAUDE_ACCT), { recursive: true })+ const res = await create({ agentId: 'claude', accountId: CLAUDE_ACCT })+ expect(res.unavailable).toBeUndefined()+ expect(spawned).toHaveLength(1)+ const env = spawned[0].env+ for (const name of NESTED_AGENT_ENV_STRIP) expect(env[name], name).toBeUndefined()+ // An explicit list, never a CLAUDE* sweep: the managed-account binding rides CLAUDE_CONFIG_DIR.+ expect(env.CLAUDE_CONFIG_DIR).toContain(CLAUDE_ACCT)+ expect(env.NODETERM_TEST_UNRELATED).toBe('kept')+ })++ it('the local tmux.conf lists them for update-environment, so a seeded server drops them too', async () => {+ const { tmuxConf } = await import('./pty-manager')+ const line = tmuxConf(10_000)+ .split('\n')+ .find((l) => /^\s*set .*update-environment/.test(l))+ expect(line).toBeDefined()+ for (const name of NESTED_AGENT_ENV_STRIP) expect(line, name).toContain(name)+ })++ it('retrofits an ALREADY-RUNNING tmux server before the session is created', async () => {+ // The conf above is read once, at server start. A server started earlier keeps its old+ // update-environment array, so the names are appended at runtime — and they must land BEFORE+ // new-session, or the session is created from the server's seeded environment.+ const { PtyManager } = await import('./pty-manager')+ const mgr = new PtyManager()+ ;(mgr as unknown as { tmuxPath: string | null }).tmuxPath = '/usr/bin/tmux'+ mgr.init(() => ({ ...DEFAULT_SETTINGS, tmuxEnabled: true }))+ mgr.registerIpc()+ const res = await create({ persistKey: 'node-tmux' })+ expect(res.unavailable).toBeUndefined()+ const created = events.indexOf('spawn new-session')+ expect(created).toBeGreaterThan(-1)+ for (const name of NESTED_AGENT_ENV_STRIP) {+ const appended = events.indexOf(`set-option ${name}`)+ expect(appended, name).toBeGreaterThan(-1)+ expect(appended, name).toBeLessThan(created)+ }+ // And the tmux client itself does not carry them: with update-environment listing a name the+ // client LACKS, tmux removes it from the new session (the #419 removal semantics).+ const client = spawned.find((s) => s.args.includes('new-session'))!+ for (const name of NESTED_AGENT_ENV_STRIP) expect(client.env[name], name).toBeUndefined()+ })+})diff --git a/src/main/agent-messaging.test.ts b/src/main/agent-messaging.test.tsindex a2aaa10bb..b3f258e48 100644--- a/src/main/agent-messaging.test.ts+++ b/src/main/agent-messaging.test.ts@@ -8,9 +8,10 @@* real tmux in `agent-message.realtty.test.ts` — this file assumes both and tests only what the* service adds.*/-import { describe, it, expect, beforeEach, vi } from 'vitest'+import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest'import {deliverFromControl,+ ptyPaneProbeDeps,renderMessageOutcome,onMessagingAgentEvent,createDeliveryQueue,@@ -576,3 +577,57 @@ describe('a target that has not started yet (launch held off screen)', () => {expect(outcome).toEqual({ kind: 'notPermitted', reason: 'unproven-target-owner' })})})++describe('deliverFromControl — the pane-read budget reaches both probes', () => {+ // A Windows pane read (PowerShell console/CIM) takes ~2.4 s. Driven through the shells' own+ // wiring helper and the whole control -> runDelivery -> deliverAgentMessage chain, so dropping+ // the budget at ANY hop turns the first case into `targetPaneUnreadable`.+ beforeEach(() => vi.useFakeTimers())+ afterEach(() => vi.useRealTimers())++ function slowPty(budgetMs: number): {+ pty: Parameters<typeof ptyPaneProbeDeps>[0]+ reads: string[]+ budgetAsks: string[]+ } {+ const reads: string[] = []+ const budgetAsks: string[] = []+ return {+ reads,+ budgetAsks,+ pty: {+ paneOwner: async (nodeId) => {+ reads.push(nodeId)+ await new Promise((r) => setTimeout(r, 3000))+ return { tty: '/dev/pts/9', panePid: 100, paneId: '%1', command: 'claude', argv: ['claude'], pids: [200] }+ },+ paneProbeTimeoutMs: (nodeId) => {+ budgetAsks.push(nodeId)+ return budgetMs+ }+ }+ }+ }++ it('with the Windows budget, a 3 s read is delivered — both reads aimed at the target', async () => {+ const { pty, reads, budgetAsks } = slowPty(8000)+ const deps = fakeDeps(ptyPaneProbeDeps(pty))+ const pending = deliverFromControl(req(), deps)+ await vi.advanceTimersByTimeAsync(10_000)+ const { outcome } = await pending+ expect(outcome.kind).toBe('delivered')+ expect(deps.rec.sent).toHaveLength(1)+ expect(reads).toEqual(['b1', 'b1']) // pre-write and post-write+ expect(budgetAsks).toContain('b1')+ })++ it('under the 2 s default the same read is refused as unreadable, and nothing is sent', async () => {+ const { pty } = slowPty(2000)+ const deps = fakeDeps(ptyPaneProbeDeps(pty))+ const pending = deliverFromControl(req(), deps)+ await vi.advanceTimersByTimeAsync(10_000)+ const { outcome } = await pending+ expect(outcome.kind).toBe('targetPaneUnreadable')+ expect(deps.rec.sent).toHaveLength(0)+ })+})diff --git a/src/main/index.ts b/src/main/index.tsindex 336d4b99b..fff53dd72 100644--- a/src/main/index.ts+++ b/src/main/index.ts@@ -83,6 +83,7 @@ import {isDeliverRequest,messagingEnabledVia,onMessagingAgentEvent,+ ptyPaneProbeDeps,setDeliveryQueue,type AgentMessagingDeps} from '../core/agents/agent-messaging'@@ -2205,7 +2206,7 @@ app.whenReady().then(async () => {// here; everything that authorizes or performs the delivery reads MAIN's stores. See// src/core/agents/agent-messaging.ts for the whole map.const messagingDeps: AgentMessagingDeps = {- paneOwner: (id) => ptyManager.paneOwner(id),+ ...ptyPaneProbeDeps(ptyManager),sendEnvelope: (id, envelope, expected) => ptyManager.sendEnvelope(id, envelope, expected),envelopePasteReady: (id) => ptyManager.envelopePasteReady(id),// Attached OR released-but-running: see AgentMessagingDeps.hasLiveSession.diff --git a/src/server/canvas-control.test.ts b/src/server/canvas-control.test.tsindex f94da79b2..bd9a8bc2d 100644--- a/src/server/canvas-control.test.ts+++ b/src/server/canvas-control.test.ts@@ -163,7 +163,8 @@ describe('initServerCanvasControl', () => {paneOwner,sendEnvelope,hasLiveSession: () => true,- sessionExists: async () => true+ sessionExists: async () => true,+ paneProbeTimeoutMs: () => 2000} as unknown as PtyManagerconst settings = (): Settings => ({ ...DEFAULT_SETTINGS })@@ -284,6 +285,8 @@ describe('initServerCanvasControl', () => {const writes: Array<{ text: string; enter: boolean | undefined }> = []let pasted = ''const legacySendEnvelope = vi.fn(async () => true)+ // The Server shell must hand messaging the pane's own read budget (ptyPaneProbeDeps).+ const paneProbeTimeoutMs = vi.fn((_nodeId: string) => 2000)const pty = {...headlessShell(),createHeadless: vi.fn(async () => ({ sessionId: 'unused', fresh: true })),@@ -315,7 +318,8 @@ describe('initServerCanvasControl', () => {})),sendEnvelope: legacySendEnvelope,hasLiveSession: () => true,- sessionExists: async () => true+ sessionExists: async () => true,+ paneProbeTimeoutMs} as unknown as PtyManagerruntime = await initServerCanvasControl({@@ -357,6 +361,7 @@ describe('initServerCanvasControl', () => {expect(writes[0]).toMatchObject({ enter: false })expect(writes[1]).toEqual({ text: '', enter: true })expect(legacySendEnvelope).not.toHaveBeenCalled()+ expect(paneProbeTimeoutMs).toHaveBeenCalledWith(targetId)})it('publishes its own writes on server-change, never on the outside-edit channel', async () => {@@ -407,7 +412,8 @@ describe('initServerCanvasControl', () => {paneOwner: vi.fn(async () => null),sendEnvelope: vi.fn(async () => true),hasLiveSession: () => true,- sessionExists: async () => true+ sessionExists: async () => true,+ paneProbeTimeoutMs: () => 2000} as unknown as PtyManagerruntime = await initServerCanvasControl({diff --git a/src/server/canvas-control.ts b/src/server/canvas-control.tsindex 794a7ca6e..e4093a1bd 100644--- a/src/server/canvas-control.ts+++ b/src/server/canvas-control.ts@@ -7,6 +7,7 @@ import {deliverStationNotice,messagingEnabledVia,onMessagingAgentEvent,+ ptyPaneProbeDeps,restoreDeliveryQueue,type AgentMessagingDeps} from '../core/agents/agent-messaging'@@ -216,7 +217,7 @@ export async function initServerCanvasControl(factoryRef = factoryconst messaging: AgentMessagingDeps = {- paneOwner: (nodeId) => deps.ptyManager.paneOwner(nodeId),+ ...ptyPaneProbeDeps(deps.ptyManager),// Server delivery has no renderer/xterm echo stream. Capture the headless pane instead and// separate paste from Enter so a fresh TUI cannot swallow the first submit keystroke.sendEnvelope: (nodeId, envelope) =>