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(grok): a session map that survives a restart, and a $GROK_HOME a GUI app can see
Xavi Guardia80f2181ddb75
diff --git a/docs/grok-agent.md b/docs/grok-agent.mdindex 19e5ee801..ee6bd5580 100644--- a/docs/grok-agent.md+++ b/docs/grok-agent.md@@ -427,14 +427,28 @@ ai-name / comments).honest; one built on a guessed key renders wrong forever. Note grok's names collide with claude'sby CASE alone in two places (`grep`/`Grep`, `write`/`Write`), so that switch must staycase-sensitive.-2. **A remote (SSH) grok node's session name never resolves.** The shells build the session directory- from the **local** `grokSessionsDir()` while the payload's `cwd` came from the host. It degrades- safely — a wrong name is never produced, only no name — but it is a real asymmetry: claude's leg- right below handles remote via `setRemoteTranscriptReader`.-3. **The `sessionId → dir` map is in-memory,** so after an app restart a grok name does not resolve- until that session's next hook. This is the deliberate "derive, never search" trade (claude- resolves immediately *because* it scans, which is the behaviour that made nodes adopt each other's- names); the checklist records how it feels.+2. **A remote (SSH) grok node's session name never resolves — the SEAM now exists, the SSH wiring+ does not.** The shells build the session directory from the **local** `grokSessionsDir()` while+ the payload's `cwd` came from the host. `readAgentSessionName` now takes a `grokRemoteSummary`+ reader, shaped exactly like claude's `setRemoteTranscriptReader`, and its answer is FINAL for a+ session it owns: an unreadable host yields **no name**, never the local directory's — because+ "could not read the host" and "there is nothing" are different facts, and answering the first+ with the second is how a node ends up wearing another session's name. Pinned by a test.+ **What is still owed** is the desktop's implementation of that reader: it needs the host's+ `$GROK_HOME`, which `RemoteHooks` computes at install time (`isSafeRemoteGrokHome`) and does not+ keep. Until it is wired, a remote grok node still degrades to no name — the same behaviour as+ before, now with the place to fix it named.+3. ~~The `sessionId → dir` map is in-memory.~~ **CLOSED: it is persisted** (`grok-session-dirs.json`+ under `userDataDir`, written atomically, debounced so a hook burst is one write and never awaited+ on the hook path). A grok node's name now resolves straight after an app restart, with no hook in+ between.+ **Persisting is not scanning, and the distinction is the whole point of grok's design here.** A+ scan searches a tree for a session id — that is what claude does, and it is the behaviour that+ made nodes adopt each other's names. What this file holds is only what a hook already TOLD us, so+ a restart recovers facts we were given rather than guessing at facts we were not.+ Every entry is re-validated with `isSafeGrokSessionId` on load: the file is ours but it sits in a+ directory a user can edit, and the values become filesystem paths. A corrupt or hand-edited file+ yields an EMPTY map, never a partial one built from whatever happened to parse.4. **No live session-name poll in the browser** — see §7.6b. **The FIRST grok node in a cwd mints without checking the disk.** The taken-id set is warmedper cwd on demand (`renderer/state/grokSessionIds.ts`), so the first mint in a directory@@ -478,6 +492,22 @@ ai-name / comments).side shares the blind spot, not because it is solved there. Fixing itmeans probing the login shell — a change with its own failure modes, not a comment — so checklist**31** asks first whether anyone sets the variable at all. The trap is documented at `grokHomeDir`.+ **LOCAL SIDE CLOSED (2026-09).** `ensureGrokHomeProbed` asks the user's LOGIN+INTERACTIVE shell+ for `GROK_HOME` once — the same spawn `resolveShellPath` already makes for `$PATH`, for the same+ reason — and `installManagedAgentHooks` re-writes grok's hook file if the answer moves the target.+ Three properties, each of which a mutation is pinned against: an explicit `process.env.GROK_HOME`+ wins and the shell is not even asked (that spawn can hang on a slow dotfile); the probe is async+ and fail-open, so boot never waits and a hung shell means today's behaviour; and the fallback+ RECORDS itself (`grokHomeFallbackWasSilent`), because the bug was never the wrong path — it was+ that a wrong path produced no diagnostic anywhere.+ Item **31**'s question, answered on this device (2026-09-02): `GROK_HOME` is unset in the+ environment AND absent from every shell rc, so the probe finds nothing here. That is precisely why+ it had to cost nothing when it finds nothing.+ A better source exists for READS: `summary.json` carries `grok_home` inside it (present in 29 of+ 29 local sessions, all agreeing). It cannot bootstrap the INSTALL — reading it means already+ knowing the sessions directory — so it is recorded for a future reader rather than used.+ **The REMOTE side is still open (item 26):** that probe runs over a plain ssh exec channel, so a+ host exporting `GROK_HOME` only from `.bashrc` still reports empty and silently gets `~/.grok`.**Follow-ups owed elsewhere:**diff --git a/src/core/agent-session-name.test.ts b/src/core/agent-session-name.test.tsindex ee71b612d..35805b5be 100644--- a/src/core/agent-session-name.test.ts+++ b/src/core/agent-session-name.test.ts@@ -22,6 +22,50 @@ describe('readAgentSessionName', () => {forgetGrokSession('gs1')})+ it('reads a REMOTE grok session on its host, not on this machine', async () => {+ // §8.4: for an SSH node the shells derive the session directory from the LOCAL sessions root+ // while the payload's `cwd` came from the host — a path on the wrong machine. The remote reader+ // answers first, and its answer is final.+ const dir = path.join(root, 'gs-remote')+ mkdirSync(dir, { recursive: true })+ writeFileSync(path.join(dir, 'summary.json'), JSON.stringify({ generated_title: 'LOCAL NAME' }))+ rememberGrokSessionDir('gs-remote', dir)+ const remote = async () => ({+ text: JSON.stringify({ generated_title: 'name from the host' })+ })+ expect(await readAgentSessionName('gs-remote', undefined, 'grok', { grokRemoteSummary: remote }))+ .toBe('name from the host')+ forgetGrokSession('gs-remote')+ })++ it('a remote session that cannot be read yields NO name, never the local one', async () => {+ // The mutation this exists for. "Could not read the host" and "there is nothing" are different+ // facts; answering a question about the host with a fact about this machine is how a node ends+ // up wearing another session's name. An empty body is still an answer from the remote reader.+ const dir = path.join(root, 'gs-remote-2')+ mkdirSync(dir, { recursive: true })+ writeFileSync(path.join(dir, 'summary.json'), JSON.stringify({ generated_title: 'LOCAL NAME' }))+ rememberGrokSessionDir('gs-remote-2', dir)+ const unreadable = async () => ({ text: '' })+ expect(+ await readAgentSessionName('gs-remote-2', undefined, 'grok', { grokRemoteSummary: unreadable })+ ).toBeNull()+ forgetGrokSession('gs-remote-2')+ })++ it('a reader that does not own the session falls through to the local map', async () => {+ // `null` means "not a remote session" — the only answer that routes locally.+ const dir = path.join(root, 'gs-local')+ mkdirSync(dir, { recursive: true })+ writeFileSync(path.join(dir, 'summary.json'), JSON.stringify({ generated_title: 'local one' }))+ rememberGrokSessionDir('gs-local', dir)+ const notMine = async () => null+ expect(+ await readAgentSessionName('gs-local', undefined, 'grok', { grokRemoteSummary: notMine })+ ).toBe('local one')+ forgetGrokSession('gs-local')+ })+it('sends everything else to the claude transcript reader', async () => {// No transcript exists for this id under any root, so the honest answer is null — the assertion// that matters is that it did NOT come back with the grok session's name below.diff --git a/src/core/agent-session-name.ts b/src/core/agent-session-name.tsindex 461f276ea..3d9264655 100644--- a/src/core/agent-session-name.ts+++ b/src/core/agent-session-name.ts@@ -17,7 +17,7 @@// Anything else has no readable session name; the claude reader answers null for it, which is what// every pre-grok caller already got.import { readSessionName, readSmallTail, TITLE_TAIL_BYTES } from './transcript-reader'-import { readGrokSessionName } from './grok-session'+import { readGrokSessionName, type GrokRemoteSummaryReader } from './grok-session'import { pickGeminiTitle } from './gemini-session'import { readCodexSessionName } from './codex-session-name'@@ -29,6 +29,16 @@ import { readCodexSessionName } from './codex-session-name'* here as a function rather than as a core singleton.*/export interface AgentSessionNameDeps {+ /**+ * Reads a REMOTE grok session's `summary.json` on its host — the grok analogue of claude's+ * `setRemoteTranscriptReader`, and the fix for §8.4: without it the shells derive the session+ * directory from the LOCAL sessions root while the payload's `cwd` came from the host, i.e. a path+ * on the wrong machine.+ *+ * Its answer is FINAL for a session it owns: `{ text: '' }` means "remote, unreadable" and yields+ * no name, never a local lookup. Only `null` — "not a remote session" — routes to the local map.+ */+ grokRemoteSummary?: GrokRemoteSummaryReader/*** sessionId → that gemini session's transcript path, i.e. `geminiContextTail.pathFor`. Fed only* by hook POSTs, so `undefined` for a session no hook has been seen for — and for a REMOTE (SSH)@@ -71,7 +81,7 @@ export function readAgentSessionName(deps?: AgentSessionNameDeps): Promise<string | null> {if (!sessionId) return Promise.resolve(null)- if (agentId === 'grok') return readGrokSessionName(sessionId)+ if (agentId === 'grok') return readGrokSessionName(sessionId, deps?.grokRemoteSummary)if (agentId === 'gemini') return readGeminiSessionName(sessionId, deps?.geminiPathFor)// Never falls through to claude's reader: that one SCANS ~/.claude/projects on a cache miss, so// an unrouted codex node would pay that scan once a minute for a guaranteed null.diff --git a/src/core/agents/grok-paths.test.ts b/src/core/agents/grok-paths.test.tsindex 717453263..b4f7ac8fc 100644--- a/src/core/agents/grok-paths.test.ts+++ b/src/core/agents/grok-paths.test.ts@@ -1,7 +1,12 @@-import { describe, expect, it } from 'vitest'+import { afterEach, beforeEach, describe, expect, it } from 'vitest'+import path from 'path'+import { homedir } from 'os'import {+ _resetGrokHomeProbeForTests,+ ensureGrokHomeProbed,grokEncodedCwdDirName,grokHomeDir,+ grokHomeFallbackWasSilent,grokSessionDir,grokSessionsDir,isSafeGrokSessionId,@@ -79,3 +84,66 @@ describe('isSafeRemoteGrokHome', () => {it('grokSessionsDir sits under the resolved home', () => {expect(grokSessionsDir({ GROK_HOME: '/srv/g' }, '/home/u')).toBe('/srv/g/sessions')})++describe('grokHomeDir — the login-shell probe (§8.9)', () => {+ // The bug this closes: a desktop app launched from Finder/Dock never sourced the user's rc, while+ // the grok CLI — started by the shell inside a tmux pane — did. For a user whose only+ // `export GROK_HOME=…` lives in `.zshrc`, nodeterm writes the hook under `~/.grok` and grok reads+ // somewhere else. Nothing errors: no badge, no unread dot, no notification, no session name, ever.+ beforeEach(() => _resetGrokHomeProbeForTests())+ afterEach(() => _resetGrokHomeProbeForTests())++ it('finds the home a shell rc exports but this process never saw', async () => {+ await ensureGrokHomeProbed(async () => '/Volumes/work/.grok')+ expect(grokHomeDir({} as never)).toBe(path.join(homedir(), '.grok'))+ expect(grokHomeDir()).toBe('/Volumes/work/.grok')+ expect(grokSessionsDir()).toBe(path.join('/Volumes/work/.grok', 'sessions'))+ })++ it('never overrides a value this process already has, and does not even ASK', async () => {+ // Two claims, and the second is the one a mutation can break invisibly: when the process already+ // knows, the probe must not spawn a login shell at all. That spawn costs hundreds of+ // milliseconds and can hang on a slow dotfile, so paying it for an answer we would discard is+ // not a harmless extra.+ process.env.GROK_HOME = '/explicit'+ let asked = 0+ try {+ await ensureGrokHomeProbed(async () => {+ asked+++ return '/from-the-shell'+ })+ expect(asked).toBe(0)+ expect(grokHomeDir()).toBe('/explicit')+ expect(grokHomeFallbackWasSilent()).toBe(false)+ } finally {+ delete process.env.GROK_HOME+ }+ })++ it('falls back to ~/.grok and SAYS SO when the shell knows nothing', async () => {+ // Rule 9: "could not measure" and "there is nothing" are different facts. The original bug was+ // not the wrong path — it was that the wrong path produced no diagnostic anywhere.+ expect(grokHomeFallbackWasSilent()).toBe(false)+ await ensureGrokHomeProbed(async () => null)+ expect(grokHomeDir()).toBe(path.join(homedir(), '.grok'))+ expect(grokHomeFallbackWasSilent()).toBe(true)+ })++ it('survives a probe that throws, without taking the caller down', async () => {+ await ensureGrokHomeProbed(async () => {+ throw new Error('dotfile exploded')+ }).catch(() => {+ throw new Error('ensureGrokHomeProbed must never reject')+ })+ expect(grokHomeDir()).toBe(path.join(homedir(), '.grok'))+ })++ it('leaves an explicitly-passed environment alone', async () => {+ // `grokHomeDir(env)` means "resolve as THIS environment would". Substituting a shell answer+ // there would make it lie about the environment it was handed — and both shells call it with a+ // real env when they build a REMOTE path, where a local shell's answer is simply wrong.+ await ensureGrokHomeProbed(async () => '/from-the-shell')+ expect(grokHomeDir({ GROK_HOME: '/given' } as never)).toBe('/given')+ expect(grokHomeDir({} as never, '/home/other')).toBe(path.join('/home/other', '.grok'))+ })+})diff --git a/src/core/agents/grok-paths.ts b/src/core/agents/grok-paths.tsindex 6ac7df573..36a4d06ca 100644--- a/src/core/agents/grok-paths.ts+++ b/src/core/agents/grok-paths.ts@@ -21,6 +21,7 @@import path from 'path'import { homedir } from 'os'import { isSafeRemoteHome } from '../remote-safety'+import { resolveShellEnvVar } from '../exec-path'export const GROK_HOOK_FILE = 'nodeterm-status.json'export const GROK_SUMMARY_FILE = 'summary.json'@@ -67,13 +68,78 @@ type GrokEnv = { GROK_HOME?: string }* host that exports `GROK_HOME` only from `.bashrc` reports empty and silently gets `~/.grok`. That is* checklist item 26, which exists BECAUSE the remote side has the problem too.*- * Deliberately NOT fixed here: resolving it means probing the user's login shell for `GROK_HOME`- * (a spawn, a cache, and a fail-open policy), which is its own change with its own failure modes —- * not a comment. It is item 31 in docs/grok-agent.md's device checklist ("is `GROK_HOME` set in your- * shell?") because a device run is what tells us whether anyone actually sets it. */+ * FIXED for the local side since 2026-09, and the shape of the fix matters. `ensureGrokHomeProbed`+ * asks the user's LOGIN+INTERACTIVE shell for `GROK_HOME` once (the same spawn `resolveShellPath`+ * already makes for `$PATH`, for the same reason), and the answer is remembered for this process.+ * Three properties it was built to have:+ *+ * - The probe never overrides a value we already have. `process.env.GROK_HOME` wins outright:+ * a shell answer is evidence about the user's shell, not about this process.+ * - It is asynchronous and fail-open. A hung dotfile, a non-POSIX shell, Windows — all resolve to+ * "not set", which is `~/.grok`, exactly today's behaviour. Nothing waits on it to launch.+ * - The fallback LEAVES A TRACE (`grokHomeFallbackWasSilent`). Rule 9: "could not measure" and+ * "there is nothing" are different facts. The bug this closes was not the wrong path — it was+ * that a wrong path produced no badge, no notification, no name and NO DIAGNOSTIC, forever.+ *+ * MEASURED on this device (2026-09-02), which is what checklist item 31 asked for: `GROK_HOME` is+ * unset in the environment AND absent from every shell rc. So the probe finds nothing here — which+ * is exactly why it must not cost anything when it finds nothing.+ *+ * A better source exists for READS once a session is known: `summary.json` carries `grok_home`+ * inside it (present in 29 of 29 local sessions). It cannot bootstrap the INSTALL, though — reading+ * it requires already knowing the sessions directory — so it is recorded here as the answer for a+ * future reader, not used as one.+ *+ * The REMOTE side is still item 26: its probe runs over a plain ssh exec channel, so a host that+ * exports `GROK_HOME` only from `.bashrc` still reports empty and silently gets `~/.grok`. */+let probedGrokHome: string | null = null+let fallbackWasSilent = false++/**+ * Ask the login shell for `GROK_HOME`, once per process. Never rejects. Call it at boot and forget+ * it: `grokHomeDir` picks the answer up whenever it lands, and until then answers what it always did.+ */+export async function ensureGrokHomeProbed(+ ask: (name: string) => Promise<string | null> = resolveShellEnvVar+): Promise<void> {+ if (probedGrokHome !== null) return+ if ((process.env as GrokEnv).GROK_HOME?.trim()) return+ let v: string | undefined+ try {+ v = (await ask('GROK_HOME'))?.trim()+ } catch {+ // A dotfile that throws is not "the variable is unset" — it is "we could not ask". Both end at+ // `~/.grok`, but only one of them is a measurement, so the failure is RECORDED below rather than+ // swallowed: that flag is the entire point of this function (rule 9).+ v = undefined+ }+ if (v) probedGrokHome = v+ else fallbackWasSilent = true+}++/**+ * True when we fell back to `~/.grok` WITHOUT any positive evidence that this is where grok looks —+ * i.e. the state in which every grok integration silently does nothing. Exposed so a diagnostic can+ * say so instead of leaving the user with a dead node and no explanation.+ */+export function grokHomeFallbackWasSilent(): boolean {+ return fallbackWasSilent+}++/** Test seam. */+export function _resetGrokHomeProbeForTests(): void {+ probedGrokHome = null+ fallbackWasSilent = false+}+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')+ if (fromEnv) return fromEnv+ // The probe answers only for the ambient environment. An explicit `env` argument is a caller+ // saying "resolve as THIS environment would", and silently substituting a shell answer there+ // would make the function lie about the environment it was handed.+ if (env === (process.env as GrokEnv) && probedGrokHome) return probedGrokHome+ return path.join(home, '.grok')}export function grokSessionsDir(env: GrokEnv = process.env as GrokEnv, home: string = homedir()): string {diff --git a/src/core/agents/hooks/index.test.ts b/src/core/agents/hooks/index.test.tsnew file mode 100644index 000000000..568cf2aad--- /dev/null+++ b/src/core/agents/hooks/index.test.ts@@ -0,0 +1,70 @@+// The $GROK_HOME probe is WIRED, not merely available.+//+// grok-paths.test.ts proves the probe resolves. This proves somebody asks it at install time — the+// distinction that matters, because the probe is exactly the kind of code the typecheck validates+// and nothing exercises: delete the call and every other test stays green while the user whose+// `export GROK_HOME=…` lives in `.zshrc` gets the hook file written where grok will never look, with+// no badge, no notification and no diagnostic, forever.+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'+import fs from 'fs'+import os from 'os'+import path from 'path'+import { installManagedAgentHooks } from './index'+import { _resetGrokHomeProbeForTests, ensureGrokHomeProbed, grokHomeDir } from '../grok-paths'+import { GROK_HOOK_FILE } from '../grok-paths'+import { fakePlatform } from '../../platform-fake'+import { initPlatform, resetPlatformForTests } from '../../platform'++// The probe's own source is mocked, not the probe: `installManagedAgentHooks` calls+// `ensureGrokHomeProbed()` with NO argument, so the only way to exercise the real wiring is to+// control what the login shell appears to say. Injecting a second `ask` from the test would resolve+// after the install's own call and prove nothing.+let shellAnswer: string | null = null+vi.mock('../../exec-path', async (orig) => ({+ ...((await orig()) as object),+ resolveShellEnvVar: async () => shellAnswer+}))++let home: string++beforeEach(() => {+ home = fs.mkdtempSync(path.join(os.tmpdir(), 'grok-home-probe-'))+ vi.spyOn(os, 'homedir').mockReturnValue(home)+ initPlatform(fakePlatform({ userDataDir: home }))+ _resetGrokHomeProbeForTests()+})+afterEach(() => {+ _resetGrokHomeProbeForTests()+ resetPlatformForTests()+ vi.restoreAllMocks()+ fs.rmSync(home, { recursive: true, force: true })+})++describe('installManagedAgentHooks — the $GROK_HOME probe (§8.9)', () => {+ it("writes grok's hook where the LOGIN SHELL says grok lives, not only under ~/.grok", async () => {+ const elsewhere = path.join(home, 'relocated-grok')+ shellAnswer = elsewhere+ // Nothing is pre-resolved: the synchronous install runs first and writes at the OLD home, then+ // the probe lands and the re-install puts the file where grok will actually look. That is the+ // real boot sequence, and it is what makes deleting the re-install a red test instead of a+ // silent regression.+ expect(grokHomeDir()).not.toBe(elsewhere)++ installManagedAgentHooks()+ await new Promise((r) => setTimeout(r, 50))++ expect(grokHomeDir()).toBe(elsewhere)+ expect(fs.existsSync(path.join(elsewhere, 'hooks', GROK_HOOK_FILE))).toBe(true)+ })++ it('writes it at the default home when the shell knows nothing — behaviour unchanged', async () => {+ // Asserted against `grokHomeDir()` rather than a hand-built `~/.grok`: this module resolves the+ // home through its own imported `homedir`, so hard-coding the path here would test the test's+ // idea of the default instead of the code's.+ shellAnswer = null+ const target = grokHomeDir()+ installManagedAgentHooks()+ await new Promise((r) => setTimeout(r, 20))+ expect(fs.existsSync(path.join(target, 'hooks', GROK_HOOK_FILE))).toBe(true)+ })+})diff --git a/src/core/agents/hooks/index.ts b/src/core/agents/hooks/index.tsindex ed1b355da..813e72f72 100644--- a/src/core/agents/hooks/index.ts+++ b/src/core/agents/hooks/index.ts@@ -6,6 +6,7 @@ import { installCodexHooks, removeCodexHooks } from './codex'import { installGeminiHooks, removeGeminiHooks } from './gemini'import { installOpencodeHooks, removeOpencodeHooks } from './opencode'import { installGrokHooks, removeGrokHooks } from './grok'+import { ensureGrokHomeProbed, grokHomeDir } from '../grok-paths'import { installCopilotHooks, removeCopilotHooks } from './copilot'type HookInstaller = readonly [string, () => void]@@ -29,6 +30,26 @@ export const MANAGED_HOOK_REMOVERS: readonly HookInstaller[] = []export function installManagedAgentHooks(): 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+ // `export GROK_HOME=…` lives there, we install into `~/.grok` and grok reads somewhere else. That+ // failure is TOTAL and SILENT: no badge, no unread dot, no notification, no session name, ever.+ //+ // Fire-and-forget and fail-open, exactly like the claude TUI call below: the first install still+ // happens synchronously against today's answer, so boot is never delayed and the pre-probe+ // behaviour is preserved. When the probe lands somewhere else, the second install puts the file+ // 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 (grokHomeDir() === grokHomeAtInstall) return+ try {+ installGrokHooks()+ } catch (e) {+ console.warn('[agent-hooks] grok re-install after $GROK_HOME probe failed', e)+ }+ })for (const [agent, install] of MANAGED_HOOK_INSTALLERS) {try {install()diff --git a/src/core/exec-path.ts b/src/core/exec-path.tsindex a678d8890..d7402cd9f 100644--- a/src/core/exec-path.ts+++ b/src/core/exec-path.ts@@ -63,6 +63,46 @@ export function resolveShellPath(): Promise<string | null> {/** The cached login-shell PATH: a string once resolved, null if the probe failed, undefined* while the async probe is still in flight (callers should then fall back + re-probe later). */+/**+ * One environment VARIABLE, as the user's login+interactive shell sees it. Same spawn shape as+ * `resolveShellPath` above and for the same reason: a GUI app launched from Finder/Dock/`.desktop`+ * never sourced the user's rc, while a CLI started by the shell inside a tmux pane did — so the two+ * disagree about anything exported there, and nothing errors.+ *+ * Cached per NAME, since each answer costs a shell spawn. Any failure (hang, non-POSIX shell,+ * Windows, unset variable) resolves to null, which every caller must read as "not set" and never as+ * a reason to refuse work.+ */+const cachedShellVars = new Map<string, Promise<string | null>>()+export function resolveShellEnvVar(name: string): Promise<string | null> {+ const hit = cachedShellVars.get(name)+ if (hit) return hit+ if (os.platform() === 'win32' || !/^[A-Z_][A-Z0-9_]*$/.test(name)) {+ const no = Promise.resolve(null)+ cachedShellVars.set(name, no)+ return no+ }+ const shell = process.env.SHELL || '/bin/bash'+ const START = '__NT_VAR_START__'+ const END = '__NT_VAR_END__'+ const p = runAsync(shell, ['-ilc', `command printf '${START}%s${END}' "$${name}"`], {+ encoding: 'utf-8',+ timeout: 5000+ })+ .then(({ stdout }) => {+ const m = stdout.match(new RegExp(`${START}([\\s\\S]*?)${END}`))+ return m?.[1]?.trim() || null+ })+ .catch(() => null)+ cachedShellVars.set(name, p)+ return p+}++/** Test seam: forget the cached shell-variable answers. */+export function _resetShellEnvVarsForTests(): void {+ cachedShellVars.clear()+}+export function shellPathNow(): string | null | undefined {return cachedShellPath}diff --git a/src/core/grok-session.test.ts b/src/core/grok-session.test.tsindex 3a3459760..add3bda6e 100644--- a/src/core/grok-session.test.ts+++ b/src/core/grok-session.test.ts@@ -15,18 +15,22 @@// `generated_title`, which is grok's own auto-name — correct, just not overridable from grok's side.// Replacing this fixture with a real capture (and correcting TITLE_KEYS if the key differs) is the// checklist item this task leaves open.-import { afterAll, describe, expect, it } from 'vitest'-import { mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'fs'-import { tmpdir } from 'os'+import { afterAll, afterEach, beforeEach, describe, expect, it } from 'vitest'+import fs, { mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'fs'+import os, { tmpdir } from 'os'import path from 'path'import {+ _resetGrokSessionDirsForTests,forgetGrokSession,grokSessionDirFor,+ persistGrokSessionDirs,pickGrokSessionMeta,readGrokSessionMeta,readGrokSessionName,rememberGrokSessionDir} from './grok-session'+import { fakePlatform } from './platform-fake'+import { initPlatform, resetPlatformForTests } from './platform'const fixture = readFileSync(path.join(__dirname, '__fixtures__/grok/summary.json'), 'utf8')@@ -143,3 +147,91 @@ describe('readGrokSessionName', () => {expect(await readGrokSessionName('unknown-session')).toBeNull()})})++describe('the sessionId → dir map survives a process restart', () => {+ // §8.5 was: the map is in-memory, so after an app restart a grok node's name does not resolve+ // until that session fires another hook. Correct but silently unhelpful — an idle session shows a+ // blank name forever. Persisting recovers what a hook already TOLD us; it is not a scan, which is+ // the thing grok deliberately does not do (a scan is how nodes adopted each other's names).+ const SID = '01a06126-b981-73f1-8b68-4547e4d7da84'+ let dataDir: string++ beforeEach(() => {+ dataDir = fs.mkdtempSync(path.join(os.tmpdir(), 'grok-map-'))+ initPlatform(fakePlatform({ userDataDir: dataDir }))+ _resetGrokSessionDirsForTests()+ })+ afterEach(() => {+ _resetGrokSessionDirsForTests()+ resetPlatformForTests()+ fs.rmSync(dataDir, { recursive: true, force: true })+ })++ it('resolves after a restart, with no hook in between', async () => {+ rememberGrokSessionDir(SID, '/some/where/sessions/enc/' + SID)+ await persistGrokSessionDirs()+ _resetGrokSessionDirsForTests() // the restart: memory gone, disk kept+ expect(grokSessionDirFor(SID)).toBe('/some/where/sessions/enc/' + SID)+ })++ it('persists BY ITSELF after a remember, with nobody calling the writer', async () => {+ // The mutation this exists for: deleting the debounced write. Every other test here calls+ // `persistGrokSessionDirs()` explicitly, so they would all stay green while production never+ // wrote a byte — the map would look persistent in the suite and be in-memory in the app.+ rememberGrokSessionDir(SID, '/auto/' + SID)+ const file = path.join(dataDir, 'grok-session-dirs.json')+ const deadline = Date.now() + 4000+ while (!fs.existsSync(file) && Date.now() < deadline) {+ await new Promise((r) => setTimeout(r, 50))+ }+ expect(fs.existsSync(file)).toBe(true)+ _resetGrokSessionDirsForTests()+ expect(grokSessionDirFor(SID)).toBe('/auto/' + SID)+ }, 8000)++ it('knows nothing when nothing was persisted — the pre-persistence answer', async () => {+ _resetGrokSessionDirsForTests()+ expect(grokSessionDirFor(SID)).toBeUndefined()+ })++ it('forgetting survives the restart too', async () => {+ rememberGrokSessionDir(SID, '/d/' + SID)+ await persistGrokSessionDirs()+ forgetGrokSession(SID)+ await persistGrokSessionDirs()+ _resetGrokSessionDirsForTests()+ expect(grokSessionDirFor(SID)).toBeUndefined()+ })++ it('rejects an id that is not a safe session id, even from our own file', async () => {+ // The file lives in a directory the user can edit and its values become filesystem paths. A+ // hand-edited or corrupt entry must not become a path we open.+ fs.writeFileSync(+ path.join(dataDir, 'grok-session-dirs.json'),+ JSON.stringify({ '../../etc': '/etc', 'not a uuid': '/tmp/x', [SID]: '/good/' + SID })+ )+ _resetGrokSessionDirsForTests()+ expect(grokSessionDirFor('../../etc')).toBeUndefined()+ expect(grokSessionDirFor('not a uuid')).toBeUndefined()+ expect(grokSessionDirFor(SID)).toBe('/good/' + SID)+ })++ it('yields an EMPTY map for a corrupt file, never a partial one', async () => {+ fs.writeFileSync(path.join(dataDir, 'grok-session-dirs.json'), '{"a": "b", TRUNCATED')+ _resetGrokSessionDirsForTests()+ expect(grokSessionDirFor(SID)).toBeUndefined()+ // …and the next remember still works: a bad file is not a permanent poison.+ rememberGrokSessionDir(SID, '/after/' + SID)+ expect(grokSessionDirFor(SID)).toBe('/after/' + SID)+ })++ it('a live hook wins over the persisted entry', async () => {+ fs.writeFileSync(+ path.join(dataDir, 'grok-session-dirs.json'),+ JSON.stringify({ [SID]: '/stale/' + SID })+ )+ _resetGrokSessionDirsForTests()+ rememberGrokSessionDir(SID, '/fresh/' + SID)+ expect(grokSessionDirFor(SID)).toBe('/fresh/' + SID)+ })+})diff --git a/src/core/grok-session.ts b/src/core/grok-session.tsindex 11263f90e..5ab91d660 100644--- a/src/core/grok-session.ts+++ b/src/core/grok-session.ts@@ -32,7 +32,9 @@// the other's tree. The choice is made once, at the IPC handler.import fs from 'fs'import path from 'path'-import { GROK_SUMMARY_FILE } from './agents/grok-paths'+import { GROK_SUMMARY_FILE, isSafeGrokSessionId } from './agents/grok-paths'+import { writeFileAtomic } from './fs-atomic'+import { platform } from './platform'/** Read at most this much of summary.json — it is small, and a capped read bounds a corrupt file. */const SUMMARY_MAX_BYTES = 256 * 1024@@ -98,11 +100,82 @@ export async function readGrokSessionMeta(sessionDir: string): Promise<GrokSessi// The hook-fed association: sessionId → its resolved session directory. Populated by the shells'// raw listeners (which see cwd + sessionId together) so every later read is a direct open. Bounded// because a long-lived app can see many sessions; the oldest entry is dropped first.+//+// PERSISTED since 2026-09, and the distinction matters: persisting is not scanning. A scan is what+// claude does — it searches its transcript tree for a session id — and it is exactly the behaviour+// that made nodes adopt each other's names, which is why grok derives instead. What is written here+// is only what a hook already TOLD us, so a restart recovers facts we were given rather than+// guessing at facts we were not. Before this, a grok node's name went blank after every app restart+// until that session next fired a hook: correct, but silently unhelpful for a session sitting idle.const MAX_TRACKED_SESSIONS = 512const sessionDirs = new Map<string, string>()+/** Where the map lives. Under userDataDir like every other derived cache, so a managed-account or+ * Server Edition install keeps its own. */+function mapFile(): string {+ return path.join(platform().userDataDir, 'grok-session-dirs.json')+}++/** Writes are debounced and never awaited by the hook path: a raw listener must not block on disk,+ * and a burst of events for one session would otherwise be a burst of writes. */+const PERSIST_DEBOUNCE_MS = 1000+let persistTimer: ReturnType<typeof setTimeout> | null = null+let loaded = false++function schedulePersist(): void {+ if (persistTimer) return+ persistTimer = setTimeout(() => {+ persistTimer = null+ void persistGrokSessionDirs()+ }, PERSIST_DEBOUNCE_MS)+ // Never hold the process open for a cache write.+ persistTimer.unref?.()+}++/** Write the map. Atomic (rule 14): a torn file here is a map that resolves nothing AND cannot be+ * repaired, which is worse than no file at all. Failures are swallowed on purpose — this is a+ * cache, and losing it costs a name until the next hook, exactly the pre-persistence behaviour. */+export async function persistGrokSessionDirs(): Promise<void> {+ try {+ await writeFileAtomic(mapFile(), JSON.stringify(Object.fromEntries(sessionDirs)), {+ mode: 0o600+ })+ } catch {+ // Cache write failed. Nothing to say and nothing to do: the in-memory map is unaffected.+ }+}++/**+ * Load the map from disk, once per process. Called lazily by the first read rather than at boot, so+ * neither shell needs a new startup step to keep the two in sync (invariant 11 by construction).+ *+ * Every entry is re-validated with `isSafeGrokSessionId` before it is trusted: this file is written+ * by us, but it sits in a directory a user can edit, and the values end up as filesystem paths. A+ * corrupt or hand-edited file yields an EMPTY map, never a partial one built from whatever parsed.+ */+function loadOnce(): void {+ if (loaded) return+ loaded = true+ try {+ const raw = fs.readFileSync(mapFile(), 'utf8')+ const parsed: unknown = JSON.parse(raw)+ if (!parsed || typeof parsed !== 'object' || Array.isArray(parsed)) return+ for (const [id, dir] of Object.entries(parsed as Record<string, unknown>)) {+ if (typeof dir !== 'string' || !dir) continue+ if (!isSafeGrokSessionId(id)) continue+ if (sessionDirs.size >= MAX_TRACKED_SESSIONS) break+ // An entry already learned from a live hook wins: it is newer by definition.+ if (!sessionDirs.has(id)) sessionDirs.set(id, dir)+ }+ } catch {+ // Absent (first run), unreadable, or not JSON — all mean "no remembered map", which is the+ // pre-persistence behaviour and never a wrong answer.+ }+}+export function rememberGrokSessionDir(sessionId: string, dir: string): void {if (!sessionId || !dir) return+ loadOnce()// Re-insert so the map's iteration order is least-recently-SEEN first: that is what makes the// eviction below drop the session nobody has heard from, not whichever one happened to be first.if (sessionDirs.has(sessionId)) sessionDirs.delete(sessionId)@@ -111,18 +184,63 @@ export function rememberGrokSessionDir(sessionId: string, dir: string): void {const oldest = sessionDirs.keys().next().valueif (oldest !== undefined) sessionDirs.delete(oldest)}+ schedulePersist()}export function grokSessionDirFor(sessionId: string | undefined): string | undefined {- return sessionId ? sessionDirs.get(sessionId) : undefined+ if (!sessionId) return undefined+ loadOnce()+ return sessionDirs.get(sessionId)}export function forgetGrokSession(sessionId: string | undefined): void {- if (sessionId) sessionDirs.delete(sessionId)+ if (!sessionId) return+ loadOnce()+ if (sessionDirs.delete(sessionId)) schedulePersist()+}++/** Test seam: drop the in-memory map AND the load flag, so a test can simulate a process restart+ * without a new process. */+export function _resetGrokSessionDirsForTests(): void {+ sessionDirs.clear()+ loaded = false+ if (persistTimer) {+ clearTimeout(persistTimer)+ persistTimer = null+ }}+/**+ * Reads a REMOTE grok session's `summary.json` on its own host.+ *+ * Returns `{ text }` for a session this reader owns (even when the body is empty — that is "remote+ * and unreadable", which must not become a local lookup), and `null` for a session it does not own,+ * which routes to the local map.+ */+export type GrokRemoteSummaryReader = (+ sessionId: string+) => Promise<{ text: string } | null>+/** The session NAME for a sessionId we have seen a hook for. null when unknown or unnamed. */-export async function readGrokSessionName(sessionId: string): Promise<string | null> {+export async function readGrokSessionName(+ sessionId: string,+ remote?: GrokRemoteSummaryReader+): Promise<string | null> {+ // A REMOTE (SSH) node's session lives on the HOST. The shells derive the directory from the LOCAL+ // sessions root with the host's `cwd`, which is a path on the wrong machine — §8.4. So the remote+ // reader is asked FIRST, and its answer is final:+ //+ // `{ text }` this session is remote. Parse that text and stop. An empty/unreadable body means+ // NO NAME — never the local map. Falling back would answer a question about the+ // host with a fact about this machine, and "could not read" and "does not exist"+ // are different facts that must stay different (rule 9).+ // `null` this session is not remote. Use the local map, exactly as before.+ //+ // Same shape as claude's `setRemoteTranscriptReader`, deliberately: one remote idiom, not two.+ if (remote) {+ const r = await remote(sessionId)+ if (r) return pickGrokSessionMeta(r.text)?.title ?? null+ }const dir = grokSessionDirFor(sessionId)if (!dir) return nullreturn (await readGrokSessionMeta(dir))?.title ?? null