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's status hooks — badges, unread, notifications, notch

enes27956eb07743
diff --git a/src/core/agents/hooks/grok.test.ts b/src/core/agents/hooks/grok.test.ts
new file mode 100644
index 000000000..5b34f41bd
--- /dev/null
+++ b/src/core/agents/hooks/grok.test.ts
@@ -0,0 +1,101 @@
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
+import { mkdtempSync, readFileSync, rmSync, writeFileSync, mkdirSync } from 'fs'
+import { tmpdir } from 'os'
+import path from 'path'
+
+// The installer resolves both the hook file (GROK_HOME) and the script path (HOME) from the
+// environment, so the whole test runs inside a temp HOME.
+let home = ''
+let grokHome = ''
+
+vi.mock('os', async (orig) => {
+ const real = (await orig()) as typeof import('os')
+ return { ...real, homedir: () => home }
+})
+
+describe('grok hook installer', () => {
+ beforeEach(() => {
+ home = mkdtempSync(path.join(tmpdir(), 'nt-grok-home-'))
+ grokHome = path.join(home, '.grok')
+ delete process.env.GROK_HOME
+ })
+ afterEach(() => {
+ rmSync(home, { recursive: true, force: true })
+ delete process.env.GROK_HOME
+ vi.resetModules()
+ })
+
+ const read = (p: string): { hooks: Record<string, { matcher?: string; hooks: { command: string }[] }[]> } =>
+ JSON.parse(readFileSync(p, 'utf8'))
+
+ it('writes OUR OWN file in grok\'s hooks DIRECTORY — no shared settings file to merge into', async () => {
+ const { installGrokHooks, grokHookConfigPath } = await import('./grok')
+ installGrokHooks()
+ expect(grokHookConfigPath()).toBe(path.join(grokHome, 'hooks', 'nodeterm-status.json'))
+ const cfg = read(grokHookConfigPath())
+ expect(Object.keys(cfg.hooks).sort()).toEqual(
+ ['Notification', 'PostToolUse', 'PostToolUseFailure', 'PreToolUse', 'SessionEnd', 'SessionStart', 'Stop', 'StopFailure', 'UserPromptSubmit'].sort()
+ )
+ })
+
+ it('writes the `.*` matcher on tool events — a bare `*` is invalid and kills them silently', async () => {
+ const { installGrokHooks, grokHookConfigPath } = await import('./grok')
+ installGrokHooks()
+ const cfg = read(grokHookConfigPath())
+ for (const ev of ['PreToolUse', 'PostToolUse', 'PostToolUseFailure']) {
+ expect(cfg.hooks[ev][0].matcher, ev).toBe('.*')
+ }
+ // Non-tool events must carry NO matcher: on Stop/UserPromptSubmit grok warns and ignores one.
+ expect(cfg.hooks.Stop[0].matcher).toBeUndefined()
+ expect(cfg.hooks.UserPromptSubmit[0].matcher).toBeUndefined()
+ })
+
+ it('points every event at the shared managed script, guarded so a missing script cannot brick a session', async () => {
+ const { installGrokHooks, grokHookConfigPath } = await import('./grok')
+ installGrokHooks()
+ const cfg = read(grokHookConfigPath())
+ const command = cfg.hooks.SessionStart[0].hooks[0].command
+ expect(command).toContain(path.join(home, '.nodeterm', 'agent-hooks', 'grok.sh'))
+ expect(command).toMatch(/^if \[ -r /)
+ expect(readFileSync(path.join(home, '.nodeterm', 'agent-hooks', 'grok.sh'), 'utf8')).toContain('/hook/grok')
+ })
+
+ it('honors GROK_HOME, because grok reads its hooks from there', async () => {
+ process.env.GROK_HOME = path.join(home, 'custom-grok')
+ const { installGrokHooks, grokHookConfigPath } = await import('./grok')
+ installGrokHooks()
+ expect(grokHookConfigPath()).toBe(path.join(home, 'custom-grok', 'hooks', 'nodeterm-status.json'))
+ expect(read(grokHookConfigPath()).hooks.Stop).toHaveLength(1)
+ })
+
+ it('is idempotent — a second install leaves exactly one entry per event', async () => {
+ const { installGrokHooks, grokHookConfigPath } = await import('./grok')
+ installGrokHooks()
+ installGrokHooks()
+ const cfg = read(grokHookConfigPath())
+ for (const defs of Object.values(cfg.hooks)) expect(defs).toHaveLength(1)
+ })
+
+ it('sweeps a managed entry off an event we no longer subscribe to', async () => {
+ const { installGrokHooks, grokHookConfigPath } = await import('./grok')
+ const p = path.join(grokHome, 'hooks', 'nodeterm-status.json')
+ mkdirSync(path.dirname(p), { recursive: true })
+ writeFileSync(
+ p,
+ JSON.stringify({
+ hooks: {
+ PreCompact: [{ hooks: [{ type: 'command', command: `sh '${path.join(home, '.nodeterm/agent-hooks/grok.sh')}'` }] }]
+ }
+ })
+ )
+ installGrokHooks()
+ expect(read(grokHookConfigPath()).hooks.PreCompact).toBeUndefined()
+ })
+
+ it('remove takes our entries back out', async () => {
+ const { installGrokHooks, removeGrokHooks, grokHookConfigPath } = await import('./grok')
+ installGrokHooks()
+ removeGrokHooks()
+ expect(read(grokHookConfigPath()).hooks).toEqual({})
+ })
+})
diff --git a/src/core/agents/hooks/grok.ts b/src/core/agents/hooks/grok.ts
new file mode 100644
index 000000000..896448b81
--- /dev/null
+++ b/src/core/agents/hooks/grok.ts
@@ -0,0 +1,34 @@
+// Grok hook service. Grok's hook config is a DIRECTORY — it merges every `$GROK_HOME/hooks/*.json`
+// — so unlike claude and gemini there is no shared settings file to merge into: nodeterm owns one
+// file outright and rewrites it. We still route through the shared install helper, because that is
+// where the missing-script guard, the idempotent re-install and the "sweep events we no longer
+// subscribe to" repair live.
+import path from 'path'
+import { GROK_HOOK_EVENTS } from '@shared/agents/hook-events'
+import { GROK_HOOK_FILE, grokHomeDir } from '@shared/agents/grok-paths'
+import { installHooksInto, removeHooksFrom } from './install-helper'
+
+const SCRIPT_FILE_NAME = 'grok.sh'
+
+/** Our hook file inside grok's hooks directory. Exported for tests and for the SSH installer,
+ * which must write the identical name on the host. */
+export function grokHookConfigPath(): string {
+ return path.join(grokHomeDir(), 'hooks', GROK_HOOK_FILE)
+}
+
+export function installGrokHooks(): void {
+ installHooksInto({
+ agentId: 'grok',
+ scriptFileName: SCRIPT_FILE_NAME,
+ configPath: grokHookConfigPath(),
+ events: GROK_HOOK_EVENTS
+ })
+}
+
+export function removeGrokHooks(): void {
+ removeHooksFrom({
+ configPath: grokHookConfigPath(),
+ events: GROK_HOOK_EVENTS,
+ scriptFileName: SCRIPT_FILE_NAME
+ })
+}
diff --git a/src/core/agents/hooks/index.ts b/src/core/agents/hooks/index.ts
index 379d830bb..0c4675f80 100644
--- a/src/core/agents/hooks/index.ts
+++ b/src/core/agents/hooks/index.ts
@@ -5,6 +5,7 @@ import { installClaudeHooks, ensureClaudeFullscreenTui, removeClaudeHooks } from
import { installCodexHooks, removeCodexHooks } from './codex'
import { installGeminiHooks, removeGeminiHooks } from './gemini'
import { installOpencodeHooks, removeOpencodeHooks } from './opencode'
+import { installGrokHooks, removeGrokHooks } from './grok'
type HookInstaller = readonly [string, () => void]
@@ -12,14 +13,16 @@ export const MANAGED_HOOK_INSTALLERS: readonly HookInstaller[] = [
['claude', installClaudeHooks],
['codex', installCodexHooks],
['gemini', installGeminiHooks],
- ['opencode', installOpencodeHooks]
+ ['opencode', installOpencodeHooks],
+ ['grok', installGrokHooks]
]
export const MANAGED_HOOK_REMOVERS: readonly HookInstaller[] = [
['claude', removeClaudeHooks],
['codex', removeCodexHooks],
['gemini', removeGeminiHooks],
- ['opencode', removeOpencodeHooks]
+ ['opencode', removeOpencodeHooks],
+ ['grok', removeGrokHooks]
]
export function installManagedAgentHooks(): void {
diff --git a/src/core/agents/hooks/install-helper.test.ts b/src/core/agents/hooks/install-helper.test.ts
index 3f88a25f6..00b257fdf 100644
--- a/src/core/agents/hooks/install-helper.test.ts
+++ b/src/core/agents/hooks/install-helper.test.ts
@@ -1,5 +1,6 @@
import { describe, expect, it } from 'vitest'
import { buildManagedHookCommand, mergeManagedHook } from './install-helper'
+import { CLAUDE_HOOK_EVENTS } from '@shared/agents/hook-events'
const cmd = buildManagedHookCommand('/remote/.nodeterm/agent-hooks/claude.sh')
@@ -90,3 +91,23 @@ describe('mergeManagedHook — repair sweep', () => {
expect(out.hooks!.SubagentStop).toEqual([foreign])
})
})
+
+/**
+ * The matcher support grok needs must not change one byte of what the other agents emit: a
+ * `matcher` key appearing in claude's settings.json would be a silent behavior change in a file
+ * three other tools also write.
+ */
+describe('mergeManagedHook — matcher support is opt-in per event', () => {
+ it('emits NO matcher key for a plain string event list', () => {
+ const out = mergeManagedHook({}, 'CMD', CLAUDE_HOOK_EVENTS)
+ for (const [ev, defs] of Object.entries(out.hooks!)) {
+ expect(Object.keys(defs[0]), ev).toEqual(['hooks'])
+ }
+ })
+
+ it('emits the matcher only for the events that asked for one', () => {
+ const out = mergeManagedHook({}, 'CMD', ['Stop', { event: 'PreToolUse', matcher: '.*' }])
+ expect(out.hooks!.Stop[0]).toEqual({ hooks: [{ type: 'command', command: 'CMD' }] })
+ expect(out.hooks!.PreToolUse[0]).toEqual({ matcher: '.*', hooks: [{ type: 'command', command: 'CMD' }] })
+ })
+})
diff --git a/src/core/agents/hooks/install-helper.ts b/src/core/agents/hooks/install-helper.ts
index 3cb9515aa..262c70a1e 100644
--- a/src/core/agents/hooks/install-helper.ts
+++ b/src/core/agents/hooks/install-helper.ts
@@ -12,9 +12,10 @@
import path from 'path'
import { homedir } from 'os'
import { readFileSync, writeFileSync, mkdirSync, chmodSync } from 'fs'
+import type { ManagedHookEvent } from '@shared/agents/hook-events'
import { buildManagedScript } from './managed-script'
-type HookDef = { hooks?: { type: string; command: string }[] }
+type HookDef = { matcher?: string; hooks?: { type: string; command: string }[] }
type Settings = { hooks?: Record<string, HookDef[]>; [k: string]: unknown }
/** Public alias for the hook settings shape, shared by local + remote merge callers. */
@@ -67,6 +68,12 @@ function managedMarkerFor(command: string): string {
return m ? m[0].replace(/\\/g, '/') : 'agent-hooks'
}
+/** A subscription's event name, whichever form it was declared in. */
+const eventNameOf = (e: ManagedHookEvent): string => (typeof e === 'string' ? e : e.event)
+/** The matcher to write for it — undefined for the plain string form, so nothing changes for the
+ * agents that never needed one (grok's tool events are the only case; see ManagedHookEvent). */
+const matcherOf = (e: ManagedHookEvent): string | undefined => (typeof e === 'string' ? undefined : e.matcher)
+
/** A managed entry: matches OUR script under `agent-hooks/` or the legacy `claude-signals` marker. */
function isManaged(d: HookDef, marker: string): boolean {
return !!d.hooks?.some(
@@ -85,15 +92,23 @@ function isManaged(d: HookDef, marker: string): boolean {
* list lacked, and if the loser's script had since been deleted those events silently did nothing.
* It also cleans up after ourselves when an event leaves the list between versions.
*/
-export function mergeManagedHook(config: HookSettings, command: string, events: readonly string[]): HookSettings {
+export function mergeManagedHook(
+ config: HookSettings,
+ command: string,
+ events: readonly ManagedHookEvent[]
+): HookSettings {
const marker = managedMarkerFor(command)
const next: HookSettings = { ...config, hooks: { ...(config.hooks ?? {}) } }
- for (const ev of events) {
+ for (const e of events) {
+ const ev = eventNameOf(e)
+ const matcher = matcherOf(e)
const existing = (next.hooks![ev] ?? []).filter((d) => !isManaged(d, marker))
- existing.push({ hooks: [{ type: 'command', command }] })
+ // Spread the matcher CONDITIONALLY: an explicit `matcher: undefined` would serialize as a
+ // missing key here but still change the object shape snapshots compare.
+ existing.push({ ...(matcher ? { matcher } : {}), hooks: [{ type: 'command', command }] })
next.hooks![ev] = existing
}
- const managedEvents = new Set(events)
+ const managedEvents = new Set(events.map(eventNameOf))
for (const ev of Object.keys(next.hooks!)) {
if (managedEvents.has(ev)) continue
const kept = next.hooks![ev].filter((d) => !isManaged(d, marker))
@@ -108,7 +123,7 @@ export interface InstallHooksOptions {
agentId: string
scriptFileName: string
configPath: string
- events: readonly string[]
+ events: readonly ManagedHookEvent[]
}
export function installHooksInto(opts: InstallHooksOptions): void {
@@ -146,7 +161,7 @@ export function installHooksInto(opts: InstallHooksOptions): void {
export interface RemoveHooksOptions {
configPath: string
- events: readonly string[]
+ events: readonly ManagedHookEvent[]
/** Our script's file name — narrows the match so foreign agent-hooks entries survive. */
scriptFileName: string
}
@@ -161,7 +176,8 @@ export function removeHooksFrom(opts: RemoveHooksOptions): void {
return
}
if (!config.hooks) return
- for (const ev of events) {
+ for (const e of events) {
+ const ev = eventNameOf(e)
if (!config.hooks[ev]) continue
config.hooks[ev] = config.hooks[ev].filter((d) => !d.hooks?.some((h) => h.command.includes(marker)))
if (config.hooks[ev].length === 0) delete config.hooks[ev]
diff --git a/src/main/index.ts b/src/main/index.ts
index ffda5c415..d23474f01 100644
--- a/src/main/index.ts
+++ b/src/main/index.ts
@@ -72,7 +72,7 @@ import { retainUntilDismissed } from './notifications'
import { installManagedAgentHooks } from '../core/agents/hooks'
import { createSubagentTail } from '../core/subagent-tail'
import { createContextTail, type TaskNotification } from '../core/context-tail'
-import { isAsyncSubagentLaunch, type NormalizedAgentEvent } from '../shared/agents/normalize'
+import { grokRawFields, isAsyncSubagentLaunch, type NormalizedAgentEvent } from '../shared/agents/normalize'
import {
readSessionName,
setRemoteTranscriptReader,
@@ -1444,6 +1444,16 @@ app.whenReady().then(async () => {
}
const SUBAGENT_TOOLS = new Set(['Agent', 'Task'])
hookServer.setRawListener((agentId, nodeId, payload) => {
+ if (agentId === 'grok') {
+ // grok's envelope carries no transcript_path — its transcript is DERIVED from (cwd,
+ // sessionId), which Tasks 5/10 use. All this branch can do correctly is the association the
+ // phone's context ring and the ⌘K session lookup read, plus the activity line (through
+ // grokRawFields, so the two dialects are read in exactly one place).
+ const g = grokRawFields(payload)
+ recordRawToolEvent(nodeId, { tool_name: g.toolName, tool_input: g.toolInput })
+ if (nodeId && g.sessionId) nodeContextSession.set(nodeId, g.sessionId)
+ return
+ }
if (agentId !== 'claude') return
// Mirror the per-node "what it's doing now" activity line for the phone (mobile-usage-inbox).
// Runs BEFORE the local/remote split so it covers remote (SSH) nodes too — it needs only
diff --git a/src/server/agent-status.ts b/src/server/agent-status.ts
index 970cd11bd..0608a0484 100644
--- a/src/server/agent-status.ts
+++ b/src/server/agent-status.ts
@@ -17,7 +17,7 @@ import { createSubagentTail, type SubagentTail } from '../core/subagent-tail'
import { createContextTail, type ContextTail, type TaskNotification } from '../core/context-tail'
import { setNodeTranscript } from '../core/context-link'
import { isSafeLocalTranscriptPath } from '../core/claude-accounts-core'
-import { isAsyncSubagentLaunch, type NormalizedAgentEvent } from '../shared/agents/normalize'
+import { grokRawFields, isAsyncSubagentLaunch, type NormalizedAgentEvent } from '../shared/agents/normalize'
import { IPC } from '../shared/ipc'
import type { ServerPlatform } from './platform-server'
@@ -141,6 +141,16 @@ export function wireAgentStatus(
const SUBAGENT_TOOLS = new Set(['Agent', 'Task'])
hooks.setRawListener((agentId, nodeId, payload) => {
+ if (agentId === 'grok') {
+ // grok's envelope carries no transcript_path — its transcript is DERIVED from (cwd,
+ // sessionId), which Tasks 5/10 use. All this branch can do correctly is the association the
+ // phone's context ring and the ⌘K session lookup read, plus the activity line (through
+ // grokRawFields, so the two dialects are read in exactly one place).
+ const g = grokRawFields(payload)
+ recordRawToolEvent(nodeId, { tool_name: g.toolName, tool_input: g.toolInput })
+ if (nodeId && g.sessionId) nodeContextSession.set(nodeId, g.sessionId)
+ return
+ }
if (agentId !== 'claude') return
// Mirror the per-node "what it's doing now" activity line for the phone (mobile-usage-inbox).
// Independent of the transcript-tailing below (no path needed), so it runs first.
diff --git a/src/shared/agents/config.capabilities.test.ts b/src/shared/agents/config.capabilities.test.ts
index 7d4a76c4f..c97f43697 100644
--- a/src/shared/agents/config.capabilities.test.ts
+++ b/src/shared/agents/config.capabilities.test.ts
@@ -71,11 +71,10 @@ describe('createdAgentId', () => {
})
/**
- * Grok arrives with spawn + resume and nothing else, which is the registry's own design for a new
- * agent ("a custom agent is in no list, so it automatically gets only spawn + terminal-title +
- * process status"). Hooks, context links and canvas control each need per-agent machinery that has
- * not been written for it — an installer, a transcript parser, a discovery file — and claiming any
- * of them here would light badges that never update and offer menu items that do nothing.
+ * Grok claims a capability only once its per-agent machinery exists — an installer, a transcript
+ * parser, a discovery file — because claiming one early lights badges that never update and offers
+ * menu items that do nothing. Hooks arrived with the normalizer (normalizeGrok) plus the installer
+ * that writes $GROK_HOME/hooks/nodeterm-status.json; context links and canvas control have not.
*/
describe('grok capabilities', () => {
it('is a builtin with a launch command and a colour', () => {
@@ -102,11 +101,19 @@ describe('grok capabilities', () => {
}
})
- it('claims resume and nothing beyond it', () => {
+ it('reports status through its own hooks', () => {
+ // What had to be true first: a normalizer for grok's dialect (normalizeGrok) and an installer
+ // that writes $GROK_HOME/hooks/nodeterm-status.json. Both exist now, so the badge, the unread
+ // dot, the completion notification, the notch capsule and the session-id capture all apply.
+ expect(hasHooks('grok')).toBe(true)
expect(canResume('grok')).toBe(true)
- expect(hasHooks('grok')).toBe(false)
+ })
+
+ it('does not yet claim the capabilities whose per-agent leaf is unwritten', () => {
expect(canContextLink('grok')).toBe(false)
- expect(canBranch('grok')).toBe(false)
expect(canControlCanvas('grok')).toBe(false)
+ expect(hasUsage('grok')).toBe(false)
+ expect(canBranch('grok')).toBe(false)
+ expect(canSubagent('grok')).toBe(false)
})
})
diff --git a/src/shared/agents/config.ts b/src/shared/agents/config.ts
index 01cd92ce3..2be45b3a5 100644
--- a/src/shared/agents/config.ts
+++ b/src/shared/agents/config.ts
@@ -87,7 +87,7 @@ export const AGENT_CONFIG: Record<BuiltinAgentId, AgentConfig> = {
// Capabilities = const membership lists. A custom agent is in no list, so it
// automatically gets only spawn + terminal-title + process status.
-export const AGENT_HOOK_TARGETS = ['claude', 'codex', 'gemini', 'opencode'] as const
+export const AGENT_HOOK_TARGETS = ['claude', 'codex', 'gemini', 'opencode', 'grok'] as const
export const RESUMABLE_AGENTS = ['claude', 'codex', 'gemini', 'opencode', 'grok'] as const
export const SUBAGENT_CAPABLE = ['claude'] as const
export const RECURRING_CAPABLE = ['claude'] as const // /loop, /schedule, /cron
diff --git a/src/shared/agents/grok-paths.test.ts b/src/shared/agents/grok-paths.test.ts
new file mode 100644
index 000000000..1fba8e87c
--- /dev/null
+++ b/src/shared/agents/grok-paths.test.ts
@@ -0,0 +1,75 @@
+import { describe, expect, it } from 'vitest'
+import {
+ grokEncodedCwdDirName,
+ grokHomeDir,
+ grokSessionDir,
+ grokSessionsDir,
+ isSafeGrokSessionId,
+ isSafeRemoteGrokHome
+} from './grok-paths'
+
+describe('grokHomeDir', () => {
+ it('defaults to ~/.grok', () => {
+ expect(grokHomeDir({}, '/home/u')).toBe('/home/u/.grok')
+ })
+ it('honors GROK_HOME, which grok itself honors for hooks AND sessions', () => {
+ expect(grokHomeDir({ GROK_HOME: '/srv/grok' }, '/home/u')).toBe('/srv/grok')
+ })
+ it('ignores a blank GROK_HOME rather than resolving to the filesystem root', () => {
+ expect(grokHomeDir({ GROK_HOME: ' ' }, '/home/u')).toBe('/home/u/.grok')
+ })
+})
+
+describe('grokEncodedCwdDirName', () => {
+ it('URL-encodes the working directory, which is how grok names the session group', () => {
+ expect(grokEncodedCwdDirName('/home/u/proj')).toBe('%2Fhome%2Fu%2Fproj')
+ })
+ it('refuses a path whose encoded name exceeds 255 bytes — grok switches to a slug+hash there', () => {
+ expect(grokEncodedCwdDirName(`/${'a'.repeat(300)}`)).toBeNull()
+ })
+ it('refuses empty and dot paths (encodeURIComponent leaves dots alone)', () => {
+ expect(grokEncodedCwdDirName(' ')).toBeNull()
+ expect(grokEncodedCwdDirName('.')).toBeNull()
+ expect(grokEncodedCwdDirName('..')).toBeNull()
+ })
+})
+
+describe('isSafeGrokSessionId', () => {
+ it('accepts the UUIDs grok generates', () => {
+ expect(isSafeGrokSessionId('0192f0c1-8f4e-7c3a-9b2d-4a5b6c7d8e9f')).toBe(true)
+ })
+ it('refuses anything that could escape a directory or reach a shell', () => {
+ for (const bad of ['', '../etc', 'a/b', 'a;rm -rf /', `${'x'.repeat(200)}`]) {
+ expect(isSafeGrokSessionId(bad), bad).toBe(false)
+ }
+ })
+})
+
+describe('grokSessionDir', () => {
+ it('builds <sessions>/<encoded cwd>/<id> — no scan needed, because hooks carry both', () => {
+ expect(grokSessionDir({ sessionsDir: '/s', cwd: '/home/u/p', sessionId: 'abc-1' })).toBe(
+ '/s/%2Fhome%2Fu%2Fp/abc-1'
+ )
+ })
+ it('is null when either half is unusable, so no caller can build a half-path', () => {
+ expect(grokSessionDir({ sessionsDir: '/s', cwd: '.', sessionId: 'abc-1' })).toBeNull()
+ expect(grokSessionDir({ sessionsDir: '/s', cwd: '/p', sessionId: '../x' })).toBeNull()
+ })
+})
+
+describe('isSafeRemoteGrokHome', () => {
+ it('accepts an absolute POSIX path from the host', () => {
+ expect(isSafeRemoteGrokHome('/home/dev/.grok')).toBe(true)
+ })
+ it('refuses relative paths, backslashes, control characters and absurd lengths', () => {
+ expect(isSafeRemoteGrokHome('relative/grok')).toBe(false)
+ expect(isSafeRemoteGrokHome('/bad\\grok')).toBe(false)
+ expect(isSafeRemoteGrokHome('/bad\u0001grok')).toBe(false)
+ expect(isSafeRemoteGrokHome(`/${'x'.repeat(5000)}`)).toBe(false)
+ expect(isSafeRemoteGrokHome(undefined)).toBe(false)
+ })
+})
+
+it('grokSessionsDir sits under the resolved home', () => {
+ expect(grokSessionsDir({ GROK_HOME: '/srv/g' }, '/home/u')).toBe('/srv/g/sessions')
+})
diff --git a/src/shared/agents/grok-paths.ts b/src/shared/agents/grok-paths.ts
new file mode 100644
index 000000000..424ffb775
--- /dev/null
+++ b/src/shared/agents/grok-paths.ts
@@ -0,0 +1,82 @@
+// Pure path algebra for grok's config + session layout. No `fs` and no `electron`, so `src/main`,
+// `src/core`, `src/server` and the SSH installer all share ONE definition — the drift between two
+// copies of a path rule is exactly what made the remote hook installer subscribe gemini to
+// claude's event names for months.
+//
+// Measured layout (shipped 1.0.0):
+// $GROK_HOME/hooks/*.json — hook files, all merged; GROK_HOME defaults to ~/.grok
+// $GROK_HOME/sessions/<encoded cwd>/<id>/ — one directory per session, grouped by cwd
+// summary.json updates.jsonl chat_history.jsonl signals.json plan.json subagents/
+import path from 'path'
+import { homedir } from 'os'
+
+export const GROK_HOOK_FILE = 'nodeterm-status.json'
+export const GROK_SUMMARY_FILE = 'summary.json'
+export const GROK_SIGNALS_FILE = 'signals.json'
+export const GROK_UPDATES_FILE = 'updates.jsonl'
+export const GROK_CHAT_HISTORY_FILE = 'chat_history.jsonl'
+
+/** grok URL-encodes the cwd to name a session group; past this many BYTES it switches to a
+ * slug+hash directory instead, which we cannot reconstruct — so we resolve nothing there. */
+export const GROK_ENCODED_CWD_MAX_BYTES = 255
+const GROK_SESSION_ID_MAX = 128
+/** Generous cap on a host-reported $GROK_HOME; longer than any real path, short enough to bound. */
+const REMOTE_HOME_MAX = 4096
+
+// The index signature is what lets `process.env` (NodeJS.ProcessEnv, i.e. Dict<string>) be the
+// default argument: without it GrokEnv is a WEAK type — all-optional — and TS rejects a source
+// whose declared properties do not overlap, index signature or not (TS2559).
+type GrokEnv = { GROK_HOME?: string | undefined; [k: string]: string | undefined }
+
+/** grok's config directory: `$GROK_HOME`, else `~/.grok`. Hooks AND sessions live under it. */
+export function grokHomeDir(env: GrokEnv = process.env, home: string = homedir()): string {
+ const fromEnv = env.GROK_HOME?.trim()
+ return fromEnv || path.join(home, '.grok')
+}
+
+export function grokSessionsDir(env: GrokEnv = process.env, home: string = homedir()): string {
+ return path.join(grokHomeDir(env, home), 'sessions')
+}
+
+/** The session-group directory name for a cwd, or null when grok would not have used this scheme. */
+export function grokEncodedCwdDirName(cwd: string): string | null {
+ const trimmed = cwd.trim()
+ if (!trimmed) return null
+ let encoded: string
+ try {
+ encoded = encodeURIComponent(trimmed)
+ } catch {
+ return null
+ }
+ // encodeURIComponent deliberately leaves dots untouched — reject path syntax explicitly.
+ if (encoded === '.' || encoded === '..' || encoded.includes('/') || encoded.includes('\\')) return null
+ return Buffer.byteLength(encoded, 'utf8') <= GROK_ENCODED_CWD_MAX_BYTES ? encoded : null
+}
+
+/** grok's ids are UUIDs; the charset is enforced because this value reaches both a path and (via
+ * `grok --resume <id>`) a shell command line. */
+export function isSafeGrokSessionId(sessionId: string): boolean {
+ return sessionId.length > 0 && sessionId.length <= GROK_SESSION_ID_MAX && /^[A-Za-z0-9_-]+$/.test(sessionId)
+}
+
+/** The session directory for (cwd, sessionId) — both of which every grok hook payload carries, so
+ * nothing has to scan. Null when either half is unusable: a half-resolved path must never leak. */
+export function grokSessionDir(a: { sessionsDir: string; cwd: string; sessionId: string }): string | null {
+ const encoded = grokEncodedCwdDirName(a.cwd)
+ const id = a.sessionId.trim()
+ if (!encoded || !isSafeGrokSessionId(id)) return null
+ return path.join(a.sessionsDir, encoded, id)
+}
+
+/** Validate a $GROK_HOME reported by a REMOTE host before it is used to build remote paths. The
+ * host's answer is data, not truth: only an absolute POSIX path with no backslash or control
+ * character is usable, and the caller falls back to `$HOME/.grok`. */
+export function isSafeRemoteGrokHome(p: string | undefined): boolean {
+ const v = p?.trim()
+ if (!v || v !== p?.trim()) return false
+ if (!v.startsWith('/') || v.includes('\\') || v.length > REMOTE_HOME_MAX) return false
+ return !Array.from(v).some((ch) => {
+ const c = ch.charCodeAt(0)
+ return c <= 0x1f || c === 0x7f
+ })
+}