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
probe a harness's models once per bootstrap credential, not once per harness
[._.]/ Adam Eivy70a7c0a32ae2
diff --git a/client/src/components/models/HarnessesTab.jsx b/client/src/components/models/HarnessesTab.jsxindex d6bf4740d3..b9303a64bb 100644--- a/client/src/components/models/HarnessesTab.jsx+++ b/client/src/components/models/HarnessesTab.jsx@@ -236,8 +236,13 @@ export default function HarnessesTab() {});const result = await refreshHarnessModels(harness.id, { silent: true }).then((data) => ({- ok: true,- message: `${data.models.length} models from ${harness.command} → ${plural(data.updated.length, 'provider')} updated.`,+ // A 200 carrying `reason` is a PARTIAL success — one credential's probe+ // failed while another answered (see server/services/harnesses.js).+ ok: !data.reason,+ message: [+ `${data.models.length} models from ${harness.command} → ${plural(data.updated.length, 'provider')} updated.`,+ data.reason,+ ].filter(Boolean).join(' '),})).catch((err) => ({ ok: false, message: err?.message || 'Could not read the model list.' }));setRefreshResults((prev) => ({ ...prev, [harness.id]: result }));diff --git a/client/src/components/models/HarnessesTab.test.jsx b/client/src/components/models/HarnessesTab.test.jsxindex 5e0227816d..2abbc1fc98 100644--- a/client/src/components/models/HarnessesTab.test.jsx+++ b/client/src/components/models/HarnessesTab.test.jsx@@ -134,6 +134,23 @@ describe('HarnessesTab', () => {expect(screen.getByTestId('install-modal')).toBeInTheDocument();});+ // The harness is probed once per bootstrap credential, so a 200 can carry a+ // `reason`: one credential answered and another did not. Reporting that as a+ // clean success hides a record the refresh left alone.+ it('does not claim success when one credential’s probe failed', async () => {+ refreshHarnessModels.mockResolvedValue({+ models: ['opencode/a'],+ updated: ['opencode-zen-cli'],+ reason: '`token-cli opencode models` returned no models.',+ });+ render(<HarnessesTab />);++ fireEvent.click(await screen.findByRole('button', { name: /Refresh models/ }));++ expect(await screen.findByText(/token-cli opencode models` returned no models/)).toBeInTheDocument();+ expect(screen.getByText(/1 models from opencode → 1 provider updated/)).toBeInTheDocument();+ });+it('renders a refusal reason verbatim instead of a generic failure', async () => {refreshHarnessModels.mockRejectedValue(new Error('Sign in to OpenCode CLI in a terminal.'));render(<HarnessesTab />);diff --git a/server/routes/providers.js b/server/routes/providers.jsindex 44a66abbaf..df4597362d 100644--- a/server/routes/providers.js+++ b/server/routes/providers.js@@ -918,7 +918,10 @@ export function createPortOSProviderRoutes(aiToolkit) {if (!stored) throw new ServerError('Provider not found', { status: 404 });let provider;if (refreshesOpenCodeCatalog(stored)) {- const result = await refreshHarnessModels('opencode');+ // Scoped to THIS record: the harness is probed once per bootstrap+ // credential (services/harnesses.js), and a card's button must not spawn+ // another record's credential CLI to answer for its own.+ const result = await refreshHarnessModels('opencode', { providerId: stored.id });if (!result.ok || !result.updated.includes(stored.id)) {throw new ServerError(result.reason || 'No models matched this provider’s namespace; its catalog was preserved.', { status: 502 });}diff --git a/server/routes/providers.refreshModels.test.js b/server/routes/providers.refreshModels.test.jsindex acb4fecdfc..823463a15a 100644--- a/server/routes/providers.refreshModels.test.js+++ b/server/routes/providers.refreshModels.test.js@@ -69,7 +69,7 @@ describe('OpenCode Zen card refresh', () => {const res = await request(app).post('/api/providers/' + zen.id + '/refresh-models');expect(res.status).toBe(200);expect(res.body.models).toEqual(['opencode/new']);- expect(refreshHarnessModels).toHaveBeenCalledWith('opencode');+ expect(refreshHarnessModels).toHaveBeenCalledWith('opencode', { providerId: zen.id });expect(service.refreshProviderModels).not.toHaveBeenCalled();});diff --git a/server/services/harnesses.js b/server/services/harnesses.jsindex c55a98c67c..4ecc01f21f 100644--- a/server/services/harnesses.js+++ b/server/services/harnesses.js@@ -247,34 +247,100 @@ export async function listHarnesses({ fresh = false, run = commandOutput, ...pro}/**- * The ONE credential every record this refresh writes agrees on, or null.+ * The target records bucketed by the credential their probe must run under.*- * A single probe serves every target, so it can only run under a credential all- * of them share: one distinct bootstrap across all targets is unambiguous, and- * anything else — a mix of bootstrapped and not, or two different ones — cannot- * be served by one spawn and probes bare, exactly as it always did.+ * A bootstrap CLI mints auth for ONE account, and `<harness> models` under it+ * prints THAT account's catalog — so a probe answers only for the records that+ * share its credential. One bucket per distinct `credentialBootstrap`, plus one+ * for the records that name none (`probeAs: null`, probed bare).+ *+ * A target's own credential is the only thing that decides which probe answers+ * for it: there is deliberately no rule that degrades a mixed set to one bare+ * probe, because "bare" is another account's answer, not a safe default.+ *+ * Deep equality rather than a serialized key: two records carrying the same+ * bootstrap by different key order are one account, not two probes.*/-const soleCredentialBootstrap = (targets) => {- const named = targets.filter(hasCredentialBootstrap);- if (named.length === 0 || named.length !== targets.length) return null;- return named.every((target) => isDeepStrictEqual(target.credentialBootstrap, named[0].credentialBootstrap))- ? named[0] : null;+const credentialProbeGroups = (targets) => {+ const groups = [];+ for (const target of targets) {+ // The RECORD to probe as, not the bootstrap itself — `resolveCliSpawn`+ // takes a provider, and null means "spawn the harness bare".+ const probeAs = hasCredentialBootstrap(target) ? target : null;+ const bucket = groups.find((group) => isDeepStrictEqual(+ group.probeAs?.credentialBootstrap ?? null,+ probeAs?.credentialBootstrap ?? null,+ ));+ if (bucket) bucket.targets.push(target);+ else groups.push({ probeAs, targets: [target] });+ }+ return groups;};+/**+ * Write one probe's catalog to the records that probe answers for, and return+ * the ids actually rewritten.+ */+async function applyHarnessCatalog(runtime, models, targets) {+ const updated = [];+ for (const provider of targets) {+ // Hold the record's namespace scope (see `storedNamespaces`). A filter that+ // matched nothing means the harness no longer lists anything this record is+ // for — skip it rather than blanking a working list on that evidence.+ const scope = storedNamespaces(provider);+ const scoped = scope.size === 0+ ? models+ : models.filter((id) => scope.has(id.slice(0, id.indexOf('/'))));+ if (scoped.length === 0) {+ console.log(`⏭️ ${runtime.label}: ${provider.id} lists no models in its own namespace — left alone`);+ continue;+ }+ // A `*-configured-default` sentinel is NOT a model the vendor will ever+ // print — it is the "send no --model, let the CLI use its own default"+ // marker (`resolveCliModel` maps it to null). Dropping it would silently+ // repin an agy/grok wrapper onto a concrete model AND remove the option+ // from the editor's picker, which renders it from this same list. So it+ // survives the rewrite rather than reading as an orphaned id.+ const next = [...(provider.models || []).filter(isConfiguredDefaultModel), ...scoped];+ // A stored default the harness no longer lists would leave the record+ // pinned to a model its own picker cannot show. Keep it when it survived+ // the refresh, otherwise fall to the first id (sentinel first when there+ // is one, then whatever the vendor listed newest-first).+ const defaultModel = next.includes(provider.defaultModel) ? provider.defaultModel : next[0];+ // Serialized rather than batched: each write is a read-modify-write of the+ // same providers.json, and Promise.all would have them clobber each other.+ await providerService.updateProvider(provider.id, { models: next, defaultModel });+ updated.push(provider.id);+ }+ return updated;+}+/*** Ask a harness which models it knows about, and write the answer to every* provider that draws from its own catalog.*+ * One probe per credential, not one per harness — see {@link credentialProbeGroups}:+ * the catalog a harness prints is the catalog of the account it ran as, so a+ * record whose auth comes from a bootstrap CLI is answered by a probe run+ * THROUGH that CLI and never by the ambient one.+ ** Refuses rather than guesses in three cases, each with its own reason string:* an id not in the table, a harness with no `models` subcommand, and a harness* that is not installed. A probe that RUNS but parses to nothing also refuses —* an empty catalog is far more likely to be a vendor output change or a* signed-out CLI than a real "this harness has zero models", and blanking every- * picker on that guess is worse than reporting the probe as failed.+ * picker on that guess is worse than reporting the probe as failed. With+ * several credentials in play those refusals are per-bucket, so `reason` is+ * present on a partial success as well as on `ok: false`.+ *+ * `providerId` narrows the run to the ONE bucket that record belongs to — what+ * a single provider card's button means. Without it a click on a plain wrapper+ * would also spawn an unrelated record's bootstrap CLI, minting a credential+ * nobody asked for. The Harnesses page button omits it and refreshes them all.** @returns {Promise<{ok:boolean, reason?:string, models:string[], updated:string[]}>}*/-export async function refreshHarnessModels(id, { run = commandOutput, ...probeDeps } = {}) {+export async function refreshHarnessModels(id, { run = commandOutput, providerId = null, ...probeDeps } = {}) {const runtime = getProviderRuntime(id);if (!runtime) return { ok: false, reason: 'Unknown harness.', models: [], updated: [] };if (!runtime.modelsArgs) {@@ -288,90 +354,87 @@ export async function refreshHarnessModels(id, { run = commandOutput, ...probeDeconst findCommand = probeDeps.findCommand || findCommandOnPath;// The records this refresh will WRITE, resolved before the probe because the- // credential the probe must run under belongs to THEM — not to whichever+ // credential each probe must run under belongs to THEM — not to whichever// card's button was clicked, and not to the ambient account.const targets = providersForHarness(await providerService.listProviders(), runtime).filter(usesHarnessCatalog);- const credentialed = soleCredentialBootstrap(targets);+ const buckets = credentialProbeGroups(targets);+ const scoped = providerId ? buckets.filter((b) => b.targets.some((t) => t.id === providerId)) : buckets;+ if (providerId && scoped.length === 0) {+ return { ok: false, reason: `${providerId} does not draw its models from ${runtime.label}.`, models: [], updated: [] };+ }+ // No targets at all still runs one bare probe, so the Harnesses page can+ // report what the harness lists even with nothing to write it to.+ const groups = scoped.length ? scoped : [{ probeAs: null, targets: [] }];// The SAME injected runner answers the availability probe, so a caller (and a// test) drives one child-process boundary rather than two. Cache-respecting:// the page rendered from a probe seconds ago, and re-spawning the binary for// a 15s worst case ahead of the 45s models probe would double the wait on a// user-facing button. A binary that broke since then still refuses below.- // Skipped entirely for a credentialed harness: it is reached through its- // bootstrap CLI and need not be on PATH, so the probe would spawn a binary to- // answer a question it would answer wrongly.- if (!credentialed) {- const status = await getProviderRuntimeStatus(runtime.id, { ...probeDeps, probeCommand: run });- if (!status?.installed) {- return { ok: false, reason: `${runtime.label} is not installed on this host.`, models: [], updated: [] };- }- }+ // Asked only when a BARE probe will run: a credentialed harness is reached+ // through its bootstrap CLI and need not be on PATH, so a missing binary is+ // that bucket's refusal alone and never the credentialed buckets'.+ const notInstalled = `${runtime.label} is not installed on this host.`;+ const probesBare = groups.some((group) => !group.probeAs);+ const installed = probesBare+ ? Boolean((await getProviderRuntimeStatus(runtime.id, { ...probeDeps, probeCommand: run }))?.installed)+ : false;// `opencode models` prints from an on-disk catalog OpenCode refreshes on its// own — silently, and not at all on a host where its fetch fails (see// `lib/opencodeCatalogCache.js`). Without this the button faithfully re-reads// a catalog frozen weeks ago and reports success, while the same account on// another machine lists models this one has never heard of. Best-effort by- // design: a refusal or a failed fetch leaves the probe below unchanged.- if (runtime.id === 'opencode') {+ // design: a refusal or a failed fetch leaves the probes below unchanged.+ // Gated on a probe actually being able to run, so the refusal below doesn't+ // first pay for a catalog nothing is going to read.+ if (runtime.id === 'opencode' && (installed || groups.some((group) => group.probeAs))) {const catalog = await primeOpencodeCatalogCache();console.log(`📚 ${runtime.label} catalog: ${catalog.primed ? 'refreshed' : 'left alone'} — ${catalog.reason}`);}- // Resolve exactly as the version probe does. An npm-installed harness is a- // `.cmd` shim on Windows, which `execFile` under `shell: false` refuses- // outright — the probe would answer nothing and the page would tell a- // signed-in user to go sign in. A credentialed harness skips the PATH walk- // (it need not be there); `resolveCliSpawn` resolves the bootstrap binary's- // own shim instead.- const resolved = credentialed ? null : await findCommand(runtime.command);- const probe = resolveCliSpawn(credentialed, resolved || runtime.command, [...runtime.modelsArgs], process.env);- const stdout = await run(probe.command, probe.args, { timeoutMs: MODELS_PROBE_TIMEOUT_MS });- const models = parseHarnessModels(runtime.id, stdout);- if (models.length === 0) {+ // Probe every bucket CONCURRENTLY: each is a distinct child with its own 45s+ // cap, so running them in series would make the Harnesses page button cost+ // one timeout per credential. Only the WRITES have to be serialized, and they+ // stay so in the apply pass below.+ const probed = await Promise.all(groups.map(async (group) => {+ if (!group.probeAs && !installed) return { group, failure: notInstalled };+ // Resolve exactly as the version probe does. An npm-installed harness is a+ // `.cmd` shim on Windows, which `execFile` under `shell: false` refuses+ // outright — the probe would answer nothing and the page would tell a+ // signed-in user to go sign in. A credentialed bucket skips the PATH walk+ // (its harness need not be there); `resolveCliSpawn` resolves the bootstrap+ // binary's own shim instead.+ const resolved = group.probeAs ? null : await findCommand(runtime.command);+ const probe = resolveCliSpawn(group.probeAs, resolved || runtime.command, [...runtime.modelsArgs], process.env);+ const listed = parseHarnessModels(runtime.id, await run(probe.command, probe.args, { timeoutMs: MODELS_PROBE_TIMEOUT_MS }));+ if (listed.length > 0) return { group, listed };// Name what RAN, and only send the user to a terminal when a terminal could// help: a credentialed harness mints its own auth and is not something they// can sign in to by hand.const ran = `\`${probe.command} ${probe.args.join(' ')}\` returned no models.`;- return {- ok: false,- reason: credentialed ? ran : `${ran} Sign in to ${runtime.label} in a terminal, then try again.`,- models: [],- updated: [],- };- }+ return { group, failure: group.probeAs ? ran : `${ran} Sign in to ${runtime.label} in a terminal, then try again.` };+ }));+ const seen = new Set();const updated = [];- for (const provider of targets) {- // Hold the record's namespace scope (see `storedNamespaces`). A filter that- // matched nothing means the harness no longer lists anything this record is- // for — skip it rather than blanking a working list on that evidence.- const scope = storedNamespaces(provider);- const scoped = scope.size === 0- ? models- : models.filter((id) => scope.has(id.slice(0, id.indexOf('/'))));- if (scoped.length === 0) {- console.log(`⏭️ ${runtime.label}: ${provider.id} lists no models in its own namespace — left alone`);+ const failures = [];+ for (const { group, listed, failure } of probed) {+ if (failure) {+ failures.push(failure);continue;}- // A `*-configured-default` sentinel is NOT a model the vendor will ever- // print — it is the "send no --model, let the CLI use its own default"- // marker (`resolveCliModel` maps it to null). Dropping it would silently- // repin an agy/grok wrapper onto a concrete model AND remove the option- // from the editor's picker, which renders it from this same list. So it- // survives the rewrite rather than reading as an orphaned id.- const next = [...(provider.models || []).filter(isConfiguredDefaultModel), ...scoped];- // A stored default the harness no longer lists would leave the record- // pinned to a model its own picker cannot show. Keep it when it survived- // the refresh, otherwise fall to the first id (sentinel first when there- // is one, then whatever the vendor listed newest-first).- const defaultModel = next.includes(provider.defaultModel) ? provider.defaultModel : next[0];- // Serialized rather than batched: each write is a read-modify-write of the- // same providers.json, and Promise.all would have them clobber each other.- await providerService.updateProvider(provider.id, { models: next, defaultModel });- updated.push(provider.id);+ for (const model of listed) seen.add(model);+ updated.push(...await applyHarnessCatalog(runtime, listed, group.targets));}++ // `reason` rides along on a PARTIAL success too: with one bucket probed per+ // credential, the caller that asked on behalf of ONE record (the provider+ // card's button, which checks `updated` for its own id) needs the message+ // from the bucket that failed, not silence because another bucket answered.+ const reason = failures.length ? failures.join(' ') : undefined;+ const models = [...seen];+ if (models.length === 0) return { ok: false, reason, models: [], updated: [] };console.log(`🔄 ${runtime.label}: ${models.length} models → ${updated.length} provider(s)`);- return { ok: true, models, updated };+ return { ok: true, reason, models, updated };}diff --git a/server/services/harnesses.test.js b/server/services/harnesses.test.jsindex cf2a4edaff..477421a2ed 100644--- a/server/services/harnesses.test.js+++ b/server/services/harnesses.test.js@@ -251,18 +251,100 @@ describe('refreshHarnessModels', () => {expect(run).toHaveBeenCalledWith('token-cli', ['run', 'opencode-harness', '--', 'models'], expect.anything());});- // One probe cannot serve two credentials, so a mix runs bare rather than- // handing one record's token to another record's refresh.- it('probes bare when only some write targets carry a bootstrap', async () => {- const run = vi.fn(async (command, args) => (args[0] === 'models' ? OPENCODE_MODELS : '1.18.27'));+ // Catches the AMBIENT account's catalog being written onto a credentialed+ // record — what a single bare probe did whenever the targets disagreed, which+ // on a stock install is always (the shipped OpenCode Zen pair carries none).+ it('probes once per credential and keeps each bucket’s catalog to its own records', async () => {+ const run = vi.fn(async (command, args) => {+ if (!args.includes('models')) return '1.18.27';+ return command === 'token-cli' ? 'opencode/private-a\n' : OPENCODE_MODELS;+ });providerService.listProviders.mockResolvedValue([{ id: 'boot-cli', type: 'cli', command: 'opencode', models: [], credentialBootstrap: { command: 'token-cli' } },{ id: 'plain-cli', type: 'cli', command: 'opencode', models: [] },]);- await refreshHarnessModels('opencode', { run, ...found });+ const result = await refreshHarnessModels('opencode', { run, ...found });+ expect(run).toHaveBeenCalledWith('token-cli', ['opencode', 'models'], expect.anything());expect(run).toHaveBeenCalledWith('/example/opencode', ['models'], expect.anything());+ expect(result.updated.sort()).toEqual(['boot-cli', 'plain-cli']);+ // The credentialed record gets ONLY what its own credential listed.+ expect(providerService.updateProvider).toHaveBeenCalledWith('boot-cli',+ expect.objectContaining({ models: ['opencode/private-a'] }));+ expect(providerService.updateProvider).toHaveBeenCalledWith('plain-cli',+ expect.objectContaining({ models: ['opencode/big-pickle', 'opencode/mimo-v2.5-free'] }));+ });++ // Catches a card's button spawning an unrelated record's bootstrap CLI —+ // minting a credential and hitting its proxy on a click not about it.+ it('probes only the clicked record’s bucket when scoped by providerId', async () => {+ const run = vi.fn(async (command, args) => (args.includes('models') ? `opencode/from-${command}\n` : '1.18.27'));+ providerService.listProviders.mockResolvedValue([+ { id: 'boot-cli', type: 'cli', command: 'opencode', models: [], credentialBootstrap: { command: 'token-cli' } },+ { id: 'plain-cli', type: 'cli', command: 'opencode', models: [] },+ ]);++ const result = await refreshHarnessModels('opencode', { run, providerId: 'plain-cli', ...found });++ expect(result.updated).toEqual(['plain-cli']);+ expect(run).not.toHaveBeenCalledWith('token-cli', expect.anything(), expect.anything());+ });++ // Two accounts: neither may be refreshed from the other's catalog.+ it('probes each distinct bootstrap separately', async () => {+ const run = vi.fn(async (command, args) => (args.includes('models') ? `opencode/from-${command}\n` : '1.18.27'));+ providerService.listProviders.mockResolvedValue([+ { id: 'a-cli', type: 'cli', command: 'opencode', models: [], credentialBootstrap: { command: 'token-a' } },+ { id: 'b-cli', type: 'cli', command: 'opencode', models: [], credentialBootstrap: { command: 'token-b' } },+ ]);++ await refreshHarnessModels('opencode', { run, findCommand: async () => null });++ expect(providerService.updateProvider).toHaveBeenCalledWith('a-cli',+ expect.objectContaining({ models: ['opencode/from-token-a'] }));+ expect(providerService.updateProvider).toHaveBeenCalledWith('b-cli',+ expect.objectContaining({ models: ['opencode/from-token-b'] }));+ });++ // Catches a bucket that answered nothing reading as a clean success for the+ // records it was supposed to write.+ it('reports the failing bucket’s reason on a partial success', async () => {+ const run = vi.fn(async (command, args) => {+ if (!args.includes('models')) return '1.18.27';+ return command === 'token-cli' ? '' : OPENCODE_MODELS;+ });+ providerService.listProviders.mockResolvedValue([+ { id: 'boot-cli', type: 'cli', command: 'opencode', models: [], credentialBootstrap: { command: 'token-cli' } },+ { id: 'plain-cli', type: 'cli', command: 'opencode', models: [] },+ ]);++ const result = await refreshHarnessModels('opencode', { run, ...found });++ expect(result.ok).toBe(true);+ expect(result.updated).toEqual(['plain-cli']);+ expect(result.reason).toContain('token-cli opencode models');+ // Nothing to sign into by hand — a bootstrap CLI mints its own credential.+ expect(result.reason).not.toContain('Sign in');+ });++ // The credentialed records reach their harness through the bootstrap CLI, so+ // a missing binary is the bare bucket's refusal alone.+ it('keeps a missing binary from failing the credentialed bucket', async () => {+ const run = vi.fn(async (command, args) => {+ if (!args.includes('models')) return null; // version probe: not installed+ return 'opencode/private-a\n';+ });+ providerService.listProviders.mockResolvedValue([+ { id: 'boot-cli', type: 'cli', command: 'opencode', models: [], credentialBootstrap: { command: 'token-cli' } },+ { id: 'plain-cli', type: 'cli', command: 'opencode', models: [] },+ ]);++ const result = await refreshHarnessModels('opencode', { run, findCommand: async () => null });++ expect(result.updated).toEqual(['boot-cli']);+ expect(result.reason).toContain('is not installed on this host');+ expect(run).not.toHaveBeenCalledWith('opencode', ['models'], expect.anything());});it('writes the harness catalog only to providers that draw from it', async () => {