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): mint a session id, feature-detected from grok's own --help
Xavi Guardia877d1e5e67d2
diff --git a/docs/grok-agent.md b/docs/grok-agent.mdindex 9dadea399..405ea5186 100644--- a/docs/grok-agent.md+++ b/docs/grok-agent.md@@ -36,7 +36,8 @@ is the cost of adding the next agent to the same list.| List | grok | What had to be true first ||---|---|---|| `AGENT_HOOK_TARGETS` | **joined** | Five things: a pure normalizer for grok's dialect (`normalizeGrok`, `src/shared/agents/normalize.ts`); a subscription list restricted to the events `normalizeGrok` actually maps — nine of the fourteen grok documents (`GROK_HOOK_EVENTS`, `src/shared/agents/hook-events.ts`); an installer able to write a **per-event matcher**, which meant widening the shared installer's event type to `ManagedHookEvent` (`core/agents/hooks/install-helper.ts`); one definition of grok's path algebra (`core/agents/grok-paths.ts`); and a raw-listener branch in **both** shells (`src/main/index.ts`, `src/server/agent-status.ts`) to derive the session directory, because grok's envelope carries no transcript path. |-| `RESUMABLE_AGENTS` | **joined** (pre-branch) | `resumeCommand('grok', id)` → `grok --resume <id>`, and a session id that reaches the renderer — which it does, off every hook payload. |+| `RESUMABLE_AGENTS` | **joined** (pre-branch) | `resumeCommand('grok', id)` → `grok --resume <id>`, and a session id that reaches the renderer — which it does, off every hook payload. **Never resume by TITLE:** `--resume` accepts one, matches it case-insensitively against the current directory's sessions, and fails as AMBIGUOUS on duplicates — so a node that resumed by name would break the day a second session shared it. The node carries its id; the id is what is used. |+| `SESSION_ID_CAPABLE` (minting the id, instead of waiting for a hook) | **joined**, on grok's OWN probe | `core/grok-cli.ts` reads `grok --help` and looks for `--session-id`, anchored on a word boundary. Feature-detection, never a version floor: an unknown flag makes grok **exit**, so a guessed floor kills every launch below it instead of degrading. The anchor is load-bearing twice — `--session-id-file` must not answer yes, and grok's own help MENTIONS `--session-id` inside the description of `--fork-session` (backticked), so a looser match would report the flag from prose alone. It is grok's probe and never claude's (rule 9: a gate fed by a version probe belongs to the agent it probes) — the two CLIs are installed and upgraded independently, and `supportsSessionIdFlag` takes grok's answer as a REQUIRED argument so no caller can silently omit it. Three grammar differences from claude, all measured on 1.0.13: the UUID **must not already exist** under the target session directory (minting a taken one is a launch error, not a resume — `mintFreeGrokSessionId` re-mints instead), `--session-id` combines with `--resume`/`--continue` only alongside `--fork-session`, and `--resume` also accepts a title (see the row above). The flag goes **before** the `--` separator: after it, grok swallows it into the prompt and the node starts looking healthy with a session nodeterm never learns. || `RENAME_CAPABLE` + `TITLE_READ_CAPABLE` | **joined both** | A **read** leg that resolves a session's own name *without searching* (`core/grok-session.ts`, keyed off the hook-fed `sessionId → session dir` map), a **write** leg byte-identical to claude's (`/rename <name>` typed into the pane via `pty.sendText`; grok also accepts `/title`), and one routing rule for the readers — `readAgentSessionName` in `core/agent-session-name.ts`, serving the desktop IPC handler *and* both shells' session-name sweeps. The list SPLIT in two after the grok branch (2026-08-09): `TITLE_READ_CAPABLE` is the read leg and `RENAME_CAPABLE` the write leg, because **gemini** names its own sessions but has no rename command. Grok is in both, so nothing about its behaviour changed — but a future agent must pick per leg, and every `RENAME_CAPABLE` member must also be `TITLE_READ_CAPABLE` (pinned in `config.capabilities.test.ts`). Routing is not cosmetic: claude's resolver scans `~/.claude/projects` on a cache miss, so an unrouted grok node paid that scan on every poll for a guaranteed null — a mounted node polls every **4 s** until the name first resolves and **15 s** after (`TerminalNode.tsx`), and the mirror's own `SESSION_NAME_SWEEP_MS` sweep adds one pass a minute. || `PERMISSION_MODE_CAPABLE` | **joined** | Grok shares claude's flag **spelling** and value vocabulary (`--permission-mode auto\|plan\|acceptEdits\|bypassPermissions`; our `manual` = no flag = grok's own `default`), which is why *its* membership needed no translation. Two things had to change around it: claude's `auto` **version gate** had to become agent-scoped (`activePermissionMode(agentId)`, `renderer/state/permissionMode.ts`), and the flag had to be emitted **before** grok's `--`. See §6. **Sharing the spelling is no longer what membership means:** the list is now `claude, grok, gemini, codex` (2026-08-09) and the last two spell it their own way (`--approval-mode`, `--ask-for-approval`), translated per agent in `src/shared/agents/approval-mode.ts` — which is also where `withPermissionMode` now lives, moved one layer up to break a `config ↔ approval-mode` cycle. || `CANVAS_CONTROL_CAPABLE` | **joined** | Nothing new to install: grok scans `~/.claude/skills` by default for Claude Code compatibility, which is exactly where `manage-nodeterm-canvas` is already written (locally, and on an SSH host by `RemoteHooks.installCanvasControl`). Membership is what sets `NODETERM_CANVAS_CONTROL=1` in the session env — `hook-server.buildPtyEnv` locally, `remoteHookEnvArgs` remotely, both through the single `canControlCanvas` predicate — i.e. what makes the sh+curl shim anything other than a no-op. **The discovery premise is MEASURED, not inferred** (grok 1.0.13, 2026-09-02): `grok inspect --json` lists `manage-nodeterm-canvas` and `get-linked-context` with `vendor: claude` and `compatibilityStatus: enabled`, and `externalCompat.cells` reports `{surface: 'skills', enabled: true, source: 'default'}`. `source: 'default'` is the part that matters: grok reads `~/.claude/skills` with **no** config edit by the user. Two per-user failure modes survive the measurement and cannot be exercised on a default-config machine — `[compat.claude] skills = false` in `~/.grok/config.toml`, and `GROK_CLAUDE_SKILLS_ENABLED=false`. In each, `NODETERM_CANVAS_CONTROL=1` is still set while the skill is undiscoverable: the shim is armed and mute. See §8.7 and checklist 21. |@@ -333,6 +334,7 @@ ai-name / comments).| ⌘M chat panel | **yes** — `chatMessagesFromGrok`, reached through the agent-routed `chat:read-transcript`. The panel is the same component; what is new is that the channel asks WHICH agent before it picks a reader | **yes, for free** — the channel is registered through the CorePlatform seam, so both shells serve it and both route the same way | the phone has no ⌘M panel || Cross-agent transfer (grok as SOURCE) | **yes** — `renderGrokTranscript` | **N/A** — `buildHandoff` lives in `src/main`; the Server Edition has no transfer path at all, pre-existing and unchanged by grok | N/A || Context meter | **yes** — a third tail, on `signals.json` rather than on a transcript, tracked from the session directory the hooks let us derive (there is no hook field pointing at it) | **yes** — both shells create the same tail the same way, with the same `wholeFile` flag. Invariant 11: a tail added in one shell only is a meter the Server Edition silently lacks | the phone reads the mirror, which is agent-agnostic, so the numbers arrive with no phone-side work |+| Session-id minting | **yes** — probed at boot (`ensureGrokCliCaps`), minted at node creation, checked against the ids already on disk for that cwd | **yes** — `registerGrokCliIpc` runs in this shell too, so the browser gets the same answer over WS-RPC. A probe registered in one shell only is minting that silently works on the desktop and not in the browser | N/A — the phone launches nothing (see §8) || Managed accounts | **deliberately N/A** — accounts are a claude config-dir mechanism. `createAgentNode` never stamps an `accountId` onto a non-claude node, and `CLAUDE_CONFIG_DIR` is irrelevant to `~/.grok/hooks`. A grok node in a managed-account project must still report status (checklist 7) | idem | idem || Brand logo | the **official** xAI mark, INLINED in `agentIcons.tsx` as `GrokMark` rather than shipped as an asset — it is a single monochrome path, so `fill="currentColor"` inherits the label colour and is correct in both themes. The other four marks are multi-colour and stay `<img src>` assets, where `currentColor` cannot inherit | same component, for free | the phone draws its own icons — **follow-up owed** || Working indicator | the **brand mark, breathing** — no critter. Since 2026-08-09 this is a THREE-agent mechanism (grok, gemini, opencode) driven by one pure decision, `brandPulsePlan` in `lib/brandPulse.ts`, with a thin renderer per surface: `BrandPulse` for the React badge (`AgentMascot` no longer imports `GrokMark`) and `workingMascot` for the notch strip. Grok is the only `kind: 'inline'` case — its mark is a single monochrome path from `lib/grokMark.ts` (`createGrokMarkSvg` in the HUD) pulsing with a `currentColor` drop-shadow bloom; the other marks are multi-colour assets whose bloom takes the label colour instead of their own ink. One decision, so an agent is never two things on two surfaces. See docs/mascot-sprites.md | **N/A** — no notch there; the canvas badge indicator works | the phone has its own SwiftUI renderer |@@ -385,6 +387,14 @@ ai-name / comments).resolves immediately *because* it scans, which is the behaviour that made nodes adopt each other'snames); the checklist records how it feels.6. **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 warmed+ per cwd on demand (`renderer/state/grokSessionIds.ts`), so the first mint in a directory+ nobody has opened yet answers "nothing taken" and the fetch it triggers only helps the NEXT+ node. Deliberate, and the alternative was worse: checking the first one too means making+ `createAgentNode` async, and it is a synchronous factory the canvas mounts from. The risk it+ leaves is a v4 UUID colliding with an existing session directory, which is not the failure+ this guard exists for — the real one is a node reusing an id from an earlier session, and+ that one IS caught once the cwd is warm.7. ~~Canvas-control discovery is unverified.~~ **MEASURED, and the premise holds.** `grok inspect--json` on grok 1.0.13 lists `get-linked-context` with `vendor: claude` and`compatibilityStatus: enabled`, and `externalCompat.cells` reportsdiff --git a/src/core/grok-cli.test.ts b/src/core/grok-cli.test.tsnew file mode 100644index 000000000..add3b7e47--- /dev/null+++ b/src/core/grok-cli.test.ts@@ -0,0 +1,50 @@+import { describe, it, expect } from 'vitest'+import { grokCliCapsFrom, UNKNOWN_GROK_CLI_CAPS } from './grok-cli'++// Verbatim from `grok --help` on 1.0.13 (2026-09-02). The two lines matter for opposite reasons:+// the first DEFINES the flag, the second only MENTIONS it inside another option's prose.+const REAL_HELP = `+ -c, --continue+ Continue the most recent session for the current working directory+ --fork-session+ When resuming (\`--resume\` / \`--continue\`), create a new session ID instead of reusing the original (optionally set via \`--session-id\`)+ -r, --resume [<SESSION_ID_OR_TITLE>]+ Resume a session by ID or title, or the most recent if omitted+ -s, --session-id <SESSION_ID>+ Use a specific session UUID for a **new** conversation (must be a valid UUID and must not already exist under the target session directory)+`++describe('grokCliCapsFrom', () => {+ it('detects the flag from the real help text', () => {+ expect(grokCliCapsFrom(REAL_HELP)).toEqual({ sessionIdFlag: true })+ })++ it('is not fooled by a longer flag that merely starts the same', () => {+ // The word-boundary anchor. `--session-id-file` is a different flag; answering yes for it would+ // put an unknown option on the command line, and an unknown option makes grok EXIT — the launch+ // dies rather than degrading.+ expect(grokCliCapsFrom(' --session-id-file <PATH>\n')).toEqual({ sessionIdFlag: false })+ })++ it('is not fooled by a prose mention inside another option', () => {+ // grok's own help does this: `--fork-session`'s description says "optionally set via+ // `--session-id`". Backticks are not whitespace, so the anchor rejects it — but the case is+ // pinned because grok WRITES it, not because it is hypothetical.+ const proseOnly =+ ' --fork-session\n create a new session ID instead of reusing the original (optionally set via `--session-id`)\n'+ expect(grokCliCapsFrom(proseOnly)).toEqual({ sessionIdFlag: false })+ })++ it('answers no for absent, empty and unreadable help', () => {+ // A failed probe must mean "omit the flag", never "block the launch".+ expect(grokCliCapsFrom('')).toEqual(UNKNOWN_GROK_CLI_CAPS)+ expect(grokCliCapsFrom(null)).toEqual(UNKNOWN_GROK_CLI_CAPS)+ expect(grokCliCapsFrom(undefined)).toEqual(UNKNOWN_GROK_CLI_CAPS)+ expect(UNKNOWN_GROK_CLI_CAPS.sessionIdFlag).toBe(false)+ })++ it('accepts the `=` spelling and end-of-line', () => {+ expect(grokCliCapsFrom('--session-id=<ID>').sessionIdFlag).toBe(true)+ expect(grokCliCapsFrom(' -s, --session-id').sessionIdFlag).toBe(true)+ })+})diff --git a/src/core/grok-cli.ts b/src/core/grok-cli.tsnew file mode 100644index 000000000..db94c171b--- /dev/null+++ b/src/core/grok-cli.ts@@ -0,0 +1,67 @@+// Capability probe for the LOCAL grok CLI.+//+// Separate from `claude-cli.ts` on purpose. Rule 9 of CLAUDE.md: *a capability gate that is fed by a+// version probe belongs to the agent it probes*. Answering "can grok mint a session id?" with what+// the OTHER CLI's probe returned would be a guess wearing a measurement's clothes — and the two are+// installed and upgraded independently, so the answer is not even correlated.+//+// Feature-detection over `grok --help`, never a version floor: an unknown flag makes grok EXIT, so a+// floor guessed too low kills every launch on the machines below it instead of degrading. Absent or+// unreadable help ⇒ false ⇒ no flag ⇒ the command line stays exactly what it is today.+import { execFile } from 'child_process'+import { promisify } from 'util'+import { IPC } from '../shared/ipc'+import { findInLoginPath } from './pty-manager'+import { platform } from './platform'+import { listGrokSessionIds } from './grok-session-mint'+import { grokSessionsDir } from './agents/grok-paths'+import { UNKNOWN_GROK_CLI_CAPS, type GrokCliCaps } from '../shared/types'++const execFileP = promisify(execFile)+const PROBE_TIMEOUT_MS = 5000++export { UNKNOWN_GROK_CLI_CAPS, type GrokCliCaps }++/**+ * Pure: help output → caps. The impure probe below is plumbing around it.+ *+ * Anchored on a word boundary, which is load-bearing twice over. `--session-id-file` must not+ * answer yes for `--session-id`; and grok's own help MENTIONS `--session-id` inside the description+ * of `--fork-session`, wrapped in backticks — a looser match would report the flag from prose alone.+ */+export function grokCliCapsFrom(helpOutput: string | null | undefined): GrokCliCaps {+ return { sessionIdFlag: /(^|\s)--session-id(\s|=|$)/m.test(helpOutput ?? '') }+}++let cached: Promise<GrokCliCaps> | null = null++async function probe(): Promise<GrokCliCaps> {+ try {+ // GUI apps don't inherit the shell PATH — resolve through the login shell like every other CLI+ // lookup in the app.+ const bin = await findInLoginPath('grok')+ if (!bin) return UNKNOWN_GROK_CLI_CAPS+ const { stdout } = await execFileP(bin, ['--help'], { timeout: PROBE_TIMEOUT_MS })+ return grokCliCapsFrom(stdout)+ } catch {+ // Missing CLI, timeout, non-zero exit — all mean "unknown", which means "omit the flag".+ return UNKNOWN_GROK_CLI_CAPS+ }+}++/** The local grok CLI's capabilities. Memoized for the process lifetime. Never rejects. */+export function grokCliCaps(): Promise<GrokCliCaps> {+ if (!cached) cached = probe()+ return cached+}++/** Wire the probe onto the platform's RPC surface (Electron ipcMain / server WS-RPC alike), so both+ * shells answer it — a probe registered in one shell only is a feature the other silently lacks. */+export function registerGrokCliIpc(): void {+ platform().handle(IPC.grokCliCaps, () => grokCliCaps())+ // The session ids grok already owns for a cwd. Sent as an ARRAY because a Set does not survive+ // the IPC/WS-RPC boundary — it would arrive as `{}` and silently report nothing taken.+ platform().handle(IPC.grokTakenSessionIds, (cwd: string) =>+ typeof cwd === 'string' && cwd ? [...listGrokSessionIds(grokSessionsDir(), cwd)] : []+ )+}diff --git a/src/core/grok-session-mint.test.ts b/src/core/grok-session-mint.test.tsnew file mode 100644index 000000000..f54c6d240--- /dev/null+++ b/src/core/grok-session-mint.test.ts@@ -0,0 +1,67 @@+import { describe, it, expect } from 'vitest'+import fs from 'fs'+import os from 'os'+import path from 'path'+import { listGrokSessionIds } from './grok-session-mint'+import { mintFreeGrokSessionId } from '../shared/agents/grok-session-mint'+import { grokEncodedCwdDirName } from './agents/grok-paths'++const ID_A = '01a06126-b981-73f1-8b68-4547e4d7da84'+const ID_B = '01a06126-b981-79f2-ad74-af463c662107'++describe('mintFreeGrokSessionId', () => {+ it('returns the candidate when nothing owns it', () => {+ expect(mintFreeGrokSessionId(new Set(), () => ID_A)).toBe(ID_A)+ })++ it('mints ANOTHER id when the first one already exists on disk', () => {+ // The whole point. grok refuses an id that already exists under the session directory — that is+ // a launch error, not a resume, so reusing it means the node never starts.+ const seq = [ID_A, ID_B]+ let i = 0+ expect(mintFreeGrokSessionId(new Set([ID_A]), () => seq[i++])).toBe(ID_B)+ })++ it('gives up rather than returning a taken id, and rather than looping forever', () => {+ // A generator that only ever produces a taken id means something is broken. The safe answer is+ // no id at all — launch without the flag, learn the id from a hook, exactly as before minting+ // existed. Returning the taken one would kill the launch; looping would hang node creation.+ let calls = 0+ const out = mintFreeGrokSessionId(new Set([ID_A]), () => {+ calls+++ return ID_A+ })+ expect(out).toBeUndefined()+ expect(calls).toBe(3)+ })++ it('never returns an empty candidate', () => {+ expect(mintFreeGrokSessionId(new Set(), () => '')).toBeUndefined()+ })+})++describe('listGrokSessionIds', () => {+ it('reads the ids grok already has for that cwd', () => {+ const root = fs.mkdtempSync(path.join(os.tmpdir(), 'grok-mint-'))+ const cwd = '/Users/someone/Repositories/thing'+ const dir = path.join(root, grokEncodedCwdDirName(cwd)!)+ fs.mkdirSync(path.join(dir, ID_A), { recursive: true })+ fs.mkdirSync(path.join(dir, ID_B), { recursive: true })+ // A stray FILE is not a session: only directory names count.+ fs.writeFileSync(path.join(dir, 'not-a-session.json'), '{}')+ expect(listGrokSessionIds(root, cwd)).toEqual(new Set([ID_A, ID_B]))+ fs.rmSync(root, { recursive: true, force: true })+ })++ it('answers the empty set for a cwd grok has never run in', () => {+ const root = fs.mkdtempSync(path.join(os.tmpdir(), 'grok-mint-'))+ expect(listGrokSessionIds(root, '/nowhere/at/all')).toEqual(new Set())+ fs.rmSync(root, { recursive: true, force: true })+ })++ it('answers the empty set — never throws — when the root is unreadable', () => {+ // Degrades to "mint freely", not to "refuse to mint": an unreadable directory must not cost the+ // node its session id.+ expect(listGrokSessionIds('/definitely/not/here', '/some/cwd')).toEqual(new Set())+ })+})diff --git a/src/core/grok-session-mint.ts b/src/core/grok-session-mint.tsnew file mode 100644index 000000000..917b425a2--- /dev/null+++ b/src/core/grok-session-mint.ts@@ -0,0 +1,38 @@+// Minting a grok session id that grok will actually accept.+//+// grok's `--session-id` is stricter than claude's in a way that turns OUR bug into a node that does+// not start (measured, 1.0.13): *"must be a valid UUID and must not already exist under the target+// session directory"*. Handing it an id that is already on disk is a LAUNCH ERROR, not a resume —+// grok exits, and the user sees a terminal that died instead of an agent.+//+// So the candidate is checked against what is already there before it is used. The check is split in+// two on purpose: a pure chooser that can be tested against any set, and a thin directory read.+import fs from 'fs'+import path from 'path'+import { grokEncodedCwdDirName } from './agents/grok-paths'++export { mintFreeGrokSessionId } from '../shared/agents/grok-session-mint'++/**+ * The session ids grok already has for this cwd: the directory names under+ * `<sessionsDir>/<encoded cwd>/`.+ *+ * Reads directory NAMES only — no file is opened and no session is parsed, because the question is+ * only "does this id exist". An unreadable or absent directory answers the empty set, which is the+ * honest answer for a cwd grok has never run in, and degrades to "mint freely" rather than to+ * "refuse to mint".+ */+export function listGrokSessionIds(sessionsDir: string, cwd: string): Set<string> {+ const encoded = grokEncodedCwdDirName(cwd)+ if (!encoded) return new Set()+ try {+ return new Set(+ fs+ .readdirSync(path.join(sessionsDir, encoded), { withFileTypes: true })+ .filter((e) => e.isDirectory())+ .map((e) => e.name)+ )+ } catch {+ return new Set()+ }+}diff --git a/src/main/index.ts b/src/main/index.tsindex 09d1f131b..8bde188df 100644--- a/src/main/index.ts+++ b/src/main/index.ts@@ -229,6 +229,7 @@ import { registerSpeechIpc } from '../core/speech/register-ipc'import { initClaudeAccounts } from './claude-accounts'import { initCodexAccounts } from './codex-accounts'import { claudeCliCaps, registerClaudeCliIpc, type ClaudeCliCaps } from '../core/claude-cli'+import { registerGrokCliIpc } from '../core/grok-cli'import { refreshCodexIdentityCaps, registerCodexIdentityIpc } from '../core/codex-identity-caps'import {bindCodexThreadIdentity,@@ -1217,6 +1218,9 @@ app.whenReady().then(async () => {process.platform === 'darwin' ? systemPreferences.askForMediaAccess('microphone') : true)registerClaudeCliIpc()+ // Invariant 11 for probes: registered in BOTH shells, or session-id minting silently works on+ // the desktop and not in the browser, with nothing to say which.+ registerGrokCliIpc()registerCodexIdentityIpc()// Warm the `claude --version` probe now (it spawns a login shell + node, ~sub-second) so the// renderer's first `claude.cliCaps()` — awaited on the launch path of a cold-restored agentdiff --git a/src/preload/index.ts b/src/preload/index.tsindex b2809c4ea..4c78e0ca7 100644--- a/src/preload/index.ts+++ b/src/preload/index.ts@@ -514,6 +514,10 @@ const api: NodeTerminalApi = {readTranscript: (sessionId, cwd, accountId, nodeId) =>ipcRenderer.invoke(IPC.claudeReadTranscript, sessionId, cwd, accountId, nodeId)},+ grok: {+ cliCaps: () => ipcRenderer.invoke(IPC.grokCliCaps),+ takenSessionIds: (cwd) => ipcRenderer.invoke(IPC.grokTakenSessionIds, cwd)+ },agent: {envSnapshot: () => ipcRenderer.invoke(IPC.envSnapshot),discoverModels: (settings) => ipcRenderer.invoke(IPC.agentDiscoverModels, settings),diff --git a/src/renderer/boot.tsx b/src/renderer/boot.tsxindex 3bac44f92..725b5b639 100644--- a/src/renderer/boot.tsx+++ b/src/renderer/boot.tsx@@ -1,7 +1,7 @@import React from 'react'import ReactDOM from 'react-dom/client'import App from './App'-import { ensureClaudeCliCaps } from './state/permissionMode'+import { ensureClaudeCliCaps, ensureGrokCliCaps } from './state/permissionMode'import { ensureCodexIdentityCaps } from './state/codexIdentity'import { initAgentResolver } from './state/agent-resolver'import { refreshAgentEnv } from './lib/agentEnv'@@ -17,6 +17,9 @@ initAgentResolver()// conservatively omit the flag. The shell warms the same memo at startup, so this normally// resolves immediately.void ensureClaudeCliCaps()+// Same, for grok: its own probe, kicked off at boot so a node created seconds later already has+// the real answer instead of the fail-open one.+void ensureGrokCliCaps()// Same shape, same reason: a Codex launch line names the managed shared-identity launcher only if// this machine has one installed and armed. Unprobed ⇒ plain `codex`, which is what every Codexdiff --git a/src/renderer/bridge/stubs.ts b/src/renderer/bridge/stubs.tsindex c912525c0..1487e7390 100644--- a/src/renderer/bridge/stubs.ts+++ b/src/renderer/bridge/stubs.ts@@ -16,6 +16,7 @@import {UNKNOWN_CLAUDE_CLI_CAPS,+ UNKNOWN_GROK_CLI_CAPS,UNKNOWN_CODEX_IDENTITY_CAPS,type ClaudeUsage,type NodeTerminalApi,@@ -286,6 +287,14 @@ export function buildStubApi(): Omit<cliCaps: () => Promise.resolve(UNKNOWN_CLAUDE_CLI_CAPS),readTranscript: U('claude.readTranscript')},+ grok: {+ // Same shape and same reason as claude's above: the launch path reads this synchronously, so+ // it must resolve rather than reject. Unprobed ⇒ no `--session-id` ⇒ today's command line.+ cliCaps: () => Promise.resolve(UNKNOWN_GROK_CLI_CAPS),+ // Nothing taken is the honest answer where no shell can look, and it degrades to today's+ // behaviour: mint freely. Overridden by the real WS-backed namespace in ws-bridge.+ takenSessionIds: () => Promise.resolve([])+ },agent: {// No env snapshot outside the desktop window: the stub (and ws-bridge, identically) answers// an empty env, so `${env:VAR}` expansion reports every referenced var as missing and thediff --git a/src/renderer/bridge/ws-bridge.ts b/src/renderer/bridge/ws-bridge.tsindex eaf35b4fb..66ae53d99 100644--- a/src/renderer/bridge/ws-bridge.ts+++ b/src/renderer/bridge/ws-bridge.ts@@ -17,6 +17,7 @@ import { IPC } from '../../shared/ipc'import type { GitHubControlApi, GitHubIssuesApi } from '../../shared/github-issues'import {UNKNOWN_CLAUDE_CLI_CAPS,+ UNKNOWN_GROK_CLI_CAPS,type BoardLogApi,type LogApi,type LogRecord,@@ -24,6 +25,8 @@ import {type ChatTranscriptResult,type ClaudeApi,type ClaudeCliCaps,+ type GrokApi,+ type GrokCliCaps,type CodexApi,type CodexIdentityCaps,UNKNOWN_CODEX_IDENTITY_CAPS,@@ -813,6 +816,18 @@ export function buildClaudeApi(client: RpcClient, stub: ClaudeApi): ClaudeApi {}}+/** grok's probe over WS-RPC. A REAL handler server-side (`registerGrokCliIpc` runs in that shell+ * too), so the browser gets the same answer the desktop does — not a stub that quietly disables+ * session-id minting on one surface only. Rejection degrades to the fail-open caps. */+export function buildGrokApi(client: RpcClient): GrokApi {+ return {+ cliCaps: () =>+ (client.request(IPC.grokCliCaps) as Promise<GrokCliCaps>).catch(() => UNKNOWN_GROK_CLI_CAPS),+ takenSessionIds: (cwd: string) =>+ (client.request(IPC.grokTakenSessionIds, cwd) as Promise<string[]>).catch(() => [])+ }+}+/*** The two transcript READ channels, now that `registerTranscriptIpc` serves them in the server* shell too. Before this the browser had no handler at all: the stub rejected, the ⌘M panel never@@ -1005,7 +1020,8 @@ export async function installWsBridge(): Promise<boolean> {const t = buildTranscriptApi(client)return {chat: t.chat,- claude: { ...buildClaudeApi(client, stubApi.claude), readTranscript: t.claudeReadTranscript }+ claude: { ...buildClaudeApi(client, stubApi.claude), readTranscript: t.claudeReadTranscript },+ grok: buildGrokApi(client)}})(),// Web replacement for the Electron native dialog: an in-app server-directory browser overdiff --git a/src/renderer/state/grokSessionIds.ts b/src/renderer/state/grokSessionIds.tsnew file mode 100644index 000000000..2585a3cc5--- /dev/null+++ b/src/renderer/state/grokSessionIds.ts@@ -0,0 +1,46 @@+// Which session ids grok already owns, per cwd — warmed in the renderer so the SYNC node factory can+// consult it.+//+// Why a memo and not an await: `createAgentNode` is a synchronous factory (it returns a node the+// canvas mounts immediately), and grok's constraint has to be answered at the moment the id is+// minted. Same shape as `permissionMode.ts`'s caps memo and `projectLaunchInfo.ts`'s per-project+// one, for the same reason both give: nothing renders off this.+//+// SELF-WARMING, and the first mint in a fresh cwd is deliberately unwarmed. An unwarmed cwd answers+// "nothing taken", which is exactly today's behaviour — mint a v4 uuid and go — and the fetch it+// kicks off means the NEXT node in that cwd is checked for real. That is the honest trade: this+// exists to stop a node reusing an id from an earlier session on disk, not to defend against a v4+// collision, and defending the first mint too would mean making node creation async everywhere.+const taken = new Map<string, Set<string>>()+const inFlight = new Map<string, Promise<void>>()++/** Ask the shell, once per cwd. Never rejects: a failed read leaves the cwd unwarmed, which reads as+ * "nothing taken" — mint freely — rather than costing the node its id. */+export function ensureGrokTakenIds(cwd: string): Promise<void> {+ if (!cwd) return Promise.resolve()+ const existing = inFlight.get(cwd)+ if (existing) return existing+ const p = Promise.resolve()+ .then(() => window.nodeTerminal.grok.takenSessionIds(cwd))+ .then((ids) => {+ taken.set(cwd, new Set(Array.isArray(ids) ? ids : []))+ })+ .catch(() => {+ // Leave it unwarmed on purpose: an entry of "nothing taken" cached after a FAILED read would+ // look identical to a real empty answer and never be retried.+ inFlight.delete(cwd)+ })+ inFlight.set(cwd, p)+ return p+}++/** What is known right now for this cwd. An unwarmed cwd is an empty set — see the module doc. */+export function grokTakenIdsNow(cwd: string): ReadonlySet<string> {+ return taken.get(cwd) ?? new Set()+}++/** Test seam. */+export function resetGrokTakenIdsForTests(): void {+ taken.clear()+ inFlight.clear()+}diff --git a/src/renderer/state/permissionMode.ts b/src/renderer/state/permissionMode.tsindex a0cdf152c..86ac791df 100644--- a/src/renderer/state/permissionMode.ts+++ b/src/renderer/state/permissionMode.ts@@ -5,7 +5,13 @@ import {type AgentId,type AgentPermissionMode} from '@shared/agents/config'-import { UNKNOWN_CLAUDE_CLI_CAPS, type ClaudeCliCaps, type Project } from '@shared/types'+import {+ UNKNOWN_CLAUDE_CLI_CAPS,+ UNKNOWN_GROK_CLI_CAPS,+ type ClaudeCliCaps,+ type GrokCliCaps,+ type Project+} from '@shared/types'import { useProjects } from './projects'import { useSettings } from './settings'import { useSshConn, type SshAutoPermAnswer } from './sshConn'@@ -62,6 +68,43 @@ export function claudeCliCapsNow(): ClaudeCliCaps {return caps}+/**+ * The same memo, for grok. A SEPARATE probe and a separate memo on purpose: rule 9 — a capability+ * gate fed by a version probe belongs to the agent it probes. grok and claude are installed and+ * upgraded independently, so claude's answer says nothing about grok's, and borrowing it would be a+ * guess dressed as a measurement.+ *+ * Same fail-open shape: until it answers, "no flag", i.e. the bare `grok` command. A launch is never+ * blocked on a probe.+ */+let grokCaps: GrokCliCaps = UNKNOWN_GROK_CLI_CAPS+let grokCapsPromise: Promise<GrokCliCaps> | null = null++export function ensureGrokCliCaps(): Promise<GrokCliCaps> {+ if (!grokCapsPromise) {+ const probe = Promise.resolve()+ .then(() => window.nodeTerminal.grok.cliCaps())+ .then((c) => (grokCaps = c ?? UNKNOWN_GROK_CLI_CAPS))+ .catch(() => UNKNOWN_GROK_CLI_CAPS)+ const timeout = new Promise<GrokCliCaps>((resolve) =>+ setTimeout(() => resolve(grokCaps), CAPS_WAIT_MS)+ )+ grokCapsPromise = Promise.race([probe, timeout])+ }+ return grokCapsPromise+}++/** Last-known grok caps, synchronously — node creation is a sync factory. */+export function grokCliCapsNow(): GrokCliCaps {+ return grokCaps+}++/** Test seam for the grok memo. */+export function resetGrokCliCapsForTests(next?: GrokCliCaps): void {+ grokCaps = next ?? UNKNOWN_GROK_CLI_CAPS+ grokCapsPromise = null+}+/** Test seam: drop the memo (and optionally preload a known answer). */export function resetClaudeCliCapsForTests(next?: ClaudeCliCaps): void {caps = next ?? UNKNOWN_CLAUDE_CLI_CAPSdiff --git a/src/renderer/state/workspace.session-id.test.ts b/src/renderer/state/workspace.session-id.test.tsindex d60057047..e57fc38db 100644--- a/src/renderer/state/workspace.session-id.test.ts+++ b/src/renderer/state/workspace.session-id.test.ts@@ -1,6 +1,7 @@import { describe, it, expect, beforeEach, afterEach } from 'vitest'import { createAgentNode, flowToNodeStates, nodeStatesToFlow } from './workspace'-import { resetClaudeCliCapsForTests } from './permissionMode'+import { resetClaudeCliCapsForTests, resetGrokCliCapsForTests } from './permissionMode'+import { resetGrokTakenIdsForTests } from './grokSessionIds'import { UNKNOWN_CLAUDE_CLI_CAPS } from '@shared/types'const UUID_RE = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i@@ -9,7 +10,11 @@ const UUID_RE = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/const capable = (): void =>resetClaudeCliCapsForTests({ ...UNKNOWN_CLAUDE_CLI_CAPS, version: '2.1.226', sessionIdFlag: true })-afterEach(() => resetClaudeCliCapsForTests())+afterEach(() => {+ resetClaudeCliCapsForTests()+ resetGrokCliCapsForTests()+ resetGrokTakenIdsForTests()+})describe('createAgentNode mints a session id when the CLI accepts one', () => {beforeEach(capable)@@ -29,7 +34,10 @@ describe('createAgentNode mints a session id when the CLI accepts one', () => {// Claude and Copilot accept a caller-chosen id. For every other agent the command line must stay// exactly what it was, or an unknown flag kills the launch.it('leaves non-capable agents unstamped and their command unchanged', () => {- for (const id of ['codex', 'gemini', 'grok', 'opencode'] as const) {+ // grok is NOT in this list any more: it mints too, but off its own probe (below). An agent whose+ // capability is real must never be used as the example of one that lacks it — the example stops+ // asserting anything the day it changes.+ for (const id of ['codex', 'gemini', 'opencode'] as const) {const n = createAgentNode(id, 0)expect(n.data.agentSessionId).toBeUndefined()expect(n.data.initialCommand).not.toContain('--session-id')@@ -97,3 +105,36 @@ describe('agentSessionId survives persistence', () => {expect(loaded.data.agentSessionId).toBeUndefined()})})+++describe('grok mints on ITS OWN probe', () => {+ beforeEach(() => {+ resetGrokTakenIdsForTests()+ resetClaudeCliCapsForTests()+ })++ it('stamps a grok node once grok\'s help advertised the flag', () => {+ resetGrokCliCapsForTests({ sessionIdFlag: true })+ const n = createAgentNode('grok', 0)+ expect(n.data.agentSessionId).toMatch(UUID_RE)+ // BEFORE the separator: grok's `--` is end of options, so a flag after it is swallowed into the+ // prompt — the node launches, looks healthy, and mints an id nodeterm never learns.+ expect(n.data.initialCommand).toContain(`--session-id ${n.data.agentSessionId}`)+ })++ it('does NOT mint when only CLAUDE advertised the flag — the probe belongs to the agent', () => {+ // The mutation this exists for: pointing grok's gate at claude's probe result. Both CLIs are+ // installed and upgraded independently, so claude's answer says nothing about grok's.+ resetClaudeCliCapsForTests({ ...UNKNOWN_CLAUDE_CLI_CAPS, version: '2.1.226', sessionIdFlag: true })+ resetGrokCliCapsForTests({ sessionIdFlag: false })+ const n = createAgentNode('grok', 0)+ expect(n.data.agentSessionId).toBeUndefined()+ expect(n.data.initialCommand).not.toContain('--session-id')+ })++ it('mints nothing while grok is unprobed, leaving the command byte-identical', () => {+ const n = createAgentNode('grok', 0)+ expect(n.data.agentSessionId).toBeUndefined()+ expect(n.data.initialCommand).not.toContain('--session-id')+ })+})diff --git a/src/renderer/state/workspace.ts b/src/renderer/state/workspace.tsindex b999f795d..dd977a635 100644--- a/src/renderer/state/workspace.ts+++ b/src/renderer/state/workspace.ts@@ -9,11 +9,13 @@ import type {Settings} from '@shared/types'import type { AgentId, AgentPermissionMode, BuiltinAgentId } from '@shared/agents/config'-import { agentConfig, supportsSessionIdFlag } from '@shared/agents/config'+import { agentConfig, capabilityAgentId, supportsSessionIdFlag } from '@shared/agents/config'import { assembleLaunchCommand } from '@shared/agents/launch'import { agentEnvSnapshot } from '../lib/agentEnv'import { uuid } from '@renderer/lib/uuid'-import { claudeCliCapsNow } from './permissionMode'+import { claudeCliCapsNow, grokCliCapsNow } from './permissionMode'+import { ensureGrokTakenIds, grokTakenIdsNow } from './grokSessionIds'+import { mintFreeGrokSessionId } from '@shared/agents/grok-session-mint'import { projectLaunchInfoNow } from './projectLaunchInfo'import { isAgentEnabled, launchableDefaultAgent } from './agentAvailability'import { codexSharedIdentity } from './codexIdentity'@@ -608,8 +610,22 @@ export function createAgentNode(// learning its id from hooks exactly as before. Inheritance-aware: a custom agent with// baseAgent:'claude' mints an id too (capabilityAgentId resolves it to claude).const cliCaps = claudeCliCapsNow()- const sessionIdFlagSupported = supportsSessionIdFlag(agentId, cliCaps.sessionIdFlag)- const mintedSessionId = sessionIdFlagSupported ? uuid() : undefined+ // Each probed agent answers with its own probe — grok's flag never rides claude's result.+ const sessionIdFlagSupported = supportsSessionIdFlag(+ agentId,+ cliCaps.sessionIdFlag,+ grokCliCapsNow().sessionIdFlag+ )+ // grok refuses a `--session-id` that already exists under its session directory for this cwd —+ // that is a LAUNCH ERROR, not a resume, so a node handed a taken id never starts. The check is+ // synchronous against a warmed per-cwd memo (see grokSessionIds.ts for why the first mint in a+ // fresh cwd is deliberately unchecked), and `mintFreeGrokSessionId` returns undefined rather than+ // a taken id — which degrades to the pre-minting command line instead of a dead terminal.+ const mintedSessionId = !sessionIdFlagSupported+ ? undefined+ : capabilityAgentId(agentId) === 'grok'+ ? (ensureGrokTakenIds(cwd ?? ''), mintFreeGrokSessionId(grokTakenIdsNow(cwd ?? ''), uuid))+ : uuid()// Command assembly is delegated to the ONE shared builder (src/shared/agents/launch.ts), used by// fresh launch AND cold-restore resume, so a custom agent's baseAgent/args/expansion are applied// identically in both paths. ${env:...} in launchCmd/args expands against the boot-time envdiff --git a/src/server/handlers/index.test.ts b/src/server/handlers/index.test.tsindex f1ef829f9..005fbe06a 100644--- a/src/server/handlers/index.test.ts+++ b/src/server/handlers/index.test.ts@@ -195,3 +195,24 @@ describe('registerCoreHandlers (managed Claude accounts, #313)', () => {await expect(call(IPC.claudeAccountsCancelWait, 'nobody')).resolves.toBeNull()})})++describe('registerCoreHandlers (the grok CLI probe, on BOTH shells)', () => {+ // Invariant 11 for probes. A probe registered in the desktop shell only is session-id minting that+ // silently works on the desktop and not in the browser, with nothing anywhere to say which — and+ // deleting the registration is a change the typecheck cannot see, which is exactly the family of+ // wiring bug this branch has been paying for.+ it('answers grok:cli caps rather than rejecting as unknown', async () => {+ const caps = (await call(IPC.grokCliCaps)) as { sessionIdFlag: boolean }+ // The value depends on whether grok is installed on the machine running the suite, so this+ // asserts the SHAPE and the fact that the method exists at all — an unregistered method throws.+ expect(typeof caps.sessionIdFlag).toBe('boolean')+ })++ it('answers the taken-session-id lookup with an array', async () => {+ // An array, not a Set: a Set does not survive the WS-RPC boundary and would arrive as `{}`,+ // reporting "nothing taken" for every cwd — the one wrong answer this call can give.+ const ids = await call(IPC.grokTakenSessionIds, '/definitely/not/a/real/cwd')+ expect(Array.isArray(ids)).toBe(true)+ expect(ids).toEqual([])+ })+})diff --git a/src/server/handlers/index.ts b/src/server/handlers/index.tsindex 23e33956b..ad092a714 100644--- a/src/server/handlers/index.ts+++ b/src/server/handlers/index.ts@@ -7,6 +7,7 @@ import { GitService } from '../../core/git-service'import { generateCommitMessage } from '../../core/commit-message'import { registerFsHandlers } from '../../core/fs-handlers'import { claudeCliCaps, registerClaudeCliIpc } from '../../core/claude-cli'+import { registerGrokCliIpc } from '../../core/grok-cli'import { registerCodexIdentityIpc } from '../../core/codex-identity-caps'import { UNKNOWN_CODEX_IDENTITY_CAPS } from '@shared/types'import { startUsageService } from '../../core/usage/usage-service'@@ -71,6 +72,9 @@ export function registerCoreHandlers(// The browser needs the same `--permission-mode auto` version gate as desktop: the server's own// claude CLI is the one that will run the terminal nodes. Warm it so the first call is cached.registerClaudeCliIpc()+ // Invariant 11 for probes: registered in BOTH shells, or session-id minting silently works on+ // the desktop and not in the browser, with nothing to say which.+ registerGrokCliIpc()void claudeCliCaps()// ---- Codex shared identity: a DELIBERATE degrade, not an omission ----------------------------diff --git a/src/shared/agents/config.capabilities.test.ts b/src/shared/agents/config.capabilities.test.tsindex 5fa224c7f..56dc1c773 100644--- a/src/shared/agents/config.capabilities.test.ts+++ b/src/shared/agents/config.capabilities.test.ts@@ -4,6 +4,8 @@ import {BUILTIN_AGENT_IDS,canBranch,canChat,+ mintsSessionId,+ supportsSessionIdFlag,readsClaudeShapedTranscript,canContextLink,canControlCanvas,@@ -230,6 +232,21 @@ describe('grok capabilities', () => {expect(readsClaudeShapedTranscript('grok')).toBe(false)})+ it('mints its own session id, gated on ITS OWN probe and never on claude\'s', () => {+ expect(mintsSessionId('grok')).toBe(true)+ // The third argument is grok's probe. Claude's answer must not move grok's gate in EITHER+ // direction — that is rule 9: a gate fed by a version probe belongs to the agent it probes, and+ // the two CLIs are installed and upgraded independently.+ expect(supportsSessionIdFlag('grok', false, true)).toBe(true)+ expect(supportsSessionIdFlag('grok', true, false)).toBe(false)+ // Unprobed reads as no: a bare command, never a blocked launch. There is no shorter call to+ // write — the third argument is required precisely so nobody can omit grok's probe by accident.+ expect(supportsSessionIdFlag('grok', true, false)).toBe(false)+ // And grok's probe must not move CLAUDE's gate either.+ expect(supportsSessionIdFlag('claude', true, false)).toBe(true)+ expect(supportsSessionIdFlag('claude', false, true)).toBe(false)+ })+it('does not yet claim the capabilities whose per-agent leaf is unwritten', () => {expect(canBranch('grok')).toBe(false)expect(canSubagent('grok')).toBe(false)diff --git a/src/shared/agents/config.ts b/src/shared/agents/config.tsindex 576190b9c..508258635 100644--- a/src/shared/agents/config.ts+++ b/src/shared/agents/config.ts@@ -120,10 +120,19 @@ export const RESUMABLE_AGENTS = ['claude', 'codex', 'gemini', 'opencode', 'grok'// clear/fork/compact), so hooks remain the only way to TRACK an id after launch. What minting// guarantees is that a node always has SOME resumable id, so the worst case degrades from "the// conversation is gone" to "continuity since the last /clear is gone".-export const SESSION_ID_CAPABLE = ['claude', 'copilot'] as const+export const SESSION_ID_CAPABLE = ['claude', 'copilot', 'grok'] as const// Claude's flag is version-gated and comes from the Claude CLI probe. Copilot's installed 1.0.80// binary and current official reference accept `--session-id=<uuid>`, so it does not borrow an// unrelated Claude probe result. Custom agents resolve through their declared base harness.+//+// grok is gated too, but on ITS OWN probe (`core/grok-cli.ts` reads `grok --help`) — never on+// claude's. The two CLIs are installed and upgraded independently, so claude's answer is not even+// correlated with grok's, and a gate fed by the wrong agent's probe is a guess wearing a+// measurement's clothes. Its grammar also differs from claude's in three measured ways (1.0.13):+// the UUID must not already exist under the target session directory, so minting one twice is a+// LAUNCH ERROR and never a resume; `--session-id` combines with `--resume`/`--continue` only+// alongside `--fork-session`; and `--resume` accepts a TITLE as well as an id, failing as ambiguous+// on duplicates — which is why nothing in this codebase resumes grok by title.export const UNCONDITIONAL_SESSION_ID_CAPABLE = ['copilot'] as const// claude: Task/Agent tool via hooks (tool_use_id-keyed). codex: spawn_agent collaboration via its// native SubagentStart/SubagentStop hooks (agent_id-keyed), measured on codex-cli 0.146.0.@@ -328,9 +337,25 @@ export const hasHooks = (id: AgentId): boolean => includes(AGENT_HOOK_TARGETS, iexport const canResume = (id: AgentId): boolean => includes(RESUMABLE_AGENTS, id)export const mintsSessionId = (id: AgentId): boolean => includes(SESSION_ID_CAPABLE, id)/** Is the caller-chosen session-id flag available for this effective base harness? */-export const supportsSessionIdFlag = (id: AgentId, claudeFlagSupported: boolean): boolean =>- includes(UNCONDITIONAL_SESSION_ID_CAPABLE, id) ||- (mintsSessionId(id) && capabilityAgentId(id) === 'claude' && claudeFlagSupported)+export const supportsSessionIdFlag = (+ id: AgentId,+ claudeFlagSupported: boolean,+ // REQUIRED, not defaulted. A default here would let a caller forget grok's probe and silently get+ // "grok never mints" — a feature quietly missing, with a green typecheck and no test to notice.+ // That is the same shape as the optional prop that let the chat panel's agent id be dropped; the+ // lesson taken from it is that the fix for this family is a type that cannot express the broken+ // state, not another test somebody has to remember to write.+ grokFlagSupported: boolean+): boolean => {+ if (includes(UNCONDITIONAL_SESSION_ID_CAPABLE, id)) return true+ if (!mintsSessionId(id)) return false+ const base = capabilityAgentId(id)+ // Each probed agent answers with ITS OWN probe. A missing third argument reads as "grok was not+ // probed", which yields a bare command — the safe direction, and the same one an unprobed claude+ // gets.+ if (base === 'grok') return grokFlagSupported+ return base === 'claude' && claudeFlagSupported+}export const canSubagent = (id: AgentId): boolean => includes(SUBAGENT_CAPABLE, id)export const canRecur = (id: AgentId): boolean => includes(RECURRING_CAPABLE, id)export const canBranch = (id: AgentId): boolean => includes(BRANCH_CAPABLE, id)diff --git a/src/shared/agents/grok-session-mint.ts b/src/shared/agents/grok-session-mint.tsnew file mode 100644index 000000000..1037d7b97--- /dev/null+++ b/src/shared/agents/grok-session-mint.ts@@ -0,0 +1,32 @@+// Choosing a grok session id that grok will actually accept. PURE — no fs, so the renderer's+// synchronous node factory can call it. The directory read that feeds `taken` lives in+// `core/grok-session-mint.ts`, which is node-side.+//+// grok's `--session-id` is stricter than claude's in a way that turns OUR bug into a node that does+// not start (measured, 1.0.13): *"must be a valid UUID and must not already exist under the target+// session directory"*. Handing it an id already on disk is a LAUNCH ERROR, not a resume — grok+// exits, and the user sees a terminal that died instead of an agent.+/** How many candidates to try before giving up and minting nothing. A v4 collision is already+ * implausible; three consecutive ones mean the generator is broken, and in that case NO id is the+ * correct answer — the node falls back to learning its id from a hook, exactly as before minting+ * existed. Looping forever on a broken generator would hang node creation instead. */+const MAX_ATTEMPTS = 3++/**+ * Pure: pick an id no existing session already owns.+ *+ * `taken` is the set of session ids already on disk for this cwd; `gen` mints candidates. Returns+ * undefined when every attempt collided, which the caller must read as "launch without the flag",+ * never as "launch with a taken id".+ */+export function mintFreeGrokSessionId(+ taken: ReadonlySet<string>,+ gen: () => string+): string | undefined {+ for (let i = 0; i < MAX_ATTEMPTS; i++) {+ const candidate = gen()+ if (candidate && !taken.has(candidate)) return candidate+ }+ return undefined+}+diff --git a/src/shared/agents/launch.test.ts b/src/shared/agents/launch.test.tsindex a3a416cfe..02d956f99 100644--- a/src/shared/agents/launch.test.ts+++ b/src/shared/agents/launch.test.ts@@ -46,6 +46,37 @@ describe('assembleLaunchCommand — builtins (byte-identical to the historical p).command).toBe('claude')})+ it('grok puts the MINTED SESSION ID before the -- separator, prompt and all', () => {+ // The failure this guards is not a crash. grok's `--` is END OF OPTIONS: a flag placed after it+ // is swallowed as part of the PROMPT, so the node launches, looks healthy, mints a session id+ // nodeterm never learns, and the agent reads "--session-id <uuid>" as the first words of its+ // instructions. Nothing about the exit code says so — which is why this asserts on POSITION.+ const cmd = assembleLaunchCommand(+ {+ agentId: 'grok',+ initialPrompt: 'do the thing',+ sessionId: '01a06126-b981-73f1-8b68-4547e4d7da84',+ sessionIdFlagSupported: true+ },+ ENV+ ).command+ expect(cmd).toBe(+ "grok --session-id 01a06126-b981-73f1-8b68-4547e4d7da84 -- 'do the thing'"+ )+ expect(cmd.indexOf('--session-id')).toBeLessThan(cmd.indexOf(' -- '))+ })++ it('mints nothing for grok when the CLI did not advertise the flag', () => {+ // The probe answers for the binary in front of us. No advertisement ⇒ NAKED command, never a+ // blocked launch: an unrecognised flag makes grok exit, so guessing costs the whole session.+ expect(+ assembleLaunchCommand(+ { agentId: 'grok', sessionId: '01a06126-b981-73f1-8b68-4547e4d7da84' },+ ENV+ ).command+ ).toBe('grok')+ })+it('grok puts the permission flag BEFORE the -- separator', () => {expect(assembleLaunchCommand({ agentId: 'grok', initialPrompt: 'version', permissionMode: 'plan' }, ENV).commanddiff --git a/src/shared/agents/resume.test.ts b/src/shared/agents/resume.test.tsindex a581aae41..3a3cd539e 100644--- a/src/shared/agents/resume.test.ts+++ b/src/shared/agents/resume.test.ts@@ -7,15 +7,24 @@ describe('withSessionId', () => {})it('leaves a non-capable agent byte-identical', () => {- for (const id of ['codex', 'gemini', 'grok', 'opencode'] as const) {+ // grok is NOT in this list any more: it joined SESSION_ID_CAPABLE. An agent whose capability is+ // real must never stand as the example of one that lacks it — the example stops asserting+ // anything the day it changes, and this one was still passing for the wrong reason.+ for (const id of ['codex', 'gemini', 'opencode'] as const) {expect(withSessionId(id, id, 'abc-123')).toBe(id)}})+ it('spells grok\'s flag with a SPACE, not copilot\'s equals form', () => {+ // Two capable agents, two spellings. `withSessionId` branches on copilot alone, so grok takes+ // the space form claude uses — which is what `grok --help` documents.+ expect(withSessionId('grok', 'grok', 'abc-123')).toBe('grok --session-id abc-123')+ })+it('uses Copilot\'s equals-form session id independently of the Claude probe', () => {- expect(supportsSessionIdFlag('copilot', false)).toBe(true)- expect(supportsSessionIdFlag('claude', false)).toBe(false)- expect(supportsSessionIdFlag('claude', true)).toBe(true)+ expect(supportsSessionIdFlag('copilot', false, false)).toBe(true)+ expect(supportsSessionIdFlag('claude', false, false)).toBe(false)+ expect(supportsSessionIdFlag('claude', true, false)).toBe(true)expect(withSessionId('copilot', 'copilot', 'abc-123')).toBe('copilot --session-id=abc-123')diff --git a/src/shared/ipc.ts b/src/shared/ipc.tsindex 9c7f50b3f..f0e006f6a 100644--- a/src/shared/ipc.ts+++ b/src/shared/ipc.ts@@ -58,6 +58,8 @@ export const IPC = {codexAccountsRollbackSwitch: 'codex-accounts:rollback-switch',codexAccountsTransferThreadToSsh: 'codex-accounts:transfer-thread-to-ssh',claudeCliCaps: 'claude-cli:caps',+ grokCliCaps: 'grok-cli:caps',+ grokTakenSessionIds: 'grok-cli:taken-session-ids',/** Can a node on this machine get a managed Codex identity? See core/codex-identity-caps.ts. */codexIdentityCaps: 'codex-identity:caps',/** main/server → renderer: a Codex node's identity mode changed ('shared' | 'plain'). Thediff --git a/src/shared/types.ts b/src/shared/types.tsindex a4de0c10a..6502853fc 100644--- a/src/shared/types.ts+++ b/src/shared/types.ts@@ -2431,6 +2431,41 @@ export interface ClaudeCliCaps {sessionIdFlag: boolean}+export interface GrokCliCaps {+ /**+ * Whether the local grok CLI accepts `--session-id <uuid>`, so nodeterm can MINT a node's session+ * id instead of waiting to learn it from a hook.+ *+ * Probed from `grok --help` by `core/grok-cli.ts` — grok's OWN probe, never claude's. The two+ * CLIs are installed and upgraded independently, so claude's answer is not even correlated with+ * grok's, and an unknown flag makes grok exit rather than degrade.+ *+ * grok's grammar differs from claude's in three measured ways (1.0.13): the UUID must not already+ * exist under the target session directory, so minting one twice is a LAUNCH ERROR and never a+ * resume; `--session-id` combines with `--resume`/`--continue` only alongside `--fork-session`;+ * and `--resume` accepts a TITLE as well as an id, failing as ambiguous on duplicates.+ */+ sessionIdFlag: boolean+}++/** Unprobed grok ⇒ omit the flag ⇒ today's command line, byte-identical. */+export const UNKNOWN_GROK_CLI_CAPS: GrokCliCaps = { sessionIdFlag: false }++export interface GrokApi {+ /** Capabilities of the local grok CLI (memoized in the shell; safe to call repeatedly).+ * Never rejects — an unprobed CLI resolves to the fail-open caps. */+ cliCaps(): Promise<GrokCliCaps>+ /**+ * The session ids grok already has under this cwd.+ *+ * Needed because grok REFUSES a `--session-id` that already exists under the target session+ * directory — that is a launch error, not a resume, so a node handed a taken id never starts. An+ * array rather than a Set: a Set does not survive the IPC/WS-RPC boundary and would arrive empty,+ * which is the one wrong answer this call can give.+ */+ takenSessionIds(cwd: string): Promise<string[]>+}+/** The answer whenever the CLI version can't be determined: no `auto` flag → bare command, and no* fullscreen-tui write (an unknown settings key can warn on old CLIs — silence is safer). */export const UNKNOWN_CLAUDE_CLI_CAPS: ClaudeCliCaps = {@@ -2886,6 +2921,7 @@ export interface NodeTerminalApi {canvas: CanvasApicodex: CodexApiclaude: ClaudeApi+ grok: GrokApi/** Custom-agent launch/preview (env-var expansion + command assembly). */agent: AgentApichat: ChatApi