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: convert the remaining shipped provider presets on boot backfill (#8159)
[._.]/ Adam Eivy2931f857d33b
diff --git a/server/lib/providerConnections.js b/server/lib/providerConnections.jsindex 607aaf9cd9..bd13aefac1 100644--- a/server/lib/providerConnections.js+++ b/server/lib/providerConnections.js@@ -181,6 +181,18 @@ export function providerConnectionProfile(provider) {if (baseUrl) transports[protocol] = { baseUrl };+ // A wrapper pointed straight at a local daemon's Anthropic-compatible port+ // (the base URL an ANTHROPIC_BASE_URL/OPENAI_BASE_URL env var names) can ALSO+ // carry its own `endpoint` field naming the daemon's OpenAI-compatible+ // listing — deliberately a different URL (Claude SGLang, #8159), read by the+ // readiness probe and by any OTHER harness materialized onto the same+ // service. Declared as a second transport rather than folded into `baseUrl`+ // above, so a connection built from this record states BOTH wires it knows+ // about instead of losing the one the env var did not already capture.+ if (protocol !== 'openai' && isNonBlankStr(record.endpoint) && record.endpoint !== baseUrl) {+ transports.openai = { baseUrl: record.endpoint };+ }+// A record fronting a local daemon or a bare API endpoint MUST name where it// is. Falling back to a conventional default here would silently equate two// installs' different daemons, so an undeclared endpoint isolates instead.diff --git a/server/lib/providerPresets.js b/server/lib/providerPresets.jsindex add52b4c34..94f02e4b14 100644--- a/server/lib/providerPresets.js+++ b/server/lib/providerPresets.js@@ -276,7 +276,17 @@ const orNull = (value) => value ?? null;*/export function derivedPresetDrift(record, derived, harness) {const drift = [];- for (const key of ['type', 'command', ...BACKEND_MARKER_KEYS]) {+ // A `*Backed`/`gatewayBacked` marker is read back by `localRuntimeNamespace`+ // to give a WRAPPER command its local namespace; `materializeRoute` writes+ // one onto every local-runtime composition regardless, including a direct+ // `type: 'api'` record that spawns nothing and never reads it. The shipped+ // `ollama` / `lmstudio` / `mtplx` samples predate the graph and carry none,+ // so comparing markers on a recipe-less (direct) harness would refuse a+ // fixpoint conversion over a field the record's own execution path ignores+ // (#8159). A WRAPPER's marker still participates — it is what makes+ // `opencode-orcarouter`'s legacy `orcarouterBacked` a real drift.+ const markerKeys = harness.recipe ? BACKEND_MARKER_KEYS : [];+ for (const key of ['type', 'command', ...markerKeys]) {if (!isDeepStrictEqual(orNull(record[key]), orNull(derived[key]))) drift.push(key);}// A wrapper that names its endpoint only inside its env or inline config@@ -335,6 +345,66 @@ export function derivedPresetPatch(record, derived) {return patch;}+/**+ * The backfill verdict for ONE legacy record already resolved onto the graph+ * — the additive structural patch when re-deriving it from `connection` is a+ * FIXPOINT, or the reason it stays legacy. Pulled out of `planPresetBackfill`'s+ * loop body (#8159) so a caller that already knows which route/connection a+ * record sits on can ask the exact same question about just THAT record,+ * without rebuilding the whole-graph maps `planPresetBackfill` needs to+ * resolve every record at once. `providerGraph.js`'s+ * `refreshPresetSkipReasonsForConnection` is the worked example: a connection+ * SETTINGS edit changes what this verdict answers for every legacy route on+ * that one connection, without writing `providers.json` (so it never triggers+ * the reconcile pass that would otherwise keep `presetSkipReason` current).+ *+ * `route`, `connection` and `instance` arrive pre-resolved (a caller looping+ * over many records resolves an instance once per connection; a single-record+ * caller resolves it inline) rather than re-read here, so this function stays+ * pure over its inputs.+ *+ * @param {object} record - a LEGACY provider record (caller has already+ * excluded a derived preset)+ * @param {{route: object|null, connection: object|null, instance: object|null,+ * bootstraps?: object, env?: object}} resolved+ * @returns {{patch: object, reason: null} | {patch: null, reason: string}}+ */+export function presetBackfillVerdict(record, { route, connection, instance, bootstraps = {}, env = process.env }) {+ const refuse = (reason) => ({ patch: null, reason });+ if (!route) return refuse('unmapped');+ if (!connection?.slug) return refuse('service-unnamed');+ if (!instance) return refuse('service-undefined');+ const harness = harnessForProvider(record);+ if (!harness) return refuse('harness-unknown');+ if (!spawnsRecipeBinary(record, harness)) return refuse('command-differs');++ const match = matchBootstrapApp(record.credentialBootstrap, harness, bootstraps);+ if (record.credentialBootstrap?.command && !match) return refuse('bootstrap-unmatched');+ const structural = {+ harnessId: harness.id,+ method: record.type,+ serviceId: connection.slug,+ ...(match ? { credentialBootstrapId: match.slug } : {}),+ };+ const listed = listedModels(instance, connection.catalog);+ const models = Array.isArray(record.models) ? record.models : [];+ if (listed.length > 0 && !isDeepStrictEqual(listed, models) && models.every((model) => listed.includes(model))) {+ structural.catalogNarrowing = [...models];+ }++ const { record: derived, error } = materializeDerivedPreset({+ record: { ...record, ...structural },+ harness,+ instance,+ catalog: connection.catalog,+ bootstrap: match ? bootstrapInputFor(match.slug, match.app) : null,+ });+ if (error) return refuse(error.code);+ const drift = derivedPresetDrift(record, derived, harness);+ if (drift.length > 0) return refuse(`drift:${drift.join(',')}`);+ return { patch: structural, reason: null };+}+/*** The boot-time backfill (#7565): every LEGACY record the graph already routes* onto a named service instance, stamped with the structural keys that make it@@ -348,7 +418,10 @@ export function derivedPresetPatch(record, derived) {* Row-derived, idempotent (a stamped record is skipped) and never a seed:* it needs the graph, so it rides the reconcile pass exactly as the* service-column backfill does. Everything it refuses is reported with a- * reason so a human can see why a record stayed legacy.+ * reason so a human can see why a record stayed legacy — the per-record rule+ * is {@link presetBackfillVerdict}; this loop only resolves each record onto+ * the graph (caching one service instance per connection across mode+ * siblings) and collects the verdicts.** @param {{graph: {connections: object[], bindings: object[], routes: object[]},* providers: object[], bootstraps?: object, env?: object}} input@@ -369,42 +442,12 @@ export function planPresetBackfill({ graph, providers, bootstraps = {}, env = prfor (const record of providers) {if (!record || typeof record !== 'object' || !record.id || isDerivedPreset(record)) continue;- const skip = (reason) => skipped.push({ id: record.id, reason });- const route = routes.get(record.id);- if (!route) { skip('unmapped'); continue; }- const connection = connections.get(bindings.get(route.bindingId)?.connectionId);- if (!connection?.slug) { skip('service-unnamed'); continue; }- const instance = instanceFor(connection);- if (!instance) { skip('service-undefined'); continue; }- const harness = harnessForProvider(record);- if (!harness) { skip('harness-unknown'); continue; }- if (!spawnsRecipeBinary(record, harness)) { skip('command-differs'); continue; }-- const match = matchBootstrapApp(record.credentialBootstrap, harness, bootstraps);- if (record.credentialBootstrap?.command && !match) { skip('bootstrap-unmatched'); continue; }- const structural = {- harnessId: harness.id,- method: record.type,- serviceId: connection.slug,- ...(match ? { credentialBootstrapId: match.slug } : {}),- };- const listed = listedModels(instance, connection.catalog);- const models = Array.isArray(record.models) ? record.models : [];- if (listed.length > 0 && !isDeepStrictEqual(listed, models) && models.every((model) => listed.includes(model))) {- structural.catalogNarrowing = [...models];- }-- const { record: derived, error } = materializeDerivedPreset({- record: { ...record, ...structural },- harness,- instance,- catalog: connection.catalog,- bootstrap: match ? bootstrapInputFor(match.slug, match.app) : null,- });- if (error) { skip(error.code); continue; }- const drift = derivedPresetDrift(record, derived, harness);- if (drift.length > 0) { skip(`drift:${drift.join(',')}`); continue; }- patches[record.id] = structural;+ const route = routes.get(record.id) ?? null;+ const connection = route ? connections.get(bindings.get(route.bindingId)?.connectionId) ?? null : null;+ const instance = connection?.slug ? instanceFor(connection) : null;+ const { patch, reason } = presetBackfillVerdict(record, { route, connection, instance, bootstraps, env });+ if (reason) { skipped.push({ id: record.id, reason }); continue; }+ patches[record.id] = patch;}return { patches, skipped };}diff --git a/server/lib/providerPresets.test.js b/server/lib/providerPresets.test.jsindex 8cb9b57017..b09826d124 100644--- a/server/lib/providerPresets.test.js+++ b/server/lib/providerPresets.test.js@@ -160,7 +160,7 @@ describe('planPresetBackfill over the shipped samples', () => {const { patches, skipped } = planPresetBackfill({ graph, providers, bootstraps: {}, env: {} });it('stamps every routed record whose re-derivation is a fixpoint, with the structural keys only', () => {- expect(Object.keys(patches).length).toBeGreaterThanOrEqual(30);+ expect(Object.keys(patches).length).toBeGreaterThanOrEqual(35);for (const patch of Object.values(patches)) {expect(Object.keys(patch).every((key) => PRESET_STRUCTURAL_KEYS.includes(key))).toBe(true);expect(patch).toMatchObject({ harnessId: expect.any(String), method: expect.any(String), serviceId: expect.any(String) });@@ -171,6 +171,26 @@ describe('planPresetBackfill over the shipped samples', () => {expect(patches.slotstream).toMatchObject({ harnessId: 'direct', method: 'api' });});+ // #8159: the remaining shipped samples the boot backfill left legacy.+ it('stamps Claude-on-SGLang now that the graph import names its OpenAI endpoint too', () => {+ // Claude Code reads `ANTHROPIC_BASE_URL` (the server root); the graph+ // import used to keep only that transport, so the derived `endpoint` (read+ // from the connection's `openai` transport) came back null against the+ // record's own OpenAI-compatible `endpoint` field.+ expect(patches['claude-sglang']).toMatchObject({ harnessId: 'claude', method: 'cli' });+ expect(patches['claude-sglang-tui']).toMatchObject({ harnessId: 'claude', method: 'tui' });+ expect(patches['claude-sglang-tui'].serviceId).toBe(patches['claude-sglang'].serviceId);+ });++ it('stamps the direct-API local-runtime samples, whose shipped records carry no *Backed marker', () => {+ // `materializeRoute` used to write `ollamaBacked`/`lmstudioBacked`/+ // `mtplxBacked` even onto a direct `type: 'api'` record that never reads+ // it, so every re-derivation drifted on a marker the shipped file never had.+ expect(patches.ollama).toMatchObject({ harnessId: 'direct', method: 'api' });+ expect(patches.lmstudio).toMatchObject({ harnessId: 'direct', method: 'api' });+ expect(patches.mtplx).toMatchObject({ harnessId: 'direct', method: 'api' });+ });+it('derives the keyless Zen CLI/TUI pair on the free plan, big-pickle included', () => {// OpenCode serves Zen's free tier signed out, so an unset OPENCODE_API_KEY// is not a refusal, and the free-plan filter keeps the bare stealth model.@@ -187,10 +207,18 @@ describe('planPresetBackfill over the shipped samples', () => {it('leaves each unmappable or drifting record legacy with a reason, never a guess', () => {const reasons = Object.fromEntries(skipped.map(({ id, reason }) => [id, reason]));+ // Pi signs in itself; the vendor connection maps to no service definition.expect(reasons['pi-cli']).toBe('service-undefined');+ expect(reasons['pi-tui']).toBe('service-undefined');+ // Kilo/OpenChamber compose onto nothing — no harness bindings at all.expect(reasons['kilo-cli']).toBe('service-undefined');- // The legacy per-gateway marker is not what a service writes.+ expect(reasons['kilo-tui']).toBe('service-undefined');+ expect(reasons['openchamber-cli']).toBe('service-undefined');+ // The legacy per-gateway marker is not what a service writes, and the+ // `orcarouter/`-namespaced models are not the catalog's own names — kept+ // on the legacy marker on purpose (scripts/generate-provider-samples.js).expect(reasons['opencode-orcarouter']).toMatch(/^drift:.*orcarouterBacked/);+ expect(reasons['opencode-orcarouter-tui']).toMatch(/^drift:.*orcarouterBacked/);for (const id of Object.keys(reasons)) expect(patches).not.toHaveProperty(id);});diff --git a/server/lib/providerRouteRecipes.js b/server/lib/providerRouteRecipes.jsindex e3ac323c35..dd3042e0d9 100644--- a/server/lib/providerRouteRecipes.js+++ b/server/lib/providerRouteRecipes.js@@ -334,6 +334,17 @@ export function mintRouteIds({ harnessId, kind, modes, taken }) {* so the spawner and `providerConnectionProfile` classify it onto that service:* the runtime's `*Backed` boolean, or `gatewayBacked: '<id>'`. Slotstream and* a plain API endpoint carry none, exactly as {@link connectionKindMarkers}.+ *+ * Written unconditionally, including onto a direct `type: 'api'` record — the+ * round-trip contract `materializeRoute` owes (`routeDescribesService`) needs+ * it there too: `localRuntimeKind`'s id/port fallback only covers `ollama` /+ * `lmstudio` (by id, name or default port) and `mtplx` (by id alone, and only+ * when the record's id is literally `mtplx`), never `llama` / `vllm` /+ * `sglang`, and a freshly minted direct record's id is `direct.api@<slug>`,+ * not the shipped sample's own id. A direct API preset's DRIFT check is what+ * ignores this marker instead (`derivedPresetDrift`, #8159) — the shipped+ * `ollama` / `lmstudio` / `mtplx` samples predate the graph and never carried+ * one, but nothing on the direct API path reads it either way.*/const serviceMarkers = (definition, { wrapper }) => {if (definition.localRuntime) return connectionKindMarkers(definition.localRuntime) || {};diff --git a/server/services/providerGraph.js b/server/services/providerGraph.jsindex 5e805f832c..ebb5f68c74 100644--- a/server/services/providerGraph.js+++ b/server/services/providerGraph.js@@ -32,6 +32,7 @@ import {derivedPresetPatch,materializeDerivedPreset,planPresetBackfill,+ presetBackfillVerdict,} from '../lib/providerPresets.js';import { effortLevelsForProvider } from '../lib/providerModels.js';import {@@ -302,6 +303,43 @@ export async function rematerializeDerivedPresets(connection, { providerIds = nureturn written;}+/**+ * Refresh the cached preset-conversion verdict — {@link presetSkipReason} —+ * for every LEGACY (not yet derived) record routed on `connection`, against+ * `connection` AS JUST SAVED (#8159).+ *+ * `presetSkipReasons` is otherwise updated only by a full reconcile pass+ * (`reconcilePass`, on boot or a `providers.json` write), so a connection+ * SETTINGS edit — which changes nothing `onProvidersSaved` watches — left the+ * "Convert to derived preset" gate answering against whatever the connection+ * looked like at the last pass. Scoped to `connection`'s own routes rather+ * than a whole-graph {@link planPresetBackfill}, because no OTHER route's+ * verdict can have changed from this edit; and to {@link presetBackfillVerdict}+ * rather than a write, because this is a read-cache refresh, not a conversion+ * — an eligible record still needs its own reconcile pass or explicit+ * "Convert" action to actually stamp.+ */+async function refreshPresetSkipReasonsForConnection(graph, connection) {+ const boundBindings = new Set(+ graph.bindings.filter((binding) => binding.connectionId === connection.id).map((binding) => binding.id),+ );+ const routes = graph.routes.filter((route) => boundBindings.has(route.bindingId));+ if (routes.length === 0) return;+ const { providers } = await providerService().getAllProviders();+ const byId = new Map(providers.map((record) => [record.id, record]));+ const legacy = routes+ .map((route) => ({ route, record: byId.get(route.providerId) }))+ .filter(({ record }) => record && typeof record === 'object' && !isDerivedPreset(record));+ if (legacy.length === 0) return;+ const instance = instanceForConnection(connection, process.env);+ const bootstraps = await bootstrapApps();+ for (const { route, record } of legacy) {+ const { reason } = presetBackfillVerdict(record, { route, connection, instance, bootstraps, env: process.env });+ if (reason) presetSkipReasons.set(record.id, reason);+ else presetSkipReasons.delete(record.id);+ }+}+/*** A binding moved between instances (link, unlink): the derived presets on its* routes now sit on `connection` and must say so. One re-derivation from the@@ -708,10 +746,15 @@ export function updateConnectionSettings({credentialVia: nextVia,};const revision = await saveConnectionSettings(next);+ const saved = { ...next, revision: revision ?? next.revision };const applied = await projectRoutes(routes.map((route) => route.providerId), next);// The derived presets on this instance follow the whole row, not only the// profile-owned half the projection carried (#7565).- const rederived = await rematerializeDerivedPresets({ ...next, revision: revision ?? next.revision });+ const rederived = await rematerializeDerivedPresets(saved);+ // This connection's still-legacy routes may have just become convertible,+ // or stopped being — keep `presetSkipReason` current rather than leaving+ // it to the next full reconcile pass, which this write never triggers (#8159).+ await refreshPresetSkipReasonsForConnection(graph, saved);console.log(`🔗 Updated connection ${connection.id} (${applied.length} routes projected, ${rederived.length} presets re-derived)`);return { connectionId: connection.id, revision, affectedRouteIds: [...new Set([...applied, ...rederived])] };});diff --git a/server/services/providerGraph.test.js b/server/services/providerGraph.test.jsindex 26a6bad665..9b63ba1c29 100644--- a/server/services/providerGraph.test.js+++ b/server/services/providerGraph.test.js@@ -23,6 +23,7 @@ const store = {relinkBinding: vi.fn().mockResolvedValue(undefined),deleteConnection: vi.fn(),detachBindingToConnection: vi.fn().mockResolvedValue(undefined),+ saveConnectionSettings: vi.fn().mockResolvedValue(2),};vi.mock('./providerGraphStore.js', () => store);@@ -34,6 +35,11 @@ vi.mock('../lib/aiToolkitState.js', () => ({requireToolkit: () => ({ services: { providers } }),}));+// `updateConnectionSettings` re-derives every DERIVED preset on the row it+// just saved, which reads the bootstrap-apps table — kept doubled and empty+// so this file never reaches `settings.js`'s real file store.+vi.mock('./credentialBootstrapApps.js', () => ({ listCredentialBootstraps: vi.fn().mockResolvedValue({}) }));+const graph = await import('./providerGraph.js');const CONN_A = '11111111-1111-4111-8111-111111111111';@@ -206,6 +212,49 @@ describe('reconciliation', () => {});});+describe('connection settings keep the preset-conversion cache live (#8159)', () => {+ it('updates presetSkipReason for this connection\'s legacy routes on the SAME write, not the next reconcile pass', async () => {+ // The connection's base URL does not yet match the routed legacy+ // record's own ANTHROPIC_BASE_URL, so the boot pass leaves it legacy —+ // re-deriving it would rewrite the env var it already carries.+ const fixture = graphFixture();+ fixture.connections[0] = connection(CONN_A, 'http://127.0.0.1:19999', 'ollama');+ store.readGraph.mockResolvedValue(fixture);+ const { harnessId, method, serviceId, ...legacy } = structuredClone(CLAUDE);+ providers.getAllProviders.mockResolvedValue({ activeProvider: 'claude-ollama', providers: [legacy] });++ await graph.initProviderGraph();+ expect(graph.presetSkipReason('claude-ollama')).toMatch(/^drift:/);++ // Fixing the connection's own base URL makes re-deriving the record a+ // fixpoint. A connection-settings edit never writes `providers.json`, so+ // `onProvidersSaved` never fires and no reconcile pass runs — the cache+ // must still answer correctly right after THIS write.+ await graph.updateConnectionSettings({+ connectionId: CONN_A, expectedRevision: 1, transports: { anthropic: { baseUrl: 'http://127.0.0.1:11434' } },+ });+ expect(graph.presetSkipReason('claude-ollama')).toBeNull();++ // And the reverse: moving the connection back off the record's own+ // ANTHROPIC_BASE_URL makes it drift again, live, the same way.+ await graph.updateConnectionSettings({+ connectionId: CONN_A, expectedRevision: 1, transports: { anthropic: { baseUrl: 'http://127.0.0.1:19999' } },+ });+ expect(graph.presetSkipReason('claude-ollama')).toMatch(/^drift:/);+ });++ it('leaves an unrelated connection\'s cached verdict untouched', async () => {+ await graph.initProviderGraph();+ expect(graph.presetSkipReason('claude-ollama')).toBeNull();+ // CONN_B carries no routes in the fixture, so this is a no-op scan, not a+ // crash on an empty route list.+ await expect(graph.updateConnectionSettings({+ connectionId: CONN_B, expectedRevision: 1, label: 'Renamed',+ })).resolves.toMatchObject({ connectionId: CONN_B });+ expect(graph.presetSkipReason('claude-ollama')).toBeNull();+ });+});+describe('linking', () => {beforeEach(() => graph.initProviderGraph());