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
JavaScript ai-agentsdashboarddeveloper-toolsdigital-twinquantified-selfsecond-brainself-hostedtailscale
make the Review Loop reviewer chain configurable, with LM Studio/Ollama as new reviewer kinds
[._.]/ Adam Eivyf1704519dc51
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.mdindex 84c7c65b16..bdb2a82fde 100644--- a/.changelog/NEXT.md+++ b/.changelog/NEXT.md@@ -15,6 +15,7 @@ TBDBoth surfaces are deep-linkable (`/sharing/duplicates`, `/sharing/conflicts`) and reachable from ⌘K / voice.- **Series now belong to exactly one Universe (enforced).** Creating a series requires a universe, a linked series can no longer be un-linked (only moved to another universe), and deleting a universe that still has live series is blocked until they're moved or deleted. A migration adopts any legacy orphan series into a synthesized universe so existing installs satisfy the rule.+- **Configurable Review Loop reviewer chain (with local-LLM reviewer support).** The Review Loop's default reviewer chain used to be hardcoded to GitHub Copilot; the new **AI Providers → Code Review Defaults** panel lets you set an ordered chain (any combination of `copilot`, `claude`, `gemini`, `codex`, `lmstudio`, `ollama`), the stop mode, and whether reviewers may apply fixes. The configured defaults seed ad-hoc tasks (Tasks page) and per-task-type schedules (CoS → Schedule) when nothing's explicitly pinned, and flow through to follow-up Review Loop agents that didn't carry their own reviewer metadata. Two new reviewer kinds — `lmstudio` and `ollama` — route the PR diff through a new `POST /api/code-review/local` endpoint that runs the model selected on the panel against the backend's OpenAI-compatible chat-completions API, so a local LM Studio or Ollama install can act as your code reviewer with no CLI in the loop.- **Use a different Chrome variant for the PortOS-managed browser.** PortOS now reads a `chromePath` (and `macAppBundle` on macOS) from `data/browser-config.json`, so you can point it at Chrome Canary, Chromium, Brave, Edge, or any Chromium-based browser — separating the automation surface from your daily-driver Chrome. Setup (`./setup.sh` / `setup.ps1`) and update (`./update.sh` / `./update.ps1`) now offer to install and configure Chrome Canary automatically: on macOS via `brew install --cask google-chrome@canary`, on Windows via `winget install Google.Chrome.Canary`. The prompt is interactive-only (CI / non-TTY runs skip silently), idempotent (won't re-prompt once configured), and supports `PORTOS_USE_CANARY=1` for headless opt-in. The Browser page's Config panel exposes both fields for after-the-fact edits.## Changeddiff --git a/client/src/components/cos/TaskAddForm.jsx b/client/src/components/cos/TaskAddForm.jsxindex 422833df69..7f21ccf800 100644--- a/client/src/components/cos/TaskAddForm.jsx+++ b/client/src/components/cos/TaskAddForm.jsx@@ -51,6 +51,23 @@ export default function TaskAddForm({ providers, apps, onTaskAdded, compact = fa.catch(() => setTemplates([]));}, []);+ // Seed reviewer state from the global Code Review Defaults (AI Providers →+ // Code Review Defaults panel). One-shot on mount: if the user later toggles+ // the picker, their per-task choice wins over the global seed. Silent so a+ // missing settings file doesn't toast on every task form mount.+ useEffect(() => {+ let cancelled = false;+ api.getCodeReviewDefaults({ silent: true })+ .then((d) => {+ if (cancelled || !d) return;+ if (Array.isArray(d.reviewers) && d.reviewers.length) setReviewers(d.reviewers);+ if (d.stopMode) setReviewStopMode(d.stopMode);+ if (d.reviewerApplies === true) setReviewerApplies(true);+ })+ .catch(() => {});+ return () => { cancelled = true; };+ }, []);+// Memoize enabled providers for dropdownconst enabledProviders = useMemo(() =>providers?.filter(p => p.enabled) || [],diff --git a/client/src/components/cos/constants.js b/client/src/components/cos/constants.jsindex 1b583366ec..f63813e0be 100644--- a/client/src/components/cos/constants.js+++ b/client/src/components/cos/constants.js@@ -60,15 +60,21 @@ export const AGENT_OPTIONS = [];// Reviewer choices for the Review Loop. `copilot` requests a GitHub Copilot-// review via the native reviewer API; the others instruct the follow-up agent-// to invoke the named CLI to critique the PR diff (via `/do:rpr --review-with`).-// Keep in sync with the `reviewer` enum in `server/lib/validation.js`.+// review via the native reviewer API; CLI reviewers (claude/gemini/codex)+// instruct the follow-up agent to invoke the named CLI; local-LLM reviewers+// (lmstudio/ollama) route the diff through PortOS's `POST /api/code-review/local`+// endpoint, which runs the model configured on the AI Providers → Code Review+// Defaults panel. Keep in sync with the `REVIEWER_VALUES` enum in+// `server/lib/validation.js`.export const REVIEWER_OPTIONS = [- { value: 'copilot', label: 'Copilot', description: 'GitHub Copilot (default, GitHub-only)' },+ { value: 'copilot', label: 'Copilot', description: 'GitHub Copilot (GitHub-only)' },{ value: 'claude', label: 'Claude', description: 'Claude CLI reviews the PR diff' },{ value: 'gemini', label: 'Gemini', description: 'Gemini CLI reviews the PR diff' },- { value: 'codex', label: 'Codex', description: 'Codex CLI reviews the PR diff' }+ { value: 'codex', label: 'Codex', description: 'Codex CLI reviews the PR diff' },+ { value: 'lmstudio', label: 'LM Studio', description: 'Local LM Studio model reviews the diff (set model on AI Providers)' },+ { value: 'ollama', label: 'Ollama', description: 'Local Ollama model reviews the diff (set model on AI Providers)' }];+export const LOCAL_LLM_REVIEWERS = ['lmstudio', 'ollama'];export const DEFAULT_REVIEWER = 'copilot';export const DEFAULT_REVIEWERS = ['copilot'];diff --git a/client/src/components/cos/tabs/ScheduleTab.jsx b/client/src/components/cos/tabs/ScheduleTab.jsxindex f57435c829..39ce9415b3 100644--- a/client/src/components/cos/tabs/ScheduleTab.jsx+++ b/client/src/components/cos/tabs/ScheduleTab.jsx@@ -5,8 +5,9 @@ import toast from '../../ui/Toast';import * as api from '../../../services/api';import AppIcon from '../../AppIcon';import CronInput from '../../CronInput';-import { AGENT_OPTIONS, DEFAULT_REVIEWERS, DEFAULT_REVIEW_STOP_MODE, toggleAppMetadataOverride, agentOptionButtonClass } from '../constants';+import { AGENT_OPTIONS, DEFAULT_REVIEW_STOP_MODE, toggleAppMetadataOverride, agentOptionButtonClass } from '../constants';import ReviewerPicker from '../ReviewerPicker';+import { CodeReviewDefaultsProvider, useCodeReviewDefaults } from '../../../hooks/useCodeReviewDefaults';import { isCronExpression, describeCron } from '../../../utils/cronHelpers';import ToggleSwitch from '../../ToggleSwitch';import { filterSelectableModels } from '../../../utils/providers';@@ -253,6 +254,7 @@ function PipelineStageConfig({ taskType, config, providers, onUpdate, updating,}function GlobalConfigControls({ taskType, config, onUpdate, onTrigger, onReset, category: _category, providers, apps, updating, setUpdating, allTaskTypes, improvementDisabled }) {+ const reviewDefaults = useCodeReviewDefaults();const [selectedType, setSelectedType] = useState(config.type);const [selectedProviderId, setSelectedProviderId] = useState(config.providerId || '');const [selectedModel, setSelectedModel] = useState(config.model || '');@@ -501,9 +503,11 @@ function GlobalConfigControls({ taskType, config, onUpdate, onTrigger, onReset,{(config.taskMetadata?.reviewLoop || config.taskMetadata?.openPR) && (<div className="mt-3 pl-2"><ReviewerPicker- reviewers={config.taskMetadata?.reviewers ?? (config.taskMetadata?.reviewer ? [config.taskMetadata.reviewer] : DEFAULT_REVIEWERS)}- stopMode={config.taskMetadata?.reviewStopMode || DEFAULT_REVIEW_STOP_MODE}- reviewerApplies={config.taskMetadata?.reviewerApplies === true || config.taskMetadata?.reviewerApplies === 'true'}+ reviewers={config.taskMetadata?.reviewers ?? (config.taskMetadata?.reviewer ? [config.taskMetadata.reviewer] : reviewDefaults.reviewers)}+ stopMode={config.taskMetadata?.reviewStopMode || reviewDefaults.stopMode || DEFAULT_REVIEW_STOP_MODE}+ reviewerApplies={config.taskMetadata?.reviewerApplies !== undefined+ ? (config.taskMetadata?.reviewerApplies === true || config.taskMetadata?.reviewerApplies === 'true')+ : reviewDefaults.reviewerApplies}disabled={updating}onChange={({ reviewers, stopMode, reviewerApplies }) => {// Drop the legacy single `reviewer` key so storage converges on `reviewers`.@@ -1093,6 +1097,7 @@ export default function ScheduleTab({ apps }) {const improvementDisabled = schedule.improvementEnabled === false;return (+ <CodeReviewDefaultsProvider><div className="space-y-6"><div className="flex items-center justify-between"><div>@@ -1157,5 +1162,6 @@ export default function ScheduleTab({ apps }) {</div>)}</div>+ </CodeReviewDefaultsProvider>);}diff --git a/client/src/components/providers/CodeReviewDefaultsPanel.jsx b/client/src/components/providers/CodeReviewDefaultsPanel.jsxnew file mode 100644index 0000000000..ec741c3c29--- /dev/null+++ b/client/src/components/providers/CodeReviewDefaultsPanel.jsx@@ -0,0 +1,151 @@+import { useEffect, useId, useMemo, useState } from 'react';+import { ShieldCheck } from 'lucide-react';+import toast from '../ui/Toast';+import * as api from '../../services/api';+import ReviewerPicker from '../cos/ReviewerPicker';+import {+ DEFAULT_REVIEWERS,+ DEFAULT_REVIEW_STOP_MODE,+} from '../cos/constants';++// Global Code Review Defaults — the chain the Review Loop uses when a task or+// task-type config didn't pin its own reviewers. Lives at the top of the AI+// Providers page so adding a new provider and pointing reviews at it stay in+// the same flow. Per-backend model dropdowns are shown only when the+// corresponding local-LLM reviewer is in the chain; the model list comes from+// `/api/local-llm/status` so it always reflects what's actually installed.+export default function CodeReviewDefaultsPanel() {+ const lmStudioSelectId = useId();+ const ollamaSelectId = useId();+ const [loading, setLoading] = useState(true);+ const [saving, setSaving] = useState(false);+ const [reviewers, setReviewers] = useState(DEFAULT_REVIEWERS);+ const [stopMode, setStopMode] = useState(DEFAULT_REVIEW_STOP_MODE);+ const [reviewerApplies, setReviewerApplies] = useState(false);+ const [lmstudioModel, setLmstudioModel] = useState('');+ const [ollamaModel, setOllamaModel] = useState('');+ const [localLlmStatus, setLocalLlmStatus] = useState(null);++ useEffect(() => {+ let cancelled = false;+ Promise.all([+ api.getCodeReviewDefaults({ silent: true }).catch(() => null),+ api.getLocalLlmStatus({ silent: true }).catch(() => null),+ ]).then(([defaults, status]) => {+ if (cancelled) return;+ if (defaults) {+ setReviewers(Array.isArray(defaults.reviewers) && defaults.reviewers.length ? defaults.reviewers : DEFAULT_REVIEWERS);+ setStopMode(defaults.stopMode || DEFAULT_REVIEW_STOP_MODE);+ setReviewerApplies(defaults.reviewerApplies === true);+ setLmstudioModel(defaults.lmstudioModel || '');+ setOllamaModel(defaults.ollamaModel || '');+ }+ setLocalLlmStatus(status || null);+ setLoading(false);+ });+ return () => { cancelled = true; };+ }, []);++ const needsLmStudio = reviewers.includes('lmstudio');+ const needsOllama = reviewers.includes('ollama');++ const lmStudioModels = useMemo(+ () => localLlmStatus?.lmstudio?.models?.map((m) => m.id).filter(Boolean) || [],+ [localLlmStatus]+ );+ const ollamaModels = useMemo(+ () => localLlmStatus?.ollama?.models?.map((m) => m.id).filter(Boolean) || [],+ [localLlmStatus]+ );++ const handleSave = async () => {+ setSaving(true);+ // Empty-string model fields round-trip via the schema's `emptyToUndefined`+ // preprocess, so an unselected dropdown clears the persisted model rather+ // than writing the literal "" the <select> renders.+ const payload = {+ reviewers,+ stopMode,+ reviewerApplies,+ lmstudioModel: lmstudioModel || undefined,+ ollamaModel: ollamaModel || undefined,+ };+ const ok = await api.updateSettings({ codeReview: payload }, { silent: true })+ .then(() => true)+ .catch((err) => { toast.error(`Failed to save Code Review Defaults: ${err?.message || 'Save failed'}`); return false; });+ setSaving(false);+ if (ok) toast.success('Code Review Defaults saved');+ };++ const renderModelPicker = (label, backend, value, setValue, options, selectId) => {+ const status = localLlmStatus?.[backend];+ const unavailable = status && status.available === false;+ return (+ <div className="flex flex-col gap-1 mt-2">+ <label htmlFor={selectId} className="text-xs text-gray-500">{label} model:</label>+ {options.length > 0 ? (+ <select+ id={selectId}+ value={value}+ onChange={(e) => setValue(e.target.value)}+ className="px-2 py-1 bg-port-bg border border-port-border rounded text-xs text-gray-300 min-h-[28px] max-w-md"+ >+ <option value="">— pick a model —</option>+ {options.map((id) => <option key={id} value={id}>{id}</option>)}+ </select>+ ) : (+ <div className="text-xs text-amber-400/80">+ {unavailable+ ? `${label} backend isn't reachable — start it from Settings → Local LLMs to load models.`+ : `No ${label} models installed yet — add one in Settings → Local LLMs.`}+ </div>+ )}+ </div>+ );+ };++ return (+ <div className="bg-port-card border border-port-border rounded-xl p-4 space-y-3">+ <div className="flex items-center gap-2">+ <ShieldCheck size={16} className="text-port-accent" />+ <h2 className="text-base font-semibold text-white">Code Review Defaults</h2>+ </div>+ <p className="text-xs text-gray-500">+ Default Review Loop reviewer chain — used by ad-hoc CoS tasks and task-type schedules that haven't pinned their own. Local-LLM reviewers route the diff through PortOS's local code-review endpoint and run the model selected below.+ </p>++ {loading ? (+ <div className="text-xs text-gray-500">Loading defaults…</div>+ ) : (+ <>+ <ReviewerPicker+ reviewers={reviewers}+ stopMode={stopMode}+ reviewerApplies={reviewerApplies}+ disabled={saving}+ onChange={({ reviewers: r, stopMode: s, reviewerApplies: a }) => {+ setReviewers(r);+ setStopMode(s);+ setReviewerApplies(a);+ }}+ />++ {needsLmStudio && renderModelPicker('LM Studio', 'lmstudio', lmstudioModel, setLmstudioModel, lmStudioModels, lmStudioSelectId)}+ {needsOllama && renderModelPicker('Ollama', 'ollama', ollamaModel, setOllamaModel, ollamaModels, ollamaSelectId)}++ <div className="flex justify-end">+ <button+ type="button"+ onClick={handleSave}+ disabled={saving}+ className="px-3 py-1.5 text-sm bg-port-accent hover:bg-port-accent/80 disabled:opacity-50 text-white rounded transition-colors"+ >+ {saving ? 'Saving…' : 'Save defaults'}+ </button>+ </div>+ </>+ )}+ </div>+ );+}+diff --git a/client/src/hooks/README.md b/client/src/hooks/README.mdindex ef0ec2cf01..1b7c149fc5 100644--- a/client/src/hooks/README.md+++ b/client/src/hooks/README.md@@ -92,6 +92,7 @@ grep -i "what you want to do" client/src/hooks/README.md| `useCityAudio` | CyberCity ambient audio. | CyberCity only. || `useCityData` | CyberCity environment data + physics. | CyberCity only. || `useCitySettings` | CyberCity quality presets + persistence. | CyberCity only. |+| `useCodeReviewDefaults` | Global Code Review Defaults (Review Loop reviewer chain + per-backend local-LLM model) via a small Provider/hook pair. | TaskAddForm, ScheduleTab, anywhere a default reviewer picker is shown. || `useDeathClock` | 1-second countdown for death-clock display. | Mortality / death-clock surfaces. || `useNextEvalCountdown` | 1-second countdown to the next CoS evaluation tick. | Chief of Staff "next eval in Xs" displays. || `usePostSession` | Post-render callback scheduling. | Generic post-action chaining. |diff --git a/client/src/hooks/index.js b/client/src/hooks/index.jsindex f2a45d5fd0..23ea545dd0 100644--- a/client/src/hooks/index.js+++ b/client/src/hooks/index.js@@ -51,6 +51,9 @@ export * from './useMediaAnnotations.js';export * from './useMediaCompletionRefresh.js';export * from './useOpenClawAttachments.js';+// === Settings-derived shared state ===+export * from './useCodeReviewDefaults.jsx';+// === Sockets & lifecycle ===export * from './useSocket.js';export * from './useTimeTick.js';diff --git a/client/src/hooks/useCodeReviewDefaults.jsx b/client/src/hooks/useCodeReviewDefaults.jsxnew file mode 100644index 0000000000..321058bbc1--- /dev/null+++ b/client/src/hooks/useCodeReviewDefaults.jsx@@ -0,0 +1,51 @@+import { createContext, useContext, useEffect, useState } from 'react';+import * as api from '../services/api';+import { DEFAULT_REVIEWERS, DEFAULT_REVIEW_STOP_MODE } from '../components/cos/constants';++// Resolved "Code Review Defaults" (AI Providers panel) — used by TaskAddForm+// and ScheduleTab's per-task-type config to seed the picker's fallback state+// instead of the hardcoded `['copilot']`. Returned shape mirrors the server's+// `getCodeReviewDefaults()` so a consumer can rely on the same field names+// regardless of whether it reads context or calls the API directly.+const FALLBACK = Object.freeze({+ reviewers: DEFAULT_REVIEWERS,+ stopMode: DEFAULT_REVIEW_STOP_MODE,+ reviewerApplies: false,+ lmstudioModel: null,+ ollamaModel: null,+});++const CodeReviewDefaultsContext = createContext(FALLBACK);++// Provider — wrap once at the page/section boundary that hosts the pickers.+// Fetches the defaults once on mount; cancellation guards against unmount mid-+// request. Re-fetch only happens on remount, so save flows that update the+// panel and the same-page consumer aren't auto-synced — that's fine because+// the panel and consumers live on different pages in practice.+export function CodeReviewDefaultsProvider({ children }) {+ const [value, setValue] = useState(FALLBACK);+ useEffect(() => {+ let cancelled = false;+ api.getCodeReviewDefaults({ silent: true })+ .then((d) => {+ if (cancelled || !d) return;+ setValue({+ reviewers: Array.isArray(d.reviewers) && d.reviewers.length ? d.reviewers : DEFAULT_REVIEWERS,+ stopMode: d.stopMode || DEFAULT_REVIEW_STOP_MODE,+ reviewerApplies: d.reviewerApplies === true,+ lmstudioModel: d.lmstudioModel || null,+ ollamaModel: d.ollamaModel || null,+ });+ })+ .catch(() => {});+ return () => { cancelled = true; };+ }, []);+ return <CodeReviewDefaultsContext.Provider value={value}>{children}</CodeReviewDefaultsContext.Provider>;+}++// Hook — reads the resolved defaults. Falls back to the frozen hardcoded+// shape when no Provider is mounted, so consumers can render outside the+// Provider (e.g. dashboard widgets) without crashing.+export function useCodeReviewDefaults() {+ return useContext(CodeReviewDefaultsContext);+}diff --git a/client/src/pages/AIProviders.jsx b/client/src/pages/AIProviders.jsxindex 1623ad4f9b..9ab774f136 100644--- a/client/src/pages/AIProviders.jsx+++ b/client/src/pages/AIProviders.jsx@@ -11,6 +11,7 @@ import {TIMEOUT_INPUT_STEP_MS,} from '../utils/formatters';import SettingsTabsHeader from '../components/settings/SettingsTabsHeader';+import CodeReviewDefaultsPanel from '../components/providers/CodeReviewDefaultsPanel';export default function AIProviders() {const [providers, setProviders] = useState([]);@@ -207,6 +208,7 @@ export default function AIProviders() {<SettingsTabsHeader activeTab="providers" /><div className="flex-1 overflow-auto p-4 space-y-6">+ <CodeReviewDefaultsPanel /><div className="flex flex-col sm:flex-row sm:items-center justify-between gap-4"><h1 className="text-2xl font-bold text-white">AI Providers</h1><div className="flex flex-wrap gap-2">diff --git a/client/src/services/README.md b/client/src/services/README.mdindex 9c150fbe18..bf38ede41c 100644--- a/client/src/services/README.md+++ b/client/src/services/README.md@@ -50,6 +50,7 @@ toasts on throw). **Custom catch ⇒ `silent: true`** — otherwise toasts fire| `apiProviders.js` | AI provider config. || `apiReferenceRepos.js` | Per-app reference-repo registry. || `apiReview.js` | Review hub. |+| `apiCodeReview.js` | Code Review Defaults (Review Loop reviewer chain + per-backend local-LLM model). || `apiRuns.js` | Agent run history. || `apiScaffold.js` | App scaffolding templates. || `apiSchedules.js` | Automation schedules. |diff --git a/client/src/services/api.js b/client/src/services/api.jsindex 7dc9b78087..bd3591fd85 100644--- a/client/src/services/api.js+++ b/client/src/services/api.js@@ -22,6 +22,7 @@ export * from './apiMessages.js';export * from './apiCalendar.js';export * from './apiGoals.js';export * from './apiReview.js';+export * from './apiCodeReview.js';export * from './apiDatabase.js';export * from './apiLocalLlm.js';export * from './apiGSD.js';diff --git a/client/src/services/apiCodeReview.js b/client/src/services/apiCodeReview.jsnew file mode 100644index 0000000000..0e4e98ff83--- /dev/null+++ b/client/src/services/apiCodeReview.js@@ -0,0 +1,7 @@+import { request } from './apiCore.js';++// Code Review Defaults — the global default reviewer chain + per-backend+// model the Review Loop seeds from when a task/task-type doesn't pin its own.+// Surfaced on the AI Providers → Code Review Defaults panel; persisted under+// `settings.codeReview` via PUT /api/settings.+export const getCodeReviewDefaults = (options) => request('/code-review/defaults', options);diff --git a/client/src/services/apiLocalLlm.js b/client/src/services/apiLocalLlm.jsindex f0264f79f5..0d2b2958d1 100644--- a/client/src/services/apiLocalLlm.js+++ b/client/src/services/apiLocalLlm.js@@ -2,7 +2,7 @@ import { request } from './apiCore.js';// Local LLM backends (Ollama / LM Studio) — status, model management, migrate.// Installed models per backend come back inside getLocalLlmStatus().-export const getLocalLlmStatus = () => request('/local-llm/status');+export const getLocalLlmStatus = (options) => request('/local-llm/status', options);export const getLocalLlmCatalog = (backend, q = '') =>request(`/local-llm/catalog?backend=${encodeURIComponent(backend)}${q ? `&q=${encodeURIComponent(q)}` : ''}`);diff --git a/server/index.js b/server/index.jsindex de257a087f..030bcac31e 100644--- a/server/index.js+++ b/server/index.js@@ -69,6 +69,7 @@ import autobiographyRoutes from './routes/autobiography.js';import backupRoutes from './routes/backup.js';import databaseRoutes from './routes/database.js';import localLlmRoutes from './routes/localLlm.js';+import codeReviewRoutes from './routes/codeReview.js';import { ensureBackendProvider, getBackend as getLocalLlmBackend } from './services/localLlm.js';import { ensureRunning as ensureOllamaRunning } from './services/ollamaManager.js';import searchRoutes from './routes/search.js';@@ -421,6 +422,7 @@ app.use('/api/digital-twin/autobiography', autobiographyRoutes);app.use('/api/digital-twin', digitalTwinRoutes);app.use('/api/lmstudio', lmstudioRoutes);app.use('/api/local-llm', localLlmRoutes);+app.use('/api/code-review', codeReviewRoutes);app.use('/api/voice', voiceRoutes);app.use('/api/browser', browserRoutes);app.use('/api/data', dataManagerRoutes);diff --git a/server/lib/validation.js b/server/lib/validation.jsindex 0c5525c9ad..4721929dcd 100644--- a/server/lib/validation.js+++ b/server/lib/validation.js@@ -546,23 +546,33 @@ export const searchQuerySchema = z.object({// COS TASK SCHEMAS// =============================================================================-// Reviewer choices for the Review Loop. `copilot` is the default and requests a-// native GitHub Copilot review; the others instruct the review-loop follow-up-// agent to invoke the named CLI to critique the PR diff. Mirrored in-// client/src/components/cos/constants.js → REVIEWER_OPTIONS.-export const REVIEWER_VALUES = ['copilot', 'claude', 'gemini', 'codex'];+// Reviewer choices for the Review Loop. `copilot` requests a native GitHub+// Copilot review; `claude`/`gemini`/`codex` instruct the review-loop follow-up+// agent to invoke the named CLI to critique the PR diff; `lmstudio`/`ollama`+// route the diff through PortOS's local code-review endpoint+// (`POST /api/code-review/local`) which runs the configured local LLM model.+// Mirrored in client/src/components/cos/constants.js → REVIEWER_OPTIONS.+export const REVIEWER_VALUES = ['copilot', 'claude', 'gemini', 'codex', 'lmstudio', 'ollama'];export const DEFAULT_REVIEWER = 'copilot';export const DEFAULT_REVIEWERS = ['copilot'];+// Reviewers that resolve to a local-LLM backend (rather than a CLI or GitHub+// bot). Used by the code-review endpoint, settings panel, and prompt builder+// to gate model-id resolution.+export const LOCAL_LLM_REVIEWERS = ['lmstudio', 'ollama'];// Stop-mode for the multi-reviewer loop (slashdo `--review-stop-on-*`).export const REVIEW_STOP_MODES = ['all', 'on-findings', 'on-clean'];export const DEFAULT_REVIEW_STOP_MODE = 'all';/*** Resolve task metadata to an ordered, deduped reviewer list. Prefers the new- * `reviewers` array; falls back to the legacy single `reviewer` string; defaults- * to `['copilot']`. Filters to known reviewers and preserves first-occurrence order.+ * `reviewers` array; falls back to the legacy single `reviewer` string. When+ * the metadata yields nothing, returns `fallback` (default `['copilot']`) —+ * pass the settings-resolved defaults here so a Review Loop run picks up the+ * user's Code Review Defaults instead of the hardcoded copilot when the task+ * itself didn't pin reviewers. Filters to known reviewers and preserves+ * first-occurrence order.*/-export function normalizeReviewers(meta) {+export function normalizeReviewers(meta, fallback = DEFAULT_REVIEWERS) {const raw = meta && typeof meta === 'object' && !Array.isArray(meta) ? meta : {};const source = Array.isArray(raw.reviewers)? raw.reviewers@@ -572,7 +582,9 @@ export function normalizeReviewers(meta) {for (const r of source) {if (REVIEWER_VALUES.includes(r) && !seen.has(r)) { seen.add(r); out.push(r); }}- return out.length ? out : [...DEFAULT_REVIEWERS];+ if (out.length) return out;+ const fallbackList = Array.isArray(fallback) ? fallback.filter((r) => REVIEWER_VALUES.includes(r)) : [];+ return fallbackList.length ? [...fallbackList] : [...DEFAULT_REVIEWERS];}/**@@ -750,6 +762,20 @@ export const featureProviderConfigSchema = z.object({model: z.preprocess(emptyToUndefined, z.string().optional()),});+// Global Code Review Loop defaults (settings.codeReview). Surfaced on the AI+// Providers page; TaskAddForm + ScheduleTab seed from this when the user+// hasn't already chosen a per-task / per-task-type reviewer list. The follow-+// up spawner reads it as the fallback for `reviewers` when none are passed in.+// `lmstudioModel` / `ollamaModel` are the installed model ids the local-LLM+// reviewer should run with (empty/undefined = pick the active default model).+export const codeReviewSettingsSchema = z.object({+ reviewers: z.array(z.enum(REVIEWER_VALUES)).optional(),+ stopMode: z.enum(REVIEW_STOP_MODES).optional(),+ reviewerApplies: z.boolean().optional(),+ lmstudioModel: z.preprocess(emptyToUndefined, z.string().optional()),+ ollamaModel: z.preprocess(emptyToUndefined, z.string().optional()),+}).strict();+// =============================================================================// WRITERS ROOM SCHEMAS// =============================================================================diff --git a/server/lib/validation.test.js b/server/lib/validation.test.jsindex b73bacf052..4c3e7ea0cd 100644--- a/server/lib/validation.test.js+++ b/server/lib/validation.test.js@@ -568,6 +568,20 @@ describe('validation.js', () => {// `reviewers` wins over legacy `reviewer`.expect(normalizeReviewers({ reviewers: ['claude'], reviewer: 'codex' })).toEqual(['claude']);});++ it('accepts local-LLM reviewer kinds (lmstudio / ollama)', () => {+ expect(normalizeReviewers({ reviewers: ['lmstudio', 'ollama'] })).toEqual(['lmstudio', 'ollama']);+ expect(normalizeReviewers({ reviewer: 'lmstudio' })).toEqual(['lmstudio']);+ });++ it('uses the fallback when metadata is empty and falls back to copilot when the fallback is invalid', () => {+ // Settings-derived defaults flow through when the task didn't pin reviewers.+ expect(normalizeReviewers({}, ['gemini', 'codex'])).toEqual(['gemini', 'codex']);+ // An all-bogus fallback collapses to the hardcoded copilot, never an empty list.+ expect(normalizeReviewers({}, ['bogus', null])).toEqual(['copilot']);+ // Explicit task metadata still wins over the fallback.+ expect(normalizeReviewers({ reviewers: ['claude'] }, ['gemini'])).toEqual(['claude']);+ });});describe('buildReviewWithArgs', () => {diff --git a/server/routes/codeReview.js b/server/routes/codeReview.jsnew file mode 100644index 0000000000..c9df2bb982--- /dev/null+++ b/server/routes/codeReview.js@@ -0,0 +1,52 @@+import { Router } from 'express'+import { z } from 'zod'+import { asyncHandler } 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'++const router = Router()++// Body shape for POST /api/code-review/local. `model` is optional — when+// omitted (or empty) we fall back to the model configured on the Code Review+// Defaults panel. The diff is sent as-is; agents can pipe `gh pr diff <N>`+// straight into it without preprocessing.+const localReviewRequestSchema = z.object({+ backend: z.enum(LOCAL_LLM_REVIEWERS),+ model: z.string().optional(),+ diff: z.string().min(1, 'diff must be non-empty'),+ timeoutMs: z.number().int().positive().max(600000).optional(),+}).strict()++// 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.+router.get('/defaults', asyncHandler(async (_req, res) => {+ res.json(await getCodeReviewDefaults())+}))++// POST /api/code-review/local — run a single review pass against the+// configured local-LLM backend (LM Studio or Ollama) and return the findings+// text the agent will act on. Synchronous: keeps the agent's `curl` step+// simple — one request, one body back.+router.post('/local', asyncHandler(async (req, res) => {+ const body = validateRequest(localReviewRequestSchema, req.body)+ const settings = await getSettings()+ const configured = body.backend === 'lmstudio'+ ? settings.codeReview?.lmstudioModel+ : settings.codeReview?.ollamaModel+ const model = body.model || configured+ const result = await runLocalCodeReview({+ backend: body.backend,+ model,+ diff: body.diff,+ timeoutMs: body.timeoutMs,+ })+ if (!result.ok) {+ res.status(502).json(result)+ return+ }+ res.json(result)+}))++export default routerdiff --git a/server/routes/settings.js b/server/routes/settings.jsindex 220e520883..8c91dc043d 100644--- a/server/routes/settings.js+++ b/server/routes/settings.js@@ -7,7 +7,7 @@ import {CODEX_PARALLEL_DEFAULT,} from '../services/mediaJobQueue/index.js';import { asyncHandler } from '../lib/errorHandler.js';-import { backupConfigSchema, sharingSettingsPatchSchema, featureProviderConfigSchema, validateRequest } from '../lib/validation.js';+import { backupConfigSchema, sharingSettingsPatchSchema, featureProviderConfigSchema, codeReviewSettingsSchema, validateRequest } from '../lib/validation.js';const router = Router();@@ -60,6 +60,9 @@ router.put('/', asyncHandler(async (req, res) => {if (req.body?.calendarSync !== undefined) {validateRequest(featureProviderConfigSchema.partial(), req.body.calendarSync);}+ if (req.body?.codeReview !== undefined) {+ validateRequest(codeReviewSettingsSchema.partial(), req.body.codeReview);+ }const merged = await updateSettings(req.body);// The queue caches codex.parallelLimit in-process; sync it from the// merged value so a save takes effect without a restart and withoutdiff --git a/server/services/agentCliSpawning.js b/server/services/agentCliSpawning.jsindex 3ef5998fb6..346f7cbc51 100644--- a/server/services/agentCliSpawning.js+++ b/server/services/agentCliSpawning.js@@ -19,7 +19,8 @@ import { analyzeAgentFailure } from './agentErrorAnalysis.js';import { completeAgentRun } from './agentRunTracking.js';import { finalizeAgent, releaseAgentLane } from './agentLifecycle.js';import { activeAgents, userTerminatedAgents } from './agentState.js';-import { normalizeReviewers, DEFAULT_REVIEW_STOP_MODE } from '../lib/validation.js';+import { normalizeReviewers } from '../lib/validation.js';+import { resolveReviewLoopOptions } from './codeReview.js';import { safeJSONParse, PATHS } from '../lib/fileUtils.js';import { createCodexStderrFormatter } from '../lib/codexCliOutput.js';import { PROVIDER_TYPES } from '../lib/aiToolkit/constants.js';@@ -589,12 +590,11 @@ export async function spawnDirectly({const directOpenPR = isTruthyMetaFn(task.metadata?.openPR);const directReviewLoopFollowUp = isTruthyMetaFn(task.metadata?.reviewLoopFollowUp);const directAgentOwnsPR = directOpenPR && (provider?.id === 'claude-code' || provider?.id === 'claude-code-bedrock');+ const reviewOptions = await resolveReviewLoopOptions(task.metadata, { normalize: normalizeReviewers, isTruthyMeta: isTruthyMetaFn });await cleanupWorktreeFn(agentId, finalSuccess, {openPR: directAgentOwnsPR ? false : directOpenPR,requestCopilotReview: !directAgentOwnsPR && directOpenPR && isTruthyMetaFn(task.metadata?.reviewLoop),- reviewers: normalizeReviewers(task.metadata),- reviewStopMode: task.metadata?.reviewStopMode || DEFAULT_REVIEW_STOP_MODE,- reviewerApplies: isTruthyMetaFn(task.metadata?.reviewerApplies),+ ...reviewOptions,skipMerge: directReviewLoopFollowUp || directAgentOwnsPR,description: task.description,agentOutput: outputBuffer,diff --git a/server/services/agentCliSpawning.test.js b/server/services/agentCliSpawning.test.jsindex 90f345888f..3978fe237e 100644--- a/server/services/agentCliSpawning.test.js+++ b/server/services/agentCliSpawning.test.js@@ -45,6 +45,10 @@ vi.mock('fs', () => ({ existsSync: vi.fn().mockReturnValue(false) }));let fakeProcess;vi.mock('child_process', () => ({spawn: vi.fn(() => fakeProcess),+ // `execFile` is pulled in transitively by codeReview.js → lmStudioManager+ // (via `resolveReviewLoopOptions`'s dependency graph), even though this+ // test never spawns one directly.+ execFile: vi.fn(),}));import { buildCliSpawnConfig, createStreamJsonParser, spawnDirectly } from './agentCliSpawning.js';diff --git a/server/services/agentLifecycle.js b/server/services/agentLifecycle.jsindex a13d230720..398b3bfe62 100644--- a/server/services/agentLifecycle.js+++ b/server/services/agentLifecycle.js@@ -36,6 +36,7 @@ import { selectModelForTask } from './agentModelSelection.js';import { processAgentCompletion } from './agentCompletion.js';import { activeAgents, runnerAgents, spawningTasks, useRunner, isTruthyMeta, isFalsyMeta } from './agentState.js';import { DEFAULT_REVIEWER, DEFAULT_REVIEWERS, DEFAULT_REVIEW_STOP_MODE, normalizeReviewers } from '../lib/validation.js';+import { resolveReviewLoopOptions } from './codeReview.js';import { v4 as uuidv4 } from '../lib/uuid.js';import { writeFile } from 'fs/promises';@@ -1308,12 +1309,15 @@ export async function handleAgentCompletion(agentId, exitCode, success, duration// so PortOS doesn't double-fire `gh pr create` ("a pull request already// exists" would preserve the worktree as a false-positive failure).const agentOwnsPR = taskOpenPR && (agent.providerId === 'claude-code' || agent.providerId === 'claude-code-bedrock');+ // Merge per-task reviewer metadata with the user's Code Review Defaults+ // (AI Providers → Code Review Defaults panel). Settings I/O is cached+ // inside the resolver, so this is effectively free even when invoked+ // from a tight CoS sweep.+ const reviewOptions = await resolveReviewLoopOptions(agent.task?.metadata, { normalize: normalizeReviewers, isTruthyMeta });const cleanupWarnings = await cleanupAgentWorktree(agentId, effectiveSuccess, {openPR: agentOwnsPR ? false : taskOpenPR,requestCopilotReview: !agentOwnsPR && taskOpenPR && taskReviewLoop,- reviewers: normalizeReviewers(agent.task?.metadata),- reviewStopMode: agent.task?.metadata?.reviewStopMode || DEFAULT_REVIEW_STOP_MODE,- reviewerApplies: isTruthyMeta(agent.task?.metadata?.reviewerApplies),+ ...reviewOptions,skipMerge: taskReviewLoopFollowUp || agentOwnsPR,description: task?.description,agentOutput: outputBuffer,diff --git a/server/services/agentPromptBuilder.js b/server/services/agentPromptBuilder.jsindex 346cda0463..6d6210a2c0 100644--- a/server/services/agentPromptBuilder.js+++ b/server/services/agentPromptBuilder.js@@ -16,7 +16,7 @@ import { getToolsSummaryForPrompt } from './tools.js';import { getActiveProvider } from './providers.js';import { runPromptThroughProvider } from '../lib/promptRunner.js';import { readJSONFile, loadSlashdoFile, PATHS, tryReadFile } from '../lib/fileUtils.js';-import { DEFAULT_REVIEWER, DEFAULT_REVIEWERS, DEFAULT_REVIEW_STOP_MODE, normalizeReviewers, buildReviewWithArgs } from '../lib/validation.js';+import { DEFAULT_REVIEWER, DEFAULT_REVIEWERS, DEFAULT_REVIEW_STOP_MODE, LOCAL_LLM_REVIEWERS, normalizeReviewers, buildReviewWithArgs } from '../lib/validation.js';import { PROVIDER_TYPES } from '../lib/aiToolkit/constants.js';import * as jiraService from './jira.js';import { emitLog } from './cosEvents.js';@@ -227,7 +227,8 @@ export function buildReviewLoopFollowUpSection(metadata = {}, { verbose = false,const stopMode = metadata.reviewLoopStopMode || DEFAULT_REVIEW_STOP_MODE;const reviewerApplies = metadata.reviewLoopReviewerApplies === true;const hasCopilot = reviewers.includes(DEFAULT_REVIEWER);- const hasCli = reviewers.some(r => r !== DEFAULT_REVIEWER);+ const hasLocalLlm = reviewers.some(r => LOCAL_LLM_REVIEWERS.includes(r));+ const hasCli = reviewers.some(r => r !== DEFAULT_REVIEWER && !LOCAL_LLM_REVIEWERS.includes(r));const multi = reviewers.length > 1;// The system pre-requests the initial Copilot review only when copilot LEADS the// order; otherwise the agent must request it at copilot's turn (so Copilot reviews@@ -240,17 +241,26 @@ export function buildReviewLoopFollowUpSection(metadata = {}, { verbose = false,// First step: how to obtain a review. For a single copilot/CLI reviewer keep the// focused wording; for a list, dispatch each reviewer in order. Only emit the// per-reviewer-kind bullet that actually applies to the configured list.+ // `lmstudio`/`ollama` don't have CLIs the agent can spawn — PortOS exposes+ // `POST /api/code-review/local` which runs the configured local model against+ // the diff and returns findings text. The agent always reaches it via+ // `http://localhost:5555` (the canonical loopback API port).+ const localLlmInvocation = `POST the diff to PortOS's local reviewer endpoint: \`gh pr diff ${prNumber || '<PR_NUMBER>'} | jq -Rs '{ backend: "<lmstudio|ollama>", diff: . }' | curl -sS -X POST http://localhost:5555/api/code-review/local -H 'Content-Type: application/json' -d @-\`. Substitute the active reviewer name for \`<lmstudio|ollama>\`. The response \`.findings\` field is the review text — treat it like any other reviewer's findings.`;const multiBullets = [hasCopilot ? `**copilot**: ${copilotIsFirst? 'wait for the initial Copilot review the system already pre-requested (Copilot leads the list)': 'request a Copilot review when you reach its turn'} (poll every 5–15s, max 5 min/round), then re-request on later rounds.` : null,hasCli ? `**codex / gemini / claude**: invoke that CLI to review this branch's diff against its base (use the CLI's own base-diff mode or \`git diff <base-branch>...HEAD\`; on GitHub \`gh pr diff ${prNumber || ''}\` also works).` : null,+ hasLocalLlm ? `**lmstudio / ollama**: ${localLlmInvocation}` : null,].filter(Boolean).join(' ');- const waitOrInvokeStep = multi- ? `For EACH reviewer in order — ${reviewerLabel} — run a full review-and-fix sub-loop before advancing to the next. ${multiBullets}`- : (hasCopilot- ? 'Wait for the latest Copilot review to complete (poll every 5–15s, max 5 minutes per round); the system already requested the initial review.'- : `Invoke the ${reviewerLabel} CLI to review this branch's diff against its base (use the CLI's own base-diff mode or \`git diff <base-branch>...HEAD\`; on GitHub \`gh pr diff ${prNumber || ''}\` also works). Capture its findings as concrete issues to address.`);+ const singleCliInvocation = `Invoke the ${reviewerLabel} CLI to review this branch's diff against its base (use the CLI's own base-diff mode or \`git diff <base-branch>...HEAD\`; on GitHub \`gh pr diff ${prNumber || ''}\` also works). Capture its findings as concrete issues to address.`;+ // Resolved sequentially so a future reviewer kind only adds one branch+ // instead of deepening the nested ternary.+ let waitOrInvokeStep;+ if (multi) waitOrInvokeStep = `For EACH reviewer in order — ${reviewerLabel} — run a full review-and-fix sub-loop before advancing to the next. ${multiBullets}`;+ else if (hasCopilot) waitOrInvokeStep = 'Wait for the latest Copilot review to complete (poll every 5–15s, max 5 minutes per round); the system already requested the initial review.';+ else if (hasLocalLlm) waitOrInvokeStep = localLlmInvocation;+ else waitOrInvokeStep = singleCliInvocation;const stopModeNote = stopMode === 'on-findings'? '**Stop mode (on-findings):** stop after the FIRST reviewer whose findings you actually fixed and committed; skip the remaining reviewers.'@@ -267,8 +277,8 @@ export function buildReviewLoopFollowUpSection(metadata = {}, { verbose = false,const initialReviewState = (hasCopilot && copilotIsFirst)? 'The system has already requested the initial Copilot code review (Copilot leads the order).': hasCopilot- ? 'Copilot is configured after a CLI reviewer, so the system did NOT pre-request it — request the Copilot review yourself when you reach its turn (after the earlier reviewers’ fixes are pushed), and invoke the CLI reviewers yourself.'- : 'The system did NOT pre-request a reviewer because the configured reviewers are CLI-based — you must invoke them yourself against the PR diff.';+ ? 'Copilot is configured after another reviewer, so the system did NOT pre-request it — request the Copilot review yourself when you reach its turn (after the earlier reviewers’ fixes are pushed), and invoke the other reviewers yourself.'+ : 'The system did NOT pre-request a reviewer because no Copilot review leads the order — you must invoke each configured reviewer yourself against the PR diff.';const repeatedCommentsNote = '**Repeated comments:** If a fresh review round only re-raises feedback you intentionally rejected (with a reply explaining why), treat that round as clean and move on.';const extraNotes = [stopModeNote, applyNote].filter(Boolean);diff --git a/server/services/agentPromptBuilder.test.js b/server/services/agentPromptBuilder.test.jsindex a065065b87..b745bbc37a 100644--- a/server/services/agentPromptBuilder.test.js+++ b/server/services/agentPromptBuilder.test.js@@ -339,8 +339,9 @@ describe('buildLightContextPrompt', () => {{ branchName: 'b', worktreePath: '/tmp/wt' },isTruthyMeta);expect(prompt).toMatch(/--review-with claude/);- // The Copilot-specific pre-request wording must be replaced for CLI reviewers.- expect(prompt).toMatch(/CLI-based/);+ // The Copilot-specific pre-request wording must be replaced when no+ // Copilot reviewer leads the order (the agent invokes the reviewers itself).+ expect(prompt).toMatch(/invoke each configured reviewer yourself/);});it('threads an ordered multi-reviewer list + flags into the follow-up block', () => {@@ -365,6 +366,27 @@ describe('buildLightContextPrompt', () => {expect(prompt).toMatch(/For EACH reviewer in order/);});+ it('emits the local-LLM POST instruction when a local-LLM reviewer is configured', () => {+ const prompt = buildLightContextPrompt(+ makeTask({ metadata: {+ reviewLoopFollowUp: true,+ reviewLoopPRUrl: 'https://github.com/o/r/pull/9',+ reviewLoopPRBranch: 'b',+ reviewLoopPRNumber: 9,+ reviewLoopReviewers: ['lmstudio'],+ sourceTaskId: 'task-src-llm',+ }}),+ '/r',+ { branchName: 'b', worktreePath: '/tmp/wt' },+ isTruthyMeta);+ // The agent gets a copy-pasteable curl pipeline pointing at PortOS's+ // loopback API — without it the lmstudio/ollama reviewer kinds have no+ // way to actually run a review.+ expect(prompt).toMatch(/POST the diff to PortOS's local reviewer endpoint/);+ expect(prompt).toMatch(/http:\/\/localhost:5555\/api\/code-review\/local/);+ expect(prompt).toMatch(/gh pr diff 9 \| jq/);+ });+it('threads reviewer into the TUI Completion Workflow as `/do:pr --review-with <reviewer>`', () => {const prompt = buildLightContextPrompt(makeTask({ metadata: { openPR: true, reviewLoop: true, simplify: true, reviewers: ['gemini'] } }),diff --git a/server/services/cleanupAgentWorktree.test.js b/server/services/cleanupAgentWorktree.test.jsindex 706cf8cb87..fa4e3d03d9 100644--- a/server/services/cleanupAgentWorktree.test.js+++ b/server/services/cleanupAgentWorktree.test.js@@ -4,7 +4,11 @@ import { describe, it, expect, vi, beforeEach } from 'vitest';vi.mock('child_process', () => ({spawn: vi.fn(),- execSync: vi.fn()+ execSync: vi.fn(),+ // `execFile` is pulled in transitively by codeReview.js → lmStudioManager+ // (via `resolveReviewLoopOptions`'s dependency graph), even though this+ // test never exercises it directly.+ execFile: vi.fn()}));vi.mock('fs/promises', () => ({diff --git a/server/services/codeReview.js b/server/services/codeReview.jsnew file mode 100644index 0000000000..1655356424--- /dev/null+++ b/server/services/codeReview.js@@ -0,0 +1,168 @@+/**+ * Local-LLM code review backend for the Review Loop's `lmstudio` / `ollama`+ * reviewer kinds. The follow-up agent (a CLI like Claude / Gemini / Codex)+ * POSTs the PR diff to `/api/code-review/local`; we feed it through the+ * configured backend's OpenAI-compatible `/v1/chat/completions` endpoint with+ * a code-review system prompt and return the findings text the agent then+ * applies.+ *+ * Kept separate from `localLlm.js` (catalog/install/migrate) and the AI+ * toolkit runner (full-session orchestration with disk-backed run dirs) — a+ * single synchronous request/response is the right shape for a reviewer that+ * has to fit inside the agent's `curl` step.+ */++import { fetchWithTimeout } from '../lib/fetchWithTimeout.js'+import {+ LOCAL_LLM_REVIEWERS,+ DEFAULT_REVIEWERS,+ DEFAULT_REVIEW_STOP_MODE,+ REVIEWER_VALUES,+ REVIEW_STOP_MODES,+} from '../lib/validation.js'+import { getSettings, settingsEvents } from './settings.js'+import { getBaseUrl as getLmStudioBaseUrl } from './lmStudioManager.js'+import { getBaseUrl as getOllamaBaseUrl } from './ollamaManager.js'++// Both LM Studio (`:1234`) and Ollama (`:11434`) ship OpenAI-compatible+// `/v1/chat/completions`. Resolve through each manager's live `getBaseUrl()`+// so a runtime `updateConfig({ baseUrl })` from the local-LLM tab takes+// effect here too — otherwise the catalog UI and the reviewer would silently+// desync when a user relocates their LM Studio install.+const BACKEND_BASE_URLS = {+ lmstudio: () => getLmStudioBaseUrl(),+ ollama: () => getOllamaBaseUrl(),+}++export function isLocalLlmReviewer(backend) {+ return LOCAL_LLM_REVIEWERS.includes(backend)+}++/**+ * Resolve the global Code Review Defaults from `settings.codeReview`, falling+ * back to the hardcoded `['copilot']` / `all` / `false` defaults when the user+ * hasn't configured them yet. Filters out invalid enum values so a hand-edited+ * settings.json can't smuggle in bogus reviewer names. Returns a value-only+ * shape (no I/O) so the spawner and `GET /api/code-review/defaults` can share.+ */+export function pickCodeReviewDefaults(settings) {+ const raw = settings && typeof settings === 'object' ? settings.codeReview : null+ const reviewersIn = Array.isArray(raw?.reviewers) ? raw.reviewers : null+ const reviewers = reviewersIn+ ? Array.from(new Set(reviewersIn.filter((r) => REVIEWER_VALUES.includes(r))))+ : []+ return {+ reviewers: reviewers.length ? reviewers : [...DEFAULT_REVIEWERS],+ stopMode: REVIEW_STOP_MODES.includes(raw?.stopMode) ? raw.stopMode : DEFAULT_REVIEW_STOP_MODE,+ reviewerApplies: raw?.reviewerApplies === true,+ lmstudioModel: typeof raw?.lmstudioModel === 'string' && raw.lmstudioModel ? raw.lmstudioModel : null,+ ollamaModel: typeof raw?.ollamaModel === 'string' && raw.ollamaModel ? raw.ollamaModel : null,+ }+}++/**+ * Convenience async wrapper that reads settings.json and returns the merged+ * defaults. Used by the lifecycle fallback and the AI Providers panel.+ *+ * Cached so the per-agent-completion fallback (`finalizeAgent`) doesn't pay+ * a `readFile + JSON.parse + stripStoreKeys` round-trip on every sweep —+ * during a busy CoS evaluation that's dozens of redundant disk reads. The+ * cache invalidates on any `settings:updated` event so the panel's save+ * takes effect immediately without a restart.+ */+let cachedDefaults = null+settingsEvents.on('settings:updated', () => { cachedDefaults = null })++export async function getCodeReviewDefaults() {+ if (cachedDefaults) return cachedDefaults+ cachedDefaults = pickCodeReviewDefaults(await getSettings())+ return cachedDefaults+}++/**+ * Reviewer-loop option resolver shared by `finalizeAgent` (agentLifecycle.js)+ * and the CLI cleanup path (agentCliSpawning.js): merges per-task metadata+ * with the user's Code Review Defaults, returning `{ reviewers, reviewStopMode,+ * reviewerApplies }` in the exact shape `cleanupAgentWorktree` expects.+ *+ * Pass `normalize` (server/lib/validation.js `normalizeReviewers`) so this+ * module doesn't have to import it directly — keeps validation.js as the+ * single source of truth for the reviewer enum & fallback rules.+ *+ * Errors in settings I/O fall back to the hardcoded defaults — settings read+ * failures shouldn't block agent completion.+ */+export async function resolveReviewLoopOptions(metadata, { normalize, isTruthyMeta }) {+ const defaults = await getCodeReviewDefaults().catch(() => null)+ const reviewers = normalize(metadata, defaults?.reviewers)+ const reviewStopMode = metadata?.reviewStopMode || defaults?.stopMode || DEFAULT_REVIEW_STOP_MODE+ const reviewerApplies = metadata?.reviewerApplies !== undefined+ ? isTruthyMeta(metadata?.reviewerApplies)+ : (defaults?.reviewerApplies === true)+ return { reviewers, reviewStopMode, reviewerApplies }+}++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+## Recommended+## Nits++For each finding, name the file:line (when known) and explain the issue + suggested fix in one or two sentences. If you find nothing in a section, omit it. If the diff is clean across all severities, reply with exactly: \`No findings.\``++/**+ * Run a single code-review request against the configured local-LLM backend.+ * Returns `{ ok, findings, model, backend, error? }`. Caller is responsible+ * for surfacing the text findings to the agent driving the review loop.+ *+ * @param {Object} opts+ * @param {'lmstudio'|'ollama'} opts.backend+ * @param {string} opts.model - Installed model id (e.g. `qwen2.5-coder:7b`).+ * @param {string} opts.diff - Unified diff text to review.+ * @param {number} [opts.timeoutMs=120000] - 2 min default — LM Studio cold-+ * load of a large coder model regularly exceeds 30s but rarely 2 min.+ */+export async function runLocalCodeReview({ backend, model, diff, timeoutMs = 120000 } = {}) {+ if (!isLocalLlmReviewer(backend)) {+ return { ok: false, error: `Unsupported reviewer backend: ${backend}` }+ }+ if (!model || typeof model !== 'string') {+ return { ok: false, error: `No model configured for ${backend} reviewer — set one on the AI Providers → Code Review Defaults panel.` }+ }+ const trimmedDiff = typeof diff === 'string' ? diff.trim() : ''+ if (!trimmedDiff) {+ return { ok: false, error: 'Empty diff — nothing to review.' }+ }++ const baseUrl = BACKEND_BASE_URLS[backend]()+ const body = {+ model,+ messages: [+ { role: 'system', content: CODE_REVIEW_SYSTEM_PROMPT },+ { role: 'user', content: `Review this PR diff:\n\n\`\`\`diff\n${trimmedDiff}\n\`\`\`` },+ ],+ temperature: 0.2,+ stream: false,+ }++ const response = await fetchWithTimeout(`${baseUrl}/v1/chat/completions`, {+ method: 'POST',+ headers: { 'Content-Type': 'application/json' },+ body: JSON.stringify(body),+ }, timeoutMs).catch((err) => ({ ok: false, _fetchError: err.message }))++ if (response._fetchError !== undefined) {+ return { ok: false, backend, model, error: `${backend} request failed: ${response._fetchError}` }+ }+ if (!response.ok) {+ const text = await response.text().catch(() => '')+ return { ok: false, backend, model, error: `${backend} API error ${response.status}: ${text.slice(0, 300)}` }+ }++ const data = await response.json().catch(() => null)+ const findings = data?.choices?.[0]?.message?.content+ if (!findings || typeof findings !== 'string') {+ return { ok: false, backend, model, error: `${backend} returned no content.` }+ }+ return { ok: true, backend, model, findings: findings.trim() }+}diff --git a/server/services/codeReview.test.js b/server/services/codeReview.test.jsnew file mode 100644index 0000000000..a5838dd417--- /dev/null+++ b/server/services/codeReview.test.js@@ -0,0 +1,191 @@+import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest'++// Mock the settings store before importing the SUT — the resolver reads+// `settings.codeReview` synchronously on every call and we want test-local+// control of that value without touching disk.+const mockedSettings = { current: {} }+vi.mock('./settings.js', () => ({+ getSettings: () => Promise.resolve(mockedSettings.current),+ // Stub the EventEmitter shape the module subscribes to for cache+ // invalidation — only `.on()` is hit at import time; the SUT never emits.+ settingsEvents: { on: () => {}, emit: () => {} },+}))+// Same one-liner stub for the two backend managers — `getCodeReviewDefaults`+// + `pickCodeReviewDefaults` don't touch them, only `runLocalCodeReview`+// does, and those tests stub `global.fetch` directly.+vi.mock('./lmStudioManager.js', () => ({ getBaseUrl: () => 'http://localhost:1234' }))+vi.mock('./ollamaManager.js', () => ({ getBaseUrl: () => 'http://localhost:11434' }))++import {+ isLocalLlmReviewer,+ pickCodeReviewDefaults,+ getCodeReviewDefaults,+ runLocalCodeReview,+} from './codeReview.js'++describe('codeReview helpers', () => {+ afterEach(() => {+ mockedSettings.current = {}+ vi.restoreAllMocks()+ })++ describe('isLocalLlmReviewer', () => {+ it('classifies only lmstudio + ollama as local-LLM reviewers', () => {+ expect(isLocalLlmReviewer('lmstudio')).toBe(true)+ expect(isLocalLlmReviewer('ollama')).toBe(true)+ expect(isLocalLlmReviewer('copilot')).toBe(false)+ expect(isLocalLlmReviewer('codex')).toBe(false)+ expect(isLocalLlmReviewer('')).toBe(false)+ expect(isLocalLlmReviewer(undefined)).toBe(false)+ })+ })++ describe('pickCodeReviewDefaults', () => {+ it('returns the hardcoded fallback when settings has no codeReview slice', () => {+ expect(pickCodeReviewDefaults(null)).toEqual({+ reviewers: ['copilot'],+ stopMode: 'all',+ reviewerApplies: false,+ lmstudioModel: null,+ ollamaModel: null,+ })+ expect(pickCodeReviewDefaults({})).toEqual({+ reviewers: ['copilot'],+ stopMode: 'all',+ reviewerApplies: false,+ lmstudioModel: null,+ ollamaModel: null,+ })+ })++ it('strips unknown reviewer enum values from a hand-edited settings.json', () => {+ const out = pickCodeReviewDefaults({+ codeReview: { reviewers: ['gemini', 'bogus', 'lmstudio', 'gemini'] },+ })+ expect(out.reviewers).toEqual(['gemini', 'lmstudio'])+ })++ it('coerces invalid stop-mode + reviewerApplies + model strings', () => {+ const out = pickCodeReviewDefaults({+ codeReview: {+ reviewers: ['copilot'],+ stopMode: 'nope',+ reviewerApplies: 'truthy-string',+ lmstudioModel: '',+ ollamaModel: 42,+ },+ })+ expect(out.stopMode).toBe('all')+ expect(out.reviewerApplies).toBe(false)+ expect(out.lmstudioModel).toBeNull()+ expect(out.ollamaModel).toBeNull()+ })++ it('passes through a valid full payload', () => {+ const out = pickCodeReviewDefaults({+ codeReview: {+ reviewers: ['codex', 'lmstudio'],+ stopMode: 'on-clean',+ reviewerApplies: true,+ lmstudioModel: 'qwen2.5-coder:7b',+ ollamaModel: 'codellama',+ },+ })+ expect(out).toEqual({+ reviewers: ['codex', 'lmstudio'],+ stopMode: 'on-clean',+ reviewerApplies: true,+ lmstudioModel: 'qwen2.5-coder:7b',+ ollamaModel: 'codellama',+ })+ })+ })++ describe('getCodeReviewDefaults', () => {+ it('reads from the settings store and runs the same pick logic', async () => {+ mockedSettings.current = {+ codeReview: { reviewers: ['ollama'], ollamaModel: 'codellama' },+ }+ const out = await getCodeReviewDefaults()+ expect(out.reviewers).toEqual(['ollama'])+ expect(out.ollamaModel).toBe('codellama')+ expect(out.stopMode).toBe('all')+ })+ })++ describe('runLocalCodeReview', () => {+ beforeEach(() => {+ // Default fetch mock — chat-completions success with a static body. Each+ // test that wants a different shape replaces this in its own setup.+ global.fetch = vi.fn().mockResolvedValue({+ ok: true,+ status: 200,+ json: () => Promise.resolve({ choices: [{ message: { content: 'No findings.' } }] }),+ text: () => Promise.resolve(''),+ })+ })++ it('rejects unsupported reviewer backends', async () => {+ const r = await runLocalCodeReview({ backend: 'copilot', model: 'x', diff: 'a' })+ expect(r.ok).toBe(false)+ expect(r.error).toMatch(/Unsupported reviewer backend/)+ })++ it('requires a model id', async () => {+ const r = await runLocalCodeReview({ backend: 'lmstudio', model: '', diff: 'a' })+ expect(r.ok).toBe(false)+ expect(r.error).toMatch(/No model configured/)+ })++ it('requires a non-empty diff', async () => {+ const r = await runLocalCodeReview({ backend: 'lmstudio', model: 'm', diff: ' ' })+ expect(r.ok).toBe(false)+ expect(r.error).toMatch(/Empty diff/)+ })++ it('posts to the backend chat-completions endpoint and returns the response content', async () => {+ const r = await runLocalCodeReview({ backend: 'ollama', model: 'codellama', diff: 'diff --git a b' })+ expect(r).toEqual({ ok: true, backend: 'ollama', model: 'codellama', findings: 'No findings.' })+ expect(global.fetch).toHaveBeenCalledTimes(1)+ const [url, init] = global.fetch.mock.calls[0]+ expect(url).toMatch(/\/v1\/chat\/completions$/)+ // Default Ollama base url; assert it's hitting the right host so a+ // future rename of the env-var fallback doesn't silently flip backends.+ expect(url).toMatch(/11434/)+ const body = JSON.parse(init.body)+ expect(body.model).toBe('codellama')+ expect(body.stream).toBe(false)+ expect(body.messages[0].role).toBe('system')+ expect(body.messages[1].content).toContain('diff --git a b')+ })++ it('surfaces a non-2xx HTTP error with the status code', async () => {+ global.fetch = vi.fn().mockResolvedValue({+ ok: false,+ status: 500,+ text: () => Promise.resolve('boom'),+ })+ const r = await runLocalCodeReview({ backend: 'lmstudio', model: 'm', diff: 'x' })+ expect(r.ok).toBe(false)+ expect(r.error).toMatch(/lmstudio API error 500: boom/)+ })++ it('surfaces a fetch-level failure', async () => {+ global.fetch = vi.fn().mockRejectedValue(new Error('ECONNREFUSED'))+ const r = await runLocalCodeReview({ backend: 'lmstudio', model: 'm', diff: 'x' })+ expect(r.ok).toBe(false)+ expect(r.error).toMatch(/lmstudio request failed: ECONNREFUSED/)+ })++ it('flags an empty model response so the agent never silently records "no findings"', async () => {+ global.fetch = vi.fn().mockResolvedValue({+ ok: true,+ status: 200,+ json: () => Promise.resolve({ choices: [{ message: { content: '' } }] }),+ })+ const r = await runLocalCodeReview({ backend: 'ollama', model: 'm', diff: 'x' })+ expect(r.ok).toBe(false)+ expect(r.error).toMatch(/no content/)+ })+ })+})diff --git a/server/services/lmStudioManager.js b/server/services/lmStudioManager.jsindex 04d4434542..02031cdea5 100644--- a/server/services/lmStudioManager.js+++ b/server/services/lmStudioManager.js@@ -438,6 +438,16 @@ async function getStatus() {}}+/**+ * Live base URL — reflects runtime `updateConfig()` patches, not just startup+ * env. Used by sibling services (e.g. the local code-review endpoint) so a+ * relocated LM Studio install doesn't desync between the catalog UI and the+ * code path that actually talks to the server.+ */+function getBaseUrl() {+ return config.baseUrl+}+/*** Update configuration* @param {Object} newConfig - New configuration@@ -683,6 +693,7 @@ export {quickCompletion,getEmbeddings,getStatus,+ getBaseUrl,updateConfig,resetCache,isAppInstalled,diff --git a/server/services/ollamaManager.js b/server/services/ollamaManager.jsindex 5f9b237d42..2ffc7f821f 100644--- a/server/services/ollamaManager.js+++ b/server/services/ollamaManager.js@@ -687,6 +687,15 @@ async function importModelFromGguf({ name, ggufPath, mode = 'copy' }) {return { success: true, modelId: name, linked }}+/**+ * Live base URL — reflects runtime config patches, not just startup env.+ * Used by sibling services (e.g. the local code-review endpoint) so the+ * catalog UI and the code-review path can't desync.+ */+function getBaseUrl() {+ return config.baseUrl+}+/*** Aggregate status for the unified local-LLM UI.*/@@ -711,6 +720,7 @@ export {pullModel,deleteModel,getStatus,+ getBaseUrl,resolveLocalModel,importModelFromGguf,startServer,