Node-based terminal manager for AI coding agents — tmux-backed terminals and parallel agent sessions as draggable nodes on an infinite pan/zoom canvas. macOS, Linux, and a browser Server Edition.
TypeScript adhdagent-orchestrationai-agentscanvasclaude-codecodexcoding-agentsdeveloper-toolselectrongeminilinuxmacosmultiplexeropencodeparallel-agentsterminalterminal-emulatorterminal-multiplexertmuxworkspace-manager
fix(grok): one $GROK_HOME rule, exact-string remote validation, node-side path module
enes32899a4a0e45
diff --git a/src/shared/agents/grok-paths.test.ts b/src/core/agents/grok-paths.test.tssimilarity index 87%rename from src/shared/agents/grok-paths.test.tsrename to src/core/agents/grok-paths.test.tsindex 5e4dfde22..717453263 100644--- a/src/shared/agents/grok-paths.test.ts+++ b/src/core/agents/grok-paths.test.ts@@ -61,10 +61,11 @@ describe('isSafeRemoteGrokHome', () => {it('accepts an absolute POSIX path from the host', () => {expect(isSafeRemoteGrokHome('/home/dev/.grok')).toBe(true)})- it('judges the TRIMMED path — a stray newline off an ssh read is not a rejection reason', () => {- // The predicate trims to decide, so it must not also pretend to reject what it trimmed: the- // earlier `v !== p?.trim()` guard compared the trimmed value with itself and never fired.- expect(isSafeRemoteGrokHome(' /home/dev/.grok\n')).toBe(true)+ it('judges the EXACT string, so surrounding whitespace is a rejection', () => {+ // The caller trims at the READ site (that is where an ssh probe's trailing newline belongs), so+ // whitespace still attached here means the read went wrong. Answering `true` about a value whose+ // `\n` is a command separator on the remote command line would be the predicate lying.+ expect(isSafeRemoteGrokHome(' /home/dev/.grok\n')).toBe(false)})it('refuses relative paths, backslashes, control characters and absurd lengths', () => {expect(isSafeRemoteGrokHome('relative/grok')).toBe(false)diff --git a/src/shared/agents/grok-paths.ts b/src/core/agents/grok-paths.tssimilarity index 55%rename from src/shared/agents/grok-paths.tsrename to src/core/agents/grok-paths.tsindex ce7b2679e..903e66611 100644--- a/src/shared/agents/grok-paths.ts+++ b/src/core/agents/grok-paths.ts@@ -1,13 +1,16 @@-// 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.+// The ONE definition of grok's config + session path algebra: `src/main`, `src/core`, `src/server`+// and the SSH installer all import it from here. 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 —+// `core/usage/grok-usage.ts`'s `grokHome()` therefore delegates to `grokHomeDir()` rather than+// re-deriving `$GROK_HOME`.//-// NODE-SIDE shared code: it imports `path`/`os` and uses `Buffer`, so it is for `src/main`,-// `src/core`, `src/server` and the SSH installer only — it has no renderer consumer today. A-// renderer surface that needs one of these helpers must first split the pure half out (the-// encoding/validation functions are pure; `grokHomeDir`/`grokSessionsDir` are not, they read-// `homedir()`), not import this file into the browser bundle.+// It lives in `src/core`, NOT `src/shared/agents`, even though its callers span three process+// contexts: it reads `os.homedir()` and measures with `Buffer` at module scope, and `src/shared` is+// renderer territory — the renderer imports `shared/agents/*`, and `tsconfig.web.json` carries node+// types, so a renderer import of this file would typecheck cleanly and fail only at bundle or run+// time. `src/core` is node-side by construction (no electron, no renderer), which is exactly this+// file's contract. Should a renderer surface ever need one of these helpers, split the genuinely+// pure half out (the encoding/validation functions) instead of moving the file back.//// Measured layout (shipped 1.0.0):// $GROK_HOME/hooks/*.json — hook files, all merged; GROK_HOME defaults to ~/.grok@@ -29,18 +32,22 @@ 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 }+// Deliberately narrow — ONE known key, so a typo'd `{ GROK_HOM: … }` is a compile error instead of+// a silent fall back to `~/.grok`. The cast on the default argument is what that costs: GrokEnv is a+// WEAK type (every property optional), and `NodeJS.ProcessEnv extends Dict<string>` declares only an+// index signature, which the weak-type check does not count as a property in common — so a bare+// `env: GrokEnv = process.env` is TS2559 under tsconfig.node.json (it passes under+// tsconfig.web.json, which has no node types). Widening GrokEnv with an index signature would fix+// the error and take the typo check with it.+type GrokEnv = { GROK_HOME?: string }/** 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 {+export function grokHomeDir(env: GrokEnv = process.env as GrokEnv, 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 {+export function grokSessionsDir(env: GrokEnv = process.env as GrokEnv, home: string = homedir()): string {return path.join(grokHomeDir(env, home), 'sessions')}@@ -76,10 +83,17 @@ export function grokSessionDir(a: { sessionsDir: string; cwd: string; sessionId:/** 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`. */+ * character is usable, and the caller falls back to `$HOME/.grok`.+ *+ * It judges the EXACT string the caller holds — surrounding whitespace is a rejection, not+ * something this predicate quietly strips. Trimming here would return `true` about a value whose+ * embedded `\n` is a command separator on the remote command line the caller then builds, which is+ * the opposite of what the name promises (same rule as `isSafeRemoteTranscriptPath`). Remote reads+ * trim at the READ site — `ssh-project.ts`'s remote `$HOME` probe does — so the caller passes an+ * already-trimmed string and a leftover newline means the read went wrong, not that we should cope. */export function isSafeRemoteGrokHome(p: string | undefined): boolean {const v = p?.trim()- if (!v) return false+ if (!v || v !== p) return falseif (!v.startsWith('/') || v.includes('\\') || v.length > REMOTE_HOME_MAX) return falsereturn !Array.from(v).some((ch) => {const c = ch.charCodeAt(0)diff --git a/src/core/agents/hooks/grok.test.ts b/src/core/agents/hooks/grok.test.tsindex 5b34f41bd..d2aff51d7 100644--- a/src/core/agents/hooks/grok.test.ts+++ b/src/core/agents/hooks/grok.test.ts@@ -45,9 +45,11 @@ describe('grok hook installer', () => {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()+ // Non-tool events must carry NO matcher — grok warns and ignores one there. Every one of them+ // is checked, so a matcher accidentally attached to an event in hook-events.ts cannot ship.+ for (const ev of ['SessionStart', 'UserPromptSubmit', 'Stop', 'StopFailure', 'Notification', 'SessionEnd']) {+ expect(cfg.hooks[ev][0].matcher, ev).toBeUndefined()+ }})it('points every event at the shared managed script, guarded so a missing script cannot brick a session', async () => {diff --git a/src/core/agents/hooks/grok.ts b/src/core/agents/hooks/grok.tsindex 896448b81..122cc3be8 100644--- a/src/core/agents/hooks/grok.ts+++ b/src/core/agents/hooks/grok.ts@@ -5,7 +5,7 @@// 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 { GROK_HOOK_FILE, grokHomeDir } from '../grok-paths'import { installHooksInto, removeHooksFrom } from './install-helper'const SCRIPT_FILE_NAME = 'grok.sh'diff --git a/src/core/agents/hooks/install-helper.ts b/src/core/agents/hooks/install-helper.tsindex 262c70a1e..b13339272 100644--- a/src/core/agents/hooks/install-helper.ts+++ b/src/core/agents/hooks/install-helper.ts@@ -104,8 +104,10 @@ export function mergeManagedHook(const matcher = matcherOf(e)const existing = (next.hooks![ev] ?? []).filter((d) => !isManaged(d, marker))// 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 }] })+ // missing key here but still change the object shape snapshots compare. The test is+ // `!== undefined`, not truthiness — the type permits `matcher: ''`, and silently dropping an+ // empty matcher would emit a subscription that does not say what its declaration said.+ existing.push({ ...(matcher !== undefined ? { matcher } : {}), hooks: [{ type: 'command', command }] })next.hooks![ev] = existing}const managedEvents = new Set(events.map(eventNameOf))diff --git a/src/core/usage/grok-usage.ts b/src/core/usage/grok-usage.tsindex a4ae5c5da..7d6d8e427 100644--- a/src/core/usage/grok-usage.ts+++ b/src/core/usage/grok-usage.ts@@ -4,8 +4,8 @@// and/or a monthly money budget, so the two limits here are derived from billing figures rather// than read off rate-limit windows. Read-only — we never write `auth.json`.import { promises as fs } from 'fs'-import os from 'os'import path from 'path'+import { grokHomeDir } from '../agents/grok-paths'import type { ProviderUsage, UsageLimit } from '../../shared/types'const DEFAULT_PROXY_BASE = 'https://cli-chat-proxy.grok.com/v1'@@ -20,8 +20,12 @@ function proxyBase(): string {return process.env.GROK_CLI_CHAT_PROXY_BASE_URL?.trim().replace(/\/$/, '') || DEFAULT_PROXY_BASE}+/** Grok's config dir. Delegates to the ONE `$GROK_HOME` rule (`core/agents/grok-paths.ts`), which+ * the hook installer and the session-path helpers also read — two copies of this rule is how the+ * remote hook installer drifted for months. Kept as a named export because this module's callers+ * and tests use it. */export function grokHome(): string {- return process.env.GROK_HOME?.trim() || path.join(os.homedir(), '.grok')+ return grokHomeDir()}interface GrokAuth {diff --git a/src/main/index.ts b/src/main/index.tsindex 43c493a21..0d999f987 100644--- a/src/main/index.ts+++ b/src/main/index.ts@@ -1445,11 +1445,13 @@ app.whenReady().then(async () => {const SUBAGENT_TOOLS = new Set(['Agent', 'Task'])hookServer.setRawListener((agentId, nodeId, payload) => {if (agentId === 'grok') {- // All this branch does is remember the node↔session association that the phone's context- // ring and the ⌘K session lookup read. Everything else the claude path does below hangs off- // `transcript_path`, and grok's envelope has none — its transcript is DERIVED from (cwd,- // sessionId), so the context tail, the subagent tails and the transcript readers arrive in- // Tasks 4/5/10. Read through `grokRawFields` so grok's two field dialects (camelCase and the+ // All this branch does is record the node↔session association, and it is deliberately the+ // only thing: nothing reads the map for a grok node YET (the badge, the session chip and ⌘K+ // all take their id from the NORMALIZED listener, and the phone's context ring only fires for+ // a sessionId a context tail emits for). It is written now so the map is already populated+ // when Tasks 4/5/10 add the readers — everything else the claude path does below hangs off+ // `transcript_path`, and grok's envelope has none: its transcript is DERIVED from (cwd,+ // sessionId). Read through `grokRawFields` so grok's two field dialects (camelCase and the// SDK's snake_case) are decoded in exactly one place.const g = grokRawFields(payload)if (nodeId && g.sessionId) nodeContextSession.set(nodeId, g.sessionId)diff --git a/src/server/agent-status.ts b/src/server/agent-status.tsindex e19706ddf..48dc47cd5 100644--- a/src/server/agent-status.ts+++ b/src/server/agent-status.ts@@ -142,11 +142,13 @@ export function wireAgentStatus(const SUBAGENT_TOOLS = new Set(['Agent', 'Task'])hooks.setRawListener((agentId, nodeId, payload) => {if (agentId === 'grok') {- // All this branch does is remember the node↔session association that the phone's context- // ring and the ⌘K session lookup read. Everything else the claude path does below hangs off- // `transcript_path`, and grok's envelope has none — its transcript is DERIVED from (cwd,- // sessionId), so the context tail, the subagent tails and the transcript readers arrive in- // Tasks 4/5/10. Read through `grokRawFields` so grok's two field dialects (camelCase and the+ // All this branch does is record the node↔session association, and it is deliberately the+ // only thing: nothing reads the map for a grok node YET (the badge, the session chip and ⌘K+ // all take their id from the NORMALIZED listener, and the phone's context ring only fires for+ // a sessionId a context tail emits for). It is written now so the map is already populated+ // when Tasks 4/5/10 add the readers — everything else the claude path does below hangs off+ // `transcript_path`, and grok's envelope has none: its transcript is DERIVED from (cwd,+ // sessionId). Read through `grokRawFields` so grok's two field dialects (camelCase and the// SDK's snake_case) are decoded in exactly one place.const g = grokRawFields(payload)if (nodeId && g.sessionId) nodeContextSession.set(nodeId, g.sessionId)