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): shared quote-aware parser for the two TS readers of the endpoint file
Claude Code11a30fc60d43
diff --git a/src/core/agents/hook-endpoint-file-sh.test.ts b/src/core/agents/hook-endpoint-file-sh.test.tsindex 5faaef3aa..c30f77dcc 100644--- a/src/core/agents/hook-endpoint-file-sh.test.ts+++ b/src/core/agents/hook-endpoint-file-sh.test.ts@@ -46,4 +46,12 @@ describe('endpoint file sources cleanly under real /bin/sh with a spaced path',// (2) and the path must arrive with its space intact, byte for byte.expect(r.stdout).toBe(nodeTokenDir())})++ it('the shared TS parser reads the REAL writer output identically to sh', async () => {+ const { parseEndpointEnv } = await import('./hook-endpoint-parse')+ const env = parseEndpointEnv(fs.readFileSync(hookServer.endpointFilePath(), 'utf8'))+ expect(env.NODETERM_NODE_TOKEN_DIR).toBe(nodeTokenDir())+ expect(env.NODETERM_HOOK_TOKEN).toBe(hookServer.getToken())+ expect(Number(env.NODETERM_HOOK_PORT)).toBe(hookServer.getPort())+ })})diff --git a/src/core/agents/hook-endpoint-parse.test.ts b/src/core/agents/hook-endpoint-parse.test.tsnew file mode 100644index 000000000..b32116fd3--- /dev/null+++ b/src/core/agents/hook-endpoint-parse.test.ts@@ -0,0 +1,56 @@+import { describe, it, expect } from 'vitest'+import { parseEndpointEnv } from './hook-endpoint-parse'+import { posixQuote } from '../../shared/ssh'++describe('parseEndpointEnv', () => {+ it('unquotes the exact posixQuote form both writers emit (spaced macOS path, #351)', () => {+ const dir = '/Users/work/Library/Application Support/node-terminal/node-tokens'+ // Built with the SAME posixQuote the writers use — not a hand-approximated fixture.+ const body =+ `NODETERM_HOOK_PORT=${posixQuote('54321')}\n` ++ `NODETERM_HOOK_TOKEN=${posixQuote('08011abf-af79')}\n` ++ `NODETERM_HOOK_VERSION=${posixQuote('2')}\n` ++ `NODETERM_NODE_TOKEN_DIR=${posixQuote(dir)}\n`+ expect(parseEndpointEnv(body)).toEqual({+ NODETERM_HOOK_PORT: '54321',+ NODETERM_HOOK_TOKEN: '08011abf-af79',+ NODETERM_HOOK_VERSION: '2',+ NODETERM_NODE_TOKEN_DIR: dir+ })+ })++ it('still parses a LEGACY unquoted file verbatim (pre-fix build; stale files are a real state)', () => {+ const body =+ 'NODETERM_HOOK_SOCK=/home/u/.nodeterm/hook-p1.sock\n' ++ 'NODETERM_HOOK_TOKEN=tok\n' ++ 'NODETERM_NODE_TOKEN_DIR=/home/u/.nodeterm/node-tokens\n'+ expect(parseEndpointEnv(body)).toEqual({+ NODETERM_HOOK_SOCK: '/home/u/.nodeterm/hook-p1.sock',+ NODETERM_HOOK_TOKEN: 'tok',+ NODETERM_NODE_TOKEN_DIR: '/home/u/.nodeterm/node-tokens'+ })+ })++ it("round-trips an embedded single quote (posixQuote's '\\'' escape)", () => {+ const value = "it's a 'weird' $token; `x`"+ expect(parseEndpointEnv(`K=${posixQuote(value)}\n`).K).toBe(value)+ // Quote at the very edge of the value.+ expect(parseEndpointEnv(`K=${posixQuote("'")}\n`).K).toBe("'")+ expect(parseEndpointEnv(`K=${posixQuote("a'")}\n`).K).toBe("a'")+ })++ it('keeps values containing "=" whole (first-= split) and skips malformed lines', () => {+ const env = parseEndpointEnv(`A=${posixQuote('x=y')}\nB=x=y\n\nnot a line\n=nope\n`)+ expect(env).toEqual({ A: 'x=y', B: 'x=y' })+ })++ it('is self-contained, so the opencode plugin can embed it via toString()', () => {+ const src = parseEndpointEnv.toString()+ // Must not close over anything or use template literals — the plugin inlines this source.+ expect(src).not.toContain('`')+ expect(src).not.toContain('${')+ // eslint-disable-next-line no-eval+ const embedded = (0, eval)(`(${src})`) as typeof parseEndpointEnv+ expect(embedded(`K=${posixQuote('a b')}\n`).K).toBe('a b')+ })+})diff --git a/src/core/agents/hook-endpoint-parse.ts b/src/core/agents/hook-endpoint-parse.tsnew file mode 100644index 000000000..1e7e044bb--- /dev/null+++ b/src/core/agents/hook-endpoint-parse.ts@@ -0,0 +1,37 @@+/**+ * TS-side parser for the endpoint env file (`hook-endpoint.env` / `hook-endpoint-<project>.env`).+ *+ * Since #351 both writers `posixQuote` every value so the file sources cleanly under /bin/sh when+ * a path carries a space (macOS "Application Support") or a token carries a shell metachar. Shell+ * consumers get the unquoting for free from `. "$file"`; every TypeScript consumer must unquote+ * through THIS function instead of splitting on `=` naively — a naive read keeps the literal+ * quote characters, which breaks the constant-time bearer check (opencode plugin) and turns+ * `Number("'54321'")` into NaN (codex relay daemon).+ *+ * Accepts BOTH forms per line, so one parser covers the whole fleet:+ * - quoted (post-#351): `KEY='value'`, with embedded single quotes escaped exactly as+ * `posixQuote` emits them (`'` → `'\''`);+ * - legacy unquoted (pre-fix builds): `KEY=value` verbatim. tmux sessions outlive the app, so a+ * stale endpoint file written by an old build is a real, documented state — it must keep+ * parsing.+ *+ * SELF-CONTAINED ON PURPOSE — no imports, no closure over module state. The opencode plugin is+ * generated JS source that runs standalone under Bun/node (it cannot import from this app), so+ * `buildOpencodePlugin()` embeds this very function via `parseEndpointEnv.toString()`. Keep it+ * dependency-free (and free of template literals / `${`) or the embedded copy breaks.+ */+export function parseEndpointEnv(text: string): Record<string, string> {+ const env: Record<string, string> = {}+ for (const line of text.split('\n')) {+ const i = line.indexOf('=')+ if (i <= 0) continue+ let v = line.slice(i + 1)+ if (v.length >= 2 && v.charAt(0) === "'" && v.charAt(v.length - 1) === "'") {+ // posixQuote form: strip the outer quotes, then collapse each embedded-quote escape+ // ('\'' — close quote, escaped quote, reopen quote) back to a literal quote.+ v = v.slice(1, -1).split("'\\''").join("'")+ }+ env[line.slice(0, i)] = v+ }+ return env+}diff --git a/src/core/agents/hooks/opencode-live-endpoint.test.ts b/src/core/agents/hooks/opencode-live-endpoint.test.tsnew file mode 100644index 000000000..3407b98f8--- /dev/null+++ b/src/core/agents/hooks/opencode-live-endpoint.test.ts@@ -0,0 +1,53 @@+import { describe, it, expect, beforeAll, afterAll, vi } from 'vitest'+import fs from 'node:fs'+import os from 'node:os'+import path from 'node:path'+import { buildOpencodePlugin } from './opencode'+import { hookServer } from '../hook-server'+import { initPlatform, resetPlatformForTests } from '../../platform'+import { fakePlatform } from '../../platform-fake'+import type { NormalizedAgentEvent } from '../../../shared/agents/normalize'++// Issue #351 follow-up: the plugin's `live()` re-parses the REAL endpoint file that+// `writeEndpointFile()` writes — every fixture in opencode.test.ts hand-writes that file, so a+// writer-format change (the #351 quoting) could break the parse without any test noticing. This+// test closes that gap end-to-end: real writer → real plugin parse → real hook server bearer+// check. If the plugin's parser ever keeps the quotes (or otherwise mangles the token), the POST+// is 401'd and the listener below never fires.+let tmp = ''+beforeAll(async () => {+ const root = fs.mkdtempSync(path.join(os.tmpdir(), 'nt-oc-live-'))+ // Spaced userDataDir — the "Application Support" shape the quoting exists for.+ tmp = path.join(root, 'App Support', 'node-terminal')+ fs.mkdirSync(tmp, { recursive: true })+ resetPlatformForTests()+ initPlatform(fakePlatform({ userDataDir: tmp }))+ await hookServer.start()+})+afterAll(() => {+ hookServer.stop()+ vi.unstubAllEnvs()+})++describe('opencode plugin against the real endpoint-file writer', () => {+ it('parses the quoted endpoint file and its token passes the real bearer check', async () => {+ const events: NormalizedAgentEvent[] = []+ hookServer.setListener((e) => events.push(e))+ vi.stubEnv('NODETERM_NODE_ID', 'node-oc-live')+ vi.stubEnv('NODETERM_HOOK_ENDPOINT', hookServer.endpointFilePath())+ // No env fallbacks: port/token MUST come out of the file, exactly as a tmux restart handoff.+ vi.stubEnv('NODETERM_HOOK_PORT', '')+ vi.stubEnv('NODETERM_HOOK_TOKEN', '')+ vi.stubEnv('NODETERM_HOOK_SOCK', '')++ const file = path.join(tmp, 'plugin-live.mjs')+ fs.writeFileSync(file, buildOpencodePlugin())+ const mod = await import(/* @vite-ignore */ `file://${file}`)+ const hooks = await mod.NodetermStatus()+ await hooks.event({ event: { type: 'session.idle', properties: { sessionID: 'ses_live' } } })++ // The listener fires only for an ACCEPTED post — a quote-mangled token is 401'd before it.+ await vi.waitFor(() => expect(events.length).toBeGreaterThan(0))+ expect(events[0].nodeId).toBe('node-oc-live')+ })+})diff --git a/src/core/agents/hooks/opencode.ts b/src/core/agents/hooks/opencode.tsindex cdcefb791..faabd7c84 100644--- a/src/core/agents/hooks/opencode.ts+++ b/src/core/agents/hooks/opencode.ts@@ -7,6 +7,7 @@import fs from 'fs'import os from 'os'import path from 'path'+import { parseEndpointEnv } from '../hook-endpoint-parse'export const PLUGIN_MARKER = '// nodeterm managed plugin — do not edit (reinstalled at app launch)'@@ -52,6 +53,12 @@ export function buildOpencodePlugin(): string {import fs from 'node:fs'import http from 'node:http'+// The SAME quote-aware parser every TS consumer of the endpoint file uses, embedded verbatim+// (this plugin runs standalone under Bun/node — it cannot import from the app). Values are+// posixQuote'd since #351; a quote-blind read would present a token wrapped in literal quotes,+// which the hook server's constant-time bearer check rejects on every POST.+const parseEndpointEnv = ${parseEndpointEnv.toString()}+export const NodetermStatus = async () => {const nodeId = process.env.NODETERM_NODE_IDif (!nodeId) return {}@@ -66,14 +73,13 @@ export const NodetermStatus = async () => {try {const file = process.env.NODETERM_HOOK_ENDPOINTif (file) {- for (const line of fs.readFileSync(file, 'utf8').split('\\n')) {- const m = line.match(/^NODETERM_HOOK_(PORT|SOCK|TOKEN|VERSION)=(.*)$/)- if (m) conf[m[1].toLowerCase()] = m[2]- // The v2 endpoint line: where this instance keeps per-node tokens. It has its own- // prefix, so it needs its own match rather than a widened NODETERM_HOOK_ group.- const d = line.match(/^NODETERM_NODE_TOKEN_DIR=(.*)$/)- if (d) conf.tokenDir = d[1]- }+ const env = parseEndpointEnv(fs.readFileSync(file, 'utf8'))+ if ('NODETERM_HOOK_PORT' in env) conf.port = env.NODETERM_HOOK_PORT+ if ('NODETERM_HOOK_SOCK' in env) conf.sock = env.NODETERM_HOOK_SOCK+ if ('NODETERM_HOOK_TOKEN' in env) conf.token = env.NODETERM_HOOK_TOKEN+ if ('NODETERM_HOOK_VERSION' in env) conf.version = env.NODETERM_HOOK_VERSION+ // The v2 endpoint line: where this instance keeps per-node tokens.+ if ('NODETERM_NODE_TOKEN_DIR' in env) conf.tokenDir = env.NODETERM_NODE_TOKEN_DIR}} catch {}return confdiff --git a/src/main/codex-relay-daemon.test.ts b/src/main/codex-relay-daemon.test.tsindex ae15aa027..eec1156ef 100644--- a/src/main/codex-relay-daemon.test.ts+++ b/src/main/codex-relay-daemon.test.ts@@ -27,6 +27,8 @@ import {readThreadAt,relayControlPost,relayThreadReservationKey,+ hookEndpointOptions,+ readHookEndpointEnv,relayThreadResponseError,resolveForeignThreadAt,retargetRelayResumeByPath,@@ -35,6 +37,7 @@ import {tryReserveRelayThread,type RelayThreadRequest} from './codex-relay-daemon'+import { posixQuote } from '../shared/ssh'async function fakeCodexServer(socketPath: string,@@ -899,3 +902,77 @@ describe('relay self-spawn + token transport (probe U6, GC 6 argv-spy)', () => {}}, 30_000)})++// The endpoint file's values are posixQuote'd since #351 (a spaced macOS path must source+// cleanly under /bin/sh). The daemon's TS-side reader must UNQUOTE them, or+// `Number("'54321'")` is NaN and `"'/sock'".startsWith('/')` is false — hookEndpointOptions+// then returns null and every authorize/observed/catalog call dies "endpoint unavailable".+describe('readHookEndpointEnv + hookEndpointOptions', () => {+ const writeEndpoint = (dir: string, lines: string) => {+ const f = path.join(dir, 'hook-endpoint.env')+ writeFileSync(f, lines)+ return f+ }++ it('parses the QUOTED (post-#351) file: TCP port', () => {+ const dir = mkdtempSync(path.join(tmpdir(), 'nt-relay-ep-'))+ try {+ const f = writeEndpoint(+ dir,+ `NODETERM_HOOK_PORT=${posixQuote('54321')}\n` ++ `NODETERM_HOOK_TOKEN=${posixQuote('tok-abc')}\n` ++ `NODETERM_HOOK_VERSION=${posixQuote('2')}\n` ++ `NODETERM_NODE_TOKEN_DIR=${posixQuote('/Users/x/Library/Application Support/node-terminal/node-tokens')}\n`+ )+ const env = readHookEndpointEnv(f)+ expect(env.NODETERM_HOOK_TOKEN).toBe('tok-abc')+ expect(env.NODETERM_NODE_TOKEN_DIR).toBe(+ '/Users/x/Library/Application Support/node-terminal/node-tokens'+ )+ expect(hookEndpointOptions(env, '/codex-thread/authorize')).toEqual({+ hostname: '127.0.0.1',+ port: 54321,+ path: '/codex-thread/authorize'+ })+ } finally {+ rmSync(dir, { recursive: true, force: true })+ }+ })++ it('parses the QUOTED (post-#351) file: unix socket with a spaced path', () => {+ const dir = mkdtempSync(path.join(tmpdir(), 'nt-relay-ep-'))+ try {+ const f = writeEndpoint(+ dir,+ `NODETERM_HOOK_SOCK=${posixQuote('/home/u/App Support/hook.sock')}\n` ++ `NODETERM_HOOK_TOKEN=${posixQuote('tok-abc')}\n`+ )+ const env = readHookEndpointEnv(f)+ expect(hookEndpointOptions(env, '/codex-thread/observed')).toEqual({+ socketPath: '/home/u/App Support/hook.sock',+ path: '/codex-thread/observed'+ })+ } finally {+ rmSync(dir, { recursive: true, force: true })+ }+ })++ it('still parses a LEGACY unquoted file (pre-fix build; tmux sessions outlive the app)', () => {+ const dir = mkdtempSync(path.join(tmpdir(), 'nt-relay-ep-'))+ try {+ const f = writeEndpoint(+ dir,+ 'NODETERM_HOOK_PORT=54321\nNODETERM_HOOK_TOKEN=tok-abc\nNODETERM_NODE_TOKEN_DIR=/home/u/.nodeterm/node-tokens\n'+ )+ const env = readHookEndpointEnv(f)+ expect(env.NODETERM_HOOK_TOKEN).toBe('tok-abc')+ expect(hookEndpointOptions(env, '/x')).toEqual({+ hostname: '127.0.0.1',+ port: 54321,+ path: '/x'+ })+ } finally {+ rmSync(dir, { recursive: true, force: true })+ }+ })+})diff --git a/src/main/codex-relay-daemon.ts b/src/main/codex-relay-daemon.tsindex 219624c6a..a287bd30d 100644--- a/src/main/codex-relay-daemon.ts+++ b/src/main/codex-relay-daemon.ts@@ -64,6 +64,7 @@ import {isSafeAccountId,planCodexRolloutExposure} from '../core/codex-accounts-core'+import { parseEndpointEnv } from '../core/agents/hook-endpoint-parse'// Protocol v6 adds a node-scoped capability to every Electron identity request. It also merges// account-isolated catalogs and resumes a selected foreign rollout by path in@@ -722,7 +723,18 @@ function indexedName(socketPath: string, threadId?: string): string | undefined}}-function hookEndpointOptions(+/**+ * Read + parse the local endpoint env file for `hookRequest`/`hookJsonRequest`. Values are+ * `posixQuote`d since #351, so this must go through the shared quote-aware parser — a naive+ * first-`=` split keeps the quotes, making the port NaN and the sock non-absolute, and every+ * authorize/observed/catalog call then dies "endpoint unavailable". Exported for tests.+ */+export function readHookEndpointEnv(file: string): Record<string, string> {+ return parseEndpointEnv(readFileSync(file, 'utf8'))+}++/** Exported for tests. */+export function hookEndpointOptions(env: Record<string, string>,pathname: string): { socketPath: string; path: string } | { hostname: string; port: number; path: string } | null {@@ -741,15 +753,7 @@ function hookRequest(return new Promise((resolve, reject) => {let env: Record<string, string>try {- env = Object.fromEntries(- readFileSync(route.hookEndpoint, 'utf8')- .split('\n')- .filter(Boolean)- .map((l) => {- const i = l.indexOf('=')- return i > 0 ? [l.slice(0, i), l.slice(i + 1)] : ['', '']- })- )+ env = readHookEndpointEnv(route.hookEndpoint)} catch (error) {reject(error)return@@ -787,15 +791,7 @@ function hookJsonRequest<T>(route: Route, pathname: string): Promise<T> {return new Promise((resolve, reject) => {let env: Record<string, string>try {- env = Object.fromEntries(- readFileSync(route.hookEndpoint, 'utf8')- .split('\n')- .filter(Boolean)- .map((line) => {- const separator = line.indexOf('=')- return separator > 0 ? [line.slice(0, separator), line.slice(separator + 1)] : ['', '']- })- )+ env = readHookEndpointEnv(route.hookEndpoint)} catch (error) {reject(error)return