feat(grok): add Grok Build (xAI) as a seventh CLI run mode

SessionMode gains 'grok', a first-class backend alongside Claude Code,
shell, OpenCode, Codex, Gemini, Antigravity and Pi: its own PTY, tmux
session, charcoal tab identity ('gk' badge), welcome button, run-mode
entry, cron agentType, Docker and remote-SSH command defaults, and
clone-repo Brain option. Flag surface verified live against grok 1.0.5.

Grok mixes two existing shapes and the wiring follows from that:

- Codex-shaped on permissions: the bypass switch is GrokConfig.alwaysApprove
  (--always-approve, grok's bypassPermissions mode; config-level deny rules
  still apply on top). The Run button sends it true, like runAntigravity(),
  and clampExternalCliBypassForOwner() puts grok in the only-if-sent branch:
  a bare grok spawn is grok's own ask-mode default, which is already safe,
  so only a sent config needs the flag forced off. Cron needs nothing for
  the same reason.
- OpenCode-shaped on rendering: grok is a fullscreen alternate-screen TUI
  with mouse support, so it stays OUT of isAltScreenStripMode() and lands
  on the narrow tmux-attach strip and the 'buffer' local-echo fallthrough
  (unmeasured against an authenticated composer; documented fallback is the
  'off' branch).
- Pi-shaped on resolution: 'grok' has npm squatters (@vibe-kit/grok-cli
  also installs a grok bin), so grok-cli-resolver.ts version-probes every
  candidate (grok --version, killSignal SIGKILL, VITEST-gated) and
  GET /api/grok/status surfaces path AND version; GROK_VERSION_REGEX is
  shared with the dependency registry so doctor and run mode cannot drift.

Env allowlist gains GROK_* plus the XAI_* vendor namespace (XAI_API_KEY is
grok's documented headless auth var), the same narrow-vendor reasoning as
GOOGLE_* for gemini. Resume is id-regexed on purpose: grok's own --resume
also matches session titles, which are arbitrary user strings that must
never reach the bash -c spawn line.

Docker: grok is not on npm, so the agent image installs it in its own step
(xAI's installer has no --dir override; the binary is copied to
/usr/local/bin and root's ~/.grok dropped in the same layer), and
credentials are seeded per-file (auth.json, config.toml, pager.toml; the
dir also holds sessions/, memory/ and the ~160MB binary). Remote SSH routes
through the login-shell wrapper like the other agent CLIs.

Verified end to end on an isolated CODEMAN_INSTANCE with grok 1.0.5
installed: /api/grok/status resolves and reports the probed version,
quick-start spawns a pane whose command line ends in 'grok
--always-approve', the real TUI renders (OAuth device screen on an
unauthenticated box), and grokConfig round-trips through state.json.
Docs: docs/grok-integration.md (user guide) + docs/grok-integration-plan.md
(decisions, verification record, follow-ups).

Tests: test/grok-mode.test.ts, test/grok-cli-resolver.test.ts, plus
extended clamp/system-routes/render-index-html/run-mode-ui/mobile-overview/
local-echo-gating coverage. npm test (the CI gate) green: 5910 tests.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
This commit is contained in:
Codeman maintainer
2026-08-23 08:39:03 +02:00
parent 88bb98de43
commit 3f8c8e99d1
55 changed files with 1474 additions and 119 deletions
+141
View File
@@ -0,0 +1,141 @@
/**
* @fileoverview Tests for the Grok CLI resolver wrapper.
*
* Grok is the second resolver with a version probe: `grok` is a binary name
* with known squatters (the unrelated @vibe-kit/grok-cli npm package also
* installs a `grok` bin), so a resolved path is only accepted once
* `grok --version` prints a version-shaped string. The probe EXECUTES the
* candidate, which is exactly why it must never run under vitest: the
* hermeticity test below pins that gate with a real executable fixture, the
* same behavior-level pin test/pi-cli-resolver.test.ts carries.
*/
import { chmodSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs';
import { tmpdir } from 'node:os';
import { join } from 'node:path';
import { afterEach, describe, expect, it, vi } from 'vitest';
import { createGrokResolverForTest, GROK_VERSION_REGEX } from '../src/utils/grok-cli-resolver.js';
import {
cliResolveRetryDelayMs,
createProductionCliResolverHost,
type CliResolverHost,
} from '../src/utils/cli-executable-resolver.js';
const temporaryDirectories: string[] = [];
afterEach(() => {
for (const directory of temporaryDirectories.splice(0)) {
rmSync(directory, { recursive: true, force: true });
}
});
function createHost(
options: {
processPathResult?: string | null;
loginShellResults?: Array<string | null>;
existingPaths?: string[];
} = {}
): CliResolverHost {
const loginShellResults = [...(options.loginShellResults ?? [])];
const existingPaths = new Set(options.existingPaths ?? []);
return {
processPath: '/service/bin',
shellPath: '/bin/zsh',
shellArgs: ['-l'],
findOnProcessPath: () => options.processPathResult ?? null,
findInLoginShell: () => loginShellResults.shift() ?? null,
exists: (path) => existingPaths.has(path),
};
}
describe('Grok CLI resolver', () => {
it('accepts a candidate the version probe verifies and carries the version as metadata', () => {
const binaryPath = '/service/bin/grok';
const probe = vi.fn(() => '1.0.5');
const resolver = createGrokResolverForTest(
createHost({ processPathResult: binaryPath, existingPaths: [binaryPath] }),
probe
);
expect(resolver.resolve()).toMatchObject({
binaryPath,
directory: '/service/bin',
source: 'process-path',
metadata: '1.0.5',
});
expect(probe).toHaveBeenCalledWith(binaryPath);
});
it('rejects a candidate the probe refuses and falls through to a later one', () => {
// An unrelated `grok` on the service PATH (probe returns null) must not
// mask the real coding agent found by the login shell.
const impostor = '/service/bin/grok';
const genuine = '/login-shell/bin/grok';
const probe = vi.fn((binPath: string) => (binPath === genuine ? '1.0.5' : null));
const resolver = createGrokResolverForTest(
createHost({
processPathResult: impostor,
loginShellResults: [genuine],
existingPaths: [impostor, genuine],
}),
probe
);
expect(resolver.resolve()).toMatchObject({ binaryPath: genuine, source: 'login-shell', metadata: '1.0.5' });
});
it('negative-caches a miss and retries only after the backoff elapses', () => {
const binaryPath = '/late/bin/grok';
let now = 0;
const probe = vi.fn(() => '1.0.5');
const resolver = createGrokResolverForTest(
createHost({ loginShellResults: [null, binaryPath], existingPaths: [binaryPath] }),
probe,
() => now
);
expect(resolver.resolve()).toBeNull();
expect(resolver.resolve()).toBeNull(); // within the backoff: no re-run
expect(probe).not.toHaveBeenCalled();
now = cliResolveRetryDelayMs(1);
expect(resolver.resolve()?.metadata).toBe('1.0.5');
expect(resolver.resolve()?.binaryPath).toBe(binaryPath);
});
it('extracts the version from the real output shape (`grok 1.0.5 (5115b46bc9)`)', () => {
// GROK_VERSION_REGEX is shared with the dependency registry (doctor), so the
// shape it accepts is contract, not implementation detail.
expect(GROK_VERSION_REGEX.exec('grok 1.0.5 (5115b46bc9)')?.[1]).toBe('1.0.5');
expect(GROK_VERSION_REGEX.exec('1.0.5')?.[1]).toBe('1.0.5');
expect(GROK_VERSION_REGEX.exec('v1.0.5')).toBeNull();
expect(GROK_VERSION_REGEX.exec('not a version')).toBeNull();
});
it('never executes a grok candidate under vitest (the ambient probe is VITEST-gated)', () => {
// A REAL executable fixture that prints a valid version. If the guard in
// probeGrokVersion is ever removed, the probe runs this script, the
// resolution SUCCEEDS, and this test fails, pinning hermeticity by
// behavior rather than by source text.
const root = mkdtempSync(join(tmpdir(), 'codeman-grok-vitest-gate-'));
temporaryDirectories.push(root);
const binaryPath = join(root, 'grok');
writeFileSync(binaryPath, '#!/bin/sh\necho "grok 9.9.9 (deadbeef)"\n');
chmodSync(binaryPath, 0o755);
const hostOptions = {
processPath: root,
shellPath: '/bin/bash',
shellArgs: ['-i', '-l'] as string[],
runCommand: () => '',
isExecutableFile: (path: string) => path === binaryPath,
};
// Default (ambient) probe: the candidate is found but never executed, so
// the VITEST gate reports it unusable and resolution misses.
const gated = createGrokResolverForTest(createProductionCliResolverHost(hostOptions));
expect(gated.resolve()).toBeNull();
// Control: identical setup with an injected probe resolves, proving the
// null above comes from the gate, not from the fixture or the host.
const control = createGrokResolverForTest(createProductionCliResolverHost(hostOptions), () => '9.9.9');
expect(control.resolve()).toMatchObject({ binaryPath, metadata: '9.9.9' });
});
});
+159
View File
@@ -0,0 +1,159 @@
import { describe, expect, it } from 'vitest';
import { CreateSessionSchema, QuickStartSchema } from '../src/web/schemas.js';
import { buildSpawnCommand } from '../src/tmux-manager.js';
import { defaultDockerCommandForMode } from '../src/docker-hosts.js';
import { defaultRemoteCommandForMode } from '../src/remote-hosts.js';
import { isExternalCliMode, isAltScreenStripMode } from '../src/session.js';
describe('Grok mode schemas', () => {
it('accepts Grok session creation config', () => {
const parsed = CreateSessionSchema.parse({
workingDir: '/tmp',
mode: 'grok',
grokConfig: {
model: 'grok-4.5',
alwaysApprove: true,
},
});
expect(parsed.mode).toBe('grok');
expect(parsed.grokConfig).toEqual({
model: 'grok-4.5',
alwaysApprove: true,
});
});
it('accepts Grok quick-start config', () => {
const parsed = QuickStartSchema.parse({
caseName: 'grok-case',
mode: 'grok',
grokConfig: { resumeSessionId: '0198f2b4-aa10-7def-8123-4c5d6e7f8a9b', continueSession: true },
});
expect(parsed.mode).toBe('grok');
expect(parsed.grokConfig?.resumeSessionId).toBe('0198f2b4-aa10-7def-8123-4c5d6e7f8a9b');
});
it('rejects unsafe Grok model strings', () => {
expect(() =>
CreateSessionSchema.parse({
workingDir: '/tmp',
mode: 'grok',
grokConfig: { model: 'grok; rm -rf /' },
})
).toThrow();
});
it('rejects unsafe Grok resumeSessionId values (ids only, never titles or paths)', () => {
// grok's own --resume also matches session TITLES, which are arbitrary user
// strings; the id regex is what keeps those (and paths) off the spawn line.
expect(() =>
CreateSessionSchema.parse({
workingDir: '/tmp',
mode: 'grok',
grokConfig: { resumeSessionId: '../../etc/passwd' },
})
).toThrow();
expect(() =>
CreateSessionSchema.parse({
workingDir: '/tmp',
mode: 'grok',
grokConfig: { resumeSessionId: 'my session title' },
})
).toThrow();
});
it('allows GROK_* and XAI_* env overrides but NOT bare provider keys', () => {
const parsed = CreateSessionSchema.parse({
workingDir: '/tmp',
mode: 'grok',
envOverrides: { GROK_HOME: '/tmp/grok-home', XAI_API_KEY: 'xai-test' },
});
expect(parsed.envOverrides).toEqual({ GROK_HOME: '/tmp/grok-home', XAI_API_KEY: 'xai-test' });
// XAI_* is xAI's own namespace (grok's documented auth var), the same
// narrow-vendor-namespace reasoning that admitted GOOGLE_* for gemini.
// Foreign provider keys stay out.
expect(() =>
CreateSessionSchema.parse({
workingDir: '/tmp',
mode: 'grok',
envOverrides: { ANTHROPIC_API_KEY: 'sk-test' },
})
).toThrow();
});
});
describe('Grok spawn command', () => {
it('builds a bare grok command when no config is sent (ask-mode default)', () => {
const cmd = buildSpawnCommand({ mode: 'grok', sessionId: 'abc12345' });
expect(cmd).toBe('grok');
});
it('maps alwaysApprove and model to flags', () => {
const cmd = buildSpawnCommand({
mode: 'grok',
sessionId: 'abc12345',
grokConfig: { alwaysApprove: true, model: 'grok-4.5' },
});
expect(cmd).toBe('grok --always-approve --model grok-4.5');
});
it('omits --always-approve when false or absent (grok defaults safe on its own)', () => {
expect(buildSpawnCommand({ mode: 'grok', sessionId: 'a', grokConfig: { alwaysApprove: false } })).toBe('grok');
expect(buildSpawnCommand({ mode: 'grok', sessionId: 'a', grokConfig: {} })).toBe('grok');
});
it('passes --resume for resume and skips --continue when both are present', () => {
expect(buildSpawnCommand({ mode: 'grok', sessionId: 'a', grokConfig: { resumeSessionId: '0198f2b4' } })).toBe(
'grok --resume 0198f2b4'
);
expect(buildSpawnCommand({ mode: 'grok', sessionId: 'a', grokConfig: { continueSession: true } })).toBe(
'grok --continue'
);
// The two conflict upstream: a valid explicit session id wins.
expect(
buildSpawnCommand({
mode: 'grok',
sessionId: 'a',
grokConfig: { continueSession: true, resumeSessionId: '0198f2b4' },
})
).toBe('grok --resume 0198f2b4');
});
it('drops unsafe values rather than escaping them (the result lands in `bash -c "..."`)', () => {
expect(buildSpawnCommand({ mode: 'grok', sessionId: 'a', grokConfig: { model: 'a`b' } })).toBe('grok');
expect(buildSpawnCommand({ mode: 'grok', sessionId: 'a', grokConfig: { resumeSessionId: 'x; rm -rf /' } })).toBe(
'grok'
);
});
it('never puts a secret-shaped flag on the spawn line (XAI_API_KEY flows via tmux setenv)', () => {
const cmd = buildSpawnCommand({
mode: 'grok',
sessionId: 'a',
grokConfig: { model: 'grok-4.5', alwaysApprove: true },
});
expect(cmd).not.toContain('key');
expect(cmd).not.toContain('token');
});
});
describe('Grok mode gates', () => {
it('is an external CLI mode (readiness/ralph/respawn gating)', () => {
expect(isExternalCliMode('grok')).toBe(true);
});
it('is NOT an alt-screen strip mode (fullscreen alt-screen TUI with mouse support)', () => {
expect(isAltScreenStripMode('grok')).toBe(false);
});
it('has docker/remote default commands', () => {
expect(defaultDockerCommandForMode('grok')).toBe('exec grok');
// Routed through an interactive login shell so ~/.grok/bin resolves,
// the same fix as the other remote agent CLIs (see defaultRemoteCommandForMode).
expect(defaultRemoteCommandForMode('grok')).toBe('exec "${SHELL:-/bin/sh}" -i -l -c \'grok\'');
});
});
+2 -2
View File
@@ -190,7 +190,7 @@ describe('_updateLocalEchoState mode gating', () => {
expect(app._localEchoEnabled).toBe(false);
});
it.each(['claude', 'gemini', 'opencode', 'pi'])('keeps the overlay enabled for %s sessions', (mode) => {
it.each(['claude', 'gemini', 'opencode', 'pi', 'grok'])('keeps the overlay enabled for %s sessions', (mode) => {
const overlay = makeOverlay();
const app = makeApp(mode, overlay);
app._updateLocalEchoState();
@@ -373,7 +373,7 @@ describe('_updateLocalEchoState echo policy', () => {
expect(app._predictiveEcho.clearPredictions).toHaveBeenCalled();
});
it.each(['claude', 'gemini', 'opencode', 'pi'])(
it.each(['claude', 'gemini', 'opencode', 'pi', 'grok'])(
"%s -> policy 'buffer' + overlay enabled (existing behavior)",
(mode) => {
const overlay = makeOverlay();
+1 -1
View File
@@ -424,7 +424,7 @@ describe('mobile overview run picker (CLI availability gating)', () => {
isCliAvailable: () => true,
});
const menu = app._buildMobileOverviewRunMenu();
expect(modeButtons(menu)).toEqual(['claude', 'opencode', 'codex', 'gemini', 'antigravity', 'pi', 'shell']);
expect(modeButtons(menu)).toEqual(['claude', 'opencode', 'codex', 'gemini', 'antigravity', 'pi', 'grok', 'shell']);
});
it('gates every mode the picker actually offers', () => {
+9
View File
@@ -18,6 +18,7 @@ import { isCodexAvailable } from '../src/utils/codex-cli-resolver.js';
import { isGeminiAvailable } from '../src/utils/gemini-cli-resolver.js';
import { isAntigravityAvailable } from '../src/utils/antigravity-cli-resolver.js';
import { isPiAvailable } from '../src/utils/pi-cli-resolver.js';
import { isGrokAvailable } from '../src/utils/grok-cli-resolver.js';
import { isCloudflaredAvailable } from '../src/utils/cloudflared-resolver.js';
import { isGitAvailable } from '../src/git-clone.js';
@@ -49,6 +50,11 @@ vi.mock('../src/utils/pi-cli-resolver.js', () => ({
resolvePiDir: vi.fn(() => null),
getPiCliVersion: vi.fn(() => null),
}));
vi.mock('../src/utils/grok-cli-resolver.js', () => ({
isGrokAvailable: vi.fn(() => false),
resolveGrokDir: vi.fn(() => null),
getGrokCliVersion: vi.fn(() => null),
}));
vi.mock('../src/utils/cloudflared-resolver.js', () => ({
isCloudflaredAvailable: vi.fn(() => false),
resolveCloudflaredPath: vi.fn(() => null),
@@ -138,6 +144,7 @@ describe('WebServer.renderIndexHtml', () => {
vi.mocked(isGeminiAvailable).mockReturnValue(false);
vi.mocked(isAntigravityAvailable).mockReturnValue(false);
vi.mocked(isPiAvailable).mockReturnValue(true);
vi.mocked(isGrokAvailable).mockReturnValue(false);
vi.mocked(isCloudflaredAvailable).mockReturnValue(true);
vi.mocked(isGitAvailable).mockReturnValue(true);
const { server } = makeServer({});
@@ -152,6 +159,7 @@ describe('WebServer.renderIndexHtml', () => {
gemini: false,
antigravity: false,
pi: true,
grok: false,
cloudflared: true,
git: true,
});
@@ -167,6 +175,7 @@ describe('WebServer.renderIndexHtml', () => {
isGeminiAvailable,
isAntigravityAvailable,
isPiAvailable,
isGrokAvailable,
isCloudflaredAvailable,
isGitAvailable,
]) {
+48 -21
View File
@@ -5,7 +5,7 @@
* `POST /api/quick-start` and, until pi was added, had no tests at all.
*
* The helper has two shapes and the difference is the whole point:
* - only-if-sent (codex, antigravity): an ABSENT config already spawns safe, so
* - only-if-sent (codex, antigravity, grok): an ABSENT config already spawns safe, so
* only a sent config needs its flag forced off.
* - MATERIALIZE (gemini, pi): the absent-config default is itself unsafe for a
* non-granted owner (gemini's builder defaults to `yolo`; pi's default is an
@@ -25,20 +25,23 @@ describe('clampExternalCliBypassForOwner — single-user mode', () => {
{ dangerouslyBypassApprovals: true },
{ approvalMode: 'yolo' },
{ dangerouslySkipPermissions: true },
{ approveProjectTrust: true }
{ approveProjectTrust: true },
{ alwaysApprove: true }
);
expect(out.codexConfig).toEqual({ dangerouslyBypassApprovals: true });
expect(out.geminiConfig).toEqual({ approvalMode: 'yolo' });
expect(out.antigravityConfig).toEqual({ dangerouslySkipPermissions: true });
expect(out.piConfig).toEqual({ approveProjectTrust: true });
expect(out.grokConfig).toEqual({ alwaysApprove: true });
});
it('leaves absent configs absent', async () => {
const out = await _clampExternalCliBypassForOwner(undefined, undefined, undefined, undefined, undefined);
const out = await _clampExternalCliBypassForOwner(undefined, undefined, undefined, undefined, undefined, undefined);
expect(out.codexConfig).toBeUndefined();
expect(out.geminiConfig).toBeUndefined();
expect(out.antigravityConfig).toBeUndefined();
expect(out.piConfig).toBeUndefined();
expect(out.grokConfig).toBeUndefined();
});
});
@@ -64,57 +67,75 @@ describe('clampExternalCliBypassForOwner — multi-user mode', () => {
{ dangerouslyBypassApprovals: true },
undefined,
{ dangerouslySkipPermissions: true },
{ approveProjectTrust: true }
{ approveProjectTrust: true },
{ alwaysApprove: true }
);
expect(out.codexConfig).toEqual({ dangerouslyBypassApprovals: true });
expect(out.geminiConfig).toBeUndefined();
expect(out.antigravityConfig).toEqual({ dangerouslySkipPermissions: true });
expect(out.piConfig).toEqual({ approveProjectTrust: true });
expect(out.grokConfig).toEqual({ alwaysApprove: true });
});
it('passes through for a user holding the bypass grant', async () => {
const out = await _clampExternalCliBypassForOwner('trusted', undefined, undefined, undefined, {
approveProjectTrust: true,
});
const out = await _clampExternalCliBypassForOwner(
'trusted',
undefined,
undefined,
undefined,
{ approveProjectTrust: true },
{ alwaysApprove: true }
);
expect(out.piConfig).toEqual({ approveProjectTrust: true });
expect(out.grokConfig).toEqual({ alwaysApprove: true });
});
it('forces codex/antigravity bypass off for a non-granted owner (only-if-sent branch)', async () => {
it('forces codex/antigravity/grok bypass off for a non-granted owner (only-if-sent branch)', async () => {
const out = await _clampExternalCliBypassForOwner(
'peon',
{ dangerouslyBypassApprovals: true, model: 'gpt-5' },
undefined,
{ dangerouslySkipPermissions: true, model: 'gemini-3-pro' },
undefined
undefined,
{ alwaysApprove: true, model: 'grok-4.5' }
);
expect(out.codexConfig).toEqual({ dangerouslyBypassApprovals: false, model: 'gpt-5' });
expect(out.antigravityConfig).toEqual({ dangerouslySkipPermissions: false, model: 'gemini-3-pro' });
expect(out.grokConfig).toEqual({ alwaysApprove: false, model: 'grok-4.5' });
});
it('leaves codex/antigravity absent when nothing was sent (they already spawn safe)', async () => {
const out = await _clampExternalCliBypassForOwner('peon', undefined, undefined, undefined, undefined);
it('leaves codex/antigravity/grok absent when nothing was sent (they already spawn safe)', async () => {
const out = await _clampExternalCliBypassForOwner('peon', undefined, undefined, undefined, undefined, undefined);
expect(out.codexConfig).toBeUndefined();
expect(out.antigravityConfig).toBeUndefined();
expect(out.grokConfig).toBeUndefined();
});
it('MATERIALIZES gemini to auto_edit even when no config was sent', async () => {
const out = await _clampExternalCliBypassForOwner('peon', undefined, undefined, undefined, undefined);
const out = await _clampExternalCliBypassForOwner('peon', undefined, undefined, undefined, undefined, undefined);
expect(out.geminiConfig).toEqual({ approvalMode: 'auto_edit' });
});
it('MATERIALIZES pi to --no-approve even when no config was sent', async () => {
// The load-bearing case: omitting --approve is NOT a clamp for pi, because
// pi's own default is to ASK, and the session user can answer that prompt.
const out = await _clampExternalCliBypassForOwner('peon', undefined, undefined, undefined, undefined);
const out = await _clampExternalCliBypassForOwner('peon', undefined, undefined, undefined, undefined, undefined);
expect(out.piConfig).toEqual({ approveProjectTrust: false });
});
it('forces a sent pi approveProjectTrust:true down to false, keeping other fields', async () => {
const out = await _clampExternalCliBypassForOwner('peon', undefined, undefined, undefined, {
approveProjectTrust: true,
model: 'sonnet:high',
provider: 'anthropic',
});
const out = await _clampExternalCliBypassForOwner(
'peon',
undefined,
undefined,
undefined,
{
approveProjectTrust: true,
model: 'sonnet:high',
provider: 'anthropic',
},
undefined
);
expect(out.piConfig).toEqual({
approveProjectTrust: false,
model: 'sonnet:high',
@@ -123,10 +144,16 @@ describe('clampExternalCliBypassForOwner — multi-user mode', () => {
});
it('fails closed for an unknown/deleted owner', async () => {
const out = await _clampExternalCliBypassForOwner('ghost', undefined, undefined, undefined, {
approveProjectTrust: true,
});
const out = await _clampExternalCliBypassForOwner(
'ghost',
undefined,
undefined,
undefined,
{ approveProjectTrust: true },
{ alwaysApprove: true }
);
expect(out.piConfig).toEqual({ approveProjectTrust: false });
expect(out.geminiConfig).toEqual({ approvalMode: 'auto_edit' });
expect(out.grokConfig).toEqual({ alwaysApprove: false });
});
});
+42
View File
@@ -92,6 +92,12 @@ vi.mock('../../src/utils/pi-cli-resolver.js', () => ({
getPiCliVersion: vi.fn(() => null),
}));
vi.mock('../../src/utils/grok-cli-resolver.js', () => ({
isGrokAvailable: vi.fn(() => false),
resolveGrokDir: vi.fn(() => null),
getGrokCliVersion: vi.fn(() => null),
}));
import fs from 'node:fs/promises';
import { existsSync, readdirSync } from 'node:fs';
import { subagentWatcher } from '../../src/subagent-watcher.js';
@@ -100,6 +106,7 @@ import { isOpenCodeAvailable, resolveOpenCodeDir } from '../../src/utils/opencod
import { isGeminiAvailable, resolveGeminiDir } from '../../src/utils/gemini-cli-resolver.js';
import { isAntigravityAvailable, resolveAntigravityDir } from '../../src/utils/antigravity-cli-resolver.js';
import { isPiAvailable, resolvePiDir, getPiCliVersion } from '../../src/utils/pi-cli-resolver.js';
import { isGrokAvailable, resolveGrokDir, getGrokCliVersion } from '../../src/utils/grok-cli-resolver.js';
const mockedReadFile = vi.mocked(fs.readFile);
const mockedWriteFile = vi.mocked(fs.writeFile);
@@ -116,6 +123,9 @@ const mockedResolveAntigravityDir = vi.mocked(resolveAntigravityDir);
const mockedIsPiAvailable = vi.mocked(isPiAvailable);
const mockedResolvePiDir = vi.mocked(resolvePiDir);
const mockedGetPiCliVersion = vi.mocked(getPiCliVersion);
const mockedIsGrokAvailable = vi.mocked(isGrokAvailable);
const mockedResolveGrokDir = vi.mocked(resolveGrokDir);
const mockedGetGrokCliVersion = vi.mocked(getGrokCliVersion);
describe('system-routes', () => {
let harness: RouteTestHarness;
@@ -881,6 +891,38 @@ describe('system-routes', () => {
});
});
// ========== GET /api/grok/status ==========
describe('GET /api/grok/status', () => {
it('returns unavailable when grok is not installed', async () => {
mockedIsGrokAvailable.mockReturnValue(false);
mockedResolveGrokDir.mockReturnValue(null);
mockedGetGrokCliVersion.mockReturnValue(null);
const res = await harness.app.inject({ method: 'GET', url: '/api/grok/status' });
expect(res.statusCode).toBe(200);
const body = JSON.parse(res.body);
expect(body.available).toBe(false);
expect(body.path).toBeNull();
expect(body.version).toBeNull();
});
it('returns available with path AND version when grok is installed', async () => {
// `version` matters for the same reason as pi: `grok` has known squatters,
// so this endpoint is where a misresolution shows up.
mockedIsGrokAvailable.mockReturnValue(true);
mockedResolveGrokDir.mockReturnValue('/home/user/.grok/bin');
mockedGetGrokCliVersion.mockReturnValue('1.0.5');
const res = await harness.app.inject({ method: 'GET', url: '/api/grok/status' });
expect(res.statusCode).toBe(200);
const body = JSON.parse(res.body);
expect(body.available).toBe(true);
expect(body.path).toBe('/home/user/.grok/bin');
expect(body.version).toBe('1.0.5');
});
});
// ========== GET /api/execution/model-config ==========
describe('GET /api/execution/model-config', () => {
+106 -1
View File
@@ -176,6 +176,7 @@ describe('Run launch synchronization', () => {
'runGemini',
'runAntigravity',
'runPi',
'runGrok',
])
);
@@ -365,12 +366,13 @@ describe('Codex quick start settings', () => {
'welcomeAntigravityBtn',
'welcomeGeminiBtn',
'welcomePiBtn',
'welcomeGrokBtn',
'welcomeTunnelBtn',
]) {
welcomeBtns[id] = { style: { display: 'PRISTINE' } };
}
const modeBtns: Record<string, { style: { display: string } }> = {};
for (const mode of ['claude', 'opencode', 'codex', 'gemini', 'antigravity', 'pi', 'shell']) {
for (const mode of ['claude', 'opencode', 'codex', 'gemini', 'antigravity', 'pi', 'grok', 'shell']) {
modeBtns[mode] = { style: { display: 'PRISTINE' } };
}
const menu = {
@@ -402,6 +404,7 @@ describe('Codex quick start settings', () => {
gemini: false,
antigravity: false,
pi: false,
grok: false,
cloudflared: false,
};
@@ -425,6 +428,13 @@ describe('Codex quick start settings', () => {
const withPi = loadUi({ ...ALL_OFF, pi: true });
withPi.app.applyWelcomeCliVisibility();
expect(withPi.welcomeBtns.welcomePiBtn.style.display).toBe('flex');
// Grok is gated on `grok` like the rest; the resolver additionally
// version-probes the binary, so a stray `grok` on PATH reports unavailable.
const withGrok = loadUi({ ...ALL_OFF, grok: true });
withGrok.app.applyWelcomeCliVisibility();
expect(withGrok.welcomeBtns.welcomeGrokBtn.style.display).toBe('flex');
expect(withGrok.welcomeBtns.welcomeClaudeBtn.style.display).toBe('none');
expect(withPi.welcomeBtns.welcomeClaudeBtn.style.display).toBe('none');
// Antigravity is a first-class welcome action, gated on `agy` like the rest.
@@ -457,6 +467,7 @@ describe('Codex quick start settings', () => {
);
expect(offered).toContain('antigravity');
expect(offered).toContain('pi');
expect(offered).toContain('grok');
const src = readFileSync(resolve(import.meta.dirname, '../src/web/public/session-ui.js'), 'utf8');
// Anchor on the DEFINITION, not the earlier call site in toggleRunModeMenu.
const fn = src.slice(src.indexOf('_refreshRunModeAvailability(menu) {'));
@@ -993,3 +1004,97 @@ describe('Pi quick start', () => {
expect(errors[0]).toContain('@earendil-works/pi-coding-agent');
});
});
describe('Grok quick start', () => {
// Same envelope-unwrap regression guard as the blocks above, for runGrok(),
// plus the rule that makes grok the OPPOSITE of pi: the Run button DOES send
// `grokConfig: { alwaysApprove: true }` (grok's bypassPermissions mode), the
// same product decision as runAntigravity's dangerouslySkipPermissions and
// claude's --dangerously-skip-permissions. The multi-user clamp strips it
// server-side for non-granted owners.
it('drives runGrok() through the {success,data} envelope and sends alwaysApprove', async () => {
const elements: Record<string, any> = {
quickStartCase: { value: 'grok-case' },
};
const requests: Array<{ url: string; body?: any }> = [];
const CodemanApp = function CodemanApp(this: any) {};
const context = vm.createContext({
CodemanApp,
localStorage: { getItem: () => null, setItem: () => {} },
document: { getElementById: (id: string) => elements[id] ?? null },
fetch: async (url: string, init?: { body?: string }) => {
requests.push({ url, body: init?.body ? JSON.parse(init.body) : undefined });
if (url === '/api/grok/status')
return {
json: async () => ({
success: true,
data: { available: true, path: '/home/user/.grok/bin', version: '1.0.5' },
}),
};
if (url === '/api/quick-start')
return { json: async () => ({ success: true, data: { sessionId: 'sess-gk' } }) };
if (url === '/api/sessions/sess-gk')
return { json: async () => ({ success: true, data: { id: 'sess-gk', name: 'w1-grok-case' } }) };
throw new Error(`unexpected fetch: ${url}`);
},
console,
});
const sessionUi = readFileSync(resolve(import.meta.dirname, '../src/web/public/session-ui.js'), 'utf8');
vm.runInContext(sessionUi, context, { filename: 'session-ui.js' });
const app = new (CodemanApp as any)();
app.terminal = { clear: () => {}, writeln: () => {}, focus: () => {} };
app.loadAppSettingsFromStorage = () => ({});
app.getCaseSettings = () => ({});
app.buildEnvOverrides = () => ({});
app.sessions = new Map();
app._onSessionCreated = (session: any) => app.sessions.set(session.id, session);
app._renderSessionTabsImmediate = vi.fn();
const selected: string[] = [];
app.selectSession = async (id: string) => {
selected.push(id);
};
await app.runGrok();
const body = requests.find((req) => req.url === '/api/quick-start')?.body;
expect(body).toMatchObject({
caseName: 'grok-case',
mode: 'grok',
grokConfig: { alwaysApprove: true },
});
expect(selected).toEqual(['sess-gk']);
});
it('reports the install hint when the CLI is missing and starts nothing', async () => {
const elements: Record<string, any> = { quickStartCase: { value: 'grok-case' } };
const requests: string[] = [];
const CodemanApp = function CodemanApp(this: any) {};
const context = vm.createContext({
CodemanApp,
localStorage: { getItem: () => null, setItem: () => {} },
document: { getElementById: (id: string) => elements[id] ?? null },
fetch: async (url: string) => {
requests.push(url);
if (url === '/api/grok/status')
return { json: async () => ({ success: true, data: { available: false, path: null, version: null } }) };
throw new Error(`unexpected fetch: ${url}`);
},
console,
});
const sessionUi = readFileSync(resolve(import.meta.dirname, '../src/web/public/session-ui.js'), 'utf8');
vm.runInContext(sessionUi, context, { filename: 'session-ui.js' });
const app = new (CodemanApp as any)();
app.terminal = { clear: () => {}, writeln: () => {}, focus: () => {} };
const errors: string[] = [];
app._reportSessionLaunchError = (_owns: boolean, msg: string) => errors.push(msg);
await app.runGrok();
expect(requests).toEqual(['/api/grok/status']);
expect(errors[0]).toContain('https://x.ai/cli/install.sh');
});
});