Open History to see the last commit
1/**
2 * ServerSettings - Server-authoritative settings service.
3 *
4 * Owns persistence, validation, and change notification of settings that affect
5 * server-side behavior (binary paths, streaming mode, env mode, custom models,
6 * text generation model selection).
7 *
8 * Follows the same pattern as `keybindings.ts`: JSON file + Cache + PubSub +
9 * Semaphore + FileSystem.watch for concurrency and external edit detection.
10 *
11 * @module ServerSettings
12 */
13import {
14 DEFAULT_GIT_TEXT_GENERATION_MODEL_BY_PROVIDER,
15 DEFAULT_SERVER_SETTINGS,
16 type ModelSelection,
17 type ProviderKind,
18 ServerSettings,
19 ServerSettingsError,
20 type ServerSettingsPatch,
21} from "@workbench/contracts";
22import {
23 Cache,
24 Deferred,
25 Duration,
26 Effect,
27 Exit,
28 FileSystem,
29 Layer,
30 Path,
31 Equal,
32 PubSub,
33 Ref,
34 Schema,
35 SchemaIssue,
36 Scope,
37 Context,
38 Stream,
39 Cause,
40} from "effect";
41import * as Semaphore from "effect/Semaphore";
42import { ServerConfig } from "./config.ts";
43import { type DeepPartial, deepMerge } from "@workbench/shared/Struct";
44import { fromLenientJson } from "@workbench/shared/schemaJson";
45import { applyServerSettingsPatch } from "@workbench/shared/serverSettings";
46
47export interface ServerSettingsShape {
48 /** Start the settings runtime and attach file watching. */
49 readonly start: Effect.Effect<void, ServerSettingsError>;
50
51 /** Await settings runtime readiness. */
52 readonly ready: Effect.Effect<void, ServerSettingsError>;
53
54 /** Read the current settings. */
55 readonly getSettings: Effect.Effect<ServerSettings, ServerSettingsError>;
56
57 /** Patch settings and persist. Returns the new full settings object. */
58 readonly updateSettings: (
59 patch: ServerSettingsPatch,
60 ) => Effect.Effect<ServerSettings, ServerSettingsError>;
61
62 /** Stream of settings change events. */
63 readonly streamChanges: Stream.Stream<ServerSettings>;
64}
65
66export class ServerSettingsService extends Context.Service<
67 ServerSettingsService,
68 ServerSettingsShape
69>()("t3/serverSettings/ServerSettingsService") {
70 static readonly layerTest = (overrides: DeepPartial<ServerSettings> = {}) =>
71 Layer.effect(
72 ServerSettingsService,
73 Effect.gen(function* () {
74 const currentSettingsRef = yield* Ref.make<ServerSettings>(
75 deepMerge(DEFAULT_SERVER_SETTINGS, overrides),
76 );
77
78 return {
79 start: Effect.void,
80 ready: Effect.void,
81 getSettings: Ref.get(currentSettingsRef),
82 updateSettings: (patch) =>
83 Ref.get(currentSettingsRef).pipe(
84 Effect.flatMap((currentSettings) =>
85 Schema.decodeEffect(ServerSettings)(
86 applyServerSettingsPatch(currentSettings, patch),
87 ).pipe(
88 Effect.mapError(
89 (cause) =>
90 new ServerSettingsError({
91 settingsPath: "<memory>",
92 detail: `failed to normalize server settings: ${SchemaIssue.makeFormatterDefault()(cause.issue)}`,
93 cause,
94 }),
95 ),
96 ),
97 ),
98 Effect.tap((nextSettings) => Ref.set(currentSettingsRef, nextSettings)),
99 ),
100 streamChanges: Stream.empty,
101 } satisfies ServerSettingsShape;
102 }),
103 );
104}
105
106const ServerSettingsJson = fromLenientJson(ServerSettings);
107
108const PROVIDER_ORDER: readonly ProviderKind[] = [
109 "codex",
110 "claudeAgent",
111 "opencode",
112 "cursor",
113 "pi",
114];
115
116/**
117 * Ensure the `textGenerationModelSelection` points to an enabled provider.
118 * If the selected provider is disabled, fall back to the first enabled
119 * provider with its default model. This is applied at read-time so the
120 * persisted preference is preserved for when a provider is re-enabled.
121 */
122function resolveTextGenerationProvider(settings: ServerSettings): ServerSettings {
123 const selection = settings.textGenerationModelSelection;
124 if (settings.providers[selection.provider].enabled) {
125 return settings;
126 }
127
128 const fallback = PROVIDER_ORDER.find((p) => settings.providers[p].enabled);
129 if (!fallback) {
130 // No providers enabled — return as-is; callers will report the error.
131 return settings;
132 }
133
134 return {
135 ...settings,
136 textGenerationModelSelection: {
137 provider: fallback,
138 model: DEFAULT_GIT_TEXT_GENERATION_MODEL_BY_PROVIDER[fallback],
139 } as ModelSelection,
140 };
141}
142
143// Values under these keys are compared as a whole — never stripped field-by-field.
144const ATOMIC_SETTINGS_KEYS: ReadonlySet<string> = new Set(["textGenerationModelSelection"]);
145
146function stripDefaultServerSettings(current: unknown, defaults: unknown): unknown | undefined {
147 if (Array.isArray(current) || Array.isArray(defaults)) {
148 return Equal.equals(current, defaults) ? undefined : current;
149 }
150
151 if (
152 current !== null &&
153 defaults !== null &&
154 typeof current === "object" &&
155 typeof defaults === "object"
156 ) {
157 const currentRecord = current as Record<string, unknown>;
158 const defaultsRecord = defaults as Record<string, unknown>;
159 const next: Record<string, unknown> = {};
160
161 for (const key of Object.keys(currentRecord)) {
162 if (ATOMIC_SETTINGS_KEYS.has(key)) {
163 if (!Equal.equals(currentRecord[key], defaultsRecord[key])) {
164 next[key] = currentRecord[key];
165 }
166 } else {
167 const stripped = stripDefaultServerSettings(currentRecord[key], defaultsRecord[key]);
168 if (stripped !== undefined) {
169 next[key] = stripped;
170 }
171 }
172 }
173
174 return Object.keys(next).length > 0 ? next : undefined;
175 }
176
177 return Object.is(current, defaults) ? undefined : current;
178}
179
180const makeServerSettings = Effect.gen(function* () {
181 const { settingsPath } = yield* ServerConfig;
182 const fs = yield* FileSystem.FileSystem;
183 const pathService = yield* Path.Path;
184 const writeSemaphore = yield* Semaphore.make(1);
185 const cacheKey = "settings" as const;
186 const changesPubSub = yield* PubSub.unbounded<ServerSettings>();
187 const startedRef = yield* Ref.make(false);
188 const startedDeferred = yield* Deferred.make<void, ServerSettingsError>();
189 const watcherScope = yield* Scope.make("sequential");
190 yield* Effect.addFinalizer(() => Scope.close(watcherScope, Exit.void));
191
192 const emitChange = (settings: ServerSettings) =>
193 PubSub.publish(changesPubSub, settings).pipe(Effect.asVoid);
194
195 const readConfigExists = fs.exists(settingsPath).pipe(
196 Effect.mapError(
197 (cause) =>
198 new ServerSettingsError({
199 settingsPath,
200 detail: "failed to check settings file existence",
201 cause,
202 }),
203 ),
204 );
205
206 const readRawConfig = fs.readFileString(settingsPath).pipe(
207 Effect.mapError(
208 (cause) =>
209 new ServerSettingsError({
210 settingsPath,
211 detail: "failed to read settings file",
212 cause,
213 }),
214 ),
215 );
216
217 const loadSettingsFromDisk = Effect.gen(function* () {
218 if (!(yield* readConfigExists)) {
219 return DEFAULT_SERVER_SETTINGS;
220 }
221
222 const raw = yield* readRawConfig;
223 const decoded = Schema.decodeUnknownExit(ServerSettingsJson)(raw);
224 if (decoded._tag === "Failure") {
225 yield* Effect.logWarning("failed to parse settings.json, using defaults", {
226 path: settingsPath,
227 issues: Cause.pretty(decoded.cause),
228 });
229 return DEFAULT_SERVER_SETTINGS;
230 }
231 return decoded.value;
232 });
233
234 const settingsCache = yield* Cache.make<typeof cacheKey, ServerSettings, ServerSettingsError>({
235 capacity: 1,
236 lookup: () => loadSettingsFromDisk,
237 });
238
239 const getSettingsFromCache = Cache.get(settingsCache, cacheKey);
240
241 const writeSettingsAtomically = (settings: ServerSettings) => {
242 const tempPath = `${settingsPath}.${process.pid}.${Date.now()}.tmp`;
243 const sparseSettings = stripDefaultServerSettings(settings, DEFAULT_SERVER_SETTINGS) ?? {};
244
245 return Effect.succeed(`${JSON.stringify(sparseSettings, null, 2)}\n`).pipe(
246 Effect.tap(() => fs.makeDirectory(pathService.dirname(settingsPath), { recursive: true })),
247 Effect.tap((encoded) => fs.writeFileString(tempPath, encoded)),
248 Effect.flatMap(() => fs.rename(tempPath, settingsPath)),
249 Effect.ensuring(fs.remove(tempPath, { force: true }).pipe(Effect.ignore({ log: true }))),
250 Effect.mapError(
251 (cause) =>
252 new ServerSettingsError({
253 settingsPath,
254 detail: "failed to write settings file",
255 cause,
256 }),
257 ),
258 );
259 };
260
261 const revalidateAndEmit = writeSemaphore.withPermits(1)(
262 Effect.gen(function* () {
263 yield* Cache.invalidate(settingsCache, cacheKey);
264 const settings = yield* getSettingsFromCache;
265 yield* emitChange(settings);
266 }),
267 );
268
269 const startWatcher = Effect.gen(function* () {
270 const settingsDir = pathService.dirname(settingsPath);
271 const settingsFile = pathService.basename(settingsPath);
272 const settingsPathResolved = pathService.resolve(settingsPath);
273
274 yield* fs.makeDirectory(settingsDir, { recursive: true }).pipe(
275 Effect.mapError(
276 (cause) =>
277 new ServerSettingsError({
278 settingsPath,
279 detail: "failed to prepare settings directory",
280 cause,
281 }),
282 ),
283 );
284
285 const revalidateAndEmitSafely = revalidateAndEmit.pipe(Effect.ignoreCause({ log: true }));
286
287 // Debounce watch events so the file is fully written before we read it.
288 // Editors emit multiple events per save (truncate, write, rename) and
289 // `fs.watch` can fire before the content has been flushed to disk.
290 const debouncedSettingsEvents = fs.watch(settingsDir).pipe(
291 Stream.filter((event) => {
292 return (
293 event.path === settingsFile ||
294 event.path === settingsPath ||
295 pathService.resolve(settingsDir, event.path) === settingsPathResolved
296 );
297 }),
298 Stream.debounce(Duration.millis(100)),
299 );
300
301 yield* Stream.runForEach(debouncedSettingsEvents, () => revalidateAndEmitSafely).pipe(
302 Effect.ignoreCause({ log: true }),
303 Effect.forkIn(watcherScope),
304 Effect.asVoid,
305 );
306 });
307
308 const start = Effect.gen(function* () {
309 const shouldStart = yield* Ref.modify(startedRef, (started) => [!started, true]);
310 if (!shouldStart) {
311 return yield* Deferred.await(startedDeferred);
312 }
313
314 const startup = Effect.gen(function* () {
315 yield* startWatcher;
316 yield* Cache.invalidate(settingsCache, cacheKey);
317 yield* getSettingsFromCache;
318 });
319
320 const startupExit = yield* Effect.exit(startup);
321 if (startupExit._tag === "Failure") {
322 yield* Deferred.failCause(startedDeferred, startupExit.cause).pipe(Effect.orDie);
323 return yield* Effect.failCause(startupExit.cause);
324 }
325
326 yield* Deferred.succeed(startedDeferred, undefined).pipe(Effect.orDie);
327 });
328
329 return {
330 start,
331 ready: Deferred.await(startedDeferred),
332 getSettings: getSettingsFromCache.pipe(Effect.map(resolveTextGenerationProvider)),
333 updateSettings: (patch) =>
334 writeSemaphore.withPermits(1)(
335 Effect.gen(function* () {
336 const current = yield* getSettingsFromCache;
337 const next = yield* Schema.decodeEffect(ServerSettings)(
338 applyServerSettingsPatch(current, patch),
339 ).pipe(
340 Effect.mapError(
341 (cause) =>
342 new ServerSettingsError({
343 settingsPath: "<memory>",
344 detail: `failed to normalize server settings: ${SchemaIssue.makeFormatterDefault()(cause.issue)}`,
345 cause,
346 }),
347 ),
348 );
349 yield* writeSettingsAtomically(next);
350 yield* Cache.set(settingsCache, cacheKey, next);
351 yield* emitChange(next);
352 return resolveTextGenerationProvider(next);
353 }),
354 ),
355 get streamChanges() {
356 return Stream.fromPubSub(changesPubSub).pipe(Stream.map(resolveTextGenerationProvider));
357 },
358 } satisfies ServerSettingsShape;
359});
360
361export const ServerSettingsLive = Layer.effect(ServerSettingsService, makeServerSettings);