Skip to content

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

fix: keep a multi-transport connection intact through reconciliation (#6452)

[._.]/ Adam Eivy199a31b8a4b1
diff --git a/server/lib/providerGraphRecords.js b/server/lib/providerGraphRecords.js
index 35716c0d8b..da07fc33e7 100644
--- a/server/lib/providerGraphRecords.js
+++ b/server/lib/providerGraphRecords.js
@@ -246,13 +246,65 @@ export const toConnectionDto = (connection) =>
/** The connection-owned half of one provider record, as stored in a snapshot. */
export const connectionOwnedSnapshot = (provider) => providerConnectionProfile(provider).owned;
-/** The identity a connection row asserts, secrets included. Server-side only. */
+/**
+ * The identity one ROUTE's profile asserts, secrets included. Server-side only.
+ *
+ * Two routes sharing this key describe the same backend as each other, which is
+ * what keeps a binding's modes together and splits them once they diverge.
+ * Whether a route still belongs on a STORED connection is a different question
+ * — see {@link routeBelongsOnConnection}.
+ */
const identityKey = ({ kind, transports, credentials }) => JSON.stringify([
kind,
Object.entries(transports || {}).sort(([a], [b]) => a.localeCompare(b)),
Object.entries(credentials || {}).sort(([a], [b]) => a.localeCompare(b)),
]);
+/**
+ * Whether a stored connection still CONTAINS the backend a route describes.
+ *
+ * A provider record names exactly one endpoint, so a route's profile always
+ * reports exactly one transport — while a connection a human linked across
+ * protocols declares one per protocol (an Ollama daemon reached by Claude on
+ * its Anthropic port and by Codex on its `/v1` port is ONE backend). Demanding
+ * {@link identityKey} equality here would therefore match none of a
+ * multi-transport row's own routes and clone every binding off it, silently
+ * undoing the explicit link the connection graph exists to hold.
+ *
+ * Containment, precisely:
+ *
+ * - `kind` matches exactly — a route never migrates between backend kinds.
+ * - The route's transport protocol is DECLARED by the connection at the same
+ * `baseUrl`. A route declaring no transport at all matches only a
+ * connection that declares none either: "names no endpoint" must never
+ * collapse into "sits on whichever backend you like".
+ * - The route's credentials are a SUBSET of the connection's, with every
+ * shared key equal. A row carrying one key per protocol is normal (Claude
+ * sends a token where OpenCode sends none); disagreeing on a key they share
+ * is a real move, and still detaches.
+ *
+ * `sameConnectionIdentity` stays strict on purpose: it answers "are these two
+ * records the same backend?" at IMPORT time, where equality is what stops an
+ * accidental merge. This is the looser question reconciliation asks about a
+ * link a human already made.
+ */
+function routeBelongsOnConnection(profile, connection) {
+ if (!connection || profile.kind !== connection.kind) return false;
+ const declared = connection.transports || {};
+ const transports = Object.entries(profile.transports || {});
+ if (transports.length === 0) return Object.keys(declared).length === 0;
+ // Both sides must name a real URL. A row hand-edited into `{ anthropic: {} }`
+ // has no endpoint, and letting two absent values compare equal is exactly the
+ // collapse of "not set" into "matches" this rule exists to prevent.
+ const declaresSameEndpoint = ([protocol, transport]) => {
+ const url = declared[protocol]?.baseUrl;
+ return typeof url === 'string' && url !== '' && url === transport?.baseUrl;
+ };
+ if (!transports.every(declaresSameEndpoint)) return false;
+ const secrets = connection.credentials || {};
+ return Object.entries(profile.credentials || {}).every(([name, value]) => secrets[name] === value);
+}
+
/**
* Mint durable rows from a read-only preview.
*
@@ -410,26 +462,31 @@ export function planGraphReconciliation(graph, providers, { mintId = randomUUID
const binding = bindingsById.get(bindingId);
if (!binding) continue;
const stored = connectionsById.get(binding.connectionId) || null;
- const storedKey = stored ? identityKey(stored) : null;
const shared = (bindingsPerConnection.get(binding.connectionId) || 0) > 1;
- // Group this binding's routes by the connection each one now describes.
- const groups = new Map();
+ // Routes the stored connection still CONTAINS stay on it together, whether
+ // or not they describe it identically — that is what keeps a cross-protocol
+ // link alive. Every other route regroups by the backend it now names.
+ const onStored = [];
+ const moved = new Map();
for (const entry of entries) {
+ if (routeBelongsOnConnection(entry.profile, stored)) {
+ onStored.push(entry);
+ continue;
+ }
const key = identityKey(entry.profile);
- groups.set(key, [...(groups.get(key) || []), entry]);
+ moved.set(key, [...(moved.get(key) || []), entry]);
}
- // The group that KEEPS this binding is the one still matching the stored
+ // The group that KEEPS this binding is the one still on the stored
// connection; failing that, the largest, so the fewest routes are moved.
- const ordered = [...groups.values()].sort((a, b) => b.length - a.length);
- const keeperIndex = Math.max(0, ordered.findIndex((group) => identityKey(group[0].profile) === storedKey));
- const [keeper] = ordered.splice(keeperIndex, 1);
+ const ordered = [...moved.values()].sort((a, b) => b.length - a.length);
+ if (onStored.length > 0) ordered.unshift(onStored);
- for (const [index, group] of [keeper, ...ordered].entries()) {
+ for (const [index, group] of ordered.entries()) {
const isKeeper = index === 0;
const lead = group[0];
- const unchanged = isKeeper && storedKey === identityKey(lead.profile);
+ const unchanged = isKeeper && onStored.length > 0;
// A clone is required whenever the values changed AND the connection row
// is shared: editing it in place would silently repoint another harness.
const action = unchanged ? 'unchanged' : (isKeeper && !shared ? 'update' : 'clone');
@@ -458,8 +515,12 @@ export function planGraphReconciliation(graph, providers, { mintId = randomUUID
id: action === 'clone' ? mintId() : binding.connectionId,
kind: lead.profile.kind,
label: stored && isKeeper ? stored.label : String(lead.provider.name || lead.provider.id),
- transports: lead.profile.transports,
- credentials: lead.profile.credentials,
+ // An unchanged row is republished exactly AS STORED rather than
+ // narrowed to the single transport this route happens to name —
+ // otherwise "nothing moved" would still describe a backend the other
+ // harness on it cannot reach.
+ transports: unchanged ? stored.transports : lead.profile.transports,
+ credentials: unchanged ? stored.credentials : lead.profile.credentials,
catalog: unchanged ? stored.catalog : { state: models.length > 0 ? 'known' : 'unknown', models },
},
});
diff --git a/server/lib/providerGraphRecords.test.js b/server/lib/providerGraphRecords.test.js
index 5b7234f89b..ca3539688d 100644
--- a/server/lib/providerGraphRecords.test.js
+++ b/server/lib/providerGraphRecords.test.js
@@ -307,6 +307,135 @@ describe('reconciling after a downgrade edited providers.json', () => {
});
});
+describe('a connection several harnesses share through different protocols', () => {
+ // One local daemon reached by Claude on its Anthropic port and Codex on its
+ // OpenAI-compatible port, linked into ONE connection row. A provider record
+ // names one endpoint, so each route reports exactly one transport — the row
+ // therefore CONTAINS what its routes describe rather than equalling it, and a
+ // reconcile pass that demanded equality would clone every binding off it.
+ const DAEMON = 'http://127.0.0.1:11434';
+ const DAEMON_V1 = 'http://127.0.0.1:11434/v1';
+ const TOKEN = 'example-token';
+ const OPENAI_KEY = 'example-openai-key';
+
+ const CODEX_CLI = Object.freeze({
+ id: 'codex-ollama',
+ name: 'Codex on the example daemon',
+ type: 'cli',
+ command: 'codex',
+ ollamaBacked: true,
+ enabled: false,
+ models: ['example-model:8b'],
+ envVars: { OPENAI_BASE_URL: DAEMON_V1, OPENAI_API_KEY: OPENAI_KEY },
+ secretEnvVars: ['OPENAI_API_KEY'],
+ });
+
+ const CONNECTION = 'conn-shared';
+ const CLAUDE_BINDING = 'binding-claude';
+ const CODEX_BINDING = 'binding-codex';
+
+ const shared = () => {
+ const providers = [CLAUDE_CLI, CLAUDE_TUI, CODEX_CLI].map((record) => structuredClone(record));
+ const byId = new Map(providers.map((provider) => [provider.id, provider]));
+ const route = (providerId, bindingId, mode) => ({
+ providerId,
+ bindingId,
+ mode,
+ modelMap: { 'example-model:8b': 'example-model:8b' },
+ projected: connectionOwnedSnapshot(byId.get(providerId)),
+ pending: null,
+ pendingRevision: null,
+ });
+ return {
+ providers,
+ graph: {
+ connections: [{
+ id: CONNECTION,
+ revision: 3,
+ kind: 'ollama',
+ label: 'Example local daemon',
+ transports: { anthropic: { baseUrl: DAEMON }, openai: { baseUrl: DAEMON_V1 } },
+ credentials: { ANTHROPIC_AUTH_TOKEN: TOKEN, OPENAI_API_KEY: OPENAI_KEY },
+ catalog: { state: 'known', models: ['example-model:8b'] },
+ }],
+ bindings: [
+ {
+ id: CLAUDE_BINDING, revision: 4, connectionId: CONNECTION, harnessId: 'claude',
+ variantKey: 'default', label: 'Claude', enabled: true, selectedModels: ['example-model:8b'],
+ },
+ {
+ id: CODEX_BINDING, revision: 2, connectionId: CONNECTION, harnessId: 'codex',
+ variantKey: 'default', label: 'Codex', enabled: false, selectedModels: [],
+ },
+ ],
+ routes: [
+ route('claude-ollama', CLAUDE_BINDING, 'cli'),
+ route('claude-ollama-tui', CLAUDE_BINDING, 'tui'),
+ route('codex-ollama', CODEX_BINDING, 'cli'),
+ ],
+ },
+ };
+ };
+
+ it('survives a reconcile pass with every binding still on it', () => {
+ const { providers, graph } = shared();
+ const plan = planGraphReconciliation(graph, providers, { mintId: minter('new') });
+
+ expect(reconciliationIsNoop(plan)).toBe(true);
+ expect(plan.regroups.every((regroup) => regroup.connectionAction === 'unchanged')).toBe(true);
+ for (const regroup of plan.regroups) expect(regroup.connection.id).toBe(CONNECTION);
+ // The row keeps BOTH protocols: a single-transport route must never narrow
+ // the backend the other harness reaches.
+ for (const regroup of plan.regroups) {
+ expect(Object.keys(regroup.connection.transports).sort()).toEqual(['anthropic', 'openai']);
+ }
+ });
+
+ it('still detaches the one harness whose base URL genuinely moved', () => {
+ const { providers, graph } = shared();
+ for (const id of ['claude-ollama', 'claude-ollama-tui']) {
+ providers.find((provider) => provider.id === id).envVars.ANTHROPIC_BASE_URL = 'http://127.0.0.1:12345';
+ }
+
+ const plan = planGraphReconciliation(graph, providers, { mintId: minter('new') });
+ const claude = plan.regroups.find((regroup) => regroup.routeIds.includes('claude-ollama'));
+ // Shared, so the moved harness gets its own row instead of repointing Codex.
+ expect(claude.connectionAction).toBe('clone');
+ expect(claude.connection.id).not.toBe(CONNECTION);
+ expect(claude.bindingId).toBe(CLAUDE_BINDING);
+ // Codex never noticed.
+ const codex = plan.regroups.find((regroup) => regroup.routeIds.includes('codex-ollama'));
+ expect(codex.connectionAction).toBe('unchanged');
+ expect(codex.connection.id).toBe(CONNECTION);
+ });
+
+ it('detaches a route whose credential disagrees with the shared one', () => {
+ // A subset is normal — two protocols, two keys. A route claiming a
+ // DIFFERENT value for a key the connection already carries is not.
+ const { providers, graph } = shared();
+ for (const id of ['claude-ollama', 'claude-ollama-tui']) {
+ providers.find((provider) => provider.id === id).envVars.ANTHROPIC_AUTH_TOKEN = 'example-other-token';
+ }
+
+ const plan = planGraphReconciliation(graph, providers, { mintId: minter('new') });
+ const claude = plan.regroups.find((regroup) => regroup.routeIds.includes('claude-ollama'));
+ expect(claude.connectionAction).toBe('clone');
+ expect(claude.connection.credentials.ANTHROPIC_AUTH_TOKEN).toBe('example-other-token');
+ });
+
+ it('detaches a route that stopped declaring an endpoint at all', () => {
+ // `Absent` must not collapse into `matches anything`: a record with no
+ // endpoint describes no backend, so it cannot stay on this one.
+ const { providers, graph } = shared();
+ delete providers.find((provider) => provider.id === 'codex-ollama').envVars.OPENAI_BASE_URL;
+
+ const plan = planGraphReconciliation(graph, providers, { mintId: minter('new') });
+ const codex = plan.regroups.find((regroup) => regroup.routeIds.includes('codex-ollama'));
+ expect(codex.connectionAction).toBe('clone');
+ expect(codex.connection.transports).toEqual({});
+ });
+});
+
describe('a mode-only legacy edit stays route-scoped', () => {
it('changes no connection-owned value and plans no graph change', () => {
const providers = providersFixture();
diff --git a/server/lib/providerRouteRecipes.js b/server/lib/providerRouteRecipes.js
index 3eac26f465..05da154b2f 100644
--- a/server/lib/providerRouteRecipes.js
+++ b/server/lib/providerRouteRecipes.js
@@ -116,11 +116,12 @@ export function connectionBlocker({ kind, transports }) {
* Why this connection cannot carry a route for this harness, or `null`.
*
* The transport rule is stricter than "declares the protocol": the connection
- * must declare that protocol and NOTHING else. A minted record's own profile
- * always names exactly one transport (a provider record has one endpoint), so a
- * connection declaring two would not be the connection its own routes describe
- * — and `planGraphReconciliation` would clone each binding onto a fresh
- * single-transport row on the next pass, silently undoing the create.
+ * must declare that protocol and NOTHING else. It was written that way because
+ * reconciliation demanded a route describe its connection EXACTLY, so a route
+ * minted onto a two-protocol row was cloned straight back off it on the next
+ * pass. #6452 replaced that with containment, so the strictness is now
+ * conservatism rather than a guard against a silently undone create — relaxing
+ * it to "declares the protocol" is tracked in #6460.
*
* @returns {{code:string, message:string}|null}
*/
diff --git a/server/routes/providers.connectionManagement.test.js b/server/routes/providers.connectionManagement.test.js
index 5801b9edaa..f6d2cd7b30 100644
--- a/server/routes/providers.connectionManagement.test.js
+++ b/server/routes/providers.connectionManagement.test.js
@@ -773,3 +773,19 @@ describe('PATCH /api/providers/routes/:providerId/model-aliases', () => {
expect(route.modelAliasOverrides).toEqual({ good: 'example-model' });
});
});
+
+describe('boot reconciliation of the shared backend this suite edits', () => {
+ it('leaves the two-protocol connection intact instead of cloning both bindings off it', async () => {
+ // The fixture is the configuration the feature exists for: one daemon, two
+ // protocol ports, two harnesses, one connection row. Each executable record
+ // names ONE endpoint, so no route can ever report the row's full identity —
+ // a reconcile pass that demanded equality would detach every binding onto a
+ // fresh single-transport row and silently undo the link.
+ graph.resetProviderGraphState();
+ store.applyReconciliation.mockClear();
+
+ await graph.initProviderGraph();
+
+ expect(store.applyReconciliation).not.toHaveBeenCalled();
+ });
+});