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(hooks): self-heal stale hook endpoints for canvas-control and context-link (#445)
enesc8e4c0522915
diff --git a/CLAUDE.md b/CLAUDE.mdindex cbc7ca07c..71e3267ba 100644--- a/CLAUDE.md+++ b/CLAUDE.md@@ -1039,6 +1039,24 @@ else, and its context links must keep classifying across restarts).layout by construction on all three surfaces) and then the well-known data dirs; it is monotone— advertised dir first, keyed by node-id filename in every candidate, and a foreign instance'sdir yields a foreign `kid` = `legacy` = exactly what presenting nothing already gave.+ - **Every generated sh client walks the SAME endpoint failover** (`nt_candidates`/`nt_adopt`,+ `core/agents/hook-endpoint-failover-sh.ts`) — issue #445, the endpoint-level twin of #384: a+ session is pinned for life to the endpoint PATH it got at tmux creation, so an app+ quit/restart (or a retired project id) leaves it POSTing at a dead port while a live endpoint+ file sits right next to it. The managed hook script had the bounded candidate walk (locals+ before tunnels, `nt_fallback_max` 3, token re-read from the ADOPTED endpoint's dir); the two+ shims did not, so hook events healed themselves while every canvas-control verb died with+ "control endpoint unreachable" — in the field, a reviewer launch silently dropped. Now shared,+ one definition. Two server-side halves in `hook-server.ts`: a FAILED `listen()` un-wedges the+ singleton (it used to leave `this.server` set, making every retry a silent no-op at port 0)+ and both `stop()` and the failed-start path delete `hook-endpoint.env` — publication reflects+ listener liveness; a crash skips that, which is exactly what the client walk exists for. An+ HTTP answer of any code is authoritative: only a dead transport (curl 000/'') fails over, so a+ 403/400 is never re-sent to another instance. The walk is skipped under+ `CODEX_SANDBOX_NETWORK_DISABLED` (#367 — the sandbox denies every connect, the hint is the+ right diagnosis) and the final error now distinguishes "no endpoint anywhere" from "an+ advertised endpoint that is not listening" (`STALE_ENDPOINT_HINT`). Desktop quit calls+ `hookServer.stop()` on the second before-quit pass, after the flush window.Enforcement is dated (`NODE_IDENTITY_STRICT_AFTER`, 2026-10-13, read through `isStrictInstant` so aclock years ahead cannot enter strict mode early) with a `settings.hookIdentityStrict` escape hatchdiff --git a/docs/node-identity.md b/docs/node-identity.mdindex 80c63d8f8..e081d43f9 100644--- a/docs/node-identity.md+++ b/docs/node-identity.md@@ -396,6 +396,41 @@ run, whose shim never learned to send the header, posts nothing while the re-attthe node — and is then refused for as long as it lives. It is genuinely indistinguishable from animpostor; the only code answer would be giving up the latch. The escape hatch is what that case has.+### ⚠ The same asymmetry one layer down: a stale ENDPOINT — issue #445++#384's shape repeated at the transport level. A session is pinned for life to the endpoint *path*+it was handed, and that path's FILE can advertise a port nothing listens on: the app quit or+crashed and has not rewritten it yet, the hook server's `start()` failed and left a previous run's+file standing, or the path carries a retired project id that is never rewritten again. The managed+hook script survived all of these — its bounded candidate walk (`nt_candidates`/`nt_adopt`) adopts+a live sibling endpoint and re-reads the token from the adopted dir — while the two sh shims posted+once at the dead port and died with "control endpoint unreachable": hook events healed themselves,+canvas control did not, and the field report was a reviewer launch silently dropped from a live+worktree session.++Three fixes, all in the same change:++- **The walk is shared** (`core/agents/hook-endpoint-failover-sh.ts`), the same extraction+ `node-token-sh.ts` performed for the token read: one definition, three clients. Both shims fail+ over on a dead transport only — an HTTP answer of any code is authoritative and is never re-sent+ to another instance — and re-read the token from each adopted endpoint (`nt_read_node_token+ "$candidate"`). The walk is skipped under `CODEX_SANDBOX_NETWORK_DISABLED` (#367: the sandbox+ denies every connect, so each candidate would burn a doomed curl and the sandbox hint is already+ the right diagnosis).+- **Publication reflects listener liveness**: `hookServer.stop()` and a FAILED `start()` now delete+ `hook-endpoint.env` (the desktop calls `stop()` on quit), and a failed `listen()` no longer+ wedges the singleton — it used to leave `this.server` assigned, so every later `start()` was a+ silent no-op at port 0 under a stale advertisement. A crash skips the delete, which is exactly+ what the client walk exists for.+- **The refusals name the state**: "no endpoint anywhere" and "an advertised endpoint that is not+ listening" are different facts with opposite advice, so the shims append `STALE_ENDPOINT_HINT`+ in the second case instead of leaving one generic sentence covering both.++The safety argument is the walk's own: the node id in the body identifies the session, a foreign+instance that does not know it answers with its ordinary refusal, and a foreign token dir yields a+foreign `kid` = `legacy`. Real /bin/sh coverage: `canvas-control-shim.failover.test.ts`,+`context-link-shim.failover.test.ts`, `hook-server.recovery.test.ts`.+### The escape hatch`settings.hookIdentityStrict` — Settings → Agents → *Require verified node identity for canvasdiff --git a/src/core/agents/hook-endpoint-failover-sh.ts b/src/core/agents/hook-endpoint-failover-sh.tsnew file mode 100644index 000000000..d6c585393--- /dev/null+++ b/src/core/agents/hook-endpoint-failover-sh.ts@@ -0,0 +1,116 @@+/**+ * ENDPOINT FAILOVER, THE SH HALF — one candidate walk, every generated client.+ *+ * A session is pinned for life to the endpoint PATH it was handed at tmux creation+ * (`buildPtyEnv` / `remoteHookEnvArgs`): tmux ignores `-e` on an existing session, and the env of+ * a live shell cannot be rewritten from outside. So every generated sh client ultimately trusts+ * one file on disk, and that file can go stale in ways the session cannot see:+ *+ * - the app quit or crashed and the file still advertises its old random port (issue #445 — a+ * `nodeterm.sh open-agent` from a live worktree session died with "endpoint unreachable"+ * while the reviewer launch it carried was silently dropped);+ * - the path carries a project id that a cross-lineage adoption retired, so the file is never+ * rewritten again while the session keeps posting into it (the managed script's stale-project+ * case);+ * - the session was spawned before any endpoint file existed at all (phone spawn on a bare+ * host).+ *+ * The managed hook script grew this walk first (see the "Fallback ordering and bound" block in+ * `hooks/managed-script.ts` for the measured reasoning behind the ordering and the bound); the+ * canvas-control and context-link shims did not, so the SAME stale file that a hook event healed+ * itself around stopped every canvas-control verb cold — the exact asymmetry issue #384 already+ * documented for the token read, one layer up. The helpers live here now, like+ * `node-token-sh.ts`, because a rule with three copies is a rule where one copy is wrong+ * (this repo's own drift lesson, three times over).+ *+ * What the fragment defines:+ * - `nt_fallback_max` — how many candidates may be tried AFTER the primary failed;+ * - `nt_candidates <tried>` — the candidate endpoint files, one per line, most-likely-alive+ * first (locals before reverse tunnels — they fail independently; tunnels share one fate);+ * - `nt_adopt <file>` — source one candidate, clearing SOCK/PORT/TOKEN_DIR first so a dead+ * transport or a foreign token dir never leaks from one candidate into the next.+ *+ * Callers own the retry loop itself (the managed script's `nt_send_request`, each shim's walk):+ * the POST shape differs per client, the walk does not. After `nt_adopt`, re-read the token with+ * `nt_read_node_token "$candidate"` (node-token-sh.ts) — the capability must come from the dir+ * the adopted endpoint advertises, never from the one being walked away from.+ *+ * Safety is the same argument as the token resolver's: sending one node's request over another+ * instance's endpoint is correct where it can succeed at all — the node id in the body is what+ * identifies the session, a foreign instance that does not know it refuses with its ordinary+ * answer, and a foreign token dir yields a foreign kid = `legacy`, bit-for-bit what presenting+ * nothing already gave.+ */+/**+ * The line both shims append under their generic transport-failure sentence when a transport WAS+ * advertised and nothing — primary or fallback — answered. It names the actual state (a stale+ * endpoint, not a broken canvas link) and the one action that works, so an agent reading it stops+ * relinking/restarting things that were never the problem. Shared for the same reason as the walk:+ * two copies of one diagnosis drift into two diagnoses.+ */+export const STALE_ENDPOINT_HINT =+ 'The endpoint this session was handed appears stale (nodeterm may have quit or restarted since this terminal was created), and no live fallback endpoint answered. If nodeterm is running, retry once — it re-advertises the endpoint on start.'++export const HOOK_ENDPOINT_FALLBACK_SH = [+ '# --- Endpoint failover helpers (shared: managed hook script + both sh shims) ---------------',+ // How many endpoints we may POST to AFTER the primary failed. See the "Fallback ordering and+ // bound" block comment above buildManagedScript for the full reasoning; the short version:+ // the ordered list is (at most 3) LOCAL endpoints followed by the reverse tunnels, only one or+ // two locals can exist on a real host (the two desktop userData paths are per-OS and mutually+ // exclusive), so 3 attempts always reaches a live local endpoint AND still leaves a tunnel slot.+ // The cost ceiling is what bounds it: each dead attempt can burn --max-time 1.5s, because an+ // sshd-held reverse-tunnel socket ACCEPTS and then never answers.+ 'nt_fallback_max=3',+ '# Print the candidate endpoint files, ONE PER LINE, most-likely-alive first, skipping the',+ '# already-tried path ($1) and anything unreadable. Ordering, and why it is not mtime:',+ "# 1. LOCAL endpoints — the host's own Server Edition, then a desktop installed on this host.",+ '# They are written by a process running HERE, a different failure domain from the tunnels.',+ '# 2. The per-project SSH reverse tunnels, freshest first (the old whole-list rule, kept as the',+ "# tie-break within this group, because the live project's endpoint is rewritten and VERIFIED",+ '# on every connect).',+ '# The tunnels all terminate at the SAME desktop, so they share one fate: when the primary tunnel',+ '# is dead (closed laptop) its siblings are almost always dead too, and mtime happily ranks those',+ '# siblings above a local endpoint that is actually listening. That is the whole bug — a host with',+ '# an always-on Server Edition sat silent while every one of its agents ran.',+ 'nt_candidates() {',+ ' nt_tried="$1"',+ ' for nt_c in \\',+ ' "$HOME/.nodeterm-server/hook-endpoint.env" \\',+ ' "$HOME/.config/node-terminal/hook-endpoint.env" \\',+ ' "$HOME/Library/Application Support/node-terminal/hook-endpoint.env"; do',+ ' [ "$nt_c" = "$nt_tried" ] && continue',+ ' [ -r "$nt_c" ] || continue',+ " printf '%s\\n' \"$nt_c\"",+ ' done',+ ' set --',+ // Unquoted glob (with $HOME itself still quoted): the per-project SSH reverse-tunnel+ // endpoints. On no match the pattern stays literal and the `-r` test below drops it.+ ' for nt_c in "$HOME"/.nodeterm/hook-endpoint-*.env; do',+ ' [ "$nt_c" = "$nt_tried" ] && continue',+ ' [ -r "$nt_c" ] || continue',+ ' set -- "$@" "$nt_c"',+ ' done',+ ' [ "$#" -gt 0 ] || return 0',+ ' ls -t "$@" 2>/dev/null',+ '}',+ '# Adopt one candidate endpoint file ($1): source it into NODETERM_HOOK_{SOCK,PORT,TOKEN,VERSION}',+ '# + NODETERM_NODE_TOKEN_DIR. Returns 0 if it was sourced, else 1.',+ '# SOCK/PORT are cleared first so a primary-vs-fallback transport switch (e.g. dead SOCK →',+ '# live PORT) never leaves the stale transport winning in the re-POST below — and, now that we',+ "# may walk several candidates, so one candidate's transport never leaks into the next one.",+ '# NODE_TOKEN_DIR is cleared for the same reason and one more: our token belongs to the instance',+ "# that MINTED it, so carrying our dir into someone else's endpoint would point the read at a",+ '# directory that server cannot verify. Cleared, the newly sourced file sets its own — we then',+ "# present THAT instance's token for this node, or (if it has none) nothing at all, which is",+ '# honest `legacy`.',+ 'nt_adopt() {',+ ' NODETERM_HOOK_SOCK=""',+ ' NODETERM_HOOK_PORT=""',+ ' NODETERM_NODE_TOKEN_DIR=""',+ // stdout swallowed for the same reason as the endpoint source at the top of every client (#186):+ // in the managed script's perm-wait branch this runs in the FOREGROUND of a hook whose stdout+ // reaches the agent's context.+ ' . "$1" >/dev/null 2>&1 || return 1',+ ' return 0',+ '}'+].join('\n')diff --git a/src/core/agents/hook-server.recovery.test.ts b/src/core/agents/hook-server.recovery.test.tsnew file mode 100644index 000000000..4850c26ee--- /dev/null+++ b/src/core/agents/hook-server.recovery.test.ts@@ -0,0 +1,90 @@+// Issue #445, the server half: endpoint publication must reflect listener liveness, and a failed+// listen must not wedge the singleton. Before this, `start()` assigned `this.server` before the+// bind completed — a rejected listen left the field set, so every later `start()` returned early+// with port 0 while a PREVIOUS run's `hook-endpoint.env` kept advertising a dead port to every+// tmux session on the machine; and `stop()` cleared the in-memory port/token but left the file.+import { describe, it, expect, beforeAll, afterAll, vi } from 'vitest'+import fs from 'node:fs'+import os from 'node:os'+import path from 'node:path'++/** Armed per-test: the next createServer() returns a server whose listen() fails asynchronously,+ * the way a real bind error (EADDRINUSE, EADDRNOTAVAIL) arrives. Everything else is real http. */+const listenControl = { failNext: false }++vi.mock('http', async (importOriginal) => {+ const actual = await importOriginal<typeof import('http')>()+ return {+ ...actual,+ createServer: (...args: Parameters<typeof actual.createServer>) => {+ const srv = actual.createServer(...args)+ if (listenControl.failNext) {+ listenControl.failNext = false+ srv.listen = ((): typeof srv => {+ process.nextTick(() =>+ srv.emit(+ 'error',+ Object.assign(new Error('listen EADDRINUSE (injected)'), { code: 'EADDRINUSE' })+ )+ )+ return srv+ }) as typeof srv.listen+ }+ return srv+ }+ }+})++import { hookServer } from './hook-server'+import { initPlatform, resetPlatformForTests } from '../platform'+import { fakePlatform } from '../platform-fake'++let dir = ''++beforeAll(() => {+ dir = fs.mkdtempSync(path.join(os.tmpdir(), 'nodeterm-hs-recovery-'))+ resetPlatformForTests()+ initPlatform(fakePlatform({ userDataDir: dir }))+})++afterAll(() => {+ hookServer.stop()+ fs.rmSync(dir, { recursive: true, force: true })+})++describe('hook server start/stop lifecycle (issue #445)', () => {+ it('a failed listen leaves the singleton retryable and drops the stale endpoint file', async () => {+ // The file a previous app run left behind — it advertises a port nothing listens on.+ const ep = hookServer.endpointFilePath()+ fs.mkdirSync(path.dirname(ep), { recursive: true })+ fs.writeFileSync(ep, "NODETERM_HOOK_PORT='59999'\nNODETERM_HOOK_TOKEN='stale'\n")++ listenControl.failNext = true+ await expect(hookServer.start()).rejects.toThrow('EADDRINUSE')+ // The singleton is back in the clean never-started state, not wedged with a dead Server…+ expect(hookServer.getPort()).toBe(0)+ expect(hookServer.getToken()).toBe('')+ // …and the stale advertisement is gone rather than pointing clients at the dead port.+ expect(fs.existsSync(ep)).toBe(false)++ // A retry — same process, no app restart — comes up and re-advertises.+ await hookServer.start()+ expect(hookServer.getPort()).toBeGreaterThan(0)+ expect(fs.existsSync(ep)).toBe(true)+ expect(fs.readFileSync(ep, 'utf8')).toContain(`NODETERM_HOOK_PORT='${hookServer.getPort()}'`)+ })++ it('stop() removes the endpoint file so it never advertises a dead listener', () => {+ const ep = hookServer.endpointFilePath()+ expect(fs.existsSync(ep)).toBe(true)+ hookServer.stop()+ expect(fs.existsSync(ep)).toBe(false)+ expect(hookServer.getPort()).toBe(0)+ })++ it('a stop/start cycle republishes the endpoint (the restart-handoff contract is unchanged)', async () => {+ await hookServer.start()+ const ep = hookServer.endpointFilePath()+ expect(fs.readFileSync(ep, 'utf8')).toContain(`NODETERM_HOOK_PORT='${hookServer.getPort()}'`)+ })+})diff --git a/src/core/agents/hook-server.ts b/src/core/agents/hook-server.tsindex 66d3a9bc0..25a6ebdf3 100644--- a/src/core/agents/hook-server.ts+++ b/src/core/agents/hook-server.ts@@ -733,6 +733,17 @@ class HookServer {await new Promise<void>((resolve, reject) => {const onErr = (e: Error): void => {this.server?.off('listening', onOk)+ // A failed listen must not WEDGE the singleton (issue #445): `this.server` was assigned+ // before the bind, so leaving it set makes every later start() a silent early-return with+ // port 0 — while a previous run's endpoint file keeps advertising a dead port to every+ // tmux session on the machine. Reset to the clean never-started state so start() can be+ // retried without restarting the app, and drop the stale advertisement (the file reflects+ // listener liveness; a client that still holds the path fails over — see the sh shims).+ this.server?.close()+ this.server = null+ this.port = 0+ this.token = ''+ this.removeEndpointFile()reject(e)}const onOk = (): void => {@@ -1034,6 +1045,21 @@ class HookServer {}}+ /**+ * Best-effort unlink of the endpoint file, so the advertisement on disk reflects listener+ * liveness (issue #445): a file that outlives its listener sends every generated client to a+ * dead port first — and before the shims learned the endpoint failover, stopped canvas-control+ * cold. Run on stop() and on a failed start(). A crash cannot run it, which is exactly why the+ * clients still carry the failover walk; this only closes the windows we CAN close.+ */+ private removeEndpointFile(): void {+ try {+ unlinkSync(this.endpointFilePath())+ } catch {+ /* nothing to remove — or no booted platform to name the path (tests); both are fine */+ }+ }+// `permWaitSecs > 0` opts this session into the deterministic hook-reply approval flow: the// managed permission hook holds for that many seconds for a phone/canvas answer file before// falling through to Claude's interactive prompt. 0/undefined ⇒ NODETERM_PERM_WAIT_SECS absent ⇒@@ -1077,6 +1103,10 @@ class HookServer {stop(): void {this.server?.close()this.server = null+ // The file must not advertise a listener that no longer exists (issue #445): a stopped server+ // whose endpoint file survives sends every long-lived tmux session's client to a dead port.+ // The next start() rewrites it; between the two, clients fail over or say "stale" honestly.+ this.removeEndpointFile()this.unixServer?.close()this.unixServer = null// Unlink so the NEXT bind is clean even if close() lost the race with process exit; thediff --git a/src/core/agents/hooks/managed-script.ts b/src/core/agents/hooks/managed-script.tsindex 26a5791c4..e3f62be73 100644--- a/src/core/agents/hooks/managed-script.ts+++ b/src/core/agents/hooks/managed-script.ts@@ -88,6 +88,7 @@ import { codexThreadIdentityResolverSh } from '../../codex-thread-identity-sh'import { codexThreadIdentityRoot } from '../../codex-identity-proxy'import { HOOK_CURL_HEADERS_SH } from '../hook-curl-config-sh'import { NODE_TOKEN_READ_SH } from '../node-token-sh'+import { HOOK_ENDPOINT_FALLBACK_SH } from '../hook-endpoint-failover-sh'/*** Bumped by hand whenever this script's CONTRACT with the server changes. Not a git sha and not a@@ -234,66 +235,12 @@ export function buildManagedScript('# Hook-reply approvals are claude-only; this script never arms the wait, even when the','# session env inherited NODETERM_PERM_WAIT_SECS from a claude node (issue #409).']),- '# --- Endpoint failover helpers --------------------------------------------------',- // How many endpoints we may POST to AFTER the primary failed. See the "Fallback ordering and- // bound" block comment above buildManagedScript for the full reasoning; the short version:- // the ordered list is (at most 3) LOCAL endpoints followed by the reverse tunnels, only one or- // two locals can exist on a real host (the two desktop userData paths are per-OS and mutually- // exclusive), so 3 attempts always reaches a live local endpoint AND still leaves a tunnel slot.- // The cost ceiling is what bounds it: each dead attempt can burn --max-time 1.5s, because an- // sshd-held reverse-tunnel socket ACCEPTS and then never answers.- 'nt_fallback_max=3',- '# Print the candidate endpoint files, ONE PER LINE, most-likely-alive first, skipping the',- '# already-tried path ($1) and anything unreadable. Ordering, and why it is not mtime:',- '# 1. LOCAL endpoints — the host\'s own Server Edition, then a desktop installed on this host.',- '# They are written by a process running HERE, a different failure domain from the tunnels.',- '# 2. The per-project SSH reverse tunnels, freshest first (the old whole-list rule, kept as the',- '# tie-break within this group, because the live project\'s endpoint is rewritten and VERIFIED',- '# on every connect).',- '# The tunnels all terminate at the SAME desktop, so they share one fate: when the primary tunnel',- '# is dead (closed laptop) its siblings are almost always dead too, and mtime happily ranks those',- '# siblings above a local endpoint that is actually listening. That is the whole bug — a host with',- '# an always-on Server Edition sat silent while every one of its agents ran.',- 'nt_candidates() {',- ' nt_tried="$1"',- ' for nt_c in \\',- ' "$HOME/.nodeterm-server/hook-endpoint.env" \\',- ' "$HOME/.config/node-terminal/hook-endpoint.env" \\',- ' "$HOME/Library/Application Support/node-terminal/hook-endpoint.env"; do',- ' [ "$nt_c" = "$nt_tried" ] && continue',- ' [ -r "$nt_c" ] || continue',- ' printf \'%s\\n\' "$nt_c"',- ' done',- ' set --',- // Unquoted glob (with $HOME itself still quoted): the per-project SSH reverse-tunnel- // endpoints. On no match the pattern stays literal and the `-r` test below drops it.- ' for nt_c in "$HOME"/.nodeterm/hook-endpoint-*.env; do',- ' [ "$nt_c" = "$nt_tried" ] && continue',- ' [ -r "$nt_c" ] || continue',- ' set -- "$@" "$nt_c"',- ' done',- ' [ "$#" -gt 0 ] || return 0',- ' ls -t "$@" 2>/dev/null',- '}',- '# Adopt one candidate endpoint file ($1): source it into NODETERM_HOOK_{SOCK,PORT,TOKEN,VERSION}',- '# + NODETERM_NODE_TOKEN_DIR. Returns 0 if it was sourced, else 1.',- '# SOCK/PORT are cleared first so a primary-vs-fallback transport switch (e.g. dead SOCK →',- '# live PORT) never leaves the stale transport winning in the re-POST below — and, now that we',- '# may walk several candidates, so one candidate\'s transport never leaks into the next one.',- '# NODE_TOKEN_DIR is cleared for the same reason and one more: our token belongs to the instance',- '# that MINTED it, so carrying our dir into someone else\'s endpoint would point the read at a',- '# directory that server cannot verify. Cleared, the newly sourced file sets its own — we then',- '# present THAT instance\'s token for this node, or (if it has none) nothing at all, which is',- '# honest `legacy`.',- 'nt_adopt() {',- ' NODETERM_HOOK_SOCK=""',- ' NODETERM_HOOK_PORT=""',- ' NODETERM_NODE_TOKEN_DIR=""',- // stdout swallowed for the same reason as the primary source above (#186): in the perm-wait- // branch this runs in the FOREGROUND of a hook whose stdout reaches the agent's context.- ' . "$1" >/dev/null 2>&1 || return 1',- ' return 0',- '}',+ // The candidate walk + adopt helpers are SHARED with the canvas-control and context-link+ // shims (hook-endpoint-failover-sh.ts) — issue #445: the shims never learned this walk, so+ // the same stale endpoint a hook event healed itself around stopped every canvas-control+ // verb cold. One definition, three clients; the "Fallback ordering and bound" reasoning in+ // the header comment above still governs it.+ HOOK_ENDPOINT_FALLBACK_SH,'# One request POST against the CURRENT endpoint vars. Returns curl\'s exit status so the','# caller can fail over; returns 1 when there is no transport at all (unset/unreadable','# endpoint) so that case also tries a fallback.',diff --git a/src/core/context-link-core.ts b/src/core/context-link-core.tsindex 99423f2ae..823a650ea 100644--- a/src/core/context-link-core.ts+++ b/src/core/context-link-core.ts@@ -5,6 +5,7 @@ import type { ContextLinkInfo } from '../shared/types'import { sessionName } from './tmux-naming'import { HOOK_CURL_HEADERS_SH } from './agents/hook-curl-config-sh'import { CODEX_SANDBOX_BLOCKED_LINE, CODEX_SANDBOX_HINT_SH } from './agents/hook-sandbox-hint-sh'+import { HOOK_ENDPOINT_FALLBACK_SH, STALE_ENDPOINT_HINT } from './agents/hook-endpoint-failover-sh'import { NODE_TOKEN_READ_SH } from './agents/node-token-sh'/** The shim's generic transport-failure sentence — exported so the agent-facing docs below can@@ -217,23 +218,65 @@ while [ "$nt_i" -lt "$nt_count" ]; doesacdone+${HOOK_ENDPOINT_FALLBACK_SH}+nt_out=$(mktemp 2>/dev/null || echo "/tmp/nodeterm-context.$$")-if [ -n "$NODETERM_HOOK_SOCK" ]; then- nt_code=$(nt_hook_headers |- curl -sS -o "$nt_out" -w '%{http_code}' -X POST --config - \\- --unix-socket "$NODETERM_HOOK_SOCK" "http://localhost/context-link/$nt_verb" \\- -H "Accept: text/plain" \\- --data-urlencode "nodeId=\${NODETERM_NODE_ID}" "$@" 2>/dev/null)-elif [ -n "$NODETERM_HOOK_PORT" ]; then- nt_code=$(nt_hook_headers |- curl -sS -o "$nt_out" -w '%{http_code}' -X POST --config - \\- "http://127.0.0.1:\${NODETERM_HOOK_PORT}/context-link/$nt_verb" \\- -H "Accept: text/plain" \\- --data-urlencode "nodeId=\${NODETERM_NODE_ID}" "$@" 2>/dev/null)-else- rm -f "$nt_out"- echo "nodeterm is not reachable from this session — nothing to read." >&2- exit 1++# One POST against the CURRENT endpoint vars — call as \`nt_ctx_post "$@"\` so the translated curl+# args reach it. Sets nt_code: '' when there is no transport at all, curl's %{http_code} otherwise+# ('000' = the transport failed before any HTTP answer). nt_had_transport remembers that SOMETHING+# was ever advertised, so the final error can tell "no endpoint anywhere" from "an endpoint that+# is not listening".+nt_ctx_post() {+ nt_code=""+ if [ -n "$NODETERM_HOOK_SOCK" ]; then+ nt_had_transport=1+ nt_code=$(nt_hook_headers |+ curl -sS -o "$nt_out" -w '%{http_code}' -X POST --config - \\+ --unix-socket "$NODETERM_HOOK_SOCK" "http://localhost/context-link/$nt_verb" \\+ -H "Accept: text/plain" \\+ --data-urlencode "nodeId=\${NODETERM_NODE_ID}" "$@" 2>/dev/null)+ elif [ -n "$NODETERM_HOOK_PORT" ]; then+ nt_had_transport=1+ nt_code=$(nt_hook_headers |+ curl -sS -o "$nt_out" -w '%{http_code}' -X POST --config - \\+ "http://127.0.0.1:\${NODETERM_HOOK_PORT}/context-link/$nt_verb" \\+ -H "Accept: text/plain" \\+ --data-urlencode "nodeId=\${NODETERM_NODE_ID}" "$@" 2>/dev/null)+ fi+}+# An answer from the server — any HTTP code — is authoritative; only a dead transport fails over.+nt_reached() { [ -n "$nt_code" ] && [ "$nt_code" != "000" ]; }++nt_had_transport=""+nt_ctx_post "$@"++# Endpoint failover (issue #445), the same bounded walk the managed hook script and the+# canvas-control shim run: a session is pinned for life to the endpoint PATH it was handed at tmux+# creation, so an app quit/restart leaves it posting at a dead port while a live endpoint file sits+# right next to it. Skipped under a codex sandbox: connect() is denied wholesale there (issue+# #367), so each candidate would burn a doomed curl and the sandbox hint below is already the+# right diagnosis.+if ! nt_reached && [ -z "$CODEX_SANDBOX_NETWORK_DISABLED" ]; then+ nt_list=$(nt_candidates "$NODETERM_HOOK_ENDPOINT")+ if [ -n "$nt_list" ]; then+ nt_n=0+ # A heredoc, not a pipe: the loop must run in THIS shell so the endpoint vars nt_adopt sets+ # (and nt_code) survive it. "$@" still holds the translated curl args.+ while IFS= read -r nt_ep; do+ [ -n "$nt_ep" ] || continue+ nt_n=$((nt_n + 1))+ [ "$nt_n" -le "$nt_fallback_max" ] || break+ nt_adopt "$nt_ep" || continue+ # Re-read the token FROM THE ADOPTED ENDPOINT's dir (node-token-sh.ts): the capability must+ # come from the instance we are about to call, never the one we are walking away from.+ nt_read_node_token "$nt_ep"+ nt_ctx_post "$@"+ nt_reached && break+ done <<NT_CANDIDATES+$nt_list+NT_CANDIDATES+ fifiif [ "$nt_code" = "200" ]; then@@ -247,8 +290,17 @@ rm -f "$nt_out"# own connect() denial (issue #367), and the generic sentence below would misdirect the agent.if [ -z "$nt_code" ] || [ "$nt_code" = "000" ]; thennt_codex_sandbox_hint && exit 1+ if [ -z "$nt_had_transport" ]; then+ echo "nodeterm is not reachable from this session — nothing to read." >&2+ exit 1+ fifiecho "${CONTEXT_UNREACHABLE_MSG}" >&2+# A transport WAS advertised and nothing answered, primary or fallback: name the stale endpoint so+# the agent stops relinking a healthy canvas (the link is fine; the app behind it is not there).+if [ -z "$nt_code" ] || [ "$nt_code" = "000" ]; then+ echo "${STALE_ENDPOINT_HINT}" >&2+fiexit 1`diff --git a/src/core/context-link-shim.failover.test.ts b/src/core/context-link-shim.failover.test.tsnew file mode 100644index 000000000..2135385d4--- /dev/null+++ b/src/core/context-link-shim.failover.test.ts@@ -0,0 +1,89 @@+// Issue #445 for the context-link shim: same stale-primary / live-sibling shape as the+// canvas-control failover suite, same discipline — the real generated script under the real+// /bin/sh against the real hook server. Before the walk, a session that outlived an app restart+// read "Could not read linked context (nodeterm unreachable)." from a perfectly healthy canvas.+import { describe, it, expect, beforeAll, afterAll } from 'vitest'+import { execFile } from 'node:child_process'+import fs from 'node:fs'+import os from 'node:os'+import path from 'node:path'+import { promisify } from 'node:util'+import { CONTEXT_SHIM_SCRIPT, CONTEXT_UNREACHABLE_MSG } from './context-link-core'+import { STALE_ENDPOINT_HINT } from './agents/hook-endpoint-failover-sh'+import { hookServer } from './agents/hook-server'+import { initPlatform, resetPlatformForTests } from './platform'+import { fakePlatform } from './platform-fake'++const run = promisify(execFile)++let dir = ''+let shim = ''+let home = ''+let staleEndpoint = ''+const asked: { verb: string; nodeId: string }[] = []++beforeAll(async () => {+ dir = fs.mkdtempSync(path.join(os.tmpdir(), 'nodeterm-ctx-fo-'))+ resetPlatformForTests()+ initPlatform(fakePlatform({ userDataDir: path.join(dir, 'userdata') }))+ shim = path.join(dir, 'context.sh')+ fs.writeFileSync(shim, CONTEXT_SHIM_SCRIPT, { mode: 0o755 })+ await hookServer.start()+ hookServer.setContextLinkHandler(async ({ verb, nodeId }) => {+ asked.push({ verb, nodeId })+ return `linked context for ${nodeId} (${verb})`+ })++ staleEndpoint = path.join(dir, 'stale-endpoint.env')+ fs.writeFileSync(+ staleEndpoint,+ "NODETERM_HOOK_PORT='1'\nNODETERM_HOOK_TOKEN='token-of-a-dead-run'\nNODETERM_HOOK_VERSION='2'\n"+ )+ home = path.join(dir, 'home')+ fs.mkdirSync(path.join(home, '.nodeterm-server'), { recursive: true })+ fs.writeFileSync(+ path.join(home, '.nodeterm-server', 'hook-endpoint.env'),+ `NODETERM_HOOK_PORT='${hookServer.getPort()}'\nNODETERM_HOOK_TOKEN='${hookServer.getToken()}'\n`+ )+})++afterAll(() => {+ hookServer.stop()+ fs.rmSync(dir, { recursive: true, force: true })+})++function callShim(+ args: string[],+ env: Record<string, string> = {}+): Promise<{ stdout: string; stderr: string }> {+ return run('/bin/sh', [shim, ...args], {+ env: {+ PATH: process.env.PATH ?? '',+ NODETERM_NODE_ID: 'node-1',+ NODETERM_HOOK_ENDPOINT: staleEndpoint,+ HOME: home,+ ...env+ }+ })+}++describe('context-link shim endpoint failover (issue #445)', () => {+ it('a stale primary endpoint fails over to a live sibling endpoint and the read succeeds', async () => {+ asked.length = 0+ const { stdout } = await callShim(['summary', '--node', 'node-2'])+ expect(stdout.trim()).toBe('linked context for node-1 (summary)')+ expect(asked).toEqual([{ verb: 'summary', nodeId: 'node-1' }])+ })++ it('with no live candidate anywhere, names the stale endpoint under the generic sentence', async () => {+ const emptyHome = path.join(dir, 'empty-home')+ fs.mkdirSync(emptyHome, { recursive: true })+ const err = await callShim(['list'], { HOME: emptyHome }).then(+ () => null,+ (e: { code: number; stderr: string }) => e+ )+ expect(err?.code).toBe(1)+ expect(err?.stderr).toContain(CONTEXT_UNREACHABLE_MSG)+ expect(err?.stderr).toContain(STALE_ENDPOINT_HINT)+ })+})diff --git a/src/main/canvas-control-core.ts b/src/main/canvas-control-core.tsindex 1d20b107d..0c9c83c46 100644--- a/src/main/canvas-control-core.ts+++ b/src/main/canvas-control-core.ts@@ -3,6 +3,7 @@// Electron/ipc/server wiring lives in canvas-control.ts + index.ts + hook-server.ts.import { HOOK_CURL_HEADERS_SH } from '../core/agents/hook-curl-config-sh'import { CODEX_SANDBOX_HINT_SH } from '../core/agents/hook-sandbox-hint-sh'+import { HOOK_ENDPOINT_FALLBACK_SH, STALE_ENDPOINT_HINT } from '../core/agents/hook-endpoint-failover-sh'import { codexSandboxGuidanceLines } from '../core/context-link-core'import { NODE_TOKEN_READ_SH } from '../core/agents/node-token-sh'import { AGENT_CONFIG, AGENT_HOOK_TARGETS, BUILTIN_AGENT_IDS } from '@shared/agents/config'@@ -496,23 +497,67 @@ while [ "$nt_i" -lt "$nt_count" ]; doesacdone+${HOOK_ENDPOINT_FALLBACK_SH}+nt_out=$(mktemp 2>/dev/null || echo "/tmp/nodeterm-control.$$")-if [ -n "$NODETERM_HOOK_SOCK" ]; then- nt_code=$(nt_hook_headers |- curl -sS -o "$nt_out" -w '%{http_code}' -X POST --config - \\- --unix-socket "$NODETERM_HOOK_SOCK" "http://localhost/control/$nt_verb" \\- -H "Accept: text/plain" \\- --data-urlencode "nodeId=\${NODETERM_NODE_ID}" "$@" 2>/dev/null)-elif [ -n "$NODETERM_HOOK_PORT" ]; then- nt_code=$(nt_hook_headers |- curl -sS -o "$nt_out" -w '%{http_code}' -X POST --config - \\- "http://127.0.0.1:\${NODETERM_HOOK_PORT}/control/$nt_verb" \\- -H "Accept: text/plain" \\- --data-urlencode "nodeId=\${NODETERM_NODE_ID}" "$@" 2>/dev/null)-else- rm -f "$nt_out"- echo "nodeterm control endpoint unavailable." >&2- exit 1++# One POST against the CURRENT endpoint vars — call as \`nt_control_post "$@"\` so the translated+# curl args reach it. Sets nt_code: '' when there is no transport to try at all, curl's+# %{http_code} otherwise ('000' = the transport failed before any HTTP answer). nt_had_transport+# remembers that SOMETHING was ever advertised, so the final error can tell "no endpoint+# anywhere" from "an endpoint that is not listening" — those need opposite advice.+nt_control_post() {+ nt_code=""+ if [ -n "$NODETERM_HOOK_SOCK" ]; then+ nt_had_transport=1+ nt_code=$(nt_hook_headers |+ curl -sS -o "$nt_out" -w '%{http_code}' -X POST --config - \\+ --unix-socket "$NODETERM_HOOK_SOCK" "http://localhost/control/$nt_verb" \\+ -H "Accept: text/plain" \\+ --data-urlencode "nodeId=\${NODETERM_NODE_ID}" "$@" 2>/dev/null)+ elif [ -n "$NODETERM_HOOK_PORT" ]; then+ nt_had_transport=1+ nt_code=$(nt_hook_headers |+ curl -sS -o "$nt_out" -w '%{http_code}' -X POST --config - \\+ "http://127.0.0.1:\${NODETERM_HOOK_PORT}/control/$nt_verb" \\+ -H "Accept: text/plain" \\+ --data-urlencode "nodeId=\${NODETERM_NODE_ID}" "$@" 2>/dev/null)+ fi+}+# An answer from the server — any HTTP code — is authoritative; only a dead transport fails over.+nt_reached() { [ -n "$nt_code" ] && [ "$nt_code" != "000" ]; }++nt_had_transport=""+nt_control_post "$@"++# Endpoint failover (issue #445), the same bounded walk the managed hook script runs: a session is+# pinned for life to the endpoint PATH it was handed at tmux creation, so an app quit/restart (or a+# retired project id) leaves it posting at a dead port while a live endpoint file sits right next+# to it. Before this walk the hook script healed itself and this shim died on the SAME stale file —+# "control endpoint unreachable" with the requested verb silently dropped. Skipped under a codex+# sandbox: there the sandbox denies EVERY connect (issue #367), so each candidate would burn a+# doomed curl and the sandbox hint below is already the right diagnosis.+if ! nt_reached && [ -z "$CODEX_SANDBOX_NETWORK_DISABLED" ]; then+ nt_list=$(nt_candidates "$NODETERM_HOOK_ENDPOINT")+ if [ -n "$nt_list" ]; then+ nt_n=0+ # A heredoc, not a pipe: the loop must run in THIS shell so the endpoint vars nt_adopt sets+ # (and nt_code) survive it. "$@" still holds the translated curl args — the read loop never+ # touches the positional parameters.+ while IFS= read -r nt_ep; do+ [ -n "$nt_ep" ] || continue+ nt_n=$((nt_n + 1))+ [ "$nt_n" -le "$nt_fallback_max" ] || break+ nt_adopt "$nt_ep" || continue+ # Re-read the token FROM THE ADOPTED ENDPOINT's dir (node-token-sh.ts): the capability must+ # come from the instance we are about to call, never the one we are walking away from.+ nt_read_node_token "$nt_ep"+ nt_control_post "$@"+ nt_reached && break+ done <<NT_CANDIDATES+$nt_list+NT_CANDIDATES+ fifiif [ "$nt_code" = "200" ]; then@@ -525,7 +570,14 @@ rm -f "$nt_out"# Empty / 000 = the TRANSPORT failed, not the server. Under a codex sandbox that is the sandbox's# own connect() denial (issue #367), and the generic sentence would misdirect the agent.if [ -z "$nt_code" ] || [ "$nt_code" = "000" ]; then- nt_codex_sandbox_hint || echo "${CONTROL_UNREACHABLE_MSG}" >&2+ if [ -z "$nt_had_transport" ]; then+ echo "nodeterm control endpoint unavailable." >&2+ else+ nt_codex_sandbox_hint || echo "${CONTROL_UNREACHABLE_MSG}" >&2+ if [ -z "$CODEX_SANDBOX_NETWORK_DISABLED" ]; then+ echo "${STALE_ENDPOINT_HINT}" >&2+ fi+ fifiexit 1`diff --git a/src/main/canvas-control-shim.failover.test.ts b/src/main/canvas-control-shim.failover.test.tsnew file mode 100644index 000000000..e736a9e91--- /dev/null+++ b/src/main/canvas-control-shim.failover.test.ts@@ -0,0 +1,148 @@+// Issue #445, the client half, exercised for real: the actual generated canvas-control shim, run+// by the real /bin/sh against the real hook server — with the PRIMARY endpoint file advertising a+// port nothing listens on (what an app quit/restart leaves behind for a tmux session created+// before it) and a live candidate endpoint sitting in one of the well-known locations under+// $HOME. Before the walk, this exact shape printed "control endpoint unreachable" and the verb —+// a reviewer launch, in the field report — was silently dropped.+import { describe, it, expect, beforeAll, afterAll } from 'vitest'+import { execFile } from 'node:child_process'+import fs from 'node:fs'+import os from 'node:os'+import path from 'node:path'+import { promisify } from 'node:util'+import { CONTROL_SHIM_SCRIPT, CONTROL_UNREACHABLE_MSG } from './canvas-control-core'+import { STALE_ENDPOINT_HINT } from '../core/agents/hook-endpoint-failover-sh'+import { hookServer } from '../core/agents/hook-server'+import { nodeAuthToken } from '../core/agents/node-auth-token'+import { initPlatform, resetPlatformForTests } from '../core/platform'+import { fakePlatform } from '../core/platform-fake'++const run = promisify(execFile)++let dir = ''+let shim = ''+let home = ''+let staleEndpoint = ''+let received: { verb: string; nodeId: string; verified: boolean }[] = []++beforeAll(async () => {+ dir = fs.mkdtempSync(path.join(os.tmpdir(), 'nodeterm-shim-fo-'))+ resetPlatformForTests()+ initPlatform(fakePlatform({ userDataDir: path.join(dir, 'userdata') }))+ shim = path.join(dir, 'nodeterm.sh')+ fs.writeFileSync(shim, CONTROL_SHIM_SCRIPT, { mode: 0o755 })+ await hookServer.start()+ hookServer.setControlHandler(async (cmd) => {+ received.push({ verb: cmd.verb, nodeId: cmd.nodeId, verified: cmd.verified })+ return { ok: true, message: `did ${cmd.verb}` }+ })++ // The primary the session is pinned to: a file whose port belonged to a previous app run.+ // Port 1 answers nothing on loopback, so curl fails at connect exactly like a dead listener.+ staleEndpoint = path.join(dir, 'stale-endpoint.env')+ fs.writeFileSync(+ staleEndpoint,+ "NODETERM_HOOK_PORT='1'\nNODETERM_HOOK_TOKEN='token-of-a-dead-run'\nNODETERM_HOOK_VERSION='2'\n"+ )++ // The live candidate in a well-known location under a fake $HOME — the Server Edition slot,+ // the first one nt_candidates prints.+ home = path.join(dir, 'home')+ fs.mkdirSync(path.join(home, '.nodeterm-server'), { recursive: true })+ fs.writeFileSync(+ path.join(home, '.nodeterm-server', 'hook-endpoint.env'),+ `NODETERM_HOOK_PORT='${hookServer.getPort()}'\n` ++ `NODETERM_HOOK_TOKEN='${hookServer.getToken()}'\n` ++ "NODETERM_HOOK_VERSION='2'\n" ++ `NODETERM_NODE_TOKEN_DIR='${path.join(dir, 'live-tokens')}'\n`+ )+})++afterAll(() => {+ hookServer.stop()+ fs.rmSync(dir, { recursive: true, force: true })+})++function callShim(+ args: string[],+ env: Record<string, string> = {}+): Promise<{ stdout: string; stderr: string }> {+ return run('/bin/sh', [shim, ...args], {+ env: {+ PATH: process.env.PATH ?? '',+ NODETERM_CANVAS_CONTROL: '1',+ NODETERM_NODE_ID: 'node-1',+ NODETERM_HOOK_ENDPOINT: staleEndpoint,+ HOME: home,+ ...env+ }+ })+}++describe('canvas-control shim endpoint failover (issue #445)', () => {+ it('a stale primary endpoint fails over to a live sibling endpoint and the verb succeeds', async () => {+ received = []+ const { stdout } = await callShim(['list'])+ expect(stdout.trim()).toBe('did list')+ expect(received).toEqual([{ verb: 'list', nodeId: 'node-1', verified: false }])+ })++ it('carries the request args through the failover POST unchanged', async () => {+ received = []+ const nasty = 'review "the worktree";\n$HOME & 100%'+ const { stdout } = await callShim(['open-agent', '--agent', 'claude', '--prompt', nasty])+ expect(stdout.trim()).toBe('did open-agent')+ expect(received.at(-1)?.verb).toBe('open-agent')+ })++ it("re-reads the node token from the ADOPTED endpoint's dir, so identity survives the failover", async () => {+ // The token dir is NON-standard (nothing under $HOME points at it) and advertised only by the+ // live candidate file — so a token found here proves the walk re-read after adopting, rather+ // than reusing whatever the stale primary (or a well-known fallback dir) yielded.+ const SECRET = Buffer.alloc(32, 9)+ hookServer.setNodeAuthSecret(SECRET)+ try {+ const tokenDir = path.join(dir, 'live-tokens')+ fs.mkdirSync(tokenDir, { recursive: true })+ fs.writeFileSync(path.join(tokenDir, 'node-1'), `${nodeAuthToken(SECRET, 'node-1')}\n`, {+ mode: 0o600+ })+ received = []+ await callShim(['list'])+ expect(received.at(-1)?.verified).toBe(true)+ } finally {+ hookServer.clearNodeAuthSecretForTests()+ }+ })++ it('with no live candidate anywhere, says the endpoint is stale rather than a bare unreachable', async () => {+ const emptyHome = path.join(dir, 'empty-home')+ fs.mkdirSync(emptyHome, { recursive: true })+ const err = await callShim(['list'], { HOME: emptyHome }).then(+ () => null,+ (e: { code: number; stderr: string }) => e+ )+ expect(err?.code).toBe(1)+ expect(err?.stderr).toContain(CONTROL_UNREACHABLE_MSG)+ expect(err?.stderr).toContain(STALE_ENDPOINT_HINT)+ })++ it('an HTTP answer from the server is authoritative — no failover on a 4xx', async () => {+ // Wrong bearer → the REAL server answers 403. A live candidate exists, but an answered+ // request must never be re-sent elsewhere: the server's refusal is the result.+ const answeredEndpoint = path.join(dir, 'answered-endpoint.env')+ fs.writeFileSync(+ answeredEndpoint,+ `NODETERM_HOOK_PORT='${hookServer.getPort()}'\nNODETERM_HOOK_TOKEN='wrong-bearer'\n`+ )+ received = []+ const err = await callShim(['list'], { NODETERM_HOOK_ENDPOINT: answeredEndpoint }).then(+ () => null,+ (e: { code: number; stderr: string }) => e+ )+ expect(err?.code).toBe(1)+ // No stale-endpoint diagnosis — the server was reached — and no fallback POST landed.+ expect(err?.stderr ?? '').not.toContain(STALE_ENDPOINT_HINT)+ expect(received).toEqual([])+ })+})diff --git a/src/main/index.ts b/src/main/index.tsindex bf3aa3afe..cc80cc77f 100644--- a/src/main/index.ts+++ b/src/main/index.ts@@ -3637,6 +3637,12 @@ app.on('before-quit', (e) => {// And the askpass relay's socket file: close() is what unlinks a unix socket (process exit// does not), and a lingering file is one more thing the next start() has to clear.askpassServer.stop()+ // Hook server last among the closers, and on THIS pass so the flush window above could still+ // receive hook POSTs: stopping unlinks its socket AND its endpoint file (issue #445), so a+ // graceful quit never leaves an advertisement pointing at a dead port for the tmux sessions+ // that outlive the app. The next launch rewrites both; a crash skips this, which is what the+ // generated clients' endpoint failover exists for.+ hookServer.stop()// A SIGTERM quit (dev runners, `kill`, logout) arrives through Chromium's shutdown// detector, and this pass's re-issued app.quit() cannot resume the OS-initiated// termination the first pass preventDefault'ed: both passes run, but will-quit never