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(ssh): keep an SSH host's agent shims, skills and instruction blocks current
review7700f58a3b71
diff --git a/CLAUDE.md b/CLAUDE.mdindex d076b44de..0e96241e3 100644--- a/CLAUDE.md+++ b/CLAUDE.md@@ -2419,6 +2419,55 @@ else, and its context links must keep classifying across restarts).the validator refuses) settles at one attempt per 15 minutes instead of rewriting every agent'shook config every 45 s. A missing spec answers "not alive" rather than "unknown": nothing of oursis bound, which is a tunnel that cannot deliver.+- **An SSH host's agent tools are CHECKED, not assumed** (`RemoteHooks.refreshAgentTools`,+ `main/remote-ssh/agent-tools-freshness.ts`). The canvas/context shims, both SKILL.md files and our+ blocks in the codex/gemini/copilot/opencode instruction files used to be written only by the+ establish path, blind, and never looked at again, so a host could keep another build's text for+ a whole run: a fire-and-forget install that failed open was never retried; a tunnel that failed+ verification at connect and was repaired later on the reuse branch (#735, above) never got them+ at all; and a managed account's skill was written ONCE, when the account was added, so after+ every update each remote account session read the verb docs of the build that created the+ account. (The obvious suspect is not one: an app update never lands on the reuse branch. `conns`+ is in memory, so the first connect after a relaunch adopts the ControlPersist orphan on the+ ESTABLISH path, which always wrote. `ssh-project.test.ts` pins that it checks there too.)+ - **The stamp is the bytes.** One generated probe (one round trip, a few hundred bytes back)+ runs POSIX `cksum` over every file the host holds and, for an instruction file, over exactly+ the span `merge*Block` would replace (awk under `LC_ALL=C`: the first start marker through the+ first end marker, only when the end follows the start). That is compared with `posixCksum` of+ the exact bytes this build would write (`core/remote-ssh/posix-cksum.ts`, pinned against the+ real binary), and only what differs is rewritten, through the same appliers as the install. A+ current host costs the probe and no write. Nothing is embedded in the artifacts: a stamp line+ would be noise in every agent's context, would need a migration for hosts written by older+ builds, and would trust a file's claim about itself. `cksum` because it is the one checksum POSIX+ requires; CRC-32 + length is not collision resistant and does not need to be, because this+ detects drift and is not a security check. Ubuntu's own BusyBox build omits `cksum`, so such a+ host exists: it falls back to writing everything on a connect or repair, which is what every+ connect did before. The probe is tested under dash, bash, BusyBox sh and zsh with mawk, gawk,+ BusyBox awk and the one-true awk (the macOS dialect, via `NT_PROBE_EXTRA_AWK`).+ - **Refusals.** A file that is not a readable regular file (a directory, a dangling dotfile link,+ no permission) is NEVER written over, and the host is not called confirmed. A managed account's+ skill is refreshed only when its dir ALREADY exists (never resurrected). A report that does not+ parse changes nothing. Account ids from settings are re-validated (`isSafeAccountId`) before+ they become paths. The copilot block is judged at the host's `$COPILOT_HOME` only when the+ installer's validator would accept that value.+ - **Cadence.** A connect (establish, including the post-relaunch orphan adoption) and a tunnel+ repair always check. The 45 s reuse branch costs nothing once this run has confirmed the host+ for the current expected set (content + account list). An unconfirmed host is retried there on+ the tunnel-repair backoff (1/5/15 min). A confirmed host is looked at again hourly+ (`AGENT_TOOLS_RECHECK_MS`), because within a run only a writer outside it (another desktop,+ possibly an older build, on the same host account; a hand edit) can change the files. One check+ per host at a time: projects sharing a host share it.+ - **Anything new we put on a host goes into the artifact plan in `remote-hooks.ts`**+ (`canvasControlArtifacts` / `contextLinkArtifacts` / `accountSkillArtifacts`). The installers+ and the probe both read it, so a file added there is written AND kept current. A file written+ anywhere else is written once and never looked at again.+ - **What a running agent sees.** The shim's `help` is answered by the shim itself (baked from the+ verb registry), so it is current the moment the file is. Claude reads a SKILL.md body when the+ skill is invoked; codex, gemini and opencode read their instruction files at session start, so+ a session started before a rewrite keeps the old text until it restarts. Nothing is typed into+ a pane to announce it.+ - Surfaces: Desktop only (SSH projects are a desktop concept). The Server Edition runs ON its host+ and rewrites its local shims at every boot. Mobile: N/A.- **The per-agent hook installs run CONCURRENTLY, and the order that still matters is the one abovethem.** `RemoteHooks.setup()` is the chain `connectOnce` awaits before a project reports`connected`, so every terminal of a switched-to project waits through it. Its shape was: resolve@@ -3086,9 +3135,11 @@ command-bearing opens; this does not add a human-confirm dialog or change mobile`open-agent` are verified-only at the Server handler boundary. A plain terminal keeps genericnode hook wiring but receives neither `NODETERM_AGENT_ID` nor `NODETERM_CANVAS_CONTROL`; missingidentity never defaults to Claude.- **SSH projects** (docs/ssh-agent-skills.md): the SAME shim + skill + blocks are installed on- the remote host at connect (`RemoteHooks.installCanvasControl` + per-account- `installCanvasSkillIntoAccountDir`), gated on the VERIFIED reverse hook tunnel — the shim+ **SSH projects** (docs/ssh-agent-skills.md): the SAME shim + skill + blocks are put on the+ remote host and KEPT current by the agent-tools check (`RemoteHooks.refreshAgentTools`: on every+ connect and tunnel repair, rewriting only what differs from this build, managed-account skill+ dirs included — see "An SSH host's agent tools are CHECKED" under Agent support; an account's+ skill is also written when the account is added), gated on the VERIFIED reverse hook tunnel — the shimcarries no machine-specific paths and POSTs through the tunnel's unix socket, so remote agentscontrol the desktop's canvas. The shim is generated source no compiler checks:`canvas-control-shim.test.ts` runs it for real (/bin/sh against a real hook server, port AND@@ -3146,9 +3197,13 @@ command-bearing opens; this does not add a human-confirm dialog or change mobile(`--cmd=--version`), which was previously unexpressible in either direction. Two parsers are inplay and both are tested — the sh loop (`control-shim-parse.test.ts`, real `sh` + a fake `curl`that records argv) and `parseControlBody` reading what it built (`canvas-control-shim.test.ts`).- **A new verb must not DEPEND on the fix**: the shim is rewritten locally every app boot but onto- an SSH host only inside `RemoteHooks.setup()` (on connect), so an already-connected project keeps- the old loop with no signal on the wire. Give every flag a value and both loops agree.+ **A new verb must still not DEPEND on the fix.** The shim is rewritten locally at every app boot,+ and an SSH host's copy is checked on every connect and brought to this build's bytes, so an app+ update reaches the host on the first connect after the relaunch. A host can still run an older+ loop for a while: while its tunnel is down (nothing is installed through a dead tunnel), when the+ file is unreadable (never written over), or while a second desktop on an older build shares the+ host account (it rewrites its own copy on its connects; ours returns within the hour). Nothing+ on the wire says which loop is running. Give every flag a value and both loops agree.**WHICH CANVAS ANSWERS, and why an open never moves the camera** (`renderer/lib/controlRouting.ts`+ `renderer/lib/coldOpen.ts`). React Flow holds only the ACTIVE project's nodes, but every otheropen project's tmux sessions keep running, so a control call routinely arrives from a node thediff --git a/CONTRIBUTING.md b/CONTRIBUTING.mdindex a32e55b4d..8449bc256 100644--- a/CONTRIBUTING.md+++ b/CONTRIBUTING.md@@ -475,6 +475,13 @@ anything else. Board-level fields survive every transform — `pullLinks` is onesymlink and mode. A guard test fails on a new bare `cat >`. A remote runner RESOLVES on anon-zero exit, so check the result or use the helper that does.+- **Anything the app puts on an SSH host goes into the agent-tools plan.** The canvas/context+ shims, their skills and our instruction-file blocks are listed once in `remote-hooks.ts`+ (`canvasControlArtifacts` and its siblings); the installers AND the connect-time freshness check+ (`RemoteHooks.refreshAgentTools`) read that list, so a host is brought up to your build's bytes+ on the next connect. A file written from anywhere else is written once and never checked again —+ hosts then keep the old text across app updates.+- **Never write `chmod <mode> -- <file>` into a remote command.** macOS (BSD) chmod stops parsingoptions at the mode, so the `--` becomes a file operand and the command fails there while passingon Linux. To test it on Linux, put a `POSIXLY_CORRECT=1` wrapper around GNU chmod first on PATH.diff --git a/docs/ssh-agent-skills.md b/docs/ssh-agent-skills.mdindex 52e52a871..275ab27e4 100644--- a/docs/ssh-agent-skills.md+++ b/docs/ssh-agent-skills.md@@ -53,12 +53,15 @@ at it (`NODETERM_HOOK_ENDPOINT`) along with `NODETERM_NODE_ID`. So the design ru(`hook-server.ts`) reads both dialects; the desktop's in-process callers still send JSON.A `text/plain` `Accept` makes the server render the reply, since sh has no JSON parser.-2. **`RemoteHooks.installCanvasControl`** writes the shim + `SKILL.md` onto the host at connect,- and merges the same marker-delimited instruction block into the host's `~/.codex/AGENTS.md`,- `~/.gemini/GEMINI.md` and `${XDG_CONFIG_HOME:-~/.config}/opencode/AGENTS.md` (that last path- is expanded by the **remote** shell — the desktop's XDG value says nothing about the host).- `installCanvasSkillIntoAccountDir` covers managed Claude accounts, whose sessions resolve- skills relative to `CLAUDE_CONFIG_DIR` and never see `~/.claude/skills`.+2. **`RemoteHooks.installCanvasControl`** writes the shim + `SKILL.md` onto the host, and merges+ the same marker-delimited instruction block into the host's `~/.codex/AGENTS.md`,+ `~/.gemini/GEMINI.md`, copilot's `copilot-instructions.md` and+ `${XDG_CONFIG_HOME:-~/.config}/opencode/AGENTS.md` (that last path is expanded by the **remote**+ shell — the desktop's XDG value says nothing about the host). Managed Claude accounts, whose+ sessions resolve skills relative to `CLAUDE_CONFIG_DIR` and never see `~/.claude/skills`, get+ their own copy (`installCanvasSkillIntoAccountDir` when the account is added). On a connect+ these are not written blind: `RemoteHooks.refreshAgentTools` checks them (see+ [Keeping the host current](#keeping-the-host-current)) and rewrites only what differs.3. **The env gap** — `remoteHookEnvArgs` injected only endpoint/node-id/version, so a remotesession inherited neither `NODETERM_AGENT_ID` nor `NODETERM_CANVAS_CONTROL`. The CLI gates@@ -79,12 +82,33 @@ valueless flag was expressible only as the last token on the line. Both failuresthe request stayed well-formed and the server answered about the wrong flag, which sends the nextdebugger to the verb table instead of to the shim.-**The staleness window this lives in:** the shim is rewritten locally at every app boot, but onto-an SSH host only inside `RemoteHooks.setup()`, i.e. **on connect**. An already-connected SSH-project keeps the shim it was handed, so a parser improvement reaches remote agent nodes only-after a reconnect, with nothing on the wire to say which loop is running — the same shape as the-managed hook script's stale window. New verbs are therefore designed to parse identically under-both loops: give every flag a value and the old and new loops agree.+**The staleness window this lives in:** the shim is rewritten locally at every app boot, and an+SSH host's copy is checked on every connect and brought up to this build (below), so a parser+improvement reaches remote agent nodes on the first connect after the update. A host can still run+an older loop for a while — its tunnel is down, the file is unreadable, or a second desktop on an+older build shares the host account — with nothing on the wire to say which loop is running. New+verbs are therefore designed to parse identically under both loops: give every flag a value and+the old and new loops agree.++### Keeping the host current++Everything above is generated by the app, so a host's copy is only as current as the last build+that wrote it. `RemoteHooks.refreshAgentTools` keeps it current, for the canvas and context shims,+both skills (system and every managed account pinned to the host), and our instruction blocks:++- **One probe, one round trip.** The host runs POSIX `cksum` over each file (over exactly our+ marker span for an instruction file), and the desktop compares that with the checksum of the+ bytes it would write. Only what differs is rewritten; a current host costs one read and no+ write. A host with no `cksum` gets everything written, as every connect did before.+- **When.** Every connect (a fresh master, or the one that survived an app restart) and every+ reverse-tunnel repair. The 45 s watchdog costs nothing once the host is confirmed for this run,+ retries an unconfirmed host on a 1/5/15-minute backoff, and looks again hourly — the only thing+ that can change the files mid-run is someone else (another desktop, a hand edit).+- **Never.** A file that cannot be read is not written over; a managed account whose dir is gone+ from the host does not get it back; a probe reply that does not parse changes nothing.+- **A running agent** keeps what it already read: the shim's `help` is current as soon as the+ file is, a Claude skill is re-read when it is next invoked, and codex / gemini / opencode read+ their instruction files at session start.### Gating and failure behaviordiff --git a/src/core/canvas-control-core.ts b/src/core/canvas-control-core.tsindex d63629a26..f390ccc8f 100644--- a/src/core/canvas-control-core.ts+++ b/src/core/canvas-control-core.ts@@ -558,10 +558,21 @@ export function parseControlRequest(const CC_START = '<!-- nodeterm:manage-canvas:start -->'const CC_END = '<!-- nodeterm:manage-canvas:end -->'+/** The two markers, for the SSH freshness probe, which must find the block exactly where the+ * merge below would. */+export const CANVAS_CONTROL_MARKERS = { start: CC_START, end: CC_END } as const++/** The exact bytes the merge below writes from the start marker through the end marker. ONE+ * definition: the SSH freshness probe compares a host's copy against this, so a second spelling+ * would make every host look stale (or, worse, current). */+export function frameCanvasControlBlock(block: string): string {+ return `${CC_START}\n${block.trim()}\n${CC_END}`+}+/** Idempotently merge the canvas-control block into a global instructions file.* Everything outside the markers is preserved; an existing block is replaced. */export function mergeCanvasControlBlock(existing: string, block: string): string {- const full = `${CC_START}\n${block.trim()}\n${CC_END}`+ const full = frameCanvasControlBlock(block)const start = existing.indexOf(CC_START)const end = existing.indexOf(CC_END)if (start >= 0 && end > start) {diff --git a/src/core/context-link-core.ts b/src/core/context-link-core.tsindex 08a47e75e..b340821b0 100644--- a/src/core/context-link-core.ts+++ b/src/core/context-link-core.ts@@ -70,10 +70,19 @@ export async function resolveLinkTranscript(const INSTR_START = '<!-- nodeterm:get-linked-context:start -->'const INSTR_END = '<!-- nodeterm:get-linked-context:end -->'+/** The two markers, for the SSH freshness probe (see `CANVAS_CONTROL_MARKERS`). */+export const LINKED_CONTEXT_MARKERS = { start: INSTR_START, end: INSTR_END } as const++/** The exact bytes the merge below writes from the start marker through the end marker — the one+ * definition the SSH freshness probe compares a host's copy against. */+export function frameInstructionsBlock(block: string): string {+ return `${INSTR_START}\n${block.trim()}\n${INSTR_END}`+}+/** Idempotently merge our marker-delimited block into a global instructions file* (~/.codex/AGENTS.md, ~/.gemini/GEMINI.md). Everything outside the markers is preserved. */export function mergeInstructionsBlock(existing: string, block: string): string {- const full = `${INSTR_START}\n${block.trim()}\n${INSTR_END}`+ const full = frameInstructionsBlock(block)const start = existing.indexOf(INSTR_START)const end = existing.indexOf(INSTR_END)if (start >= 0 && end > start) {diff --git a/src/core/remote-ssh/posix-cksum.test.ts b/src/core/remote-ssh/posix-cksum.test.tsnew file mode 100644index 000000000..6933f1d0f--- /dev/null+++ b/src/core/remote-ssh/posix-cksum.test.ts@@ -0,0 +1,46 @@+// The local half of the SSH agent-tools freshness check computes, for the exact bytes we would+// write, what the host's own `cksum` prints for the bytes it holds. The two must agree on every+// input or the check reports a current file as stale (a wasted write) or — worse — a stale one as+// current. So this is pinned against the REAL `cksum` binary, not against a table of constants.+import { execFileSync } from 'child_process'+import { describe, expect, it } from 'vitest'+import { CONTROL_SHIM_SCRIPT, buildCanvasSkillBody } from '../canvas-control-core'+import { CONTEXT_SHIM_SCRIPT } from '../context-link-core'+import { formatCksum, parseCksumLine, posixCksum } from './posix-cksum'++function realCksum(bytes: Uint8Array): string {+ return execFileSync('cksum', [], { input: bytes, encoding: 'utf8' }).trim()+}++const cases: [string, Uint8Array][] = [+ ['empty', new Uint8Array()],+ ['one byte', Buffer.from('a')],+ ['a newline', Buffer.from('\n')],+ ['utf-8 multibyte', Buffer.from('şğüçöı — ✓ 日本\n', 'utf8')],+ ['255 bytes (length fits one byte)', Buffer.alloc(255, 0x41)],+ ['256 bytes (length needs two bytes)', Buffer.alloc(256, 0x42)],+ ['every byte value', Uint8Array.from({ length: 256 }, (_, i) => i)],+ ['70 000 bytes (length needs three bytes)', Buffer.alloc(70_000, 0x7a)],+ ['the canvas shim', Buffer.from(CONTROL_SHIM_SCRIPT, 'utf8')],+ ['the context shim', Buffer.from(CONTEXT_SHIM_SCRIPT, 'utf8')],+ ['the canvas skill', Buffer.from(buildCanvasSkillBody('/home/u/.nodeterm/nodeterm.sh'), 'utf8')]+]++describe.skipIf(process.platform === 'win32')('posixCksum agrees with the real cksum', () => {+ it.each(cases)('%s', (_name, bytes) => {+ expect(formatCksum(posixCksum(bytes))).toBe(realCksum(bytes))+ })+})++describe('parseCksumLine', () => {+ it('reads CRC and size, ignoring a trailing file name (BusyBox/GNU print one for an operand)', () => {+ expect(parseCksumLine('4294967295 0')).toEqual({ crc: 4294967295, size: 0 })+ expect(parseCksumLine('123 45 -')).toEqual({ crc: 123, size: 45 })+ })++ it('refuses anything that is not two unsigned decimal numbers', () => {+ for (const bad of ['', 'x 1', '1', '-1 2', '4294967296 1', '1 2.5', 'NaN 3']) {+ expect(parseCksumLine(bad)).toBeNull()+ }+ })+})diff --git a/src/core/remote-ssh/posix-cksum.ts b/src/core/remote-ssh/posix-cksum.tsnew file mode 100644index 000000000..6fdd8732a--- /dev/null+++ b/src/core/remote-ssh/posix-cksum.ts@@ -0,0 +1,60 @@+/**+ * The POSIX `cksum` algorithm, computed locally so we can predict what a host's own `cksum` prints+ * for the bytes we would write there.+ *+ * Why this and not a real hash: `cksum` is the one checksum utility POSIX REQUIRES, so it is on+ * every host we already support (GNU coreutils, macOS, BusyBox) with one output format, while+ * `sha256sum` / `shasum -a 256` / `sha256` / `openssl dgst` each exist on only some of them. It is+ * a CRC-32, not collision resistant — acceptable because it is never a security check here (anyone+ * who can write these files already owns the account). It detects accidental drift between two+ * versions of a generated file, and together with the exact byte length a miss needs a change that+ * keeps both, about one in 2^32.+ *+ * Algorithm (POSIX.1-2017, `cksum`): CRC-32 with polynomial 0x04C11DB7, most significant bit first,+ * initial value 0, run over the data and then over the data LENGTH (least significant byte first,+ * only as many bytes as the value needs), then complemented.+ */++const TABLE = (() => {+ const t = new Uint32Array(256)+ for (let i = 0; i < 256; i++) {+ let c = i << 24+ for (let k = 0; k < 8; k++) c = c & 0x80000000 ? (c << 1) ^ 0x04c11db7 : c << 1+ t[i] = c >>> 0+ }+ return t+})()++export interface Cksum {+ crc: number+ size: number+}++function step(crc: number, byte: number): number {+ return ((crc << 8) ^ TABLE[((crc >>> 24) ^ byte) & 0xff]) >>> 0+}++export function posixCksum(bytes: Uint8Array): Cksum {+ let crc = 0+ for (let i = 0; i < bytes.length; i++) crc = step(crc, bytes[i])+ for (let n = bytes.length; n > 0; n = Math.floor(n / 256)) crc = step(crc, n % 256)+ return { crc: ~crc >>> 0, size: bytes.length }+}++/** `cksum`'s own output for stdin: `<crc> <size>`. */+export function formatCksum(c: Cksum): string {+ return `${c.crc} ${c.size}`+}++/**+ * The first two fields of a `cksum` line, or null when they are not two unsigned decimals.+ * Anything after them (a file name some implementations print) is ignored.+ */+export function parseCksumLine(line: string): Cksum | null {+ const m = /^(\d+) (\d+)(?: .*)?$/.exec(line.trim())+ if (!m) return null+ const crc = Number(m[1])+ const size = Number(m[2])+ if (!Number.isSafeInteger(crc) || crc > 0xffffffff || !Number.isSafeInteger(size)) return null+ return { crc, size }+}diff --git a/src/main/index.ts b/src/main/index.tsindex 9077198b6..bf13b3d61 100644--- a/src/main/index.ts+++ b/src/main/index.ts@@ -4395,7 +4395,13 @@ app.whenReady().then(async () => {loadCodexRelayBundle,// Lead-pane width (issue #119) for the remote tmux conf, read at connect time so the host// carries the value the user last saved. 0 (the default) keeps the conf byte-identical.- () => settingsStore.get().tmuxLeadPaneWidth+ () => settingsStore.get().tmuxLeadPaneWidth,+ // The managed Claude accounts pinned to a host, whose config dirs there hold their own copies of+ // the canvas/context skills — kept current by the connect-time agent-tools check. Read per+ // check, so an account added mid-run is included. A pending account has no finished login and+ // is skipped; the refresh re-validates every id before it becomes a path.+ (hostKey) =>+ (settingsStore.get().claudeAccounts ?? []).filter((a) => a.host === hostKey && !a.pending).map((a) => a.id))// Pre-warm the ControlMasters of OPEN SSH projects, in the background, one host at a time.//diff --git a/src/main/remote-ssh/agent-tools-freshness.test.ts b/src/main/remote-ssh/agent-tools-freshness.test.tsnew file mode 100644index 000000000..55851c9a0--- /dev/null+++ b/src/main/remote-ssh/agent-tools-freshness.test.ts@@ -0,0 +1,308 @@+// The freshness probe is generated shell that runs on someone else's machine, so it is tested the+// way this repo tests every such script: for real, under /bin/sh, against a fake host tree — plus+// the pure halves (the report parser and the cadence) on their own.+import { execFileSync, spawnSync } from 'child_process'+import { mkdirSync, mkdtempSync, readdirSync, rmSync, symlinkSync, writeFileSync } from 'fs'+import { tmpdir } from 'os'+import path from 'path'+import { afterEach, beforeEach, describe, expect, it } from 'vitest'+import { formatCksum, posixCksum } from '../../core/remote-ssh/posix-cksum'+import { mergeCanvasControlBlock, frameCanvasControlBlock, CANVAS_CONTROL_MARKERS } from '../../core/canvas-control-core'+import { posixQuote } from '../../shared/ssh'+import {+ AGENT_TOOLS_RECHECK_MS,+ agentToolsCheckCommand,+ agentToolsCheckDue,+ parseAgentToolsReport,+ recordAgentToolsCheck,+ type ProbeEntry+} from './agent-tools-freshness'++const sum = (text: string) => formatCksum(posixCksum(Buffer.from(text, 'utf8')))+/** The formatted checksum the report holds for entry `i`, or its state when it holds none. */+function sumAt(report: ReturnType<typeof parseAgentToolsReport>, i: number): string {+ if (report?.kind !== 'report') return String(report?.kind)+ const s = report.statuses[i]+ return s.state === 'present' ? formatCksum(s.sum) : s.state+}+const { start: S, end: E } = CANVAS_CONTROL_MARKERS++let home: string+beforeEach(() => {+ home = mkdtempSync(path.join(tmpdir(), "nt-fresh-' h-"))+})+afterEach(() => rmSync(home, { recursive: true, force: true }))++function put(rel: string, content: string): string {+ const p = path.join(home, rel)+ mkdirSync(path.dirname(p), { recursive: true })+ writeFileSync(p, content)+ return p+}++function runProbe(entries: ProbeEntry[], env: Record<string, string> = {}, pathVar?: string): string {+ const cmd = agentToolsCheckCommand(`NT_H=${posixQuote(home)}; `, entries, 'COPILOT_HOME')+ const r = spawnSync('/bin/sh', ['-c', cmd], {+ env: { PATH: pathVar ?? process.env.PATH ?? '/usr/bin:/bin', HOME: home, ...env },+ encoding: 'utf8'+ })+ if (r.error) throw r.error+ expect(r.status).toBe(0)+ return r.stdout+}++const file = (p: string, gateDir?: string): ProbeEntry => ({+ kind: 'file',+ pathExpr: posixQuote(p),+ ...(gateDir ? { gateDirExpr: posixQuote(gateDir) } : {})+})+const block = (pathExpr: string): ProbeEntry => ({ kind: 'block', pathExpr, start: S, end: E })++describe.skipIf(process.platform === 'win32')('the freshness probe (real /bin/sh)', () => {+ it('reports each owned file by the checksum of the bytes on disk', () => {+ const body = '#!/bin/sh\necho şimdi\n'+ const p = put('.nodeterm/nodeterm.sh', body)+ const report = parseAgentToolsReport(runProbe([file(p)]), 1)+ expect(report).toEqual({ kind: 'report', statuses: [{ state: 'present', sum: posixCksum(Buffer.from(body)) }], env: '' })+ })++ it('tells missing from unreadable, and never reads through a dangling link or a directory', () => {+ const dir = path.join(home, '.claude/skills/manage-nodeterm-canvas/SKILL.md')+ mkdirSync(dir, { recursive: true }) // a directory where the file should be+ const dangling = path.join(home, 'dangling.md')+ symlinkSync(path.join(home, 'nowhere'), dangling)+ const report = parseAgentToolsReport(+ runProbe([file(path.join(home, 'absent.sh')), file(dir), file(dangling)]),+ 3+ )+ expect(report?.kind === 'report' && report.statuses.map((s) => s.state)).toEqual([+ 'missing',+ 'unreadable',+ 'unreadable'+ ])+ })++ it('skips a gated file whose directory does not exist, and reads it when the directory does', () => {+ const acc = path.join(home, '.nodeterm/claude-accounts/acc-1')+ const gone = path.join(home, '.nodeterm/claude-accounts/gone')+ const skill = put('.nodeterm/claude-accounts/acc-1/skills/x/SKILL.md', 'x\n')+ const report = parseAgentToolsReport(+ runProbe([file(skill, acc), file(path.join(gone, 'skills/x/SKILL.md'), gone)]),+ 2+ )+ expect(report?.kind === 'report' && report.statuses).toEqual([+ { state: 'present', sum: posixCksum(Buffer.from('x\n')) },+ { state: 'no-gate' }+ ])+ })++ it('checksums EXACTLY the span the merge would replace — so a current block matches, a stale one does not', () => {+ const current = mergeCanvasControlBlock('# my notes\r\n\r\nkeep me\n', 'the block\nsecond line')+ const p = put('.codex/AGENTS.md', `${current}trailing user text\n`)+ const stale = put('.gemini/GEMINI.md', mergeCanvasControlBlock('', 'an OLD block'))+ const report = parseAgentToolsReport(runProbe([block(posixQuote(p)), block(posixQuote(stale))]), 2)+ const want = frameCanvasControlBlock('the block\nsecond line')+ expect(report?.kind === 'report' && report.statuses[0]).toEqual({ state: 'present', sum: posixCksum(Buffer.from(want)) })+ expect(sumAt(report, 1)).not.toBe(sum(want))+ })++ it('an end marker BEFORE the start marker is no block at all, as the merge sees it', () => {+ // mergeCanvasControlBlock only replaces when the first end marker follows the first start+ // marker; otherwise it appends. The probe must not call such a file current.+ const p = put('.codex/AGENTS.md', `${E}\n${frameCanvasControlBlock('b')}\n`)+ const report = parseAgentToolsReport(runProbe([block(posixQuote(p))]), 1)+ expect(sumAt(report, 0)).toBe(sum(''))+ })++ it('evaluates a shell-expanded target through the $NT_H binding, and reports the env it was asked for', () => {+ put('.copilot/copilot-instructions.md', 'c\n')+ const expr = '"${COPILOT_HOME:-$NT_H/.copilot}/copilot-instructions.md"'+ const unset = parseAgentToolsReport(runProbe([{ kind: 'file', pathExpr: expr }]), 1)+ expect(unset).toEqual({ kind: 'report', statuses: [{ state: 'present', sum: posixCksum(Buffer.from('c\n')) }], env: '' })+ const hostile = '/x\nNT_END\n0 C 1 1'+ const set = parseAgentToolsReport(runProbe([{ kind: 'file', pathExpr: expr }], { COPILOT_HOME: hostile }), 1)+ // The env value is data: it can neither forge a status line nor end the report early.+ expect(set).toEqual({ kind: 'report', statuses: [{ state: 'missing' }], env: hostile })+ })++ it('a host with no cksum says so instead of reporting every file unreadable', () => {+ // A PATH holding every tool this machine has EXCEPT cksum (Ubuntu's own BusyBox build ships+ // without the applet, so "no cksum" is a real host, not a hypothetical one).+ const bin = mkdtempSync(path.join(tmpdir(), 'nt-no-cksum-'))+ try {+ for (const d of ['/usr/bin', '/bin']) {+ let names: string[] = []+ try {+ names = readdirSync(d)+ } catch {+ continue+ }+ for (const n of names) {+ if (n === 'cksum') continue+ try {+ symlinkSync(path.join(d, n), path.join(bin, n))+ } catch {+ // already linked from the other directory+ }+ }+ }+ const out = runProbe([file(put('a', 'a'))], {}, bin)+ expect(parseAgentToolsReport(out, 1)).toEqual({ kind: 'no-cksum', env: '' })+ } finally {+ rmSync(bin, { recursive: true, force: true })+ }+ })++ it('agrees with the real cksum for the probe itself (no locale or newline drift)', () => {+ const body = 'x'.repeat(3000) + '\n'+ const p = put('f', body)+ const report = parseAgentToolsReport(runProbe([file(p)]), 1)+ const real = execFileSync('cksum', [p], { encoding: 'utf8' }).split(' ').slice(0, 2).join(' ')+ expect(sumAt(report, 0)).toBe(real)+ })+})++/**+ * The probe runs in the HOST's login shell with the host's awk: dash, bash, zsh or BusyBox ash, with+ * mawk, gawk, BusyBox awk or the one-true awk macOS ships. Every combination this machine has must+ * produce the same report, and the same checksums the local side computes. (Combinations that are+ * absent are skipped; `NT_PROBE_EXTRA_AWK` / `NT_PROBE_EXTRA_SH` add binaries for a one-off run —+ * e.g. an extracted `original-awk`, the macOS dialect.)+ */+describe.skipIf(process.platform === 'win32')('the probe under every sh × awk on this machine', () => {+ const which = (bin: string) => {+ const r = spawnSync('/bin/sh', ['-c', `command -v ${bin}`], { encoding: 'utf8' })+ return r.status === 0 ? r.stdout.trim() : null+ }+ const busybox = which('busybox')+ const busyboxHas = (applet: string) =>+ !!busybox && spawnSync(busybox, ['--list'], { encoding: 'utf8' }).stdout.split('\n').includes(applet)+ const shells: [string, string[]][] = [+ ...['dash', 'bash', 'zsh'].flatMap((n): [string, string[]][] => (which(n) ? [[n, [which(n)!]]] : [])),+ ...(busyboxHas('sh') ? [['busybox sh', [busybox!, 'sh']] as [string, string[]]] : []),+ ...(process.env.NT_PROBE_EXTRA_SH ?? '').split(':').filter(Boolean).map((p): [string, string[]] => [p, [p]])+ ]+ const awks: [string, string][] = [+ ...['mawk', 'gawk'].flatMap((n): [string, string][] => (which(n) ? [[n, which(n)!]] : [])),+ ...(busyboxHas('awk') ? [['busybox awk', busybox!] as [string, string]] : []),+ ...(process.env.NT_PROBE_EXTRA_AWK ?? '').split(':').filter(Boolean).map((p): [string, string] => [p, p])+ ]+ const combos = shells.flatMap(([sn, sh]) => awks.map(([an, awk]) => [`${sn} + ${an}`, sh, awk] as const))++ it.each(combos)('%s', (_name, sh, awk) => {+ const texts = {+ current: `# notes ş\n${frameCanvasControlBlock('line one\nline — two')}\nafter\n`,+ crlf: frameCanvasControlBlock('a\nb').replace(/\n/g, '\r\n'),+ endFirst: `${E}\n${frameCanvasControlBlock('b')}`,+ none: 'no block here\n',+ noNewline: `x${frameCanvasControlBlock('tail')}`+ }+ const entries: ProbeEntry[] = Object.entries(texts).map(([n, t]) => block(posixQuote(put(`${n}.md`, t))))+ entries.push(file(put('owned.sh', '#!/bin/sh\necho ğ\n')))+ // `awk` is whichever dialect this combination names; every other tool is the machine's own.+ const bin = mkdtempSync(path.join(tmpdir(), 'nt-probe-bin-'))+ try {+ if (awk.endsWith('busybox')) writeFileSync(path.join(bin, 'awk'), `#!/bin/sh\nexec ${awk} awk "$@"\n`, { mode: 0o755 })+ else symlinkSync(awk, path.join(bin, 'awk'))+ const cmd = agentToolsCheckCommand(`NT_H=${posixQuote(home)}; `, entries, 'COPILOT_HOME')+ const r = spawnSync(sh[0], [...sh.slice(1), '-c', cmd], {+ env: { PATH: `${bin}:${process.env.PATH ?? '/usr/bin:/bin'}`, HOME: home },+ encoding: 'utf8'+ })+ expect(r.status).toBe(0)+ const report = parseAgentToolsReport(r.stdout, entries.length)+ expect([0, 1, 2, 3, 4, 5].map((i) => sumAt(report, i))).toEqual([+ sum(frameCanvasControlBlock('line one\nline — two')),+ sum(texts.crlf), // CR stays inside its line: the span is the file's own bytes+ sum(''), // end before start: no block, as the merge sees it+ sum(''),+ sum(frameCanvasControlBlock('tail')),+ sum('#!/bin/sh\necho ğ\n')+ ])+ } finally {+ rmSync(bin, { recursive: true, force: true })+ }+ })+})++describe('parseAgentToolsReport', () => {+ const ok = 'NT_AGENT_TOOLS_CHECK 1\n0 C 1 2\n1 M\n2 U\n3 D\nNT_ENV COPILOT_HOME=/c\nNT_END\n'++ it('reads a well-formed report, tolerating a login banner before it', () => {+ expect(parseAgentToolsReport(`Welcome!\n${ok}`, 4)).toEqual({+ kind: 'report',+ statuses: [+ { state: 'present', sum: { crc: 1, size: 2 } },+ { state: 'missing' },+ { state: 'unreadable' },+ { state: 'no-gate' }+ ],+ env: '/c'+ })+ })++ it('refuses a report that is cut short, out of order, over-long or malformed — never guesses', () => {+ const bad = [+ '',+ 'NT_AGENT_TOOLS_CHECK 1\n0 C 1 2\n', // no end+ ok.replace('\nNT_END\n', '\n'), // no end sentinel+ ok.replace('1 M', '2 M'), // out of order+ ok.replace('3 D\n', ''), // too few+ ok.replace('3 D\n', '3 D\n4 M\n'), // too many+ ok.replace('0 C 1 2', '0 C one 2'), // not a checksum+ ok.replace('2 U', '2 X'), // unknown status+ ok.replace('NT_AGENT_TOOLS_CHECK 1', 'NT_AGENT_TOOLS_CHECK 2') // a version we do not speak+ ]+ for (const b of bad) expect(parseAgentToolsReport(b, 4)).toBeNull()+ })+})++describe('agentToolsCheckDue — how often a host is looked at', () => {+ const t0 = 1_000_000_000++ it('a connect or a tunnel repair always checks: a master just came up', () => {+ const verified = recordAgentToolsCheck(undefined, 'set', true, t0)+ expect(agentToolsCheckDue(verified, 'set', t0 + 1, 'connect')).toBe(true)+ expect(agentToolsCheckDue(verified, 'set', t0 + 1, 'repair')).toBe(true)+ })++ it('the 45 s reuse branch costs nothing once this run has confirmed the host', () => {+ const verified = recordAgentToolsCheck(undefined, 'set', true, t0)+ expect(agentToolsCheckDue(verified, 'set', t0 + 45_000, 'reuse')).toBe(false)+ expect(agentToolsCheckDue(verified, 'set', t0 + AGENT_TOOLS_RECHECK_MS - 1, 'reuse')).toBe(false)+ })++ it('…and looks again once an hour, because another desktop may have written its own version', () => {+ const verified = recordAgentToolsCheck(undefined, 'set', true, t0)+ expect(agentToolsCheckDue(verified, 'set', t0 + AGENT_TOOLS_RECHECK_MS, 'reuse')).toBe(true)+ })++ it('a host never confirmed this run is checked on the next reuse tick', () => {+ expect(agentToolsCheckDue(undefined, 'set', t0, 'reuse')).toBe(true)+ })++ it('a different expected set (an account added, a new home) is unconfirmed', () => {+ const verified = recordAgentToolsCheck(undefined, 'set', true, t0)+ expect(agentToolsCheckDue(verified, 'other', t0 + 1, 'reuse')).toBe(true)+ })++ it('a failing host backs off on the reuse branch instead of retrying every tick', () => {+ let s = recordAgentToolsCheck(undefined, 'set', false, t0)+ expect(agentToolsCheckDue(s, 'set', t0 + 45_000, 'reuse')).toBe(false)+ expect(agentToolsCheckDue(s, 'set', t0 + 60_000, 'reuse')).toBe(true)+ s = recordAgentToolsCheck(s, 'set', false, t0 + 60_000)+ s = recordAgentToolsCheck(s, 'set', false, t0 + 400_000)+ // settles at one attempt per 15 minutes+ expect(agentToolsCheckDue(s, 'set', t0 + 400_000 + 899_000, 'reuse')).toBe(false)+ expect(agentToolsCheckDue(s, 'set', t0 + 400_000 + 900_000, 'reuse')).toBe(true)+ })++ it('a success resets the backoff and a failure keeps the earlier confirmation', () => {+ let s = recordAgentToolsCheck(undefined, 'set', true, t0)+ s = recordAgentToolsCheck(s, 'set', false, t0 + AGENT_TOOLS_RECHECK_MS)+ expect(s.verified).toEqual({ setId: 'set', at: t0 })+ expect(s.failures).toBe(1)+ s = recordAgentToolsCheck(s, 'set', true, t0 + AGENT_TOOLS_RECHECK_MS + 60_000)+ expect(s.failures).toBe(0)+ })+})diff --git a/src/main/remote-ssh/agent-tools-freshness.ts b/src/main/remote-ssh/agent-tools-freshness.tsnew file mode 100644index 000000000..ab6d5e32b--- /dev/null+++ b/src/main/remote-ssh/agent-tools-freshness.ts@@ -0,0 +1,201 @@+/**+ * Is what an SSH host holds of our agent tools — the canvas and context shims, their SKILL.md files+ * (system and managed-account), and our marker blocks in the codex/gemini/copilot/opencode+ * instruction files — still exactly what this app build would write? And when may we ask?+ *+ * WHY THIS EXISTS. Those files are generated by the app and written onto the host only from the+ * connect path. Nothing ever looked at them again, so a host could keep another build's text for a+ * whole app run: an install that failed open on connect (they are fire-and-forget) was never+ * retried; a tunnel that failed verification at connect and was repaired later on the reuse branch+ * never got them at all; a managed account's skill was written once, when the account was ADDED,+ * and never again — so after an update every remote account session read the verb docs of the+ * build that created the account. And a second desktop sharing the host account writes its own+ * version on its own connects. Agents then read verb docs for a product that no longer exists.+ *+ * THE STAMP IS THE BYTES. The host checksums the files it actually holds (for an instruction file,+ * exactly the span `mergeCanvasControlBlock` / `mergeInstructionsBlock` would replace), and we+ * compare against the checksum of the exact bytes we would write. Nothing is embedded in the+ * artifacts: a stamp line would be noise in every agent's context, would need a migration for+ * hosts written by older builds, and would trust a file's claim about itself — a hand edit or a+ * foreign writer that keeps the line goes unseen. Hashing the bytes catches a generator change+ * with no version bump, a deletion, and a foreign or older writer, and works on day one against+ * files older builds wrote. The checksum is POSIX `cksum` (see posix-cksum.ts for why not sha256);+ * a host without one falls back to the pre-check behaviour — write everything.+ *+ * ONE ROUND TRIP. Every file is probed by one generated command whose reply is a few hundred bytes,+ * so a check costs no more than the tunnel probe beside it — and a host that is current costs no+ * write at all.+ */+import { parseCksumLine, type Cksum } from '../../core/remote-ssh/posix-cksum'+import { posixQuote } from '../../shared/ssh'+import { recordTunnelRepair, shouldAttemptTunnelRepair } from './tunnel-repair'++/** One file the probe looks at. `pathExpr` is a ready-to-splice shell word: a `posixQuote`d+ * literal, or a double-quoted expansion bound through the command's prelude (see+ * `openCodeInstructionsTarget`). */+export type ProbeEntry =+ | {+ kind: 'file'+ pathExpr: string+ /** A directory that must ALREADY exist for this file to be ours to write — a managed+ * account's config dir. Absent ⇒ `no-gate`, and the file is never recreated (that would+ * resurrect the directory of an account the host no longer has). */+ gateDirExpr?: string+ }+ | { kind: 'block'; pathExpr: string; start: string; end: string }++export type ProbeStatus =+ | { state: 'present'; sum: Cksum }+ | { state: 'missing' }+ /** Exists but is not a readable regular file (a directory, a dangling link, no permission).+ * NEVER written over: we cannot see what we would be replacing. */+ | { state: 'unreadable' }+ | { state: 'no-gate' }++export type AgentToolsReport =+ | { kind: 'report'; statuses: ProbeStatus[]; env: string }+ /** The host has no `cksum`. Nothing was probed; `env` is still reported. */+ | { kind: 'no-cksum'; env: string }++const HEADER = 'NT_AGENT_TOOLS_CHECK 1'+const END = 'NT_END'++/**+ * The span of an instruction file that `merge*Block` would replace, printed byte for byte (awk+ * under LC_ALL=C, so `index`/`substr` count bytes): from the FIRST start marker through the end of+ * the FIRST end marker, and only when that end marker comes after the start marker — otherwise the+ * merge appends, so there is no block and nothing is printed. Lines are rejoined with the `\n` awk+ * split them on; a `\r` stays inside its line, so a CRLF file does not pass for our LF block.+ */+const AWK_BLOCK =+ '{ t = (NR == 1) ? $0 : t "\\n" $0 } ' ++ 'END { i = index(t, s); j = index(t, e); if (i > 0 && j > i) printf "%s", substr(t, i, j - i + length(e)) }'++/**+ * The probe. Output, one line each: the header; then either `NT_NO_CKSUM`, or one status per entry+ * in order (`<i> C <crc> <size>` | `<i> M` | `<i> U` | `<i> D`); then `NT_ENV <name>=<value>`+ * (the one environment variable the caller needs resolved on the host — printed LAST, because it+ * is host data and must not be able to forge a status line); then `NT_END`.+ */+export function agentToolsCheckCommand(prelude: string, entries: readonly ProbeEntry[], envName: string): string {+ if (!/^[A-Z_][A-Z0-9_]*$/.test(envName)) throw new Error(`not an environment variable name: ${envName}`)+ for (const e of entries) {+ // awk -v expands backslash escapes; our markers have none, and a future one must not slip in.+ if (e.kind === 'block' && (e.start.includes('\\') || e.end.includes('\\'))) {+ throw new Error('a block marker may not contain a backslash')+ }+ }+ const fns =+ `nt_s() { if [ ! -e "$2" ] && [ ! -L "$2" ]; then printf '%s M\\n' "$1"; return 1; fi; ` ++ `if [ ! -f "$2" ] || [ ! -r "$2" ]; then printf '%s U\\n' "$1"; return 1; fi; return 0; }; ` ++ `nt_f() { nt_s "$1" "$2" || return 0; nt_c=$(cksum < "$2") || { printf '%s U\\n' "$1"; return 0; }; ` ++ `printf '%s C %s\\n' "$1" "$nt_c"; }; ` ++ `nt_g() { if [ -d "$3" ]; then nt_f "$1" "$2"; else printf '%s D\\n' "$1"; fi; }; ` ++ `nt_b() { nt_s "$1" "$2" || return 0; nt_c=$(awk -v s="$3" -v e="$4" ${posixQuote(AWK_BLOCK)} "$2" | cksum) || ` ++ `{ printf '%s U\\n' "$1"; return 0; }; printf '%s C %s\\n' "$1" "$nt_c"; }; `+ const probes = entries+ .map((e, i) => {+ if (e.kind === 'block') return `nt_b ${i} ${e.pathExpr} ${posixQuote(e.start)} ${posixQuote(e.end)}; `+ return e.gateDirExpr ? `nt_g ${i} ${e.pathExpr} ${e.gateDirExpr}; ` : `nt_f ${i} ${e.pathExpr}; `+ })+ .join('')+ const env = `printf 'NT_ENV %s=%s\\n' ${envName} "\${${envName}:-}"; printf '%s\\n' ${END}`+ return (+ `${prelude}LC_ALL=C; export LC_ALL; printf '%s\\n' ${posixQuote(HEADER)}; ` ++ `if command -v cksum >/dev/null 2>&1; then ${fns}${probes}else printf '%s\\n' NT_NO_CKSUM; fi; ${env}`+ )+}++/**+ * Parse the probe's reply. Anything that is not exactly the shape above is `null` — a report we+ * cannot read is never evidence that a file is stale (or current); the caller retries later. A+ * login banner printed before the header is tolerated.+ */+export function parseAgentToolsReport(stdout: string, count: number): AgentToolsReport | null {+ const at = stdout.indexOf(`${HEADER}\n`)+ if (at < 0) return null+ const body = stdout.slice(at + HEADER.length + 1)+ const envAt = body.indexOf('NT_ENV ')+ if (envAt < 0 || (envAt > 0 && body[envAt - 1] !== '\n')) return null+ const tail = body.slice(envAt)+ const endAt = tail.lastIndexOf(`\n${END}`)+ if (endAt < 0 || tail.slice(endAt).trim() !== END) return null+ const eq = tail.indexOf('=')+ if (eq < 0 || eq > endAt) return null+ const env = tail.slice(eq + 1, endAt)+ const lines = body.slice(0, envAt).split('\n').filter((l, i, all) => !(i === all.length - 1 && l === ''))+ if (lines.length === 1 && lines[0] === 'NT_NO_CKSUM') return { kind: 'no-cksum', env }+ if (lines.length !== count) return null+ const statuses: ProbeStatus[] = []+ for (let i = 0; i < count; i++) {+ const m = /^(\d+) (C (.+)|M|U|D)$/.exec(lines[i])+ if (!m || Number(m[1]) !== i) return null+ if (m[2] === 'M') statuses.push({ state: 'missing' })+ else if (m[2] === 'U') statuses.push({ state: 'unreadable' })+ else if (m[2] === 'D') statuses.push({ state: 'no-gate' })+ else {+ const sum = parseCksumLine(m[3])+ if (!sum) return null+ statuses.push({ state: 'present', sum })+ }+ }+ return { kind: 'report', statuses, env }+}++// ---- cadence --------------------------------------------------------------------------------++/**+ * How long a confirmed host goes before the reuse branch looks again. Within one app run our own+ * bytes cannot change, so the only thing a re-look can find is a writer outside this run — another+ * desktop (possibly another build) on the same host account, or a hand edit. Hourly bounds how long+ * that lasts at one read per host per hour, and bounds a two-desktop tug-of-war to one write each.+ */+export const AGENT_TOOLS_RECHECK_MS = 60 * 60_000++/** What woke the check. `connect` = a master was just (re-)established, `repair` = the reuse+ * branch just rebuilt a dead hook tunnel, `reuse` = a routine connect() on a live master (the 45 s+ * watchdog, a tab switch). */+export type AgentToolsTrigger = 'connect' | 'repair' | 'reuse'++export interface AgentToolsHostState {+ /** The expected set the last SUCCESSFUL check confirmed, and when. */+ verified?: { setId: string; at: number }+ /** Consecutive failed checks since the last success (the same backoff shape as tunnel repair). */+ failures: number+ lastAttemptAt: number+}++/**+ * May we check this host now?+ *+ * A connect or a repair always may: a master just came up, it is rare, and it is exactly when the+ * host could have been touched by someone else. The reuse branch runs every 45 s per project, so+ * there it costs NOTHING once this run has confirmed the host for the set we would write — until+ * the hourly re-look. An unconfirmed host (the connect-time check failed, or never ran because the+ * tunnel was not verified then) is retried on the reuse branch with the tunnel-repair backoff:+ * immediately, then 1 / 5 / 15 minutes — a host whose files cannot be written is not rewritten+ * every tick.+ */+export function agentToolsCheckDue(+ state: AgentToolsHostState | undefined,+ setId: string,+ now: number,+ trigger: AgentToolsTrigger+): boolean {+ if (trigger !== 'reuse') return true+ const v = state?.verified+ if (v && v.setId === setId && now - v.at < AGENT_TOOLS_RECHECK_MS) return false+ return shouldAttemptTunnelRepair(state, now)+}++/** Fold one check's outcome into the state `agentToolsCheckDue` reads. A failure keeps the earlier+ * confirmation (it still describes the last known-good set) but counts toward the backoff. */+export function recordAgentToolsCheck(+ state: AgentToolsHostState | undefined,+ setId: string,+ ok: boolean,+ now: number+): AgentToolsHostState {+ const next = recordTunnelRepair(state, ok, now)+ return { ...next, verified: ok ? { setId, at: now } : state?.verified }+}diff --git a/src/main/remote-ssh/agent-tools-refresh.test.ts b/src/main/remote-ssh/agent-tools-refresh.test.tsnew file mode 100644index 000000000..df7cb653b--- /dev/null+++ b/src/main/remote-ssh/agent-tools-refresh.test.ts@@ -0,0 +1,281 @@+// `RemoteHooks.refreshAgentTools`, run for real under /bin/sh against a fake host tree: the one+// check that keeps an SSH host's canvas/context shims, skills and instruction blocks equal to what+// THIS build would write — rewriting only what differs, and never what it cannot read.+import { spawnSync } from 'child_process'+import {+ existsSync,+ lstatSync,+ mkdirSync,+ mkdtempSync,+ readFileSync,+ readdirSync,+ readlinkSync,+ rmSync,+ symlinkSync,+ writeFileSync+} from 'fs'+import { tmpdir } from 'os'+import path from 'path'+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'+import {+ CONTROL_SHIM_SCRIPT,+ buildCanvasControlInstructions,+ buildCanvasSkillBody,+ mergeCanvasControlBlock+} from '../../core/canvas-control-core'+import { CONTEXT_SHIM_SCRIPT, buildContextLinkSkillBody } from '../../core/context-link-core'+import { RemoteHooks, type RemoteRunner } from './remote-hooks'++const conn = { host: 'fixture', user: 'fixture' }+let home: string+let warn: ReturnType<typeof vi.spyOn>++beforeEach(() => {+ home = mkdtempSync(path.join(tmpdir(), "nt-refresh-' h-"))+ warn = vi.spyOn(console, 'warn').mockImplementation(() => {})+ vi.spyOn(console, 'info').mockImplementation(() => {})+})+afterEach(() => {+ vi.restoreAllMocks()+ rmSync(home, { recursive: true, force: true })+})++const SHIM = () => `${home}/.nodeterm/nodeterm.sh`+const CTX = () => `${home}/.nodeterm/context.sh`+const SKILL = () => `${home}/.claude/skills/manage-nodeterm-canvas/SKILL.md`+const CTX_SKILL = () => `${home}/.claude/skills/get-linked-context/SKILL.md`+const accountDir = (id: string) => `${home}/.nodeterm/claude-accounts/${id}`++interface HostRunner extends RemoteRunner {+ /** Every remote command, in order. */+ calls: string[]+}++/** Runs each remote command in /bin/sh with only a host's environment. */+function hostRunner(opts: { env?: Record<string, string>; path?: string; failProbe?: boolean } = {}): HostRunner {+ const calls: string[] = []+ return {+ calls,+ run: async (args, stdin) => {+ const command = args.at(-1)!+ calls.push(command)+ if (opts.failProbe && command.includes('NT_AGENT_TOOLS_CHECK')) return { code: 255, stdout: '' }+ // cwd = $HOME, as an ssh exec channel starts there: a relative path the host resolves must+ // land under the fake home, never in the repo running the test.+ const r = spawnSync('/bin/sh', ['-c', command], {+ cwd: home,+ env: { PATH: opts.path ?? process.env.PATH ?? '/usr/bin:/bin', HOME: home, ...opts.env },+ input: stdin,+ encoding: 'utf8'+ })+ if (r.error) throw r.error+ return { code: r.status ?? 1, stdout: r.stdout }+ }+ }+}++const probes = (r: HostRunner) => r.calls.filter((c) => c.includes('NT_AGENT_TOOLS_CHECK'))+/** Every write publishes by renaming onto the target (owned files AND the guarded transaction). */+const publishes = (r: HostRunner) => r.calls.filter((c) => c.includes('mv -f -- '))+const publishedTo = (r: HostRunner, p: string) => publishes(r).some((c) => c.includes(p.replace(/'/g, "'\\''")))+const read = (p: string) => readFileSync(p, 'utf8')+function put(p: string, content: string): void {+ mkdirSync(path.dirname(p), { recursive: true })+ writeFileSync(p, content)+}++/** A host exactly as this build leaves it. */+async function freshHost(accounts: string[] = []): Promise<void> {+ for (const id of accounts) mkdirSync(accountDir(id), { recursive: true })+ await new RemoteHooks(hostRunner()).refreshAgentTools(conn, '/fixture.sock', home, accounts, 'connect')+}++describe.skipIf(process.platform === 'win32')('RemoteHooks.refreshAgentTools (real /bin/sh)', () => {+ it('a fresh host gets every file this build writes', async () => {+ const outcome = await new RemoteHooks(hostRunner()).refreshAgentTools(conn, '/fixture.sock', home, [], 'connect')+ expect(outcome).toBe('refreshed')+ expect(read(SHIM())).toBe(CONTROL_SHIM_SCRIPT)+ expect(read(CTX())).toBe(CONTEXT_SHIM_SCRIPT)+ expect(read(SKILL())).toBe(buildCanvasSkillBody(SHIM()))+ expect(read(CTX_SKILL())).toBe(buildContextLinkSkillBody(CTX()))+ for (const f of ['.codex/AGENTS.md', '.gemini/GEMINI.md', '.config/opencode/AGENTS.md']) {+ const text = read(path.join(home, f))+ expect(text).toContain('nodeterm:manage-canvas:start')+ expect(text).toContain('nodeterm:get-linked-context:start')+ }+ expect(read(path.join(home, '.copilot/copilot-instructions.md'))).toContain('nodeterm:manage-canvas:start')+ })++ it('a current host costs ONE read and not a single write', async () => {+ await freshHost(['acc-1'])+ const runner = hostRunner()+ const outcome = await new RemoteHooks(runner).refreshAgentTools(conn, '/fixture.sock', home, ['acc-1'], 'connect')+ expect(outcome).toBe('current')+ // Exactly the probe: a block that only LOOKED stale would cost a merge read here, and a file+ // that only looked stale a write.+ expect(runner.calls).toHaveLength(1)+ expect(probes(runner)).toHaveLength(1)+ })++ it('rewrites exactly the stale files, keeping the user text around a stale block', async () => {+ await freshHost()+ put(SHIM(), '#!/bin/sh\necho "an older build"\n')+ put(SKILL(), '---\nname: manage-nodeterm-canvas\n---\nold verbs\n')+ const gemini = path.join(home, '.gemini/GEMINI.md')+ const current = read(gemini)+ const withOldCanvas = mergeCanvasControlBlock(current, 'OLD canvas instructions')+ put(gemini, `# mine\n${withOldCanvas}`)+ const runner = hostRunner()+ const outcome = await new RemoteHooks(runner).refreshAgentTools(conn, '/fixture.sock', home, [], 'connect')+ expect(outcome).toBe('refreshed')+ expect(read(SHIM())).toBe(CONTROL_SHIM_SCRIPT)+ expect(read(SKILL())).toBe(buildCanvasSkillBody(SHIM()))+ const merged = read(gemini)+ expect(merged.startsWith('# mine\n')).toBe(true)+ expect(merged).not.toContain('OLD canvas instructions')+ expect(merged).toContain(buildCanvasControlInstructions(SHIM()).trim())+ expect(merged).toContain('nodeterm:get-linked-context:start')+ expect(publishes(runner)).toHaveLength(3)+ expect(publishedTo(runner, SHIM())).toBe(true)+ expect(publishedTo(runner, SKILL())).toBe(true)+ expect(publishedTo(runner, gemini)).toBe(true)+ })++ it('writes what is missing and nothing else', async () => {+ await freshHost()+ rmSync(CTX())+ rmSync(path.dirname(CTX_SKILL()), { recursive: true })+ const runner = hostRunner()+ await new RemoteHooks(runner).refreshAgentTools(conn, '/fixture.sock', home, [], 'connect')+ expect(read(CTX())).toBe(CONTEXT_SHIM_SCRIPT)+ expect(read(CTX_SKILL())).toBe(buildContextLinkSkillBody(CTX()))+ expect(publishes(runner)).toHaveLength(2)+ })++ it('never writes over what it cannot read — and does not call that host confirmed', async () => {+ await freshHost()+ rmSync(SKILL())+ mkdirSync(SKILL()) // a directory where our file should be+ const codex = path.join(home, '.codex/AGENTS.md')+ rmSync(codex)+ symlinkSync(path.join(home, 'no-such-dotfile'), codex) // a dangling dotfile link+ put(SHIM(), 'stale\n')+ const runner = hostRunner()+ const rh = new RemoteHooks(runner)+ expect(await rh.refreshAgentTools(conn, '/fixture.sock', home, [], 'connect')).toBe('failed')+ expect(lstatSync(SKILL()).isDirectory()).toBe(true)+ expect(readdirSync(SKILL())).toEqual([])+ expect(lstatSync(codex).isSymbolicLink()).toBe(true)+ expect(readlinkSync(codex)).toBe(path.join(home, 'no-such-dotfile'))+ expect(existsSync(path.join(home, 'no-such-dotfile'))).toBe(false)+ // The rest of the host is still brought up to date…+ expect(read(SHIM())).toBe(CONTROL_SHIM_SCRIPT)+ expect(publishes(runner)).toHaveLength(1)+ // …and the refusal is said out loud, naming what was skipped.+ expect(warn.mock.calls.flat().join('\n')).toContain('SKILL.md')+ // Not confirmed ⇒ the reuse branch keeps trying (on its backoff), instead of calling it done.+ expect(await rh.refreshAgentTools(conn, '/fixture.sock', home, [], 'reuse', Date.now() + 60_000)).toBe('failed')+ })++ it("refreshes a managed account's skills — and never resurrects an account dir the host no longer has", async () => {+ await freshHost(['acc-1'])+ put(`${accountDir('acc-1')}/skills/manage-nodeterm-canvas/SKILL.md`, 'written when the account was added\n')+ const runner = hostRunner()+ await new RemoteHooks(runner).refreshAgentTools(conn, '/fixture.sock', home, ['acc-1', 'gone', '../escape'], 'connect')+ expect(read(`${accountDir('acc-1')}/skills/manage-nodeterm-canvas/SKILL.md`)).toBe(buildCanvasSkillBody(SHIM()))+ expect(read(`${accountDir('acc-1')}/skills/get-linked-context/SKILL.md`)).toBe(buildContextLinkSkillBody(CTX()))+ expect(existsSync(accountDir('gone'))).toBe(false)+ expect(existsSync(path.join(home, '.nodeterm/escape'))).toBe(false)+ expect(runner.calls.some((c) => c.includes('escape'))).toBe(false)+ expect(publishes(runner)).toHaveLength(1)+ })++ it('writes the copilot block where the installer would: a safe COPILOT_HOME, else ~/.copilot', async () => {+ const elsewhere = path.join(home, 'copilot-home')+ await new RemoteHooks(hostRunner({ env: { COPILOT_HOME: elsewhere } })).refreshAgentTools(+ conn,+ '/fixture.sock',+ home,+ [],+ 'connect'+ )+ expect(read(path.join(elsewhere, 'copilot-instructions.md'))).toContain('nodeterm:manage-canvas:start')+ expect(existsSync(path.join(home, '.copilot'))).toBe(false)++ // A relative COPILOT_HOME is refused by the installer's validator, which falls back to+ // ~/.copilot; the refresh must land in the same place, never under the refused value. The file+ // the probe reads there (relative to the session's cwd) even holds a CURRENT block — a probe+ // taken at its word would call copilot done and ~/.copilot would never get one.+ const current = read(path.join(elsewhere, 'copilot-instructions.md'))+ put(path.join(home, 'relative-dir/copilot-instructions.md'), current)+ const runner = hostRunner({ env: { COPILOT_HOME: 'relative-dir' } })+ await new RemoteHooks(runner).refreshAgentTools(conn, '/fixture.sock', home, [], 'connect')+ expect(read(path.join(home, '.copilot/copilot-instructions.md'))).toContain('nodeterm:manage-canvas:start')+ expect(read(path.join(home, 'relative-dir/copilot-instructions.md'))).toBe(current)+ })++ it('a probe that could not run changes nothing', async () => {+ put(SHIM(), 'stale\n')+ const runner = hostRunner({ failProbe: true })+ expect(await new RemoteHooks(runner).refreshAgentTools(conn, '/fixture.sock', home, [], 'connect')).toBe('failed')+ expect(read(SHIM())).toBe('stale\n')+ expect(runner.calls).toHaveLength(1)+ })++ it('the reuse branch costs nothing once the host is confirmed, and concurrent callers share one probe', async () => {+ const runner = hostRunner()+ const rh = new RemoteHooks(runner)+ // Two projects on one host connecting at once: ONE probe, one set of writes.+ const [a, b] = await Promise.all([+ rh.refreshAgentTools(conn, '/a.sock', home, [], 'connect'),+ rh.refreshAgentTools(conn, '/b.sock', home, [], 'connect')+ ])+ expect([a, b]).toEqual(['refreshed', 'refreshed'])+ expect(probes(runner)).toHaveLength(1)+ const before = runner.calls.length+ expect(await rh.refreshAgentTools(conn, '/a.sock', home, [], 'reuse')).toBe('skipped')+ expect(runner.calls.length).toBe(before)+ // A tunnel repair looks again even so.+ expect(await rh.refreshAgentTools(conn, '/a.sock', home, [], 'repair')).toBe('current')+ expect(probes(runner)).toHaveLength(2)+ })++ describe('a host with no cksum', () => {+ let bin: string+ beforeEach(() => {+ bin = mkdtempSync(path.join(tmpdir(), 'nt-no-cksum-'))+ for (const d of ['/usr/bin', '/bin']) {+ let names: string[] = []+ try {+ names = readdirSync(d)+ } catch {+ continue+ }+ for (const n of names) {+ if (n === 'cksum') continue+ try {+ symlinkSync(path.join(d, n), path.join(bin, n))+ } catch {+ // linked from the other directory already+ }+ }+ }+ })+ afterEach(() => rmSync(bin, { recursive: true, force: true }))++ it('falls back to writing everything, as every connect did before the check existed', async () => {+ put(SHIM(), 'stale\n')+ const runner = hostRunner({ path: bin })+ const rh = new RemoteHooks(runner)+ expect(await rh.refreshAgentTools(conn, '/fixture.sock', home, [], 'connect')).toBe('refreshed')+ expect(read(SHIM())).toBe(CONTROL_SHIM_SCRIPT)+ expect(read(CTX_SKILL())).toBe(buildContextLinkSkillBody(CTX()))+ // …but the hourly re-look of a host it already brought up to date writes nothing blind.+ const writes = publishes(runner).length+ expect(await rh.refreshAgentTools(conn, '/fixture.sock', home, [], 'reuse', Date.now() + 2 * 60 * 60_000)).toBe(+ 'current'+ )+ expect(publishes(runner).length).toBe(writes)+ })+ })+})diff --git a/src/main/remote-ssh/remote-hooks.ts b/src/main/remote-ssh/remote-hooks.tsindex 1c89d0f01..52dcd3fba 100644--- a/src/main/remote-ssh/remote-hooks.ts+++ b/src/main/remote-ssh/remote-hooks.ts@@ -17,7 +17,8 @@ import { hookServer } from '../../core/agents/hook-server'import {updateRemoteSettingsFile,updateRemoteSettingsFileResult,- updateRemoteTextFile+ updateRemoteTextFile,+ type RemoteTextResult} from '../../core/agents/hooks/remote-settings-file'import { remoteAtomicWrite, runRemoteAtomicWrite, type RemoteAtomicWriteOptions } from '../remote-atomic-write'import { curlHeaderConfigLine } from '../../core/agents/hook-curl-config-sh'@@ -46,19 +47,35 @@ import {import { upsertHookTrustEntriesInContent, type CodexTrustEntry } from '../../core/agents/hooks/codex-trust'import { ensureFullscreenTui } from '../../core/agents/hooks/claude-tui'import {+ CANVAS_CONTROL_MARKERS,CONTROL_SHIM_SCRIPT,buildCanvasControlInstructions,buildCanvasSkillBody,+ frameCanvasControlBlock,mergeCanvasControlBlock} from '../../core/canvas-control-core'import {CONTEXT_SHIM_SCRIPT,+ LINKED_CONTEXT_MARKERS,buildContextLinkSkillBody,buildLinkedContextInstructions,+ frameInstructionsBlock,mergeInstructionsBlock} from '../../core/context-link-core'+import { isSafeAccountId } from '../../core/claude-accounts-core'+import { formatCksum, posixCksum } from '../../core/remote-ssh/posix-cksum'import { posixQuote, type SshConnection } from '../../shared/ssh'import { describeTunnelProbe } from './tunnel-repair'+import {+ agentToolsCheckCommand,+ agentToolsCheckDue,+ parseAgentToolsReport,+ recordAgentToolsCheck,+ type AgentToolsHostState,+ type AgentToolsReport,+ type AgentToolsTrigger,+ type ProbeEntry+} from './agent-tools-freshness'/*** Every install step in this file fails OPEN for the connect — a host that cannot take a hook must@@ -116,10 +133,115 @@ const AGENT_TARGETS: { agentId: string; config: string; events: readonly Managed{ agentId: 'gemini', config: '.gemini/settings.json', events: GEMINI_HOOK_EVENTS }]+/** Where the host's instruction files live — one marker block per feature in each. */+type InstructionTarget = 'codex' | 'gemini' | 'copilot' | 'opencode'+const CANVAS_TARGETS: readonly InstructionTarget[] = ['codex', 'gemini', 'copilot', 'opencode']+const CONTEXT_TARGETS: readonly InstructionTarget[] = ['codex', 'gemini', 'opencode']++/**+ * One thing the agent tools put on a host, as DATA. The installers write these and the freshness+ * check (`refreshAgentTools`) probes these — one list, so the check can never judge a file the+ * installer does not write, or at a path the installer does not use.+ *+ * `group` is the unit that fails together: a shim that did not land stops the rest of its group+ * (a skill pointing at a missing shim is worse than no skill), and `label` is what the warning+ * names.+ */+type AgentToolArtifact = { group: string; label: string } & (+ | { kind: 'file'; path: string; body: string; mode?: '755'; gateDir?: string }+ | {+ kind: 'block'+ target: InstructionTarget+ block: string+ /** The exact bytes the merge places from the start marker through the end marker. */+ framed: string+ markers: { start: string; end: string }+ merge: (existing: string, block: string) => string+ }+)++export type AgentToolsOutcome = 'current' | 'refreshed' | 'skipped' | 'failed'++const canvasShimPath = (home: string) => `${home}/.nodeterm/nodeterm.sh`+const contextShimPath = (home: string) => `${home}/.nodeterm/context.sh`+const skillFilePath = (configDir: string, name: string) => `${configDir}/skills/${name}/SKILL.md`+const accountConfigDir = (home: string, accountId: string) => `${home}/.nodeterm/claude-accounts/${accountId}`++function canvasControlArtifacts(home: string): AgentToolArtifact[] {+ const shim = canvasShimPath(home)+ const block = buildCanvasControlInstructions(shim)+ const g = { group: 'canvas', label: 'canvas control' }+ return [+ { ...g, kind: 'file', path: shim, body: CONTROL_SHIM_SCRIPT, mode: '755' },+ { ...g, kind: 'file', path: skillFilePath(`${home}/.claude`, 'manage-nodeterm-canvas'), body: buildCanvasSkillBody(shim) },+ ...CANVAS_TARGETS.map((target): AgentToolArtifact => ({+ ...g,+ kind: 'block',+ target,+ block,+ framed: frameCanvasControlBlock(block),+ markers: CANVAS_CONTROL_MARKERS,+ merge: mergeCanvasControlBlock+ }))+ ]+}++function contextLinkArtifacts(home: string): AgentToolArtifact[] {+ const shim = contextShimPath(home)+ const block = buildLinkedContextInstructions(shim)+ const g = { group: 'context', label: 'context link' }+ return [+ { ...g, kind: 'file', path: shim, body: CONTEXT_SHIM_SCRIPT, mode: '755' },+ { ...g, kind: 'file', path: skillFilePath(`${home}/.claude`, 'get-linked-context'), body: buildContextLinkSkillBody(shim) },+ ...CONTEXT_TARGETS.map((target): AgentToolArtifact => ({+ ...g,+ kind: 'block',+ target,+ block,+ framed: frameInstructionsBlock(block),+ markers: LINKED_CONTEXT_MARKERS,+ merge: mergeInstructionsBlock+ }))+ ]+}++/** A managed account's two skills. Gated on the account dir ALREADY existing on the host: the+ * refresh keeps an account's skills current, it never recreates the dir of an account the host+ * no longer has. (Creating it is `remoteAccountAdd`'s job.) */+function accountSkillArtifacts(home: string, accountId: string): AgentToolArtifact[] {+ const dir = accountConfigDir(home, accountId)+ const g = { group: `account:${accountId}`, label: 'a managed-account skill' }+ return [+ { ...g, kind: 'file', path: skillFilePath(dir, 'manage-nodeterm-canvas'), body: buildCanvasSkillBody(canvasShimPath(home)), gateDir: dir },+ { ...g, kind: 'file', path: skillFilePath(dir, 'get-linked-context'), body: buildContextLinkSkillBody(contextShimPath(home)), gateDir: dir }+ ]+}++/** Where `resolveCopilotHome` would put copilot's instructions, from the host's raw `$COPILOT_HOME`+ * (the installer's validator: a value it refuses means `~/.copilot`, never the refused value). */+function copilotHomeFromReported(reported: string, home: string): string {+ const trimmed = reported.trim()+ const stripped = trimmed.replace(/\/+$/, '') || '/'+ return isSafeRemoteCopilotHome(trimmed) ? stripped : `${home}/.copilot`+}++/** What a human reads in a log line about one artifact. */+function describeArtifact(a: AgentToolArtifact): string {+ return a.kind === 'file' ? a.path : `the ${a.target} instructions file (${a.label} block)`+}+export class RemoteHooks {// Remember the absolute sock path + hook port used at setup per project so teardown cancels// the exact `-R` spec (teardown does not re-resolve $HOME).private specs = new Map<string, { sock: string; port: number }>()+ /** Per HOST (user, host, port, remote $HOME — several projects share one host's files): what the+ * last agent-tools check confirmed, and the backoff after failed ones. See agent-tools-freshness. */+ private agentToolsState = new Map<string, AgentToolsHostState>()+ /** One check per host at a time; a caller arriving mid-check shares it. */+ private agentToolsInFlight = new Map<string, Promise<AgentToolsOutcome>>()+ /** The expected bytes are fixed for an app build + home + account set, and the reuse branch asks+ * every 45 s per project — do not rebuild ~150 KB of skill text and its checksums each time. */+ private agentToolsPlans = new Map<string, { plan: AgentToolArtifact[]; expected: string[]; setId: string }>()constructor(private r: RemoteRunner) {}@@ -609,9 +731,7 @@ export class RemoteHooks {const { stdout } = await this.r.run(childArgs(conn, controlPath, 'printf %s "${COPILOT_HOME:-}"'))- const reported = stdout.trim()- const stripped = reported.replace(/\/+$/, '') || '/'- return isSafeRemoteCopilotHome(reported) ? stripped : `${home}/.copilot`+ return copilotHomeFromReported(stdout, home)}/**@@ -679,40 +799,12 @@ export class RemoteHooks {* instead of telling the user canvas control is unavailable. Fail-open per step otherwise.*/async installCanvasControl(conn: SshConnection, controlPath: string, remoteHome: string): Promise<void> {- try {- const shim = `${remoteHome}/.nodeterm/nodeterm.sh`- await this.writeRemoteShim(conn, controlPath, shim, CONTROL_SHIM_SCRIPT)- await this.writeRemoteSkill(- conn,- controlPath,- `${remoteHome}/.claude`,- 'manage-nodeterm-canvas',- buildCanvasSkillBody(shim)- )- // codex / gemini / opencode have no skill system — same marker-delimited instruction block- // the desktop merges into their global instruction files. The opencode path is expanded by- // the REMOTE shell (it is XDG-respecting and the local value says nothing about the host).- const block = buildCanvasControlInstructions(shim)- // codex/gemini are plain quoted literals; opencode must stay shell-expandable and so- // carries a prelude that binds the untrusted $HOME to a variable (see the helper).- const targets: { pathExpr: string; prelude?: string }[] = [- { pathExpr: posixQuote(`${remoteHome}/.codex/AGENTS.md`) },- { pathExpr: posixQuote(`${remoteHome}/.gemini/GEMINI.md`) },- {- pathExpr: posixQuote(- `${await this.resolveCopilotHome(conn, controlPath, remoteHome)}/copilot-instructions.md`- )- },- openCodeInstructionsTarget(remoteHome)- ]- for (const t of targets) {- await this.mergeRemoteInstructions(conn, controlPath, t.pathExpr, block, mergeCanvasControlBlock, t.prelude)- }- } catch (e) {- // Fail-open for the connect, never silent: a shim that did not land is an agent whose canvas- // calls fail, and this line is the only place that says why.- warnNotInstalled('canvas control', e)- }+ // codex / gemini / copilot / opencode have no skill system — they get the same marker-delimited+ // instruction block the desktop merges into their global instruction files. The copilot home is+ // the HOST's, resolved only when that block is reached.+ await this.applyAgentTools(conn, controlPath, remoteHome, canvasControlArtifacts(remoteHome), () =>+ this.resolveCopilotHome(conn, controlPath, remoteHome)+ )}/**@@ -753,30 +845,9 @@ export class RemoteHooks {* verified tunnel; fail-open per step.*/async installContextLink(conn: SshConnection, controlPath: string, remoteHome: string): Promise<void> {- try {- const shim = `${remoteHome}/.nodeterm/context.sh`- await this.writeRemoteShim(conn, controlPath, shim, CONTEXT_SHIM_SCRIPT)- await this.writeRemoteSkill(- conn,- controlPath,- `${remoteHome}/.claude`,- 'get-linked-context',- buildContextLinkSkillBody(shim)- )- const block = buildLinkedContextInstructions(shim)- // codex/gemini are plain quoted literals; opencode must stay shell-expandable and so- // carries a prelude that binds the untrusted $HOME to a variable (see the helper).- const targets: { pathExpr: string; prelude?: string }[] = [- { pathExpr: posixQuote(`${remoteHome}/.codex/AGENTS.md`) },- { pathExpr: posixQuote(`${remoteHome}/.gemini/GEMINI.md`) },- openCodeInstructionsTarget(remoteHome)- ]- for (const t of targets) {- await this.mergeRemoteInstructions(conn, controlPath, t.pathExpr, block, mergeInstructionsBlock, t.prelude)- }- } catch (e) {- warnNotInstalled('context link', e)- }+ await this.applyAgentTools(conn, controlPath, remoteHome, contextLinkArtifacts(remoteHome), () =>+ this.resolveCopilotHome(conn, controlPath, remoteHome)+ )}/** The context-link skill for a REMOTE managed-account config dir (see the canvas twin). */@@ -817,7 +888,207 @@ export class RemoteHooks {name: string,body: string): Promise<void> {- await this.writeOwnedFile(conn, controlPath, `${configDir}/skills/${name}/SKILL.md`, body)+ await this.writeOwnedFile(conn, controlPath, skillFilePath(configDir, name), body)+ }++ /**+ * Write (or merge) a list of agent-tool artifacts, in order, one group at a time.+ *+ * Fail-open for the connect, never silent: a failed owned-file write THROWS and ends its group+ * (the steps after it depend on the file) with a warning naming the group; a failed instruction+ * merge is logged by the transaction and the group carries on. Returns whether everything landed.+ * `copilotHome` is asked at most once, and only when a copilot block is reached.+ */+ private async applyAgentTools(+ conn: SshConnection,+ controlPath: string,+ remoteHome: string,+ artifacts: readonly AgentToolArtifact[],+ copilotHome: () => Promise<string>+ ): Promise<boolean> {+ let copilot: Promise<string> | undefined+ const groups = new Map<string, AgentToolArtifact[]>()+ for (const a of artifacts) {+ const members = groups.get(a.group)+ if (members) members.push(a)+ else groups.set(a.group, [a])+ }+ let ok = true+ for (const members of groups.values()) {+ try {+ for (const a of members) {+ if (a.kind === 'file') {+ await this.writeOwnedFile(conn, controlPath, a.path, a.body, a.mode ? { mode: a.mode } : {})+ continue+ }+ const target =+ a.target === 'copilot'+ ? { pathExpr: posixQuote(`${await (copilot ??= copilotHome())}/copilot-instructions.md`) }+ : this.instructionTarget(remoteHome, a.target)+ const r = await this.mergeRemoteInstructions(conn, controlPath, target.pathExpr, a.block, a.merge, target.prelude)+ if (r === 'failed') ok = false+ }+ } catch (e) {+ ok = false+ warnNotInstalled(members[0].label, e)+ }+ }+ return ok+ }++ /** The instruction files whose path does not depend on host state we have to ask for. codex and+ * gemini are plain quoted literals; opencode must stay shell-expandable (XDG) and so carries a+ * prelude binding the untrusted $HOME to a variable (see `openCodeInstructionsTarget`). */+ private instructionTarget(+ remoteHome: string,+ target: Exclude<InstructionTarget, 'copilot'>+ ): { pathExpr: string; prelude?: string } {+ if (target === 'codex') return { pathExpr: posixQuote(`${remoteHome}/.codex/AGENTS.md`) }+ if (target === 'gemini') return { pathExpr: posixQuote(`${remoteHome}/.gemini/GEMINI.md`) }+ return openCodeInstructionsTarget(remoteHome)+ }++ /**+ * Bring an SSH host's agent tools — both shims, both skills (system and every managed account+ * pinned to this host), and our blocks in the instruction files — up to what THIS build writes,+ * rewriting ONLY what differs.+ *+ * One probe checksums everything the host holds (see agent-tools-freshness.ts for the stamp and+ * the cadence); a current host costs that one round trip and no write. A file we cannot read is+ * never written over, and a host with one is not called confirmed, so the reuse branch keeps+ * looking (on the tunnel-repair backoff). A host with no `cksum` falls back to writing everything,+ * which is what every connect did before this check existed. Never throws.+ */+ async refreshAgentTools(+ conn: SshConnection,+ controlPath: string,+ remoteHome: string,+ accountIds: readonly string[],+ trigger: AgentToolsTrigger,+ now = Date.now()+ ): Promise<AgentToolsOutcome> {+ try {+ // settings.json is hand-editable: an id that could leave the accounts root is dropped here,+ // before it is spliced into any path.+ const accounts = [...new Set(accountIds.filter(isSafeAccountId))].sort()+ const key = `${conn.user}@${conn.host}:${conn.port ?? 22}\0${remoteHome}`+ const inFlight = this.agentToolsInFlight.get(key)+ if (inFlight) return await inFlight+ const planned = this.agentToolsPlan(remoteHome, accounts)+ if (!agentToolsCheckDue(this.agentToolsState.get(key), planned.setId, now, trigger)) return 'skipped'+ const attempt = this.checkAgentTools(conn, controlPath, remoteHome, planned, trigger, key, now)+ this.agentToolsInFlight.set(key, attempt)+ try {+ return await attempt+ } finally {+ this.agentToolsInFlight.delete(key)+ }+ } catch (e) {+ warnNotInstalled('an agent-tools refresh', e)+ return 'failed'+ }+ }++ private agentToolsPlan(+ remoteHome: string,+ accounts: readonly string[]+ ): { plan: AgentToolArtifact[]; expected: string[]; setId: string } {+ const cacheKey = [remoteHome, ...accounts].join('\0')+ const cached = this.agentToolsPlans.get(cacheKey)+ if (cached) return cached+ const plan = [+ ...canvasControlArtifacts(remoteHome),+ ...contextLinkArtifacts(remoteHome),+ ...accounts.flatMap((id) => accountSkillArtifacts(remoteHome, id))+ ]+ const expected = plan.map((a) => formatCksum(posixCksum(Buffer.from(a.kind === 'file' ? a.body : a.framed, 'utf8'))))+ const setId = createHash('sha256')+ .update(JSON.stringify(plan.map((a, i) => [a.kind === 'file' ? a.path : `${a.group}:${a.target}`, expected[i]])))+ .digest('hex')+ if (this.agentToolsPlans.size >= 16) this.agentToolsPlans.clear()+ const planned = { plan, expected, setId }+ this.agentToolsPlans.set(cacheKey, planned)+ return planned+ }++ private async checkAgentTools(+ conn: SshConnection,+ controlPath: string,+ remoteHome: string,+ planned: { plan: AgentToolArtifact[]; expected: string[]; setId: string },+ trigger: AgentToolsTrigger,+ key: string,+ now: number+ ): Promise<AgentToolsOutcome> {+ const { plan, expected, setId } = planned+ const host = `${conn.user}@${conn.host}`+ const done = (ok: boolean, outcome: AgentToolsOutcome): AgentToolsOutcome => {+ this.agentToolsState.set(key, recordAgentToolsCheck(this.agentToolsState.get(key), setId, ok, now))+ return outcome+ }+ const entries = plan.map((a) => this.probeEntry(remoteHome, a))+ const command = agentToolsCheckCommand(openCodeInstructionsTarget(remoteHome).prelude, entries, 'COPILOT_HOME')+ let report: AgentToolsReport | null = null+ try {+ const r = await this.r.run(childArgs(conn, controlPath, command))+ report = r.code === 0 ? parseAgentToolsReport(r.stdout, entries.length) : null+ // A report we cannot read is not evidence that anything is stale: change nothing.+ if (!report) console.warn(`[remote-hooks] could not check the agent tools on ${host} (exit ${r.code}); will look again`)+ } catch (e) {+ console.warn(`[remote-hooks] could not check the agent tools on ${host}: ${e instanceof Error ? e.message : String(e)}`)+ }+ if (!report) return done(false, 'failed')+ const copilotHome = copilotHomeFromReported(report.env, remoteHome)++ if (report.kind === 'no-cksum') {+ // Nothing was probed. On a connect or repair, write everything we used to write on every+ // connect (never the gated account skills: we cannot see whether their dirs exist). On the+ // hourly re-look of a host this run already wrote, write nothing blind.+ if (trigger === 'reuse' && this.agentToolsState.get(key)?.verified?.setId === setId) return done(true, 'current')+ const system = plan.filter((a) => !(a.kind === 'file' && a.gateDir))+ const ok = await this.applyAgentTools(conn, controlPath, remoteHome, system, async () => copilotHome)+ return done(ok, ok ? 'refreshed' : 'failed')+ }++ // The probe read copilot's file at the host's raw `$COPILOT_HOME`; the installer refuses an+ // unsafe value and writes under ~/.copilot instead. Trust the probe only when the two agree.+ const copilotProbeTrusted = report.env === '' || isSafeRemoteCopilotHome(report.env)+ const stale: AgentToolArtifact[] = []+ const unreadable: AgentToolArtifact[] = []+ plan.forEach((a, i) => {+ const status = report.statuses[i]+ if (status.state === 'unreadable') unreadable.push(a)+ else if (status.state === 'no-gate') return+ else if (status.state === 'missing' || formatCksum(status.sum) !== expected[i]) stale.push(a)+ else if (a.kind === 'block' && a.target === 'copilot' && !copilotProbeTrusted) stale.push(a)+ })+ if (unreadable.length) {+ console.warn(+ `[remote-hooks] left ${unreadable.length} agent tool file(s) on ${host} untouched because they cannot be ` ++ `read (not a readable regular file): ${unreadable.map(describeArtifact).join(', ')}`+ )+ }+ if (!stale.length) return done(!unreadable.length, unreadable.length ? 'failed' : 'current')+ const ok = await this.applyAgentTools(conn, controlPath, remoteHome, stale, async () => copilotHome)+ console.info(+ `[remote-hooks] ${host}: ${ok ? 'rewrote' : 'tried to rewrite'} ${stale.length} out-of-date agent tool file(s): ` ++ stale.map(describeArtifact).join(', ')+ )+ const settled = ok && !unreadable.length+ return done(settled, settled ? 'refreshed' : 'failed')+ }++ /** How the probe looks at one artifact — at the SAME path the writer uses (copilot aside: the+ * probe reads the host's own `$COPILOT_HOME`, which `checkAgentTools` reconciles). */+ private probeEntry(remoteHome: string, a: AgentToolArtifact): ProbeEntry {+ if (a.kind === 'file') {+ return { kind: 'file', pathExpr: posixQuote(a.path), ...(a.gateDir ? { gateDirExpr: posixQuote(a.gateDir) } : {}) }+ }+ const pathExpr =+ a.target === 'copilot'+ ? '"${COPILOT_HOME:-$NT_H/.copilot}/copilot-instructions.md"'+ : this.instructionTarget(remoteHome, a.target).pathExpr+ return { kind: 'block', pathExpr, start: a.markers.start, end: a.markers.end }}/**@@ -863,13 +1134,13 @@ export class RemoteHooks {block: string,merge: (existing: string, block: string) => string,prelude = ''- ): Promise<void> {+ ): Promise<RemoteTextResult> {// These are the USER's instruction files (often a dotfile symlink), so they get the same// guarded transaction as settings.json: the link and the mode are kept, and nothing is// published unless exactly the merged body arrived and the file still holds what we read. The// old `cat … || true` then `cat >` read an UNREADABLE file as empty and replaced the user's// text with our block alone. Never throws; a failure is logged and leaves the file as it was.- await updateRemoteTextFile(+ return updateRemoteTextFile({ pathExpr, prelude, label: pathExpr },(cmd, stdin) => this.r.run(childArgs(conn, controlPath, cmd), stdin),(before) => {diff --git a/src/main/remote-ssh/remote-write-truncation.test.ts b/src/main/remote-ssh/remote-write-truncation.test.tsindex 61878555e..e335237f1 100644--- a/src/main/remote-ssh/remote-write-truncation.test.ts+++ b/src/main/remote-ssh/remote-write-truncation.test.ts@@ -398,10 +398,31 @@ describe.skipIf(process.platform === 'win32')('canvas control and context link sexpect(missing).toEqual([])})+ // The connect path now goes through the freshness check, which writes the same artifacts through+ // the same applier, group by group — the same property, for the chain that actually runs.+ it('the freshness check leaves BOTH blocks in every shared file (8 fresh hosts)', { timeout: 60_000 }, async () => {+ const shared = ['.codex/AGENTS.md', '.gemini/GEMINI.md', '.config/opencode/AGENTS.md']+ const missing: string[] = []+ for (let i = 0; i < 8; i++) {+ const h = mkdtempSync(path.join(tmpdir(), 'nt-rw-fresh-'))+ try {+ await new RemoteHooks(asyncHostRunner(h)).refreshAgentTools(conn, '/fixture.sock', h, [], 'connect')+ for (const f of shared) {+ const text = readFileSync(path.join(h, f), 'utf8')+ if (!text.includes('nodeterm:manage-canvas:start')) missing.push(`${i}:${f}:canvas`)+ if (!text.includes('nodeterm:get-linked-context:start')) missing.push(`${i}:${f}:context`)+ }+ } finally {+ rmSync(h, { recursive: true, force: true })+ }+ }+ expect(missing).toEqual([])+ })+it('the connect path runs them as one chain, never side by side', () => {const src = readFileSync(path.join(__dirname, 'ssh-project.ts'), 'utf8').replace(/\r\n/g, '\n')const code = src.split('\n').filter((l) => !/^\s*(\/\/|\*)/.test(l)).join('\n')- expect(code).toContain('this.remoteHooks.installAgentTools(')- expect(code).not.toMatch(/void this\.remoteHooks\.install(CanvasControl|ContextLink)\(/)+ expect(code).toContain('this.remoteHooks.refreshAgentTools(')+ expect(code).not.toMatch(/this\.remoteHooks\.install(CanvasControl|ContextLink|AgentTools)\(/)})})diff --git a/src/main/remote-ssh/ssh-project.test.ts b/src/main/remote-ssh/ssh-project.test.tsindex a2ab07ffe..e354287fc 100644--- a/src/main/remote-ssh/ssh-project.test.ts+++ b/src/main/remote-ssh/ssh-project.test.ts@@ -6,6 +6,7 @@ import { afterEach, describe, expect, it, vi } from 'vitest'import { SshProjectManager, lastSshErrorLine } from './ssh-project'import { AskpassServer } from './ssh-askpass'import { AppSshAgent } from './ssh-agent'+import { RemoteHooks } from './remote-hooks'import { controlPathFor } from '../../core/remote-ssh/control-master'import { remoteCodexSocket } from '../../core/codex-accounts-core'import type { SshConnection } from '@shared/ssh'@@ -1611,6 +1612,95 @@ describe('SshProjectManager', () => {})})+ // --- the host's agent tools (shims, skills, instruction blocks) --------------------------------+ //+ // They used to be written only by the establish path, blind, and never looked at again: a+ // tunnel repaired later on the reuse branch never got them, a fire-and-forget install that+ // failed was never retried, and a managed account's skill was written only when the account was+ // added. These pin WHO asks for the check and with which trigger; the check itself (one probe,+ // rewrite only what differs, the cadence) is pinned in agent-tools-refresh.test.ts.+ describe('agent tools on the host', () => {+ afterEach(() => {+ vi.restoreAllMocks()+ })++ function agentToolsMgr(opts: { httpCode?: () => string; leftoverSocket?: boolean; accounts?: string[] } = {}) {+ const refresh = vi.spyOn(RemoteHooks.prototype, 'refreshAgentTools').mockResolvedValue('current')+ const install = vi.spyOn(RemoteHooks.prototype, 'installAgentTools')+ vi.spyOn(fs, 'mkdir').mockResolvedValue(undefined as never)+ if (opts.leftoverSocket) vi.spyOn(fs, 'stat').mockResolvedValue({ isSocket: () => true } as never)+ else vi.spyOn(fs, 'stat').mockRejectedValue(Object.assign(new Error('ENOENT'), { code: 'ENOENT' }))+ const spawnMaster = vi.fn(() => ({ kill: vi.fn(), on: vi.fn() }))+ const hostKeys: string[] = []+ const run = vi.fn(async (args: string[]) => {+ const j = args.join(' ')+ if (j.includes('$HOME')) return { code: 0, stdout: '/home/u' }+ if (j.includes('%{http_code}')) return { code: 0, stdout: opts.httpCode?.() ?? '204' }+ return { code: 0, stdout: '' }+ })+ const mgr = new SshProjectManager({+ userDataDir: '/ud',+ spawnMaster,+ run,+ runScp: vi.fn(async () => ({ code: 0 })),+ getHook: () => ({ port: 1, token: 't', version: '1' }),+ onStatus: vi.fn(),+ claudeAccountIdsForHost: (hostKey: string) => {+ hostKeys.push(hostKey)+ return opts.accounts ?? []+ }+ })+ return { mgr, refresh, install, spawnMaster, hostKeys }+ }+ const triggers = (refresh: { mock: { calls: unknown[][] } }) => refresh.mock.calls.map((c) => c[4])++ it('a genuine establish CHECKS the host — with this host\'s managed accounts — instead of rewriting it blind', async () => {+ const { mgr, refresh, install, hostKeys } = agentToolsMgr({ accounts: ['acc-1', 'acc-2'] })+ await mgr.connect('p1', conn, '/remote/cwd')+ expect(refresh).toHaveBeenCalledTimes(1)+ expect(refresh).toHaveBeenCalledWith(conn, controlPathFor('p1'), '/home/u', ['acc-1', 'acc-2'], 'connect')+ expect(hostKeys).toEqual(['u@h'])+ expect(install).not.toHaveBeenCalled()+ })++ it('the first connect after an app restart adopts the surviving master AND checks the host', async () => {+ // The trigger an update actually takes: `conns` is in memory, so a relaunch never lands on the+ // reuse branch — it adopts the ControlPersist orphan on the establish path. This pins that+ // the check runs there too, so an update's new docs reach the host on its first connect.+ const { mgr, refresh, spawnMaster } = agentToolsMgr({ leftoverSocket: true })+ await mgr.connect('p1', conn, '/remote/cwd')+ expect(spawnMaster).not.toHaveBeenCalled() // adopted+ expect(triggers(refresh)).toEqual(['connect'])+ })++ it('the reuse branch asks too (the check decides whether that costs anything)', async () => {+ const { mgr, refresh } = agentToolsMgr()+ await mgr.connect('p1', conn, '/remote/cwd')+ await mgr.connect('p1', conn, '/remote/cwd')+ expect(triggers(refresh)).toEqual(['connect', 'reuse'])+ })++ it('a tunnel repaired on the reuse branch gets its agent tools — it never did before', async () => {+ // An establish whose tunnel failed verification installs nothing (a skill pointing at a dead+ // socket is worse than none); the watchdog's later repair used to rebuild the tunnel and stop+ // there, leaving the host with no shim, or another build's, for the rest of the run.+ let dead = true+ const { mgr, refresh } = agentToolsMgr({ httpCode: () => (dead ? '000' : '204') })+ await mgr.connect('p1', conn, '/remote/cwd')+ expect(refresh).not.toHaveBeenCalled()+ dead = false+ await mgr.connect('p1', conn, '/remote/cwd')+ expect(triggers(refresh)).toEqual(['repair'])+ })++ it('a reuse whose tunnel is still dead asks nothing', async () => {+ const { mgr, refresh } = agentToolsMgr({ httpCode: () => '000' })+ await mgr.connect('p1', conn, '/remote/cwd')+ await mgr.connect('p1', conn, '/remote/cwd')+ expect(refresh).not.toHaveBeenCalled()+ })+ })+// --- concurrent connect for one project ---------------------------------------------------//// Four callers can fire at once (watchdog revalidateAll, powerMonitor resume, the renderer'sdiff --git a/src/main/remote-ssh/ssh-project.ts b/src/main/remote-ssh/ssh-project.tsindex 644f48005..34167f7dd 100644--- a/src/main/remote-ssh/ssh-project.ts+++ b/src/main/remote-ssh/ssh-project.ts@@ -54,6 +54,7 @@ import {import { SshChildGate } from '../../core/remote-ssh/ssh-child-gate'import { claudeVersionProbeCommand, parseClaudeVersionProbe } from '../../core/remote-ssh/claude-version-probe'import { RemoteHooks } from './remote-hooks'+import type { AgentToolsTrigger } from './agent-tools-freshness'import {recordTunnelRepair,shouldAttemptTunnelRepair,@@ -185,6 +186,11 @@ interface Runners {/** Mints this instance's per-node token, or null when there is no node-auth secret at all* (legacy everywhere). Resolved per pass so one connect's tokens all come from one secret. */nodeTokenMinter?: () => ((nodeId: string) => string) | null+ /** The managed Claude accounts pinned to this host (`sshHostKey`), whose config dirs on the host+ * carry their own copies of the canvas/context skills. Read per check, so an account added or+ * removed mid-run is picked up. Absent ⇒ no account dirs are checked (their skills are then+ * only ever written when the account is added). */+ claudeAccountIdsForHost?: (hostKey: string) => string[]}/** Backoff after a FAILED remote claude probe (no markers = claude not found on that attempt).@@ -515,6 +521,11 @@ export class SshProjectManager {this.tunnelRepair.delete(projectId)this.tunnelProbeFailures.delete(projectId)this.hookTunnelHealth(projectId, true)+ // Free once this run has confirmed the host (the check's own cadence); otherwise this is+ // where a host the connect-time check could not confirm gets looked at again.+ if (existing.remoteHome && existing.hookEndpointPath) {+ this.refreshAgentTools(existing.conn, existing.controlPath, existing.remoteHome, 'reuse')+ }return}const failures = (this.tunnelProbeFailures.get(projectId) ?? 0) + 1@@ -543,6 +554,12 @@ export class SshProjectManager {existing.hookEndpointPath = res.endpointPaththis.tunnelProbeFailures.delete(projectId)this.hookTunnelHealth(projectId, true)+ // The agent tools are gated on a verified tunnel, so a host whose tunnel failed at connect+ // never got them; and a tunnel that died may have died with a master another desktop+ // rebuilt. Look now.+ if (existing.remoteHome) {+ this.refreshAgentTools(existing.conn, existing.controlPath, existing.remoteHome, 'repair')+ }// Same contract as the establish path: hook events lost while the tunnel was down are gone// for good, so the working agents need a resync. Fire-and-forget behind a catch — a repair// job must never surface to the user as a dead SSH project.@@ -556,6 +573,27 @@ export class SshProjectManager {}}+ /**+ * Bring the host's canvas/context shims, skills (system + this host's managed accounts) and+ * instruction blocks up to this build — rewriting only what differs (RemoteHooks.refreshAgentTools+ * owns the probe and the cadence). Fire-and-forget on every caller: it is several remote round+ * trips at most, pure best-effort, and must never delay or fail a connect.+ */+ private refreshAgentTools(+ conn: SshConnection,+ controlPath: string,+ remoteHome: string,+ trigger: AgentToolsTrigger+ ): void {+ let accounts: string[] = []+ try {+ accounts = this.r.claudeAccountIdsForHost?.(sshHostKey(conn)) ?? []+ } catch {+ // a settings read that throws costs the account dirs this check, nothing else+ }+ void this.remoteHooks.refreshAgentTools(conn, controlPath, remoteHome, accounts, trigger).catch(() => {})+ }+startWatchdog(intervalMs = MASTER_WATCHDOG_MS): void {if (this.watchdog) returnthis.watchdog = setInterval(() => {@@ -980,9 +1018,12 @@ export class SshProjectManager {// canvas control as unavailable. Not awaited: it is several remote round-trips of pure// best-effort setup, and holding the connect on them would delay every terminal.if (remoteHome && hookEndpointPath) {- // ONE chain, not two: both merge into the same instruction files, and two writers racing- // on one file cannot both publish (see RemoteHooks.installAgentTools).- void this.remoteHooks.installAgentTools(conn, controlPath, remoteHome)+ // ONE chain, not two: canvas control and context link merge into the same instruction+ // files, and two writers racing on one file cannot both publish (see+ // RemoteHooks.installAgentTools) — the check applies them group by group, in order. It+ // writes only what differs from this build; a master just came up, so it always looks,+ // and an app update's new docs reach the host here, on the first connect after the relaunch.+ this.refreshAgentTools(conn, controlPath, remoteHome, 'connect')// Per-node tokens for every node of this project (the endpoint file written just above// is what tells the host's hook script where to find them, which is also why this is// gated on `hookEndpointPath`: a token nothing can be pointed at is a wasted round-trip).@@ -2694,7 +2735,10 @@ export function initSshProject(codexRelaySource?: () => Promise<string>,/** Current `settings.tmuxLeadPaneWidth` for the remote tmux conf (issue #119). Injected by* main/index.ts because the settings store lives there; absent ⇒ 0 ⇒ pre-feature conf. */- leadPaneWidth?: () => number+ leadPaneWidth?: () => number,+ /** The managed Claude accounts pinned to a host (see Runners.claudeAccountIdsForHost). Injected+ * for the same reason: the settings store lives in main/index.ts. */+ claudeAccountIdsForHost?: (hostKey: string) => string[]): SshProjectManager {const ssh = sshBin()const scp = scpBin()@@ -2822,6 +2866,7 @@ export function initSshProject(getHook: () => ({ port: hookServer.getPort(), token: hookServer.getToken(), version: hookServer.getVersion() }),codexRelaySource,leadPaneWidth,+ claudeAccountIdsForHost,// Per-node identity for REMOTE nodes. Both come from the same module the local materialiser// uses, so one canvas cannot be judged by two different rules depending on where it runs.nodeIdsForProject: (projectId) => nodeIdsForCanvas(projectId),