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
fix: detect npm-shimmed CLIs and a non-macOS LM Studio on Windows
[._.]/ Adam Eivy99f80bf2ea9c
diff --git a/client/src/components/cos/ReviewerPicker.jsx b/client/src/components/cos/ReviewerPicker.jsxindex 521f74d3fd..4d5977e168 100644--- a/client/src/components/cos/ReviewerPicker.jsx+++ b/client/src/components/cos/ReviewerPicker.jsx@@ -250,7 +250,7 @@ export default function ReviewerPicker({const efforts = keyedLookup(effortsMap);// Why this reviewer can't run here, or null when nothing says it can't.//- // Two independent signals, both warn-only and both reported only when the+ // Three independent signals, all warn-only and each reported only when the// caller actually fetched them — a reviewer stays selectable and selected// either way, since the checks are local-machine-only and a federated peer// (or a later install / a flip in Settings) may satisfy them:@@ -258,6 +258,11 @@ export default function ReviewerPicker({// - `installed[token] === false` — the CLI binary isn't on PATH. Only an// explicit `false` counts; `undefined` covers both "not a CLI reviewer"// (copilot/@username) and "caller didn't fetch `installed`".+ // - `unavailable[token] === true` — a LOCAL backend (LM Studio / Ollama) that+ // didn't answer its probe. This is the ONLY availability signal those three+ // get: their reviews hit the daemon's base URL directly, so a same-named+ // provider record's on/off switch says nothing about them (the hook exempts+ // them from `providerDisabled` for that reason).// - `providerDisabled[token]` — every provider record fronting that binary is// switched off on this install, so the user has said they don't use it. A// `/api/providers` that failed or hasn't landed reports nothing (see the@@ -284,6 +289,16 @@ export default function ReviewerPicker({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.`};}+ // A local backend answers from its own daemon, so the live probe — not a+ // provider record — is what says whether it can review. `=== true` keeps a+ // pre-fetch render (undefined) from accusing a healthy backend.+ if (modelOptions?.unavailable?.[token] === true) {+ const backendPage = LOCAL_BACKEND_MANAGE_PAGES[token];+ return {+ label: 'not running',+ title: `${labelFor(token)} isn't answering on this machine${backendPage ? ` — start its server from ${backendPage}` : ''}. It still runs (federation-wide config), but a review here won't complete until it's up.`+ };+ }if (modelOptions?.providerDisabled?.[token]) {return {label: 'disabled',diff --git a/client/src/components/cos/ReviewerPicker.test.jsx b/client/src/components/cos/ReviewerPicker.test.jsxindex 002cc2b370..99ef3dc823 100644--- a/client/src/components/cos/ReviewerPicker.test.jsx+++ b/client/src/components/cos/ReviewerPicker.test.jsx@@ -61,6 +61,27 @@ describe('ReviewerPicker', () => {});});+ // A local backend answers from its own daemon, so the live probe is the only+ // thing that can say whether it will review — a same-named AI-provider record+ // being switched off says nothing about it (see the hook's exemption).+ describe('local-backend reachability badge', () => {+ it('flags a local backend whose probe reports it down', () => {+ render(<ReviewerPicker reviewers={['lmstudio']} modelOptions={{ loaded: true, unavailable: { lmstudio: true } }} onChange={() => {}} />);+ expect(screen.getByText('not running')).toBeInTheDocument();+ });++ it('leaves a reachable local backend unbadged', () => {+ render(<ReviewerPicker reviewers={['lmstudio']} modelOptions={{ loaded: true, unavailable: { lmstudio: false } }} onChange={() => {}} />);+ expect(screen.queryByText('not running')).not.toBeInTheDocument();+ expect(screen.queryByText('disabled')).not.toBeInTheDocument();+ });++ it('says nothing before the probe has landed', () => {+ render(<ReviewerPicker reviewers={['lmstudio']} modelOptions={{ loaded: false }} onChange={() => {}} />);+ expect(screen.queryByText('not running')).not.toBeInTheDocument();+ });+ });+// #7660: an enabled, present provider that still has no enforceable tool-free// review transport is the one case nothing used to say out loud — the user// found out only when every PR it gated sat unmergeable forever.diff --git a/client/src/hooks/useReviewerModelOptions.js b/client/src/hooks/useReviewerModelOptions.jsindex 33db8b3127..e331844100 100644--- a/client/src/hooks/useReviewerModelOptions.js+++ b/client/src/hooks/useReviewerModelOptions.js@@ -7,7 +7,7 @@ import { filterSelectableModels, selectableModelsForProvider, antigravityModelEf// handed the user — is exactly the drift a second copy would reintroduce.import { REVIEWER_PROVIDER_MATCHERS, providersForReviewer } from '../../../server/lib/reviewerProviderMatchers.js';import { MODEL_SELECTABLE_REVIEWERS } from '../components/cos/constants';-import { reviewerEffortLevels, normalizeReviewerSlug } from '../lib/reviewerPins';+import { reviewerEffortLevels, normalizeReviewerSlug, LOCAL_LLM_REVIEWERS } from '../lib/reviewerPins';import { LOCAL_LLM_BACKENDS } from '../lib/localLlmBackends';// Local backends whose installed-model list `/api/local-llm/status` actually@@ -53,7 +53,9 @@ const PROBED_LOCAL_BACKENDS = LOCAL_LLM_BACKENDS.map((b) => b.id);* `ReviewerPicker` uses to drop it from the Add row, so a machine that never* enabled Kimi or Cursor isn't offered them. Only ever true from a landed fetch:* a null/failed `/api/providers` matches no record, which reads as "nothing- * known", never as "switched off".+ * known", never as "switched off". Always false for a LOCAL_LLM_REVIEWERS+ * backend, whose review never reads a provider record at all — see the exemption+ * at the return site.** `loaded` flips once both fetches settle, so a consumer can tell "no options* yet" from "genuinely no options" (an empty list is a real answer, not a@@ -249,9 +251,17 @@ export default function useReviewerModelOptions() {// reads a record with no `enabled` key as ON — the opposite of// `providerCardState`'s stricter test, because this answer HIDES a control// and incomplete data must never do that.+ //+ // A LOCAL-LLM reviewer is exempt: `lmstudio`/`ollama`/`mtplx` reviews go+ // straight to the daemon's own base URL (`BACKEND_BASE_URLS` in+ // server/services/codeReview.js), so a switched-off AI-provider record+ // named after the same backend does not stop the review from running. Left+ // in, it reported a reachable LM Studio serving models as unusable and+ // hid the row behind "show hidden reviewers". The live probe below+ // (`unavailable`) is the authoritative signal for these three.providerDisabled: Object.fromEntries(Object.entries(providersByReviewer).map(([reviewer, matched]) =>- [reviewer, matched.length > 0 && matched.every((p) => p.enabled === false)]+ [reviewer, !LOCAL_LLM_REVIEWERS.includes(reviewer) && matched.length > 0 && matched.every((p) => p.enabled === false)])),loaded,diff --git a/client/src/hooks/useReviewerModelOptions.test.jsx b/client/src/hooks/useReviewerModelOptions.test.jsxindex 365f7c936f..e16755f3bb 100644--- a/client/src/hooks/useReviewerModelOptions.test.jsx+++ b/client/src/hooks/useReviewerModelOptions.test.jsx@@ -210,6 +210,22 @@ describe('useReviewerModelOptions', () => {expect(result.current.providerDisabled[reviewer], reviewer).toBe(false);}});++ // A `lmstudio`/`ollama`/`mtplx` review is sent to the daemon's own base URL+ // (BACKEND_BASE_URLS in server/services/codeReview.js) and never reads a+ // provider record, so a switched-off record of the same name does not stop+ // it. Counting it did: a reachable LM Studio serving models reported as+ // unusable and the row was hidden behind "show hidden reviewers".+ it('exempts a local backend, whose review never reads a provider record', async () => {+ getProviders.mockResolvedValue({ providers: [+ { id: 'lmstudio', type: 'api', enabled: false, models: [] },+ { id: 'ollama', type: 'api', enabled: false, models: [] },+ ] });+ const { result } = renderHook(() => useReviewerModelOptions());+ await waitFor(() => expect(result.current.loaded).toBe(true));+ expect(result.current.providerDisabled.lmstudio).toBe(false);+ expect(result.current.providerDisabled.ollama).toBe(false);+ });});// #3733: `agy` validates the model/effort PAIR, so the Effort cell's ladder hasdiff --git a/server/lib/commandExists.js b/server/lib/commandExists.jsindex e5dc49c959..6e5a0de5c5 100644--- a/server/lib/commandExists.js+++ b/server/lib/commandExists.js@@ -7,6 +7,18 @@ const execFileAsync = promisify(execFile);* Run a bounded capability probe and return its trimmed stdout, or `null` when* the command could not run or exited non-zero.*+ * The command is routed through `prepareCliSpawn` first. On Windows an+ * npm-installed CLI is a `.cmd` shim, and `execFile`'s default `shell: false`+ * neither applies a PATHEXT search to a bare name (`codex` → `spawn ENOENT`)+ * nor will it launch a `.cmd` target at all post-CVE-2024-27980 (`spawn+ * EINVAL`). Both failures land in the same `.catch(() => null)` as a genuinely+ * missing binary, so EVERY npm-shimmed CLI probed through here reported as+ * "not installed" on Windows while `codex --version` worked fine in a terminal+ * — the reviewer-CLI install probe behind the Code Review picker being the+ * visible case. `prepareCliSpawn` resolves the bare name to its+ * explicit-extension path and wraps a batch target as `cmd.exe /c <path>+ * <args>`; every branch of it is a no-op off Windows.+ ** The child's stdin is closed immediately. `agy models` blocks on an open stdin* and prints NOTHING until it closes — with execFile's default pipe that is a* full timeout's hang ending in SIGTERM and empty output. (execFile ignores an@@ -22,13 +34,20 @@ function probe(cmd, args, { timeoutMs, env, cwd, maxBuffer }) {...(cwd === undefined ? {} : { cwd }),...(maxBuffer === undefined ? {} : { maxBuffer }),};- // Some spawn failures (notably ENOEXEC for a broken text shim on macOS)- // are thrown synchronously by the child-process wrapper before it can- // return a promise. Start the call in a microtask so those failures follow- // the same null result as an ordinary rejected execFile promise.- return Promise.resolve()- .then(() => {- const pending = execFileAsync(cmd, args, options);+ // `bufferedSpawn.js` is imported lazily, not at module load: this module is+ // reached by a very large share of the server suite, and an eager edge into+ // that subtree pushed the tree-wide instantiation budget over (see "Import+ // scoping" in server/AGENTS.md). The import also supplies the microtask+ // boundary the `Promise.resolve()` used to — some spawn failures (notably+ // ENOEXEC for a broken text shim on macOS) are thrown synchronously by the+ // child-process wrapper, and this keeps them on the same rejected-promise path+ // as an ordinary failure.+ return import('./bufferedSpawn.js')+ .then(({ prepareCliSpawn }) => {+ // Resolution reads the env the CHILD will run under, so a caller that+ // overrides PATH probes its own binary, not one off the server's PATH.+ const launch = prepareCliSpawn(cmd, args, env || process.env);+ const pending = execFileAsync(launch.command, launch.args, options);pending.child?.stdin?.end();return pending;})diff --git a/server/lib/commandExists.test.js b/server/lib/commandExists.test.jsindex d5cbdbde8d..8f959bb228 100644--- a/server/lib/commandExists.test.js+++ b/server/lib/commandExists.test.js@@ -5,11 +5,25 @@ vi.mock('./childProcess.js', () => ({execFile: (cmd, args, opts, cb) => execFileMock.impl(cmd, args, opts, cb),}))+// Real by default (a no-op off Windows); overridden in the shim suite below to+// stand in for what it returns on a real Windows box.+const prepareMock = { impl: null }+vi.mock('./bufferedSpawn.js', async (importOriginal) => {+ const actual = await importOriginal()+ return {+ ...actual,+ prepareCliSpawn: (cmd, args, env) => (+ prepareMock.impl ? prepareMock.impl(cmd, args, env) : actual.prepareCliSpawn(cmd, args, env)+ ),+ }+})+const { commandExists } = await import('./commandExists.js')describe('commandExists', () => {beforeEach(() => {execFileMock.impl = (_cmd, _args, _opts, cb) => cb(null, { stdout: '', stderr: '' })+ prepareMock.impl = null})it('resolves true when the command exits cleanly', async () => {@@ -56,4 +70,44 @@ describe('commandExists', () => {expect(seenOpts).toEqual({ timeout: 5_000, env, cwd: '/example/workspace' })})++ // A bare `codex` is a `.cmd` shim on Windows. execFile's default shell:false+ // applies no PATHEXT search to the bare name and refuses a `.cmd` target+ // outright post-CVE-2024-27980 — both land in the same catch as a missing+ // binary, so every npm-shimmed reviewer CLI read as "not installed" there.+ describe('Windows .cmd shims', () => {+ it('probes the launchable pair prepareCliSpawn resolved, not the bare name', async () => {+ prepareMock.impl = () => ({+ command: 'cmd.exe',+ args: ['/c', 'C:\\ProgramData\\npm\\codex.cmd', '--version'],+ })+ let seen = null+ execFileMock.impl = (cmd, args, _opts, cb) => { seen = { cmd, args }; cb(null, { stdout: 'codex-cli 0.1.0', stderr: '' }) }++ await expect(commandExists('codex')).resolves.toBe(true)+ expect(seen).toEqual({+ cmd: 'cmd.exe',+ args: ['/c', 'C:\\ProgramData\\npm\\codex.cmd', '--version'],+ })+ })++ it('resolves the bare name against the CHILD env, so a PATH override is honored', async () => {+ let seenEnv = null+ prepareMock.impl = (cmd, args, env) => { seenEnv = env; return { command: cmd, args } }+ const env = { PATH: '/example/bin' }++ await commandExists('codex', undefined, { env })++ expect(seenEnv).toBe(env)+ })++ it('falls back to process.env when the caller passes no child env', async () => {+ let seenEnv = null+ prepareMock.impl = (cmd, args, env) => { seenEnv = env; return { command: cmd, args } }++ await commandExists('codex')++ expect(seenEnv).toBe(process.env)+ })+ })})diff --git a/server/services/lmStudioManager.js b/server/services/lmStudioManager.jsindex 757da0732c..b5701e2b04 100644--- a/server/services/lmStudioManager.js+++ b/server/services/lmStudioManager.js@@ -638,11 +638,23 @@ function resetCache() {lastCheckAt = null}-// LM Studio can be installed as a macOS app without the `lms` CLI on PATH and+// LM Studio can be installed as a desktop app without the `lms` CLI on PATH and// without the local server running — mirror scripts/setup-llm.js so status// doesn't report "Not installed" (and offer a redundant install) in that case.+//+// macOS has one fixed bundle path, so it is checked directly. Windows and Linux+// do NOT: the installer lets the user place the app anywhere, including a+// non-system drive, so there is no fixed path to probe.+// What every platform DOES have is the app's own home directory — LM Studio+// creates `~/.lmstudio` (or the older `~/.cache/lm-studio`) on first launch, and+// `getModelsDir()` above already treats those two as its authoritative roots.+// Keying off them makes a Windows install with the server stopped and `lms`+// unbootstrapped read as installed instead of prompting to install it again.+const LM_STUDIO_HOME_DIRS = ['.lmstudio', '.cache/lm-studio']+function isAppInstalled() {- return process.platform === 'darwin' && existsSync('/Applications/LM Studio.app')+ if (process.platform === 'darwin' && existsSync('/Applications/LM Studio.app')) return true+ return LM_STUDIO_HOME_DIRS.some((dir) => existsSync(join(homedir(), ...dir.split('/'))))}/**diff --git a/server/services/lmStudioManager.test.js b/server/services/lmStudioManager.test.jsindex 622ae02b8c..2ad8b77eeb 100644--- a/server/services/lmStudioManager.test.js+++ b/server/services/lmStudioManager.test.js@@ -8,6 +8,17 @@ import fs from 'fs';// developer's LM Studio.const lmsSpawn = vi.fn();vi.mock('../lib/bufferedSpawn.js', () => ({ bufferedSpawn: (...args) => lmsSpawn(...args) }));+// `isAppInstalled` reads LM Studio's home directory, which is the only+// cross-platform install marker (the app's own location is user-chosen off+// macOS). Redirected to a temp dir so the assertion never depends on whether+// the developer's machine happens to have LM Studio.+const fakeHome = { path: null };+vi.mock('os', async (importOriginal) => {+ const actual = await importOriginal();+ const homedir = () => fakeHome.path ?? actual.homedir();+ return { ...actual, homedir, default: { ...actual, homedir } };+});+const lmsBinary = { path: '/usr/local/bin/lms' };vi.mock('../lib/processEnv.js', async (importOriginal) => ({...(await importOriginal()),@@ -29,6 +40,7 @@ beforeEach(() => {process.env.LM_STUDIO_URL = 'http://127.0.0.1:1';lmsSpawn.mockReset().mockResolvedValue({ success: true, code: 0, stdout: '', stderr: '' });lmsBinary.path = '/usr/local/bin/lms';+ fakeHome.path = null;vi.resetModules();});@@ -478,3 +490,39 @@ describe('lmStudioManager.loadModelWithArgs', () => {expect(lmsSpawn).not.toHaveBeenCalled();});});++// Before this, `isAppInstalled` was hard-gated to `process.platform === 'darwin'`+// plus the fixed `/Applications` bundle path, so a Windows or Linux install —+// where the user picks the install drive and there is no path to probe — always+// read false. With the `lms` CLI unbootstrapped and the local server stopped,+// that made `getStatus()` report an installed LM Studio as "Not installed" and+// offer to install it again.+describe('isAppInstalled', () => {+ const home = () => {+ const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'portos-lms-home-'));+ fakeHome.path = dir;+ return dir;+ };++ it('counts an LM Studio home directory as installed on any platform', async () => {+ fs.mkdirSync(path.join(home(), '.lmstudio'), { recursive: true });+ const { isAppInstalled } = await import('./lmStudioManager.js');+ expect(isAppInstalled()).toBe(true);+ });++ it('counts the older ~/.cache/lm-studio layout too', async () => {+ fs.mkdirSync(path.join(home(), '.cache', 'lm-studio'), { recursive: true });+ const { isAppInstalled } = await import('./lmStudioManager.js');+ expect(isAppInstalled()).toBe(true);+ });++ it('stays false when neither marker exists', async () => {+ home();+ const { isAppInstalled } = await import('./lmStudioManager.js');+ // A macOS dev box with a real bundle would answer true through the other+ // branch, so only assert the no-bundle case.+ if (process.platform !== 'darwin' || !fs.existsSync('/Applications/LM Studio.app')) {+ expect(isAppInstalled()).toBe(false);+ }+ });+});