The best way to control Claude Code, Codex and more from any computer or phone
test(server): use the live clock for theme watch notifications (#39598)
Co-authored-by: Julius Marminge <julius0216@outlook.com>
Wout Stiens committed
Nov 20, 2026 at 09:50 UTC
e96357245c3e250c81de851b17053724aa313aef
5 files changed
+373
-39
apps/server/src/environmentTheme.test.ts
+134
-3
@@ -5,7 +5,8 @@ import {
5
THEME_CSS_MAX_LENGTH,
6
} from "@t3tools/contracts";
7
import * as NodeServices from "@effect/platform-node/NodeServices";
8
-import { assert, it } from "@effect/vitest";
8
+import * as HostProcess from "@t3tools/shared/HostProcess";
9
+import { assert, describe, it } from "@effect/vitest";
10
import * as Effect from "effect/Effect";
11
import * as FileSystem from "effect/FileSystem";
12
import * as Layer from "effect/Layer";
@@ -97,14 +98,14 @@ const withEnvironmentThemes = <A, E>(
98
),
99
),
100
);
100
- });
101
+ }).pipe(Effect.provide(NodeServices.layer));
102
103
const currentThemes = Effect.gen(function* () {
104
const environmentTheme = yield* EnvironmentTheme.EnvironmentThemeService;
105
return yield* environmentTheme.current;
106
});
107
107
-it.layer(NodeServices.layer)("environment theme", (it) => {
108
+describe("environment theme", () => {
109
it.effect("follows the directory rather than the set read at start", () =>
110
withEnvironmentThemes(
111
{ "nightfall.json": encodeThemeFile(NIGHTFALL_THEME) },
@@ -159,6 +160,136 @@ it.layer(NodeServices.layer)("environment theme", (it) => {
160
),
161
);
162
163
+ it.live("publishes restored themes to subscribers that saw the directory disappear", () =>
164
+ withEnvironmentThemes(
165
+ { "nightfall.json": encodeThemeFile(NIGHTFALL_THEME) },
166
+ Effect.gen(function* () {
167
+ const service = yield* EnvironmentTheme.EnvironmentThemeService;
168
+ const { environmentThemesDir } = yield* ServerConfig.ServerConfig;
169
+ const fs = yield* FileSystem.FileSystem;
170
+ const path = yield* Path.Path;
171
+ const restored = path.join(path.dirname(environmentThemesDir), "themes-restored");
172
+ yield* fs.makeDirectory(restored);
173
+ yield* fs.writeFileString(
174
+ path.join(restored, "shared-light.json"),
175
+ encodeThemeFile(SHARED_THEME),
176
+ );
177
+
178
+ const snapshots = yield* service.streamChanges.pipe(
179
+ Stream.map((themes) => themes.map((theme) => theme.name)),
180
+ Stream.toQueue({ capacity: "unbounded" }),
181
+ );
182
+ assert.deepEqual(yield* Queue.take(snapshots), ["Nightfall"]);
183
+
184
+ yield* fs.rename(
185
+ environmentThemesDir,
186
+ path.join(path.dirname(restored), "themes-previous"),
187
+ );
188
+ assert.deepEqual(yield* Queue.take(snapshots), []);
189
+
190
+ yield* fs.rename(restored, environmentThemesDir);
191
+ assert.deepEqual(yield* Queue.take(snapshots), ["Shared Light"]);
192
+
193
+ yield* fs.writeFileString(
194
+ path.join(environmentThemesDir, "nightfall.json"),
195
+ encodeThemeFile(NIGHTFALL_THEME),
196
+ );
197
+ assert.deepEqual(yield* Queue.take(snapshots), ["Nightfall", "Shared Light"]);
198
+ }),
199
+ ),
200
+ );
201
+
202
+ it.live.skipIf(!symlinksSupported)(
203
+ "publishes edits after the target of a symlinked themes directory is restored",
204
+ () =>
205
+ withEnvironmentThemes(
206
+ { "nightfall.json": encodeThemeFile(NIGHTFALL_THEME) },
207
+ Effect.gen(function* () {
208
+ const service = yield* EnvironmentTheme.EnvironmentThemeService;
209
+ const { environmentThemesDir } = yield* ServerConfig.ServerConfig;
210
+ const fs = yield* FileSystem.FileSystem;
211
+ const path = yield* Path.Path;
212
+ const outside = yield* fs.makeTempDirectoryScoped({ prefix: "t3code-linked-themes-" });
213
+ const targetParent = path.join(outside, "active-parent");
214
+ const target = path.join(targetParent, "active");
215
+ const restored = path.join(outside, "restored");
216
+ yield* fs.makeDirectory(target, { recursive: true });
217
+ yield* fs.makeDirectory(restored);
218
+ let linkTarget = target;
219
+ if ((yield* HostProcess.Platform) !== "win32") {
220
+ const userdata = path.dirname(environmentThemesDir);
221
+ const anchor = path.join(targetParent, "anchor");
222
+ yield* fs.makeDirectory(anchor);
223
+ yield* fs.makeDirectory(path.join(userdata, "active"));
224
+ yield* fs.symlink(anchor, path.join(userdata, "alias"));
225
+ linkTarget = "alias/../active";
226
+ }
227
+ yield* fs.writeFileString(
228
+ path.join(target, "shared-light.json"),
229
+ encodeThemeFile(SHARED_THEME),
230
+ );
231
+ yield* fs.writeFileString(
232
+ path.join(restored, "nightfall.json"),
233
+ encodeThemeFile(NIGHTFALL_THEME),
234
+ );
235
+
236
+ const snapshots = yield* service.streamChanges.pipe(
237
+ Stream.map((themes) => themes.map((theme) => theme.name)),
238
+ Stream.toQueue({ capacity: "unbounded" }),
239
+ );
240
+ assert.deepEqual(yield* Queue.take(snapshots), ["Nightfall"]);
241
+
242
+ yield* fs.rename(environmentThemesDir, path.join(outside, "original"));
243
+ yield* fs.symlink(linkTarget, environmentThemesDir);
244
+ assert.deepEqual(
245
+ yield* Stream.fromQueue(snapshots).pipe(
246
+ Stream.filter((names) => names.length > 0),
247
+ Stream.runHead,
248
+ Effect.map((names) => names.valueOrUndefined),
249
+ ),
250
+ ["Shared Light"],
251
+ );
252
+
253
+ yield* fs.writeFileString(
254
+ path.join(target, "nightfall.json"),
255
+ encodeThemeFile(NIGHTFALL_THEME),
256
+ );
257
+ assert.deepEqual(yield* Queue.take(snapshots), ["Nightfall", "Shared Light"]);
258
+
259
+ yield* fs.rename(target, path.join(outside, "previous"));
260
+ assert.deepEqual(yield* Queue.take(snapshots), []);
261
+ yield* fs.rename(restored, target);
262
+ assert.deepEqual(yield* Queue.take(snapshots), ["Nightfall"]);
263
+
264
+ yield* fs.writeFileString(
265
+ path.join(target, "shared-light.json"),
266
+ encodeThemeFile(SHARED_THEME),
267
+ );
268
+ assert.deepEqual(yield* Queue.take(snapshots), ["Nightfall", "Shared Light"]);
269
+
270
+ const restoredParent = path.join(outside, "restored-parent");
271
+ const restoredTarget = path.join(restoredParent, "active");
272
+ yield* fs.makeDirectory(restoredTarget, { recursive: true });
273
+ yield* fs.makeDirectory(path.join(restoredParent, "anchor"));
274
+ yield* fs.writeFileString(
275
+ path.join(restoredTarget, "shared-light.json"),
276
+ encodeThemeFile(SHARED_THEME),
277
+ );
278
+
279
+ yield* fs.rename(targetParent, path.join(outside, "previous-parent"));
280
+ assert.deepEqual(yield* Queue.take(snapshots), []);
281
+ yield* fs.rename(restoredParent, targetParent);
282
+ assert.deepEqual(yield* Queue.take(snapshots), ["Shared Light"]);
283
+
284
+ yield* fs.writeFileString(
285
+ path.join(target, "nightfall.json"),
286
+ encodeThemeFile(NIGHTFALL_THEME),
287
+ );
288
+ assert.deepEqual(yield* Queue.take(snapshots), ["Nightfall", "Shared Light"]);
289
+ }),
290
+ ),
291
+ );
292
+
293
it.effect("skips invalid files while keeping valid ones", () =>
294
withEnvironmentThemes(
295
{
apps/server/src/environmentTheme.ts
+27
-2
@@ -22,6 +22,7 @@ import {
22
import * as Cause from "effect/Cause";
23
import * as Context from "effect/Context";
24
import * as DateTime from "effect/DateTime";
25
+import * as Deferred from "effect/Deferred";
26
import * as Duration from "effect/Duration";
27
import * as Effect from "effect/Effect";
28
import * as Equal from "effect/Equal";
@@ -38,6 +39,7 @@ import * as Stream from "effect/Stream";
39
40
import * as ServerConfig from "./config.ts";
41
import * as ServerSettings from "./serverSettings.ts";
42
+import { watchDirectoryPath } from "./watchDirectoryReplacements.ts";
43
44
const decodeEnvironmentThemeFileJsonExit = Schema.decodeUnknownExit(
45
Schema.fromJsonString(EnvironmentThemeFile),
@@ -315,8 +317,31 @@ const make = Effect.gen(function* () {
317
.makeDirectory(environmentThemesDir, { recursive: true })
318
.pipe(Effect.ignoreCause({ log: true }));
319
318
- // A save emits several events, and fs.watch can fire before content is flushed.
319
- const watchEvents = fs.watch(environmentThemesDir).pipe(Stream.debounce(Duration.millis(100)));
320
+ const watchDirectory = (directory: string) =>
321
+ Stream.unwrap(
322
+ Effect.gen(function* () {
323
+ const ready = yield* Deferred.make<void>();
324
+ const markReady = () => Deferred.doneUnsafe(ready, Exit.void);
325
+ const events = fs.watch(directory, { onReady: markReady }).pipe(
326
+ Stream.as(undefined),
327
+ Stream.catchIf(
328
+ (error) => error.reason._tag === "NotFound",
329
+ () => Stream.empty,
330
+ ),
331
+ Stream.ignoreCause({ log: true }),
332
+ Stream.ensuring(Effect.sync(markReady)),
333
+ );
334
+ return Stream.merge(events, Stream.fromEffect(Deferred.await(ready)));
335
+ }),
336
+ );
337
+
338
+ const watchEvents = watchDirectoryPath(
339
+ environmentThemesDir,
340
+ watchDirectory(environmentThemesDir),
341
+ ).pipe(
342
+ // A save emits several events, and fs.watch can fire before content is flushed.
343
+ Stream.debounce(Duration.millis(100)),
344
+ );
345
346
yield* refresh;
347
yield* Stream.runForEach(watchEvents, () => refresh.pipe(Effect.ignoreCause({ log: true }))).pipe(
apps/server/src/serverSettings.ts
+18
-34
@@ -57,6 +57,7 @@ import {
57
import * as ServerSecretStore from "./auth/ServerSecretStore.ts";
58
import * as ManagedPolicy from "./policy/ManagedPolicy.ts";
59
import { secretProviderDefinitions } from "./secrets/secretProviderDefinitions.ts";
60
+import { watchDirectoryReplacements } from "./watchDirectoryReplacements.ts";
61
import {
62
readSecretFieldValues,
63
sourceControlHostSecretName,
@@ -1298,40 +1299,23 @@ const make = Effect.gen(function* () {
1299
// A directory watch follows the directory's inode, so when the target's
1300
// directory is renamed away and another takes its path, watch the new one.
1301
const watchLinkTargetChanges = (linkTargetPath: string, ready: Deferred.Deferred<void>) =>
1301
- Stream.unwrap(
1302
- Effect.gen(function* () {
1303
- const parentReady = yield* Deferred.make<void>();
1304
- const replacements = yield* watchFileChanges(
1305
- pathService.dirname(linkTargetPath),
1306
- parentReady,
1307
- ).pipe(
1308
- // Native watch registration can throw, including when the OS runs out of watches.
1309
- Stream.ignoreCause({ log: true }),
1310
- Stream.toQueue({ capacity: 1, strategy: "sliding" }),
1311
- );
1312
- // Start buffering replacements before attaching to the target directory's inode.
1313
- yield* Deferred.await(parentReady);
1314
-
1315
- const targetChanges = Stream.unwrap(
1316
- Effect.gen(function* () {
1317
- const registered = yield* Deferred.make<void>();
1318
- return Stream.merge(
1319
- watchFileChanges(linkTargetPath, registered).pipe(Stream.ignoreCause({ log: true })),
1320
- // Startup reloads once ready. Later watches trigger their own reload.
1321
- Stream.fromEffect(
1322
- Deferred.await(registered).pipe(Effect.andThen(Deferred.succeed(ready, undefined))),
1323
- ).pipe(
1324
- Stream.filter((completedStartup) => !completedStartup),
1325
- Stream.as(undefined),
1326
- ),
1327
- );
1328
- }),
1329
- );
1330
- return Stream.make(targetChanges).pipe(
1331
- Stream.concat(Stream.fromQueue(replacements).pipe(Stream.as(targetChanges))),
1332
- Stream.switchMap((changes) => changes),
1333
- );
1334
- }),
1302
+ watchDirectoryReplacements(
1303
+ (parentReady) => watchFileChanges(pathService.dirname(linkTargetPath), parentReady),
1304
+ Stream.unwrap(
1305
+ Effect.gen(function* () {
1306
+ const registered = yield* Deferred.make<void>();
1307
+ return Stream.merge(
1308
+ watchFileChanges(linkTargetPath, registered).pipe(Stream.ignoreCause({ log: true })),
1309
+ // Startup reloads once ready. Later watches trigger their own reload.
1310
+ Stream.fromEffect(
1311
+ Deferred.await(registered).pipe(Effect.andThen(Deferred.succeed(ready, undefined))),
1312
+ ).pipe(
1313
+ Stream.filter((completedStartup) => !completedStartup),
1314
+ Stream.as(undefined),
1315
+ ),
1316
+ );
1317
+ }),
1318
+ ),
1319
);
1320
1321
const startWatcher = Effect.gen(function* () {
apps/server/src/watchDirectoryReplacements.ts
new
+119
@@ -0,0 +1,119 @@
1
+// @effect-diagnostics nodeBuiltinImport:off - parent watches need native filename filtering and path resolution.
2
+import * as NodeFS from "node:fs";
3
+import * as NodePath from "node:path";
4
+
5
+import { resolveSymlinkTarget } from "@t3tools/shared/symlink";
6
+import * as Cause from "effect/Cause";
7
+import * as Deferred from "effect/Deferred";
8
+import * as Effect from "effect/Effect";
9
+import * as FileSystem from "effect/FileSystem";
10
+import * as Option from "effect/Option";
11
+import * as Path from "effect/Path";
12
+import * as PlatformError from "effect/PlatformError";
13
+import * as Queue from "effect/Queue";
14
+import * as Stream from "effect/Stream";
15
+
16
+/** Buffer parent events before opening the child watch so a replacement cannot strand it. */
17
+export const watchDirectoryReplacements = <R>(
18
+ watchParent: (ready: Deferred.Deferred<void>) => Stream.Stream<unknown, unknown>,
19
+ watchChild: Stream.Stream<void, never, R>,
20
+) =>
21
+ Stream.unwrap(
22
+ Effect.gen(function* () {
23
+ const ready = yield* Deferred.make<void>();
24
+ const replacements = yield* watchParent(ready).pipe(
25
+ Stream.ignoreCause({ log: true }),
26
+ Stream.ensuring(Deferred.succeed(ready, undefined)),
27
+ Stream.toQueue({ capacity: 1, strategy: "sliding" }),
28
+ );
29
+ yield* Deferred.await(ready);
30
+
31
+ return Stream.make(watchChild).pipe(
32
+ Stream.concat(Stream.fromQueue(replacements).pipe(Stream.as(watchChild))),
33
+ Stream.switchMap((events) => events),
34
+ );
35
+ }),
36
+ );
37
+
38
+const watchDirectoryEntry = (path: string, ready: Deferred.Deferred<void>) => {
39
+ const directory = NodePath.dirname(path);
40
+ const name = NodePath.basename(path);
41
+ const watchError = (cause: unknown) =>
42
+ PlatformError.systemError({
43
+ _tag: "Unknown",
44
+ module: "FileSystem",
45
+ method: "watch",
46
+ pathOrDescriptor: directory,
47
+ cause,
48
+ });
49
+ // Filter in the native callback to avoid queueing and statting unrelated entries.
50
+ return Stream.callback<void, PlatformError.PlatformError>(
51
+ (events) =>
52
+ Effect.acquireRelease(
53
+ Effect.try({
54
+ try: () => {
55
+ const watcher = NodeFS.watch(directory, (_, filename) => {
56
+ if (filename === name || filename === null) Queue.offerUnsafe(events, undefined);
57
+ });
58
+ watcher.on("error", (error) =>
59
+ Queue.failCauseUnsafe(events, Cause.fail(watchError(error))),
60
+ );
61
+ watcher.on("close", () => Queue.endUnsafe(events));
62
+ return watcher;
63
+ },
64
+ catch: watchError,
65
+ }),
66
+ (watcher) => Effect.sync(() => watcher.close()),
67
+ ).pipe(Effect.tap(() => Deferred.succeed(ready, undefined))),
68
+ { bufferSize: 1, strategy: "sliding" },
69
+ );
70
+};
71
+
72
+// Node's JS realpath can collapse `..` before resolving a symlink in the preceding segment.
73
+const realPath = (entry: string) =>
74
+ Effect.callback<string, NodeJS.ErrnoException>((resume) => {
75
+ NodeFS.realpath.native(entry, (error, resolved) => {
76
+ resume(error ? Effect.fail(error) : Effect.succeed(resolved));
77
+ });
78
+ });
79
+
80
+const resolveWatchTarget = Effect.fn("watchDirectoryReplacements.resolveWatchTarget")(function* (
81
+ entry: string,
82
+) {
83
+ const fs = yield* FileSystem.FileSystem;
84
+ const path = yield* Path.Path;
85
+ const link = yield* fs.readLink(entry).pipe(Effect.option);
86
+ if (Option.isNone(link)) return entry;
87
+
88
+ const resolved = yield* realPath(entry).pipe(Effect.option);
89
+ if (Option.isSome(resolved)) return resolved.value;
90
+
91
+ // A dangling link needs a watch on the directory where its target should appear.
92
+ const rawTarget = path.isAbsolute(link.value)
93
+ ? link.value
94
+ : `${path.dirname(entry)}${path.sep}${link.value}`;
95
+ const parent = yield* realPath(path.dirname(rawTarget)).pipe(Effect.option);
96
+ const unresolved = Option.isSome(parent)
97
+ ? path.join(parent.value, path.basename(rawTarget))
98
+ : entry;
99
+ return yield* resolveSymlinkTarget(unresolved).pipe(Effect.orElseSucceed(() => unresolved));
100
+});
101
+
102
+/** Watch replacements of a configured directory, its symlink target, and the target's parent. */
103
+export const watchDirectoryPath = (directory: string, watchChild: Stream.Stream<void>) => {
104
+ const entry = NodePath.resolve(directory);
105
+ return watchDirectoryReplacements(
106
+ (ready) => watchDirectoryEntry(entry, ready),
107
+ Stream.unwrap(
108
+ resolveWatchTarget(entry).pipe(
109
+ Effect.map((target) => {
110
+ if (target === entry) return watchChild;
111
+ return watchDirectoryReplacements(
112
+ (ready) => watchDirectoryEntry(NodePath.dirname(target), ready),
113
+ watchDirectoryReplacements((ready) => watchDirectoryEntry(target, ready), watchChild),
114
+ );
115
+ }),
116
+ ),
117
+ ),
118
+ );
119
+};
scripts/scenarios/restored-theme-directory-stays-live.e2e.ts
new
+75
@@ -0,0 +1,75 @@
1
+import { expect } from "e2e";
2
+import * as Effect from "effect/Effect";
3
+import * as FileSystem from "effect/FileSystem";
4
+
5
+import { T3_HOME } from "../e2e.config.ts";
6
+import { runPromise, test, WEB } from "./t3.ts";
7
+
8
+test(
9
+ "Appearance reflects new edits after the environment theme directory is restored",
10
+ WEB,
11
+ async ({ t3, app, screen }) => {
12
+ await t3.project("theme-directory");
13
+ const themes = `${T3_HOME}/userdata/themes`;
14
+ const previous = `${T3_HOME}/themes-before-restore`;
15
+ const restored = `${T3_HOME}/themes-to-restore`;
16
+ const file = "restore-fixture.json";
17
+ const contents = (name: string) =>
18
+ JSON.stringify({
19
+ version: 1,
20
+ name,
21
+ appearance: "dark",
22
+ colors: { canvas: "#171820", accent: "#7aa2f7" },
23
+ });
24
+ await runPromise(
25
+ Effect.gen(function* () {
26
+ const fs = yield* FileSystem.FileSystem;
27
+ yield* fs.writeFileString(`${themes}/${file}`, contents("Original Palette"));
28
+ yield* fs.makeDirectory(restored);
29
+ yield* fs.writeFileString(`${restored}/${file}`, contents("Restored Palette"));
30
+ }),
31
+ );
32
+ try {
33
+ await t3.open("/settings/appearance");
34
+ await screen.getByRole("button", "Use Original Palette theme", { exact: true }).waitFor();
35
+ await runPromise(
36
+ Effect.gen(function* () {
37
+ const fs = yield* FileSystem.FileSystem;
38
+ yield* fs.rename(themes, previous);
39
+ yield* fs.rename(restored, themes);
40
+ }),
41
+ );
42
+ // Wait for the rename event to be reflected before editing the replacement directory.
43
+ const restoredTheme = screen.getByRole("button", "Use Restored Palette theme", {
44
+ exact: true,
45
+ });
46
+ await restoredTheme.waitFor();
47
+ await restoredTheme.scrollIntoView();
48
+
49
+ await runPromise(
50
+ Effect.flatMap(FileSystem.FileSystem, (fs) =>
51
+ fs.writeFileString(`${themes}/${file}`, contents("Edited Restored Palette")),
52
+ ),
53
+ );
54
+ try {
55
+ await expect(
56
+ screen.getByRole("button", "Use Edited Restored Palette theme", { exact: true }),
57
+ ).toBeVisible();
58
+ } finally {
59
+ await app.screenshot("appearance-after-editing-restored-theme");
60
+ }
61
+ } finally {
62
+ await runPromise(
63
+ Effect.gen(function* () {
64
+ const fs = yield* FileSystem.FileSystem;
65
+ if (yield* fs.exists(previous)) {
66
+ yield* fs.remove(themes, { recursive: true, force: true });
67
+ yield* fs.rename(previous, themes);
68
+ }
69
+ yield* fs.remove(`${themes}/${file}`, { force: true });
70
+ yield* fs.remove(restored, { recursive: true, force: true });
71
+ }),
72
+ );
73
+ }
74
+ },
75
+);