The ultimate harness for coding agents and beyond. All your agents. All your machines. One command center. Start with code, then follow your curiosity and build across disciplines: CAD, circuits, robots, games and music.
TypeScript 3d-modelingagent-frameworkagent-harnessai-agentscadclaude-codecodexcoding-agentsdeveloper-toolsesp32game-developmentmcp-servermulti-agentopen-hardwareopencodeopenharnesspcbroboticsterminaltmux
fix(cli): the daemon could not start on any machine with a pane to restore
0xken15ac4d62b6a0b6
diff --git a/cli/src/cli.ts b/cli/src/cli.tsindex b0ca57204..37a027cb0 100644--- a/cli/src/cli.ts+++ b/cli/src/cli.ts@@ -4334,6 +4334,39 @@ async function runForeground(session: AuthSession | null): Promise<void> {if (overrides.gridLaunchRecord) registry.setGridLaunch(agentId, overrides.gridLaunchRecord)}+ /**+ * The permission this relaunch can actually ask for. Nobody is waiting on a restart, a retarget, a+ * restore or a resume, so an engine that no longer takes the row's flag costs it the mode, not the+ * harness — the alternative is a pane of help text, or no pane at all (openharness#285).+ *+ * The row is NOT rewritten. `permissionMode` is the person's recorded choice and `setPermissionMode`+ * is fill-only for that reason; an engine put back the way it was gets Auto again on the next+ * relaunch, with nobody having to ask for it twice. The row stops CLAIMING the mode on its own:+ * discovery re-derives `bypassPermission` from the live argv on every pass (`setBypassPermission`+ * above), so a launch without the flag reads as one within a reconcile.+ *+ * ⚠️ DECLARED BEFORE THE RESTORE PASS, and it has to stay there. `restoreAgents` runs during+ * start-up and calls `buildLaunch` for every pane it rebuilds, which asks this — and a `const`+ * declared further down the function is still in its dead zone then, so the daemon died on boot+ * with `Cannot access 'downgradedPermission' before initialization` on any machine that had a+ * pane to restore. Everything it needs is imported; it closes over nothing local.+ */+ const downgradedPermission = async (+ session: RegisteredSession,+ bypassPermission: boolean,+ what: string,+ ): Promise<{ permissionMode?: string | null; bypassPermission?: boolean }> => {+ const { choice, droppedFlag } = await dropPermissionFlagIfUnsupported(session.engine, {+ permissionMode: session.permissionMode ?? null,+ bypassPermission,+ })+ if (droppedFlag) {+ console.warn(`[agent] ${what} ${sid(session.agentId)} · ${session.engine} does not take ${droppedFlag}`+ + ` · starting in Ask · update ${session.engine} to get ${session.permissionMode ?? 'Auto'} back`)+ }+ return choice+ }+const prepareSessionResume = (session: RegisteredSession): void => {const repair = prepareCodexResume(session)if (repair.repairedItems) {@@ -4994,33 +5027,6 @@ async function runForeground(session: AuthSession | null): Promise<void> {&& current.tmuxPane === session.tmuxPane && current.engine === session.engine}- /**- * The permission this relaunch can actually ask for. Nobody is waiting on a restart, a retarget, a- * restore or a resume, so an engine that no longer takes the row's flag costs it the mode, not the- * harness — the alternative is a pane of help text, or no pane at all (openharness#285).- *- * The row is NOT rewritten. `permissionMode` is the person's recorded choice and `setPermissionMode`- * is fill-only for that reason; an engine put back the way it was gets Auto again on the next- * relaunch, with nobody having to ask for it twice. The row stops CLAIMING the mode on its own:- * discovery re-derives `bypassPermission` from the live argv on every pass (`setBypassPermission`- * above), so a launch without the flag reads as one within a reconcile.- */- const downgradedPermission = async (- session: RegisteredSession,- bypassPermission: boolean,- what: string,- ): Promise<{ permissionMode?: string | null; bypassPermission?: boolean }> => {- const { choice, droppedFlag } = await dropPermissionFlagIfUnsupported(session.engine, {- permissionMode: session.permissionMode ?? null,- bypassPermission,- })- if (droppedFlag) {- console.warn(`[agent] ${what} ${sid(session.agentId)} · ${session.engine} does not take ${droppedFlag}`- + ` · starting in Ask · update ${session.engine} to get ${session.permissionMode ?? 'Auto'} back`)- }- return choice- }-const paneSwapDeps = (session: RegisteredSession,runtime: TmuxRuntimeRef,diff --git a/cli/src/startupOrder.spec.ts b/cli/src/startupOrder.spec.tsnew file mode 100644index 000000000..6a50748a3--- /dev/null+++ b/cli/src/startupOrder.spec.ts@@ -0,0 +1,68 @@+import { describe, expect, it } from 'vitest'+import { readFileSync } from 'node:fs'+import { join } from 'node:path'++/**+ * `runForeground` is one very long function, and the restore pass runs in the MIDDLE of it:+ * `restoreAgents` rebuilds every pane whose tmux session died while the daemon was down, calling the+ * deps it was handed — `buildLaunch`, `createPane`, `respawn` — before start-up has reached the rest+ * of the body. A `const` those deps close over but that is declared further down is still in its+ * temporal dead zone then, and the daemon dies on boot:+ *+ * Failed to start adapter: ReferenceError: Cannot access 'p4' before initialization+ * at Object.buildLaunch (cli.js:1472:7962)+ * at async restoreAgents (cli.js:728:2238)+ * at async runForeground+ *+ * Nothing else catches it: the types are fine, every unit test passes, and the crash only appears on+ * a machine that has a pane to restore (openharness, v0.3.5 on a person's Mac — the daemon would not+ * start at all, twice in a row, until they removed the registry). So the order is asserted here, on+ * the source, rather than left to whoever next adds a helper below the restore block.+ */+const SOURCE = readFileSync(join(import.meta.dirname, 'cli.ts'), 'utf-8')++/** The source with comments blanked, so a name mentioned in prose is not read as a reference.+ * Strings are left alone on purpose: blanking them needs a tokenizer to survive the backticks and+ * regex literals this file is full of, and a word inside a string cannot match a local's name. */+function code(text: string): string {+ return text+ .replace(/\/\*[\s\S]*?\*\//g, match => ' '.repeat(match.length))+ .replace(/(^|[^:])\/\/[^\n]*/g, (match, lead: string) => lead + ' '.repeat(match.length - lead.length))+}++/** The object literal passed to `name(`, by brace balance. */+function callArgument(source: string, name: string): { body: string; at: number } {+ const at = source.indexOf(`await ${name}({`)+ expect(at, `${name} is still called as \`await ${name}({\` in cli.ts`).toBeGreaterThan(-1)+ let depth = 0+ for (let i = source.indexOf('{', at); i < source.length; i++) {+ if (source[i] === '{') depth+++ else if (source[i] === '}' && --depth === 0) return { body: source.slice(at, i + 1), at }+ }+ throw new Error(`unbalanced braces after ${name}(`)+}++/** Every call whose dependencies run DURING start-up, before `runForeground` has finished its body. */+const STARTUP_CALLS = ['repairClaudeCwd', 'restoreAgents']++describe('cli.ts start-up order', () => {+ it.each(STARTUP_CALLS)('every local %s reaches is initialised before it runs', (name) => {+ const source = code(SOURCE)+ const { body, at } = callArgument(source, name)+ // Locals of `runForeground` are the two-space-indented declarations; anything else is a module+ // constant, an import, or a nested scope, none of which can be in a dead zone here.+ const declaredAt = new Map<string, number>()+ for (const match of source.matchAll(/^ {2}(?:const|let) ([A-Za-z_$][\w$]*)\s*[:=]/gm)) {+ if (!declaredAt.has(match[1])) declaredAt.set(match[1], match.index)+ }+ // A name the closures declare themselves shadows anything outside them, however late that is.+ const own = new Set([...body.matchAll(/\b(?:const|let|var)\s+([A-Za-z_$][\w$]*)/g)].map(match => match[1]))+ // `entry.agentId` names a property, not the `const agentId` three thousand lines down; the same+ // goes for every other member access in these closures.+ const referenced = body.replace(/\.\s*[A-Za-z_$][\w$]*/g, '')+ const late = [...new Set(referenced.match(/[A-Za-z_$][\w$]*/g) ?? [])]+ .filter(used => !own.has(used) && (declaredAt.get(used) ?? -1) > at)+ .sort()+ expect(late, `declare these above the \`${name}\` call — see this file’s header`).toEqual([])+ })+})