Skip to content

Self-hosted, Self-Improving, Federated Everything App — dev management, agent orchestration, persistent mind, digital twin, second brain, and creative pipeline from a single dashboard over Tailscale to port the user into the OS

feat([issue-3606]): detect missing CLI-reviewer binaries server-side

[._.]/ Adam Eivyc7a46a6a437f
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.md
index c44b276a47..8598d31c97 100644
--- a/.changelog/NEXT.md
+++ b/.changelog/NEXT.md
@@ -1,5 +1,8 @@
# Unreleased
+## Code Review Defaults
+- **[issue-3606] A Review Loop reviewer whose CLI isn't installed is now flagged up front.** Previously the only way to find out a configured reviewer (Claude, Antigravity, Codex, or Grok) couldn't actually run was to wait for the review loop itself to discover its command was missing — after PortOS had already opened the PR and spent an agent run. The Code Review Defaults panel, task form, schedule config, and `/do:next` run drawer now show a "not installed" badge next to any reviewer whose CLI binary isn't found on this machine. It's informational only — the reviewer stays selectable, since a federated peer machine (or a later install) may still be able to run it.
+
## Added
- **The claim-issue author gate has a "Me + collaborators" setting.** Until now the only way to let an agent work on a teammate's issue was "Any author", which also opens the queue to drive-by issues from strangers — so a repo with any real collaborators had to choose between ignoring their issues and claiming everyone's. The new option trusts you plus every account the forge already grants access to (GitHub collaborators, GitLab project members including group-inherited ones), which is the same set that could push the code anyway. It sits between "Filed by me only" (still the default) and "Any author" in the CoS → Schedule author-filter dropdown, in the per-app override, and in the `/do:next` run drawer, and applies to `claim-issue` and `claim-work` alike. Neither CLI's `--author` flag accepts more than one account, so the gate is applied to the issue listing rather than pushed into the query — both the work detector and the agent prompt resolve the trusted set first, then filter. If that lookup fails (a token without push access can't read the collaborator list), PortOS reports it and retries rather than quietly narrowing back to your own issues or widening to everybody — and because that failure repeats identically on every retry, both the run drawer and the "Run now" toast name the filter and the way out instead of the generic "try again shortly".
diff --git a/client/src/components/apps/SlashDoRunDrawer.jsx b/client/src/components/apps/SlashDoRunDrawer.jsx
index c04b9de978..58cfd90565 100644
--- a/client/src/components/apps/SlashDoRunDrawer.jsx
+++ b/client/src/components/apps/SlashDoRunDrawer.jsx
@@ -153,6 +153,7 @@ function SlashDoRunDrawerBody({ open, command, label, appId, appName, onClose, o
reviewerMaxRounds={reviewValue.reviewerMaxRounds}
reviewerModels={reviewValue.reviewerModels}
modelOptions={reviewerModelOptions}
+ installed={codeReviewDefaults.installed}
// The claim flows substitute a reviewer CSV into their prompt and have
// no slashdo flag string, so stop-mode / reviewer-applies can't be honored.
showRunFlags={false}
diff --git a/client/src/components/cos/ReviewerPicker.jsx b/client/src/components/cos/ReviewerPicker.jsx
index 3de5d7062b..1975857504 100644
--- a/client/src/components/cos/ReviewerPicker.jsx
+++ b/client/src/components/cos/ReviewerPicker.jsx
@@ -1,5 +1,6 @@
import { useId, useState } from 'react';
import { Plus, X, ChevronUp, ChevronDown } from 'lucide-react';
+import Pill from '../ui/Pill';
import {
REVIEWER_OPTIONS,
REVIEW_STOP_MODES,
@@ -55,6 +56,15 @@ const normalizeReviewerValue = (value) => value === 'gemini' ? 'antigravity' : v
* flows substitute a reviewer CSV into their prompt and have no slashdo flag
* string, so rendering those two controls there would be a knob wired to
* nothing. The reviewer list itself still applies.
+ *
+ * `installed` is a per-reviewer-slug install probe from the Code Review
+ * Defaults endpoint (`GET /api/code-review/defaults`'s `installed` field,
+ * #3606) — `{ claude: true, antigravity: false, ... }`. Only an explicit
+ * `false` renders a "not installed" badge; `undefined` (not a CLI reviewer,
+ * or the caller didn't fetch it) renders nothing. Warn-only: a reviewer stays
+ * selectable and selected even when flagged not-installed, since the CLI
+ * check is local-machine-only and a federated peer (or a later install) may
+ * satisfy it.
*/
export default function ReviewerPicker({
reviewers = [],
@@ -63,6 +73,7 @@ export default function ReviewerPicker({
reviewerMaxRounds = {},
reviewerModels = {},
modelOptions = null,
+ installed = null,
stopMode = DEFAULT_REVIEW_STOP_MODE,
reviewerApplies = false,
onChange,
@@ -116,6 +127,20 @@ export default function ReviewerPicker({
// DELETES the key rather than persisting `''` (a `--model ` with no id).
const modelsMap = asMap(reviewerModels);
const models = keyedLookup(modelsMap);
+ // Only an explicit `false` counts — `undefined` covers both "not a CLI
+ // reviewer" (copilot/lmstudio/ollama/@username) and "caller didn't fetch
+ // `installed`", neither of which should render a warning badge.
+ const notInstalled = (token) => installed?.[token] === false;
+ const renderInstalledBadge = (token) => notInstalled(token) && (
+ <Pill
+ tone="warning"
+ size="xs"
+ className="shrink-0"
+ title={`${labelFor(token)}'s CLI binary wasn't found on this machine. It still runs (federation-wide config), but the review loop here will report it unsatisfied until it's installed.`}
+ >
+ not installed
+ </Pill>
+ );
const emit = (next) => onChange?.({
reviewers: selected,
@@ -397,7 +422,10 @@ export default function ReviewerPicker({
<ChevronDown size={12} />
</button>
</div>
- <span className="text-xs text-gray-300 col-span-2 sm:col-span-1 truncate">{labelFor(value)}</span>
+ <span className="flex items-center gap-1 min-w-0 col-span-2 sm:col-span-1">
+ <span className="text-xs text-gray-300 truncate">{labelFor(value)}</span>
+ {renderInstalledBadge(value)}
+ </span>
<span className={CELL_LABEL_CLASS}>Model</span>
<div className="min-w-0">{renderModelCell(value)}</div>
<span className={CELL_LABEL_CLASS}>Optional</span>
@@ -449,6 +477,7 @@ export default function ReviewerPicker({
>
<Plus size={11} />
{opt.label}
+ {renderInstalledBadge(opt.value)}
</button>
))}
</div>
diff --git a/client/src/components/cos/ReviewerPicker.test.jsx b/client/src/components/cos/ReviewerPicker.test.jsx
index 4c9c21e570..bb2daa0f42 100644
--- a/client/src/components/cos/ReviewerPicker.test.jsx
+++ b/client/src/components/cos/ReviewerPicker.test.jsx
@@ -14,6 +14,31 @@ describe('ReviewerPicker', () => {
expect(screen.getByRole('button', { name: /Claude/ })).toBeInTheDocument();
});
+ describe('installed badge (#3606)', () => {
+ it('flags a selected reviewer whose CLI probe came back false', () => {
+ render(<ReviewerPicker reviewers={['antigravity']} installed={{ antigravity: false }} onChange={() => {}} />);
+ expect(screen.getByText('not installed')).toBeInTheDocument();
+ });
+
+ it('does not flag a selected reviewer with no probe entry (not a CLI reviewer, or not fetched)', () => {
+ render(<ReviewerPicker reviewers={['copilot']} installed={{ antigravity: false }} onChange={() => {}} />);
+ // copilot has no `installed` entry (it's not a CLI reviewer) — its row
+ // stays unbadged even though the map has an entry for a different reviewer.
+ expect(screen.getByText('Copilot').closest('div')).not.toHaveTextContent('not installed');
+ });
+
+ it('does not flag anything when installed is absent', () => {
+ render(<ReviewerPicker reviewers={['codex', 'antigravity']} onChange={() => {}} />);
+ expect(screen.queryByText('not installed')).not.toBeInTheDocument();
+ });
+
+ it('flags an unselected reviewer in the Add row too', () => {
+ render(<ReviewerPicker reviewers={['copilot']} installed={{ antigravity: false }} onChange={() => {}} />);
+ const addButton = screen.getByRole('button', { name: /Antigravity/ });
+ expect(addButton).toHaveTextContent('not installed');
+ });
+ });
+
it('shows the empty-state hint when no reviewers are selected', () => {
render(<ReviewerPicker reviewers={[]} onChange={() => {}} />);
expect(screen.getByText(/none — defaults to Copilot/)).toBeInTheDocument();
diff --git a/client/src/components/cos/TaskAddForm.jsx b/client/src/components/cos/TaskAddForm.jsx
index 97b986fb38..0737045ca6 100644
--- a/client/src/components/cos/TaskAddForm.jsx
+++ b/client/src/components/cos/TaskAddForm.jsx
@@ -32,6 +32,7 @@ export default function TaskAddForm({ providers, apps, onTaskAdded, compact = fa
const [reviewerModels, setReviewerModels] = useState({});
const [reviewStopMode, setReviewStopMode] = useState(DEFAULT_REVIEW_STOP_MODE);
const [reviewerApplies, setReviewerApplies] = useState(false);
+ const [reviewerCliInstalled, setReviewerCliInstalled] = useState({});
const [createJiraTicket, setCreateJiraTicket] = useState(false);
const [screenshots, setScreenshots] = useState([]);
const [attachments, setAttachments] = useState([]);
@@ -82,6 +83,7 @@ export default function TaskAddForm({ providers, apps, onTaskAdded, compact = fa
setReviewerModels(reviewerModelsFromDefaults(d));
if (d.stopMode) setReviewStopMode(d.stopMode);
if (d.reviewerApplies === true) setReviewerApplies(true);
+ if (d.installed && typeof d.installed === 'object' && !Array.isArray(d.installed)) setReviewerCliInstalled(d.installed);
})
.catch(() => {});
return () => { cancelled = true; };
@@ -589,6 +591,7 @@ export default function TaskAddForm({ providers, apps, onTaskAdded, compact = fa
reviewerMaxRounds={reviewerMaxRounds}
reviewerModels={reviewerModels}
modelOptions={reviewerModelOptions}
+ installed={reviewerCliInstalled}
stopMode={reviewStopMode}
reviewerApplies={reviewerApplies}
onChange={({ reviewers: r, usernames: u, optionalReviewers: o, reviewerMaxRounds: m, reviewerModels: rm, stopMode, reviewerApplies: ra }) => {
diff --git a/client/src/components/cos/tabs/schedule/GlobalConfigControls.jsx b/client/src/components/cos/tabs/schedule/GlobalConfigControls.jsx
index 3bb68d4516..b03c2a455a 100644
--- a/client/src/components/cos/tabs/schedule/GlobalConfigControls.jsx
+++ b/client/src/components/cos/tabs/schedule/GlobalConfigControls.jsx
@@ -471,6 +471,7 @@ export default function GlobalConfigControls({ taskType, config, onUpdate, onTri
// Review Defaults (persisted as `<reviewer>Model` scalars).
reviewerModels={config.taskMetadata?.reviewerModels ?? reviewerModelsFromDefaults(reviewDefaults)}
modelOptions={reviewerModelOptions}
+ installed={reviewDefaults.installed}
stopMode={config.taskMetadata?.reviewStopMode || reviewDefaults.stopMode || DEFAULT_REVIEW_STOP_MODE}
reviewerApplies={config.taskMetadata?.reviewerApplies !== undefined
? (config.taskMetadata?.reviewerApplies === true || config.taskMetadata?.reviewerApplies === 'true')
diff --git a/client/src/components/providers/CodeReviewDefaultsPanel.jsx b/client/src/components/providers/CodeReviewDefaultsPanel.jsx
index 3d9052aae9..d8805eb3a2 100644
--- a/client/src/components/providers/CodeReviewDefaultsPanel.jsx
+++ b/client/src/components/providers/CodeReviewDefaultsPanel.jsx
@@ -26,6 +26,7 @@ export default function CodeReviewDefaultsPanel() {
const [reviewerModels, setReviewerModels] = useState({});
const [stopMode, setStopMode] = useState(DEFAULT_REVIEW_STOP_MODE);
const [reviewerApplies, setReviewerApplies] = useState(false);
+ const [installed, setInstalled] = useState({});
const modelOptions = useReviewerModelOptions();
useEffect(() => {
@@ -44,6 +45,7 @@ export default function CodeReviewDefaultsPanel() {
setReviewerModels(reviewerModelsFromDefaults(defaults));
setStopMode(defaults.stopMode || DEFAULT_REVIEW_STOP_MODE);
setReviewerApplies(defaults.reviewerApplies === true);
+ setInstalled(defaults.installed && typeof defaults.installed === 'object' && !Array.isArray(defaults.installed) ? defaults.installed : {});
}
setLoading(false);
});
@@ -89,6 +91,7 @@ export default function CodeReviewDefaultsPanel() {
reviewerMaxRounds={reviewerMaxRounds}
reviewerModels={reviewerModels}
modelOptions={modelOptions}
+ installed={installed}
stopMode={stopMode}
reviewerApplies={reviewerApplies}
disabled={saving}
diff --git a/client/src/hooks/useCodeReviewDefaults.jsx b/client/src/hooks/useCodeReviewDefaults.jsx
index 715d89593d..7b90b6035c 100644
--- a/client/src/hooks/useCodeReviewDefaults.jsx
+++ b/client/src/hooks/useCodeReviewDefaults.jsx
@@ -22,6 +22,10 @@ const FALLBACK = Object.freeze({
ollamaModel: null,
codexModel: null,
claudeModel: null,
+ // Per-CLI-reviewer install probe (#3606) — absent/empty means "not fetched
+ // yet", not "nothing installed"; ReviewerPicker only warns on an explicit
+ // `false`.
+ installed: {},
});
const CodeReviewDefaultsContext = createContext(FALLBACK);
@@ -51,6 +55,7 @@ export function CodeReviewDefaultsProvider({ children }) {
ollamaModel: d.ollamaModel || null,
codexModel: d.codexModel || null,
claudeModel: d.claudeModel || null,
+ installed: d.installed && typeof d.installed === 'object' && !Array.isArray(d.installed) ? d.installed : {},
});
})
.catch(() => {});
diff --git a/server/lib/README.md b/server/lib/README.md
index c9ca533cea..1f38fe5b91 100644
--- a/server/lib/README.md
+++ b/server/lib/README.md
@@ -168,6 +168,7 @@ The barrel `server/lib/index.js` is a machine-checkable enumeration of every pub
| `bashResolver.js` | `resolveBashBinary()` — resolves the POSIX `bash` for running bundled `*.sh` scripts (e.g. `scripts/db.sh`). On Windows a bare `bash` often resolves (via PM2's PATH) to WSL, which mounts drives at `/mnt/h` and can't see a `H:/...` drive path (exit 127); this prefers Git Bash (PORTOS_BASH override → standard install dirs → derived from `git` on PATH → bare `bash`). No-op (`bash`) on non-Windows. |
| `openFolder.js` | `openFolderInSystemExplorer(localPath)` — cross-platform "open in Finder/Explorer/Nautilus" via detached spawn; child `error` handler prevents spawn failures from crashing the process. |
| `bufferedSpawn.js` | `bufferedSpawn(cmd, args, opts)` (structured non-throwing result) + `bufferedSpawnOrThrow` (throwing adapter), plus `killProcessTree`, `resolveWindowsExecutable`, `prepareWindowsSafeSpawn`, `prepareCliSpawn(command, args, env)` (composed resolve+wrap for a `spawn()`-safe pair), `needsShell`, `IS_WIN32`, `WIN_CMD_SHIMS`, `MAX_OUTPUT_BYTES` — shared buffered-spawn machinery with capped stdout/stderr, timeout-kill, Windows `.cmd`/`.bat` shim resolution, and `taskkill /T /F` tree-kill. Used by `appBuilder.js`, `appUpdater.js`, and the CoS agent spawners. |
+| `commandExists.js` | `commandExists(cmd, args = ['--version'], { timeoutMs = 5_000 })` — does running `cmd args` succeed? A capability probe (`execFile`-based), not a PATH lookup like `processEnv.js`'s `whichFirst`. Consolidates the two previously-private copies in `localLlm.js`/`ollamaManager.js`; callers probing a heavier CLI (e.g. `codeReview.js`'s reviewer-binary probe) pass a longer `timeoutMs`. |
| `spawnCwd.js` | `resolveSpawnCwd(workspacePath, fallbackRoot, label)` — resolves and **logs** the working directory a run/agent spawns into (expanding `~`), and throws when a workspace was requested but is missing / not a directory. Behind `services/runner.js#resolveRunCwd`, which turns that throw into a normal failed-run record for the two spawning runners. Stops a bad app `repoPath` from silently spawning in the PortOS checkout (#3180). `withSpawnCwdEnv(env, cwd)` — returns a copy of `env` with `PWD` pinned to `cwd` (dropping stale case-variant keys), because `spawn({ cwd })` doesn't rewrite the inherited `PWD` and OpenCode resolves its project root as `process.env.PWD ?? process.cwd()` (#3193). Apply it at every spawn that names its own cwd — the shared wrappers (`bufferedSpawn`, `spawnDetached`) already do, so their callers inherit it. `spawnCwd.test.js` discovers cwd-passing spawns across `server/` and fails on any that neither pins nor is listed exempt.
| `commandSecurity.js` | Allowlist of safe shell commands + `validatePm2Command(args)` (rejects daemon-wide `pm2 kill`/`startup`/`unstartup` and `<verb> all`). `validateCommand` runs the pm2 check for `pm2` base commands. Mirrored by the `agentGuard/` PATH shim for agentic paths. |
| `detachedSpawn.js` | `spawnDetached(bin, args, {controlDir,env,cwd})` → ChildProcess-like handle for a long media job that SURVIVES `pm2 restart portos-server`. A pure-`sh` double-fork reparents the job to init (escaping pm2's PPID-based TreeKill — `detached:true` alone doesn't, since it only changes the process group); the server tails on-disk log files for `stdout`/`stderr`/`close`. Used by loraTraining + videoGen. Also exports `reattachDetached(controlDir)` / `isReattachable(controlDir)` to RE-ATTACH a survivor after a restart (boot re-attach, #1332) and `reapDetached` to checkpoint-kill one when re-attach isn't possible. |
diff --git a/server/lib/commandExists.js b/server/lib/commandExists.js
new file mode 100644
index 0000000000..e91959cc8b
--- /dev/null
+++ b/server/lib/commandExists.js
@@ -0,0 +1,24 @@
+import { execFile } from 'child_process';
+import { promisify } from 'util';
+
+const execFileAsync = promisify(execFile);
+
+/**
+ * Does running `cmd args` succeed without error? A capability probe (not a
+ * PATH lookup like `whichFirst` in processEnv.js) — it actually invokes the
+ * command, so it also catches a binary that's on PATH but broken. Bounded by
+ * `timeoutMs` so a hung/interactive command can't stall the caller. Default
+ * 5s suits the lightweight system tools this was extracted from (`brew`,
+ * `systemctl`, `ollama`); a heavier agentic CLI (`codex`, `grok`, `agy`) needs
+ * the caller to pass a longer bound — `imageGen/{grok,agy,codex}.js`'s own
+ * `checkConnection()` probes use 15s for exactly these binaries. Consolidates
+ * two previously-private copies (localLlm.js, ollamaManager.js — see #3606).
+ *
+ * @param {string} cmd
+ * @param {string[]} [args] - defaults to `['--version']`, the common probe
+ * @param {{timeoutMs?: number}} [opts]
+ * @returns {Promise<boolean>}
+ */
+export async function commandExists(cmd, args = ['--version'], { timeoutMs = 5_000 } = {}) {
+ return execFileAsync(cmd, args, { timeout: timeoutMs }).then(() => true).catch(() => false);
+}
diff --git a/server/lib/commandExists.test.js b/server/lib/commandExists.test.js
new file mode 100644
index 0000000000..10f620dbb8
--- /dev/null
+++ b/server/lib/commandExists.test.js
@@ -0,0 +1,44 @@
+import { describe, it, expect, vi, beforeEach } from 'vitest'
+
+const execFileMock = { impl: (_cmd, _args, _opts, cb) => cb(null, { stdout: '', stderr: '' }) }
+vi.mock('child_process', () => ({
+ execFile: (cmd, args, opts, cb) => execFileMock.impl(cmd, args, opts, cb),
+}))
+
+const { commandExists } = await import('./commandExists.js')
+
+describe('commandExists', () => {
+ beforeEach(() => {
+ execFileMock.impl = (_cmd, _args, _opts, cb) => cb(null, { stdout: '', stderr: '' })
+ })
+
+ it('resolves true when the command exits cleanly', async () => {
+ await expect(commandExists('claude', ['--version'])).resolves.toBe(true)
+ })
+
+ it('resolves false when the command errors (e.g. ENOENT)', async () => {
+ execFileMock.impl = (_cmd, _args, _opts, cb) => cb(new Error('ENOENT'))
+ await expect(commandExists('nope', ['--version'])).resolves.toBe(false)
+ })
+
+ it('defaults args to ["--version"] when omitted', async () => {
+ let seenArgs = null
+ execFileMock.impl = (_cmd, args, _opts, cb) => { seenArgs = args; cb(null, { stdout: '', stderr: '' }) }
+ await commandExists('claude')
+ expect(seenArgs).toEqual(['--version'])
+ })
+
+ it('defaults the timeout to 5s when no opts are passed', async () => {
+ let seenOpts = null
+ execFileMock.impl = (_cmd, _args, opts, cb) => { seenOpts = opts; cb(null, { stdout: '', stderr: '' }) }
+ await commandExists('claude')
+ expect(seenOpts.timeout).toBe(5_000)
+ })
+
+ it('honors a longer timeoutMs for a heavier CLI probe', async () => {
+ let seenOpts = null
+ execFileMock.impl = (_cmd, _args, opts, cb) => { seenOpts = opts; cb(null, { stdout: '', stderr: '' }) }
+ await commandExists('codex', undefined, { timeoutMs: 15_000 })
+ expect(seenOpts.timeout).toBe(15_000)
+ })
+})
diff --git a/server/lib/index.js b/server/lib/index.js
index 7ced684026..90c14532ae 100644
--- a/server/lib/index.js
+++ b/server/lib/index.js
@@ -157,6 +157,7 @@ export * from './agentSentinel.js';
export * from './bareUrl.js';
export * from './bashResolver.js';
export * from './bufferedSpawn.js';
+export * from './commandExists.js';
export * from './commandSecurity.js';
export * from './detachedSpawn.js';
export * from './hostShutdown.js';
diff --git a/server/routes/codeReview.js b/server/routes/codeReview.js
index 01ef240984..dffa242da3 100644
--- a/server/routes/codeReview.js
+++ b/server/routes/codeReview.js
@@ -3,7 +3,7 @@ import { z } from 'zod'
import { asyncHandler, ServerError } from '../lib/errorHandler.js'
import { validateRequest, LOCAL_LLM_REVIEWERS } from '../lib/validation.js'
import { getSettings } from '../services/settings.js'
-import { runLocalCodeReview, getCodeReviewDefaults } from '../services/codeReview.js'
+import { runLocalCodeReview, getCodeReviewDefaults, getReviewerCliInstalled } from '../services/codeReview.js'
const router = Router()
@@ -21,8 +21,12 @@ const localReviewRequestSchema = z.object({
// GET /api/code-review/defaults — resolved global defaults (settings.codeReview
// + hardcoded fallback). The AI Providers panel reads this to render the
// initial state; TaskAddForm + ScheduleTab read it to seed new reviewer lists.
+// `installed` (per-CLI-reviewer boolean, TTL-probed) rides alongside so a
+// picker can flag a configured reviewer whose binary isn't on this machine
+// (#3606) — warn-only, never filters the `reviewers` list above.
router.get('/defaults', asyncHandler(async (_req, res) => {
- res.json(await getCodeReviewDefaults())
+ const [defaults, installed] = await Promise.all([getCodeReviewDefaults(), getReviewerCliInstalled()])
+ res.json({ ...defaults, installed })
}))
// POST /api/code-review/local — run a single review pass against the
diff --git a/server/routes/codeReview.test.js b/server/routes/codeReview.test.js
index aac4d4813e..c3b7cf3644 100644
--- a/server/routes/codeReview.test.js
+++ b/server/routes/codeReview.test.js
@@ -6,6 +6,7 @@ import { errorMiddleware } from '../lib/errorHandler.js'
vi.mock('../services/codeReview.js', () => ({
runLocalCodeReview: vi.fn(),
getCodeReviewDefaults: vi.fn(),
+ getReviewerCliInstalled: vi.fn(),
}))
vi.mock('../services/settings.js', () => ({
@@ -35,6 +36,16 @@ beforeEach(() => {
lmstudioModel: null,
ollamaModel: null,
})
+ codeReviewSvc.getReviewerCliInstalled.mockResolvedValue({ claude: true, antigravity: false, codex: true, grok: true })
+})
+
+describe('GET /api/code-review/defaults', () => {
+ it('merges the reviewer-CLI-installed probe into the defaults response', async () => {
+ const res = await request(makeApp()).get('/api/code-review/defaults')
+ expect(res.status).toBe(200)
+ expect(res.body.reviewers).toEqual(['copilot'])
+ expect(res.body.installed).toEqual({ claude: true, antigravity: false, codex: true, grok: true })
+ })
})
describe('POST /api/code-review/local', () => {
diff --git a/server/services/codeReview.js b/server/services/codeReview.js
index a9577d5a0e..a0203bfd53 100644
--- a/server/services/codeReview.js
+++ b/server/services/codeReview.js
@@ -14,6 +14,7 @@
import { fetchWithTimeout } from '../lib/fetchWithTimeout.js'
import { readResponseJson } from '../lib/readResponseJson.js'
+import { commandExists } from '../lib/commandExists.js'
import {
LOCAL_LLM_REVIEWERS,
DEFAULT_REVIEWERS,
@@ -21,6 +22,8 @@ import {
REVIEWER_ALIASES,
REVIEWER_VALUES,
REVIEW_STOP_MODES,
+ isCliReviewer,
+ reviewerCliBinary,
normalizeReviewUsernames,
normalizeOptionalReviewers,
resolveReviewUsernames,
@@ -169,6 +172,49 @@ export async function resolveReviewLoopOptions(metadata, { normalize, isTruthyMe
return { reviewers, usernames, optionalReviewers, reviewerMaxRounds, reviewStopMode, reviewerApplies, reviewerModels }
}
+/**
+ * Per-reviewer CLI-binary install probe, keyed by reviewer slug (e.g.
+ * `{ claude: true, antigravity: false, codex: true, grok: false }`). Only CLI
+ * reviewers (`isCliReviewer`) are probed — `copilot` is a GitHub API review
+ * and `lmstudio`/`ollama` route through `/api/code-review/local`, neither has
+ * a binary to find.
+ *
+ * TTL-cached (`authGate.js`'s inline Map+expiresAt pattern) rather than
+ * settings-event-invalidated like `getCodeReviewDefaults()`, because a probe
+ * result can go stale from something settings changes never fire for (the
+ * user installs/uninstalls a CLI mid-session). Deliberately kept OUT of
+ * `getCodeReviewDefaults()`/`pickCodeReviewDefaults()`: those are synchronous,
+ * no-I/O functions also called from the agent-completion spawn path
+ * (`resolveReviewLoopOptions`), and this does a real `execFile` per reviewer —
+ * only the `GET /defaults` route needs it, so it's called from there alone.
+ *
+ * Warn-only, per #3606's "warn, do not block" decision: this never filters or
+ * rejects a reviewer, it only reports installed state for the UI to surface.
+ */
+const REVIEWER_CLI_INSTALLED_TTL_MS = 5 * 60 * 1000
+// Matches imageGen/{grok,agy,codex}.js's own checkConnection() probes for
+// these same binaries — a plain 5s default (commandExists's fallback, sized
+// for lightweight tools like `brew --version`) previously clocked these
+// heavier agentic CLIs as falsely uninstalled under a cold start.
+const REVIEWER_CLI_PROBE_TIMEOUT_MS = 15_000
+let cachedInstalled = null
+let cachedInstalledExpiresAt = 0
+
+/** Test-only: reset the memoized reviewer-CLI-installed cache. */
+export function __resetReviewerCliInstalledCache() { cachedInstalled = null; cachedInstalledExpiresAt = 0 }
+
+export async function getReviewerCliInstalled() {
+ if (cachedInstalled && cachedInstalledExpiresAt > Date.now()) return cachedInstalled
+ const cliReviewers = REVIEWER_VALUES.filter(isCliReviewer)
+ const entries = await Promise.all(cliReviewers.map(async (reviewer) => {
+ const binary = reviewerCliBinary(reviewer)
+ return [reviewer, binary ? await commandExists(binary, undefined, { timeoutMs: REVIEWER_CLI_PROBE_TIMEOUT_MS }) : true]
+ }))
+ cachedInstalled = Object.fromEntries(entries)
+ cachedInstalledExpiresAt = Date.now() + REVIEWER_CLI_INSTALLED_TTL_MS
+ return cachedInstalled
+}
+
const CODE_REVIEW_SYSTEM_PROMPT = `You are a careful senior code reviewer. The user will paste a unified PR diff. Review only what the diff changes (not the whole repo). Produce findings as a markdown list grouped by severity:
## Blocking
diff --git a/server/services/codeReview.test.js b/server/services/codeReview.test.js
index 4039fcb7d0..11d50ef6f1 100644
--- a/server/services/codeReview.test.js
+++ b/server/services/codeReview.test.js
@@ -15,6 +15,10 @@ vi.mock('./settings.js', () => ({
// does, and those tests stub `global.fetch` directly.
vi.mock('./lmStudioManager.js', () => ({ getBaseUrl: () => 'http://localhost:1234' }))
vi.mock('./ollamaManager.js', () => ({ getBaseUrl: () => 'http://localhost:11434' }))
+// Reviewer-CLI-installed probe: stub the shared execFile-based helper so the
+// test controls per-binary results without touching the real PATH.
+const commandExistsMock = { impl: async () => true }
+vi.mock('../lib/commandExists.js', () => ({ commandExists: (...args) => commandExistsMock.impl(...args) }))
import { mockJsonResponse, mockTextResponse } from '../lib/testHelper.js'
import {
@@ -23,7 +27,9 @@ import {
getCodeReviewDefaults,
resolveReviewLoopOptions,
runLocalCodeReview,
+ getReviewerCliInstalled,
__resetCodeReviewDefaultsCache,
+ __resetReviewerCliInstalledCache,
} from './codeReview.js'
// Minimal stand-ins for the deps resolveReviewLoopOptions is handed by its
@@ -38,6 +44,8 @@ describe('codeReview helpers', () => {
afterEach(() => {
mockedSettings.current = {}
__resetCodeReviewDefaultsCache()
+ __resetReviewerCliInstalledCache()
+ commandExistsMock.impl = async () => true
vi.restoreAllMocks()
})
@@ -171,6 +179,31 @@ describe('codeReview helpers', () => {
})
})
+ describe('getReviewerCliInstalled', () => {
+ it('probes only CLI reviewers, resolving each through reviewerCliBinary', async () => {
+ const probed = []
+ commandExistsMock.impl = async (binary) => { probed.push(binary); return binary !== 'agy' }
+ const out = await getReviewerCliInstalled()
+ expect(out).toEqual({ claude: true, antigravity: false, codex: true, grok: true })
+ expect(probed.sort()).toEqual(['agy', 'claude', 'codex', 'grok'])
+ })
+
+ it('caches the result within the TTL — a second call does not re-probe', async () => {
+ let calls = 0
+ commandExistsMock.impl = async () => { calls += 1; return true }
+ await getReviewerCliInstalled()
+ await getReviewerCliInstalled()
+ expect(calls).toBe(4) // one probe per CLI reviewer, only on the first call
+ })
+
+ it('probes with the longer 15s timeout these heavier agentic CLIs need', async () => {
+ const seenOpts = []
+ commandExistsMock.impl = async (_binary, _args, opts) => { seenOpts.push(opts); return true }
+ await getReviewerCliInstalled()
+ expect(seenOpts).toEqual(seenOpts.map(() => ({ timeoutMs: 15_000 })))
+ })
+ })
+
describe('resolveReviewLoopOptions', () => {
it('assembles a reviewer-keyed model map from the per-CLI-reviewer scalars', async () => {
mockedSettings.current = {
diff --git a/server/services/localLlm.js b/server/services/localLlm.js
index f1ac48727b..22b3606a20 100644
--- a/server/services/localLlm.js
+++ b/server/services/localLlm.js
@@ -33,6 +33,7 @@ import { compareSemver } from '../lib/versionUtils.js'
import { isBackend, mapModelToBackend } from '../lib/localLlmCatalog.js'
import { sanitizeOllamaName } from '../lib/localLlmDisk.js'
import { recommendEditorialModel, isVisionModel, isVisionCapableCliProvider, isToolUseModel } from '../lib/localModelHeuristics.js'
+import { commandExists } from '../lib/commandExists.js'
import * as ollamaManager from './ollamaManager.js'
import * as lmStudioManager from './lmStudioManager.js'
import { getProviderById, getAllProviders, updateProvider, refreshProviderModels, isOllamaBackedProvider } from './providers.js'
@@ -197,10 +198,6 @@ export async function ensureBackendProvider(backend) {
// ---- backend capability probes ----------------------------------------------
-async function commandExists(cmd, args) {
- return execFileAsync(cmd, args, { timeout: 5_000 }).then(() => true).catch(() => false)
-}
-
// Whether Homebrew already has the backend's formula/cask installed. Used to
// recover from a non-zero `brew install` exit that nonetheless left the package
// on disk (post-install cleanup/hint failures exit 1 after a successful pour).
diff --git a/server/services/ollamaManager.js b/server/services/ollamaManager.js
index e3a7aa0b9a..43c1cb66e2 100644
--- a/server/services/ollamaManager.js
+++ b/server/services/ollamaManager.js
@@ -29,6 +29,7 @@ import {
} from '../lib/localLlmDisk.js'
import { buildHfAuthHeaders } from '../lib/huggingfaceLora.js'
import { isEmbeddingModel } from '../lib/localModelHeuristics.js'
+import { commandExists } from '../lib/commandExists.js'
const execFileAsync = promisify(execFile)
const AVAILABILITY_CACHE_TTL_MS = 30_000
@@ -86,10 +87,6 @@ let managedProcessPid = null
const status = { lastError: null, lastSuccessAt: null, consecutiveErrors: 0 }
-async function commandExists(cmd, args = ['--version']) {
- return execFileAsync(cmd, args, { timeout: 5_000 }).then(() => true).catch(() => false)
-}
-
async function getServiceController() {
if (process.platform === 'darwin' && await commandExists('brew', ['--version'])) {
return {