Skip to content

Commit 276a860

Browse files
Pysephclaude
andcommitted
fix(server): a half-written settings.json no longer resets live settings
A watcher reload that caught settings.json mid-write, or while it failed the schema, replaced the running settings with defaults and published them to every client and service. Keep the settings that last loaded until the file parses again (saves still refuse to overwrite it), warn once until it does, and publish a reload only when it differs from what subscribers already have, so the watcher no longer re-publishes the app's own saves. Co-Authored-By: Claude Opus 5.5 <[email protected]>
1 parent 14b47ee commit 276a860

2 files changed

Lines changed: 216 additions & 10 deletions

File tree

‎apps/server/src/serverSettings.test.ts‎

Lines changed: 175 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -19,9 +19,11 @@ import * as Duration from "effect/Duration";
1919
import * as FileSystem from "effect/FileSystem";
2020
import * as Fiber from "effect/Fiber";
2121
import * as Layer from "effect/Layer";
22+
import * as Logger from "effect/Logger";
2223
import * as Option from "effect/Option";
2324
import * as Path from "effect/Path";
2425
import * as PlatformError from "effect/PlatformError";
26+
import * as Queue from "effect/Queue";
2527
import * as Schema from "effect/Schema";
2628
import * as Stream from "effect/Stream";
2729
import * as TestClock from "effect/testing/TestClock";
@@ -64,6 +66,49 @@ const layerServerSettingsWithSecrets = () =>
6466
),
6567
);
6668

69+
// Reports each read of settings.json, so a test knows when the watcher has reloaded the file.
70+
const layerServerSettingsReportingReads = (reads: Queue.Queue<void>) =>
71+
ServerSettingsModule.layer.pipe(
72+
Layer.provide(ServerSecretStore.layer),
73+
Layer.provide(
74+
Layer.effect(
75+
FileSystem.FileSystem,
76+
Effect.gen(function* () {
77+
const fs = yield* FileSystem.FileSystem;
78+
const { settingsPath } = yield* ServerConfig.ServerConfig;
79+
return FileSystem.FileSystem.of({
80+
...fs,
81+
readFileString: (path, encoding) =>
82+
fs
83+
.readFileString(path, encoding)
84+
.pipe(
85+
Effect.ensuring(
86+
path === settingsPath ? Queue.offer(reads, undefined) : Effect.void,
87+
),
88+
),
89+
});
90+
}),
91+
),
92+
),
93+
Layer.provideMerge(Layer.fresh(SqlitePersistence.layerMemory)),
94+
Layer.provideMerge(
95+
Layer.fresh(
96+
ServerConfig.layerTest(process.cwd(), {
97+
prefix: "t3code-server-settings-test-",
98+
}),
99+
),
100+
),
101+
);
102+
103+
const usageScript = {
104+
id: "usage",
105+
name: "Usage",
106+
command: "echo usage",
107+
icon: "debug",
108+
runOnWorktreeCreate: false,
109+
} as const;
110+
const perfLabScript = { ...usageScript, id: "perf-lab", name: "Perf lab" } as const;
111+
67112
const layerFailingSecretStore = (cause: ServerSecretStore.SecretStoreError) =>
68113
Layer.succeed(
69114
ServerSecretStore.ServerSecretStore,
@@ -324,6 +369,136 @@ it.layer(NodeServices.layer)("server settings", (it) => {
324369
).pipe(TestClock.withLive, Effect.provide(layerServerSettings())),
325370
);
326371

372+
it.effect("publishes a default project script that another program adds to settings.json", () =>
373+
Effect.scoped(
374+
Effect.gen(function* () {
375+
const config = yield* ServerConfig.ServerConfig;
376+
const fs = yield* FileSystem.FileSystem;
377+
const service = yield* ServerSettingsModule.ServerSettingsService;
378+
yield* fs.writeFileString(
379+
config.settingsPath,
380+
JSON.stringify({ defaultProjectScripts: [usageScript] }),
381+
);
382+
yield* service.start;
383+
const changes = yield* service.subscribeChanges;
384+
385+
yield* fs.writeFileString(
386+
config.settingsPath,
387+
JSON.stringify({ defaultProjectScripts: [usageScript, perfLabScript] }),
388+
);
389+
390+
const change = yield* changes.pipe(Stream.runHead, Effect.timeout("2 seconds"));
391+
assert.deepEqual(
392+
Option.getOrUndefined(change)?.defaultProjectScripts.map((script) => script.id),
393+
["usage", "perf-lab"],
394+
);
395+
assert.lengthOf((yield* service.getSettings).defaultProjectScripts, 2);
396+
}),
397+
).pipe(TestClock.withLive, Effect.provide(layerServerSettings())),
398+
);
399+
400+
it.effect("keeps the last good settings while settings.json is invalid and warns once", () => {
401+
const messages: string[] = [];
402+
const logger = Logger.make(({ message }) => {
403+
messages.push(String(message));
404+
});
405+
return Effect.gen(function* () {
406+
const reads = yield* Queue.unbounded<void>();
407+
yield* Effect.scoped(
408+
Effect.gen(function* () {
409+
const config = yield* ServerConfig.ServerConfig;
410+
const fs = yield* FileSystem.FileSystem;
411+
const service = yield* ServerSettingsModule.ServerSettingsService;
412+
yield* fs.writeFileString(
413+
config.settingsPath,
414+
JSON.stringify({ responseStreamingMode: "turn", defaultProjectScripts: [usageScript] }),
415+
);
416+
yield* service.start;
417+
yield* Queue.clear(reads);
418+
const changes = yield* service.subscribeChanges;
419+
420+
// A write caught halfway, then one the schema rejects.
421+
for (const contents of [
422+
`{ "responseStreamingMode": "turn", "defaultProjectScripts": [`,
423+
JSON.stringify({ defaultProjectScripts: [{ ...perfLabScript, icon: "no-such-icon" }] }),
424+
]) {
425+
yield* fs.writeFileString(config.settingsPath, contents);
426+
yield* Queue.take(reads).pipe(Effect.timeout("2 seconds"));
427+
// The reload holds the write lock, so this snapshot waits for it to finish.
428+
const kept = yield* service.withSettingsSnapshot(Effect.succeed);
429+
assert.equal(kept.responseStreamingMode, "turn");
430+
assert.deepEqual(
431+
kept.defaultProjectScripts.map((script) => script.id),
432+
["usage"],
433+
);
434+
}
435+
assert.lengthOf(
436+
messages.filter((message) => message.includes("failed to parse settings.json")),
437+
1,
438+
);
439+
440+
yield* fs.writeFileString(
441+
config.settingsPath,
442+
JSON.stringify({
443+
responseStreamingMode: "turn",
444+
defaultProjectScripts: [usageScript, perfLabScript],
445+
}),
446+
);
447+
const change = yield* changes.pipe(Stream.runHead, Effect.timeout("2 seconds"));
448+
assert.deepEqual(
449+
Option.getOrUndefined(change)?.defaultProjectScripts.map((script) => script.id),
450+
["usage", "perf-lab"],
451+
);
452+
}),
453+
).pipe(
454+
Effect.provide(
455+
Layer.mergeAll(
456+
layerServerSettingsReportingReads(reads),
457+
Logger.layer([logger], { mergeWithExisting: false }),
458+
),
459+
),
460+
);
461+
}).pipe(TestClock.withLive);
462+
});
463+
464+
it.effect("publishes a settings save once, not again when the watcher sees the write", () =>
465+
Effect.gen(function* () {
466+
const reads = yield* Queue.unbounded<void>();
467+
yield* Effect.scoped(
468+
Effect.gen(function* () {
469+
const config = yield* ServerConfig.ServerConfig;
470+
const fs = yield* FileSystem.FileSystem;
471+
const service = yield* ServerSettingsModule.ServerSettingsService;
472+
yield* fs.writeFileString(config.settingsPath, "{}");
473+
yield* service.start;
474+
yield* Queue.clear(reads);
475+
const changes = yield* service.subscribeChanges;
476+
477+
yield* service.updateSettings({ responseStreamingMode: "turn" });
478+
// One read is the save's own; the next is the watcher reloading the saved file.
479+
yield* Queue.take(reads);
480+
yield* Queue.take(reads).pipe(Effect.timeout("2 seconds"));
481+
yield* fs.writeFileString(
482+
config.settingsPath,
483+
JSON.stringify({ responseStreamingMode: "turn", defaultProjectScripts: [usageScript] }),
484+
);
485+
486+
const [saved, edited] = yield* changes.pipe(
487+
Stream.take(2),
488+
Stream.runCollect,
489+
Effect.timeout("2 seconds"),
490+
);
491+
assert.equal(saved?.responseStreamingMode, "turn");
492+
assert.deepEqual(saved?.defaultProjectScripts, []);
493+
assert.deepEqual(
494+
edited?.defaultProjectScripts.map((script) => script.id),
495+
["usage"],
496+
);
497+
}),
498+
).pipe(Effect.provide(layerServerSettingsReportingReads(reads)));
499+
}).pipe(TestClock.withLive),
500+
);
501+
327502
it.effect("preserves context when reading a provider environment secret fails", () => {
328503
const platformCause = PlatformError.systemError({
329504
_tag: "PermissionDenied",

‎apps/server/src/serverSettings.ts‎

Lines changed: 41 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -572,9 +572,16 @@ const make = Effect.gen(function* () {
572572
const startedDeferred = yield* Deferred.make<void, ServerSettingsError>();
573573
const watcherScope = yield* Scope.make("sequential");
574574
yield* Effect.addFinalizer(() => Scope.close(watcherScope, Exit.void));
575+
// What subscribers last received. A reload that finds the same settings, such as our own
576+
// write coming back through the watcher, publishes nothing.
577+
const publishedRef = yield* Ref.make(Option.none<ServerSettings>());
578+
const parseFailureLoggedRef = yield* Ref.make(false);
575579

576580
const emitChange = (settings: ServerSettings) =>
577-
PubSub.publish(changesPubSub, settings).pipe(Effect.asVoid);
581+
Ref.set(publishedRef, Option.some(settings)).pipe(
582+
Effect.andThen(PubSub.publish(changesPubSub, settings)),
583+
Effect.asVoid,
584+
);
578585

579586
const readConfigExists = fs.exists(settingsPath).pipe(
580587
Effect.mapError(
@@ -675,16 +682,25 @@ const make = Effect.gen(function* () {
675682
settings = { ...DEFAULT_SERVER_SETTINGS, continueThreadsAfterServerUpdate: false };
676683
if (failure._tag === "Failure") {
677684
parseFailure = Option.some(Cause.squash(failure.cause));
678-
yield* Effect.logWarning("failed to parse settings.json, using defaults", {
679-
path: settingsPath,
680-
issues: Cause.pretty(failure.cause),
681-
cause: failure.cause,
682-
});
685+
// An editor or agent can leave the file invalid across several reloads.
686+
if (!(yield* Ref.getAndSet(parseFailureLoggedRef, true))) {
687+
yield* Effect.logWarning(
688+
"failed to parse settings.json, ignoring it until it is fixed",
689+
{
690+
path: settingsPath,
691+
issues: Cause.pretty(failure.cause),
692+
cause: failure.cause,
693+
},
694+
);
695+
}
683696
}
684697
} else {
685698
settings = decoded.value;
686699
}
687700
}
701+
if (Option.isNone(parseFailure)) {
702+
yield* Ref.set(parseFailureLoggedRef, false);
703+
}
688704

689705
// A file that failed to decode must stay on disk for the user to repair.
690706
const settingsFileTrusted = Option.isNone(parseFailure);
@@ -796,9 +812,17 @@ const make = Effect.gen(function* () {
796812
const getSettingsFromCache = Cache.get(settingsCache, cacheKey).pipe(
797813
Effect.map((loaded) => loaded.settings),
798814
);
799-
const reloadSettings = Cache.invalidate(settingsCache, cacheKey).pipe(
800-
Effect.andThen(Cache.get(settingsCache, cacheKey)),
801-
);
815+
// A file caught mid-write or left invalid keeps the settings that last loaded instead of
816+
// resetting them to defaults. Its parse failure still blocks saves.
817+
const reloadSettings = Effect.gen(function* () {
818+
const previous = yield* Cache.getSuccess(settingsCache, cacheKey);
819+
yield* Cache.invalidate(settingsCache, cacheKey);
820+
const loaded = yield* Cache.get(settingsCache, cacheKey);
821+
if (Option.isNone(loaded.parseFailure) || Option.isNone(previous)) return loaded;
822+
const kept = { settings: previous.value.settings, parseFailure: loaded.parseFailure };
823+
yield* Cache.set(settingsCache, cacheKey, kept);
824+
return kept;
825+
});
802826

803827
const materializeSettingsSecrets = Effect.fn("serverSettings.materializeSettingsSecrets")(
804828
function* (settings: ServerSettings): Effect.fn.Return<ServerSettings, ServerSettingsError> {
@@ -1045,6 +1069,8 @@ const make = Effect.gen(function* () {
10451069
const revalidateAndEmit = writeSemaphore.withPermits(1)(
10461070
Effect.gen(function* () {
10471071
const { settings } = yield* reloadSettings;
1072+
const published = yield* Ref.get(publishedRef);
1073+
if (Option.isSome(published) && Equal.equals(published.value, settings)) return;
10481074
yield* emitChange(settings);
10491075
}),
10501076
);
@@ -1133,7 +1159,12 @@ const make = Effect.gen(function* () {
11331159

11341160
const startup = Effect.gen(function* () {
11351161
yield* startWatcher;
1136-
yield* reloadSettings;
1162+
const { settings } = yield* reloadSettings;
1163+
// Clients start from a snapshot of these, so they count as published.
1164+
yield* Ref.update(
1165+
publishedRef,
1166+
Option.orElseSome(() => settings),
1167+
);
11371168
});
11381169

11391170
const startupExit = yield* Effect.exit(startup);

0 commit comments

Comments
 (0)