Skip to content

Commit 2f92259

Browse files
committed
fix(config): rebase stale live saves
1 parent e2f7f2b commit 2f92259

2 files changed

Lines changed: 120 additions & 18 deletions

File tree

‎src/config.ts‎

Lines changed: 81 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -2717,6 +2717,12 @@ export function websocketsEnabled(config: Pick<OcxConfig, "websockets">): boolea
27172717
* against, or a later stale save would masquerade as "our own change".
27182718
*/
27192719
const claudeCodeBaseline = new WeakMap<OcxConfig, unknown>();
2720+
/**
2721+
* Full live-config baseline used to rebase unrelated cooperating writes. The
2722+
* Claude subtree and the bound listener fields remain on their dedicated
2723+
* reconciliation paths below.
2724+
*/
2725+
const liveConfigBaseline = new WeakMap<OcxConfig, OcxConfig>();
27202726

27212727
/**
27222728
* The live config retains the address of the socket Bun actually opened, while
@@ -2734,6 +2740,7 @@ const persistedLiveServerBinding = new WeakMap<OcxConfig, PersistedServerBinding
27342740
* save, which is the case the guard exists for.
27352741
*/
27362742
export function armClaudeCodeBaseline(config: OcxConfig): void {
2743+
liveConfigBaseline.set(config, structuredClone(config));
27372744
claudeCodeBaseline.set(config, structuredClone(config.claudeCode));
27382745
}
27392746

@@ -2781,6 +2788,54 @@ function cloneConfigValue(value: ConfigMergeValue): ConfigMergeValue {
27812788
return value === MISSING_CONFIG_VALUE ? value : structuredClone(value);
27822789
}
27832790

2791+
type IndexedCustomModels = {
2792+
order: string[];
2793+
byId: Map<string, Record<string, unknown>>;
2794+
};
2795+
2796+
function indexCustomModels(value: ConfigMergeValue): IndexedCustomModels | null {
2797+
if (!Array.isArray(value)) return null;
2798+
const order: string[] = [];
2799+
const byId = new Map<string, Record<string, unknown>>();
2800+
for (const item of value) {
2801+
if (!isPlainConfigRecord(item) || typeof item.id !== "string" || item.id.length === 0 || byId.has(item.id)) {
2802+
return null;
2803+
}
2804+
order.push(item.id);
2805+
byId.set(item.id, item);
2806+
}
2807+
return { order, byId };
2808+
}
2809+
2810+
/**
2811+
* Merge custom-model rows by their stable id instead of treating the array as
2812+
* one opaque value. A row changed only on disk is adopted, a row changed only
2813+
* in the live config is retained, and disjoint edits to the same row recurse
2814+
* through the normal three-way object merge.
2815+
*/
2816+
function reconcileCustomModels(
2817+
baseline: ConfigMergeValue,
2818+
live: ConfigMergeValue,
2819+
persisted: ConfigMergeValue,
2820+
): ConfigMergeValue | null {
2821+
const baselineRows = indexCustomModels(baseline);
2822+
const liveRows = indexCustomModels(live);
2823+
const persistedRows = indexCustomModels(persisted);
2824+
if (!baselineRows || !liveRows || !persistedRows) return null;
2825+
2826+
const order = [...liveRows.order, ...persistedRows.order.filter(id => !liveRows.byId.has(id))];
2827+
const merged: Array<Record<string, unknown>> = [];
2828+
for (const id of order) {
2829+
const row = reconcileConfigValue(
2830+
baselineRows.byId.get(id) ?? MISSING_CONFIG_VALUE,
2831+
liveRows.byId.get(id) ?? MISSING_CONFIG_VALUE,
2832+
persistedRows.byId.get(id) ?? MISSING_CONFIG_VALUE,
2833+
);
2834+
if (row !== MISSING_CONFIG_VALUE) merged.push(row as Record<string, unknown>);
2835+
}
2836+
return merged;
2837+
}
2838+
27842839
function reconcileConfigRecord(
27852840
live: Record<string, unknown>,
27862841
baseline: Record<string, unknown>,
@@ -2790,11 +2845,13 @@ function reconcileConfigRecord(
27902845
const keys = new Set([...Object.keys(baseline), ...Object.keys(live), ...Object.keys(persisted)]);
27912846
for (const key of keys) {
27922847
if (skippedKeys?.has(key)) continue;
2793-
const merged = reconcileConfigValue(
2794-
ownConfigValue(baseline, key),
2795-
ownConfigValue(live, key),
2796-
ownConfigValue(persisted, key),
2797-
);
2848+
const baselineValue = ownConfigValue(baseline, key);
2849+
const liveValue = ownConfigValue(live, key);
2850+
const persistedValue = ownConfigValue(persisted, key);
2851+
const merged = key === "customModels"
2852+
? reconcileCustomModels(baselineValue, liveValue, persistedValue)
2853+
?? reconcileConfigValue(baselineValue, liveValue, persistedValue)
2854+
: reconcileConfigValue(baselineValue, liveValue, persistedValue);
27982855
if (merged === MISSING_CONFIG_VALUE) delete live[key];
27992856
else live[key] = merged;
28002857
}
@@ -2920,20 +2977,31 @@ function readPersistedServerBinding(
29202977
*
29212978
* Conflict policy, chosen deliberately:
29222979
* - disk changed, we did not → their hand edit wins;
2923-
* - disk changed AND we changed → our change wins and the baseline rebases, so the
2924-
* user's next edit starts from the new value (a three-way merge is out of scope);
2980+
* - disk changed AND we changed → disjoint fields are merged, while a same-leaf
2981+
* conflict keeps the live value;
29252982
* - file missing/unreadable → save what we have, no throw.
29262983
*
2927-
* Scope residual: only `claudeCode` is reconciled. A hand edit to `providers` is still
2928-
* clobbered — recorded and asserted in tests so it cannot drift into an assumed
2929-
* guarantee.
2984+
* Custom-model rows are merged by their stable `id`, preserving independent
2985+
* edits and deletions across stale whole-config saves.
29302986
*/
29312987
export function saveConfigPreservingClaudeCode(config: OcxConfig): void {
29322988
withConfigMutationLockSync(() => {
29332989
const bindingBaseline = persistedLiveServerBinding.get(config);
29342990
// One authoritative pre-write read feeds both the live-config reconciliation and
29352991
// custom-model deletion migration. A second read could observe different bytes.
29362992
const onDisk = readRawConfigJson();
2993+
const baseline = liveConfigBaseline.get(config);
2994+
if (baseline && onDisk !== undefined) {
2995+
const persistedDiagnostics = configDiagnosticsFromRaw(JSON.stringify(onDisk));
2996+
if (persistedDiagnostics.source === "file") {
2997+
reconcileConfigRecord(
2998+
config as unknown as Record<string, unknown>,
2999+
baseline as unknown as Record<string, unknown>,
3000+
persistedDiagnostics.config as unknown as Record<string, unknown>,
3001+
new Set(["hostname", "port", "claudeCode"]),
3002+
);
3003+
}
3004+
}
29373005
if (claudeCodeBaseline.has(config)) {
29383006
if (onDisk !== undefined) {
29393007
const baseline = claudeCodeBaseline.get(config);
@@ -2965,6 +3033,9 @@ export function saveConfigPreservingClaudeCode(config: OcxConfig): void {
29653033
if (claudeCodeBaseline.has(config)) {
29663034
claudeCodeBaseline.set(config, structuredClone(config.claudeCode));
29673035
}
3036+
if (liveConfigBaseline.has(config)) {
3037+
liveConfigBaseline.set(config, structuredClone(config));
3038+
}
29683039
});
29693040
}
29703041

‎tests/config-user-edits.test.ts‎

Lines changed: 39 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -16,13 +16,16 @@ import {
1616
} from "../src/config";
1717
import { legacyCustomModelCatalogSlugs } from "../src/codex/custom-model-catalog-migration";
1818
import { rateLimitRetryPolicyFor } from "../src/providers/key-failover";
19-
import { activeUserCostOverlays, refreshUserCostOverlays } from "../src/usage/user-cost-overlays";
19+
import {
20+
activeUserCostOverlays,
21+
refreshUserCostOverlays,
22+
resetPreservedDiskOnlyProvidersForTests,
23+
} from "../src/usage/user-cost-overlays";
2024
import type { OcxConfig } from "../src/types";
2125

2226
/**
23-
* A user hand-edits `config.json` while the proxy runs. `saveConfig` serializes the
24-
* WHOLE object, so ANY later service-time save rewrites `claudeCode` from memory and
25-
* the edit vanishes with no visible cause (#488, devlog 260726_claude_auth_auto/040 H1).
27+
* A user or cooperating process can edit config.json while the proxy runs.
28+
* Guarded saves rebase disjoint live changes onto that newer disk snapshot.
2629
*/
2730

2831
let home: string;
@@ -618,16 +621,44 @@ test("an unarmed config saves without reconciliation", () => {
618621
expect((diskConfig().claudeCode as Record<string, unknown>).authMode).toBe("subscription");
619622
});
620623

621-
// DOCUMENTED RESIDUAL, asserted so it cannot drift into an assumed guarantee: only the
622-
// `claudeCode` subtree is reconciled. A hand edit to `providers` is still lost.
623-
test("a providers hand edit is NOT preserved", () => {
624+
test("a provider deletion from a newer disk snapshot survives an unrelated live save", () => {
624625
const live = loadConfig();
626+
live.providers.extra = {
627+
adapter: "openai-chat",
628+
baseUrl: "http://127.0.0.1:2/v1",
629+
allowPrivateNetwork: true,
630+
};
631+
saveConfig(live);
625632
armClaudeCodeBaseline(live);
626-
writeDiskConfig({ providers: { handEdited: { adapter: "openai-chat", baseUrl: "http://127.0.0.1:2/v1", allowPrivateNetwork: true } } });
633+
resetPreservedDiskOnlyProvidersForTests();
634+
writeDiskConfig({ providers: { test: live.providers.test } });
627635

628636
live.port = 10103;
637+
live.disabledModels = ["test/one"];
629638
saveConfigPreservingClaudeCode(live);
630639
expect(Object.keys(diskConfig().providers as Record<string, unknown>)).toEqual(["test"]);
640+
expect(diskConfig().disabledModels).toEqual(["test/one"]);
641+
});
642+
643+
test("independent custom-model edits survive a guarded stale save", () => {
644+
const live = loadConfig();
645+
live.customModels = [customModel("one"), customModel("two")];
646+
saveConfig(live);
647+
armClaudeCodeBaseline(live);
648+
649+
live.customModels![0]!.modelId = "live-one";
650+
writeDiskConfig({
651+
customModels: [
652+
customModel("one"),
653+
{ ...customModel("two"), modelId: "disk-two" },
654+
],
655+
});
656+
saveConfigPreservingClaudeCode(live);
657+
658+
expect(diskConfig().customModels).toEqual([
659+
{ ...customModel("one"), modelId: "live-one" },
660+
{ ...customModel("two"), modelId: "disk-two" },
661+
]);
631662
});
632663

633664
test("upstreamHostCircuitThreshold live writes accept only integer values from 0 through 20", () => {

0 commit comments

Comments
 (0)