Node-based terminal manager for AI coding agents — tmux-backed terminals and parallel agent sessions as draggable nodes on an infinite pan/zoom canvas. macOS, Linux, and a browser Server Edition.
TypeScript adhdagent-orchestrationai-agentscanvasclaude-codecodexcoding-agentsdeveloper-toolselectrongeminilinuxmacosmultiplexeropencodeparallel-agentsterminalterminal-emulatorterminal-multiplexertmuxworkspace-manager
feat(integrations): ask before writing agent config; skills replace AGENTS.md blocks
review652b156cd116
diff --git a/CLAUDE.md b/CLAUDE.mdindex 41a2ea385..b6ace3a76 100644--- a/CLAUDE.md+++ b/CLAUDE.md@@ -2765,6 +2765,32 @@ else, and its context links must keep classifying across restarts).`launchCmd`/`args`/`env` in the mirror** — they carry API keys and the file lands on every SSHhost. `binariesFor` resolves a BLANK launch command with a *builtin* `baseAgent` to the base'sbinaries (what `resolveAgentConfig` actually launches).+- **Agent-integration consent (#744)** — `core/agent-integrations.ts` (booted by BOTH shells) is the+ ONE writer of user-owned agent config; consent is `settings.agentIntegrations`+ (`@shared/agent-integrations`, sanitized on every read). Per agent: **enabled** = hook + both skills+ in the agent's own skills dir + strip older builds' AGENTS.md/GEMINI.md blocks (they were 17 KB of+ codex's 32 KiB `project_doc_max_bytes`); **declined** = remove exactly what we wrote (hooks by exact+ command, skills by exact-content receipt in `<userData>/integration-receipts.json` — a user-edited+ file is KEPT and listed in Settings, bounded at 20 — legacy blocks, our hook scripts);+ **undecided** = nothing either way. Server `installHooks: false` is a hard veto. Rules a refactor+ must not undo:+ - **Grandfathering is decided at boot from OUR files only** (non-empty `~/.nodeterm/agent-hooks/`+ or the userData shims), before `settingsStore.registerIpc()` and before any install: an existing+ install gets every agent + `hostDefault` enabled and a one-time notice; a new install gets NO+ record and a banner (Enable all / Choose… / Not now — "Not now" declines all, so it asks once).+ - **No caller reaches an installer by omission.** `installManagedAgentHooks(agents)` takes a+ REQUIRED set; `RemoteHooks` takes a REQUIRED plan (`NO_REMOTE_INTEGRATION` = fail-closed);+ account add/link asks `currentIntegrationLifecycle()` and writes nothing when none is registered.+ `agent-integrations-wiring.test.ts` pins every call site of the global installers.+ - **SSH consent is per HOST (`sshHostKey`, never identity file / port / args).** A host installs an+ agent only when the host AND the agent are enabled; an unanswered host is not touched at all+ (no clean-up, no ssh); removals run on connect and when the plan changes+ (`SshProjectManager.onIntegrationConsentChanged`). A removal never creates a missing config+ file (`stripRemoteSettingsFile`).+ - **`$CLAUDE_CONFIG_DIR` decides the system Claude dir** (`claudeSystemConfigDir`), never a+ hardcoded `~/.claude`; a decline also cleans the legacy `~/.claude` when they differ.+ - The fullscreen-TUI write is part of the claude integration and follows its consent.+ Measurements, the device checklist and the open product question: `docs/agent-integration-consent.md`.- **Hook installers** — `src/core/agents/hooks/` holds per-agent hook services + an installerregistry `MANAGED_HOOK_INSTALLERS`. `managed-script.ts` builds the POSIX hook script thatPOSTs to the server (env-gated: a no-op in the user's normal terminals, active only in@@ -2830,7 +2856,9 @@ 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`,+- **An SSH host's agent tools are CHECKED, not assumed** (since #744 the plan holds only what the+ host's consent installs — shims + skills, no instruction blocks; an unanswered host is skipped)+ (`RemoteHooks.refreshAgentTools`,`main/remote-ssh/agent-tools-freshness.ts`). The canvas/context shims, both SKILL.md files and ourblocks in the codex/gemini/copilot/opencode instruction files used to be written only by theestablish path, blind, and never looked at again, so a host could keep another build's text for@@ -3781,14 +3809,14 @@ command-bearing opens; this does not add a human-confirm dialog or change mobileescaping sh can be trusted with — `parseControlBody` reads both this and the JSON dialect) tothe hook server's `/control/<verb>` routes; `Accept: text/plain` makes the server render thereply (sh has no JSON parser). Env-gated on `NODETERM_CANVAS_CONTROL` (set by- `buildPtyEnv`/`remoteHookEnvArgs` per `canControlCanvas`). Discovery: claude gets a- `skills/manage-nodeterm-canvas/SKILL.md` (system `~/.claude` + each managed account dir);- codex/gemini/opencode plus Copilot's `copilot-instructions.md` get a marker block- (`<!-- nodeterm:manage-canvas:start/end -->`); **grok needs- no installer at all** — it scans `~/.claude/skills` by default for Claude compat, so membership alone- (which sets `NODETERM_CANVAS_CONTROL`) is the whole wiring. That premise rests on grok's shipped- docs and is **unverified** (`grok inspect --json` never run); if it does not hold, grok takes the- marker-block route instead — see docs/grok-agent.md.+ `buildPtyEnv`/`remoteHookEnvArgs` per `canControlCanvas`). Discovery (since #744): EVERY+ consented agent gets `skills/manage-nodeterm-canvas/SKILL.md` in its OWN skills dir — claude's+ config dir (+ each local managed/linked account dir), `$CODEX_HOME/skills`, `~/.gemini/skills`,+ `$GROK_HOME/skills`, `$COPILOT_HOME/skills`, opencode's `<config>/skills`; on an SSH host claude's+ dir and `~/.agents/skills` (read by codex, gemini, opencode, grok — measured — and copilot,+ documented). The marker blocks (`<!-- nodeterm:manage-canvas:start/end -->`) in AGENTS.md /+ GEMINI.md / copilot-instructions.md are no longer written and an older build's copy is STRIPPED;+ see **Agent-integration consent** under Agent support.**Server creator ownership (2026-08 incident hardening):** enabled Server control accepts onlyverified node identity. `HeadlessNodeFactory` records which source node opened each new node in aprocess-local ledger; link/group/rename/color/sticky-update, message delivery, and close validate@@ -3854,7 +3882,8 @@ command-bearing opens; this does not add a human-confirm dialog or change mobile**Keep the agent-facing text in sync with behaviour, in the SAME PR.** The verb help agentsactually read is generated by `buildCanvasSkillBody` (the SKILL.md, rewritten into every configdir by `installCanvasSkillInto` on launch) and `buildCanvasControlInstructions` (the- codex/gemini/copilot/opencode marker block) — both in `canvas-control-core.ts`. When you add or+ codex/gemini/copilot/opencode marker block — NOT INSTALLED since #744, its parity tests are what+ keep it; every agent now reads the skill) — both in `canvas-control-core.ts`. When you add orrename a verb, change a flag, or change what an outcome MEANS (e.g. PR 7 turned a busy target's`targetBusy` refusal into a deliver-on-idle queue), update those two functions in the same change,or the docs describe a product that no longer exists and an orchestrating agent acts on the stale@@ -4891,10 +4920,10 @@ command-bearing opens; this does not add a human-confirm dialog or change mobilethe local locators for remote nodes (they'd resolve a stranger's local transcript). ServerEdition IS wired (`src/server/context-link.ts` calls `initContextLink(ptyManager, {})`) butpasses no remote deps → **local-only**, which is the complete answer there: that shell runs ON the- host whose transcripts and tmux it reads, and SSH projects are a desktop-only concept. Discovery is per-agent: claude installs a- `get-linked-context` skill; codex/gemini get an idempotent marker block- (`<!-- nodeterm:get-linked-context:start/end -->`) merged into `~/.codex/AGENTS.md` /- `~/.gemini/GEMINI.md`. On connect an idle-gated one-line note is injected into each endpoint+ host whose transcripts and tmux it reads, and SSH projects are a desktop-only concept. Discovery is the `get-linked-context` skill in each consented+ context-link-capable agent's own skills dir (since #744; the old marker block+ `<!-- nodeterm:get-linked-context:start/end -->` in AGENTS.md / GEMINI.md is stripped — see+ **Agent-integration consent**). On connect an idle-gated one-line note is injected into each endpoint(claude → skill pointer; codex/gemini → inline CLI command via `contextLink.info()`).(Replaced the earlier MCP-based bridge.)**One-way links (issue #852):** a context bridge may carry `reader` (`BridgeLink.reader`, the ONEdiff --git a/CONTRIBUTING.md b/CONTRIBUTING.mdindex 2aff2f74f..9fab8fed1 100644--- a/CONTRIBUTING.md+++ b/CONTRIBUTING.md@@ -1082,6 +1082,16 @@ Grok billing diagnostics must keep HTTP codes and safe failure categories per bi## User-owned agent settings+**Nothing writes into an agent's global config except `src/core/agent-integrations.ts`** (issue+#744). Hooks, skills and anything else under `~/.claude`, `~/.codex`, `~/.gemini`, `~/.grok`,+`~/.copilot`, opencode's config dir, `~/.agents` — locally or on an SSH host — are installed only+for an agent the user ENABLED in `settings.agentIntegrations`, removed when they decline, and left+alone while they have not answered. Do not add a direct call to an installer; add the artifact to+the lifecycle (local) or to the `RemoteHooks` artifact plan (SSH), and give it a removal that+deletes only what nodeterm wrote. `src/core/agent-integrations-wiring.test.ts` fails on a new call+site. Do not merge text into `AGENTS.md` / `GEMINI.md` — agents get skills (progressive disclosure)+instead; the old blocks crowded codex's 32 KiB instruction budget.+Claude/Gemini settings must go through the guarded transactions in`src/core/agents/hooks/{settings-file,remote-settings-file}.ts`. Confirmed absence or a successfully read empty/whitespace file may start from `{}`;malformed, non-object and unreadable files must survive unchanged.@@ -1145,6 +1155,13 @@ parser refuses unknown options on purpose). Test from macOS/Linux with `NODETERM## Testing+**Run the suite with a scratch `HOME`, and know what else points at your real config.** The worker+setup (`test/setup/agent-env.ts`) strips `CLAUDE_CONFIG_DIR`, `CODEX_HOME`, `GROK_HOME`,+`COPILOT_HOME`, `GEMINI_CLI_HOME`, `XDG_CONFIG_HOME` and the `NODETERM_*` session variables, because+a suite run from inside a nodeterm agent session inherits them and code under test resolves the+LIVE agent config dir from them — a scratch `HOME` alone did not stop a test from rewriting the+running session's own skills and hooks (#744). A test that needs one sets it itself.+**Screenshot paste has one route per gesture.** On macOS, Cmd+V saves/uploads a file andpastes its path; Ctrl+V belongs to the foreground program. A node's configured agent is notproof of foreground clipboard-image support. Keep shell/SSH/Server file routing and capturediff --git a/docs/agent-integration-consent.md b/docs/agent-integration-consent.mdnew file mode 100644index 000000000..0f6fbc846--- /dev/null+++ b/docs/agent-integration-consent.md@@ -0,0 +1,104 @@+# Agent-integration consent++Issue #744 (redo of the superseded draft #900). nodeterm used to write into every agent CLI's+user-owned global configuration on every launch, and onto every SSH host at connect, with no+recorded decision and no way to say no: status hooks in `~/.claude/settings.json`,+`~/.gemini/settings.json`, `~/.codex/hooks.json` + `config.toml` trust, grok/copilot/opencode/+antigravity hook files, and ~17 KB of canvas-control + context-link instructions merged into+`~/.codex/AGENTS.md`, `~/.gemini/GEMINI.md`, copilot's and opencode's instruction files. The codex+blocks alone took 17,102 bytes of codex's 32 KiB `project_doc_max_bytes` budget, crowding out the+user's own repository instructions.++## The model++`settings.agentIntegrations` (`src/shared/agent-integrations.ts`), hand-editable and sanitized on+every read:++| field | meaning |+|---|---|+| `agents[<id>]` | `enabled` / `declined` per agent on THIS machine; absent = never asked |+| `hosts[<user@host>]` | per SSH host; keyed on `sshHostKey` only, so editing the identity file, port or extra args keeps the answer |+| `hostDefault` | the answer for a host with no entry; set to `enabled` only by grandfathering |+| `origin` | `grandfathered` (an install from before this feature) or `asked` |+| `noticeDismissed` | the grandfathered install's one-time notice was dismissed |++Per agent the lifecycle (`src/core/agent-integrations.ts`, booted by BOTH shells) does:++- **enabled**: install/refresh the status hook and the two skills (canvas control, context link) in+ that agent's OWN skills dir; strip the legacy marker blocks older builds merged into its global+ instruction file.+- **declined**: remove exactly what nodeterm wrote — hook entries by exact command match (a user's+ own hooks survive), skill files by exact-content receipt (a file the user edited is kept and+ listed in Settings), the legacy blocks, our hook scripts.+- **undecided**: nothing, in either direction.++The Server Edition's `installHooks: false` is a hard veto that outranks every choice.++## Default for existing vs new installs (product decision — confirm)++- **Existing installs are grandfathered as enabled.** Evidence is our own files only: a non-empty+ `~/.nodeterm/agent-hooks/` or the canvas/context shims under userData. The record is written at+ boot, before the renderer loads settings and before any install, with every agent enabled and+ `hostDefault: enabled`, so nobody's badges or canvas control stop on upgrade. A one-time+ dismissible notice says integrations are now a choice and links to Settings → Agents.+- **New installs are asked once**, by a banner (Enable all / Choose… / Not now). Until answered+ nothing global is written; terminals work, but agents have no status badges, notifications,+ session names, context meter, subagent cards, canvas control or linked-node reads. "Not now"+ records a decline for every agent, so it is asked once.+- **SSH hosts**: a host with no answer gets nothing (and nothing is removed). When the active+ project's host is connected and unanswered, a banner asks (Allow on this host / Not on this host).+ A host installs an agent only when BOTH the host and that agent are enabled.++## Where the skills go (measured 2026-10-03)++Local, each agent's own dir (so a per-agent decline is precise):++| agent | dir | measured with |+|---|---|---|+| claude | `$CLAUDE_CONFIG_DIR` or `~/.claude` `/skills`, plus every local managed/linked account dir | (existing) |+| codex 0.156.1 | `$CODEX_HOME/skills` (+ managed codex homes) | `codex debug prompt-input` |+| gemini 0.62.0 | `$GEMINI_CLI_HOME`/`~` `/.gemini/skills` | `gemini skills list --all` |+| opencode 1.18.33 | `<opencode config>/skills` | `opencode debug skill` |+| copilot 1.0.89 | `$COPILOT_HOME`/`~/.copilot` `/skills` | `copilot skill --help` (documented) |+| grok 1.0.44 | `$GROK_HOME`/`~/.grok` `/skills` | `grok inspect --json` |++On an SSH host: claude's `~/.claude/skills` (and remote account dirs), and **`~/.agents/skills`**+for everyone else — codex, gemini, opencode and grok were all measured reading it, copilot documents+it — because one env-independent dir is what a host we cannot introspect cheaply needs.++Copilot has no context link, so it gets the canvas skill only (as before). Antigravity has neither.++## What is deliberately not done++- `config.toml` codex trust entries are left on decline: a trust entry for a hook that no longer+ exists is inert, and the file is the user's.+- The `buildCanvasControlInstructions` / `buildLinkedContextInstructions` builders are no longer+ installed anywhere; their parity tests still pin them and should move to the skill bodies+ (follow-up).+- A file that held ONLY our block is removed locally; on an SSH host (or behind a symlink) it is+ left with one newline, because the guarded transaction never publishes an empty file.+- An SSH host's removal only recognises skill files this build would write, or whose bytes were+ recorded when this machine wrote them (receipts in `<userData>/integration-receipts.json`); an+ older build's copy on a host this machine never refreshed is kept and reported.++## Surfaces++Desktop: full. Server Edition: the same lifecycle and Settings rows (`installHooks: false` vetoes),+no SSH hosts. Relay tabs: the consent is the host's (settings are host-only); the relay tab's own+Settings describe THIS machine. Mobile: N/A for v1 — the phone reads status the host's hooks+produce; a phone-side explanation of "integration off" is an iOS follow-up.++## Device checklist (not runnable here)++1. macOS desktop upgrade from 0.4.x: grandfathered notice appears once; badges keep working.+2. Fresh macOS install: banner appears before any `~/.claude` write (`ls ~/.claude` unchanged);+ Enable all → badges and canvas control work.+3. Decline claude on macOS: `~/.claude/settings.json` keeps the user's own hooks, our entries gone;+ an edited `SKILL.md` is listed in Settings.+4. Codex on macOS reads the canvas skill from `~/.codex/skills` (ask it to list nodes).+5. SSH host (Linux, codex + gemini + claude installed): Allow → `~/.agents/skills` and+ `~/.claude/skills` populated, no `AGENTS.md` block; Not on this host → cleaned.+6. SSH host with an old 17 KB `AGENTS.md` block: stripped on the first connect after upgrade.+7. Copilot on a real login: `copilot skill list` shows manage-nodeterm-canvas from `~/.copilot/skills`+ (local) and `~/.agents/skills` (SSH) — only the help text was measured here.+8. Windows desktop: hooks for a consented codex (`codex-hook.cmd`) and the skills dirs resolve.diff --git a/src/core/agent-integrations-ipc.ts b/src/core/agent-integrations-ipc.tsnew file mode 100644index 000000000..82ff5821c--- /dev/null+++ b/src/core/agent-integrations-ipc.ts@@ -0,0 +1,16 @@+// IPC for the agent-integration consent lifecycle (issue #744). The choice itself rides+// settings.json (`settings:save`, then `SettingsStore.onChange` → `onSettingsChanged`); this only+// reports what the last reconcile did, for Settings → Agents. Registered by BOTH shells.+import { IPC } from '../shared/ipc'+import type { AgentIntegrationsStatus } from '../shared/agent-integrations'+import { platform } from './platform'+import type { IntegrationLifecycle } from './agent-integrations'++export function registerIntegrationIpc(lc: IntegrationLifecycle): void {+ platform().handle(IPC.integrationsStatus, (): AgentIntegrationsStatus => {+ const r = lc.lastReport()+ return r+ ? { enabled: r.enabled, declined: r.declined, retained: r.retained, vetoed: r.vetoed }+ : { enabled: [], declined: [], retained: [], vetoed: false }+ })+}diff --git a/src/core/agent-integrations-wiring.test.ts b/src/core/agent-integrations-wiring.test.tsnew file mode 100644index 000000000..b0362ef20--- /dev/null+++ b/src/core/agent-integrations-wiring.test.ts@@ -0,0 +1,67 @@+// Issue #744, at source level: a consent gate is only as good as the ONE path through it. A new call+// to a global installer that skips the lifecycle compiles fine and writes into the user's agent+// config without asking — exactly the bug this feature closes — so the call sites are pinned.+import { describe, expect, it } from 'vitest'+import { readdirSync, readFileSync, statSync } from 'fs'+import path from 'path'++const SRC = path.join(__dirname, '..')+const code = (rel: string): string =>+ readFileSync(path.join(SRC, rel), 'utf8')+ .replace(/\r\n/g, '\n')+ .split('\n')+ .filter((l) => !/^\s*(\/\/|\*|\/\*)/.test(l))+ .join('\n')++function walk(dir: string, out: string[] = []): string[] {+ for (const n of readdirSync(dir)) {+ const p = path.join(dir, n)+ if (statSync(p).isDirectory()) walk(p, out)+ else if (/\.tsx?$/.test(n) && !/\.test\.tsx?$/.test(n) && !n.includes('test-plan')) out.push(path.relative(SRC, p))+ }+ return out+}++describe('agent-integration consent wiring (#744)', () => {+ it.each(['main/index.ts', 'server/index.ts'])('%s boots the lifecycle, registers its IPC and grandfathers at boot', (shell) => {+ const src = code(shell)+ expect(src).toContain('createIntegrationLifecycle(')+ expect(src).toContain('registerIntegrationLifecycle(')+ expect(src).toContain('registerIntegrationIpc(')+ expect(src).toContain('resolveIntegrationConsentAtBoot(')+ expect(src).toMatch(/settingsStore\.onChange\(\(s\) => integrations\.onSettingsChanged\(s\)\)/)+ })++ it('the Server Edition passes installHooks:false as a hard veto', () => {+ expect(code('server/index.ts')).toMatch(/veto: config\.installHooks === false/)+ })++ it('the desktop re-applies the SSH plan when the consent changes', () => {+ expect(code('main/index.ts')).toContain('sshProjectManager?.onIntegrationConsentChanged()')+ expect(code('main/index.ts')).toContain('integrationsForHost:')+ })++ it('no file outside the lifecycle calls a global installer', () => {+ const allowed: Record<string, readonly string[]> = {+ 'installManagedAgentHooks(': ['core/agent-integrations.ts', 'core/agents/hooks/index.ts'],+ 'installClaudeHooksInto(': ['core/agent-integrations.ts', 'core/agents/hooks/claude.ts'],+ 'ensureClaudeFullscreenTuiInto(': ['core/agent-integrations.ts', 'core/agents/hooks/claude.ts'],+ 'installCanvasSkillInto(': [],+ 'mergeInstructionFile(': ['core/agents/hooks/settings-file.ts', 'core/integration-files.ts']+ }+ const offenders: string[] = []+ for (const rel of walk(SRC)) {+ const src = code(rel)+ for (const [needle, ok] of Object.entries(allowed)) {+ if (src.includes(needle) && !ok.includes(rel.split(path.sep).join('/'))) offenders.push(`${rel}: ${needle}`)+ }+ }+ expect(offenders).toEqual([])+ })++ it('RemoteHooks cannot be built without a consent plan', () => {+ expect(code('main/remote-ssh/remote-hooks.ts')).toMatch(+ /constructor\(\s*private r: RemoteRunner,\s*private integrations: \(conn: SshConnection\) => RemoteIntegrationPlan/+ )+ })+})diff --git a/src/core/agent-integrations.test.ts b/src/core/agent-integrations.test.tsnew file mode 100644index 000000000..f914e30d3--- /dev/null+++ b/src/core/agent-integrations.test.ts@@ -0,0 +1,300 @@+// The agent-integration consent lifecycle (issue #744), against a real scratch $HOME.+//+// Each case is a promise to the user about their OWN files: nothing is written for an agent they+// did not enable, a decline removes exactly what nodeterm wrote (a file they edited is kept and+// reported), and every agent that has canvas control / context link still discovers them.+import { afterEach, beforeEach, describe, expect, it } from 'vitest'+import { existsSync, mkdirSync, mkdtempSync, readFileSync, readdirSync, rmSync, writeFileSync } from 'fs'+import os from 'os'+import path from 'path'+import { initPlatform, resetPlatformForTests } from './platform'+import { fakePlatform } from './platform-fake'+import { DEFAULT_SETTINGS, type Settings } from '../shared/types'+import {+ CANVAS_SKILL,+ CONTEXT_SKILL,+ createIntegrationLifecycle,+ detectExistingIntegrations,+ resolveIntegrationConsentAtBoot+} from './agent-integrations'+import { buildCanvasSkillBody, frameCanvasControlBlock } from './canvas-control-core'+import { buildContextLinkSkillBody, frameInstructionsBlock } from './context-link-core'+import { MAX_RETAINED } from './integration-files'+import { registerClaudeAccountsSource, resetClaudeAccountsSourceForTests } from './claude-config-dir'+import { accountConfigDir } from './claude-accounts-core'+import type { ClaudeAccount } from '../shared/types'++const ENV_KEYS = ['HOME', 'USERPROFILE', 'CLAUDE_CONFIG_DIR', 'CODEX_HOME', 'GROK_HOME', 'COPILOT_HOME', 'XDG_CONFIG_HOME', 'GEMINI_CLI_HOME']+let saved: Record<string, string | undefined>+let home: string+let userData: string++beforeEach(() => {+ saved = Object.fromEntries(ENV_KEYS.map((k) => [k, process.env[k]]))+ for (const k of ENV_KEYS) delete process.env[k]+ home = mkdtempSync(path.join(os.tmpdir(), 'nt-integrations-'))+ userData = path.join(home, 'userData')+ mkdirSync(userData, { recursive: true })+ process.env.HOME = home+ process.env.USERPROFILE = home+ initPlatform(fakePlatform({ userDataDir: userData }))+})+afterEach(() => {+ for (const k of ENV_KEYS) {+ if (saved[k] === undefined) delete process.env[k]+ else process.env[k] = saved[k]+ }+ resetPlatformForTests()+ resetClaudeAccountsSourceForTests()+ rmSync(home, { recursive: true, force: true })+})++const SHIMS = () => ({+ canvas: path.join(userData, 'canvas-control', 'nodeterm.sh'),+ context: path.join(userData, 'context-links', 'context.sh')+})+const withAgents = (agents: Record<string, 'enabled' | 'declined'>, extra: Partial<Settings> = {}): Settings => ({+ ...DEFAULT_SETTINGS,+ ...extra,+ agentIntegrations: { agents, origin: 'asked' }+})+const read = (p: string) => readFileSync(p, 'utf8')+const put = (p: string, body: string) => {+ mkdirSync(path.dirname(p), { recursive: true })+ writeFileSync(p, body)+}+/** Every file under home, relative — minus our own userData. */+function filesUnder(root: string): string[] {+ const out: string[] = []+ const walk = (d: string) => {+ for (const n of readdirSync(d, { withFileTypes: true })) {+ const p = path.join(d, n.name)+ if (p === userData) continue+ if (n.isDirectory()) walk(p)+ else out.push(path.relative(root, p))+ }+ }+ walk(root)+ return out.sort()+}++function lifecycle(settings: () => Settings, opts: { veto?: boolean; realHooks?: boolean } = {}) {+ const hookCalls: { install: string[][]; remove: string[][] } = { install: [], remove: [] }+ const lc = createIntegrationLifecycle({+ settings,+ userDataDir: () => userData,+ shims: SHIMS,+ veto: opts.veto,+ ...(opts.realHooks+ ? {}+ : {+ installHooks: (a) => void hookCalls.install.push([...a].sort()),+ removeHooks: (a) => void hookCalls.remove.push([...a].sort())+ })+ })+ return { lc, hookCalls }+}++describe('nothing global is written without consent', () => {+ it('a new install that has not answered writes NOTHING and removes nothing', () => {+ put(path.join(home, '.codex', 'AGENTS.md'), '# mine\n')+ const { lc, hookCalls } = lifecycle(() => DEFAULT_SETTINGS, { realHooks: true })+ lc.reconcile()+ expect(filesUnder(home)).toEqual(['.codex/AGENTS.md'])+ expect(read(path.join(home, '.codex', 'AGENTS.md'))).toBe('# mine\n')+ expect(hookCalls.install).toEqual([])+ })++ it('only the enabled agents get hooks — the undecided ones are left alone', () => {+ const { lc } = lifecycle(() => withAgents({ claude: 'enabled' }), { realHooks: true })+ lc.reconcile()+ expect(JSON.stringify(JSON.parse(read(path.join(home, '.claude', 'settings.json'))))).toContain('agent-hooks/claude.sh')+ expect(existsSync(path.join(home, '.gemini'))).toBe(false)+ expect(existsSync(path.join(home, '.codex'))).toBe(false)+ expect(existsSync(path.join(home, '.nodeterm', 'agent-hooks', 'claude.sh'))).toBe(true)+ expect(existsSync(path.join(home, '.nodeterm', 'agent-hooks', 'codex.sh'))).toBe(false)+ })++ it('the Server Edition veto (installHooks: false) outranks every choice', () => {+ const { lc, hookCalls } = lifecycle(() => withAgents({ claude: 'enabled', codex: 'enabled' }), { veto: true })+ expect(lc.reconcile().vetoed).toBe(true)+ expect(filesUnder(home)).toEqual([])+ expect(hookCalls.install).toEqual([])+ })+})++describe('discovery: every capable agent still finds canvas control and context link (no regression)', () => {+ it('each agent gets the skills in ITS OWN skills dir — and nothing in AGENTS.md / GEMINI.md', () => {+ process.env.GROK_HOME = path.join(home, 'grok-home')+ process.env.COPILOT_HOME = path.join(home, 'copilot-home')+ process.env.XDG_CONFIG_HOME = path.join(home, 'xdg')+ process.env.CODEX_HOME = path.join(home, 'codex-home')+ const all = { claude: 'enabled', codex: 'enabled', gemini: 'enabled', grok: 'enabled', copilot: 'enabled', opencode: 'enabled' } as const+ const { lc, hookCalls } = lifecycle(() => withAgents(all))+ lc.reconcile()+ const canvas = buildCanvasSkillBody(SHIMS().canvas)+ const context = buildContextLinkSkillBody(SHIMS().context)+ const dirs: Record<string, [boolean, boolean]> = {+ [path.join(home, '.claude', 'skills')]: [true, true],+ [path.join(home, 'codex-home', 'skills')]: [true, true],+ [path.join(home, '.gemini', 'skills')]: [true, true],+ [path.join(home, 'grok-home', 'skills')]: [true, true],+ [path.join(home, 'copilot-home', 'skills')]: [true, false], // copilot: canvas control only+ [path.join(home, 'xdg', 'opencode', 'skills')]: [true, true]+ }+ for (const [dir, [hasCanvas, hasContext]] of Object.entries(dirs)) {+ const c = path.join(dir, CANVAS_SKILL, 'SKILL.md')+ const x = path.join(dir, CONTEXT_SKILL, 'SKILL.md')+ expect(existsSync(c), c).toBe(hasCanvas)+ expect(existsSync(x), x).toBe(hasContext)+ if (hasCanvas) expect(read(c)).toBe(canvas)+ if (hasContext) expect(read(x)).toBe(context)+ }+ for (const f of ['.codex/AGENTS.md', '.gemini/GEMINI.md', 'codex-home/AGENTS.md', 'copilot-home/copilot-instructions.md', 'xdg/opencode/AGENTS.md']) {+ expect(existsSync(path.join(home, f)), f).toBe(false)+ }+ expect(hookCalls.install).toEqual([['claude', 'codex', 'copilot', 'gemini', 'grok', 'opencode']])+ })++ it('respects $CLAUDE_CONFIG_DIR — never a hardcoded ~/.claude', () => {+ process.env.CLAUDE_CONFIG_DIR = path.join(home, 'claude-elsewhere')+ const { lc } = lifecycle(() => withAgents({ claude: 'enabled' }), { realHooks: true })+ lc.reconcile()+ expect(existsSync(path.join(home, 'claude-elsewhere', 'skills', CANVAS_SKILL, 'SKILL.md'))).toBe(true)+ expect(read(path.join(home, 'claude-elsewhere', 'settings.json'))).toContain('agent-hooks/claude.sh')+ expect(existsSync(path.join(home, '.claude'))).toBe(false)+ })++ it('every local managed and linked Claude account gets BOTH skills and the hook', () => {+ const linked = path.join(home, '.claude-2')+ mkdirSync(linked, { recursive: true })+ const accounts = [+ { id: 'acc-1', label: 'a', createdAt: 0 },+ { id: 'linked', label: 'l', configDir: linked, createdAt: 0 },+ { id: 'remote', label: 'r', host: 'u@h', createdAt: 0 },+ { id: 'pending', label: 'p', pending: true, createdAt: 0 }+ ] as ClaudeAccount[]+ registerClaudeAccountsSource(() => accounts)+ const { lc } = lifecycle(() => withAgents({ claude: 'enabled' }, { claudeAccounts: accounts }), { realHooks: true })+ lc.reconcile()+ for (const dir of [accountConfigDir(userData, 'acc-1'), linked]) {+ expect(existsSync(path.join(dir, 'skills', CANVAS_SKILL, 'SKILL.md')), dir).toBe(true)+ expect(existsSync(path.join(dir, 'skills', CONTEXT_SKILL, 'SKILL.md')), dir).toBe(true)+ expect(read(path.join(dir, 'settings.json'))).toContain('agent-hooks/claude.sh')+ }+ expect(existsSync(accountConfigDir(userData, 'remote'))).toBe(false)+ expect(existsSync(accountConfigDir(userData, 'pending'))).toBe(false)+ })+})++describe('upgrade: the legacy instruction blocks go, the user text stays', () => {+ it("strips both blocks (the ~17 KB that crowded codex's AGENTS.md) and nothing else", () => {+ const user = '# my repo rules\n\nAlways run the tests.\n'+ const legacy =+ `${user}\n${frameCanvasControlBlock('X'.repeat(12_000))}\n\n${frameInstructionsBlock('Y'.repeat(5_000))}\n`+ put(path.join(home, '.codex', 'AGENTS.md'), legacy)+ put(path.join(home, '.gemini', 'GEMINI.md'), `${frameInstructionsBlock('Z')}\n`)+ const { lc } = lifecycle(() => withAgents({ codex: 'enabled', gemini: 'declined' }))+ lc.reconcile()+ expect(read(path.join(home, '.codex', 'AGENTS.md'))).toBe(user)+ // A file that held NOTHING but our block was ours: it goes, rather than staying behind empty.+ expect(existsSync(path.join(home, '.gemini', 'GEMINI.md'))).toBe(false)+ })++ it('an undecided agent\'s instruction file is not touched at all', () => {+ const legacy = `# mine\n\n${frameCanvasControlBlock('X')}\n`+ put(path.join(home, '.gemini', 'GEMINI.md'), legacy)+ const { lc } = lifecycle(() => withAgents({ codex: 'enabled' }))+ lc.reconcile()+ expect(read(path.join(home, '.gemini', 'GEMINI.md'))).toBe(legacy)+ })+})++describe('decline: remove exactly what we wrote', () => {+ it("removes our hook (keeping the user's own), our skills and our script; keeps a skill the user edited and reports it", () => {+ let settings = withAgents({ claude: 'enabled', codex: 'enabled' })+ const { lc } = lifecycle(() => settings, { realHooks: true })+ lc.reconcile()+ // The user adds their own hook beside ours and edits one of our skills.+ const settingsFile = path.join(home, '.claude', 'settings.json')+ const cfg = JSON.parse(read(settingsFile)) as { hooks: Record<string, { hooks: { type: string; command: string }[] }[]> }+ cfg.hooks.Stop.push({ hooks: [{ type: 'command', command: 'my-own-hook' }] })+ writeFileSync(settingsFile, JSON.stringify(cfg))+ const edited = path.join(home, '.claude', 'skills', CONTEXT_SKILL, 'SKILL.md')+ writeFileSync(edited, `${read(edited)}\nmy note\n`)++ settings = withAgents({ claude: 'declined', codex: 'enabled' })+ lc.onSettingsChanged(settings)+ const after = read(settingsFile)+ expect(after).not.toContain('agent-hooks/claude.sh')+ expect(after).toContain('my-own-hook')+ expect(existsSync(path.join(home, '.claude', 'skills', CANVAS_SKILL))).toBe(false)+ expect(existsSync(edited)).toBe(true)+ expect(lc.lastReport()?.retained).toEqual([edited])+ expect(existsSync(path.join(home, '.nodeterm', 'agent-hooks', 'claude.sh'))).toBe(false)+ // codex is still enabled: untouched.+ expect(existsSync(path.join(home, '.codex', 'skills', CANVAS_SKILL, 'SKILL.md'))).toBe(true)+ })++ it('never overwrites a skill the user edited while still enabled', () => {+ const { lc } = lifecycle(() => withAgents({ gemini: 'enabled' }))+ lc.reconcile()+ const f = path.join(home, '.gemini', 'skills', CANVAS_SKILL, 'SKILL.md')+ writeFileSync(f, 'my own version\n')+ lc.reconcile()+ expect(read(f)).toBe('my own version\n')+ expect(lc.lastReport()?.retained).toEqual([f])+ })++ it('the retained list is bounded', () => {+ const accounts = Array.from({ length: 30 }, (_, i) => ({ id: `acc-${i}`, label: 'x', createdAt: 0 })) as ClaudeAccount[]+ registerClaudeAccountsSource(() => accounts)+ let settings = withAgents({ claude: 'enabled' }, { claudeAccounts: accounts })+ const { lc } = lifecycle(() => settings)+ lc.reconcile()+ for (const a of accounts) {+ const f = path.join(accountConfigDir(userData, a.id), 'skills', CANVAS_SKILL, 'SKILL.md')+ writeFileSync(f, 'edited\n')+ }+ settings = withAgents({ claude: 'declined' }, { claudeAccounts: accounts })+ lc.onSettingsChanged(settings)+ expect(lc.lastReport()?.retained.length).toBe(MAX_RETAINED)+ })+})++describe('reconcile cadence', () => {+ it('re-runs only when the consent or the local account list changes', () => {+ let settings = withAgents({ codex: 'enabled' })+ const { lc, hookCalls } = lifecycle(() => settings)+ lc.reconcile()+ lc.onSettingsChanged({ ...settings, fontSize: 20 })+ expect(hookCalls.install).toHaveLength(1)+ settings = withAgents({ codex: 'enabled', gemini: 'enabled' })+ lc.onSettingsChanged(settings)+ expect(hookCalls.install).toHaveLength(2)+ })+})++describe('the existing-vs-new default', () => {+ it('an install whose own hook scripts are on disk is grandfathered as enabled — every agent and every host', () => {+ mkdirSync(path.join(home, '.nodeterm', 'agent-hooks'), { recursive: true })+ writeFileSync(path.join(home, '.nodeterm', 'agent-hooks', 'claude.sh'), '#!/bin/sh\n')+ const existing = detectExistingIntegrations(userData, home)+ expect(existing).toBe(true)+ const next = resolveIntegrationConsentAtBoot(DEFAULT_SETTINGS, existing)+ expect(next?.agentIntegrations?.origin).toBe('grandfathered')+ expect(next?.agentIntegrations?.agents?.codex).toBe('enabled')+ expect(next?.agentIntegrations?.hostDefault).toBe('enabled')+ expect(next?.agentIntegrations?.noticeDismissed).toBeUndefined()+ })++ it('a new install (nothing of ours on disk) is NOT grandfathered — it is asked', () => {+ expect(detectExistingIntegrations(userData, home)).toBe(false)+ expect(resolveIntegrationConsentAtBoot(DEFAULT_SETTINGS, false)).toBeNull()+ })++ it('an answered record is never rewritten at boot', () => {+ const answered = withAgents({ claude: 'declined' })+ expect(resolveIntegrationConsentAtBoot(answered, true)).toBeNull()+ })+})diff --git a/src/core/agent-integrations.ts b/src/core/agent-integrations.tsnew file mode 100644index 000000000..75590adae--- /dev/null+++ b/src/core/agent-integrations.ts@@ -0,0 +1,375 @@+// Agent-integration lifecycle (issue #744): the ONE place that decides what nodeterm writes into+// user-owned global agent configuration on THIS machine, shared by the desktop and the Server+// Edition. Consent is `settings.agentIntegrations` (`@shared/agent-integrations`).+//+// Per agent:+// enabled → install/refresh its status hook + its skills (canvas control, context link) in the+// agent's OWN skills dir; strip the legacy marker blocks older builds merged into its+// global instruction file (skills replaced them — they were ~17 KB in AGENTS.md).+// declined → remove exactly what we wrote: our hook entries (exact command match), our skill+// files (exact-content receipts — a file the user edited is KEPT and reported), our+// legacy blocks, and our hook script.+// undecided → nothing at all, in either direction. A new install writes nothing until asked.+//+// The Server Edition's `installHooks: false` is a hard veto that outranks every choice.+import { existsSync, readdirSync, rmSync } from 'fs'+import os from 'os'+import path from 'path'+import {+ INTEGRATION_AGENT_IDS,+ grandfatheredIntegrations,+ integrationsOf,+ localIntegrationSignature,+ type IntegrationAgentId+} from '../shared/agent-integrations'+import { canContextLink, canControlCanvas } from '../shared/agents/config'+import type { Settings } from '../shared/types'+import { installManagedAgentHooks, removeManagedAgentHooks } from './agents/hooks'+import {+ claudeSystemConfigDir,+ ensureClaudeFullscreenTuiInto,+ installClaudeHooksInto,+ removeClaudeHooksFrom+} from './agents/hooks/claude'+import { copilotHomeDir } from './agents/hooks/copilot'+import { managedHookScriptPath } from './agents/hooks/install-helper'+import { opencodeConfigDir } from './agents/hooks/opencode'+import { grokHomeDir } from './agents/grok-paths'+import { buildCanvasSkillBody } from './canvas-control-core'+import { buildContextLinkSkillBody } from './context-link-core'+import { claudeConfigDirFor } from './claude-config-dir'+import { codexHomeForAccount, systemCodexHome } from './codex-accounts-core'+import { applySkillShare } from './claude-skill-share'+import {+ ReceiptStore,+ pushRetained,+ removeOwnedFile,+ stripLegacyBlocks,+ writeOwnedFile+} from './integration-files'++export const CANVAS_SKILL = 'manage-nodeterm-canvas'+export const CONTEXT_SKILL = 'get-linked-context'++/** Where our hook scripts live; its presence is the strongest evidence of an existing install. */+export function agentHooksDir(home: string = os.homedir()): string {+ return path.join(home, '.nodeterm', 'agent-hooks')+}++/**+ * Did a build from before this feature already integrate with this machine's agents? Evidence is+ * our OWN files only (never a guess from the user's config): the managed hook scripts dir every+ * install created, or our canvas/context shims under userData. True ⇒ grandfather as enabled.+ */+export function detectExistingIntegrations(userDataDir: string, home: string = os.homedir()): boolean {+ const nonEmpty = (d: string): boolean => {+ try {+ return readdirSync(d).length > 0+ } catch {+ return false+ }+ }+ return (+ nonEmpty(agentHooksDir(home)) ||+ existsSync(path.join(userDataDir, 'canvas-control', 'nodeterm.sh')) ||+ existsSync(path.join(userDataDir, 'context-links', 'context.sh'))+ )+}++/**+ * Resolve the consent record at boot, BEFORE any install and before the renderer loads settings.+ * Returns the settings to persist when the record had to be created (grandfathering), else null.+ * A new install (no evidence) gets no record: it is asked at first launch.+ */+export function resolveIntegrationConsentAtBoot(settings: Settings, existingInstall: boolean): Settings | null {+ const s = integrationsOf(settings)+ if (s.origin || Object.keys(s.agents ?? {}).length > 0) return null+ if (!existingInstall) return null+ return { ...settings, agentIntegrations: { ...grandfatheredIntegrations(), ...s, origin: 'grandfathered' } }+}++export interface IntegrationShims {+ /** The canvas-control shim the canvas skill points at; absent = canvas control is off here+ * (Server Edition without `--canvas-control`), so no canvas skill is installed. */+ canvas?: string+ /** The context-link shim. */+ context: string+}++export interface IntegrationReport {+ enabled: IntegrationAgentId[]+ declined: IntegrationAgentId[]+ /** Files we kept because the user changed them since we wrote them (bounded). */+ retained: string[]+ vetoed: boolean+}++export interface IntegrationLifecycleDeps {+ settings: () => Settings+ userDataDir: () => string+ shims: () => IntegrationShims+ /** Server Edition `installHooks: false`: nothing global is ever written or removed. */+ veto?: boolean+ /** Test seams. */+ installHooks?: (agents: ReadonlySet<string>) => void+ removeHooks?: (agents: ReadonlySet<string>) => void+ home?: () => string+}++/** The skills dirs one agent reads, for THIS machine. Measured 2026-10-03: codex 0.156.1 reads+ * `$CODEX_HOME/skills`, gemini 0.62.0 `~/.gemini/skills` (`gemini skills list`), opencode 1.18.33+ * `<config>/skills` (`opencode debug skill`), copilot 1.0.89 `~/.copilot/skills` (`copilot skill+ * --help`), grok 1.0.44 `$GROK_HOME/skills` (binary strings), claude `<config dir>/skills`. */+export function skillRootsFor(+ agent: IntegrationAgentId,+ settings: Settings,+ userDataDir: string,+ home: string = os.homedir()+): string[] {+ switch (agent) {+ case 'claude': {+ const roots = [claudeSystemConfigDir()]+ for (const a of settings.claudeAccounts ?? []) {+ if (a.host || a.pending) continue+ try {+ roots.push(claudeConfigDirFor(a.id))+ } catch {+ /* an id outside the alphabet is skipped */+ }+ }+ return [...new Set(roots)].map((d) => path.join(d, 'skills'))+ }+ case 'codex': {+ const roots = [systemCodexHome()]+ for (const a of settings.codexAccounts ?? []) {+ if (a.host || a.pending) continue+ try {+ roots.push(codexHomeForAccount(userDataDir, a.id))+ } catch {+ /* skipped */+ }+ }+ return [...new Set(roots)].map((d) => path.join(d, 'skills'))+ }+ case 'gemini':+ return [path.join(process.env.GEMINI_CLI_HOME || home, '.gemini', 'skills')]+ case 'grok':+ return [path.join(grokHomeDir(), 'skills')]+ case 'copilot':+ return [path.join(copilotHomeDir(), 'skills')]+ case 'opencode':+ return [path.join(opencodeConfigDir(), 'skills')]+ default:+ return []+ }+}++/** The skills one agent gets, as (file name → body). */+export function skillsFor(agent: IntegrationAgentId, shims: IntegrationShims): Map<string, string> {+ const out = new Map<string, string>()+ if (shims.canvas && canControlCanvas(agent)) out.set(CANVAS_SKILL, buildCanvasSkillBody(shims.canvas))+ if (canContextLink(agent)) out.set(CONTEXT_SKILL, buildContextLinkSkillBody(shims.context))+ return out+}++/** The global instruction files older builds merged discovery blocks into, per agent. */+export function legacyInstructionFiles(agent: IntegrationAgentId, home: string = os.homedir()): string[] {+ switch (agent) {+ case 'codex':+ return [...new Set([path.join(home, '.codex', 'AGENTS.md'), path.join(systemCodexHome(), 'AGENTS.md')])]+ case 'gemini':+ return [path.join(home, '.gemini', 'GEMINI.md')]+ case 'copilot':+ return [path.join(copilotHomeDir(), 'copilot-instructions.md')]+ case 'opencode':+ return [path.join(opencodeConfigDir(), 'AGENTS.md')]+ default:+ return []+ }+}++const HOOK_SCRIPTS: Partial<Record<IntegrationAgentId, string[]>> = {+ claude: ['claude.sh'],+ codex: ['codex.sh', 'codex-hook.cmd'],+ gemini: ['gemini.sh'],+ grok: ['grok.sh'],+ copilot: ['copilot.sh'],+ antigravity: ['antigravity.sh', 'antigravity-hook.cmd']+}++export interface IntegrationLifecycle {+ /** Bring this machine to the current consent. Idempotent; never throws. */+ reconcile(): IntegrationReport+ /** Re-reconcile only when the consent (or the local account list) changed. */+ onSettingsChanged(settings: Settings): void+ /** For a managed/linked Claude account dir just added: install there if claude is enabled. */+ installIntoClaudeAccount(configDir: string): void+ /** The last report (for Settings). */+ lastReport(): IntegrationReport | null+ /** The ownership receipts (also used for skills written on SSH hosts). */+ receipts: ReceiptStore+}++function accountSignature(s: Settings): string {+ const c = (s.claudeAccounts ?? []).filter((a) => !a.host && !a.pending).map((a) => a.id)+ const x = (s.codexAccounts ?? []).filter((a) => !a.host && !a.pending).map((a) => a.id)+ return `${c.join(',')}|${x.join(',')}`+}++export function createIntegrationLifecycle(deps: IntegrationLifecycleDeps): IntegrationLifecycle {+ const receipts = new ReceiptStore(() => deps.userDataDir())+ const installHooks = deps.installHooks ?? installManagedAgentHooks+ const removeHooks = deps.removeHooks ?? removeManagedAgentHooks+ let last: IntegrationReport | null = null+ let lastSig = ''++ const reconcile = (): IntegrationReport => {+ const settings = deps.settings()+ const home = deps.home?.() ?? os.homedir()+ const s = integrationsOf(settings)+ const enabled = INTEGRATION_AGENT_IDS.filter((a) => s.agents?.[a] === 'enabled')+ const declined = INTEGRATION_AGENT_IDS.filter((a) => s.agents?.[a] === 'declined')+ const report: IntegrationReport = { enabled, declined, retained: [], vetoed: !!deps.veto }+ lastSig = `${localIntegrationSignature(settings)}|${accountSignature(settings)}`+ if (deps.veto) {+ last = report+ return report+ }+ let shims: IntegrationShims+ try {+ shims = deps.shims()+ } catch {+ shims = { context: '' }+ }+ // Hooks.+ try {+ if (enabled.length) installHooks(new Set(enabled))+ } catch (e) {+ console.warn('[integrations] hook install failed', e)+ }+ try {+ if (declined.length) removeHooks(new Set(declined))+ } catch (e) {+ console.warn('[integrations] hook removal failed', e)+ }+ // Claude accounts: every local managed/linked dir carries its own settings.json.+ for (const a of settings.claudeAccounts ?? []) {+ if (a.host || a.pending) continue+ let dir: string+ try {+ dir = claudeConfigDirFor(a.id)+ } catch {+ continue+ }+ try {+ if (enabled.includes('claude')) {+ installClaudeHooksInto(dir)+ void ensureClaudeFullscreenTuiInto(dir)+ } else if (declined.includes('claude')) {+ removeClaudeHooksFrom(dir)+ }+ } catch (e) {+ console.warn(`[integrations] claude account ${a.id} failed`, e)+ }+ // Shared system skills (issue #643) is its own explicit, per-account opt-in, independent of+ // this consent (it links INTO the account dir, never writes the user's skills).+ if (a.shareSystemSkills) void applySkillShare(dir, true)+ }+ // A $CLAUDE_CONFIG_DIR that moved the system dir leaves the legacy ~/.claude behind.+ const legacyClaude = path.join(home, '.claude')+ if (declined.includes('claude') && legacyClaude !== claudeSystemConfigDir()) {+ try {+ removeClaudeHooksFrom(legacyClaude)+ } catch {+ /* fail open */+ }+ }+ // Skills + legacy blocks.+ for (const agent of [...enabled, ...declined]) {+ const on = enabled.includes(agent)+ const skills = skillsFor(agent, shims)+ for (const root of skillRootsFor(agent, settings, deps.userDataDir(), home)) {+ for (const name of [CANVAS_SKILL, CONTEXT_SKILL]) {+ const file = path.join(root, name, 'SKILL.md')+ const body = skills.get(name)+ if (on && body !== undefined) {+ if (writeOwnedFile(receipts, file, body) === 'retained') pushRetained(report.retained, file)+ } else if (!on) {+ const known = [...skills.values()]+ if (removeOwnedFile(receipts, file, known) === 'retained') pushRetained(report.retained, file)+ }+ }+ }+ for (const f of legacyInstructionFiles(agent, home)) {+ if (stripLegacyBlocks(f) === 'failed') console.warn('[integrations] could not clean', f)+ }+ if (!on) {+ for (const script of HOOK_SCRIPTS[agent] ?? []) {+ try {+ rmSync(managedHookScriptPath(script), { force: true })+ } catch {+ /* ours, but not removable right now */+ }+ }+ }+ }+ // A declined claude also loses its skills in the legacy ~/.claude (pre-$CLAUDE_CONFIG_DIR).+ if (declined.includes('claude') && legacyClaude !== claudeSystemConfigDir()) {+ for (const name of [CANVAS_SKILL, CONTEXT_SKILL]) {+ const file = path.join(legacyClaude, 'skills', name, 'SKILL.md')+ if (removeOwnedFile(receipts, file, [...skillsFor('claude', shims).values()]) === 'retained') {+ pushRetained(report.retained, file)+ }+ }+ }+ if (report.retained.length) {+ console.warn(`[integrations] kept ${report.retained.length} file(s) you changed: ${report.retained.join(', ')}`)+ }+ last = report+ return report+ }++ const safeReconcile = (): IntegrationReport => {+ try {+ return reconcile()+ } catch (e) {+ console.warn('[integrations] reconcile failed', e)+ return last ?? { enabled: [], declined: [], retained: [], vetoed: !!deps.veto }+ }+ }++ return {+ reconcile: safeReconcile,+ onSettingsChanged(settings) {+ const sig = `${localIntegrationSignature(settings)}|${accountSignature(settings)}`+ if (sig !== lastSig) safeReconcile()+ },+ installIntoClaudeAccount(configDir) {+ if (deps.veto) return+ if (integrationsOf(deps.settings()).agents?.claude !== 'enabled') return+ try {+ installClaudeHooksInto(configDir)+ void ensureClaudeFullscreenTuiInto(configDir)+ const shims = deps.shims()+ for (const [name, body] of skillsFor('claude', shims)) {+ writeOwnedFile(receipts, path.join(configDir, 'skills', name, 'SKILL.md'), body)+ }+ } catch (e) {+ console.warn('[integrations] account install failed', configDir, e)+ }+ },+ lastReport: () => last,+ receipts+ }+}++// The lifecycle the running shell booted. Account add/link (core/claude-accounts-service.ts) asks+// it; with none registered (a test, a shell that has not booted it) NOTHING is written — the+// fail-closed direction.+let current: IntegrationLifecycle | null = null+export function registerIntegrationLifecycle(lc: IntegrationLifecycle | null): void {+ current = lc+}+export function currentIntegrationLifecycle(): IntegrationLifecycle | null {+ return current+}diff --git a/src/core/agents/hooks/claude.ts b/src/core/agents/hooks/claude.tsindex 8af35a886..3f8bc4578 100644--- a/src/core/agents/hooks/claude.ts+++ b/src/core/agents/hooks/claude.ts@@ -10,8 +10,16 @@ import { CLAUDE_HOOK_EVENTS } from '@shared/agents/hook-events'const SCRIPT_FILE_NAME = 'claude.sh'+/** The SYSTEM Claude config dir: `$CLAUDE_CONFIG_DIR` when the app's environment sets it (a+ * system node inherits that environment, so its claude reads hooks and skills from there), else+ * `~/.claude`. Never hardcode `~/.claude` (issue #744). */+export function claudeSystemConfigDir(env: NodeJS.ProcessEnv = process.env): string {+ const fromEnv = env.CLAUDE_CONFIG_DIR?.trim()+ return fromEnv && path.isAbsolute(fromEnv) ? fromEnv : path.join(homedir(), '.claude')+}+function configPath(): string {- return path.join(homedir(), '.claude', 'settings.json')+ return path.join(claudeSystemConfigDir(), 'settings.json')}export function installClaudeHooks(): void {@@ -57,3 +65,13 @@ export function removeClaudeHooks(): void {scriptFileName: SCRIPT_FILE_NAME})}++/** Remove the managed hook from a specific Claude config dir (managed/linked accounts, or the+ * legacy `~/.claude` when `$CLAUDE_CONFIG_DIR` moved the system dir). */+export function removeClaudeHooksFrom(configDir: string): void {+ removeHooksFrom({+ configPath: path.join(configDir, 'settings.json'),+ events: CLAUDE_HOOK_EVENTS,+ scriptFileName: SCRIPT_FILE_NAME+ })+}diff --git a/src/core/agents/hooks/codex.ts b/src/core/agents/hooks/codex.tsindex 820d8bea4..4a6dae70e 100644--- a/src/core/agents/hooks/codex.ts+++ b/src/core/agents/hooks/codex.ts@@ -140,6 +140,22 @@ function removeManagedFromDefinitions(defs: HookDefinition[]): HookDefinition[]})}+/** Pure: hooks.json without our managed handlers, or null when there was nothing of ours. */+export function stripCodexManagedHooks(config: HooksConfig): HooksConfig | null {+ if (!config || typeof config !== 'object' || !config.hooks || typeof config.hooks !== 'object') return null+ const next: Record<string, HookDefinition[]> = { ...config.hooks }+ let removed = false+ for (const [ev, defs] of Object.entries(next)) {+ if (!Array.isArray(defs)) continue+ const cleaned = removeManagedFromDefinitions(defs)+ if (cleaned.length === defs.length && cleaned.every((d, i) => d === defs[i])) continue+ removed = true+ if (cleaned.length === 0) delete next[ev]+ else next[ev] = cleaned+ }+ return removed ? { ...config, hooks: next } : null+}+/*** `%SystemRoot%\System32\cmd.exe`, or bare `cmd` when that cannot be spelled unquoted.*diff --git a/src/core/agents/hooks/index.test.ts b/src/core/agents/hooks/index.test.tsindex 568cf2aad..617322910 100644--- a/src/core/agents/hooks/index.test.ts+++ b/src/core/agents/hooks/index.test.ts@@ -50,7 +50,7 @@ describe('installManagedAgentHooks — the $GROK_HOME probe (§8.9)', () => {// silent regression.expect(grokHomeDir()).not.toBe(elsewhere)- installManagedAgentHooks()+ installManagedAgentHooks(new Set(['grok']))await new Promise((r) => setTimeout(r, 50))expect(grokHomeDir()).toBe(elsewhere)@@ -63,8 +63,27 @@ describe('installManagedAgentHooks — the $GROK_HOME probe (§8.9)', () => {// idea of the default instead of the code's.shellAnswer = nullconst target = grokHomeDir()- installManagedAgentHooks()+ installManagedAgentHooks(new Set(['grok']))await new Promise((r) => setTimeout(r, 20))expect(fs.existsSync(path.join(target, 'hooks', GROK_HOOK_FILE))).toBe(true)})})++describe('installManagedAgentHooks — consent (issue #744)', () => {+ it('writes ONLY the agents in the set: no claude/gemini/codex config for a grok-only consent', async () => {+ shellAnswer = null+ installManagedAgentHooks(new Set(['grok']))+ await new Promise((r) => setTimeout(r, 20))+ expect(fs.existsSync(path.join(grokHomeDir(), 'hooks', GROK_HOOK_FILE))).toBe(true)+ for (const f of ['.claude/settings.json', '.gemini/settings.json', '.codex/hooks.json']) {+ expect(fs.existsSync(path.join(home, f)), f).toBe(false)+ }+ })++ it('an empty set writes nothing at all, not even the hook scripts dir', async () => {+ shellAnswer = null+ installManagedAgentHooks(new Set())+ await new Promise((r) => setTimeout(r, 20))+ expect(fs.readdirSync(home)).toEqual([])+ })+})diff --git a/src/core/agents/hooks/index.ts b/src/core/agents/hooks/index.tsindex 254213022..a0e717ac2 100644--- a/src/core/agents/hooks/index.ts+++ b/src/core/agents/hooks/index.ts@@ -36,7 +36,12 @@ export const MANAGED_HOOK_REMOVERS: readonly HookInstaller[] = [['antigravity', () => removeAntigravityHooks()]]-export function installManagedAgentHooks(): void {+/**+ * Install (or refresh) the managed status hook for exactly the agents in `agents` — the ones the+ * user consented to (issue #744, `core/agent-integrations.ts`). REQUIRED, so no caller can reach the+ * global writes by omission.+ */+export function installManagedAgentHooks(agents: ReadonlySet<string>): void {// Ask the login shell where grok lives BEFORE writing its hook file, and re-write it if the answer// moves the target. A GUI app launched from Finder/Dock/`.desktop` never sourced the user's rc,// while the grok CLI — started by the shell inside a tmux pane — did; for a user whose only@@ -49,7 +54,7 @@ export function installManagedAgentHooks(): void {// where grok will actually look — and when it lands nowhere, `grokHomeFallbackWasSilent` records// that we fell back without evidence, which is the diagnostic this bug never had.const grokHomeAtInstall = grokHomeDir()- void ensureGrokHomeProbed().then(() => {+ if (agents.has('grok')) void ensureGrokHomeProbed().then(() => {// The diagnostic the flag exists for. Without this line `grokHomeFallbackWasSilent` promised an// explanation the user never saw, which is the very failure it was written to close.if (grokHomeFallbackWasSilent()) {@@ -68,6 +73,7 @@ export function installManagedAgentHooks(): void {}})for (const [agent, install] of MANAGED_HOOK_INSTALLERS) {+ if (!agents.has(agent)) continuetry {install()} catch (e) {@@ -78,11 +84,14 @@ export function installManagedAgentHooks(): void {// version-gated) right after its hooks land. Fire-and-forget (it awaits the memoized CLI probe)// and fail-open, so it never blocks boot — and runs on BOTH desktop and Server Edition, which// both call this at launch. Managed account dirs are ensured by their own install call sites.- void ensureClaudeFullscreenTui()+ if (agents.has('claude')) void ensureClaudeFullscreenTui()}-export function removeManagedAgentHooks(): void {+/** Remove the managed hook from the agents in `agents` (all of them when omitted — the uninstall+ * path). Exact-command matching: only OUR handler is stripped, a user's own hooks survive. */+export function removeManagedAgentHooks(agents?: ReadonlySet<string>): void {for (const [agent, remove] of MANAGED_HOOK_REMOVERS) {+ if (agents && !agents.has(agent)) continuetry {remove()} catch (e) {diff --git a/src/core/agents/hooks/install-helper.ts b/src/core/agents/hooks/install-helper.tsindex 7b414972e..d21183356 100644--- a/src/core/agents/hooks/install-helper.ts+++ b/src/core/agents/hooks/install-helper.ts@@ -331,6 +331,29 @@ export interface RemoveHooksOptions {atomicConfig?: boolean}+/** Pure: the config without OUR handler for `scriptFileName` on any of `events` (same normalized+ * match as the installer; a user's own hooks survive). Returns the input when nothing changes. */+export function stripManagedHook(+ config: HookSettings,+ scriptFileName: string,+ events: readonly ManagedHookEvent[]+): HookSettings {+ if (!config.hooks) return config+ const isOurs = managedCommandMatcher(`agent-hooks/${scriptFileName}`, false)+ let changed = false+ const hooks = { ...config.hooks }+ for (const e of events) {+ const ev = eventNameOf(e)+ if (!Array.isArray(hooks[ev])) continue+ const kept = stripManaged(hooks[ev], isOurs)+ if (kept.length === hooks[ev].length && kept.every((d, i) => d === hooks[ev][i])) continue+ changed = true+ if (kept.length === 0) delete hooks[ev]+ else hooks[ev] = kept+ }+ return changed ? { ...config, hooks } : config+}+export function removeHooksFrom(opts: RemoveHooksOptions): void {const { configPath, events, scriptFileName, atomicConfig = false } = opts// Same normalized comparison as the installer — a raw `includes` left every entry behind ondiff --git a/src/core/agents/hooks/remote-settings-file.ts b/src/core/agents/hooks/remote-settings-file.tsindex aa0a053b8..2fce87648 100644--- a/src/core/agents/hooks/remote-settings-file.ts+++ b/src/core/agents/hooks/remote-settings-file.ts@@ -143,3 +143,25 @@ export async function updateRemoteSettingsFile(): Promise<boolean> {return (await updateRemoteSettingsFileResult(file, run, update)) === 'written'}++/** Like `updateRemoteSettingsFileResult` for a REMOVAL: a missing file stays missing (never+ * created as `{}`), an unparseable one is left alone, and nothing is written when the update+ * changes nothing. */+export function stripRemoteSettingsFile(+ file: string,+ run: SettingsRunner,+ update: (config: Record<string, unknown>) => Record<string, unknown>+): Promise<RemoteTextResult> {+ return updateRemoteTextFile(file, run, (before) => {+ if (before === null || before.trim() === '') return null+ let config: Record<string, unknown>+ try {+ config = parseSettings(before)+ } catch {+ return null+ }+ const original = JSON.stringify(config)+ const updated = update(config)+ return JSON.stringify(updated) === original ? null : JSON.stringify(updated, null, 2)+ })+}diff --git a/src/core/canvas-control-core.ts b/src/core/canvas-control-core.tsindex 8432a89f3..ef54ea270 100644--- a/src/core/canvas-control-core.ts+++ b/src/core/canvas-control-core.ts@@ -816,6 +816,9 @@ export function mergeCanvasControlBlock(existing: string, block: string): string}/** The instructions body telling codex/gemini how to control the nodeterm canvas.+ * NOT INSTALLED since #744: every agent now gets the manage-nodeterm-canvas SKILL in its own+ * skills dir (core/agent-integrations.ts); older builds' copies of this block are stripped. Kept+ * only until its parity tests move to the skill body (follow-up).* Keep the verb list in sync with the skill template in canvas-control.ts. */export function buildCanvasControlInstructions(shimPath: string): string {const agentChoices = `${BUILTIN_AGENT_IDS.join('|')}|<custom-id>`@@ -1162,7 +1165,7 @@ if [ "$nt_verb" = "help" ] || [ "$nt_verb" = "--help" ] || [ "$nt_verb" = "-h" ]# word of the verb list is \`list\` — which sh then tried to RUN.echo 'Run with no verb to list the current nodes (same as \`list\`).'echo "Flags take a value: --flag value, or --flag=value when the value starts with '--'."- echo "Per-verb flags are documented in the manage-nodeterm-canvas skill / instructions block."+ echo "Per-verb flags are documented in the manage-nodeterm-canvas skill."exit 0fidiff --git a/src/core/claude-accounts-link-symlink.test.ts b/src/core/claude-accounts-link-symlink.test.tsindex 9014fd06d..3983e4c95 100644--- a/src/core/claude-accounts-link-symlink.test.ts+++ b/src/core/claude-accounts-link-symlink.test.ts@@ -31,6 +31,8 @@ import { initPlatform, resetPlatformForTests } from './platform'import { fakePlatform, type FakePlatform } from './platform-fake'import { IPC } from '../shared/ipc'import { registerClaudeAccountsIpc } from './claude-accounts-service'+import { createIntegrationLifecycle, registerIntegrationLifecycle } from './agent-integrations'+import { DEFAULT_SETTINGS } from '../shared/types'import { resetClaudeAccountsSourceForTests } from './claude-config-dir'let fake: FakePlatform@@ -57,12 +59,21 @@ beforeEach(() => {process.env.USERPROFILE = rootfake = fakePlatform({ userDataDir })initPlatform(fake)+ // The consent lifecycle decides whether an account gets the hook (#744); claude is enabled here.+ registerIntegrationLifecycle(+ createIntegrationLifecycle({+ settings: () => ({ ...DEFAULT_SETTINGS, agentIntegrations: { agents: { claude: 'enabled' }, origin: 'asked' } }),+ userDataDir: () => userDataDir,+ shims: () => ({ context: path.join(userDataDir, 'context-links', 'context.sh') })+ })+ )registerClaudeAccountsIpc()})afterEach(() => {if (realHome === undefined) delete process.env.HOMEelse process.env.HOME = realHomedelete process.env.USERPROFILE+ registerIntegrationLifecycle(null)resetPlatformForTests()resetClaudeAccountsSourceForTests()rmSync(root, { recursive: true, force: true })diff --git a/src/core/claude-accounts-service.test.ts b/src/core/claude-accounts-service.test.tsindex 922045ffd..d4a9a15df 100644--- a/src/core/claude-accounts-service.test.ts+++ b/src/core/claude-accounts-service.test.ts@@ -7,8 +7,8 @@* (canvas control is not wired there) and no SSH manager, so a ctx carrying a projectId must still* take the local path.*- * MUTATION: drop the `installSkill` call, or let `remoteFor` treat a projectId alone as remote →- * the skill case and the local-fallback case redden.+ * MUTATION: drop the consent lifecycle's `installIntoClaudeAccount` call, or let `remoteFor` treat+ * a projectId alone as remote → the install case and the local-fallback case redden.*/import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest'import { existsSync, mkdtempSync, readFileSync, rmSync, writeFileSync, mkdirSync } from 'fs'@@ -17,7 +17,8 @@ import path from 'path'import { initPlatform, resetPlatformForTests } from './platform'import { fakePlatform, type FakePlatform } from './platform-fake'import { IPC } from '../shared/ipc'-import { registerClaudeAccountsIpc, installHooksIntoLocalAccounts } from './claude-accounts-service'+import { registerClaudeAccountsIpc } from './claude-accounts-service'+import { registerIntegrationLifecycle, type IntegrationLifecycle } from './agent-integrations'import { accountConfigDir } from './claude-accounts-core'import {registerClaudeAccountsSource,@@ -29,7 +30,8 @@ import type { ClaudeAccount } from '../shared/types'// and a real write would touch the account dir this file then asserts about.const installed: string[] = []const tui: string[] = []-vi.mock('./agents/hooks/claude', () => ({+vi.mock('./agents/hooks/claude', async (importOriginal) => ({+ ...(await importOriginal<typeof import('./agents/hooks/claude')>()),installClaudeHooksInto: (dir: string) => {installed.push(dir)},@@ -87,23 +89,27 @@ describe('registerClaudeAccountsIpc — the seven channels', () => {)})- it('add() creates the config dir under userData, installs the hook and returns the id', async () => {- const skilled: string[] = []- registerClaudeAccountsIpc({ installSkill: (d) => skilled.push(d) })- const res = await call(IPC.claudeAccountsAdd)- expect(res.id).toMatch(/^[A-Za-z0-9-]+$/)- expect(res.configDir).toBe(accountConfigDir(userDataDir, res.id))- expect(existsSync(res.configDir)).toBe(true)- expect(installed).toEqual([res.configDir])- expect(skilled).toEqual([res.configDir])- expect(tui).toEqual([res.configDir])+ it('add() creates the config dir under userData, asks the consent lifecycle to install, and returns the id', async () => {+ const asked: string[] = []+ registerIntegrationLifecycle({ installIntoClaudeAccount: (d: string) => asked.push(d) } as unknown as IntegrationLifecycle)+ try {+ registerClaudeAccountsIpc()+ const res = await call(IPC.claudeAccountsAdd)+ expect(res.id).toMatch(/^[A-Za-z0-9-]+$/)+ expect(res.configDir).toBe(accountConfigDir(userDataDir, res.id))+ expect(existsSync(res.configDir)).toBe(true)+ expect(asked).toEqual([res.configDir])+ } finally {+ registerIntegrationLifecycle(null)+ }})- it('add() without an installSkill dep (the Server Edition) writes no skill', async () => {+ it('add() with no consent lifecycle registered writes NO hook, skill or TUI setting (fail-closed, #744)', async () => {registerClaudeAccountsIpc()const res = await call(IPC.claudeAccountsAdd)expect(existsSync(res.configDir)).toBe(true)- expect(installed).toEqual([res.configDir])+ expect(installed).toEqual([])+ expect(tui).toEqual([])})it('waitLogin resolves once .claude.json carries an oauthAccount email', async () => {@@ -179,45 +185,6 @@ describe('the remote leg is resolved lazily, and its absence falls back to LOCAL})})-describe('installHooksIntoLocalAccounts', () => {- it('installs into every LOCAL account dir and skips host-scoped ones', () => {- const extra: string[] = []- installHooksIntoLocalAccounts(- [{ id: 'aaa' }, { id: 'bbb', host: 'user@example' }, { id: 'ccc' }],- (d) => extra.push(d)- )- const dirs = ['aaa', 'ccc'].map((id) => accountConfigDir(userDataDir, id))- expect(installed).toEqual(dirs)- expect(extra).toEqual(dirs)- expect(tui).toEqual(dirs)- })-- it('one failing account never stops the rest (boot must not be blocked)', () => {- const warn = vi.spyOn(console, 'warn').mockImplementation(() => {})- mkdirSync(path.join(userDataDir, 'claude-accounts'), { recursive: true })- installHooksIntoLocalAccounts([{ id: 'aaa' }, { id: '../evil' }, { id: 'ccc' }])- expect(installed).toEqual(- ['aaa', 'ccc'].map((id) => accountConfigDir(userDataDir, id))- )- expect(warn).toHaveBeenCalled()- warn.mockRestore()- })-- // Issue #643. The launch sweep re-links (a skill added to ~/.claude/skills since the last run)- // and NEVER removes: ownership is inferred from a link's shape, so an OFF pass here could delete- // an identical link the user made by hand in their own linked-account dir. Removal happens only- // where the user asked for it, in `setSkillSharing`.- it('re-links shared skills for local accounts that opted in, and touches no other account', () => {- installHooksIntoLocalAccounts([- { id: 'aaa', shareSystemSkills: true },- { id: 'bbb', host: 'user@example', shareSystemSkills: true },- { id: 'ccc' },- { id: 'ddd', shareSystemSkills: false }- ])- expect(shared).toEqual([{ dir: accountConfigDir(userDataDir, 'aaa'), enabled: true }])- })-})-describe('claudeAccounts.setSkillSharing', () => {it('reconciles the account dir and reports what happened', async () => {registerClaudeAccountsIpc()@@ -259,18 +226,23 @@ describe('claudeAccounts.link', () => {})afterEach(() => rmSync(linkDir, { recursive: true, force: true }))- it('links an existing dir: id + normalized path + email, hook and TUI installed into it', async () => {+ it('links an existing dir: id + normalized path + email, and asks the consent lifecycle to install into it', async () => {writeFileSync(path.join(linkDir, '.claude.json'),JSON.stringify({ oauthAccount: { emailAddress: '[email protected]' } }))- const res = await call(IPC.claudeAccountsLink, `${linkDir}/`)- expect(res.id).toMatch(/^[A-Za-z0-9-]+$/)- expect(res.configDir).toBe(linkDir) // trailing slash normalized away- expect(res.email).toBe('[email protected]')- // The same two writes an ADDED account gets — or the linked identity reports no agent status.- expect(installed).toEqual([linkDir])- expect(tui).toEqual([linkDir])+ const asked: string[] = []+ registerIntegrationLifecycle({ installIntoClaudeAccount: (d: string) => asked.push(d) } as unknown as IntegrationLifecycle)+ try {+ const res = await call(IPC.claudeAccountsLink, `${linkDir}/`)+ expect(res.id).toMatch(/^[A-Za-z0-9-]+$/)+ expect(res.configDir).toBe(linkDir) // trailing slash normalized away+ expect(res.email).toBe('[email protected]')+ // The same install an ADDED account gets — or the linked identity reports no agent status.+ expect(asked).toEqual([linkDir])+ } finally {+ registerIntegrationLifecycle(null)+ }})it('is email: null — not a failure — when the dir is not signed in yet', async () => {@@ -376,16 +348,6 @@ describe('removing a LINKED account never deletes the directory', () => {})})-describe('installHooksIntoLocalAccounts covers linked accounts', () => {- it('installs into the linked dir, not into a managed dir that does not exist', () => {- registerClaudeAccountsSource(() => [- { id: 'linked', label: 'l', configDir: '/home/u/.claude-2', createdAt: 0 } as ClaudeAccount- ])- installHooksIntoLocalAccounts([{ id: 'linked' }, { id: 'managed' }])- expect(installed).toEqual(['/home/u/.claude-2', accountConfigDir(userDataDir, 'managed')])- })-})-// The running-node "Switch Claude account" copy. The renderer is not the boundary: core decides// which accounts are real targets, and it never copies into a pending/remote/unknown one.describe('claudeAccounts.copySession', () => {diff --git a/src/core/claude-accounts-service.ts b/src/core/claude-accounts-service.tsindex 464c6dfa5..808a3aeb6 100644--- a/src/core/claude-accounts-service.ts+++ b/src/core/claude-accounts-service.ts@@ -26,7 +26,7 @@ import {linkedClaudeConfigDirFor} from './claude-config-dir'import { applySkillShare, EMPTY_SKILL_SHARE } from './claude-skill-share'-import { installClaudeHooksInto, ensureClaudeFullscreenTuiInto } from './agents/hooks/claude'+import { currentIntegrationLifecycle } from './agent-integrations'import { findInLoginPath } from './pty-manager'import { platform } from './platform'import { copyClaudeSession, type ClaudeSessionCopyOutcome } from './claude-session-copy'@@ -70,13 +70,6 @@ export interface ClaudeAccountsRemote {}export interface ClaudeAccountsDeps {- /**- * Install the canvas-control skill into a freshly created account dir. Claude Code resolves- * skills relative to CLAUDE_CONFIG_DIR, so a managed account needs its own copy. DESKTOP ONLY:- * canvas control is not wired on the Server Edition at all (its hook server answers- * `control unavailable` by name), so there is nothing for a skill file to reach there.- */- installSkill?: (configDir: string) => void/*** Resolves the live remote legs, or undefined when SSH is not wired / not yet created. A THUNK* rather than a plain object because that is the fact the local fallback turns on: desktop@@ -131,11 +124,9 @@ export function registerClaudeAccountsIpc(deps: ClaudeAccountsDeps = {}): void {// Install the managed hook (+ the canvas skill where the shell has one) up front so the very// first session in this account already reports status (badges/notifications/subagent viz)// and can control the canvas (Claude resolves both relative to CLAUDE_CONFIG_DIR, not ~/.claude).- installClaudeHooksInto(configDir)- deps.installSkill?.(configDir)- // Ensure fullscreen TUI in the new account dir (write-if-absent, version-gated). Best-effort,- // off the response path — the memoized probe + write both fail open.- void ensureClaudeFullscreenTuiInto(configDir)+ // Hook + skills + fullscreen TUI, only when the user consented to the claude integration+ // (issue #744); the consent lifecycle owns that decision.+ currentIntegrationLifecycle()?.installIntoClaudeAccount(configDir)const versionSupported = await checkClaudeVersion()return { id, configDir, versionSupported }})@@ -263,8 +254,7 @@ export function registerClaudeAccountsIpc(deps: ClaudeAccountsDeps = {}): void {// to its resolved target without replacing a symlink — the two-profile layout where// `<dir>/settings.json` is a symlink into `~/.claude/` keeps its symlink and the shared target// gains the managed hook (pinned by test).- installClaudeHooksInto(configDir)- void ensureClaudeFullscreenTuiInto(configDir)+ currentIntegrationLifecycle()?.installIntoClaudeAccount(configDir)return { id: randomUUID(), configDir, email }})@@ -364,47 +354,3 @@ export function registerClaudeAccountsIpc(deps: ClaudeAccountsDeps = {}): void {)}-/**- * Install the managed hook + fullscreen-TUI setting into every LOCAL managed account dir. Managed- * accounts each carry their own settings.json (Claude Code resolves it relative to- * CLAUDE_CONFIG_DIR), so an app update's new hook version must reach them too. Best-effort per- * account: one failing account must never block launch (matches installManagedAgentHooks'- * fail-open). `extra` is the shell's per-account addition — desktop installs the canvas skill.- *- * LINKED accounts (`ClaudeAccount.configDir`) are covered by the same loop and need no branch:- * they carry no `host`, and `claudeConfigDirFor` answers with the user's own dir — which is the- * point, because an app update's new hook version has to reach `~/.claude-2` too or that identity- * silently stops reporting agent status. The shells register the accounts source BEFORE calling- * this, or the resolver would hand back a managed dir that does not exist for those rows.- */-export function installHooksIntoLocalAccounts(- accounts: readonly { id: string; host?: string; shareSystemSkills?: boolean }[],- extra?: (configDir: string) => void-): void {- for (const acct of accounts) {- if (acct.host) continue // remote accounts live on another host; nothing to install locally- try {- const configDir = claudeConfigDirFor(acct.id)- installClaudeHooksInto(configDir)- extra?.(configDir)- // Shared-skills reconcile (issue #643) — the ON direction ONLY, and that asymmetry is the- // safety property. ON has real work to do at every boot: a skill the user added to- // `~/.claude/skills` since the last run needs a new link, and one they deleted leaves a- // broken entry Claude Code would still try to read. OFF is a REMOVAL, and a launch sweep is- // the wrong place to perform one: ownership here is inferred from a link's shape (a link at- // `<name>` pointing at `<system>/<name>`), which cannot tell OUR link from an identical one- // the user made by hand — and a LINKED account's dir is the user's own `~/.claude-2`, where- // exactly that hand-made link is a normal thing to find. So the off-switch removes links- // only where intent is explicit (`claude-accounts:set-skill-sharing`). The cost is that a- // settings.json edited to `false` while the app was closed leaves its links until the switch- // is flipped — links, not data, and visible in the account's own folder.- // AFTER `extra`, so the canvas skill's own directory exists before anything looks at it.- if (acct.shareSystemSkills) void applySkillShare(configDir, true)- // Off the critical path: it awaits the memoized CLI probe, then writes fail-open. (The- // system ~/.claude is handled by installManagedAgentHooks, which covers both shells.)- void ensureClaudeFullscreenTuiInto(configDir)- } catch (e) {- console.warn(`[agent-hooks] account ${acct.id} hook install failed`, e)- }- }-}diff --git a/src/core/context-link-core.ts b/src/core/context-link-core.tsindex 732305db4..eaa1bca4d 100644--- a/src/core/context-link-core.ts+++ b/src/core/context-link-core.ts@@ -93,7 +93,10 @@ export function mergeInstructionsBlock(existing: string, block: string): stringreturn existing + sep + full + '\n'}-/** The instructions body telling codex/gemini how to read linked-node context. */+/** The instructions body telling codex/gemini how to read linked-node context.+ * NOT INSTALLED since #744: every agent now gets the get-linked-context SKILL in its own skills+ * dir (core/agent-integrations.ts); older builds' copies of this block are stripped. Kept only+ * until its parity tests move to the skill body (follow-up). */export function buildLinkedContextInstructions(shimPath: string): string {return ['# Reading linked nodeterm nodes (get-linked-context)',@@ -358,7 +361,7 @@ description: Read the conversation/transcript, a recent summary, or the terminal# Get linked context-On the nodeterm canvas, this Claude session may be connected to other agent nodes (Claude, Codex or Gemini) by a+On the nodeterm canvas, this session may be connected to other agent nodes (Claude, Codex, Gemini, opencode or Grok) by acontext-link edge. When you are linked, you can READ the other node's context on demand byrunning the local CLI shim below. Nothing is pushed to you automatically — pull what you need.diff --git a/src/core/context-link.handler.test.ts b/src/core/context-link.handler.test.tsindex ba6462b17..c8094f038 100644--- a/src/core/context-link.handler.test.ts+++ b/src/core/context-link.handler.test.ts@@ -44,7 +44,7 @@ function start(deps: ContextLinkDeps = {}): void {// own ~/.claude and merged nodeterm's marker block into their ~/.codex/AGENTS.md,// ~/.gemini/GEMINI.md and opencode AGENTS.md. Nothing under test needs those writes — the read// handler and the dataDir shim are registered regardless.- initContextLink(fakePty(), deps, { installAgentIntegrations: false })+ initContextLink(fakePty(), deps)}beforeEach(() => start())diff --git a/src/core/context-link.ts b/src/core/context-link.tsindex d050caedc..d3c926e72 100644--- a/src/core/context-link.ts+++ b/src/core/context-link.ts@@ -15,11 +15,9 @@// that already knows the difference. The link documents are also still written to// <userData>/context-links/ as a debugging aid.import fs from 'fs'-import os from 'os'import path from 'path'import { platform } from './platform'import { writeManagedHookFileAtomic } from './agents/hooks/install-helper'-import { mergeInstructionFile } from './agents/hooks/settings-file'import { IPC } from '../shared/ipc'import type { ContextLinkInfo, ContextLinkMap } from '../shared/types'import { type PtyManager } from './pty-manager'@@ -28,10 +26,7 @@ import { isSafeOpencodeSessionId, runOpencodeExportAt } from './opencode-export'import { TMUX_SOCKET } from './tmux-naming'import {buildContextShimScript,- buildContextLinkSkillBody,buildLinkDoc,- buildLinkedContextInstructions,- mergeInstructionsBlock,resolveLinkTranscript,transcriptPathOf,type LinkDoc,@@ -46,7 +41,6 @@ import {} from './context-link-render'import { hookServer } from './agents/hook-server'import { locateClaude, locateCodex, locateGemini, locateGrok } from './handoff/locate'-import { opencodeConfigDir } from './agents/hooks/opencode'export { setNodeTranscript } from './context-link-core'@@ -58,8 +52,10 @@ export function contextLinkDir(): string {function cliShimPath(): string {return path.join(contextLinkDir(), 'context.sh')}-function skillPath(): string {- return path.join(os.homedir(), '.claude', 'skills', 'get-linked-context', 'SKILL.md')+/** The context-link shim the get-linked-context skill points at (written by `initContextLink`).+ * The skill itself is installed by the consent lifecycle (`core/agent-integrations.ts`). */+export function contextLinkShimPath(): string {+ return cliShimPath()}function writeCliFiles(): void {@@ -76,32 +72,6 @@ function writeCliFiles(): void {}}-function installSkill(): void {- try {- fs.mkdirSync(path.dirname(skillPath()), { recursive: true })- writeManagedHookFileAtomic(skillPath(), buildContextLinkSkillBody(cliShimPath()))- } catch (e) {- console.warn('[context-link] skill install failed', e)- }-}--// Codex/Gemini/opencode have no skill system — merge an instructions block into their global-// instruction files instead (marker-delimited, idempotent, other content preserved).-function installAgentInstructions(): void {- const block = buildLinkedContextInstructions(cliShimPath())- const targets = [- path.join(os.homedir(), '.codex', 'AGENTS.md'),- path.join(os.homedir(), '.gemini', 'GEMINI.md'),- path.join(opencodeConfigDir(), 'AGENTS.md')- ]- for (const p of targets) {- // The user's file: the guarded transaction keeps its link and mode (see canvas-control.ts).- if (mergeInstructionFile(p, (existing) => mergeInstructionsBlock(existing, block)) === 'failed') {- console.warn('[context-link] instructions install failed', p)- }- }-}-let pty: PtyManager | undefinedlet deps: ContextLinkDeps = {}@@ -317,27 +287,14 @@ export function setContextLinks(map: ContextLinkMap): Promise<void> {}/**- * Boot Context Link: register the hook-server read handler, (re)write the shim under `dataDir`,- * and — only when `options.installAgentIntegrations` says so — install the discovery surface into- * the machine's REAL agent configuration directories (`~/.claude/skills/get-linked-context`, plus- * the marker block in `~/.codex/AGENTS.md`, `~/.gemini/GEMINI.md` and opencode's `AGENTS.md`).+ * Boot Context Link: register the hook-server read handler and (re)write the shim under `dataDir`.*- * `options` is REQUIRED and its flag is a plain `boolean`, deliberately: those instruction files- * belong to the user and are loaded by every agent session on the machine, ours or not, so- * writing them is a decision each caller owes an answer to (issue #490). The previous shape —- * an optional options bag whose flag was read as `!== false` — meant the WRITE was what you got- * by saying nothing, which is the wrong default direction for a filesystem effect outside our own- * data dir, and it is exactly how a unit test that never thought about `HOME` came to rewrite the- * developer's own `~/.codex/AGENTS.md` on every run. Same asymmetry as- * `session-memory-service.ts`'s required `remote.isRemoteProject`: acting-without-knowing is a- * compile error. `platformDeps` lost its default with it — every caller already passes one, and a- * defaulted parameter in front of a required one is unreachable anyway.+ * Nothing here writes outside our own data dir. The discovery surface (the `get-linked-context`+ * skill in each consented agent's skills dir) is installed by the consent lifecycle+ * (`core/agent-integrations.ts`, issue #744) — the one place that decides what nodeterm may write+ * into user-owned agent configuration. `platformDeps` carries the shell's remote reach.*/-export function initContextLink(- ptyManager: PtyManager,- platformDeps: ContextLinkDeps,- options: { installAgentIntegrations: boolean }-): void {+export function initContextLink(ptyManager: PtyManager, platformDeps: ContextLinkDeps): void {pty = ptyManagerdeps = platformDeps// Re-derive from the platform this init runs under: a process that boots a second core (the@@ -355,10 +312,6 @@ export function initContextLink(if (f.endsWith('.json')) fs.rmSync(path.join(d, f), { force: true })}writeCliFiles()- if (options.installAgentIntegrations) {- installSkill()- installAgentInstructions()- }} catch (e) {console.error('[context-link] setup failed', e)returndiff --git a/src/core/integration-files.ts b/src/core/integration-files.tsnew file mode 100644index 000000000..29ea36d52--- /dev/null+++ b/src/core/integration-files.ts@@ -0,0 +1,202 @@+// The files agent integrations put into user-owned config dirs (skills), and the ownership+// receipts that let a decline remove ONLY what we wrote (issue #744).+//+// A receipt is the SHA-256 of the exact bytes we last wrote at a path. A file is ours to replace or+// remove when its current bytes match that receipt (or the body we are about to write); a file whose+// bytes match neither was edited by the user and is KEPT and reported, never overwritten or deleted.+// A path with no receipt (written by a build from before receipts) is ours by NAME — the skill dirs+// carry nodeterm's own names — so the next enabled reconcile rewrites it and records the receipt.+import { createHash } from 'crypto'+import { existsSync, lstatSync, mkdirSync, readFileSync, readdirSync, rmSync, rmdirSync } from 'fs'+import path from 'path'+import { writeManagedHookFileAtomic } from './agents/hooks/install-helper'+import { mergeInstructionFile } from './agents/hooks/settings-file'+import { CANVAS_CONTROL_MARKERS } from './canvas-control-core'+import { LINKED_CONTEXT_MARKERS } from './context-link-core'++const RECEIPTS_FILE = 'integration-receipts.json'+/** Bounded: every entry is a line in Settings and a path in a log. */+export const MAX_RETAINED = 20+/** Bounded: one skill per (agent, config dir, name); a hand-edited file must not grow us forever. */+const MAX_RECEIPTS = 2000++export const sha256 = (s: string): string => createHash('sha256').update(s, 'utf8').digest('hex')++interface ReceiptFile {+ version: 1+ files: Record<string, string>+}++export class ReceiptStore {+ private cache: Record<string, string> | null = null+ constructor(private readonly dir: () => string) {}++ private file(): string {+ return path.join(this.dir(), RECEIPTS_FILE)+ }++ private load(): Record<string, string> {+ if (this.cache) return this.cache+ let files: Record<string, string> = {}+ try {+ const parsed = JSON.parse(readFileSync(this.file(), 'utf8')) as Partial<ReceiptFile>+ if (parsed && typeof parsed.files === 'object' && parsed.files) {+ for (const [k, v] of Object.entries(parsed.files)) {+ if (typeof v === 'string' && /^([0-9a-f]{64}|\d{1,10} \d{1,12})$/.test(v) && (path.isAbsolute(k) || /^ssh:[^\s/]+:\//.test(k))) files[k] = v+ }+ }+ } catch {+ files = {}+ }+ this.cache = files+ return files+ }++ get(p: string): string | undefined {+ return Object.prototype.hasOwnProperty.call(this.load(), p) ? this.load()[p] : undefined+ }++ set(p: string, hash: string | null): void {+ const files = { ...this.load() }+ if (hash === null) delete files[p]+ else files[p] = hash+ const keys = Object.keys(files)+ if (keys.length > MAX_RECEIPTS) for (const k of keys.slice(0, keys.length - MAX_RECEIPTS)) delete files[k]+ this.cache = files+ try {+ mkdirSync(this.dir(), { recursive: true })+ writeManagedHookFileAtomic(this.file(), JSON.stringify({ version: 1, files }, null, 2), undefined, 0o600)+ } catch (e) {+ console.warn('[integrations] receipt write failed', e)+ }+ }+}++function readIfRegular(p: string): string | null | 'not-regular' {+ let st+ try {+ st = lstatSync(p)+ } catch {+ return null+ }+ if (!st.isFile()) return 'not-regular'+ try {+ return readFileSync(p, 'utf8')+ } catch {+ return 'not-regular'+ }+}++export type OwnedWrite = 'written' | 'unchanged' | 'retained' | 'failed'++/** Write `body` at `p` unless the file there is the user's (edited since our last write). */+export function writeOwnedFile(receipts: ReceiptStore, p: string, body: string): OwnedWrite {+ const current = readIfRegular(p)+ if (current === 'not-regular') return 'retained'+ const want = sha256(body)+ if (current !== null) {+ const have = sha256(current)+ if (have === want) {+ if (receipts.get(p) !== want) receipts.set(p, want)+ return 'unchanged'+ }+ const receipt = receipts.get(p)+ if (receipt !== undefined && receipt !== have) return 'retained'+ }+ try {+ mkdirSync(path.dirname(p), { recursive: true })+ writeManagedHookFileAtomic(p, body)+ receipts.set(p, want)+ return 'written'+ } catch (e) {+ console.warn('[integrations] write failed', p, e)+ return 'failed'+ }+}++export type OwnedRemove = 'removed' | 'absent' | 'retained' | 'failed'++/** Remove `p` only if its bytes are what we wrote; then drop its now-empty skill dir. `known`+ * are bodies this build would write there (a pre-receipt install is recognised by them). */+export function removeOwnedFile(receipts: ReceiptStore, p: string, known: readonly string[] = []): OwnedRemove {+ const current = readIfRegular(p)+ if (current === null) {+ receipts.set(p, null)+ return 'absent'+ }+ if (current === 'not-regular') return 'retained'+ const have = sha256(current)+ const ours = receipts.get(p) === have || known.some((b) => sha256(b) === have)+ if (!ours) return 'retained'+ try {+ rmSync(p, { force: true })+ receipts.set(p, null)+ const dir = path.dirname(p)+ try {+ if (existsSync(dir) && readdirSync(dir).length === 0) rmdirSync(dir)+ } catch {+ /* not empty / not ours to remove */+ }+ return 'removed'+ } catch (e) {+ console.warn('[integrations] remove failed', p, e)+ return 'failed'+ }+}++/** Remove one marker-delimited block (start through end, end searched after start) and the blank+ * separator the merge put before it. Everything else is preserved byte for byte. */+export function stripMarkerBlock(existing: string, markers: { start: string; end: string }): string {+ const start = existing.indexOf(markers.start)+ if (start < 0) return existing+ const end = existing.indexOf(markers.end, start)+ if (end < 0) return existing+ let before = existing.slice(0, start)+ let after = existing.slice(end + markers.end.length)+ if (after.startsWith('\n')) after = after.slice(1)+ if (before.endsWith('\n\n')) before = before.slice(0, -1)+ else if (!after && before.endsWith('\n') && before.trim() === '') before = ''+ return before + after+}++/** Strip both legacy discovery blocks (canvas control, context link) from an instruction file.+ * These were ~17 KB in ~/.codex/AGENTS.md and crowded codex's 32 KiB project-doc budget (#744);+ * skills replaced them. Runs through the guarded transaction (link + mode kept, an unreadable file+ * left alone, nothing written when nothing changes). */+export function stripLegacyBlocks(file: string): 'written' | 'unchanged' | 'failed' {+ const strip = (existing: string): string =>+ stripMarkerBlock(stripMarkerBlock(existing, CANVAS_CONTROL_MARKERS), LINKED_CONTEXT_MARKERS)+ let st+ try {+ st = lstatSync(file)+ } catch {+ return 'unchanged'+ }+ // A regular file that held NOTHING but our blocks was ours (an older build created it to hold+ // them): remove it rather than leave an empty AGENTS.md behind. Re-read right before the unlink.+ if (st.isFile()) {+ try {+ const before = readFileSync(file, 'utf8')+ const after = strip(before)+ if (after !== before && after.trim() === '') {+ if (readFileSync(file, 'utf8') !== before) return 'unchanged'+ rmSync(file, { force: true })+ return 'written'+ }+ } catch {+ return 'failed'+ }+ }+ // Everything else through the guarded transaction (link + mode kept, an unreadable file left+ // alone, nothing written when nothing changes). A linked file reduced to nothing keeps one+ // newline: the transaction never publishes an empty file, and the link is the user's.+ return mergeInstructionFile(file, (existing) => {+ const after = strip(existing)+ return after !== existing && after.trim() === '' ? '\n' : after+ })+}++/** A bounded list of paths we kept because the user changed them. */+export function pushRetained(list: string[], p: string): void {+ if (list.length < MAX_RETAINED && !list.includes(p)) list.push(p)+}diff --git a/src/core/relay/access-policy.ts b/src/core/relay/access-policy.tsindex f8a0ec719..a1667ec5e 100644--- a/src/core/relay/access-policy.ts+++ b/src/core/relay/access-policy.ts@@ -313,6 +313,8 @@ export const EDITOR_ONLY: ReadonlySet<string> = new Set<string>([IPC.projectSetupUnsubscribe,IPC.worktreeMaterializeShared,// Host settings, credentials and paths.+ // Agent-integration consent status (#744): host-only, never a viewer's.+ IPC.integrationsStatus,IPC.settingsLoad,IPC.settingsSave,IPC.agentDiscoverModels,diff --git a/src/core/relay/scoped-guest-policy.ts b/src/core/relay/scoped-guest-policy.tsindex 4a0d3e1b2..ee96683c4 100644--- a/src/core/relay/scoped-guest-policy.ts+++ b/src/core/relay/scoped-guest-policy.ts@@ -440,6 +440,8 @@ export const SCOPED_REFUSED: ReadonlySet<string> = new Set<string>([// Host settings and credentials (also host-only for every peer, shared/host-control.ts).IPC.settingsLoad,IPC.settingsSave,+ // Agent-integration consent status: paths in the host's home (host-only, #744).+ IPC.integrationsStatus,IPC.agentDiscoverModels,IPC.agentGatewayCredentialStatus,IPC.agentGatewayCredentialSave,diff --git a/src/main/canvas-control.ts b/src/main/canvas-control.tsindex 7206a274f..e1dd534c7 100644--- a/src/main/canvas-control.ts+++ b/src/main/canvas-control.ts@@ -1,46 +1,35 @@-// Installs the outbound canvas-control CLI + per-agent discovery docs. Mirrors-// context-link.ts: a self-contained POSIX-sh CLI (nodeterm.sh) POSTs to the hook server's-// /control/* routes; a Claude skill / codex-gemini instruction blocks tell the agent how +-// when to call it. The CLI no-ops unless NODETERM_CANVAS_CONTROL is set.+// Installs the outbound canvas-control CLI (nodeterm.sh) under userData. A self-contained POSIX-sh+// CLI POSTs to the hook server's /control/* routes; it no-ops unless NODETERM_CANVAS_CONTROL is set.//-// The SSH counterpart is RemoteHooks.installCanvasControl. Both use the same machine-neutral-// body, but the LOCAL installer prepends the shared-Codex thread resolver with this machine's-// ownership-record path; a desktop path must never be baked into the remote copy.+// Discovery (the manage-nodeterm-canvas skill in each agent's skills dir) is NOT written here: it is+// the consent lifecycle's (`core/agent-integrations.ts`, issue #744), the one place that decides what+// nodeterm may write into user-owned agent configuration.+//+// The SSH counterpart is RemoteHooks.installCanvasControl. Both use the same machine-neutral body,+// but the LOCAL shim prepends the shared-Codex thread resolver with this machine's ownership-record+// path; a desktop path must never be baked into the remote copy.import fs from 'fs'-import os from 'os'import path from 'path'import { app } from 'electron'-import {- buildControlShimScript,- buildCanvasControlInstructions,- buildCanvasSkillBody,- mergeCanvasControlBlock-} from '../core/canvas-control-core'+import { buildControlShimScript } from '../core/canvas-control-core'import { codexThreadIdentityRoot } from '../core/codex-identity-proxy'import { writeManagedHookFileAtomic } from '../core/agents/hooks/install-helper'-import { mergeInstructionFile } from '../core/agents/hooks/settings-file'-import { opencodeConfigDir } from '../core/agents/hooks/opencode'-import { copilotHomeDir } from '../core/agents/hooks/copilot'function dir(): string {return path.join(app.getPath('userData'), 'canvas-control')}-function shimPath(): string {++/** The shim the canvas skill points at. */+export function canvasControlShimPath(): string {return path.join(dir(), 'nodeterm.sh')}-function skillPathIn(configDir: string): string {- return path.join(configDir, 'skills', 'manage-nodeterm-canvas', 'SKILL.md')-}-function skillBody(): string {- return buildCanvasSkillBody(shimPath())-}function writeCliFiles(): void {const d = dir()fs.mkdirSync(d, { recursive: true })// Temp + rename, never a truncating write: agents execute this file, and a shim caught half// written is a canvas call that exits 0 having done nothing.- writeManagedHookFileAtomic(shimPath(), buildControlShimScript(codexThreadIdentityRoot()), undefined, 0o755)+ writeManagedHookFileAtomic(canvasControlShimPath(), buildControlShimScript(codexThreadIdentityRoot()), undefined, 0o755)// Sweep the retired Electron-as-Node CLI off upgraders' disks — the shim no longer execs it,// so it would sit there forever pointing at a binary path that moves with every app update.try {@@ -50,48 +39,9 @@ function writeCliFiles(): void {}}-/**- * Install (or refresh) the canvas-control skill into a Claude config dir's `skills/`.- * Claude Code resolves user skills relative to CLAUDE_CONFIG_DIR, so managed accounts- * (config dir = {userData}/claude-accounts/<id>) need their own copy — mirroring how the- * managed status hook is merged into each account dir's settings.json. Best-effort.- */-export function installCanvasSkillInto(configDir: string): void {- const p = skillPathIn(configDir)- try {- fs.mkdirSync(path.dirname(p), { recursive: true })- writeManagedHookFileAtomic(p, skillBody())- } catch (e) {- console.warn('[canvas-control] skill install failed', p, e)- }-}--// Codex/Gemini/Copilot/opencode use global instruction files here — merge the canvas-control block-// instruction files (marker-delimited, idempotent, other content preserved). Same pattern-// as context-link's get-linked-context block. The CLI env-gate keeps the block inert in-// the user's normal (non-nodeterm) codex/gemini/opencode sessions.-function installAgentInstructions(): void {- const block = buildCanvasControlInstructions(shimPath())- const targets = [- path.join(os.homedir(), '.codex', 'AGENTS.md'),- path.join(os.homedir(), '.gemini', 'GEMINI.md'),- path.join(copilotHomeDir(), 'copilot-instructions.md'),- path.join(opencodeConfigDir(), 'AGENTS.md')- ]- for (const p of targets) {- // The user's file: merged through the guarded transaction (link and mode kept, never read an- // unreadable file as empty and replace it with our block).- if (mergeInstructionFile(p, (existing) => mergeCanvasControlBlock(existing, block)) === 'failed') {- console.warn('[canvas-control] instructions install failed', p)- }- }-}-export function initCanvasControl(): void {try {writeCliFiles()- installCanvasSkillInto(path.join(os.homedir(), '.claude'))- installAgentInstructions()} catch (e) {console.error('[canvas-control] setup failed', e)}diff --git a/src/main/claude-accounts.ts b/src/main/claude-accounts.tsindex 6be801000..a7e30f8bf 100644--- a/src/main/claude-accounts.ts+++ b/src/main/claude-accounts.ts@@ -1,9 +1,8 @@// Desktop wiring for the managed-Claude-account lifecycle. The lifecycle itself lives in// src/core/claude-accounts-service.ts so the Server Edition serves the same four channels-// (issue #313); this file supplies only the two things core cannot reach — the canvas-control-// skill installer (which imports electron's `app`) and the SSH project manager.+// (issue #313); this file supplies only what core cannot reach — the SSH project manager. The+// account's hook + skills come from the consent lifecycle (core/agent-integrations.ts).import { registerClaudeAccountsIpc } from '../core/claude-accounts-service'-import { installCanvasSkillInto } from './canvas-control'import type { SshProjectManager } from './remote-ssh/ssh-project'// Re-exported for this module's other consumers (claude-usage.ts) so their import path is@@ -16,7 +15,6 @@ export { claudeConfigDirFor } from '../core/claude-config-dir'*/export function initClaudeAccounts(getSshManager?: () => SshProjectManager | undefined): void {registerClaudeAccountsIpc({- installSkill: installCanvasSkillInto,remote: () => {const mgr = getSshManager?.()if (!mgr) return undefineddiff --git a/src/main/index.ts b/src/main/index.tsindex 89446a8a7..80eab02a8 100644--- a/src/main/index.ts+++ b/src/main/index.ts@@ -260,7 +260,6 @@ import { PUSH_WEBHOOK_DEFAULT_API_BASE } from '../shared/push-webhook'import { initRemoteStatusPush } from './remote-ssh/remote-status-push'import { initCanvasSync } from '../core/canvas-sync'import { retainUntilDismissed } from './notifications'-import { installManagedAgentHooks } from '../core/agents/hooks'import { createSubagentTail } from '../core/subagent-tail'import { ClaudeSubagentLifecycle } from '../core/claude-subagent-lifecycle'import { claudeSubagentTranscriptPath, isClaudeAgentId } from '../shared/agents/claude-subagents'@@ -319,9 +318,9 @@ import { planSshPrewarm, runSshPrewarm } from '../core/remote-ssh/ssh-prewarm'import { sessionName } from '../core/tmux-naming'import { posixQuote, sshHostKey, type SshConnection } from '../shared/ssh'import { buildHandoff, type HandoffRemote } from './handoff'-import { initContextLink, setNodeTranscript } from '../core/context-link'+import { contextLinkShimPath, initContextLink, setNodeTranscript } from '../core/context-link'import { transcriptPathOf } from '../core/context-link-core'-import { initCanvasControl, installCanvasSkillInto } from './canvas-control'+import { initCanvasControl, canvasControlShimPath } from './canvas-control'import { DRY_RUN_VERBS, dryRunRequested, dryRunRefusal } from '../shared/control-verbs'import { issueFlagRefusal } from '../core/canvas-control-core'import { afterPrFlagRefusal } from '../shared/pr-wait'@@ -371,7 +370,14 @@ import {isSafeRemoteTranscriptPath,remoteAccountConfigDirAbs} from '../core/claude-accounts-core'-import { installHooksIntoLocalAccounts } from '../core/claude-accounts-service'+import {+ createIntegrationLifecycle,+ detectExistingIntegrations,+ registerIntegrationLifecycle,+ resolveIntegrationConsentAtBoot+} from '../core/agent-integrations'+import { registerIntegrationIpc } from '../core/agent-integrations-ipc'+import { remoteIntegrationPlan } from '../shared/agent-integrations'import { createPairingService } from './pairing-service'import {initRemoteHost,@@ -1443,6 +1449,18 @@ app.whenReady().then(async () => {// retry next launch, and the user never loses their only copy of the credential.console.warn('[model-gateway] could not migrate the legacy API key to secret storage', error)}+ // Agent-integration consent (issue #744): an install from before this feature (our own hook+ // scripts / shims are on disk) is grandfathered as enabled, so nobody's badges or canvas control+ // silently stop on upgrade. Decided BEFORE the renderer can load settings and before any install.+ try {+ const grandfathered = resolveIntegrationConsentAtBoot(+ settingsStore.get(),+ detectExistingIntegrations(app.getPath('userData'))+ )+ if (grandfathered) await settingsStore.save(grandfathered)+ } catch (error) {+ console.warn('[integrations] could not record the grandfathered consent', error)+ }settingsStore.registerIpc()sshStore.registerIpc()// Gateway discovery/credential IPC (peer-reachable by design; the renderer never receives a@@ -3079,13 +3097,19 @@ app.whenReady().then(async () => {) => buildHandoff({ sessionId, agentId, sourceNodeId, cwd, accountId, remote: handoffRemote }))- installManagedAgentHooks()- // Managed accounts each carry their own settings.json AND skills/ (Claude Code resolves both- // relative to CLAUDE_CONFIG_DIR) — re-install the hook + canvas skill there too (idempotent),- // so an app update's new versions reach every account dir. The loop is shared with the Server- // Edition's boot (src/core/claude-accounts-service.ts); each shell supplies its own canvas-skill- // installer when that control surface is enabled.- installHooksIntoLocalAccounts(settingsStore.get().claudeAccounts ?? [], installCanvasSkillInto)+ // Agent-integration consent (issue #744): the ONE writer of user-owned agent config on this+ // machine — status hooks and skills, per consented agent, system dirs and every local managed /+ // linked account dir. Nothing is written for an agent the user has not enabled; a declined one+ // is cleaned up. Re-runs whenever the consent or the local account list changes.+ const integrations = createIntegrationLifecycle({+ settings: () => settingsStore.get(),+ userDataDir: () => app.getPath('userData'),+ shims: () => ({ canvas: canvasControlShimPath(), context: contextLinkShimPath() })+ })+ registerIntegrationLifecycle(integrations)+ integrations.reconcile()+ settingsStore.onChange((s) => integrations.onSettingsChanged(s))+ registerIntegrationIpc(integrations)// Fan a normalized agent event to BOTH consumers: the renderer's agentStatus store (canvas badge)// and the mobile-facing mirror. Named so the deterministic-approval answer handler below can reuse// it for the optimistic flip.@@ -4325,11 +4349,6 @@ app.whenReady().then(async () => {return null}}- }, {- // The desktop app is the surface Context Link's discovery was designed for, so it installs- // the skill + instruction blocks. Stated rather than defaulted: the flag is required so no- // caller can reach the write by omission (see initContextLink, issue #490).- installAgentIntegrations: true})initCanvasControl()// Usage service + the mobile `usage` mirror block (mobile-usage-inbox): poll all local managed@@ -4854,8 +4873,18 @@ app.whenReady().then(async () => {// 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)+ (settingsStore.get().claudeAccounts ?? []).filter((a) => a.host === hostKey && !a.pending).map((a) => a.id),+ // Agent-integration consent per SSH host (issue #744): nothing is installed on a host the user+ // has not answered for, and a declined one is cleaned up.+ {+ integrationsForHost: (hostKey) => {+ const plan = remoteIntegrationPlan(settingsStore.get(), hostKey)+ return { install: new Set(plan.install), remove: new Set(plan.remove), decided: plan.decided }+ },+ integrationReceipts: integrations.receipts+ })+ settingsStore.onChange(() => sshProjectManager?.onIntegrationConsentChanged())// Pre-warm the ControlMasters of OPEN SSH projects, in the background, one host at a time.//// Without this the master for a project is dialed only when the user first switches to it, so thediff --git a/src/main/remote-ssh/agent-tools-refresh.test.ts b/src/main/remote-ssh/agent-tools-refresh.test.tsindex 503af805d..42e1e962c 100644--- a/src/main/remote-ssh/agent-tools-refresh.test.ts+++ b/src/main/remote-ssh/agent-tools-refresh.test.ts@@ -1,6 +1,7 @@// `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 { allRemote } from './remote-hooks.test-plan'import { spawnSync } from 'child_process'import {existsSync,@@ -17,12 +18,7 @@ import {import { tmpdir } from 'os'import path from 'path'import { afterAll, afterEach, beforeAll, beforeEach, describe, expect, it, vi } from 'vitest'-import {- CONTROL_SHIM_SCRIPT,- buildCanvasControlInstructions,- buildCanvasSkillBody,- mergeCanvasControlBlock-} from '../../core/canvas-control-core'+import { CONTROL_SHIM_SCRIPT, buildCanvasSkillBody } from '../../core/canvas-control-core'import { CONTEXT_SHIM_SCRIPT, buildContextLinkSkillBody } from '../../core/context-link-core'import { RemoteHooks, type RemoteRunner } from './remote-hooks'@@ -47,6 +43,9 @@ 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`+/** The env-independent dir codex/gemini/copilot/opencode/grok all read (#744). */+const AGENTS_SKILL = () => `${home}/.agents/skills/manage-nodeterm-canvas/SKILL.md`+const AGENTS_CTX_SKILL = () => `${home}/.agents/skills/get-linked-context/SKILL.md`const accountDir = (id: string) => `${home}/.nodeterm/claude-accounts/${id}`interface HostRunner extends RemoteRunner {@@ -90,29 +89,37 @@ function put(p: string, content: string): void {/** 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')+ await new RemoteHooks(hostRunner(), allRemote).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')+ const outcome = await new RemoteHooks(hostRunner(), allRemote).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(AGENTS_SKILL())).toBe(buildCanvasSkillBody(SHIM()))+ expect(read(AGENTS_CTX_SKILL())).toBe(buildContextLinkSkillBody(CTX()))+ // Skills replaced the instruction blocks (#744): no global instruction file is created.+ for (const f of ['.codex/AGENTS.md', '.gemini/GEMINI.md', '.config/opencode/AGENTS.md', '.copilot/copilot-instructions.md']) {+ expect(existsSync(path.join(home, f)), f).toBe(false)}- expect(read(path.join(home, '.copilot/copilot-instructions.md'))).toContain('nodeterm:manage-canvas:start')+ })++ it('an unanswered host gets nothing at all — not even a probe (#744)', async () => {+ const runner = hostRunner()+ const undecided = () => ({ install: new Set<string>(), remove: new Set<string>(), decided: false })+ expect(await new RemoteHooks(runner, undecided).refreshAgentTools(conn, '/fixture.sock', home, ['acc-1'], 'connect')).toBe('skipped')+ expect(runner.calls).toHaveLength(0)+ expect(existsSync(path.join(home, '.nodeterm'))).toBe(false)})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')+ const outcome = await new RemoteHooks(runner, allRemote).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.@@ -120,68 +127,21 @@ describe.skipIf(process.platform === 'win32')('RemoteHooks.refreshAgentTools (reexpect(probes(runner)).toHaveLength(1)})- it('rewrites exactly the stale files, keeping the user text around a stale block', async () => {+ it('rewrites exactly the stale files', 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}`)+ put(AGENTS_SKILL(), '---\nname: manage-nodeterm-canvas\n---\nold verbs\n')const runner = hostRunner()- const outcome = await new RemoteHooks(runner).refreshAgentTools(conn, '/fixture.sock', home, [], 'connect')+ const outcome = await new RemoteHooks(runner, allRemote).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(read(AGENTS_SKILL())).toBe(buildCanvasSkillBody(SHIM()))expect(publishes(runner)).toHaveLength(3)expect(publishedTo(runner, SHIM())).toBe(true)expect(publishedTo(runner, SKILL())).toBe(true)- expect(publishedTo(runner, gemini)).toBe(true)- })-- // Measured before the fix: 41,693 → 81,279 → 120,865 → 160,451 bytes over a connect and three- // hourly re-checks — the merge took the stray end marker for "no block" and appended each time.- // Two hosts, because two halves had the bug: on a normal host the PROBE must find the block (else- // it reads stale every check); on a host whose awk fails every block is merged on every check,- // so the MERGE itself must find it.- it.each([- ['a normal host', false],- ['a host whose awk fails (every block merged every check)', true]- ])('a stray end marker left by a hand-deleted block costs ONE append, not one per check — %s', async (_n, badAwk) => {- await freshHost()- const bin = mkdtempSync(path.join(tmpdir(), 'nt-bad-awk-'))- try {- writeFileSync(path.join(bin, 'awk'), '#!/bin/sh\nexit 2\n', { mode: 0o755 })- const opts = badAwk ? { path: `${bin}:${process.env.PATH ?? '/usr/bin:/bin'}` } : {}- const codex = path.join(home, '.codex/AGENTS.md')- // Both of our blocks gone from the file, each leaving its end line behind.- let text = read(codex)- for (const m of ['manage-canvas', 'get-linked-context']) {- const start = text.indexOf(`<!-- nodeterm:${m}:start -->`)- const end = text.indexOf(`<!-- nodeterm:${m}:end -->`)- text = text.slice(0, start) + text.slice(end)- }- put(codex, `# mine\n${text}`)- await new RemoteHooks(hostRunner(opts)).refreshAgentTools(conn, '/fixture.sock', home, [], 'connect')- const size = read(codex).length- expect(read(codex).match(/manage-canvas:start/g)).toHaveLength(1)- expect(read(codex).match(/get-linked-context:start/g)).toHaveLength(1)- for (let i = 0; i < 2; i++) {- const runner = hostRunner(opts)- expect(await new RemoteHooks(runner).refreshAgentTools(conn, '/fixture.sock', home, [], 'connect')).toBe('current')- expect(read(codex).length).toBe(size)- expect(publishes(runner)).toHaveLength(0)- // On a normal host the probe agrees with the merge outright: no merge read at all.- if (!badAwk) expect(runner.calls).toHaveLength(1)- }- } finally {- rmSync(bin, { recursive: true, force: true })- }+ expect(publishedTo(runner, AGENTS_SKILL())).toBe(true)})it('writes what is missing and nothing else', async () => {@@ -189,7 +149,7 @@ describe.skipIf(process.platform === 'win32')('RemoteHooks.refreshAgentTools (rermSync(CTX())rmSync(path.dirname(CTX_SKILL()), { recursive: true })const runner = hostRunner()- await new RemoteHooks(runner).refreshAgentTools(conn, '/fixture.sock', home, [], 'connect')+ await new RemoteHooks(runner, allRemote).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)@@ -199,12 +159,12 @@ describe.skipIf(process.platform === 'win32')('RemoteHooks.refreshAgentTools (reawait freshHost()rmSync(SKILL())mkdirSync(SKILL()) // a directory where our file should be- const codex = path.join(home, '.codex/AGENTS.md')+ const codex = AGENTS_SKILL()rmSync(codex)- symlinkSync(path.join(home, 'no-such-dotfile'), codex) // a dangling dotfile link+ symlinkSync(path.join(home, 'no-such-dotfile'), codex) // a dangling link where our file should beput(SHIM(), 'stale\n')const runner = hostRunner()- const rh = new RemoteHooks(runner)+ const rh = new RemoteHooks(runner, allRemote)expect(await rh.refreshAgentTools(conn, '/fixture.sock', home, [], 'connect')).toBe('failed')expect(lstatSync(SKILL()).isDirectory()).toBe(true)expect(readdirSync(SKILL())).toEqual([])@@ -224,7 +184,7 @@ describe.skipIf(process.platform === 'win32')('RemoteHooks.refreshAgentTools (reawait 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')+ await new RemoteHooks(runner, allRemote).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)@@ -233,53 +193,11 @@ describe.skipIf(process.platform === 'win32')('RemoteHooks.refreshAgentTools (reexpect(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)-- // The probe can never vouch for ~/.copilot under that env, so every check re-merges it — and a- // merge that changes nothing is NOT a rewrite: no write, no "rewrote" line, outcome current.- info.mockClear()- const again = hostRunner({ env: { COPILOT_HOME: 'relative-dir' } })- expect(await new RemoteHooks(again).refreshAgentTools(conn, '/fixture.sock', home, [], 'connect')).toBe('current')- expect(publishes(again)).toHaveLength(0)- expect(claimedRewrite()).toBe(false)- })-- it('a host whose awk fails has its blocks MERGED instead (which write only on a change) — never a false rewrite', async () => {- await freshHost()- const bin = mkdtempSync(path.join(tmpdir(), 'nt-bad-awk-'))- try {- writeFileSync(path.join(bin, 'awk'), '#!/bin/sh\nexit 2\n', { mode: 0o755 })- info.mockClear()- const runner = hostRunner({ path: `${bin}:${process.env.PATH ?? '/usr/bin:/bin'}` })- expect(await new RemoteHooks(runner).refreshAgentTools(conn, '/fixture.sock', home, [], 'connect')).toBe('current')- expect(publishes(runner)).toHaveLength(0)- expect(claimedRewrite()).toBe(false)- // …and said once, so a host that never confirms by checksum is visible in the log.- expect(warn.mock.calls.flat().join('\n')).toMatch(/could not checksum 7 instruction block/)- } finally {- rmSync(bin, { recursive: true, force: true })- }+ it("puts the shared skills in ~/.agents/skills whatever the host's COPILOT_HOME / GROK_HOME / XDG say", async () => {+ const env = { COPILOT_HOME: path.join(home, 'cp'), GROK_HOME: path.join(home, 'gk'), XDG_CONFIG_HOME: path.join(home, 'xdg') }+ await new RemoteHooks(hostRunner({ env }), allRemote).refreshAgentTools(conn, '/fixture.sock', home, [], 'connect')+ expect(read(AGENTS_SKILL())).toBe(buildCanvasSkillBody(SHIM()))+ for (const d of ['cp', 'gk', 'xdg']) expect(existsSync(path.join(home, d)), d).toBe(false)})it('an account dir removed between the probe and the write is not brought back', async () => {@@ -294,7 +212,7 @@ describe.skipIf(process.platform === 'win32')('RemoteHooks.refreshAgentTools (rereturn r}}- await new RemoteHooks(racing).refreshAgentTools(conn, '/fixture.sock', home, ['acc-1'], 'connect')+ await new RemoteHooks(racing, allRemote).refreshAgentTools(conn, '/fixture.sock', home, ['acc-1'], 'connect')expect(existsSync(accountDir('acc-1'))).toBe(false)// The system files still landed: a vanished account costs only its own skills.expect(read(SHIM())).toBe(CONTROL_SHIM_SCRIPT)@@ -303,14 +221,14 @@ describe.skipIf(process.platform === 'win32')('RemoteHooks.refreshAgentTools (reit('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(await new RemoteHooks(runner, allRemote).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)+ const rh = new RemoteHooks(runner, allRemote)// 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'),@@ -354,7 +272,7 @@ describe.skipIf(process.platform === 'win32')('RemoteHooks.refreshAgentTools (remkdirSync(SKILL(), { recursive: true }) // a directory where our file should bemkdirSync(accountDir('acc-1'), { recursive: true })const runner = hostRunner({ path: bin })- expect(await new RemoteHooks(runner).refreshAgentTools(conn, '/fixture.sock', home, ['acc-1', 'gone'], 'connect')).toBe(+ expect(await new RemoteHooks(runner, allRemote).refreshAgentTools(conn, '/fixture.sock', home, ['acc-1', 'gone'], 'connect')).toBe('failed')expect(readdirSync(SKILL())).toEqual([])@@ -366,7 +284,7 @@ describe.skipIf(process.platform === 'win32')('RemoteHooks.refreshAgentTools (reit('writes what it can read without comparison, as every connect did before the check existed', async () => {put(SHIM(), 'stale\n')const runner = hostRunner({ path: bin })- const rh = new RemoteHooks(runner)+ const rh = new RemoteHooks(runner, allRemote)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()))diff --git a/src/main/remote-ssh/remote-hooks.test-plan.ts b/src/main/remote-ssh/remote-hooks.test-plan.tsnew file mode 100644index 000000000..b999660ca--- /dev/null+++ b/src/main/remote-ssh/remote-hooks.test-plan.ts@@ -0,0 +1,11 @@+// Test helper: a consent plan that enables every agent on every host — the pre-#744 behaviour the+// older remote-hooks suites were written against. Production never uses it.+import { INTEGRATION_AGENT_IDS } from '../../shared/agent-integrations'+import type { RemoteIntegrationPlan } from './remote-hooks'++export const ALL_REMOTE_INTEGRATION: RemoteIntegrationPlan = {+ install: new Set(INTEGRATION_AGENT_IDS),+ remove: new Set(),+ decided: true+}+export const allRemote = (): RemoteIntegrationPlan => ALL_REMOTE_INTEGRATIONdiff --git a/src/main/remote-ssh/remote-hooks.test.ts b/src/main/remote-ssh/remote-hooks.test.tsindex 3793dde8e..fb178ab49 100644--- a/src/main/remote-ssh/remote-hooks.test.ts+++ b/src/main/remote-ssh/remote-hooks.test.ts@@ -1,7 +1,8 @@+import { allRemote, ALL_REMOTE_INTEGRATION } from './remote-hooks.test-plan'import { createHash } from 'crypto'import { execFileSync } from 'child_process'import { describe, expect, it, vi } from 'vitest'-import { RemoteHooks, openCodeInstructionsTarget } from './remote-hooks'+import { RemoteHooks, type RemoteIntegrationPlan, openCodeInstructionsTarget } from './remote-hooks'import { isSafeRemoteHome } from '../../core/remote-safety'import { hookServer } from '../../core/agents/hook-server'@@ -20,6 +21,8 @@ function harness(failOn?: string/** Command substring whose runner result is non-zero (the runner itself still resolves). */failCodeOn?: string+ /** The host's consent plan (issue #744). Default: every agent enabled. */+ plan?: RemoteIntegrationPlan} = {}) {// One record per ssh child command. `args` is what the runner was handed; `cmd` is the joined@@ -44,7 +47,7 @@ function harness(if (joined.includes('%{http_code}')) return { code: 0, stdout: verifyAnswers.shift() ?? '204' }return { code: 0, stdout: '' }})- return { rh: new RemoteHooks({ run }), calls, runs: calls, run, conn }+ return { rh: new RemoteHooks({ run }, () => opts.plan ?? ALL_REMOTE_INTEGRATION), calls, runs: calls, run, conn }}/** A remote command that PUBLISHES `p`: every write now ends in a rename onto the quoted path —@@ -196,7 +199,7 @@ describe('RemoteHooks.setup', () => {}return { code: 0, stdout: '' }})- await new RemoteHooks({ run }).setup('p1', conn, '/s.sock', { port: 1, token: 't', version: '1' })+ await new RemoteHooks({ run }, allRemote).setup('p1', conn, '/s.sock', { port: 1, token: 't', version: '1' })const joined = calls.map((c) => c.args.join(' '))// the script is still (idempotently) written, but neither hooks.json nor config.toml is rewritten.expect(joined.some((j) => writesTo(j, '/home/u/.nodeterm/agent-hooks/codex.sh'))).toBe(true)@@ -268,7 +271,7 @@ describe('RemoteHooks.setup', () => {if (joined.includes("cat '/home/u/.claude/settings.json'")) return { code: 0, stdout: '{}' }return { code: 0, stdout: '' }})- const rh = new RemoteHooks({ run })+ const rh = new RemoteHooks({ run }, allRemote)const res = await rh.setup('p1', conn, '/s.sock', { port: 51234, token: 'tok', version: '1' })expect(res?.endpointPath).toBe(`/home/u/.nodeterm/hook-endpoint-p1-${owner}.env`)expect(forwards).toBe(2)@@ -365,26 +368,19 @@ describe('RemoteHooks — the opencode XDG path expression', () => {expect(probe('/home/u')).toBe('ARGC=1|/home/u/.config/opencode/AGENTS.md')})- for (const [what, install] of [- ['canvas control', (rh: RemoteHooks, c: typeof conn) => rh.installCanvasControl(c, '/s.sock', HOSTILE)],- ['context link', (rh: RemoteHooks, c: typeof conn) => rh.installContextLink(c, '/s.sock', HOSTILE)]- ] as const) {- it(`${what} routes the opencode target through that safe form`, async () => {- const { rh, conn: c, runs } = harness()- await install(rh, c)- const lines = runs- .map((r) => r.args[r.args.length - 1])- .filter((l) => l.includes('opencode/AGENTS.md'))- expect(lines.length).toBeGreaterThan(0)- for (const line of lines) {- // The untrusted half is bound to a single-quoted shell variable; it never appears raw- // inside the double-quoted expansion, where `$`/backticks would still be live.- expect(line).toContain(`NT_H='${HOSTILE}'`)- expect(line).toContain('"${XDG_CONFIG_HOME:-$NT_H/.config}/opencode/AGENTS.md"')- expect(line).not.toContain(`{XDG_CONFIG_HOME:-${HOSTILE}`)- }- })- }+ it('the legacy-block clean-up routes the opencode target through that safe form', async () => {+ const { rh, conn: c, runs } = harness()+ await rh['stripLegacyInstructionBlocks'](c, '/s.sock', HOSTILE)+ const lines = runs.map((r) => r.args[r.args.length - 1]).filter((l) => l.includes('opencode/AGENTS.md'))+ expect(lines.length).toBeGreaterThan(0)+ for (const line of lines) {+ // The untrusted half is bound to a single-quoted shell variable; it never appears raw+ // inside the double-quoted expansion, where `$`/backticks would still be live.+ expect(line).toContain(`NT_H='${HOSTILE}'`)+ expect(line).toContain('"${XDG_CONFIG_HOME:-$NT_H/.config}/opencode/AGENTS.md"')+ expect(line).not.toContain(`{XDG_CONFIG_HOME:-${HOSTILE}`)+ }+ })})describe('RemoteHooks.ensureFullscreenTui — the fourth $(dirname …) site', () => {@@ -559,7 +555,7 @@ describe('RemoteHooks.ensureFullscreenTui', () => {if (isReadOf(args, target)) return { code: 0, stdout: `${target}\n` + JSON.stringify({ hooks: { Stop: [] } }) }return { code: 0, stdout: '' }})- const rh = new RemoteHooks({ run })+ const rh = new RemoteHooks({ run }, allRemote)await rh.ensureFullscreenTui(conn, '/s.sock', '/home/u')const write = calls.find((c) => isWriteTo(c.args, target))expect(write).toBeTruthy()@@ -574,7 +570,7 @@ describe('RemoteHooks.ensureFullscreenTui', () => {if (isReadOf(args, target)) return { code: 0, stdout: `${target}\n` + JSON.stringify({ tui: 'default' }) }return { code: 0, stdout: '' }})- const rh = new RemoteHooks({ run })+ const rh = new RemoteHooks({ run }, allRemote)await rh.ensureFullscreenTui(conn, '/s.sock', '/home/u')expect(calls.some((c) => isWriteTo(c.args, target))).toBe(false)})@@ -586,7 +582,7 @@ describe('RemoteHooks.ensureFullscreenTui', () => {calls.push({ args, stdin })return { code: 0, stdout: `${target}\n{}` } // resolved target header + empty settings})- const rh = new RemoteHooks({ run })+ const rh = new RemoteHooks({ run }, allRemote)await rh.ensureFullscreenTuiInAccountDir(conn, '/s.sock', '/home/u', 'acc-1')expect(calls.some((c) => isWriteTo(c.args, target))).toBe(true)expect(calls.some((c) => (c.stdin ?? '').includes('"tui": "fullscreen"'))).toBe(true)@@ -611,63 +607,43 @@ describe('RemoteHooks.teardown', () => {describe('RemoteHooks.installCanvasControl', () => {const isWriteTo = (args: string[], p: string) => writesTo(args.join(' '), p)- it('writes an executable shim + the skill, and merges every instruction-file block', async () => {+ it('writes an executable shim + the skill in claude\'s dir and ~/.agents/skills — and NO instruction-file block (#744)', async () => {const { rh, calls } = harness()await rh.installCanvasControl(conn, '/s.sock', '/home/u')const joined = calls.map((c) => c.args.join(' '))- // The shim must land executable: the skill tells the agent to run it via `sh <path>`, but the- // instruction blocks and a user's own habits may exec it directly.+ // The shim must land executable: the skill tells the agent to run it via `sh <path>`, but a+ // user's own habits may exec it directly.const shimWrite = joined.find((j) => writesTo(j, '/home/u/.nodeterm/nodeterm.sh')) ?? ''expect(shimWrite).toContain(`chmod 755 ${tempFor(shimWrite, '/home/u/.nodeterm/nodeterm.sh')}`)- // It is the POSIX shim, NOT the retired Electron-as-Node one — nothing may reference a local- // interpreter path, which is exactly what made the old CLI unusable off the desktop.+ // It is the POSIX shim, NOT the retired Electron-as-Node one.const shim = calls.find((c) => isWriteTo(c.args, '/home/u/.nodeterm/nodeterm.sh'))?.stdin ?? ''expect(shim).toContain('#!/bin/sh')expect(shim).toContain('--unix-socket')expect(shim).not.toContain('ELECTRON_RUN_AS_NODE')- // The skill points at the REMOTE shim path (a desktop path would resolve to nothing here).- const skill = calls.find((c) => isWriteTo(c.args, '/home/u/.claude/skills/manage-nodeterm-canvas/SKILL.md'))?.stdin ?? ''- expect(skill).toContain('name: manage-nodeterm-canvas')- expect(skill).toContain('sh "/home/u/.nodeterm/nodeterm.sh"')- // codex/gemini get the marker block; opencode's path is expanded by the REMOTE shell, since- // the desktop's XDG_CONFIG_HOME says nothing about the host's.- expect(joined.some((j) => j.includes('/home/u/.codex/AGENTS.md'))).toBe(true)- expect(joined.some((j) => j.includes('/home/u/.gemini/GEMINI.md'))).toBe(true)- // …with the remote $HOME bound to a shell variable first, so it is never live inside the- // double-quoted expansion (see "the opencode XDG path expression" below).- expect(joined.some((j) => j.includes(`NT_H='/home/u'`))).toBe(true)- expect(joined.some((j) => j.includes('${XDG_CONFIG_HOME:-$NT_H/.config}/opencode/AGENTS.md'))).toBe(true)- expect(joined.some((j) => j.includes('/home/u/.copilot/copilot-instructions.md'))).toBe(true)- expect(calls.some((c) => (c.stdin ?? '').includes('nodeterm:manage-canvas:start'))).toBe(true)+ // The skill points at the REMOTE shim path (a desktop path would resolve to nothing here), in+ // claude's dir AND in ~/.agents/skills, which codex/gemini/copilot/opencode/grok all read.+ for (const dir of ['/home/u/.claude/skills', '/home/u/.agents/skills']) {+ const skill = calls.find((c) => isWriteTo(c.args, `${dir}/manage-nodeterm-canvas/SKILL.md`))?.stdin ?? ''+ expect(skill, dir).toContain('name: manage-nodeterm-canvas')+ expect(skill, dir).toContain('sh "/home/u/.nodeterm/nodeterm.sh"')+ }+ // Nothing touches a global instruction file any more (they crowded codex's 32 KiB budget).+ expect(joined.some((j) => /AGENTS\.md|GEMINI\.md|copilot-instructions\.md/.test(j))).toBe(false)+ expect(calls.some((c) => (c.stdin ?? '').includes('nodeterm:manage-canvas:start'))).toBe(false)// no unexpanded tilde survives in any remote path.expect(joined.some((j) => j.includes('~/'))).toBe(false)})- it('preserves existing instruction-file content and rewrites its own block only', async () => {- const existing = '# my notes\n\n<!-- nodeterm:manage-canvas:start -->\nSTALE\n<!-- nodeterm:manage-canvas:end -->\n'- const { rh, calls } = harness({ responses: { '.codex/AGENTS.md': existing } })- await rh.installCanvasControl(conn, '/s.sock', '/home/u')- const write = calls.find((c) => isWriteTo(c.args, '/home/u/.codex/AGENTS.md'))- // The transaction's stdin is the snapshot it read, then the merged file.- expect(write?.stdin?.startsWith(existing)).toBe(true)- const merged = write!.stdin!.slice(existing.length)- expect(merged).toContain('# my notes')- expect(merged).not.toContain('STALE')- expect(merged).toContain('nodeterm canvas')- })-- it('skips the write when the block is already current (idempotent reconnects)', async () => {- // A connect happens on every app start and every reconnect; rewriting an unchanged file each- // time would churn the user's instruction files (and their mtimes) for nothing.- const first = harness()- await first.rh.installCanvasControl(conn, '/s.sock', '/home/u')- // A missing file: the snapshot part of stdin is empty, so stdin IS the merged file.- const merged = first.calls.find((c) => isWriteTo(c.args, '/home/u/.gemini/GEMINI.md'))?.stdin ?? ''- expect(merged).toBeTruthy()+ it('writes only the dirs of agents this host consented to — nothing at all for an unanswered host', async () => {+ const onlyCodex = harness({ plan: { install: new Set(['codex']), remove: new Set(), decided: true } })+ await onlyCodex.rh.installCanvasControl(conn, '/s.sock', '/home/u')+ const a = onlyCodex.calls.map((c) => c.args.join(' '))+ expect(a.some((j) => writesTo(j, '/home/u/.agents/skills/manage-nodeterm-canvas/SKILL.md'))).toBe(true)+ expect(a.some((j) => j.includes('/home/u/.claude/'))).toBe(false)- const { rh, calls } = harness({ responses: { '.gemini/GEMINI.md': merged } })- await rh.installCanvasControl(conn, '/s.sock', '/home/u')- expect(calls.some((c) => isWriteTo(c.args, '/home/u/.gemini/GEMINI.md'))).toBe(false)+ const none = harness({ plan: { install: new Set(), remove: new Set(), decided: false } })+ await none.rh.installCanvasControl(conn, '/s.sock', '/home/u')+ expect(none.calls).toHaveLength(0)})it('installs the skill into a remote managed-account config dir', async () => {@@ -685,14 +661,14 @@ describe('RemoteHooks.installCanvasControl', () => {const run = vi.fn(async () => {throw new Error('ssh died')})- await expect(new RemoteHooks({ run }).installCanvasControl(conn, '/s.sock', '/home/u')).resolves.toBeUndefined()+ await expect(new RemoteHooks({ run }, allRemote).installCanvasControl(conn, '/s.sock', '/home/u')).resolves.toBeUndefined()})})describe('RemoteHooks.installContextLink', () => {const isWriteTo = (args: string[], p: string) => writesTo(args.join(' '), p)- it('writes an executable shim + the skill, and merges the instruction blocks', async () => {+ it('writes an executable shim + the skill in claude\'s dir and ~/.agents/skills, no block', async () => {const { rh, calls } = harness()await rh.installContextLink(conn, '/s.sock', '/home/u')const joined = calls.map((c) => c.args.join(' '))@@ -705,26 +681,15 @@ describe('RemoteHooks.installContextLink', () => {expect(shim).toContain('/context-link/')expect(shim).toContain('--unix-socket')expect(shim).not.toContain('ELECTRON_RUN_AS_NODE')- const skill = calls.find((c) => isWriteTo(c.args, '/home/u/.claude/skills/get-linked-context/SKILL.md'))?.stdin ?? ''- expect(skill).toContain('name: get-linked-context')- expect(skill).toContain('sh "/home/u/.nodeterm/context.sh"')- expect(calls.some((c) => (c.stdin ?? '').includes('nodeterm:get-linked-context:start'))).toBe(true)+ for (const dir of ['/home/u/.claude/skills', '/home/u/.agents/skills']) {+ const skill = calls.find((c) => isWriteTo(c.args, `${dir}/get-linked-context/SKILL.md`))?.stdin ?? ''+ expect(skill, dir).toContain('name: get-linked-context')+ expect(skill, dir).toContain('sh "/home/u/.nodeterm/context.sh"')+ }+ expect(calls.some((c) => (c.stdin ?? '').includes('nodeterm:get-linked-context:start'))).toBe(false)expect(joined.some((j) => j.includes('~/'))).toBe(false)})- it('leaves the canvas-control block in the same file alone', async () => {- // Both features merge into ~/.codex/AGENTS.md under DIFFERENT markers. Installing one must- // not evict the other, or every connect would leave the host with exactly one of the two.- const existing =- '<!-- nodeterm:manage-canvas:start -->\nCANVAS BLOCK\n<!-- nodeterm:manage-canvas:end -->\n'- const { rh, calls } = harness({ responses: { '.codex/AGENTS.md': existing } })- await rh.installContextLink(conn, '/s.sock', '/home/u')- const write = calls.find((c) => isWriteTo(c.args, '/home/u/.codex/AGENTS.md'))- const merged = write!.stdin!.slice(existing.length)- expect(merged).toContain('CANVAS BLOCK')- expect(merged).toContain('nodeterm:get-linked-context:start')- })-it('installs the skill into a remote managed-account config dir', async () => {const { rh, calls } = harness()await rh.installContextLinkSkillIntoAccountDir(conn, '/s.sock', '/home/u', 'acc-1')@@ -737,7 +702,7 @@ describe('RemoteHooks.installContextLink', () => {const run = vi.fn(async () => {throw new Error('ssh died')})- await expect(new RemoteHooks({ run }).installContextLink(conn, '/s.sock', '/home/u')).resolves.toBeUndefined()+ await expect(new RemoteHooks({ run }, allRemote).installContextLink(conn, '/s.sock', '/home/u')).resolves.toBeUndefined()})})@@ -758,7 +723,7 @@ describe('RemoteHooks.writeNodeTokens', () => {if (opts.throws) throw new Error('ssh died')return { code: opts.code ?? 0, stdout: '' }})- return { rh: new RemoteHooks({ run }), calls, run }+ return { rh: new RemoteHooks({ run }, allRemote), calls, run }}it('writes every token through STDIN — a credential never rides an ssh command line', async () => {@@ -841,7 +806,7 @@ describe('RemoteHooks.writeNodeTokens', () => {if (cmd.includes('node-1')) throw new Error('EACCES')return { code: 0, stdout: '' }})- await new RemoteHooks({ run }).writeNodeTokens(conn, '/s.sock', '/home/u', ['node-1', 'node-2'], mint)+ await new RemoteHooks({ run }, allRemote).writeNodeTokens(conn, '/s.sock', '/home/u', ['node-1', 'node-2'], mint)expect(calls.some((c) => c.includes("node-tokens/node-2'"))).toBe(true)})@@ -890,7 +855,7 @@ describe('RemoteHooks.writeNodeTokens', () => {code: args.join(' ').includes('cat >') ? 1 : 0,stdout: ''}))- await new RemoteHooks({ run }).writeNodeTokens(conn, '/s.sock', '/home/u', ['node-1'], mint)+ await new RemoteHooks({ run }, allRemote).writeNodeTokens(conn, '/s.sock', '/home/u', ['node-1'], mint)expect(forget).toHaveBeenCalledWith('node-1')forget.mockRestore()})@@ -901,7 +866,7 @@ describe('RemoteHooks.writeNodeTokens', () => {if (args.join(' ').includes('cat >')) throw new Error('EACCES')return { code: 0, stdout: '' }})- await new RemoteHooks({ run }).writeNodeTokens(conn, '/s.sock', '/home/u', ['node-1'], mint)+ await new RemoteHooks({ run }, allRemote).writeNodeTokens(conn, '/s.sock', '/home/u', ['node-1'], mint)expect(forget).toHaveBeenCalledWith('node-1')forget.mockRestore()})@@ -976,7 +941,7 @@ describe('RemoteHooks.setup — install concurrency', () => {return { code: 0, stdout: '' }})return {- rh: new RemoteHooks({ run }),+ rh: new RemoteHooks({ run }, allRemote),calls,releaseAll: () => {for (const g of gates.splice(0)) g()diff --git a/src/main/remote-ssh/remote-hooks.ts b/src/main/remote-ssh/remote-hooks.tsindex 21637e25e..1e0b800c5 100644--- a/src/main/remote-ssh/remote-hooks.ts+++ b/src/main/remote-ssh/remote-hooks.ts@@ -15,6 +15,7 @@ import { GROK_HOOK_FILE, REMOTE_GROK_HOME_PROBE, resolveReportedGrokHome } fromimport { isSafeNodeId, isSafeRemoteHome } from '../../core/remote-safety'import { hookServer } from '../../core/agents/hook-server'import {+ stripRemoteSettingsFile,updateRemoteSettingsFile,updateRemoteSettingsFileResult,updateRemoteTextFile,@@ -44,30 +45,19 @@ import {* hosts is a later slice; when it lands, this becomes the REMOTE host's root, not null.*/const REMOTE_IDENTITY_ROOT = null-import { buildManagedHookCommand, mergeManagedHook, type HookSettings } from '../../core/agents/hooks/install-helper'+import { buildManagedHookCommand, mergeManagedHook, stripManagedHook, type HookSettings } from '../../core/agents/hooks/install-helper'import {+ stripCodexManagedHooks,buildCodexHooksAndTrust,buildManagedCommand as buildCodexManagedCommand,type HooksConfig as CodexHooksConfig} from '../../core/agents/hooks/codex'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 { CANVAS_CONTROL_MARKERS, CONTROL_SHIM_SCRIPT, buildCanvasSkillBody } from '../../core/canvas-control-core'+import { CONTEXT_SHIM_SCRIPT, LINKED_CONTEXT_MARKERS, buildContextLinkSkillBody } from '../../core/context-link-core'+import { canContextLink, canControlCanvas } from '../../shared/agents/config'+import { stripMarkerBlock } from '../../core/integration-files'import { isSafeAccountId } from '../../core/claude-accounts-core'import { formatCksum, posixCksum } from '../../core/remote-ssh/posix-cksum'import { posixQuote, type SshConnection } from '../../shared/ssh'@@ -118,6 +108,15 @@ export function openCodeInstructionsTarget(remoteHome: string): { prelude: strin}}+/** What nodeterm may install on one SSH host, and what it must remove there (issue #744). */+export interface RemoteIntegrationPlan {+ install: ReadonlySet<string>+ remove: ReadonlySet<string>+ /** The host has an answer (enabled or declined). Undecided ⇒ install nothing, remove nothing. */+ decided: boolean+}+export const NO_REMOTE_INTEGRATION: RemoteIntegrationPlan = { install: new Set(), remove: new Set(), decided: false }+export interface RemoteRunner {/** Run one ssh child command (over the master); optional stdin written to the child. */run: (args: string[], stdin?: string) => Promise<{ code: number; stdout: string }>@@ -141,8 +140,9 @@ const AGENT_TARGETS: { agentId: string; config: string; events: readonly Managed/** 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']+/** Every instruction file an older build merged a discovery block into; stripped once per host+ * per run when the host has an answer (`stripLegacyInstructionBlocks`). */+const LEGACY_INSTRUCTION_TARGETS: readonly InstructionTarget[] = ['codex', 'gemini', 'copilot', 'opencode']/*** One thing the agent tools put on a host, as DATA. The installers write these and the freshness@@ -173,40 +173,56 @@ 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[] {+/**+ * Where the skills go on a HOST, per agent (issue #744 — skills replaced the ~17 KB instruction+ * blocks that crowded codex's AGENTS.md budget). Claude reads `<config dir>/skills`; every other+ * agent here reads `~/.agents/skills` WHATEVER its relocation env var says (measured 2026-10-03:+ * codex 0.156.1 `debug prompt-input`, gemini 0.62.0 `skills list`, opencode 1.18.33 `debug skill`,+ * grok 1.0.44 `inspect --json`; copilot 1.0.89 documents it in `copilot skill --help`). One+ * env-independent dir is what a host we cannot introspect cheaply needs: `$COPILOT_HOME`,+ * `$GROK_HOME` and `$XDG_CONFIG_HOME` on the host say nothing about it.+ */+const AGENTS_SKILLS_AGENTS: readonly string[] = ['codex', 'gemini', 'copilot', 'opencode', 'grok']+const claudeSkillsRoot = (home: string) => `${home}/.claude`+const agentsSkillsRoot = (home: string) => `${home}/.agents`++/** The config roots (each gets `skills/<name>/SKILL.md`) one feature's skill goes into, for the+ * agents this host may integrate with and that have the feature. */+function skillRoots(home: string, agents: ReadonlySet<string>, capable: (id: string) => boolean): string[] {+ const roots: string[] = []+ if (agents.has('claude') && capable('claude')) roots.push(claudeSkillsRoot(home))+ if (AGENTS_SKILLS_AGENTS.some((a) => agents.has(a) && capable(a))) roots.push(agentsSkillsRoot(home))+ return roots+}++function canvasControlArtifacts(home: string, agents: ReadonlySet<string>): AgentToolArtifact[] {+ const roots = skillRoots(home, agents, canControlCanvas)+ if (!roots.length) return []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 => ({+ ...roots.map((r): AgentToolArtifact => ({...g,- kind: 'block',- target,- block,- framed: frameCanvasControlBlock(block),- markers: CANVAS_CONTROL_MARKERS,- merge: mergeCanvasControlBlock+ kind: 'file',+ path: skillFilePath(r, 'manage-nodeterm-canvas'),+ body: buildCanvasSkillBody(shim)}))]}-function contextLinkArtifacts(home: string): AgentToolArtifact[] {+function contextLinkArtifacts(home: string, agents: ReadonlySet<string>): AgentToolArtifact[] {+ const roots = skillRoots(home, agents, canContextLink)+ if (!roots.length) return []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 => ({+ ...roots.map((r): AgentToolArtifact => ({...g,- kind: 'block',- target,- block,- framed: frameInstructionsBlock(block),- markers: LINKED_CONTEXT_MARKERS,- merge: mergeInstructionsBlock+ kind: 'file',+ path: skillFilePath(r, 'get-linked-context'),+ body: buildContextLinkSkillBody(shim)}))]}@@ -249,7 +265,30 @@ export class RemoteHooks {* 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) {}+ /** Hosts whose legacy instruction blocks this run already stripped (once per host per run). */+ private legacyStripped = new Set<string>()++ /**+ * `integrations` answers, per connection, what nodeterm may install on that HOST and what it must+ * remove there (issue #744, `remoteIntegrationPlan`). REQUIRED: a RemoteHooks built without an+ * answer would install by omission. `NO_REMOTE_INTEGRATION` is the fail-closed answer.+ */+ constructor(+ private r: RemoteRunner,+ private integrations: (conn: SshConnection) => RemoteIntegrationPlan,+ /** Where we record the bytes of each skill we wrote on a host, so a later decline can remove a+ * file an OLDER build wrote (not just this build's exact bytes). Optional. */+ private receipts?: { get(key: string): string | undefined; set(key: string, v: string | null): void }+ ) {}++ /** The plan for one connection; a provider that throws installs and removes nothing. */+ planFor(conn: SshConnection): RemoteIntegrationPlan {+ try {+ return this.integrations(conn)+ } catch {+ return NO_REMOTE_INTEGRATION+ }+ }/*** Is THIS project's reverse hook tunnel still answering? (issue #735)@@ -413,26 +452,186 @@ export class RemoteHooks {// the time we get here, so ONE agent's installer failing must not discard a working setup for// every other agent. Each installer already catches its own errors, so today nothing rejects —// this is the guard for the next one that forgets to.- const installs = await Promise.allSettled([- ...AGENT_TARGETS.map((t) => this.installJsonAgentRemote(conn, controlPath, home, remoteDir, t)),- // codex: hooks.json merge + config.toml trust (its own shape — not a JSON-settings agent).- this.installCodexRemote(conn, controlPath, home, remoteDir),- // grok: our own file in its hooks DIRECTORY, under the HOST's $GROK_HOME.- this.installGrokRemote(conn, controlPath, home, remoteDir),- // copilot: its own file/grammar under the HOST's $COPILOT_HOME hooks directory.- this.installCopilotRemote(conn, controlPath, home, remoteDir)- ])- for (const r of installs) {- if (r.status === 'rejected') {- console.warn('[remote-hooks] one agent hook install failed; the others are installed', r.reason)- }- }+ await this.installAgentHooks(conn, controlPath, home)return { endpointPath: endpoint }} catch {return null // fail-open: agent runs without hooks}}+ /**+ * Install the managed status hook for every agent this host may integrate with (the consent plan+ * — nothing for an agent the user has not enabled for this host). CONCURRENT, because the+ * installers are independent of each other.+ *+ * Each one writes its own script under `<remoteDir>/agent-hooks/` and merges its own agent's+ * config file; no two touch the same remote path, and the only shared statement is an idempotent+ * `mkdir -p` of that one directory. Run serially they were ~16 remote round trips in a row —+ * MEASURED at 3.54 s on a 50 ms-RTT link, which is wall-clock every terminal of a switched-to+ * project used to wait through. The `SshChildGate` (cap 6 per ControlMaster) is what makes the+ * fan-out safe against a stock host's `MaxSessions`.+ *+ * ORDER IS STILL LOAD-BEARING in `setup()`: the tunnel must be verified and the endpoint file+ * written first, because that file is what every one of these hooks POSTs through.+ *+ * `allSettled`, not `all`: ONE agent's installer failing must not discard the others.+ */+ async installAgentHooks(conn: SshConnection, controlPath: string, home: string): Promise<void> {+ const plan = this.planFor(conn)+ if (!plan.install.size) return+ const remoteDir = `${home}/.nodeterm`+ const installs = await Promise.allSettled([+ ...AGENT_TARGETS.filter((t) => plan.install.has(t.agentId)).map((t) =>+ this.installJsonAgentRemote(conn, controlPath, home, remoteDir, t)+ ),+ // codex: hooks.json merge + config.toml trust (its own shape — not a JSON-settings agent).+ ...(plan.install.has('codex') ? [this.installCodexRemote(conn, controlPath, home, remoteDir)] : []),+ // grok: our own file in its hooks DIRECTORY, under the HOST's $GROK_HOME.+ ...(plan.install.has('grok') ? [this.installGrokRemote(conn, controlPath, home, remoteDir)] : []),+ // copilot: its own file/grammar under the HOST's $COPILOT_HOME hooks directory.+ ...(plan.install.has('copilot') ? [this.installCopilotRemote(conn, controlPath, home, remoteDir)] : [])+ ])+ for (const r of installs) {+ if (r.status === 'rejected') {+ console.warn('[remote-hooks] one agent hook install failed; the others are installed', r.reason)+ }+ }+ }++ /**+ * Bring a host to its consent answer on the REMOVAL side: strip the legacy instruction blocks+ * older builds merged (once per host per run, for any answered host), and remove what we wrote+ * for every agent the plan removes — our hook entries (exact command match; the user's own hooks+ * survive), our owned hook files, our hook scripts, and our skills (only a file whose bytes are+ * what this build writes or what we recorded writing; anything else is the user's and is kept and+ * reported). An unanswered host is left exactly as it is. Never throws.+ */+ async applyIntegrationRemovals(+ conn: SshConnection,+ controlPath: string,+ home: string,+ accountIds: readonly string[],+ receiptsArg?: { get(key: string): string | undefined; set(key: string, v: string | null): void }+ ): Promise<{ retained: string[] }> {+ const receipts = receiptsArg ?? this.receipts+ const retained: string[] = []+ const plan = this.planFor(conn)+ if (!plan.decided || !isSafeRemoteHome(home)) return { retained }+ try {+ const hostKey = `${conn.user}@${conn.host}:${conn.port ?? 22}\0${home}`+ if (!this.legacyStripped.has(hostKey)) {+ this.legacyStripped.add(hostKey)+ await this.stripLegacyInstructionBlocks(conn, controlPath, home)+ }+ if (!plan.remove.size) return { retained }+ const run = (cmd: string, stdin?: string) => this.r.run(childArgs(conn, controlPath, cmd), stdin)+ const remoteDir = `${home}/.nodeterm`+ const accounts = [...new Set(accountIds.filter(isSafeAccountId))]+ // Hooks in the JSON-settings agents (claude system + managed account dirs, gemini).+ for (const t of AGENT_TARGETS) {+ if (!plan.remove.has(t.agentId)) continue+ const files = [`${home}/${t.config}`]+ if (t.agentId === 'claude') for (const id of accounts) files.push(`${accountConfigDir(home, id)}/settings.json`)+ for (const f of files) {+ await stripRemoteSettingsFile(f, run, (cfg) => stripManagedHook(cfg as HookSettings, `${t.agentId}.sh`, t.events) as Record<string, unknown>)+ }+ }+ if (plan.remove.has('codex')) {+ await stripRemoteSettingsFile(`${home}/.codex/hooks.json`, run, (cfg) => (stripCodexManagedHooks(cfg as CodexHooksConfig) ?? cfg) as Record<string, unknown>)+ }+ // Files we own outright: grok's and copilot's hook configs, and our hook scripts.+ const owned: string[] = []+ if (plan.remove.has('grok')) {+ const { stdout } = await run(REMOTE_GROK_HOME_PROBE)+ const grokHome = resolveReportedGrokHome(stdout) ?? `${home}/.grok`+ owned.push(`${grokHome.replace(/\/$/, '')}/hooks/${GROK_HOOK_FILE}`)+ }+ if (plan.remove.has('copilot')) {+ const copilotHome = await this.resolveCopilotHome(conn, controlPath, home)+ owned.push(`${copilotHome.replace(/\/$/, '')}/hooks/${COPILOT_HOOK_FILE}`)+ }+ for (const a of plan.remove) owned.push(`${remoteDir}/agent-hooks/${a}.sh`)+ if (owned.length) await run(`rm -f -- ${owned.map(posixQuote).join(' ')}`)+ // Skills, by exact content.+ const keep = new Set(plan.install)+ const removeRoots: string[] = []+ if (!keep.has('claude')) {+ removeRoots.push(claudeSkillsRoot(home))+ for (const id of accounts) removeRoots.push(accountConfigDir(home, id))+ }+ if (!AGENTS_SKILLS_AGENTS.some((a) => keep.has(a))) removeRoots.push(agentsSkillsRoot(home))+ for (const root of removeRoots) {+ for (const [name, body] of [+ ['manage-nodeterm-canvas', buildCanvasSkillBody(canvasShimPath(home))],+ ['get-linked-context', buildContextLinkSkillBody(contextShimPath(home))]+ ] as const) {+ const file = skillFilePath(root, name)+ const receiptKey = `ssh:${conn.user}@${conn.host}:${file}`+ const sums = [formatCksum(posixCksum(Buffer.from(body, 'utf8')))]+ const rec = receipts?.get(receiptKey)+ if (rec) sums.push(rec)+ const verdict = await this.removeRemoteFileIfOurs(run, file, sums)+ if (verdict === 'retained') retained.push(file)+ if (verdict !== 'retained') receipts?.set(receiptKey, null)+ }+ }+ if (retained.length) {+ console.warn(`[remote-hooks] kept ${retained.length} file(s) on ${conn.user}@${conn.host} that were changed since nodeterm wrote them: ${retained.join(', ')}`)+ }+ } catch (e) {+ warnNotInstalled('the integration clean-up', e)+ }+ return { retained }+ }++ /** `rm` one regular file only when its POSIX cksum is one of `sums`; then drop its now-empty+ * directory. A link, a directory, or different bytes are left alone (`retained`). */+ private async removeRemoteFileIfOurs(+ run: (cmd: string, stdin?: string) => Promise<{ code: number; stdout: string }>,+ file: string,+ sums: readonly string[]+ ): Promise<'removed' | 'absent' | 'retained'> {+ const f = posixQuote(file)+ const cases = sums.map((x) => posixQuote(x)).join('|')+ const cmd =+ `if [ ! -e ${f} ] && [ ! -L ${f} ]; then echo ABSENT; ` ++ `elif [ -L ${f} ] || [ ! -f ${f} ]; then echo RETAINED; ` ++ `else s=$(cksum < ${f} | awk '{print $1" "$2}'); case "$s" in ${cases}) rm -f -- ${f} && rmdir -- "$(dirname -- ${f})" 2>/dev/null; echo REMOVED;; *) echo RETAINED;; esac; fi`+ const { stdout } = await run(cmd)+ const out = stdout.trim()+ return out.endsWith('REMOVED') ? 'removed' : out === 'ABSENT' ? 'absent' : 'retained'+ }++ /** Strip both legacy discovery blocks from every instruction file older builds merged them into+ * (~17 KB in codex's AGENTS.md, crowding its 32 KiB project-doc budget — #744). Writes only+ * when a block was there; an unreadable file is left alone. */+ private async stripLegacyInstructionBlocks(conn: SshConnection, controlPath: string, home: string): Promise<void> {+ const strip = (existing: string): string =>+ stripMarkerBlock(stripMarkerBlock(existing, CANVAS_CONTROL_MARKERS), LINKED_CONTEXT_MARKERS)+ for (const target of LEGACY_INSTRUCTION_TARGETS) {+ try {+ const t =+ target === 'copilot'+ ? { pathExpr: posixQuote(`${await this.resolveCopilotHome(conn, controlPath, home)}/copilot-instructions.md`) }+ : this.instructionTarget(home, target)+ await updateRemoteTextFile(+ { pathExpr: t.pathExpr, prelude: t.prelude ?? '', label: t.pathExpr },+ (cmd, stdin) => this.r.run(childArgs(conn, controlPath, cmd), stdin),+ (before) => {+ if (before === null) return null+ const next = strip(before)+ // The transaction never publishes an empty file; a file that held only our blocks keeps+ // one newline (it may be a dotfile link the user owns).+ return next === before ? null : next.trim() === '' ? '\n' : next+ },+ { createMode: '644' }+ )+ } catch (e) {+ warnNotInstalled(`the legacy ${target} instructions clean-up`, e)+ }+ }+ }+/*** Materialise this instance's per-node tokens ON THE HOST — `<home>/.nodeterm/node-tokens/<id>`,* 0600 in a 0700 dir, exactly the layout the endpoint file already advertises as@@ -756,6 +955,7 @@ export class RemoteHooks {remoteHome: string,accountId: string): Promise<void> {+ if (!this.planFor(conn).install.has('claude')) returntry {const remoteDir = `${remoteHome}/.nodeterm`const script = `${remoteDir}/agent-hooks/claude.sh`@@ -805,10 +1005,9 @@ 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> {- // 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), () =>+ // Skills in each consented agent's skills dir on the host (claude's own, `~/.agents/skills` for+ // the rest) — nothing for an agent the user has not enabled for this host.+ await this.applyAgentTools(conn, controlPath, remoteHome, canvasControlArtifacts(remoteHome, this.planFor(conn).install), () =>this.resolveCopilotHome(conn, controlPath, remoteHome))}@@ -824,6 +1023,7 @@ export class RemoteHooks {remoteHome: string,accountId: string): Promise<void> {+ if (!this.planFor(conn).install.has('claude')) returntry {const shim = `${remoteHome}/.nodeterm/nodeterm.sh`// Idempotently (re)write the shim: installCanvasControl may not have run (fail-open) yet.@@ -851,7 +1051,7 @@ export class RemoteHooks {* verified tunnel; fail-open per step.*/async installContextLink(conn: SshConnection, controlPath: string, remoteHome: string): Promise<void> {- await this.applyAgentTools(conn, controlPath, remoteHome, contextLinkArtifacts(remoteHome), () =>+ await this.applyAgentTools(conn, controlPath, remoteHome, contextLinkArtifacts(remoteHome, this.planFor(conn).install), () =>this.resolveCopilotHome(conn, controlPath, remoteHome))}@@ -863,6 +1063,7 @@ export class RemoteHooks {remoteHome: string,accountId: string): Promise<void> {+ if (!this.planFor(conn).install.has('claude')) returntry {const shim = `${remoteHome}/.nodeterm/context.sh`await this.writeRemoteShim(conn, controlPath, shim, CONTEXT_SHIM_SCRIPT)@@ -936,6 +1137,9 @@ export class RemoteHooks {...(a.gateDir ? { requireDir: a.gateDir } : {})})written.push(a)+ if (a.path.endsWith('/SKILL.md')) {+ this.receipts?.set(`ssh:${conn.user}@${conn.host}:${a.path}`, formatCksum(posixCksum(Buffer.from(a.body, 'utf8'))))+ }} catch (e) {// The account was removed between the probe and this write: nothing to keep current.if (!(a.gateDir && e instanceof RemoteWriteError && e.code === REMOTE_WRITE_NO_DIR)) throw e@@ -997,7 +1201,11 @@ export class RemoteHooks {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)+ const install = this.planFor(conn).install+ // A managed account's skills follow the claude consent for this host.+ const planned = this.agentToolsPlan(remoteHome, install.has('claude') ? accounts : [], install)+ // Nothing consented for this host ⇒ nothing to keep current (and nothing to probe).+ if (!planned.plan.length) return 'skipped'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)@@ -1014,14 +1222,15 @@ export class RemoteHooks {private agentToolsPlan(remoteHome: string,- accounts: readonly string[]+ accounts: readonly string[],+ install: ReadonlySet<string>): { plan: AgentToolArtifact[]; expected: string[]; setId: string } {- const cacheKey = [remoteHome, ...accounts].join('\0')+ const cacheKey = [remoteHome, [...install].sort().join(','), ...accounts].join('\0')const cached = this.agentToolsPlans.get(cacheKey)if (cached) return cachedconst plan = [- ...canvasControlArtifacts(remoteHome),- ...contextLinkArtifacts(remoteHome),+ ...canvasControlArtifacts(remoteHome, install),+ ...contextLinkArtifacts(remoteHome, install),...accounts.flatMap((id) => accountSkillArtifacts(remoteHome, id))]const expected = plan.map((a) => formatCksum(posixCksum(Buffer.from(a.kind === 'file' ? a.body : a.framed, 'utf8'))))@@ -1196,6 +1405,7 @@ export class RemoteHooks {* so the path is absolute (a literal `~` would not expand). Fail-open.*/async ensureFullscreenTui(conn: SshConnection, controlPath: string, remoteHome: string): Promise<void> {+ if (!this.planFor(conn).install.has('claude')) returnawait this.ensureFullscreenTuiAt(conn, controlPath, `${remoteHome}/.claude/settings.json`)}@@ -1206,6 +1416,7 @@ export class RemoteHooks {remoteHome: string,accountId: string): Promise<void> {+ if (!this.planFor(conn).install.has('claude')) returnconst config = `${remoteHome}/.nodeterm/claude-accounts/${accountId}/settings.json`await this.ensureFullscreenTuiAt(conn, controlPath, config)}diff --git a/src/main/remote-ssh/remote-integration-consent.test.ts b/src/main/remote-ssh/remote-integration-consent.test.tsnew file mode 100644index 000000000..9cb7cf736--- /dev/null+++ b/src/main/remote-ssh/remote-integration-consent.test.ts@@ -0,0 +1,124 @@+// Agent-integration consent on an SSH HOST (issue #744), run for real under /bin/sh against a fake+// host $HOME: an unanswered host is never touched, a declined host loses exactly what nodeterm+// wrote there (a file the user changed is kept and reported), and a host the user keeps has its+// older builds' instruction blocks stripped.+import { spawnSync } from 'child_process'+import { existsSync, mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'fs'+import { tmpdir } from 'os'+import path from 'path'+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'+import { INTEGRATION_AGENT_IDS } from '../../shared/agent-integrations'+import { frameCanvasControlBlock } from '../../core/canvas-control-core'+import { RemoteHooks, type RemoteIntegrationPlan, type RemoteRunner } from './remote-hooks'++const conn = { host: 'fixture', user: 'fixture' }+let home: string+beforeEach(() => {+ home = mkdtempSync(path.join(tmpdir(), 'nt-remote-consent-'))+ vi.spyOn(console, 'warn').mockImplementation(() => {})+ vi.spyOn(console, 'info').mockImplementation(() => {})+})+afterEach(() => {+ vi.restoreAllMocks()+ rmSync(home, { recursive: true, force: true })+})++function hostRunner(): RemoteRunner & { calls: string[] } {+ const calls: string[] = []+ return {+ calls,+ run: async (args, stdin) => {+ const command = args.at(-1)!+ calls.push(command)+ const r = spawnSync('/bin/sh', ['-c', command], {+ cwd: home,+ env: { PATH: process.env.PATH ?? '/usr/bin:/bin', HOME: home },+ input: stdin,+ encoding: 'utf8'+ })+ if (r.error) throw r.error+ return { code: r.status ?? 1, stdout: r.stdout }+ }+ }+}++const ALL = new Set<string>(INTEGRATION_AGENT_IDS)+const plan = (install: string[], remove: string[], decided = true): RemoteIntegrationPlan => ({+ install: new Set(install),+ remove: new Set(remove),+ decided+})+const read = (rel: string) => readFileSync(path.join(home, rel), 'utf8')+const has = (rel: string) => existsSync(path.join(home, rel))++/** A host as an enabled nodeterm leaves it: every agent's hook + both skills in both dirs. */+async function enabledHost(runner: RemoteRunner): Promise<void> {+ const rh = new RemoteHooks(runner, () => plan([...ALL], []))+ await rh.installAgentHooks(conn, '/fixture.sock', home)+ await rh.installAgentTools(conn, '/fixture.sock', home)+}++describe.skipIf(process.platform === 'win32')('RemoteHooks.applyIntegrationRemovals (real /bin/sh)', () => {+ it('an unanswered host is left exactly as it is — not one ssh command', async () => {+ const runner = hostRunner()+ const rh = new RemoteHooks(runner, () => plan([], [], false))+ await rh.applyIntegrationRemovals(conn, '/fixture.sock', home, [])+ expect(runner.calls).toEqual([])+ })++ it('a declined host loses our hooks, owned files, scripts and skills — the user\'s own hook and edited skill stay', async () => {+ const setup = hostRunner()+ await enabledHost(setup)+ expect(read('.claude/settings.json')).toContain('agent-hooks/claude.sh')+ expect(has('.agents/skills/manage-nodeterm-canvas/SKILL.md')).toBe(true)+ // The user's own hook beside ours, and an edit to one of our skills.+ const cfg = JSON.parse(read('.claude/settings.json')) as { hooks: Record<string, unknown[]> }+ cfg.hooks.Stop.push({ hooks: [{ type: 'command', command: 'my-own-hook' }] })+ writeFileSync(path.join(home, '.claude/settings.json'), JSON.stringify(cfg))+ const edited = '.agents/skills/get-linked-context/SKILL.md'+ writeFileSync(path.join(home, edited), `${read(edited)}\nmy note\n`)++ const rh = new RemoteHooks(hostRunner(), () => plan([], [...ALL]))+ const { retained } = await rh.applyIntegrationRemovals(conn, '/fixture.sock', home, [])++ const claude = read('.claude/settings.json')+ expect(claude).not.toContain('agent-hooks/claude.sh')+ expect(claude).toContain('my-own-hook')+ expect(read('.gemini/settings.json')).not.toContain('agent-hooks/gemini.sh')+ expect(read('.codex/hooks.json')).not.toContain('agent-hooks/codex.sh')+ expect(has('.grok/hooks/nodeterm-status.json')).toBe(false)+ expect(has('.copilot/hooks/nodeterm-status.json')).toBe(false)+ for (const a of ['claude', 'gemini', 'codex', 'grok', 'copilot']) expect(has(`.nodeterm/agent-hooks/${a}.sh`), a).toBe(false)+ expect(has('.claude/skills/manage-nodeterm-canvas')).toBe(false)+ expect(has('.claude/skills/get-linked-context')).toBe(false)+ expect(has('.agents/skills/manage-nodeterm-canvas')).toBe(false)+ expect(has(edited)).toBe(true)+ expect(retained).toEqual([path.join(home, edited)])+ })++ it('a removal never creates a config file that was not there', async () => {+ const rh = new RemoteHooks(hostRunner(), () => plan([], [...ALL]))+ await rh.applyIntegrationRemovals(conn, '/fixture.sock', home, ['acc-1'])+ for (const f of ['.claude/settings.json', '.gemini/settings.json', '.codex/hooks.json', '.codex/AGENTS.md']) {+ expect(has(f), f).toBe(false)+ }+ })++ it('declining ONE agent on a kept host removes only that agent; the shared ~/.agents skills stay for the others', async () => {+ await enabledHost(hostRunner())+ const rh = new RemoteHooks(hostRunner(), () => plan(['claude', 'gemini'], ['codex']))+ await rh.applyIntegrationRemovals(conn, '/fixture.sock', home, [])+ expect(read('.codex/hooks.json')).not.toContain('agent-hooks/codex.sh')+ expect(read('.claude/settings.json')).toContain('agent-hooks/claude.sh')+ expect(has('.agents/skills/manage-nodeterm-canvas/SKILL.md')).toBe(true)+ expect(has('.claude/skills/manage-nodeterm-canvas/SKILL.md')).toBe(true)+ })++ it("an answered host has older builds' instruction blocks stripped, keeping the user's text", async () => {+ mkdirSync(path.join(home, '.codex'), { recursive: true })+ writeFileSync(path.join(home, '.codex/AGENTS.md'), `# mine\n\n${frameCanvasControlBlock('OLD 17 KB')}\n`)+ const rh = new RemoteHooks(hostRunner(), () => plan(['codex'], []))+ await rh.applyIntegrationRemovals(conn, '/fixture.sock', home, [])+ expect(read('.codex/AGENTS.md')).toBe('# mine\n')+ })+})diff --git a/src/main/remote-ssh/remote-settings-preservation.test.ts b/src/main/remote-ssh/remote-settings-preservation.test.tsindex ae852004c..1901a2ec6 100644--- a/src/main/remote-ssh/remote-settings-preservation.test.ts+++ b/src/main/remote-ssh/remote-settings-preservation.test.ts@@ -1,3 +1,4 @@+import { allRemote } from './remote-hooks.test-plan'import { afterEach, beforeEach, describe, expect, it } from 'vitest'import { spawnSync } from 'child_process'import { mkdtempSync, mkdirSync, readFileSync, writeFileSync, rmSync } from 'fs'@@ -22,7 +23,7 @@ for (const account of [false, true]) {const result = spawnSync('/bin/sh', ['-c', command], { input: stdin, encoding: 'utf8' })if (result.error) throw result.errorreturn { code: result.status ?? 1, stdout: result.stdout }- } })+ } }, allRemote)if (account) await rh.installIntoAccountDir(conn, '/fixture.sock', home, 'acc')else await rh['installJsonAgentRemote'](conn, '/fixture.sock', home, `${home}/.nodeterm`, {agentId: 'claude', config: '.claude/settings.json', events: ['Stop']diff --git a/src/main/remote-ssh/remote-write-truncation.test.ts b/src/main/remote-ssh/remote-write-truncation.test.tsindex e335237f1..74a96be60 100644--- a/src/main/remote-ssh/remote-write-truncation.test.ts+++ b/src/main/remote-ssh/remote-write-truncation.test.ts@@ -13,6 +13,7 @@//// The `cut` runner below is that failure: every command that carries a body gets NO body — the// host sees stdin at EOF, exactly as when the channel dies first. Read commands run untouched.+import { allRemote } from './remote-hooks.test-plan'import { execFileSync, spawn, spawnSync } from 'child_process'import {chmodSync,@@ -122,7 +123,7 @@ const warned = (needle: string) =>describe.skipIf(process.platform === 'win32')('remote writes never leave a truncated file (real /bin/sh)', () => {it('a normal connect lands both shims whole, executable, with no temp left behind', async () => {- const rh = new RemoteHooks(hostRunner('deliver'))+ const rh = new RemoteHooks(hostRunner('deliver'), allRemote)await rh.installCanvasControl(conn, '/fixture.sock', home)await rh.installContextLink(conn, '/fixture.sock', home)@@ -131,10 +132,10 @@ describe.skipIf(process.platform === 'win32')('remote writes never leave a truncexpect(modeOf('.nodeterm/nodeterm.sh')).toBe(0o755)expect(modeOf('.nodeterm/context.sh')).toBe(0o755)expect(read('.claude/skills/manage-nodeterm-canvas/SKILL.md')).toContain('name: manage-nodeterm-canvas')- expect(read('.codex/AGENTS.md')).toContain('nodeterm:manage-canvas:start')- expect(read('.codex/AGENTS.md')).toContain('nodeterm:get-linked-context:start')- // opencode's path is expanded by the host shell ($XDG_CONFIG_HOME unset → $HOME/.config).- expect(read('.config/opencode/AGENTS.md')).toContain('nodeterm:manage-canvas:start')+ expect(read('.agents/skills/manage-nodeterm-canvas/SKILL.md')).toContain('name: manage-nodeterm-canvas')+ expect(read('.agents/skills/get-linked-context/SKILL.md')).toContain('name: get-linked-context')+ // No global instruction file is created any more (#744).+ expect(existsSync(path.join(home, '.codex/AGENTS.md'))).toBe(false)expect(leftovers()).toEqual([])})@@ -143,7 +144,7 @@ describe.skipIf(process.platform === 'win32')('remote writes never leave a truncseed('.nodeterm/context.sh', '#!/bin/sh\necho previous-good-context\n', 0o755)seed('.claude/skills/manage-nodeterm-canvas/SKILL.md', 'previous skill\n')- const rh = new RemoteHooks(hostRunner('cut'))+ const rh = new RemoteHooks(hostRunner('cut'), allRemote)await rh.installCanvasControl(conn, '/fixture.sock', home)await rh.installContextLink(conn, '/fixture.sock', home)@@ -160,7 +161,7 @@ describe.skipIf(process.platform === 'win32')('remote writes never leave a truncit('a channel that dies before the body leaves every agent hook script intact', async () => {const agents = ['claude', 'gemini', 'codex', 'grok', 'copilot']for (const a of agents) seed(`.nodeterm/agent-hooks/${a}.sh`, `#!/bin/sh\n# previous ${a}\n`, 0o755)- const rh = new RemoteHooks(hostRunner('cut'))+ const rh = new RemoteHooks(hostRunner('cut'), allRemote)const remoteDir = `${home}/.nodeterm`await rh['installJsonAgentRemote'](conn, '/fixture.sock', home, remoteDir, {agentId: 'claude', config: '.claude/settings.json', events: ['Stop']@@ -184,25 +185,28 @@ describe.skipIf(process.platform === 'win32')('remote writes never leave a truncconst agents = '# my own agent notes\n'seed('.codex/config.toml', toml, 0o600)seed('.codex/hooks.json', hooks)- seed('.codex/AGENTS.md', agents)- seed('.gemini/GEMINI.md', agents)+ // An older build's block, which the clean-up strips — a write into the USER's file.+ const withBlock = `${agents}\n<!-- nodeterm:manage-canvas:start -->\nOLD\n<!-- nodeterm:manage-canvas:end -->\n`+ seed('.codex/AGENTS.md', withBlock)+ seed('.gemini/GEMINI.md', withBlock)seed('.claude/settings.json', '{"model":"opus"}')// Only the bodies bound for the user's files are lost; our own scripts and shims land, so the// installers really do reach — and publish nothing into — the user's files.const usersFile = /(config\.toml|hooks\.json|AGENTS\.md|GEMINI\.md|settings\.json)/- const rh = new RemoteHooks(hostRunner((command) => usersFile.test(command)))+ const rh = new RemoteHooks(hostRunner((command) => usersFile.test(command)), allRemote)await rh['installCodexRemote'](conn, '/fixture.sock', home, `${home}/.nodeterm`)await rh['installJsonAgentRemote'](conn, '/fixture.sock', home, `${home}/.nodeterm`, {agentId: 'claude', config: '.claude/settings.json', events: ['Stop']})await rh.installCanvasControl(conn, '/fixture.sock', home)await rh.installContextLink(conn, '/fixture.sock', home)+ await rh['stripLegacyInstructionBlocks'](conn, '/fixture.sock', home)expect(read('.codex/config.toml')).toBe(toml)expect(read('.codex/hooks.json')).toBe(hooks)- expect(read('.codex/AGENTS.md')).toBe(agents)- expect(read('.gemini/GEMINI.md')).toBe(agents)+ expect(read('.codex/AGENTS.md')).toBe(withBlock)+ expect(read('.gemini/GEMINI.md')).toBe(withBlock)expect(read('.claude/settings.json')).toBe('{"model":"opus"}')expect(modeOf('.codex/config.toml')).toBe(0o600)expect(leftovers()).toEqual([])@@ -223,12 +227,15 @@ describe.skipIf(process.platform === 'win32')('remote writes never leave a truncseed('.codex/config.toml', toml, 0o600)seed('.codex/hooks.json', '{"hooks":{"Stop":[{"hooks":[{"type":"command","command":"my-own-hook"}]}]}}')// A dotfile-managed AGENTS.md: the link must still be a link afterwards.- const real = seed('dotfiles/AGENTS.md', '# my own agent notes\n')+ const real = seed(+ 'dotfiles/AGENTS.md',+ '# my own agent notes\n\n<!-- nodeterm:get-linked-context:start -->\nOLD\n<!-- nodeterm:get-linked-context:end -->\n'+ )symlinkSync(real, path.join(home, '.codex', 'AGENTS.md'))- const rh = new RemoteHooks(hostRunner('deliver'))+ const rh = new RemoteHooks(hostRunner('deliver'), allRemote)await rh['installCodexRemote'](conn, '/fixture.sock', home, `${home}/.nodeterm`)- await rh.installCanvasControl(conn, '/fixture.sock', home)+ await rh['stripLegacyInstructionBlocks'](conn, '/fixture.sock', home)const nextToml = read('.codex/config.toml')expect(nextToml.startsWith(toml)).toBe(true)@@ -240,23 +247,23 @@ describe.skipIf(process.platform === 'win32')('remote writes never leave a truncexpect(read('.nodeterm/agent-hooks/codex.sh')).toContain('#!/bin/sh')expect(modeOf('.nodeterm/agent-hooks/codex.sh')).toBe(0o755)expect(lstatSync(path.join(home, '.codex', 'AGENTS.md')).isSymbolicLink()).toBe(true)- expect(readFileSync(real, 'utf8')).toMatch(/^# my own agent notes\n[\s\S]*nodeterm:manage-canvas:start/)+ // The legacy block is stripped through the link; the user's text is all that is left.+ expect(readFileSync(real, 'utf8')).toBe('# my own agent notes\n')expect(leftovers()).toEqual([])})- it('an unreadable instruction file is left alone, not read as empty and replaced by our block', async () => {- // The old `cat file 2>/dev/null || true` turned a read failure into '' and then wrote our block- // alone over the user's file. A directory in the file's place is the portable read failure.+ it('an unreadable instruction file is left alone by the legacy clean-up', async () => {+ // A directory in the file's place is the portable read failure; it must not be read as empty.mkdirSync(path.join(home, '.gemini', 'GEMINI.md'), { recursive: true })- const rh = new RemoteHooks(hostRunner('deliver'))- await rh.installCanvasControl(conn, '/fixture.sock', home)+ const rh = new RemoteHooks(hostRunner('deliver'), allRemote)+ await rh['stripLegacyInstructionBlocks'](conn, '/fixture.sock', home)expect(lstatSync(path.join(home, '.gemini', 'GEMINI.md')).isDirectory()).toBe(true)expect(warned('Remote file unchanged')).toBe(true)})it('an empty body is refused before any ssh', async () => {const runner = hostRunner('deliver')- const rh = new RemoteHooks(runner)+ const rh = new RemoteHooks(runner, allRemote)await expect(rh['writeOwnedFile'](conn, '/fixture.sock', `${home}/.nodeterm/nodeterm.sh`, '', { mode: '755' })).rejects.toThrow(/empty body/)@@ -267,7 +274,7 @@ describe.skipIf(process.platform === 'win32')('remote writes never leave a truncdescribe.skipIf(process.platform === 'win32')('every mode-bearing caller publishes on a macOS host (non-permuting chmod)', () => {it('setup(): the hook endpoint lands 0600, every agent hook script 0755', async () => {- const rh = new RemoteHooks(hostRunner('deliver'))+ const rh = new RemoteHooks(hostRunner('deliver'), allRemote)const res = await rh.setup('p1', conn, '/fixture.sock', { port: 51234, token: 'tok', version: '1' })// On a host whose chmod does not permute, `chmod 600 -- <temp>` failed the endpoint write, so// setup returned null and the host got no status hooks, canvas control or context link at all.@@ -282,7 +289,7 @@ describe.skipIf(process.platform === 'win32')('every mode-bearing caller publish})it('node tokens land 0600', async () => {- const rh = new RemoteHooks(hostRunner('deliver'))+ const rh = new RemoteHooks(hostRunner('deliver'), allRemote)await rh.writeNodeTokens(conn, '/fixture.sock', home, ['n-1', 'n-2'], (id) => `token-${id}`)for (const id of ['n-1', 'n-2']) {expect(read(`.nodeterm/node-tokens/${id}`)).toBe(`token-${id}\n`)@@ -291,7 +298,7 @@ describe.skipIf(process.platform === 'win32')('every mode-bearing caller publish})it('the canvas/context shims and a managed-account hook script land 0755', async () => {- const rh = new RemoteHooks(hostRunner('deliver'))+ const rh = new RemoteHooks(hostRunner('deliver'), allRemote)await rh.installAgentTools(conn, '/fixture.sock', home)await rh.installIntoAccountDir(conn, '/fixture.sock', home, 'acc')expect(modeOf('.nodeterm/nodeterm.sh')).toBe(0o755)@@ -379,17 +386,16 @@ describe.skipIf(process.platform === 'win32')('canvas control and context link s}// ~25 real shell processes per host; the budget is for a loaded CI runner, not the work.- it('a fresh connect 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']+ it('a fresh connect leaves BOTH skills in both dirs (8 fresh hosts)', { timeout: 60_000 }, async () => {+ const shared = ['.claude/skills', '.agents/skills']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)).installAgentTools(conn, '/fixture.sock', h)+ await new RemoteHooks(asyncHostRunner(h), allRemote).installAgentTools(conn, '/fixture.sock', h)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`)+ if (!existsSync(path.join(h, f, 'manage-nodeterm-canvas/SKILL.md'))) missing.push(`${i}:${f}:canvas`)+ if (!existsSync(path.join(h, f, 'get-linked-context/SKILL.md'))) missing.push(`${i}:${f}:context`)}} finally {rmSync(h, { recursive: true, force: true })@@ -400,17 +406,16 @@ describe.skipIf(process.platform === 'win32')('canvas control and context link s// 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']+ it('the freshness check leaves BOTH skills in both dirs (8 fresh hosts)', { timeout: 60_000 }, async () => {+ const shared = ['.claude/skills', '.agents/skills']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')+ await new RemoteHooks(asyncHostRunner(h), allRemote).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`)+ if (!existsSync(path.join(h, f, 'manage-nodeterm-canvas/SKILL.md'))) missing.push(`${i}:${f}:canvas`)+ if (!existsSync(path.join(h, f, 'get-linked-context/SKILL.md'))) missing.push(`${i}:${f}:context`)}} finally {rmSync(h, { recursive: true, force: true })diff --git a/src/main/remote-ssh/ssh-project.ts b/src/main/remote-ssh/ssh-project.tsindex 028cdbbea..6e413a546 100644--- a/src/main/remote-ssh/ssh-project.ts+++ b/src/main/remote-ssh/ssh-project.ts@@ -58,7 +58,7 @@ import { SshChildGate } from '../../core/remote-ssh/ssh-child-gate'import { claudeVersionProbeCommand, parseClaudeVersionProbe } from '../../core/remote-ssh/claude-version-probe'import { codexNoDaemonProbeCommand, parseCodexNoDaemonProbe } from '../../core/remote-ssh/codex-no-daemon-probe'import { codexProbeHostKey } from '../../shared/agents/codex-daemon'-import { RemoteHooks } from './remote-hooks'+import { NO_REMOTE_INTEGRATION, RemoteHooks, type RemoteIntegrationPlan } from './remote-hooks'import type { AgentToolsTrigger } from './agent-tools-freshness'import {recordTunnelRepair,@@ -198,6 +198,13 @@ interface Runners {* 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[]+ /** What nodeterm may install on / must remove from one SSH host (`sshHostKey`), from the+ * agent-integration consent (issue #744, `remoteIntegrationPlan`). Absent ⇒ NOTHING is+ * installed and nothing removed on any host — the fail-closed direction. */+ integrationsForHost?: (hostKey: string) => RemoteIntegrationPlan+ /** Receipts for the skill files nodeterm wrote on hosts, so a decline can tell its own bytes+ * from a user's edit. Absent ⇒ only this build's exact bytes count as ours. */+ integrationReceipts?: { get(key: string): string | undefined; set(key: string, v: string | null): void }}/** Backoff after a FAILED remote claude probe (no markers = claude not found on that attempt).@@ -464,7 +471,11 @@ export class SshProjectManager {>()private watchdog?: ReturnType<typeof setInterval>constructor(private r: Runners) {- this.remoteHooks = new RemoteHooks({ run: r.run })+ this.remoteHooks = new RemoteHooks(+ { run: r.run },+ (conn) => r.integrationsForHost?.(sshHostKey(conn)) ?? NO_REMOTE_INTEGRATION,+ r.integrationReceipts+ )}/**@@ -604,6 +615,47 @@ export class SshProjectManager {void this.remoteHooks.refreshAgentTools(conn, controlPath, remoteHome, accounts, trigger).catch(() => {})}+ private applyIntegrationRemovals(conn: SshConnection, controlPath: string, remoteHome: string): void {+ const plan = this.remoteHooks.planFor(conn)+ // An unanswered host is left exactly as it is: no clean-up, no account lookup, no ssh.+ if (!plan.decided) return+ let accounts: string[] = []+ try {+ if (plan.remove.has('claude')) accounts = this.r.claudeAccountIdsForHost?.(sshHostKey(conn)) ?? []+ } catch {+ /* the account dirs are skipped this time */+ }+ void this.remoteHooks+ .applyIntegrationRemovals(conn, controlPath, remoteHome, accounts, this.r.integrationReceipts)+ .catch(() => {})+ }++ /** Last consent signature applied per connected project (issue #744). */+ private integrationSigs = new Map<string, string>()++ /**+ * The user changed an agent-integration choice. For every connected project whose host's plan+ * moved: remove what is no longer consented, and install what newly is (hooks need the verified+ * tunnel's endpoint, so they wait for `hookEndpointPath`). Never throws, never awaited.+ */+ onIntegrationConsentChanged(): void {+ for (const [projectId, c] of this.conns) {+ if (!c.remoteHome) continue+ const plan = this.remoteHooks.planFor(c.conn)+ const sig = `${plan.decided}|${[...plan.install].sort().join(',')}|${[...plan.remove].sort().join(',')}`+ if (this.integrationSigs.get(projectId) === sig) continue+ this.integrationSigs.set(projectId, sig)+ this.applyIntegrationRemovals(c.conn, c.controlPath, c.remoteHome)+ if (plan.install.size && c.hookEndpointPath) {+ const { conn, controlPath, remoteHome } = c+ void this.remoteHooks+ .installAgentHooks(conn, controlPath, remoteHome)+ .then(() => this.refreshAgentTools(conn, controlPath, remoteHome, 'repair'))+ .catch(() => {})+ }+ }+ }+startWatchdog(intervalMs = MASTER_WATCHDOG_MS): void {if (this.watchdog) returnthis.watchdog = setInterval(() => {@@ -1041,6 +1093,11 @@ export class SshProjectManager {// Same not-awaited best-effort terms as the two installs.void this.materialiseNodeTokens(projectId, conn, controlPath, remoteHome)}+ // Agent-integration consent (issue #744), REMOVAL side: a host the user declined (or agents+ // they declined) loses what we wrote there, and the legacy instruction blocks older builds+ // merged are stripped. Independent of the tunnel; not awaited (best-effort, never delays+ // the connect). The INSTALL side rides setup() and the agent-tools check above.+ if (remoteHome) this.applyIntegrationRemovals(conn, controlPath, remoteHome)// Managed-Codex runtime: upload the relay bundle + launcher and probe node/codex/curl.// Deliberately gated on `remoteHome` ALONE, not on `hookEndpointPath` — account isolation +// a shared app-server need only the launcher/relay, never the canvas hooks, and the reverse@@ -2789,7 +2846,9 @@ export function initSshProject(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[]+ claudeAccountIdsForHost?: (hostKey: string) => string[],+ /** Agent-integration consent per host (see Runners.integrationsForHost / integrationReceipts). */+ integrations?: Pick<Runners, 'integrationsForHost' | 'integrationReceipts'>): SshProjectManager {const ssh = sshBin()const scp = scpBin()@@ -2944,6 +3003,7 @@ export function initSshProject(codexRelaySource,leadPaneWidth,claudeAccountIdsForHost,+ ...integrations,// 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),diff --git a/src/preload/index.ts b/src/preload/index.tsindex 603370946..8b8bd18a3 100644--- a/src/preload/index.ts+++ b/src/preload/index.ts@@ -231,6 +231,9 @@ const api: NodeTerminalApi = {load: () => ipcRenderer.invoke(IPC.settingsLoad),save: (settings) => ipcRenderer.invoke(IPC.settingsSave, settings)},+ integrations: {+ status: () => ipcRenderer.invoke(IPC.integrationsStatus)+ },githubIssues: {subscribe: (projectId) => ipcRenderer.invoke(IPC.githubIssuesSubscribe, { projectId }),unsubscribe: async (projectId) => {diff --git a/src/renderer/bridge/stubs.ts b/src/renderer/bridge/stubs.tsindex fd0e41a4f..f10d8079e 100644--- a/src/renderer/bridge/stubs.ts+++ b/src/renderer/bridge/stubs.ts@@ -118,6 +118,7 @@ export function buildStubApi(): Omit<| 'pty'| 'workspace'| 'settings'+ | 'integrations'| 'fs'| 'git'| 'files'@@ -681,6 +682,7 @@ export function buildStubApi(): Omit<| 'pty'| 'workspace'| 'settings'+ | 'integrations'| 'fs'| 'git'| 'files'diff --git a/src/renderer/bridge/ws-bridge.ts b/src/renderer/bridge/ws-bridge.tsindex db60895e9..e736cc67e 100644--- a/src/renderer/bridge/ws-bridge.ts+++ b/src/renderer/bridge/ws-bridge.ts@@ -246,6 +246,7 @@ export function buildRealApi(| 'projectSetup'| 'worktree'| 'settings'+ | 'integrations'| 'agent'| 'userDataDir'> {@@ -422,6 +423,11 @@ export function buildRealApi(save: (s: Settings) => client.request(IPC.settingsSave, s) as Promise<void>}+ // REAL: both shells boot the consent lifecycle (core/agent-integrations.ts) and register it.+ const integrations: NodeTerminalApi['integrations'] = {+ status: () => client.request(IPC.integrationsStatus) as ReturnType<NodeTerminalApi['integrations']['status']>+ }+const agent: NodeTerminalApi['agent'] = {// Deliberately NOT a request: the server registers no env-snapshot handler (a full host-env// dump answerable by any authenticated WS client is the PR #195 leak class at the RPC layer).@@ -451,7 +457,7 @@ export function buildRealApi(// `/worktrees/…` at the filesystem root (the server usually runs as root, and git would create it).const userDataDir = (): Promise<string> => client.request(IPC.appUserDataDir) as Promise<string>- return { pty, workspace, projectSettings, projectSetup, worktree, settings, agent, userDataDir }+ return { pty, workspace, projectSettings, projectSetup, worktree, settings, integrations, agent, userDataDir }}export function buildGitHubApi(diff --git a/src/renderer/canvas/Canvas.tsx b/src/renderer/canvas/Canvas.tsxindex e6111eed0..665f1e797 100644--- a/src/renderer/canvas/Canvas.tsx+++ b/src/renderer/canvas/Canvas.tsx@@ -687,6 +687,11 @@ import { useContextWindow } from '../state/contextWindow'import { useSessionNaming } from '../state/sessionNaming'import { useSshServers } from '../state/sshServers'import { useSshConn } from '../state/sshConn'+import {+ HostIntegrationBanner,+ IntegrationGrandfatherNotice,+ IntegrationPromptBanner+} from '../components/settings/IntegrationConsent'import { scopeFromKey, usageScopeKey } from '../lib/usageScope'import { useSystemAccount } from '../state/systemAccount'import { useEntitlement } from '../state/entitlement'@@ -2039,6 +2044,12 @@ export function Canvas() {/** The active project runs on a remote host → every worktree affordance is off (see* WORKTREE_SSH_HINT). Reactive, so the menus rebuild when the user switches projects. */const isSshProject = !!activeSshServer+ /** The active SSH project's host, once it is CONNECTED — the host the consent banner asks about+ * (nothing is installed there until it is answered). */+ const activeSshHostKey = useSshConn((c) => {+ const id = useProjects.getState().activeProjectId+ return activeSshServer && id && c.byProject[id] ? sshHostKey(activeSshServer) : null+ })/*** ONE confirm dialog at a time — mirrored into a ref so the []-dep agent-control effect sees the* CURRENT dialogs (it closes over a stale `confirm`).@@ -18280,6 +18291,21 @@ export function Canvas() {<div className="top-banners"><AnnouncementBanner />+ {/* Agent-integration consent (issue #744): the first-run question, the grandfathered+ install's one-time notice, and the active SSH host's own question. */}+ <IntegrationPromptBanner+ onChoose={() => {+ setSettingsSection('agents')+ setSettingsOpen(true)+ }}+ />+ <IntegrationGrandfatherNotice+ onOpenSettings={() => {+ setSettingsSection('agents')+ setSettingsOpen(true)+ }}+ />+ <HostIntegrationBanner hostKey={activeSshHostKey} />{/* Discovery belongs to the local core; never run its installer on an SSH/relay host. */}<TmuxBanneronInstall={!isSshProject && session.id === localSession.id ? runInTerminal : undefined}diff --git a/src/renderer/components/settings/IntegrationConsent.test.tsx b/src/renderer/components/settings/IntegrationConsent.test.tsxnew file mode 100644index 000000000..fc793200b--- /dev/null+++ b/src/renderer/components/settings/IntegrationConsent.test.tsx@@ -0,0 +1,115 @@+// @vitest-environment jsdom+//+// The consent UI (issue #744). What it must do: ask a NEW install once (and only once), tell a+// grandfathered install once, ask about an SSH host nobody answered for, and give Settings an+// Enable / Decline-and-clean-up per agent and per host. All it ever writes is the choice.+import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest'+import { act } from 'react'+import { createRoot, type Root } from 'react-dom/client'+import { DEFAULT_SETTINGS } from '@shared/types'+import { INTEGRATION_AGENT_IDS, grandfatheredIntegrations, answerIntegrationPrompt } from '@shared/agent-integrations'+import { useSettings } from '../../state/settings'+import {+ HostIntegrationBanner,+ IntegrationGrandfatherNotice,+ IntegrationPromptBanner,+ IntegrationSettings+} from './IntegrationConsent'++;(globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean }).IS_REACT_ACT_ENVIRONMENT = true++let root: Root+let host: HTMLElement++beforeEach(() => {+ ;(window as unknown as { nodeTerminal: unknown }).nodeTerminal = {+ settings: { save: vi.fn(async () => undefined) },+ integrations: { status: vi.fn(async () => ({ enabled: [], declined: [], retained: ['/h/.gemini/skills/x/SKILL.md'], vetoed: false })) }+ }+ useSettings.setState({ settings: { ...DEFAULT_SETTINGS }, hydrated: true })+ host = document.createElement('div')+ document.body.appendChild(host)+ root = createRoot(host)+})+afterEach(() => {+ act(() => root.unmount())+ host.remove()+})++const render = (el: React.JSX.Element) => act(() => root.render(el))+const button = (text: string) =>+ [...host.querySelectorAll('button')].find((b) => b.textContent?.trim() === text) as HTMLButtonElement+const click = (b: HTMLElement) => act(() => b.click())+const consent = () => useSettings.getState().settings.agentIntegrations++describe('the first-run question', () => {+ it('is shown to a new install and "Enable all" records every agent enabled', () => {+ render(<IntegrationPromptBanner onChoose={() => {}} />)+ expect(host.querySelector('[data-testid="integration-prompt"]')).toBeTruthy()+ click(button('Enable all'))+ for (const a of INTEGRATION_AGENT_IDS) expect(consent()?.agents?.[a]).toBe('enabled')+ expect(host.querySelector('[data-testid="integration-prompt"]')).toBeNull()+ })++ it('"Not now" declines every agent, so it is asked ONCE', () => {+ render(<IntegrationPromptBanner onChoose={() => {}} />)+ click(button('Not now'))+ for (const a of INTEGRATION_AGENT_IDS) expect(consent()?.agents?.[a]).toBe('declined')+ expect(host.querySelector('[data-testid="integration-prompt"]')).toBeNull()+ })++ it('waits for settings to load (never asks over a record it has not read)', () => {+ useSettings.setState({ hydrated: false })+ render(<IntegrationPromptBanner onChoose={() => {}} />)+ expect(host.querySelector('[data-testid="integration-prompt"]')).toBeNull()+ })+})++describe('the grandfathered notice', () => {+ it('shows once and dismisses for good', () => {+ useSettings.setState({ settings: { ...DEFAULT_SETTINGS, agentIntegrations: grandfatheredIntegrations() } })+ render(<IntegrationGrandfatherNotice onOpenSettings={() => {}} />)+ expect(host.querySelector('[data-testid="integration-notice"]')).toBeTruthy()+ click(host.querySelector('button[aria-label="Dismiss"]') as HTMLElement)+ expect(consent()?.noticeDismissed).toBe(true)+ expect(consent()?.agents?.claude).toBe('enabled')+ expect(host.querySelector('[data-testid="integration-notice"]')).toBeNull()+ })+})++describe('the per-host question', () => {+ it('asks about an unanswered host once the first-run question is answered, and records the answer', () => {+ useSettings.setState({ settings: { ...DEFAULT_SETTINGS, agentIntegrations: answerIntegrationPrompt(['claude']) } })+ render(<HostIntegrationBanner hostKey="me@srv" />)+ click(button('Not on this host'))+ expect(consent()?.hosts?.['me@srv']).toBe('declined')+ expect(host.querySelector('[data-testid="host-integration-prompt"]')).toBeNull()+ })++ it('is not shown for a grandfathered install (its hosts keep working)', () => {+ useSettings.setState({ settings: { ...DEFAULT_SETTINGS, agentIntegrations: grandfatheredIntegrations() } })+ render(<HostIntegrationBanner hostKey="me@srv" />)+ expect(host.querySelector('[data-testid="host-integration-prompt"]')).toBeNull()+ })+})++describe('Settings → Agents', () => {+ it('has Enable / Decline & clean up per agent, and lists what the host kept', async () => {+ vi.useFakeTimers()+ try {+ useSettings.setState({ settings: { ...DEFAULT_SETTINGS, agentIntegrations: answerIntegrationPrompt(['claude']) } })+ render(<IntegrationSettings />)+ for (const a of INTEGRATION_AGENT_IDS) expect(host.querySelector(`[data-testid="integration-row-${a}"]`)).toBeTruthy()+ const decline = host.querySelector('button[aria-label^="Turn off the Claude"]') as HTMLButtonElement+ click(decline)+ expect(consent()?.agents?.claude).toBe('declined')+ await act(async () => {+ vi.advanceTimersByTime(500)+ await Promise.resolve()+ })+ expect(host.querySelector('[data-testid="integration-retained"]')?.textContent).toContain('/h/.gemini/skills/x/SKILL.md')+ } finally {+ vi.useRealTimers()+ }+ })+})diff --git a/src/renderer/components/settings/IntegrationConsent.tsx b/src/renderer/components/settings/IntegrationConsent.tsxnew file mode 100644index 000000000..6761c4c92--- /dev/null+++ b/src/renderer/components/settings/IntegrationConsent.tsx@@ -0,0 +1,243 @@+// Agent-integration consent UI (issue #744): the first-run question, the one-time notice for an+// install that was grandfathered, the per-SSH-host question, and the Settings → Agents rows.+//+// The CHOICE is `settings.agentIntegrations` (`@shared/agent-integrations`); saving it is all the+// renderer does — the host's lifecycle (core/agent-integrations.ts) reacts to the settings change+// and installs or cleans up. Every reader goes through the shared sanitizer.+import { useEffect, useState } from 'react'+import { useSettings } from '../../state/settings'+import {+ FEATURES_NEEDING_INTEGRATION,+ INTEGRATION_AGENT_IDS,+ agentChoice,+ answerIntegrationPrompt,+ hostChoice,+ integrationsOf,+ needsGrandfatherNotice,+ needsIntegrationPrompt,+ withAgentChoice,+ withHostChoice,+ withNoticeDismissed,+ type AgentIntegrationsStatus,+ type IntegrationAgentId,+ type IntegrationChoice+} from '@shared/agent-integrations'+import { AGENT_CONFIG } from '@shared/agents/config'+import { Button } from '@renderer/ui/Button'+import { AgentIcon } from '../../lib/agentIcons'+import { IconClose } from '../icons'++const labelOf = (id: IntegrationAgentId): string => AGENT_CONFIG[id]?.label ?? id++/** What an integration writes, in one sentence (the same words everywhere it is offered). */+export const INTEGRATION_WRITES =+ 'nodeterm adds a status hook to each agent’s own settings and installs two small skills ' ++ '(canvas control, reading linked nodes) in its skills folder. Nothing is added to your ' ++ 'AGENTS.md / GEMINI.md, and turning an agent off removes exactly what nodeterm added.'++export const INTEGRATION_UNAVAILABLE =+ `Terminals always work. Without an integration, that agent has no ${FEATURES_NEEDING_INTEGRATION.join('; no ')}.`++function useSave(): (next: ReturnType<typeof useSettings.getState>['settings']) => void {+ const update = useSettings((s) => s.update)+ return (next) => update({ agentIntegrations: next.agentIntegrations })+}++/** The first-run question (a new install that has not answered). Nothing global is written until+ * it is answered; "Not now" records a decline, so it is asked once. */+export function IntegrationPromptBanner({ onChoose }: { onChoose: () => void }): React.JSX.Element | null {+ const settings = useSettings((s) => s.settings)+ const hydrated = useSettings((s) => s.hydrated)+ const save = useSave()+ if (!hydrated || !needsIntegrationPrompt(settings)) return null+ return (+ <div className="announce-banner announce-banner--info" role="status" data-testid="integration-prompt">+ <span className="announce-banner__dot" />+ <div className="announce-banner__content">+ <span className="announce-banner__title">Integrate nodeterm with your agent CLIs?</span>+ <span className="announce-banner__body">+ {INTEGRATION_WRITES} {INTEGRATION_UNAVAILABLE}+ </span>+ </div>+ <button+ className="announce-banner__btn"+ onClick={() => save({ ...settings, agentIntegrations: answerIntegrationPrompt([...INTEGRATION_AGENT_IDS]) })}+ >+ Enable all+ </button>+ <button className="announce-banner__btn" onClick={onChoose}>+ Choose…+ </button>+ <button+ className="announce-banner__btn"+ onClick={() => save({ ...settings, agentIntegrations: answerIntegrationPrompt([]) })}+ >+ Not now+ </button>+ </div>+ )+}++/** The one-time notice for an install from before this feature: everything it had stays on. */+export function IntegrationGrandfatherNotice({ onOpenSettings }: { onOpenSettings: () => void }): React.JSX.Element | null {+ const settings = useSettings((s) => s.settings)+ const hydrated = useSettings((s) => s.hydrated)+ const save = useSave()+ if (!hydrated || !needsGrandfatherNotice(settings)) return null+ const dismiss = (): void => save(withNoticeDismissed(settings))+ return (+ <div className="announce-banner announce-banner--info" role="status" data-testid="integration-notice">+ <span className="announce-banner__dot" />+ <div className="announce-banner__content">+ <span className="announce-banner__title">Agent integrations are now a choice</span>+ <span className="announce-banner__body">+ They stay on for every agent, as before. You can turn any agent (or any SSH host) off in+ Settings → Agents — nodeterm then removes exactly what it added.+ </span>+ </div>+ <button+ className="announce-banner__btn"+ onClick={() => {+ dismiss()+ onOpenSettings()+ }}+ >+ Review+ </button>+ <button className="announce-banner__close" title="Dismiss" aria-label="Dismiss" onClick={dismiss}>+ <IconClose />+ </button>+ </div>+ )+}++/** The per-host question: the active project's SSH host has no answer yet, so nothing was+ * installed there. Shown only once the first-run question is answered. */+export function HostIntegrationBanner({ hostKey }: { hostKey: string | null }): React.JSX.Element | null {+ const settings = useSettings((s) => s.settings)+ const hydrated = useSettings((s) => s.hydrated)+ const save = useSave()+ if (!hydrated || !hostKey || needsIntegrationPrompt(settings)) return null+ if (hostChoice(settings, hostKey) !== undefined) return null+ if (!INTEGRATION_AGENT_IDS.some((a) => agentChoice(settings, a) === 'enabled')) return null+ return (+ <div className="announce-banner announce-banner--info" role="status" data-testid="host-integration-prompt">+ <span className="announce-banner__dot" />+ <div className="announce-banner__content">+ <span className="announce-banner__title">Integrate with the agents on {hostKey}?</span>+ <span className="announce-banner__body">+ nodeterm writes the same hooks and skills into your agent config on that host. Nothing is+ installed there until you say. {INTEGRATION_UNAVAILABLE}+ </span>+ </div>+ <button className="announce-banner__btn" onClick={() => save(withHostChoice(settings, hostKey, 'enabled'))}>+ Allow on this host+ </button>+ <button className="announce-banner__btn" onClick={() => save(withHostChoice(settings, hostKey, 'declined'))}>+ Not on this host+ </button>+ </div>+ )+}++function choiceText(c: IntegrationChoice | undefined): string {+ return c === 'enabled' ? 'On' : c === 'declined' ? 'Off' : 'Not asked'+}++/** Settings → Agents: one row per agent, the per-host answers, and what the host kept. */+export function IntegrationSettings(): React.JSX.Element {+ const settings = useSettings((s) => s.settings)+ const save = useSave()+ const [status, setStatus] = useState<AgentIntegrationsStatus | null>(null)+ const sig = JSON.stringify(integrationsOf(settings))+ useEffect(() => {+ let live = true+ // Give the host a moment to reconcile after a save, then ask what it did.+ const t = setTimeout(() => {+ window.nodeTerminal.integrations+ ?.status()+ .then((s) => {+ if (live) setStatus(s)+ })+ .catch(() => {})+ }, 400)+ return () => {+ live = false+ clearTimeout(t)+ }+ }, [sig])+ const hosts = Object.entries(integrationsOf(settings).hosts ?? {})+ return (+ <div className="space-y-2" data-testid="integration-settings">+ <p className="text-[12px] text-muted">+ {INTEGRATION_WRITES} {INTEGRATION_UNAVAILABLE}+ </p>+ {status?.vetoed && (+ <p className="text-[12px] text-muted">+ This server was started with agent installs disabled, so nothing is written regardless of+ these choices.+ </p>+ )}+ {INTEGRATION_AGENT_IDS.map((id) => {+ const c = agentChoice(settings, id)+ return (+ <div key={id} className="flex items-center gap-3 py-1" data-testid={`integration-row-${id}`}>+ <AgentIcon agentId={id} size={18} />+ <span className="flex-1 text-[13px] text-text">{labelOf(id)}</span>+ <span className="text-[12px] text-muted">{choiceText(c)}</span>+ <Button+ variant={c === 'enabled' ? 'primary' : 'default'}+ onClick={() => save(withAgentChoice(settings, id, 'enabled'))}+ aria-label={`Enable the ${labelOf(id)} integration`}+ >+ Enable+ </Button>+ <Button+ variant={c === 'declined' ? 'primary' : 'default'}+ onClick={() => save(withAgentChoice(settings, id, 'declined'))}+ aria-label={`Turn off the ${labelOf(id)} integration and remove what nodeterm added`}+ >+ Decline & clean up+ </Button>+ </div>+ )+ })}+ {hosts.length > 0 && (+ <div className="pt-2">+ <div className="text-[12px] text-muted pb-1">SSH hosts</div>+ {hosts.map(([host, c]) => (+ <div key={host} className="flex items-center gap-3 py-1" data-testid={`integration-host-${host}`}>+ <span className="flex-1 text-[13px] text-text">{host}</span>+ <span className="text-[12px] text-muted">{choiceText(c)}</span>+ <Button+ variant={c === 'enabled' ? 'primary' : 'default'}+ onClick={() => save(withHostChoice(settings, host, 'enabled'))}+ >+ Allow+ </Button>+ <Button+ variant={c === 'declined' ? 'primary' : 'default'}+ onClick={() => save(withHostChoice(settings, host, 'declined'))}+ >+ Decline & clean up+ </Button>+ </div>+ ))}+ </div>+ )}+ {!!status?.retained.length && (+ <div className="pt-2 text-[12px] text-muted" data-testid="integration-retained">+ Kept because you changed them since nodeterm wrote them (remove by hand if you no longer+ want them):+ <ul className="list-disc pl-5">+ {status.retained.map((p) => (+ <li key={p} className="font-mono">+ {p}+ </li>+ ))}+ </ul>+ </div>+ )}+ </div>+ )+}diff --git a/src/renderer/components/settings/sections/AgentsSection.tsx b/src/renderer/components/settings/sections/AgentsSection.tsxindex f36e20f8d..697ecda81 100644--- a/src/renderer/components/settings/sections/AgentsSection.tsx+++ b/src/renderer/components/settings/sections/AgentsSection.tsx@@ -58,8 +58,13 @@ import { NumberField } from '@renderer/ui/NumberField'import { SettingsSection } from '../SettingsSection'import { SearchableRow } from '../SearchableRow'import { FieldRow } from '../FieldRow'+import { IntegrationSettings } from '../IntegrationConsent'const ROWS = {+ integrations: {+ title: 'Agent integrations',+ keywords: ['integration', 'consent', 'hook', 'hooks', 'skill', 'skills', 'install', 'opt out', 'decline', 'clean up', 'ssh', 'host', 'agents.md', 'gemini.md']+ },agents: {title: 'Agents',keywords: ['agent', 'claude', 'codex', 'gemini', 'enable', 'disable', 'default']@@ -455,6 +460,10 @@ export function AgentsSection({ isActive }: { isActive: boolean }): React.JSX.ElisActive={isActive}searchEntries={ENTRIES}>+ <SearchableRow {...ROWS.integrations}>+ <FieldRow label="Agent integrations" description="What nodeterm may write into each agent CLI’s own configuration, on this machine and on each SSH host." control={null} />+ <IntegrationSettings />+ </SearchableRow><SearchableRow {...ROWS.agents}><div className="space-y-2">{rows.map((row) => {diff --git a/src/server/canvas-control.test.ts b/src/server/canvas-control.test.tsindex 3be363f22..f94da79b2 100644--- a/src/server/canvas-control.test.ts+++ b/src/server/canvas-control.test.ts@@ -181,8 +181,7 @@ describe('initServerCanvasControl', () => {codexSharedIdentity: async () => true,// Pinned, never this machine's codex: the line depends on what the CLI advertises. `true`// also proves the Server Edition's opens carry `--no-daemon` (shared/agents/codex-daemon.ts).- codexCaps: async () => ({ approvalValues: null, noDaemon: true }),- installAgentIntegrations: false+ codexCaps: async () => ({ approvalValues: null, noDaemon: true })})const shim = path.join(dataDir, 'canvas-control', 'nodeterm.sh')@@ -191,11 +190,6 @@ describe('initServerCanvasControl', () => {expect(shimBody).toContain('CODEX_THREAD_ID')expect(shimBody).toContain(path.join(dataDir, 'codex-thread-nodes'))expect(fs.statSync(shim).mode & 0o111).not.toBe(0)- const accountDir = path.join(dataDir, 'test-account')- runtime.installSkillInto(accountDir)- expect(- fs.readFileSync(path.join(accountDir, 'skills', 'manage-nodeterm-canvas', 'SKILL.md'), 'utf8')- ).toContain(shim)const opened = await runtime.handler({verb: 'open-agent',@@ -328,8 +322,7 @@ describe('initServerCanvasControl', () => {workspaceStore: store,ptyManager: pty,settings: () => ({ ...DEFAULT_SETTINGS }),- boardLog: { append: async () => false },- installAgentIntegrations: false+ boardLog: { append: async () => false }})const opened = await runtime.handler({@@ -421,8 +414,7 @@ describe('initServerCanvasControl', () => {workspaceStore: store,ptyManager: pty,settings: () => ({ ...DEFAULT_SETTINGS }),- boardLog: { append: async () => false },- installAgentIntegrations: false+ boardLog: { append: async () => false }})fake.sent.length = 0diff --git a/src/server/canvas-control.ts b/src/server/canvas-control.tsindex ae5ec7f92..e34e6fe41 100644--- a/src/server/canvas-control.ts+++ b/src/server/canvas-control.ts@@ -1,5 +1,4 @@import fs from 'node:fs'-import os from 'node:os'import path from 'node:path'import {@@ -28,19 +27,13 @@ import {nodeState} from '../core/agent-status-mirror'import type { BoardLogHandlers } from '../core/board-log-handlers'-import {- buildControlShimScript,- buildCanvasControlInstructions,- buildCanvasSkillBody,- mergeCanvasControlBlock-} from '../core/canvas-control-core'+import { buildControlShimScript } from '../core/canvas-control-core'import { codexIdentityCaps } from '../core/codex-identity-caps'import { codexThreadIdentityRoot } from '../core/codex-identity-proxy'import { claudeCliCaps, type ClaudeCliCaps } from '../core/claude-cli'import { grokCliCaps } from '../core/grok-cli'import { codexCliCaps } from '../core/codex-cli'import type { CodexCliCaps, GrokCliCaps } from '../shared/types'-import { installHooksIntoLocalAccounts } from '../core/claude-accounts-service'import { platform } from '../core/platform'import type { PtyManager } from '../core/pty-manager'import type { WorkspaceStore } from '../core/workspace-store'@@ -78,27 +71,6 @@ export interface ServerCanvasControlDeps {/** The GitHub service's cache reads behind `issues` / `prs` (core/github/control-read.ts).* Absent = those verbs answer that the GitHub lane is unavailable here. */githubRead?: Pick<GitHubReadDeps, 'snapshot' | 'dispatch'>- /**- * Whether to write this server's discovery surface into the machine's REAL agent configuration- * directories: `~/.claude/skills/manage-nodeterm-canvas/SKILL.md`, the marker block in- * `~/.codex/AGENTS.md` and `~/.gemini/GEMINI.md`, and the same skill in every managed Claude- * account dir. `true` = the server's `installHooks` gate said yes; `false` = leave them alone.- *- * REQUIRED, and deliberately not defaulted. A service process editing files inside a user's- * `$HOME` is a documented hazard in this repo — those instruction files are loaded by EVERY- * agent session on the machine, nodeterm's or not, so a stray write follows the user into work- * that has nothing to do with this server (issue #490). The previous shape was an OPTIONAL flag- * read as `!== false`, which meant OMITTING the decision installed: the dangerous direction was- * the one you got by saying nothing, and a new call site or a test that simply forgot the field- * would rewrite the developer's own agent configuration with no diagnostic. Making it required- * turns "I did not think about this" into a compile error — the same asymmetry- * `session-memory-service.ts` uses for its `remote.isRemoteProject` dep, where- * reading-without-knowing is likewise refused at the type level.- *- * Production passes `config.installHooks !== false`; every test must pass `false` unless it is- * specifically exercising the install and has redirected `HOME` to a scratch directory first.- */- installAgentIntegrations: boolean/*** Does this process own the hook endpoint (`hookServer.startForApp()` returned no warning)? The* durable orchestration facts (queue, station reports, hand-over holds) belong to the owning@@ -117,7 +89,6 @@ export interface ServerCanvasControl {stationOutcomes: StationOutcomeStore/** Stations with unfinished handed-over work in THIS server run (plain `--after` holds on them). */stationHandovers: StationHandoverTracker- installSkillInto(configDir: string): voidstop(): void}@@ -129,10 +100,6 @@ function shimPath(): string {return path.join(canvasControlDir(), 'nodeterm.sh')}-function skillPathIn(configDir: string): string {- return path.join(configDir, 'skills', 'manage-nodeterm-canvas', 'SKILL.md')-}-function writeShim(): void {const dir = canvasControlDir()fs.mkdirSync(dir, { recursive: true })@@ -150,27 +117,17 @@ function writeShim(): void {}}-function installInstructions(file: string, body: string): void {- try {- let existing = ''- try {- existing = fs.readFileSync(file, 'utf8')- } catch {- /* first install */- }- fs.mkdirSync(path.dirname(file), { recursive: true })- fs.writeFileSync(file, mergeCanvasControlBlock(existing, body), 'utf8')- } catch (error) {- console.warn('[server-canvas-control] instruction install failed', file, error)- }+/** The canvas-control shim under the server dataDir (what the canvas skill points at). */+export function serverCanvasShimPath(): string {+ return shimPath()}/**- * Boot the Server Edition canvas runtime and install its discovery surface.+ * Boot the Server Edition canvas runtime.** The shim itself always lives under the configured server dataDir, never under a hard-coded- * `~/.nodeterm-server`. Writes to real Claude/Codex/Gemini homes are separately controlled by the- * existing `installHooks` gate, exactly like `initServerContextLink`.+ * `~/.nodeterm-server`. Its discovery skill is the consent lifecycle's (core/agent-integrations.ts,+ * issue #744), which also honours `installHooks: false` as a veto.*/export async function initServerCanvasControl(deps: ServerCanvasControlDeps@@ -182,29 +139,6 @@ export async function initServerCanvasControl(console.warn('[server-canvas-control] shim install failed', error)}- const skillBody = buildCanvasSkillBody(shimPath())- const instructions = buildCanvasControlInstructions(shimPath())- const installSkillInto = (configDir: string): void => {- const file = skillPathIn(configDir)- try {- fs.mkdirSync(path.dirname(file), { recursive: true })- fs.writeFileSync(file, skillBody, 'utf8')- } catch (error) {- console.warn('[server-canvas-control] skill install failed', file, error)- }- }-- // Required field, so this is a plain read of a decision the caller had to make — never a- // default. See ServerCanvasControlDeps.installAgentIntegrations for why omission must not- // be spellable here.- if (deps.installAgentIntegrations) {- installSkillInto(path.join(os.homedir(), '.claude'))- installInstructions(path.join(os.homedir(), '.codex', 'AGENTS.md'), instructions)- installInstructions(path.join(os.homedir(), '.gemini', 'GEMINI.md'), instructions)- // Managed accounts resolve skills relative to their own CLAUDE_CONFIG_DIR.- installHooksIntoLocalAccounts(deps.settings().claudeAccounts ?? [], installSkillInto)- }-// Station task outcomes: built before the factory, which reads them for `--after-success`.// Durable across a server restart, each report bound to the session that made it — the same// store, file and rules as the desktop (core/station-outcome-store.ts). The status mirror is@@ -437,7 +371,6 @@ export async function initServerCanvasControl(stationNotices,stationOutcomes,stationHandovers,- installSkillInto,stop: () => {factory.stop()queue.resetForTests()diff --git a/src/server/context-link.test.ts b/src/server/context-link.test.tsindex 9fcda0383..8cd3af62b 100644--- a/src/server/context-link.test.ts+++ b/src/server/context-link.test.ts@@ -152,8 +152,7 @@ describe('initServerContextLink', () => {nodes: [node('term-a', { title: 'Alpha' }), node('term-b', { title: 'Beta' })],bridges: [bridge('term-a', 'term-b')]}- ],- installAgentIntegrations: false+ ]})// Without this registration the hook server answers every read with// "Context link is unavailable in this session." — the whole desktop-only symptom.@@ -171,8 +170,7 @@ describe('initServerContextLink', () => {it('answers a node with no links, rather than pretending the feature is missing', async () => {const { link, handler } = start({ptyManager: fakePty(),- canvases: () => [],- installAgentIntegrations: false+ canvases: () => []})await link.refresh()const out = await handler({ verb: 'list', nodeId: 'term-a', args: {} })@@ -180,11 +178,10 @@ describe('initServerContextLink', () => {await link.stop()})- it('respects installHooks false while keeping the read handler available', async () => {+ it('never writes into the agent config dirs itself — that is the consent lifecycle\'s (#744)', async () => {const { link, registered } = start({ptyManager: fakePty(),- canvases: () => [],- installAgentIntegrations: false+ canvases: () => []})expect(registered).toBe(true)expect(existsSync(join(home, '.claude', 'skills', 'get-linked-context', 'SKILL.md'))).toBe(false)@@ -192,30 +189,11 @@ describe('initServerContextLink', () => {await link.stop()})- // The other half of the pair. With the flag REQUIRED, every other case in this file says- // `false`, so without this the install branch would have no coverage at all and "we stopped- // writing into $HOME" would be indistinguishable from "we can no longer write into $HOME".- // Safe to assert for real: `home` is a per-test scratch dir this suite points HOME at.- it('installs the discovery surface into the agent config dirs when asked to', async () => {- const { link, registered } = start({- ptyManager: fakePty(),- canvases: () => [],- installAgentIntegrations: true- })- expect(registered).toBe(true)- expect(existsSync(join(home, '.claude', 'skills', 'get-linked-context', 'SKILL.md'))).toBe(true)- expect(readFileSync(join(home, '.codex', 'AGENTS.md'), 'utf8')).toContain(- 'nodeterm:get-linked-context'- )- await link.stop()- })-it('picks up a bridge drawn after boot', async () => {let bridges = [] as ReturnType<typeof bridge>[]const { link, handler } = start({ptyManager: fakePty(),- canvases: () => [{ id: 'p1', nodes: [node('term-a'), node('term-b', { title: 'Beta' })], bridges }],- installAgentIntegrations: false+ canvases: () => [{ id: 'p1', nodes: [node('term-a'), node('term-b', { title: 'Beta' })], bridges }]})await link.refresh()expect(await handler({ verb: 'list', nodeId: 'term-a', args: {} })).toContain('No linked nodes')@@ -245,8 +223,7 @@ describe('initServerContextLink', () => {]const { link, handler } = start({ptyManager: fakePty(),- canvases,- installAgentIntegrations: false+ canvases})await link.refresh()expect(await handler({ verb: 'summary', nodeId: 'term-a', args: {} })).toContain(@@ -265,8 +242,7 @@ describe('initServerContextLink', () => {ptyManager: fakePty(),canvases: () => [{ id: 'p1', nodes: [node('term-a'), node('term-b')], bridges: [bridge('term-a', 'term-b')] }- ],- installAgentIntegrations: false+ ]})// Neither the sweep nor onPersist awaits a refresh, so at close there is normally one in// flight. A stop that does not drain it lets link files land in a dataDir the caller is@@ -285,8 +261,7 @@ describe('initServerContextLink', () => {ptyManager: fakePty(),canvases: () => [{ id: 'p1', nodes: [node('term-a'), node('term-b')], bridges: [bridge('term-a', 'term-b')] }- ],- installAgentIntegrations: false+ ]})await link.refresh()// The sweep runs every 15s for the life of the server: an unconditional rewrite would be adiff --git a/src/server/context-link.ts b/src/server/context-link.tsindex 3a7e41e1d..829b69502 100644--- a/src/server/context-link.ts+++ b/src/server/context-link.ts@@ -41,22 +41,6 @@ export interface ServerContextLinkDeps {/** nodeId → hook-fed transcript path; part of the change signature, not of the map. */transcriptOf?: (nodeId: string) => stringsweepMs?: number- /**- * Whether to write the context-link discovery surface into the machine's REAL agent- * configuration directories: `~/.claude/skills/get-linked-context/SKILL.md` and the marker- * block in `~/.codex/AGENTS.md`, `~/.gemini/GEMINI.md` and opencode's `AGENTS.md`. `true` =- * the server's `installHooks` gate said yes; `false` = leave them alone (the read handler and- * the shim under `dataDir` are registered either way, so the feature still works for sessions- * that already know about it).- *- * REQUIRED, and deliberately not defaulted — same reason as- * `ServerCanvasControlDeps.installAgentIntegrations`: a service process writing into a user's- * `$HOME` is a documented hazard (issue #490), those instruction files are read by every agent- * session on the machine rather than only ours, and an OPTIONAL flag read as `!== false` made- * the write the thing you got by saying nothing. Omission must be a compile error, not a- * silent install.- */- installAgentIntegrations: boolean}/**@@ -82,8 +66,8 @@ export function deriveLinkMap(deps: {}/**- * Boot context-link server-side: register the read handler + write the shim/skill/instructions- * (core), then keep the link map in step with the canvases on disk.+ * Boot context-link server-side: register the read handler + write the shim (core; the skill is the+ * consent lifecycle's, `core/agent-integrations.ts`), then keep the link map in step with the canvases on disk.** Returns `refresh` (also the onPersist hook the caller wires to the workspace store) and a* `stop` that settles the sweep — awaitable, because a refresh is a write into `dataDir` and a@@ -98,9 +82,7 @@ export function initServerContextLink(deps: ServerContextLinkDeps): {// No remote deps: the Server Edition runs ON the host whose transcripts and tmux it reads, so// the local-only behavior is the complete answer (SSH projects are a desktop-only concept here).- initContextLink(deps.ptyManager, {}, {- installAgentIntegrations: deps.installAgentIntegrations- })+ initContextLink(deps.ptyManager, {})// Skip a rewrite when nothing a link document depends on has changed. The map alone is not the// whole input — a link's transcript path is resolved at write time from the hook-fed table, anddiff --git a/src/server/handlers/index.test.ts b/src/server/handlers/index.test.tsindex 005fbe06a..5fe257d9d 100644--- a/src/server/handlers/index.test.ts+++ b/src/server/handlers/index.test.ts@@ -5,6 +5,7 @@ import path from 'path'import { execFileSync } from 'child_process'import { ServerPlatform } from '../platform-server'import { registerCoreHandlers } from './index'+import { createIntegrationLifecycle, registerIntegrationLifecycle } from '../../core/agent-integrations'import { IPC } from '../../shared/ipc'import { DEFAULT_SETTINGS, type GitStatus } from '../../shared/types'import { initPlatform, resetPlatformForTests } from '../../core/platform'@@ -15,7 +16,8 @@ import { projectImagesDir } from '../../core/canvas-images'// them here instead of running them: the real installer writes into the USER's `~/.nodeterm`, and// a unit test has no business touching the machine it runs on.const hookInstalls: string[] = []-vi.mock('../../core/agents/hooks/claude', () => ({+vi.mock('../../core/agents/hooks/claude', async (importOriginal) => ({+ ...(await importOriginal<typeof import('../../core/agents/hooks/claude')>()),installClaudeHooksInto: (dir: string) => {hookInstalls.push(dir)},@@ -163,7 +165,16 @@ describe('registerCoreHandlers (download tickets)', () => {describe('registerCoreHandlers (managed Claude accounts, #313)', () => {beforeEach(() => {hookInstalls.length = 0- })+ // The account's hook comes from the consent lifecycle (#744) — claude enabled here.+ registerIntegrationLifecycle(+ createIntegrationLifecycle({+ settings: () => ({ ...DEFAULT_SETTINGS, agentIntegrations: { agents: { claude: 'enabled' }, origin: 'asked' } }),+ userDataDir: () => repo,+ shims: () => ({ context: path.join(repo, 'context-links', 'context.sh') })+ })+ )+ })+ afterEach(() => registerIntegrationLifecycle(null))it('add() creates the config dir under this host userData and remove() deletes it', async () => {const added = (await call(IPC.claudeAccountsAdd)) as { id: string; configDir: string }diff --git a/src/server/index.ts b/src/server/index.tsindex 7586b3b56..cd11cfd55 100644--- a/src/server/index.ts+++ b/src/server/index.ts@@ -51,7 +51,7 @@ import { registerLogHandlers } from '../core/log-handlers'import os from 'os'import { hookServer } from '../core/agents/hook-server'import { serverEditionControlHandler } from './control-unsupported'-import { initServerCanvasControl, type ServerCanvasControl } from './canvas-control'+import { initServerCanvasControl, serverCanvasShimPath, type ServerCanvasControl } from './canvas-control'import { registerStationNoticeIpc } from '../core/agents/station-notice'import { registerStationOutcomeIpc } from '../core/station-outcome-store'import { registerStationHandoverIpc } from '../core/station-handover'@@ -66,8 +66,14 @@ import {} from '../core/agents/pending-approvals'import { answerHeldPermission } from '../core/agents/permission-decision'import type { AnswerPermissionPayload } from '../shared/agents/permission-answer'-import { installManagedAgentHooks } from '../core/agents/hooks'-import { installHooksIntoLocalAccounts } from '../core/claude-accounts-service'+import {+ createIntegrationLifecycle,+ detectExistingIntegrations,+ registerIntegrationLifecycle,+ resolveIntegrationConsentAtBoot+} from '../core/agent-integrations'+import { registerIntegrationIpc } from '../core/agent-integrations-ipc'+import { contextLinkShimPath } from '../core/context-link'import {initAgentStatusMirror,flush as flushAgentStatusMirror,@@ -268,6 +274,19 @@ export async function startServer(} catch (error) {console.warn('[model-gateway] could not migrate the legacy API key to secret storage', error)}+ // Agent-integration consent (issue #744): grandfather an install from before this feature (our own+ // hook scripts / shims are on disk) as enabled, before any browser can load settings.+ if (config.installHooks !== false) {+ try {+ const grandfathered = resolveIntegrationConsentAtBoot(+ settingsStore.get(),+ detectExistingIntegrations(config.dataDir)+ )+ if (grandfathered) await settingsStore.save(grandfathered)+ } catch (error) {+ console.warn('[integrations] could not record the grandfathered consent', error)+ }+ }settingsStore.registerIpc()// Gateway discovery/credential IPC. NO env snapshot on the server: every registered handler// here is dispatchable by any authenticated WS client, and the server process environment is@@ -685,21 +704,23 @@ export async function startServer(mobilePushEnabled: () => settingsStore.get().mobilePushEnabled !== false,mobileLiveActivities: () => settingsStore.get().mobileLiveActivities !== false})- // `installHooks: false` (tests) skips the merge into the user's real ~/.claude et al —- // the hook it would write points into `dataDir`, which a test then deletes.- if (config.installHooks !== false) {- try {- // Fail-open: installManagedAgentHooks is itself best-effort, but a throw must never block boot.- installManagedAgentHooks()- } catch (e) {- console.warn('[nodeterm-server] managed hook install failed', e)- }- // Managed Claude accounts each carry their OWN settings.json (Claude Code resolves it relative- // to CLAUDE_CONFIG_DIR), so the hook has to be re-installed there as well or a managed account- // reports no agent status at all. Canvas-control adds its skill in its own opt-in initializer;- // this baseline hook pass stays unchanged when the feature flag is off.- installHooksIntoLocalAccounts(settingsStore.get().claudeAccounts ?? [])- }+ // Agent-integration consent (issue #744) — the same lifecycle the desktop boots: hooks + skills+ // only for the agents the user enabled, a declined one cleaned up, nothing for an undecided one.+ // `installHooks: false` (tests) is a hard veto that outranks every choice: the hook it would write+ // points into `dataDir`, which a test then deletes.+ const integrations = createIntegrationLifecycle({+ settings: () => settingsStore.get(),+ userDataDir: () => config.dataDir,+ shims: () => ({+ canvas: config.canvasControl === true ? serverCanvasShimPath() : undefined,+ context: contextLinkShimPath()+ }),+ veto: config.installHooks === false+ })+ registerIntegrationLifecycle(integrations)+ integrations.reconcile()+ settingsStore.onChange((s) => integrations.onSettingsChanged(s))+ registerIntegrationIpc(integrations)const hookStartupWarning = await hookServer.startForApp()if (hookStartupWarning) console.error('[nodeterm-server]', hookStartupWarning)// Safe default and rollback path. The opt-in runtime replaces this handler only after its@@ -742,8 +763,7 @@ export async function startServer(// src/server/context-link.ts.const contextLink = initServerContextLink({ptyManager,- canvases: () => workspaceStore.persistedCanvases(),- installAgentIntegrations: config.installHooks !== false+ canvases: () => workspaceStore.persistedCanvases()})// A governed project's outside edit goes to the canvas authority, which publishes the difference// as canvas ops and then the persisted project on `workspace:server-change` (its non-content@@ -792,7 +812,6 @@ export async function startServer(snapshot: (projectId) => github.service.controlSnapshot(projectId),dispatch: (projectId) => boardDispatchReports.forProject(projectId)},- installAgentIntegrations: config.installHooks !== false,// The durable orchestration facts follow hook-endpoint ownership, like the request ledger.ownsDurableState: hookStartupWarning === null})diff --git a/src/shared/agent-integrations.test.ts b/src/shared/agent-integrations.test.tsnew file mode 100644index 000000000..6abf671cc--- /dev/null+++ b/src/shared/agent-integrations.test.ts@@ -0,0 +1,105 @@+import { describe, expect, it } from 'vitest'+import {+ INTEGRATION_AGENT_IDS,+ MAX_HOST_CHOICES,+ answerIntegrationPrompt,+ grandfatheredIntegrations,+ hostChoice,+ localIntegrationSignature,+ needsGrandfatherNotice,+ needsIntegrationPrompt,+ remoteIntegrationPlan,+ sanitizeAgentIntegrations,+ withAgentChoice,+ withHostChoice,+ withNoticeDismissed+} from './agent-integrations'+import { sshHostKey } from './ssh'++describe('sanitizeAgentIntegrations (settings.json is hand-editable)', () => {+ it('drops unknown agents, bad choices, malformed host keys; keeps the rest', () => {+ const s = sanitizeAgentIntegrations({+ agents: { claude: 'enabled', codex: 'yes', nope: 'enabled', gemini: 'declined', constructor: 'enabled' },+ hosts: { 'u@h': 'declined', 'no-at-sign': 'enabled', 'a@b c': 'enabled' },+ hostDefault: 'maybe',+ origin: 'hacked',+ noticeDismissed: 'true'+ })+ expect(s).toEqual({ agents: { claude: 'enabled', gemini: 'declined' }, hosts: { 'u@h': 'declined' } })+ })++ it('bounds the host list', () => {+ const hosts = Object.fromEntries(Array.from({ length: MAX_HOST_CHOICES + 50 }, (_, i) => [`u@h${i}`, 'enabled']))+ expect(Object.keys(sanitizeAgentIntegrations({ hosts }).hosts ?? {})).toHaveLength(MAX_HOST_CHOICES)+ })++ it('a non-object is no record at all', () => {+ expect(sanitizeAgentIntegrations('enabled')).toEqual({})+ expect(sanitizeAgentIntegrations(null)).toEqual({})+ })+})++describe('the first-run question and the grandfathered notice', () => {+ it('a new install (no record) is asked; an answer, either way, is not asked again', () => {+ expect(needsIntegrationPrompt({})).toBe(true)+ expect(needsIntegrationPrompt({ agentIntegrations: answerIntegrationPrompt([]) })).toBe(false)+ expect(needsIntegrationPrompt({ agentIntegrations: answerIntegrationPrompt(['claude']) })).toBe(false)+ })++ it('"Not now" records a decline for every agent; "Enable all" an enable', () => {+ const none = answerIntegrationPrompt([])+ const all = answerIntegrationPrompt([...INTEGRATION_AGENT_IDS])+ for (const a of INTEGRATION_AGENT_IDS) {+ expect(none.agents?.[a]).toBe('declined')+ expect(all.agents?.[a]).toBe('enabled')+ }+ })++ it('a grandfathered install shows the notice once', () => {+ const g = { agentIntegrations: grandfatheredIntegrations() }+ expect(needsIntegrationPrompt(g)).toBe(false)+ expect(needsGrandfatherNotice(g)).toBe(true)+ expect(needsGrandfatherNotice(withNoticeDismissed(g))).toBe(false)+ })+})++describe('per-SSH-host consent', () => {+ it('is keyed on the HOST identity: editing the identity file / port / extra args keeps it', () => {+ const before = { host: 'srv.example', user: 'me', port: 22, identityFile: '~/.ssh/a' }+ const after = { host: 'srv.example', user: 'me', port: 2222, identityFile: '~/.ssh/b', extraArgs: ['-A'] }+ const s = withHostChoice({}, sshHostKey(before), 'enabled')+ expect(hostChoice(s, sshHostKey(after))).toBe('enabled')+ })++ it('an unanswered host installs nothing and removes nothing', () => {+ const s = { agentIntegrations: answerIntegrationPrompt([...INTEGRATION_AGENT_IDS]) }+ expect(remoteIntegrationPlan(s, 'me@srv')).toEqual({ install: [], remove: [], decided: false })+ })++ it('an enabled host installs only the locally enabled agents and removes the declined ones', () => {+ let s = withHostChoice({ agentIntegrations: answerIntegrationPrompt(['claude', 'codex']) }, 'me@srv', 'enabled')+ s = withAgentChoice(s, 'codex', 'declined')+ const plan = remoteIntegrationPlan(s, 'me@srv')+ expect(plan.install).toEqual(['claude'])+ expect(plan.remove).toContain('codex')+ expect(plan.decided).toBe(true)+ })++ it('a declined host removes everything', () => {+ const s = withHostChoice({ agentIntegrations: answerIntegrationPrompt(['claude']) }, 'me@srv', 'declined')+ expect(remoteIntegrationPlan(s, 'me@srv')).toEqual({ install: [], remove: [...INTEGRATION_AGENT_IDS], decided: true })+ })++ it('grandfathered: hosts with no answer of their own keep working', () => {+ const s = { agentIntegrations: grandfatheredIntegrations() }+ expect(remoteIntegrationPlan(s, 'me@old-host').install).toEqual([...INTEGRATION_AGENT_IDS])+ })+})++describe('localIntegrationSignature', () => {+ it('moves with the consent and ignores everything else', () => {+ const a = { agentIntegrations: answerIntegrationPrompt(['claude']) }+ expect(localIntegrationSignature({ ...a, fontSize: 12 } as object)).toBe(localIntegrationSignature(a))+ expect(localIntegrationSignature(withAgentChoice(a, 'claude', 'declined'))).not.toBe(localIntegrationSignature(a))+ })+})diff --git a/src/shared/agent-integrations.ts b/src/shared/agent-integrations.tsnew file mode 100644index 000000000..46fbead9e--- /dev/null+++ b/src/shared/agent-integrations.ts@@ -0,0 +1,189 @@+// Agent-integration consent (issue #744): which agents nodeterm may integrate with by writing into+// their user-owned global configuration (status hooks, skills), here and on each SSH host.+//+// Pure and shared by every side: core decides what to install from it, the renderer renders the+// choice from it, and settings.json is hand-editable, so every reader goes through `sanitize…`.+//+// THE RULE: nothing global is written for an agent unless its choice is `'enabled'`. `undefined`+// (never asked) is NOT consent — it writes nothing and removes nothing. `'declined'` writes nothing+// AND removes what we wrote. See docs/agent-integration-consent.md for the product decision.+import { AGENT_HOOK_TARGETS } from './agents/config'++/** Every agent nodeterm can integrate with = every agent it has a status hook for. */+export const INTEGRATION_AGENT_IDS = AGENT_HOOK_TARGETS+export type IntegrationAgentId = (typeof INTEGRATION_AGENT_IDS)[number]++export type IntegrationChoice = 'enabled' | 'declined'++export interface AgentIntegrationsSettings {+ /** Per-agent choice for THIS machine. Absent key = never asked. */+ agents?: Partial<Record<IntegrationAgentId, IntegrationChoice>>+ /** Per-SSH-host choice, keyed by `sshHostKey` (`user@host`) — the HOST identity only, never the+ * identity file / port / extra args, so editing how we reach a host does not drop its consent.+ * A host installs an agent only when BOTH the host and that agent are enabled. */+ hosts?: Record<string, IntegrationChoice>+ /** The choice for a host with no entry in `hosts`. Absent = ask. Set to `'enabled'` only by+ * grandfathering, so SSH hosts an existing install already integrated keep working. */+ hostDefault?: IntegrationChoice+ /** How the record came to exist: `'grandfathered'` = an install from before this feature (we+ * found our own integrations already on disk), `'asked'` = the user answered the first-run+ * question. Absent = a new install that has not answered yet. */+ origin?: 'grandfathered' | 'asked'+ /** The grandfathered install's one-time notice was dismissed. */+ noticeDismissed?: boolean+}++const isAgent = (v: string): v is IntegrationAgentId => (INTEGRATION_AGENT_IDS as readonly string[]).includes(v)+const isChoice = (v: unknown): v is IntegrationChoice => v === 'enabled' || v === 'declined'+// Same shape the rest of the app accepts for a host key (`user@host`); anything else is dropped+// rather than carried into a log line or a UI row.+const HOST_KEY = /^[^\s@]{1,128}@[^\s@]{1,253}$/+/** Bounded: settings.json is hand-editable and every entry is a row in Settings. */+export const MAX_HOST_CHOICES = 200++/** Normalize a hand-editable value. Unknown agents, bad choices and malformed host keys are dropped. */+export function sanitizeAgentIntegrations(raw: unknown): AgentIntegrationsSettings {+ if (!raw || typeof raw !== 'object') return {}+ const r = raw as Record<string, unknown>+ const out: AgentIntegrationsSettings = {}+ if (r.agents && typeof r.agents === 'object') {+ const agents: Partial<Record<IntegrationAgentId, IntegrationChoice>> = {}+ for (const [k, v] of Object.entries(r.agents as Record<string, unknown>)) {+ if (isAgent(k) && isChoice(v)) agents[k] = v+ }+ out.agents = agents+ }+ if (r.hosts && typeof r.hosts === 'object') {+ const hosts: Record<string, IntegrationChoice> = {}+ let n = 0+ for (const [k, v] of Object.entries(r.hosts as Record<string, unknown>)) {+ if (n >= MAX_HOST_CHOICES) break+ if (HOST_KEY.test(k) && isChoice(v)) {+ hosts[k] = v+ n+++ }+ }+ out.hosts = hosts+ }+ if (isChoice(r.hostDefault)) out.hostDefault = r.hostDefault+ if (r.origin === 'grandfathered' || r.origin === 'asked') out.origin = r.origin+ if (r.noticeDismissed === true) out.noticeDismissed = true+ return out+}++type WithIntegrations = { agentIntegrations?: unknown }++export function integrationsOf(settings: WithIntegrations): AgentIntegrationsSettings {+ return sanitizeAgentIntegrations(settings.agentIntegrations)+}++/** This machine's choice for one agent. `undefined` = never asked. */+export function agentChoice(settings: WithIntegrations, agent: string): IntegrationChoice | undefined {+ return isAgent(agent) ? integrationsOf(settings).agents?.[agent] : undefined+}++export function isAgentIntegrationEnabled(settings: WithIntegrations, agent: string): boolean {+ return agentChoice(settings, agent) === 'enabled'+}++/** A host's choice: its own entry, else the default, else `undefined` (= ask). */+export function hostChoice(settings: WithIntegrations, hostKey: string): IntegrationChoice | undefined {+ const s = integrationsOf(settings)+ return s.hosts?.[hostKey] ?? s.hostDefault+}++/** The agents nodeterm may integrate with on one SSH host: host enabled AND agent enabled. */+export function remoteIntegrationAgents(settings: WithIntegrations, hostKey: string): IntegrationAgentId[] {+ if (hostChoice(settings, hostKey) !== 'enabled') return []+ return INTEGRATION_AGENT_IDS.filter((a) => isAgentIntegrationEnabled(settings, a))+}++/** What nodeterm may do on one SSH host: install for the agents enabled both here and for that+ * host; remove what it wrote for the rest once the host has an answer. An unanswered host gets+ * neither — nothing is written AND nothing is removed until the user says. */+export function remoteIntegrationPlan(+ settings: WithIntegrations,+ hostKey: string+): { install: IntegrationAgentId[]; remove: IntegrationAgentId[]; decided: boolean } {+ const choice = hostChoice(settings, hostKey)+ if (choice === undefined) return { install: [], remove: [], decided: false }+ if (choice === 'declined') return { install: [], remove: [...INTEGRATION_AGENT_IDS], decided: true }+ const s = integrationsOf(settings)+ return {+ install: INTEGRATION_AGENT_IDS.filter((a) => s.agents?.[a] === 'enabled'),+ remove: INTEGRATION_AGENT_IDS.filter((a) => s.agents?.[a] === 'declined'),+ decided: true+ }+}++/** A new install that has not answered the first-run question: ask before writing anything. */+export function needsIntegrationPrompt(settings: WithIntegrations): boolean {+ const s = integrationsOf(settings)+ return !s.origin && Object.keys(s.agents ?? {}).length === 0+}++/** A grandfathered install that has not dismissed the one-time notice. */+export function needsGrandfatherNotice(settings: WithIntegrations): boolean {+ const s = integrationsOf(settings)+ return s.origin === 'grandfathered' && !s.noticeDismissed+}++/** The record an install from before this feature gets: everything it already had stays on, so+ * nobody's badges or canvas control silently stop on upgrade. */+export function grandfatheredIntegrations(): AgentIntegrationsSettings {+ const agents: Partial<Record<IntegrationAgentId, IntegrationChoice>> = {}+ for (const a of INTEGRATION_AGENT_IDS) agents[a] = 'enabled'+ return { agents, hostDefault: 'enabled', origin: 'grandfathered' }+}++/** The first-run answer: the listed agents enabled, every other one declined. */+export function answerIntegrationPrompt(enabled: readonly string[]): AgentIntegrationsSettings {+ const agents: Partial<Record<IntegrationAgentId, IntegrationChoice>> = {}+ for (const a of INTEGRATION_AGENT_IDS) agents[a] = enabled.includes(a) ? 'enabled' : 'declined'+ return { agents, origin: 'asked' }+}++export function withAgentChoice<S extends WithIntegrations>(settings: S, agent: IntegrationAgentId, choice: IntegrationChoice): S {+ const s = integrationsOf(settings)+ return { ...settings, agentIntegrations: { ...s, origin: s.origin ?? 'asked', agents: { ...s.agents, [agent]: choice } } }+}++export function withHostChoice<S extends WithIntegrations>(settings: S, hostKey: string, choice: IntegrationChoice): S {+ const s = integrationsOf(settings)+ return { ...settings, agentIntegrations: { ...s, hosts: { ...s.hosts, [hostKey]: choice } } }+}++export function withNoticeDismissed<S extends WithIntegrations>(settings: S): S {+ return { ...settings, agentIntegrations: { ...integrationsOf(settings), noticeDismissed: true } }+}++/** Stable key of everything that changes what is installed locally — the lifecycle reconciles+ * only when this moves, because the renderer saves full settings snapshots constantly. */+export function localIntegrationSignature(settings: WithIntegrations): string {+ const s = integrationsOf(settings)+ return INTEGRATION_AGENT_IDS.map((a) => `${a}=${s.agents?.[a] ?? '-'}`).join(',')+}++/** Same, for one SSH host. */+export function remoteIntegrationSignature(settings: WithIntegrations, hostKey: string): string {+ return `${hostChoice(settings, hostKey) ?? '-'}|${localIntegrationSignature(settings)}`+}++/** What a declined (or not-yet-answered) agent loses, in the user's words. One list so the+ * first-run prompt and Settings cannot describe two different products. Terminals themselves+ * always work. */+export const FEATURES_NEEDING_INTEGRATION: readonly string[] = [+ 'running / needs-you status badges, unread dots and completion notifications',+ 'session names, the context meter and subagent cards',+ 'canvas control (agents opening and organizing nodes) and reading linked nodes'+]++/** What the host's last reconcile did (Settings → Agents). */+export interface AgentIntegrationsStatus {+ enabled: string[]+ declined: string[]+ /** User-edited files we kept rather than overwrite or delete (bounded). */+ retained: string[]+ /** Server Edition started with `installHooks: false`: nothing global is written. */+ vetoed: boolean+}diff --git a/src/shared/host-control.ts b/src/shared/host-control.tsindex 748ac0039..f418b51dc 100644--- a/src/shared/host-control.ts+++ b/src/shared/host-control.ts@@ -65,7 +65,10 @@ export const HOST_ONLY_CHANNEL_PREFIXES: readonly string[] = [// Live links: publishing a host terminal to anyone with a URL, with the host's Pro. No relay peer// may create, list (every link's URL carries its secret), stop, kick or chat as the owner. The// viewer's own protocol is `watch:*`, which this prefix deliberately does not match.- 'watchLink:'+ 'watchLink:',+ // Agent-integration consent status: paths in the host's home it kept or wrote. The consent itself+ // is in settings (already host-only).+ 'integrations:']export const HOST_ONLY_CHANNELS: ReadonlySet<string> = new Set([diff --git a/src/shared/ipc.ts b/src/shared/ipc.tsindex b98476936..c0d166e6b 100644--- a/src/shared/ipc.ts+++ b/src/shared/ipc.ts@@ -522,6 +522,9 @@ export const IPC = {filesSaveAlertSound: 'files:save-alert-sound',filesReadAlertSound: 'files:read-alert-sound',filesClearAlertSound: 'files:clear-alert-sound',+ /** Agent-integration consent (issue #744): the last reconcile's report (what is enabled,+ * declined, and which user-edited files were kept). Host-only. */+ integrationsStatus: 'integrations:status',settingsLoad: 'settings:load',settingsSave: 'settings:save',sshList: 'ssh:list',diff --git a/src/shared/types.ts b/src/shared/types.tsindex 0f90c2846..1233b8222 100644--- a/src/shared/types.ts+++ b/src/shared/types.ts@@ -3,6 +3,7 @@ import type { PushWebhookMinted, PushWebhookResult, PushWebhookTokenInfo } fromimport type { IdentitySeedEntry } from './agent-identity-seed'import type { PrWaitHold } from './pr-wait'import type { SessionBackend } from './session-backend'+import type { AgentIntegrationsSettings } from './agent-integrations'// Types shared across the main, preload, and renderer processes.import { TABBAR_HEIGHT_PX } from './window-chrome-metrics'@@ -2251,6 +2252,11 @@ export interface Settings {* strands a live session gets their canvas back without downgrading the app. Neither value ever* admits a forged token. */hookIdentityStrict?: boolean+ /** Agent-integration consent (issue #744, `@shared/agent-integrations`): which agents nodeterm+ * may integrate with by writing into their user-owned global config (status hooks, skills),+ * here and per SSH host. Optional and absent from DEFAULT_SETTINGS: absent = a new install that+ * has not been asked, which writes NOTHING. Hand-editable, so every reader sanitizes. */+ agentIntegrations?: AgentIntegrationsSettings/** Machine-local waivers for the canvas-control destructive confirm dialog* (@shared/control-confirm). Absent — and absent from DEFAULT_SETTINGS — means "always ask",* which is the pre-feature behavior bit for bit.@@ -2434,6 +2440,12 @@ export interface SettingsApi {save(settings: Settings): Promise<void>}+/** Agent-integration consent status (issue #744). The CHOICE rides `settings.agentIntegrations`;+ * this only reports what the host's last reconcile did. */+export interface IntegrationsApi {+ status(): Promise<import('./agent-integrations').AgentIntegrationsStatus>+}+/** A downloadable whisper model plus its on-disk status, as returned by `speech.models()`. */export interface SpeechModelInfo extends WhisperModelInfo {downloaded: boolean@@ -4191,6 +4203,7 @@ export interface NodeTerminalApi {worktree: WorktreeApidialog: DialogApisettings: SettingsApi+ integrations: IntegrationsApispeech: SpeechApissh: SshApisshProject: SshProjectApidiff --git a/test/server/hook-install-guard.test.ts b/test/server/hook-install-guard.test.tsindex a36e3f486..4cdd92a44 100644--- a/test/server/hook-install-guard.test.ts+++ b/test/server/hook-install-guard.test.ts@@ -10,7 +10,11 @@ import path from 'path'// which Claude Code runs on every tool call, so every later session on that machine died.// `installHooks: false` is the opt-out; every server test must pass it. This test keeps the// flag honest (and the default — a real deployment does need the hooks installed).-vi.mock('../../src/core/agents/hooks', () => ({ installManagedAgentHooks: vi.fn() }))+vi.mock('../../src/core/agents/hooks', async (importOriginal) => ({+ ...(await importOriginal<typeof import('../../src/core/agents/hooks')>()),+ installManagedAgentHooks: vi.fn(),+ removeManagedAgentHooks: vi.fn()+}))import { startServer } from '../../src/server/index'import { installManagedAgentHooks } from '../../src/core/agents/hooks'@@ -56,11 +60,36 @@ describe('startServer: managed hook install is opt-out-able', () => {expect(fs.existsSync(path.join(testHome, '.codex', 'AGENTS.md'))).toBe(false)}, 30_000)- it('installs the hooks by default (real deployments need them)', async () => {+ // Issue #744: the default no longer writes into a user's agent config without consent.+ it('a NEW install (nothing of ours on disk, no answer) writes nothing — it is asked first', async () => {+ const srv = await boot(undefined)+ close = srv.close+ expect(installManagedAgentHooks).not.toHaveBeenCalled()+ expect(fs.existsSync(path.join(testHome, '.claude'))).toBe(false)+ expect(fs.existsSync(path.join(testHome, '.codex'))).toBe(false)+ }, 30_000)++ it('installs for the agents the user enabled — skills in their own dirs, nothing in AGENTS.md', async () => {+ fs.writeFileSync(+ path.join(dataDir, 'settings.json'),+ JSON.stringify({ agentIntegrations: { agents: { claude: 'enabled', codex: 'enabled' }, origin: 'asked' } })+ )const srv = await boot(undefined)close = srv.closeexpect(installManagedAgentHooks).toHaveBeenCalledOnce()+ expect([...vi.mocked(installManagedAgentHooks).mock.calls[0][0]].sort()).toEqual(['claude', 'codex'])expect(fs.existsSync(path.join(testHome, '.claude', 'skills', 'get-linked-context', 'SKILL.md'))).toBe(true)- expect(fs.existsSync(path.join(testHome, '.codex', 'AGENTS.md'))).toBe(true)+ expect(fs.existsSync(path.join(testHome, '.codex', 'skills', 'get-linked-context', 'SKILL.md'))).toBe(true)+ expect(fs.existsSync(path.join(testHome, '.codex', 'AGENTS.md'))).toBe(false)+ }, 30_000)++ it('an existing install (our hook scripts on disk) is grandfathered as enabled at boot', async () => {+ fs.mkdirSync(path.join(testHome, '.nodeterm', 'agent-hooks'), { recursive: true })+ fs.writeFileSync(path.join(testHome, '.nodeterm', 'agent-hooks', 'claude.sh'), '#!/bin/sh\n')+ const srv = await boot(undefined)+ close = srv.close+ expect(installManagedAgentHooks).toHaveBeenCalledOnce()+ const saved = JSON.parse(fs.readFileSync(path.join(dataDir, 'settings.json'), 'utf8'))+ expect(saved.agentIntegrations.origin).toBe('grandfathered')}, 30_000)})diff --git a/test/setup/agent-env.ts b/test/setup/agent-env.tsnew file mode 100644index 000000000..df550f9b2--- /dev/null+++ b/test/setup/agent-env.ts@@ -0,0 +1,21 @@+// TEST-ONLY — issue #744. A developer running the suite from INSIDE a nodeterm agent session (the+// normal way this repo is worked on) inherits that session's agent-config relocation variables —+// a managed Claude account's `CLAUDE_CONFIG_DIR` above all. Code under test resolves the agent's+// LIVE config dir from them (`claudeSystemConfigDir`, `systemCodexHome`, …), so a test that boots+// the real integration lifecycle with a scratch `HOME` still wrote into the developer's own+// account dir (measured: a server boot test overwrote the session's `get-linked-context` skill).+// CI never sets these; stripping them here makes every machine behave like CI. A test that needs+// one sets it itself.+for (const k of [+ 'CLAUDE_CONFIG_DIR',+ 'CODEX_HOME',+ 'GROK_HOME',+ 'COPILOT_HOME',+ 'GEMINI_CLI_HOME',+ 'XDG_CONFIG_HOME',+ 'NODETERM_NODE_ID',+ 'NODETERM_HOOK_ENDPOINT',+ 'NODETERM_CANVAS_CONTROL'+]) {+ delete process.env[k]+}diff --git a/vitest.config.ts b/vitest.config.tsindex 02dcb1257..259ea5c27 100644--- a/vitest.config.ts+++ b/vitest.config.ts@@ -42,7 +42,7 @@ export default defineConfig({'test/setup/tmux-sandbox.ts','test/setup/tmp-sandbox.ts'],- setupFiles: ['test/setup/tmux-worker-env.ts', 'test/setup/tmp-worker-env.ts', 'test/setup/jsdom-storage.ts'],+ setupFiles: ['test/setup/tmux-worker-env.ts', 'test/setup/agent-env.ts', 'test/setup/tmp-worker-env.ts', 'test/setup/jsdom-storage.ts'],// Issue #160: with the default (one worker per core), a 10-core Mac runs ~10 fs-heavy suites// at once and transient fd exhaustion (EMFILE) turns into silent test flakiness — probes like// `fs.existsSync` swallow the error and answer false, so whole files fail in ways that never