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: keep control fallback on the owning nodeterm instance
reviewbbb3a291abe5
diff --git a/CLAUDE.md b/CLAUDE.mdindex 47b5da05e..499aa3f8f 100644--- a/CLAUDE.md+++ b/CLAUDE.md@@ -2138,6 +2138,14 @@ command-bearing opens; this does not add a human-confirm dialog or change mobilethe launcher and the prelude, pass `npm run typecheck` and every unit test, and ship INERT.`main/codex-identity-record-wiring.test.ts` pins it at source level, the same remedy`hook-verified-parity.test.ts` uses for the same class of hole.+ - Control/context endpoint discovery retains a known node capability. A dead Desktop SSH tunnel+ must not redirect a command to a local Server Edition that has no matching token for that node:+ its unsupported-edition response describes the wrong instance. The two shims use+ `nt_adopt_for_node` and read only the candidate's advertised token directory (or adjacent+ `node-tokens` for old endpoint files), never borrow a global token for a candidate. Unknown+ legacy callers retain existing discovery; actual owning-endpoint refusals remain final.+ Skipped foreign candidates do not consume the three-network-attempt budget. Hook event+ delivery retains its existing independent failover policy.- **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: asession is pinned for life to the endpoint PATH it got at tmux creation, so an appdiff --git a/CONTRIBUTING.md b/CONTRIBUTING.mdindex 82f705219..bc19e8ab0 100644--- a/CONTRIBUTING.md+++ b/CONTRIBUTING.md@@ -919,3 +919,8 @@ paste mode immediately before Enter, not just the surviving PTY root. A missinga transmitted text request is uncertain delivery, never a pre-paste refusal; show the no-resendwarning. SessionStart idle rescue is scoped to that same nonempty session and agent identity,and a foreign idle must not broadcast fresh state proof to the renderer.++Control and linked-context fallback must keep a known node identity on its owning nodeterm+instance. A foreign server being reachable is not evidence that it owns the canvas. Match the+candidate's own advertised node token before sending; never borrow a token from a global directory+for that check. Keep real owning-endpoint refusals final and legacy hook delivery unchanged.diff --git a/src/core/agents/hook-endpoint-failover-sh.ts b/src/core/agents/hook-endpoint-failover-sh.tsindex dca53cee0..218ef88de 100644--- a/src/core/agents/hook-endpoint-failover-sh.ts+++ b/src/core/agents/hook-endpoint-failover-sh.ts@@ -35,11 +35,10 @@* `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.+ * Hook events retain the legacy failover policy: foreign node tokens classify as legacy on the+ * receiver. That is NOT sufficient routing evidence for control/context requests: a foreign+ * instance can answer an unsupported-edition or unknown-node refusal before a live owning tunnel+ * is reached. Those clients use OWNED_ENDPOINT_FALLBACK_SH below to retain a known capability.*//*** The line both shims append under their generic transport-failure sentence when a transport WAS@@ -115,3 +114,31 @@ export const HOOK_ENDPOINT_FALLBACK_SH = [' return 0','}'].join('\n')+++/** Control/context requests must retain a known node identity across endpoint discovery.+ * Hook event failover deliberately keeps its existing policy. This is client-side routing,+ * not authorization: the receiving server still checks every bearer, node and verb. */+export const OWNED_ENDPOINT_FALLBACK_SH = `+# A candidate must advertise this node's SAME capability. Do not use the global token search:+# that could borrow the desktop token while posting to an unrelated headless server.+nt_adopt_for_node() {+ nt_adopt "$1" || return 1+ if [ -z "$nt_owner_node_token" ]; then+ nt_read_node_token "$1"+ return 0+ fi+ nt_node_token=""+ nt_owner_dir="$NODETERM_NODE_TOKEN_DIR"+ [ -n "$nt_owner_dir" ] || nt_owner_dir=$(nt_token_dir_beside "$1")+ if [ -n "$nt_owner_dir" ]; then+ nt_node_token=$(head -n 1 "$nt_owner_dir/$NODETERM_NODE_ID" 2>/dev/null) || nt_node_token=""+ fi+ [ -n "$nt_node_token" ] && [ "$nt_node_token" = "$nt_owner_node_token" ] && return 0+ nt_skipped_foreign_endpoint=1+ return 1+}+`++export const FOREIGN_ENDPOINT_HINT =+ 'Unrelated endpoints were skipped because they do not advertise this node\'s current identity. The owning nodeterm connection must be available; another local server cannot control this canvas.'diff --git a/src/core/canvas-control-core.ts b/src/core/canvas-control-core.tsindex 1eefb9421..ab2bee2e6 100644--- a/src/core/canvas-control-core.ts+++ b/src/core/canvas-control-core.ts@@ -4,7 +4,12 @@ import { LINK_ENDPOINT_NOT_FOUND } from '../shared/canvas-link'// Electron/ipc/server wiring lives in canvas-control.ts + index.ts + hook-server.ts.import { HOOK_CURL_HEADERS_SH } from './agents/hook-curl-config-sh'import { 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 {+ HOOK_ENDPOINT_FALLBACK_SH,+ OWNED_ENDPOINT_FALLBACK_SH,+ FOREIGN_ENDPOINT_HINT,+ STALE_ENDPOINT_HINT+} from './agents/hook-endpoint-failover-sh'import { codexSandboxGuidanceLines } from './context-link-core'import { NODE_TOKEN_READ_SH } from './agents/node-token-sh'import { AGENT_CONFIG, AGENT_HOOK_TARGETS, BUILTIN_AGENT_IDS } from '@shared/agents/config'@@ -659,6 +664,8 @@ fi# Missing everywhere leaves it empty, which the server reads as legacy — the request still goes.${NODE_TOKEN_READ_SH}nt_read_node_token+nt_owner_node_token="$nt_node_token"+nt_skipped_foreign_endpoint=""${HOOK_CURL_HEADERS_SH}@@ -737,6 +744,7 @@ while [ "$nt_i" -lt "$nt_count" ]; dodone${HOOK_ENDPOINT_FALLBACK_SH}+${OWNED_ENDPOINT_FALLBACK_SH}nt_out=$(mktemp 2>/dev/null || echo "/tmp/nodeterm-control.$$")@@ -786,12 +794,9 @@ if ! nt_reached && { [ "$nt_code" = "421" ] || [ -z "$CODEX_SANDBOX_NETWORK_DISA# touches the positional parameters.while IFS= read -r nt_ep; do[ -n "$nt_ep" ] || continue+ [ "$nt_n" -lt "$nt_fallback_max" ] || break+ nt_adopt_for_node "$nt_ep" || continuent_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 && breakdone <<NT_CANDIDATES@@ -805,6 +810,9 @@ if [ "$nt_code" = "200" ]; thenrm -f "$nt_out"exit 0fi+if [ -n "$nt_skipped_foreign_endpoint" ] && ! nt_reached; then+ echo "${FOREIGN_ENDPOINT_HINT}" >&2+ficat "$nt_out" >&2 2>/dev/nullrm -f "$nt_out"# Empty / 000 = the TRANSPORT failed, not the server. Under a codex sandbox that is the sandbox'sdiff --git a/src/core/context-link-core.ts b/src/core/context-link-core.tsindex bd9cf4813..a3be8fa78 100644--- a/src/core/context-link-core.ts+++ b/src/core/context-link-core.ts@@ -5,7 +5,12 @@ 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 {+ HOOK_ENDPOINT_FALLBACK_SH,+ OWNED_ENDPOINT_FALLBACK_SH,+ FOREIGN_ENDPOINT_HINT,+ STALE_ENDPOINT_HINT+} from './agents/hook-endpoint-failover-sh'import { NODE_TOKEN_READ_SH } from './agents/node-token-sh'import { codexThreadIdentityResolverSh } from './codex-thread-identity-sh'@@ -192,6 +197,8 @@ fi# falls back to the standard locations rather than reading as \`legacy\` forever (issue #384).${NODE_TOKEN_READ_SH}nt_read_node_token+nt_owner_node_token="$nt_node_token"+nt_skipped_foreign_endpoint=""${HOOK_CURL_HEADERS_SH}@@ -219,6 +226,7 @@ while [ "$nt_i" -lt "$nt_count" ]; dodone${HOOK_ENDPOINT_FALLBACK_SH}+${OWNED_ENDPOINT_FALLBACK_SH}nt_out=$(mktemp 2>/dev/null || echo "/tmp/nodeterm-context.$$")@@ -265,12 +273,9 @@ if ! nt_reached && { [ "$nt_code" = "421" ] || [ -z "$CODEX_SANDBOX_NETWORK_DISA# (and nt_code) survive it. "$@" still holds the translated curl args.while IFS= read -r nt_ep; do[ -n "$nt_ep" ] || continue+ [ "$nt_n" -lt "$nt_fallback_max" ] || break+ nt_adopt_for_node "$nt_ep" || continuent_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 && breakdone <<NT_CANDIDATES@@ -284,6 +289,9 @@ if [ "$nt_code" = "200" ]; thenrm -f "$nt_out"exit 0fi+if [ -n "$nt_skipped_foreign_endpoint" ] && ! nt_reached; then+ echo "${FOREIGN_ENDPOINT_HINT}" >&2+ficat "$nt_out" >&2 2>/dev/nullrm -f "$nt_out"# Empty / 000 = the TRANSPORT failed, not the server. Under a codex sandbox that is the sandbox'sdiff --git a/src/main/control-owner-failover.test.ts b/src/main/control-owner-failover.test.tsnew file mode 100644index 000000000..55a64f5fb--- /dev/null+++ b/src/main/control-owner-failover.test.ts@@ -0,0 +1,111 @@+// Exercise generated POSIX clients with a dead Desktop tunnel, an unrelated local server,+// and a second tunnel. No control request may reach the unrelated server, even for `close`.+import { createServer, type Server } from 'node:http'+import { execFile } from 'node:child_process'+import { promisify } from 'node:util'+import fs from 'node:fs'+import os from 'node:os'+import path from 'node:path'+import { afterEach, describe, expect, it } from 'vitest'+import { CONTROL_SHIM_SCRIPT } from '../core/canvas-control-core'+import { CONTEXT_SHIM_SCRIPT } from '../core/context-link-core'+import { FOREIGN_ENDPOINT_HINT } from '../core/agents/hook-endpoint-failover-sh'++const run = promisify(execFile)+const servers: Server[] = []+const dirs: string[] = []+afterEach(async () => {+ await Promise.all(servers.splice(0).map(s => new Promise<void>(r => s.close(() => r()))))+ for (const dir of dirs.splice(0)) fs.rmSync(dir, { recursive: true, force: true })+})+async function endpoint(status: number, message: string) {+ const requests: { url: string; body: string; nodeToken: string | string[] | undefined }[] = []+ const server = createServer(async (req, res) => {+ let body = ''+ for await (const chunk of req) body += chunk+ requests.push({ url: req.url!, body, nodeToken: req.headers['x-nodeterm-node-token'] })+ res.writeHead(status); res.end(message)+ })+ servers.push(server)+ await new Promise<void>(r => server.listen(0, '127.0.0.1', r))+ return { port: (server.address() as { port: number }).port, requests }+}+const clients = [+ { name: 'control', script: CONTROL_SHIM_SCRIPT, args: ['close', '--node', 'finished-a,finished-b'], route: '/control/close' },+ { name: 'context', script: CONTEXT_SHIM_SCRIPT, args: ['list'], route: '/context-link' }+]++describe.skipIf(process.platform === 'win32')('node identity survives endpoint failover', () => {+ for (const client of clients) {+ it.each(['missing', 'different'])(`${client.name}: skips a local server with %s node identity and reaches its own tunnel`, async kind => {+ const fixture = await setup(client, kind)+ const result = await fixture.call()+ expect(result.stdout).toBe('owner reply')+ expect(fixture.foreign.requests).toEqual([])+ expect(fixture.owner.requests).toHaveLength(1)+ expect(fixture.owner.requests[0].nodeToken).toBe('owner-capability')+ if (client.name === 'control') {+ expect(fixture.owner.requests[0].url).toBe(client.route)+ expect(new URLSearchParams(fixture.owner.requests[0].body).get('arg.node')).toBe('finished-a,finished-b')+ }+ })+ it(`${client.name}: accepts an old owning endpoint with adjacent tokens after three foreign candidates`, async () => {+ const fixture = await setup(client, 'missing')+ const home = path.dirname(path.dirname(fixture.fallback))+ const foreignFile = path.join(home, '.nodeterm-server/hook-endpoint.env')+ for (const relative of ['.config/node-terminal', 'Library/Application Support/node-terminal']) {+ const directory = path.join(home, relative)+ fs.mkdirSync(directory, { recursive: true })+ fs.copyFileSync(foreignFile, path.join(directory, 'hook-endpoint.env'))+ }+ fs.writeFileSync(fixture.fallback, fs.readFileSync(fixture.fallback, 'utf8')+ .replace(/^NODETERM_NODE_TOKEN_DIR=.*\n/m, ''))+ expect((await fixture.call()).stdout).toBe('owner reply')+ expect(fixture.foreign.requests).toEqual([])+ expect(fixture.owner.requests).toHaveLength(1)+ })+ it(`${client.name}: reports the missing owning connection, not a foreign edition refusal`, async () => {+ const fixture = await setup(client, 'missing')+ fs.unlinkSync(fixture.fallback)+ const error = await fixture.call().catch(e => e)+ expect(error.code).toBe(1)+ expect(error.stderr).toContain(FOREIGN_ENDPOINT_HINT)+ expect(error.stderr).not.toContain('control-unsupported-on-this-edition')+ expect(error.stderr).not.toContain('owner-capability')+ expect(fixture.foreign.requests).toEqual([])+ expect(fixture.owner.requests).toEqual([])+ })+ it.each([400, 403])(`${client.name}: keeps an owning endpoint's %s refusal final`, async status => {+ const fixture = await setup(client, 'missing', status)+ const error = await fixture.call().catch(e => e)+ expect(error.code).toBe(1)+ expect(error.stderr).toContain('owner refused')+ expect(error.stderr).not.toContain(FOREIGN_ENDPOINT_HINT)+ expect(fixture.owner.requests).toHaveLength(1)+ expect(fixture.foreign.requests).toEqual([])+ })+ }+})++async function setup(client: typeof clients[number], kind: string, ownerStatus = 200) {+ const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'nt-control-owner-')); dirs.push(dir)+ const foreign = await endpoint(400, 'control-unsupported-on-this-edition')+ const owner = await endpoint(ownerStatus, ownerStatus === 200 ? 'owner reply' : 'owner refused')+ const ownTokens = path.join(dir, '.nodeterm/node-tokens')+ const foreignTokens = path.join(dir, '.nodeterm-server/node-tokens')+ fs.mkdirSync(ownTokens, { recursive: true }); fs.mkdirSync(foreignTokens, { recursive: true })+ fs.writeFileSync(path.join(ownTokens, 'node-1'), 'owner-capability\n')+ if (kind === 'different') fs.writeFileSync(path.join(foreignTokens, 'node-1'), 'foreign-capability\n')+ const writeEndpoint = (file: string, port: number, tokens: string) => fs.writeFileSync(file,+ `NODETERM_HOOK_PORT='${port}'\nNODETERM_HOOK_TOKEN='fixture-bearer'\nNODETERM_NODE_TOKEN_DIR='${tokens}'\n`)+ const primary = path.join(dir, '.nodeterm/primary.env')+ const fallback = path.join(dir, '.nodeterm/hook-endpoint-live.env')+ writeEndpoint(primary, 1, ownTokens)+ writeEndpoint(path.join(dir, '.nodeterm-server/hook-endpoint.env'), foreign.port, foreignTokens)+ writeEndpoint(fallback, owner.port, ownTokens)+ const shim = path.join(dir, 'client.sh'); fs.writeFileSync(shim, client.script)+ return { foreign, owner, fallback, call: () => run('/bin/sh', [shim, ...client.args], {+ timeout: 5000,+ env: { PATH: process.env.PATH, HOME: dir, NODETERM_CANVAS_CONTROL: '1', NODETERM_NODE_ID: 'node-1', NODETERM_HOOK_ENDPOINT: primary }+ }) }+}