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
feat(relay): stable admin error codes and JSON refusals on stdout
review3fef01c08d36
diff --git a/src/core/relay/admin-error.ts b/src/core/relay/admin-error.tsnew file mode 100644index 000000000..5de464eb1--- /dev/null+++ b/src/core/relay/admin-error.ts@@ -0,0 +1,19 @@+// A leaf module, so the workspace store and the bootstrap verb can raise coded errors without+// importing the admin socket (team-admin.ts re-exports all three).++/** The shape of a stable admin error code (`E_BAD_CWD`, `E_HOSTING_OFF`, …). A remote caller — the+ * desktop's Share with team, over ssh — branches on the code, never on the English sentence. */+export const ADMIN_ERROR_CODE_RE = /^E_[A-Z][A-Z0-9_]{0,40}$/++/** An Error carrying a stable admin code. */+export function codedError(code: string, message: string): Error & { code: string } {+ return Object.assign(new Error(message), { code })+}++/** The stable code a thrown error carries, if it carries one of OURS. Node's own errno codes+ * (`ENOENT`, `EACCES`) never match, so a filesystem failure is reported by its message only. */+export function adminErrorCode(err: unknown): string | undefined {+ if (!(err instanceof Error)) return undefined+ const code = (err as { code?: unknown }).code+ return typeof code === 'string' && ADMIN_ERROR_CODE_RE.test(code) ? code : undefined+}diff --git a/src/core/relay/team-admin.test.ts b/src/core/relay/team-admin.test.tsindex 2f1c15747..79c4d08d3 100644--- a/src/core/relay/team-admin.test.ts+++ b/src/core/relay/team-admin.test.ts@@ -14,6 +14,10 @@ import {projectIdProblem,parseAdminRequest,ADMIN_REQUEST_MAX,+ adminErrorCode,+ codedError,+ ADMIN_ERROR_CODE_RE,+ CMD_TIMEOUT_MS,type AdminReply} from './team-admin'import { createHostKey } from './host-key'@@ -455,3 +459,60 @@ describe.skipIf(process.platform === 'win32')('team admin socket (unix socket, Pidle.destroy()})})++describe('admin error codes', () => {+ it('adminErrorCode reads a well-formed E_ code off a thrown error and ignores anything else', () => {+ expect(adminErrorCode(codedError('E_BAD_CWD', 'nope'))).toBe('E_BAD_CWD')+ expect(adminErrorCode(Object.assign(new Error('x'), { code: 'ENOENT' }))).toBeUndefined()+ expect(adminErrorCode(Object.assign(new Error('x'), { code: 'E_lower' }))).toBeUndefined()+ expect(adminErrorCode('E_BAD_KEY')).toBeUndefined()+ expect(adminErrorCode(null)).toBeUndefined()+ expect(ADMIN_ERROR_CODE_RE.test('E_HOSTING_OFF')).toBe(true)+ })+ it('bootstrap and resume get longer client timeouts than the 30 s default', () => {+ expect(CMD_TIMEOUT_MS.bootstrap).toBe(45_000)+ expect(CMD_TIMEOUT_MS.resume).toBe(60_000)+ expect(CMD_TIMEOUT_MS.init).toBeUndefined()+ })+})++describe.skipIf(process.platform === 'win32')('coded failures over the socket', () => {+ it('a throw carrying an E_ code reaches the client with its code', async () => {+ const dataDir = tmp()+ writeTeam(dataDir)+ const { svc } = fakeService()+ ;(svc as { share: HostedService['share'] }).share = async () => {+ throw codedError('E_ADOPT_FAILED', 'the project file is unreadable')+ }+ await boot(dataDir, svc)+ expect(await callTeamAdmin(dataDir, { cmd: 'share', projectId: 'p1', on: true })).toEqual({+ ok: false,+ error: 'the project file is unreadable',+ code: 'E_ADOPT_FAILED'+ })+ })+ it('a plain throw stays code-less (byte-identical to before)', async () => {+ const dataDir = tmp()+ writeTeam(dataDir)+ const { svc } = fakeService()+ ;(svc as { share: HostedService['share'] }).share = async () => {+ throw new Error('disk full')+ }+ await boot(dataDir, svc)+ expect(await callTeamAdmin(dataDir, { cmd: 'share', projectId: 'p1', on: true })).toEqual({ ok: false, error: 'disk full' })+ })+})++describe.skipIf(process.platform === 'win32')('client timeout', () => {+ it('opts.timeoutMs overrides the default wait, and the message names it', async () => {+ const dataDir = tmp()+ writeTeam(dataDir)+ const { svc } = fakeService()+ ;(svc as { share: HostedService['share'] }).share = () => new Promise<void>(() => {})+ await boot(dataDir, svc)+ const started = Date.now()+ const r = await callTeamAdmin(dataDir, { cmd: 'share', projectId: 'p1', on: true }, { timeoutMs: 100 })+ expect(r).toEqual({ ok: false, error: expect.stringMatching(/did not answer within 0\.1 s/) })+ expect(Date.now() - started).toBeLessThan(5_000)+ })+})diff --git a/src/core/relay/team-admin.ts b/src/core/relay/team-admin.tsindex 374093445..a335d02ed 100644--- a/src/core/relay/team-admin.ts+++ b/src/core/relay/team-admin.ts@@ -17,6 +17,7 @@ import { ensurePrivateDir } from './private-dir'import { TeamStore, TEAM_LABEL_MAX, TEAM_PROJECT_ID_MAX } from './team-store'import { loadHostKey } from './host-key'import { publicKeyFromB64, publicKeyToB64 } from './e2ee'+import { ADMIN_ERROR_CODE_RE, adminErrorCode } from './admin-error'import type {HostedInfo,HostedRotateResult,@@ -25,6 +26,8 @@ import type {HostedStatus} from './hosted-service'+export { codedError, adminErrorCode, ADMIN_ERROR_CODE_RE } from './admin-error'+export type AdminRequest =| { cmd: 'init' }| { cmd: 'add-owner'; pubkey: string; label: string }@@ -33,7 +36,7 @@ export type AdminRequest =| { cmd: 'status' }| { cmd: 'share'; projectId: string; on: boolean }| { cmd: 'rotate-key' }-export type AdminReply = { ok: true; result: unknown } | { ok: false; error: string }+export type AdminReply = { ok: true; result: unknown } | { ok: false; error: string; code?: string }/** `init`'s answer. The address and join code are present only when hosting is running. */export interface AdminInitResult {@@ -72,6 +75,9 @@ export const ADMIN_REQUEST_MAX = 64 * 1024const REQUEST_IDLE_MS = 10_000/** How long the CLI waits for an answer. `init` and `rotate-key` do local file work only. */const CALL_TIMEOUT_MS = 30_000+/** Client timeouts for verbs that do more than local file work: bootstrap may wait up to 15 s for+ * the first relay registration, resume settles up to 4 agent launches at a time. */+export const CMD_TIMEOUT_MS: Readonly<Record<string, number>> = Object.freeze({ bootstrap: 45_000, resume: 60_000 })/** How long probing an existing socket may take before it is treated as "cannot tell". */const PROBE_TIMEOUT_MS = 2_000/** A `remove` key is compared, never decoded: bound it only so a line cannot be all key. */@@ -230,7 +236,7 @@ async function offReason(relayDir: string): Promise<HostingOff> {}const ok = (result: unknown): AdminReply => ({ ok: true, result })-const fail = (error: string): AdminReply => ({ ok: false, error })+const fail = (error: string, code?: string): AdminReply => (code ? { ok: false, error, code } : { ok: false, error })/** The address teammates need — only while hosting actually runs. */const address = (svc: HostedService, running: boolean): { info: HostedInfo | null; joinCode: string | null } =>@@ -302,7 +308,7 @@ async function answer(relayDir: string, svc: HostedService, line: string, closintry {return await handle(relayDir, svc, req, closing)} catch (err) {- return fail(err instanceof Error ? err.message : String(err))+ return fail(err instanceof Error ? err.message : String(err), adminErrorCode(err))}}@@ -446,24 +452,29 @@ function parseReply(line: string): AdminReply {try {const r = JSON.parse(line) as Record<string, unknown> | nullif (r && r.ok === true && 'result' in r) return { ok: true, result: r.result }- if (r && r.ok === false && typeof r.error === 'string') return { ok: false, error: r.error }+ if (r && r.ok === false && typeof r.error === 'string') {+ const code = typeof r.code === 'string' && ADMIN_ERROR_CODE_RE.test(r.code) ? r.code : undefined+ return fail(r.error, code)+ }} catch {// fall through}return fail('The nodeterm server sent a reply this CLI does not understand (is the server a different version?).')}-export function callTeamAdmin(dataDir: string, req: AdminRequest): Promise<AdminReply> {+export function callTeamAdmin(dataDir: string, req: AdminRequest, opts: { timeoutMs?: number } = {}): Promise<AdminReply> {const sock = adminSocketPath(dataDir)const problem = socketPathProblem(sock)if (problem) return Promise.resolve(fail(problem))+ const perVerb = Object.hasOwn(CMD_TIMEOUT_MS, req.cmd) ? CMD_TIMEOUT_MS[req.cmd] : undefined+ const timeoutMs = opts.timeoutMs ?? perVerb ?? CALL_TIMEOUT_MSreturn new Promise((resolve) => {let done = falselet buf = ''const c = net.connect(sock)const timer = setTimeout(- () => finish(fail(`The nodeterm server did not answer within ${CALL_TIMEOUT_MS / 1000} s (${sock}).`)),- CALL_TIMEOUT_MS+ () => finish(fail(`The nodeterm server did not answer within ${timeoutMs / 1000} s (${sock}).`)),+ timeoutMs)function finish(r: AdminReply): void {if (done) returndiff --git a/src/server/team-cli.test.ts b/src/server/team-cli.test.tsindex e7f2e90d0..d0cd7b73c 100644--- a/src/server/team-cli.test.ts+++ b/src/server/team-cli.test.ts@@ -370,4 +370,30 @@ describe.skipIf(process.platform === 'win32')('runTeamCli over the admin socketexpect(help.code).toBe(0)expect(help.out).toMatch(/usage/i)})++ it('--json prints a refusal as one JSON line on stdout (an ssh exec reads stdout only)', async () => {+ const { dataDir } = await served({ running: false }, false)+ // No team, and `info --json` IS allowed without one — use a verb the no-team guard refuses.+ const r = await run(['share', 'p1'], dataDir)+ expect(r.code).toBe(1)+ expect(r.out).toBe('') // no --json: stdout stays empty exactly as before+ const j = await run(['status', '--json'], dataDir)+ expect(j.code).toBe(0)+ })++ it('a refused --json verb prints {"ok":false,…} on stdout and the human line on stderr', async () => {+ const dataDir = tmp()+ fs.mkdirSync(path.join(dataDir, 'relay'), { recursive: true, mode: 0o700 })+ fs.writeFileSync(path.join(dataDir, 'relay', 'team.json'), JSON.stringify({ v: 1, peers: [], sharedProjects: [] }))+ const f = fake()+ ;(f.svc as { status: unknown }).status = () => {+ throw Object.assign(new Error('status broke'), { code: 'E_HOSTING_OFF' })+ }+ const admin = await startTeamAdmin(dataDir, f.svc)+ closers.push(() => admin.close())+ const r = await run(['status', '--json'], dataDir)+ expect(r.code).toBe(1)+ expect(JSON.parse(r.out)).toEqual({ ok: false, error: 'status broke', code: 'E_HOSTING_OFF' })+ expect(r.err).toBe('status broke')+ })})diff --git a/src/server/team-cli.ts b/src/server/team-cli.tsindex cba8864ce..1dc78540c 100644--- a/src/server/team-cli.ts+++ b/src/server/team-cli.ts@@ -363,13 +363,17 @@ export async function runTeamCli(return 2}const r = await callTeamAdmin(dd.dataDir ?? dataDir, req)+ const json = dd.argv.includes('--json')if (!r.ok) {+ // A remote caller (the desktop, over an ssh exec channel) reads stdout only: under --json the+ // refusal is also one machine-readable line there. The human line still goes to stderr.+ if (json) out(JSON.stringify({ ok: false, error: clean(r.error), ...(r.code ? { code: r.code } : {}) }))err(clean(r.error))return 1}// The reply is printed to `out` even when the exit code is 1: the command ran, and what it found// (hosting did not start, no address yet) is its answer, not a failure to run.- const { lines, code } = render(req, r.result, dd.argv.includes('--json'))+ const { lines, code } = render(req, r.result, json)for (const line of lines) out(line)return code}