Skip to content

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.

feat(grok): install grok status hooks on SSH hosts, under the host's GROK_HOME

enes540197d179b4
diff --git a/src/main/remote-ssh/remote-hooks.test.ts b/src/main/remote-ssh/remote-hooks.test.ts
index 66645c48f..d30ab76c3 100644
--- a/src/main/remote-ssh/remote-hooks.test.ts
+++ b/src/main/remote-ssh/remote-hooks.test.ts
@@ -3,13 +3,29 @@ import { RemoteHooks } from './remote-hooks'
const conn = { host: 'h', user: 'u' }
-function mk(opts: { verifyAnswers?: string[] } = {}) {
- const calls: { args: string[]; stdin?: string }[] = []
+function harness(
+ opts: {
+ verifyAnswers?: string[]
+ /** Command-substring → that run's stdout, matched (in declaration order) BEFORE the built-in
+ * defaults below. This is how a test answers a host probe (`$HOME`, the host's own
+ * `GROK_HOME`) or hands back a present-but-malformed remote config file. */
+ responses?: Record<string, string>
+ /** Command substring whose run REJECTS — the fail-open proof for one remote step. */
+ failOn?: string
+ } = {}
+) {
+ // One record per ssh child command. `args` is what the runner was handed; `cmd` is the joined
+ // line the assertions match on (both views of the SAME array, so `calls` and `runs` agree).
+ const calls: { args: string[]; stdin?: string; cmd: string }[] = []
// Tunnel-verify curl answers, consumed in order (default: healthy on the first try).
const verifyAnswers = [...(opts.verifyAnswers ?? ['204'])]
const run = vi.fn(async (args: string[], stdin?: string) => {
- calls.push({ args, stdin })
const joined = args.join(' ')
+ calls.push({ args, stdin, cmd: joined })
+ if (opts.failOn && joined.includes(opts.failOn)) throw new Error(`fake ssh failed: ${opts.failOn}`)
+ for (const [needle, stdout] of Object.entries(opts.responses ?? {})) {
+ if (joined.includes(needle)) return { code: 0, stdout }
+ }
// resolve the remote $HOME probe → absolute remote paths build from this.
if (joined.includes('$HOME')) return { code: 0, stdout: '/home/u' }
if (joined.includes('cat /home/u/.claude/settings.json')) return { code: 0, stdout: '{}' }
@@ -17,12 +33,12 @@ function mk(opts: { verifyAnswers?: string[] } = {}) {
if (joined.includes('%{http_code}')) return { code: 0, stdout: verifyAnswers.shift() ?? '204' }
return { code: 0, stdout: '' }
})
- return { rh: new RemoteHooks({ run }), calls, run }
+ return { rh: new RemoteHooks({ run }), calls, runs: calls, run, conn }
}
describe('RemoteHooks.setup', () => {
it('opens a reverse forward, writes the endpoint file, and installs the managed hook for claude', async () => {
- const { rh, calls } = mk()
+ const { rh, calls } = harness()
const res = await rh.setup('p1', conn, '/s.sock', { port: 51234, token: 'tok', version: '1' })
// Endpoint file is PER-PROJECT (was a single shared hook-endpoint.env): each connection —
// real project OR a transient folder-picker browse — has its own reverse-tunnel socket, so a
@@ -58,7 +74,7 @@ describe('RemoteHooks.setup', () => {
})
it('installs codex too — hooks.json merge PLUS the config.toml trust write', async () => {
- const { rh, calls } = mk()
+ const { rh, calls } = harness()
const res = await rh.setup('p1', conn, '/s.sock', { port: 51234, token: 'tok', version: '1' })
expect(res).not.toBeNull()
const joined = calls.map((c) => c.args.join(' '))
@@ -107,7 +123,7 @@ describe('RemoteHooks.setup', () => {
it('verifies the tunnel end-to-end and heals a stale forward with one rebind', async () => {
// First verify sees a dead target (a reused live-orphan master serving a previous run's
// forward — the field case that killed remote statuses for hours); the rebind fixes it.
- const { rh, calls } = mk({ verifyAnswers: ['000', '204'] })
+ const { rh, calls } = harness({ verifyAnswers: ['000', '204'] })
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.env')
const joined = calls.map((c) => c.args.join(' '))
@@ -119,7 +135,7 @@ describe('RemoteHooks.setup', () => {
})
it('refuses to advertise a tunnel that never verifies — no endpoint file, null result', async () => {
- const { rh, calls } = mk({ verifyAnswers: ['000', '000'] })
+ const { rh, calls } = harness({ verifyAnswers: ['000', '000'] })
const res = await rh.setup('p1', conn, '/s.sock', { port: 51234, token: 'tok', version: '1' })
expect(res).toBeNull()
// The endpoint file must NOT be written: sessions would source a socket that answers nothing.
@@ -145,8 +161,8 @@ describe('RemoteHooks.setup', () => {
})
it('gives two different projects (or a browse) distinct endpoint files — no shared clobber', async () => {
- const a = await mk().rh.setup('proj', conn, '/s', { port: 1, token: 't', version: '1' })
- const { rh, calls } = mk()
+ const a = await harness().rh.setup('proj', conn, '/s', { port: 1, token: 't', version: '1' })
+ const { rh, calls } = harness()
const b = await rh.setup('ssh-browse-xyz', conn, '/s', { port: 2, token: 't', version: '1' })
expect(a?.endpointPath).toBe('/home/u/.nodeterm/hook-endpoint-proj.env')
expect(b?.endpointPath).toBe('/home/u/.nodeterm/hook-endpoint-ssh-browse-xyz.env')
@@ -157,6 +173,46 @@ describe('RemoteHooks.setup', () => {
})
})
+describe('RemoteHooks.setup — grok', () => {
+ it('writes our hook file under the HOST\'s $GROK_HOME with the `.*` tool matcher', async () => {
+ const { rh, conn, runs } = harness({
+ // The host answers $HOME first (existing behavior), then its own $GROK_HOME.
+ responses: { '$HOME': '/home/dev', 'GROK_HOME': '/home/dev/.grok' }
+ })
+ await rh.setup('p1', conn, '/s.sock', { port: 1234, token: 't', version: '1' })
+ const write = runs.find((r) => r.cmd.includes('/home/dev/.grok/hooks/nodeterm-status.json') && r.stdin)
+ expect(write).toBeTruthy()
+ const cfg = JSON.parse(write!.stdin!)
+ expect(cfg.hooks.PreToolUse[0].matcher).toBe('.*')
+ expect(cfg.hooks.Stop[0].matcher).toBeUndefined()
+ expect(cfg.hooks.SessionStart[0].hooks[0].command).toContain('/home/dev/.nodeterm/agent-hooks/grok.sh')
+ // The shared managed script is written on the host too, posting to /hook/grok through the tunnel.
+ const script = runs.find((r) => r.cmd.includes('agent-hooks/grok.sh') && r.stdin)
+ expect(script!.stdin).toContain('/hook/grok')
+ })
+
+ it('falls back to $HOME/.grok when the host reports an unusable GROK_HOME', async () => {
+ const { rh, conn, runs } = harness({ responses: { '$HOME': '/home/dev', 'GROK_HOME': 'relative/oops' } })
+ await rh.setup('p1', conn, '/s.sock', { port: 1234, token: 't', version: '1' })
+ expect(runs.some((r) => r.cmd.includes('/home/dev/.grok/hooks/nodeterm-status.json'))).toBe(true)
+ expect(runs.some((r) => r.cmd.includes('relative/oops'))).toBe(false)
+ })
+
+ it('never clobbers a present-but-malformed remote hook file', async () => {
+ const { rh, conn, runs } = harness({
+ responses: { '$HOME': '/home/dev', 'GROK_HOME': '/home/dev/.grok', 'nodeterm-status.json': '{ oops' }
+ })
+ await rh.setup('p1', conn, '/s.sock', { port: 1234, token: 't', version: '1' })
+ const write = runs.find((r) => r.cmd.includes('cat > ') && r.cmd.includes('nodeterm-status.json'))
+ expect(write).toBeUndefined()
+ })
+
+ it('a grok failure never breaks the connect (fail open)', async () => {
+ const { rh, conn } = harness({ failOn: 'nodeterm-status.json' })
+ await expect(rh.setup('p1', conn, '/s.sock', { port: 1234, token: 't', version: '1' })).resolves.toBeTruthy()
+ })
+})
+
describe('RemoteHooks.ensureFullscreenTui', () => {
// Paths are posixQuote'd (single-quoted) in the remote commands; a read is `cat '<path>' …`
// and a write is `… cat > '<path>'`, so we distinguish them by the presence of `cat >`.
@@ -208,7 +264,7 @@ describe('RemoteHooks.ensureFullscreenTui', () => {
describe('RemoteHooks.teardown', () => {
it('cancels the reverse forward', async () => {
- const { rh, run } = mk()
+ const { rh, run } = harness()
await rh.setup('p1', conn, '/s.sock', { port: 51234, token: 't', version: '1' })
run.mockClear()
await rh.teardown('p1', conn, '/s.sock')
@@ -225,7 +281,7 @@ describe('RemoteHooks.installCanvasControl', () => {
const isWriteTo = (args: string[], p: string) => args.join(' ').includes('cat > ') && args.join(' ').includes(p)
it('writes an executable shim + the skill, and merges the codex/gemini/opencode blocks', async () => {
- const { rh, calls } = mk()
+ 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
@@ -270,7 +326,7 @@ describe('RemoteHooks.installCanvasControl', () => {
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 = mk()
+ const first = harness()
await first.rh.installCanvasControl(conn, '/s.sock', '/home/u')
const merged = first.calls.find((c) => c.args.join(' ').includes('cat > \'/home/u/.gemini/GEMINI.md\''))?.stdin ?? ''
expect(merged).toBeTruthy()
@@ -289,7 +345,7 @@ describe('RemoteHooks.installCanvasControl', () => {
it('installs the skill into a remote managed-account config dir', async () => {
// claude resolves user skills relative to CLAUDE_CONFIG_DIR, so an account session never sees
// ~/.claude/skills — the same gap installIntoAccountDir exists for on the hook side.
- const { rh, calls } = mk()
+ const { rh, calls } = harness()
await rh.installCanvasSkillIntoAccountDir(conn, '/s.sock', '/home/u', 'acc-1')
const target = '/home/u/.nodeterm/claude-accounts/acc-1/skills/manage-nodeterm-canvas/SKILL.md'
expect(calls.some((c) => isWriteTo(c.args, target))).toBe(true)
@@ -309,7 +365,7 @@ describe('RemoteHooks.installContextLink', () => {
const isWriteTo = (args: string[], p: string) => args.join(' ').includes('cat > ') && args.join(' ').includes(p)
it('writes an executable shim + the skill, and merges the instruction blocks', async () => {
- const { rh, calls } = mk()
+ const { rh, calls } = harness()
await rh.installContextLink(conn, '/s.sock', '/home/u')
const joined = calls.map((c) => c.args.join(' '))
expect(joined.some((j) => j.includes("cat > '/home/u/.nodeterm/context.sh'") && j.includes('chmod 755'))).toBe(true)
@@ -346,7 +402,7 @@ describe('RemoteHooks.installContextLink', () => {
})
it('installs the skill into a remote managed-account config dir', async () => {
- const { rh, calls } = mk()
+ const { rh, calls } = harness()
await rh.installContextLinkSkillIntoAccountDir(conn, '/s.sock', '/home/u', 'acc-1')
const target = '/home/u/.nodeterm/claude-accounts/acc-1/skills/get-linked-context/SKILL.md'
expect(calls.some((c) => isWriteTo(c.args, target))).toBe(true)
diff --git a/src/main/remote-ssh/remote-hooks.ts b/src/main/remote-ssh/remote-hooks.ts
index bd31fdb35..ecadfc094 100644
--- a/src/main/remote-ssh/remote-hooks.ts
+++ b/src/main/remote-ssh/remote-hooks.ts
@@ -1,11 +1,13 @@
// Connection-time remote hook setup for SSH projects: opens the reverse unix-socket tunnel
// (local loopback hook server → remote socket), writes the owner-only remote endpoint file,
// and installs the managed hook into the remote agent configs (claude + gemini JSON settings,
-// plus codex's hooks.json + config.toml trust). Every step fails open: any remote failure →
-// setup returns null (or, for codex, the agent simply runs without status). Takes an INJECTED
-// runner so the flow is unit-testable without real ssh/electron.
+// codex's hooks.json + config.toml trust, and grok's own file inside the host's hooks directory).
+// Every step fails open: any remote failure → setup returns null (or, for codex/grok, that agent
+// simply runs without status). Takes an INJECTED runner so the flow is unit-testable without real
+// ssh/electron.
import { childArgs, hookForwardArgs, hookForwardCancelArgs, remoteEndpointFileContents } from '../../core/remote-ssh/control-master'
-import { CLAUDE_HOOK_EVENTS, GEMINI_HOOK_EVENTS } from '@shared/agents/hook-events'
+import { CLAUDE_HOOK_EVENTS, GEMINI_HOOK_EVENTS, GROK_HOOK_EVENTS } from '@shared/agents/hook-events'
+import { GROK_HOOK_FILE, isSafeRemoteGrokHome } from '../../core/agents/grok-paths'
import { buildManagedScript } from '../../core/agents/hooks/managed-script'
import { buildManagedHookCommand, mergeManagedHook, type HookSettings } from '../../core/agents/hooks/install-helper'
import {
@@ -43,7 +45,8 @@ export interface RemoteRunner {
// Per-agent remote install targets (JSON-settings agents merged via mergeManagedHook). Codex
// is installed separately (installCodexRemote) because it needs a hooks.json merge PLUS a
-// config.toml trust write — see that method.
+// config.toml trust write — see that method. Grok is separate too (installGrokRemote): its config
+// path is NOT $HOME-relative when the host sets GROK_HOME, which is exactly what this list assumes.
// Paths are relative to the remote $HOME and are made absolute once it is resolved at setup
// (a literal `~` is NOT expanded inside double quotes or when passed as data, so the merged
// hook command / endpoint file / `-R` bind path would otherwise carry an unexpanded tilde).
@@ -145,6 +148,8 @@ export class RemoteHooks {
}
// 4. codex: hooks.json merge + config.toml trust (its own shape — not a JSON-settings agent).
await this.installCodexRemote(conn, controlPath, home, remoteDir)
+ // 5. grok: our own file in its hooks DIRECTORY, under the HOST's $GROK_HOME.
+ await this.installGrokRemote(conn, controlPath, home, remoteDir)
return { endpointPath: endpoint }
} catch {
return null // fail-open: agent runs without hooks
@@ -240,6 +245,56 @@ export class RemoteHooks {
}
}
+ /**
+ * Install the managed grok status hook on the REMOTE host. Grok differs from claude/gemini in two
+ * ways that keep it out of AGENT_TARGETS: its config lives in a hooks DIRECTORY (we own one file
+ * there outright, so nothing of the user's is at risk inside it), and its path is not
+ * $HOME-relative when the host sets GROK_HOME — which we therefore ASK THE HOST for, and
+ * validate, because a host-reported string is data and not truth.
+ *
+ * Fail-open at every step: a remote grok session simply runs without status hooks.
+ */
+ private async installGrokRemote(
+ conn: SshConnection,
+ controlPath: string,
+ home: string,
+ remoteDir: string
+ ): Promise<void> {
+ try {
+ const { stdout: rawHome } = await this.r.run(
+ childArgs(conn, controlPath, 'printf %s "${GROK_HOME:-}"')
+ )
+ // Trim at the READ site: isSafeRemoteGrokHome judges the exact string we would go on to
+ // interpolate into a remote command line, so it (correctly) refuses an untrimmed value.
+ const reported = rawHome.trim()
+ const grokHome = isSafeRemoteGrokHome(reported) ? reported.replace(/\/+$/, '') : `${home}/.grok`
+ const config = `${grokHome}/hooks/${GROK_HOOK_FILE}`
+ const script = `${remoteDir}/agent-hooks/grok.sh`
+
+ await this.r.run(
+ childArgs(
+ conn,
+ controlPath,
+ `mkdir -p ${posixQuote(`${remoteDir}/agent-hooks`)} && cat > ${posixQuote(script)} && chmod 755 ${posixQuote(script)}`
+ ),
+ buildManagedScript('grok')
+ )
+ // `|| echo '{}'` fires ONLY when the file is missing, so a present-but-malformed file reaches
+ // JSON.parse and throws → we skip the write and leave the host's file alone.
+ const { stdout: cfgRaw } = await this.r.run(
+ childArgs(conn, controlPath, `cat ${posixQuote(config)} 2>/dev/null || echo '{}'`)
+ )
+ const cfg = JSON.parse(cfgRaw || '{}') as HookSettings
+ const merged = mergeManagedHook(cfg, buildManagedHookCommand(script), GROK_HOOK_EVENTS)
+ await this.r.run(
+ childArgs(conn, controlPath, `mkdir -p $(dirname ${posixQuote(config)}) && cat > ${posixQuote(config)}`),
+ JSON.stringify(merged, null, 2)
+ )
+ } catch {
+ /* fail-open: the remote grok session simply runs without status hooks */
+ }
+ }
+
/**
* Merge the managed claude hook into a REMOTE managed-account config dir's `settings.json`, so an
* agent that runs under `CLAUDE_CONFIG_DIR=<accountDir>` reports status like the default