diff --git a/apps/server/src/keybindings.ts b/apps/server/src/keybindings.ts index bf58467825..726b3d11cf 100644 --- a/apps/server/src/keybindings.ts +++ b/apps/server/src/keybindings.ts @@ -23,6 +23,7 @@ import { Cache, Cause, Deferred, + Duration, Effect, Exit, FileSystem, @@ -42,6 +43,7 @@ import { } from "effect"; import * as Semaphore from "effect/Semaphore"; import { ServerConfig } from "./config"; +import { fromLenientJson } from "@t3tools/shared/schemaJson"; export class KeybindingsConfigError extends Schema.TaggedErrorClass()( "KeybindingsConfigParseError", @@ -408,7 +410,7 @@ function encodeWhenAst(node: KeybindingWhenNode): string { const DEFAULT_RESOLVED_KEYBINDINGS = compileResolvedKeybindingsConfig(DEFAULT_KEYBINDINGS); -const RawKeybindingsEntries = Schema.fromJsonString(Schema.Array(Schema.Unknown)); +const RawKeybindingsEntries = fromLenientJson(Schema.Array(Schema.Unknown)); const KeybindingsConfigJson = Schema.fromJsonString(KeybindingsConfig); const PrettyJsonString = SchemaGetter.parseJson().compose( SchemaGetter.stringifyJson({ space: 2 }), @@ -817,16 +819,25 @@ const makeKeybindings = Effect.gen(function* () { const revalidateAndEmitSafely = revalidateAndEmit.pipe(Effect.ignoreCause({ log: true })); - yield* Stream.runForEach(fs.watch(keybindingsConfigDir), (event) => { - const isTargetConfigEvent = - event.path === keybindingsConfigFile || - event.path === keybindingsConfigPath || - path.resolve(keybindingsConfigDir, event.path) === keybindingsConfigPathResolved; - if (!isTargetConfigEvent) { - return Effect.void; - } - return revalidateAndEmitSafely; - }).pipe(Effect.ignoreCause({ log: true }), Effect.forkIn(watcherScope), Effect.asVoid); + // Debounce watch events so the file is fully written before we read it. + // Editors emit multiple events per save (truncate, write, rename) and + // `fs.watch` can fire before the content has been flushed to disk. + const debouncedKeybindingsEvents = fs.watch(keybindingsConfigDir).pipe( + Stream.filter((event) => { + return ( + event.path === keybindingsConfigFile || + event.path === keybindingsConfigPath || + path.resolve(keybindingsConfigDir, event.path) === keybindingsConfigPathResolved + ); + }), + Stream.debounce(Duration.millis(100)), + ); + + yield* Stream.runForEach(debouncedKeybindingsEvents, () => revalidateAndEmitSafely).pipe( + Effect.ignoreCause({ log: true }), + Effect.forkIn(watcherScope), + Effect.asVoid, + ); }); const start = Effect.gen(function* () { diff --git a/apps/server/src/serverSettings.ts b/apps/server/src/serverSettings.ts index c156c31bed..0f54cdf71e 100644 --- a/apps/server/src/serverSettings.ts +++ b/apps/server/src/serverSettings.ts @@ -19,6 +19,7 @@ import { import { Cache, Deferred, + Duration, Effect, Exit, FileSystem, @@ -34,6 +35,7 @@ import { } from "effect"; import * as Semaphore from "effect/Semaphore"; import { ServerConfig } from "./config"; +import { fromLenientJson } from "@t3tools/shared/schemaJson"; export class ServerSettingsError extends Schema.TaggedErrorClass()( "ServerSettingsError", @@ -113,7 +115,7 @@ export function deriveProviderStartOptions( return Object.keys(providerOptions).length > 0 ? providerOptions : undefined; } -const ServerSettingsJson = Schema.fromJsonString(ServerSettings); +const ServerSettingsJson = fromLenientJson(ServerSettings); const PrettyJsonString = SchemaGetter.parseJson().compose( SchemaGetter.stringifyJson({ space: 2 }), ); @@ -229,16 +231,25 @@ const makeServerSettings = Effect.gen(function* () { const revalidateAndEmitSafely = revalidateAndEmit.pipe(Effect.ignoreCause({ log: true })); - yield* Stream.runForEach(fs.watch(settingsDir), (event) => { - const isTargetEvent = - event.path === settingsFile || - event.path === settingsPath || - pathService.resolve(settingsDir, event.path) === settingsPathResolved; - if (!isTargetEvent) { - return Effect.void; - } - return revalidateAndEmitSafely; - }).pipe(Effect.ignoreCause({ log: true }), Effect.forkIn(watcherScope), Effect.asVoid); + // Debounce watch events so the file is fully written before we read it. + // Editors emit multiple events per save (truncate, write, rename) and + // `fs.watch` can fire before the content has been flushed to disk. + const debouncedSettingsEvents = fs.watch(settingsDir).pipe( + Stream.filter((event) => { + return ( + event.path === settingsFile || + event.path === settingsPath || + pathService.resolve(settingsDir, event.path) === settingsPathResolved + ); + }), + Stream.debounce(Duration.millis(100)), + ); + + yield* Stream.runForEach(debouncedSettingsEvents, () => revalidateAndEmitSafely).pipe( + Effect.ignoreCause({ log: true }), + Effect.forkIn(watcherScope), + Effect.asVoid, + ); }); const start = Effect.gen(function* () { diff --git a/apps/web/src/lib/serverReactQuery.ts b/apps/web/src/lib/serverReactQuery.ts index 85853e2ee2..37029a3a3e 100644 --- a/apps/web/src/lib/serverReactQuery.ts +++ b/apps/web/src/lib/serverReactQuery.ts @@ -6,6 +6,13 @@ export const serverQueryKeys = { config: () => ["server", "config"] as const, }; +/** + * Server config query options. + * + * `staleTime` is kept short so that push-driven `invalidateQueries` calls in + * the EventRouter always trigger a refetch, and so the query re-fetches when + * the component re-mounts (e.g. navigating away from settings and back). + */ export function serverConfigQueryOptions() { return queryOptions({ queryKey: serverQueryKeys.config(), @@ -13,6 +20,5 @@ export function serverConfigQueryOptions() { const api = ensureNativeApi(); return api.server.getConfig(); }, - staleTime: Infinity, }); } diff --git a/apps/web/src/routes/__root.tsx b/apps/web/src/routes/__root.tsx index 496f27e15e..bc9070a2ed 100644 --- a/apps/web/src/routes/__root.tsx +++ b/apps/web/src/routes/__root.tsx @@ -263,8 +263,14 @@ function EventRouter() { // don't produce duplicate toasts. let subscribed = false; const unsubServerConfigUpdated = onServerConfigUpdated((payload) => { + // Invalidate the config query so active observers refetch fresh data. void queryClient.invalidateQueries({ queryKey: serverQueryKeys.config() }); + if (!subscribed) return; + + // Only show keybindings toasts for keybindings changes (no settings in payload) + if (payload.settings) return; + const issue = payload.issues.find((entry) => entry.kind.startsWith("keybindings.")); if (!issue) { toastManager.add({ diff --git a/packages/shared/src/schemaJson.ts b/packages/shared/src/schemaJson.ts index 190dc097e8..9e38b1f8b8 100644 --- a/packages/shared/src/schemaJson.ts +++ b/packages/shared/src/schemaJson.ts @@ -1,4 +1,14 @@ -import { Cause, Exit, Result, Schema, SchemaIssue } from "effect"; +import { + Cause, + Effect, + Exit, + Option, + Result, + Schema, + SchemaGetter, + SchemaIssue, + SchemaTransformation, +} from "effect"; export const decodeJsonResult = >( schema: S, @@ -32,3 +42,55 @@ export const formatSchemaError = (cause: Cause.Cause) => { ? SchemaIssue.makeFormatterDefault()(squashed.issue) : Cause.pretty(cause); }; + +/** + * A `Getter` that parses a lenient JSON string (tolerating trailing commas + * and JS-style comments) into an unknown value. + * + * Mirrors `SchemaGetter.parseJson()` but uses `parseLenientJson` instead + * of `JSON.parse`. + */ +const parseLenientJsonGetter = SchemaGetter.onSome((input: string) => + Effect.try({ + try: () => { + // Strip single-line comments — alternation preserves quoted strings. + let stripped = input.replace( + /("(?:[^"\\]|\\.)*")|\/\/[^\n]*/g, + (match, stringLiteral: string | undefined) => (stringLiteral ? match : ""), + ); + + // Strip multi-line comments. + stripped = stripped.replace( + /("(?:[^"\\]|\\.)*")|\/\*[\s\S]*?\*\//g, + (match, stringLiteral: string | undefined) => (stringLiteral ? match : ""), + ); + + // Strip trailing commas before `}` or `]`. + stripped = stripped.replace(/,(\s*[}\]])/g, "$1"); + + return Option.some(JSON.parse(stripped)); + }, + catch: (e) => new SchemaIssue.InvalidValue(Option.some(input), { message: String(e) }), + }), +); + +/** + * Schema transformation: lenient JSONC string ↔ unknown. + * + * Same API as `SchemaTransformation.fromJsonString`, but the decode side + * strips trailing commas and JS-style comments before parsing. + * Encoding produces strict JSON via `JSON.stringify`. + */ +export const fromLenientJsonString = new SchemaTransformation.Transformation( + parseLenientJsonGetter, + SchemaGetter.stringifyJson(), +); + +/** + * Build a schema that decodes a lenient JSON string into `A`. + * + * Drop-in replacement for `Schema.fromJsonString(schema)` that tolerates + * trailing commas and comments in the input. + */ +export const fromLenientJson = (schema: S) => + Schema.String.pipe(Schema.decodeTo(schema, fromLenientJsonString));