The best way to control Claude Code, Codex and more from any computer or phone

main
ts 736 lines 28.6 KB
Raw
1 import * as NodeServices from "@effect/platform-node/NodeServices";
2 import { assert, describe, it } from "@effect/vitest";
3 import * as HostProcess from "@t3tools/shared/HostProcess";
4 import * as Cause from "effect/Cause";
5 import * as Deferred from "effect/Deferred";
6 import * as Effect from "effect/Effect";
7 import * as Exit from "effect/Exit";
8 import * as Fiber from "effect/Fiber";
9 import * as FileSystem from "effect/FileSystem";
10 import * as Layer from "effect/Layer";
11 import * as Option from "effect/Option";
12 import * as Path from "effect/Path";
13 import * as PlatformError from "effect/PlatformError";
14 import * as Sink from "effect/Sink";
15 import * as Stream from "effect/Stream";
16 import * as TestClock from "effect/testing/TestClock";
17 import * as ChildProcess from "effect/process/ChildProcess";
18 import * as ChildProcessSpawner from "effect/process/ChildProcessSpawner";
19
20 import * as DesktopEnvironment from "./DesktopEnvironment.ts";
21 import * as DesktopAssets from "./DesktopAssets.ts";
22 import * as DesktopLinuxUrlHandler from "./DesktopLinuxUrlHandler.ts";
23
24 interface RecordedRegistration {
25 readonly directories: string[];
26 readonly files: Array<{ readonly path: string; readonly content: string }>;
27 readonly commands: Array<{ readonly command: string; readonly args: ReadonlyArray<string> }>;
28 readonly copies: Array<{ readonly source: string; readonly destination: string }>;
29 readonly icons: Array<{ readonly path: string; readonly bytes: ReadonlyArray<number> }>;
30 }
31
32 const ICON_BYTES = new Uint8Array([137, 80, 78, 71, 13, 10, 26, 10]);
33
34 const makeEnvironment = (path: Path.Path, overrides: Record<string, unknown> = {}) =>
35 DesktopEnvironment.DesktopEnvironment.of({
36 platform: "linux",
37 isPackaged: true,
38 isDevelopment: false,
39 displayName: "T3 Code (Alpha)",
40 linuxDesktopEntryName: "com.t3tools.T3Code.desktop",
41 linuxApplicationsDir: "/home/alice/.local/share/applications",
42 desktopLauncherPath: Option.none(),
43 appImagePath: Option.some("/home/alice/Applications/T3-Code.AppImage"),
44 path,
45 ...overrides,
46 } as unknown as DesktopEnvironment.DesktopEnvironment["Service"]);
47
48 const mockProcess = (exitCode: number, stalled = false) =>
49 ChildProcessSpawner.makeHandle({
50 pid: ChildProcessSpawner.ProcessId(1),
51 exitCode: stalled ? Effect.never : Effect.succeed(ChildProcessSpawner.ExitCode(exitCode)),
52 isRunning: Effect.succeed(false),
53 kill: () => Effect.void,
54 unref: Effect.succeed(Effect.void),
55 stdin: Sink.drain,
56 stdout: Stream.empty,
57 stderr: Stream.empty,
58 all: Stream.empty,
59 getInputFd: () => Sink.drain,
60 getOutputFd: () => Stream.empty,
61 });
62
63 const layerHandler = (
64 recorded: RecordedRegistration,
65 input: {
66 readonly environment?: Record<string, unknown>;
67 readonly processSpawner?: ChildProcessSpawner.ChildProcessSpawner["Service"];
68 readonly updateDesktopDatabaseExitCode?: number;
69 readonly updateDesktopDatabaseStalled?: boolean;
70 readonly updateDesktopDatabaseStarted?: Deferred.Deferred<void>;
71 readonly xdgMimeExitCode?: number;
72 readonly writeError?: PlatformError.PlatformError;
73 readonly existingEntry?: string;
74 readonly iconSource?: string;
75 readonly iconWriteError?: PlatformError.PlatformError;
76 } = {},
77 ) =>
78 DesktopLinuxUrlHandler.layer.pipe(
79 Layer.provide(
80 Layer.mergeAll(
81 Layer.effect(
82 DesktopEnvironment.DesktopEnvironment,
83 Path.Path.pipe(
84 Effect.map((path) => makeEnvironment(path, input.environment)),
85 Effect.provide(Path.layer),
86 ),
87 ),
88 Layer.succeed(DesktopAssets.DesktopAssets, {
89 iconPaths: Effect.succeed({
90 png: Option.fromUndefinedOr(input.iconSource),
91 ico: Option.none(),
92 icns: Option.none(),
93 }),
94 resolveResourcePath: () => Effect.succeedNone,
95 }),
96 FileSystem.layerNoop({
97 copyFile: (source, destination) =>
98 Effect.sync(() => {
99 recorded.copies.push({ source, destination });
100 }),
101 readFile: (path) =>
102 path === input.iconSource
103 ? Effect.succeed(ICON_BYTES)
104 : Effect.fail(
105 PlatformError.systemError({
106 _tag: "NotFound",
107 module: "FileSystem",
108 method: "readFile",
109 pathOrDescriptor: path,
110 }),
111 ),
112 writeFile: (path, bytes) =>
113 input.iconWriteError
114 ? Effect.fail(input.iconWriteError)
115 : Effect.sync(() => {
116 recorded.icons.push({ path, bytes: [...bytes] });
117 }),
118 readFileString: () => Effect.succeed(input.existingEntry ?? ""),
119 makeDirectory: (path) =>
120 Effect.sync(() => {
121 recorded.directories.push(path);
122 }),
123 writeFileString: (path, content) =>
124 input.writeError
125 ? Effect.fail(input.writeError)
126 : Effect.sync(() => {
127 recorded.files.push({ path, content });
128 }),
129 }),
130 Layer.succeed(
131 ChildProcessSpawner.ChildProcessSpawner,
132 ChildProcessSpawner.make((command) => {
133 if (input.processSpawner) return input.processSpawner.spawn(command);
134 const childProcess = command as unknown as {
135 readonly command: string;
136 readonly args: ReadonlyArray<string>;
137 };
138 if (childProcess.command === "update-desktop-database") {
139 assert.isTrue(
140 recorded.files.length > 0 || input.existingEntry !== undefined,
141 "the desktop entry must exist before refreshing the MIME cache",
142 );
143 }
144 recorded.commands.push({
145 command: childProcess.command,
146 args: childProcess.args,
147 });
148 const exitCode =
149 childProcess.command === "update-desktop-database"
150 ? (input.updateDesktopDatabaseExitCode ?? 0)
151 : (input.xdgMimeExitCode ?? 0);
152 const handle = mockProcess(
153 exitCode,
154 childProcess.command === "update-desktop-database" &&
155 input.updateDesktopDatabaseStalled === true,
156 );
157 return childProcess.command === "update-desktop-database" &&
158 input.updateDesktopDatabaseStarted
159 ? Deferred.succeed(input.updateDesktopDatabaseStarted, undefined).pipe(
160 Effect.as(handle),
161 )
162 : Effect.succeed(handle);
163 }),
164 ),
165 ),
166 ),
167 );
168
169 const runRegister = (
170 recorded: RecordedRegistration,
171 input: Parameters<typeof layerHandler>[1] = {},
172 ) =>
173 Effect.gen(function* () {
174 const handler = yield* DesktopLinuxUrlHandler.DesktopLinuxUrlHandler;
175 yield* handler.register;
176 }).pipe(Effect.provide(layerHandler(recorded, input)));
177
178 const emptyRecording = (): RecordedRegistration => ({
179 directories: [],
180 files: [],
181 commands: [],
182 copies: [],
183 icons: [],
184 });
185
186 describe("DesktopLinuxUrlHandler", () => {
187 it("renders a scheme-handler desktop entry with freedesktop Exec quoting", () => {
188 const entry = DesktopLinuxUrlHandler.renderUrlHandlerDesktopEntry({
189 displayName: "T3 Code (Nightly)",
190 execTarget: '/home/al ice/Apps/T3 "100%" $HOME\\x.AppImage',
191 scheme: "t3code",
192 iconPath: "/home/al ice/icons/T3\\x.png",
193 });
194
195 assert.include(entry, "[Desktop Entry]");
196 assert.include(entry, "Name=T3 Code (Nightly)");
197 assert.include(
198 entry,
199 'Exec="/home/al ice/Apps/T3 \\\\"100%%\\\\" \\\\$HOME\\\\\\\\x.AppImage" %U',
200 );
201 assert.include(entry, "NoDisplay=true");
202 assert.notInclude(entry, "StartupWMClass=");
203 assert.include(entry, "MimeType=x-scheme-handler/t3code;");
204 assert.include(entry, "Icon=/home/al ice/icons/T3\\\\x.png");
205 });
206
207 it.each([
208 { from: "T3-Code-0.1.8-x86_64.AppImage", to: "T3-Code-x86_64.AppImage", restored: true },
209 {
210 from: "T3-Code-0.1.9-nightly.20261110.4449-arm64.AppImage",
211 to: "T3-Code-Nightly-arm64.AppImage",
212 restored: true,
213 },
214 { from: "T3-Code-0.1.8-x86_64.AppImage", to: "T3-Code-0.1.9-x86_64.AppImage", restored: false },
215 { from: "t3code.AppImage", to: "T3-Code-x86_64.AppImage", restored: false },
216 { from: "T3-Code-x86_64.AppImage", to: "T3-Code-x86_64.AppImage", restored: false },
217 { from: "../T3-Code-0.1.8-x86_64.AppImage", to: "T3-Code-x86_64.AppImage", restored: false },
218 ])("finds the launch path an update from $from to $to removed", ({ from, to, restored }) => {
219 for (const dir of ["/home/alice/Applications", '/home/al ice/My "100%" $Apps\\x']) {
220 const previous = dir + "/" + from;
221 const previousEntry = DesktopLinuxUrlHandler.renderUrlHandlerDesktopEntry({
222 displayName: "T3 Code (Beta)",
223 execTarget: previous,
224 scheme: "t3code",
225 });
226 assert.equal(
227 DesktopLinuxUrlHandler.replacedVersionedAppImagePath({
228 previousEntry,
229 appImagePath: dir + "/" + to,
230 }),
231 restored ? previous : null,
232 );
233 }
234 });
235
236 it.effect(
237 "writes the handler entry, refreshes the MIME cache, and claims the scheme default",
238 () => {
239 const recorded = emptyRecording();
240
241 return Effect.gen(function* () {
242 yield* runRegister(recorded);
243
244 assert.deepEqual(recorded.directories, ["/home/alice/.local/share/applications"]);
245 assert.equal(recorded.files.length, 1);
246 assert.equal(
247 recorded.files[0]?.path,
248 "/home/alice/.local/share/applications/com.t3tools.T3Code.desktop",
249 );
250 assert.include(
251 recorded.files[0]?.content,
252 "Exec=/home/alice/Applications/T3-Code.AppImage %U",
253 );
254 assert.include(recorded.files[0]?.content, "MimeType=x-scheme-handler/t3code;");
255 assert.deepEqual(recorded.commands, [
256 {
257 command: "update-desktop-database",
258 args: ["/home/alice/.local/share/applications"],
259 },
260 {
261 command: "xdg-mime",
262 args: ["default", "com.t3tools.T3Code.desktop", "x-scheme-handler/t3code"],
263 },
264 ]);
265 });
266 },
267 );
268
269 it.effect("falls back to the process executable outside an AppImage", () => {
270 const recorded = emptyRecording();
271
272 return Effect.gen(function* () {
273 yield* runRegister(recorded, { environment: { appImagePath: Option.none() } });
274
275 assert.include(
276 recorded.files[0]?.content,
277 DesktopLinuxUrlHandler.renderUrlHandlerDesktopEntry({
278 displayName: "T3 Code (Alpha)",
279 execTarget: process.execPath,
280 scheme: "t3code",
281 iconPath: "/home/alice/.local/share/icons/com.t3tools.T3Code.desktop.png",
282 }),
283 );
284 });
285 });
286
287 it.effect("launches a distribution package through its configured launcher", () => {
288 const recorded = emptyRecording();
289
290 return Effect.gen(function* () {
291 yield* runRegister(recorded, {
292 environment: { desktopLauncherPath: Option.some("/opt/T3 Code/t3code") },
293 });
294
295 assert.include(recorded.files[0]?.content, 'Exec="/opt/T3 Code/t3code" %U');
296 });
297 });
298
299 it.effect("does not rewrite the pre-ready entry while the portal can be reading it", () => {
300 const recorded = emptyRecording();
301
302 return Effect.gen(function* () {
303 yield* runRegister(recorded, {
304 existingEntry: DesktopLinuxUrlHandler.renderUrlHandlerDesktopEntry({
305 displayName: "T3 Code (Alpha)",
306 execTarget: "/home/alice/Applications/T3-Code.AppImage",
307 scheme: "t3code",
308 iconPath: "/home/alice/.local/share/icons/com.t3tools.T3Code.desktop.png",
309 }),
310 });
311
312 assert.deepEqual(recorded.files, []);
313 assert.deepEqual(recorded.directories, []);
314 assert.deepEqual(recorded.commands, [
315 {
316 command: "update-desktop-database",
317 args: ["/home/alice/.local/share/applications"],
318 },
319 {
320 command: "xdg-mime",
321 args: ["default", "com.t3tools.T3Code.desktop", "x-scheme-handler/t3code"],
322 },
323 ]);
324 });
325 });
326
327 it.effect("installs a persistent icon even when the desktop entry is already current", () => {
328 const recorded = emptyRecording();
329 const iconPath = "/home/alice/.local/share/icons/com.t3tools.T3Code.desktop.png";
330 return Effect.gen(function* () {
331 yield* runRegister(recorded, {
332 iconSource: "/tmp/.mount_T3/resources/icon.png",
333 existingEntry: DesktopLinuxUrlHandler.renderUrlHandlerDesktopEntry({
334 displayName: "T3 Code (Alpha)",
335 execTarget: "/home/alice/Applications/T3-Code.AppImage",
336 scheme: "t3code",
337 iconPath,
338 }),
339 });
340 assert.deepEqual(recorded.files, []);
341 assert.deepEqual(recorded.copies, [], "icon must not be copied out of the app bundle");
342 assert.deepEqual(recorded.icons, [{ path: iconPath, bytes: [...ICON_BYTES] }]);
343 assert.equal(recorded.commands.at(-1)?.command, "xdg-mime");
344 });
345 });
346
347 it.effect("still registers the handler when installing its icon fails", () => {
348 const recorded = emptyRecording();
349 return Effect.gen(function* () {
350 yield* runRegister(recorded, {
351 iconSource: "/tmp/.mount_T3/resources/icon.png",
352 iconWriteError: PlatformError.systemError({
353 _tag: "PermissionDenied",
354 module: "FileSystem",
355 method: "writeFile",
356 description: "read-only icon directory",
357 }),
358 });
359 assert.equal(recorded.files.length, 1);
360 assert.deepEqual(
361 recorded.commands.map(({ command }) => command),
362 ["update-desktop-database", "xdg-mime"],
363 );
364 });
365 });
366
367 it.effect("writes the portal identity without claiming the URL scheme in development", () => {
368 const nonLinux = emptyRecording();
369 const unpackaged = emptyRecording();
370
371 return Effect.gen(function* () {
372 yield* runRegister(nonLinux, { environment: { platform: "darwin" } });
373 yield* runRegister(unpackaged, {
374 environment: {
375 isPackaged: false,
376 linuxDesktopEntryName: "com.t3tools.T3Code.Development.desktop",
377 },
378 });
379
380 assert.deepEqual(nonLinux.files, []);
381 assert.equal(
382 unpackaged.files[0]?.path,
383 "/home/alice/.local/share/applications/com.t3tools.T3Code.Development.desktop",
384 );
385 assert.deepEqual(unpackaged.commands, []);
386 });
387 });
388
389 it.effect("never fails startup when registration cannot complete", () => {
390 const desktopDatabaseFailed = emptyRecording();
391 const xdgMimeFailed = emptyRecording();
392 const writeFailed = emptyRecording();
393
394 return Effect.gen(function* () {
395 yield* runRegister(desktopDatabaseFailed, { updateDesktopDatabaseExitCode: 1 });
396 yield* runRegister(xdgMimeFailed, { xdgMimeExitCode: 1 });
397 yield* runRegister(writeFailed, {
398 writeError: PlatformError.systemError({
399 _tag: "PermissionDenied",
400 module: "FileSystem",
401 method: "writeFileString",
402 description: "read-only filesystem",
403 pathOrDescriptor: "/home/alice/.local/share/applications/com.t3tools.T3Code.desktop",
404 }),
405 });
406
407 assert.deepEqual(
408 desktopDatabaseFailed.commands.map(({ command }) => command),
409 ["update-desktop-database", "xdg-mime"],
410 );
411 assert.equal(xdgMimeFailed.files.length, 1);
412 assert.deepEqual(writeFailed.commands, []);
413 });
414 });
415
416 for (const stalledHelper of ["update-desktop-database", "xdg-mime"] as const) {
417 it.effect.skipIf(HostProcess.Platform.defaultValue() !== "linux")(
418 `finishes registration after a timed-out ${stalledHelper} ignores SIGTERM`,
419 () =>
420 Effect.gen(function* () {
421 const realSpawner = yield* ChildProcessSpawner.ChildProcessSpawner;
422 const nodeExecutable = yield* HostProcess.ExecutablePath;
423 const recorded = emptyRecording();
424 const spawned = yield* Deferred.make<ChildProcessSpawner.ChildProcessHandle>();
425 const ready = yield* Deferred.make<void>();
426 const processSpawner = ChildProcessSpawner.make((command) =>
427 Effect.gen(function* () {
428 if (!ChildProcess.isStandardCommand(command)) {
429 return yield* Effect.die("expected a single registration command");
430 }
431 recorded.commands.push({ command: command.command, args: command.args.map(String) });
432 if (command.command !== stalledHelper) return mockProcess(0);
433 const child = yield* realSpawner.spawn(
434 ChildProcess.make(
435 nodeExecutable,
436 [
437 "-e",
438 // The watchdog makes the unfixed case exit with a distinguishable code.
439 "process.on('SIGTERM', () => setTimeout(() => process.exit(99), 5000));" +
440 "process.stdout.write('ready\\n'); setInterval(() => {}, 2147483647);",
441 ],
442 { ...command.options, stdout: "pipe" },
443 ),
444 );
445 yield* Deferred.succeed(spawned, child);
446 yield* Stream.runHead(child.stdout);
447 yield* Deferred.succeed(ready, undefined);
448 return child;
449 }),
450 );
451 const registration = yield* runRegister(recorded, { processSpawner }).pipe(
452 Effect.forkScoped,
453 );
454 const child = yield* Deferred.await(spawned);
455 yield* Effect.addFinalizer(() =>
456 child.isRunning.pipe(
457 Effect.flatMap((running) =>
458 running ? child.kill({ killSignal: "SIGKILL" }) : Effect.void,
459 ),
460 Effect.ignore,
461 ),
462 );
463 yield* Deferred.await(ready);
464 yield* TestClock.adjust("5 seconds");
465 yield* Fiber.join(registration);
466
467 const exit = yield* Effect.exit(child.exitCode);
468 if (Exit.isFailure(exit)) {
469 assert.include(Cause.pretty(exit.cause), "SIGKILL");
470 } else {
471 assert.fail(`${stalledHelper} exited with ${exit.value} instead of being force-killed`);
472 }
473 assert.deepEqual(
474 recorded.commands.map(({ command }) => command),
475 ["update-desktop-database", "xdg-mime"],
476 );
477 }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)),
478 );
479 }
480 });
481
482 interface ThemeIconRun {
483 readonly root: string;
484 readonly commands: Array<{ readonly command: string; readonly args: ReadonlyArray<string> }>;
485 readonly iconCacheOptions?: Array<Record<string, unknown>>;
486 readonly sourceMissing?: boolean;
487 readonly iconCacheExitCode?: number;
488 readonly iconCacheSpawnFails?: boolean;
489 readonly iconCacheStalled?: boolean;
490 readonly iconCacheStarted?: Deferred.Deferred<void>;
491 // Stands in for gtk-update-icon-cache rewriting the cache on success.
492 readonly onIconCacheRefresh?: Effect.Effect<void>;
493 }
494
495 const registerWithRealFileSystem = (run: ThemeIconRun) =>
496 Effect.gen(function* () {
497 const handler = yield* DesktopLinuxUrlHandler.DesktopLinuxUrlHandler;
498 yield* handler.register;
499 }).pipe(
500 Effect.provide(
501 DesktopLinuxUrlHandler.layer.pipe(
502 Layer.provide(
503 Layer.mergeAll(
504 Layer.effect(
505 DesktopEnvironment.DesktopEnvironment,
506 Path.Path.pipe(
507 Effect.map((path) =>
508 makeEnvironment(path, {
509 linuxApplicationsDir: path.join(run.root, "applications"),
510 }),
511 ),
512 ),
513 ),
514 Layer.effect(
515 DesktopAssets.DesktopAssets,
516 Path.Path.pipe(
517 Effect.map((path) => ({
518 iconPaths: Effect.succeed({
519 png: Option.none(),
520 ico: Option.none(),
521 icns: Option.none(),
522 }),
523 resolveResourcePath: (fileName: string) =>
524 Effect.succeed(
525 fileName === "icons/256x256.png"
526 ? Option.some(
527 path.join(
528 run.root,
529 run.sourceMissing ? "missing" : "resources",
530 fileName,
531 ),
532 )
533 : Option.none(),
534 ),
535 })),
536 ),
537 ),
538 Layer.succeed(
539 ChildProcessSpawner.ChildProcessSpawner,
540 ChildProcessSpawner.make((command) => {
541 const childProcess = command as unknown as {
542 readonly command: string;
543 readonly args: ReadonlyArray<string>;
544 };
545 run.commands.push({ command: childProcess.command, args: childProcess.args });
546 if (childProcess.command !== "gtk-update-icon-cache") {
547 return Effect.succeed(mockProcess(0));
548 }
549 run.iconCacheOptions?.push(
550 (command as unknown as { readonly options: Record<string, unknown> }).options,
551 );
552 if (run.iconCacheSpawnFails) {
553 return Effect.fail(
554 PlatformError.systemError({
555 _tag: "NotFound",
556 module: "ChildProcess",
557 method: "spawn",
558 description: "gtk-update-icon-cache is not installed",
559 }),
560 );
561 }
562 const exitCode = run.iconCacheExitCode ?? 0;
563 const handle = mockProcess(exitCode, run.iconCacheStalled === true);
564 const refreshed =
565 exitCode === 0 && run.onIconCacheRefresh ? run.onIconCacheRefresh : Effect.void;
566 return refreshed.pipe(
567 Effect.andThen(
568 run.iconCacheStarted
569 ? Deferred.succeed(run.iconCacheStarted, undefined)
570 : Effect.void,
571 ),
572 Effect.as(handle),
573 );
574 }),
575 ),
576 ),
577 ),
578 ),
579 ),
580 );
581
582 const themeIconFixture = (source: Uint8Array) =>
583 Effect.gen(function* () {
584 const fileSystem = yield* FileSystem.FileSystem;
585 const path = yield* Path.Path;
586 const root = yield* fileSystem.makeTempDirectoryScoped({ prefix: "t3-theme-icons-" });
587 yield* fileSystem.makeDirectory(path.join(root, "resources", "icons"), { recursive: true });
588 yield* fileSystem.writeFile(path.join(root, "resources", "icons", "256x256.png"), source);
589 const hicolorDir = path.join(root, "icons", "hicolor");
590 const appsDir = path.join(hicolorDir, "256x256", "apps");
591 const cachePath = path.join(hicolorDir, "icon-theme.cache");
592 const pastSeconds = 1_600_000_000;
593 const seedCache = Effect.gen(function* () {
594 yield* fileSystem.makeDirectory(appsDir, { recursive: true });
595 yield* fileSystem.writeFile(cachePath, new Uint8Array([0]));
596 yield* fileSystem.utimes(cachePath, pastSeconds, pastSeconds);
597 });
598 const rewriteCache = fileSystem
599 .writeFile(cachePath, new Uint8Array([1]))
600 .pipe(Effect.orDie, Effect.provideService(FileSystem.FileSystem, fileSystem));
601 return { root, hicolorDir, appsDir, cachePath, pastSeconds, seedCache, rewriteCache };
602 });
603
604 const iconCacheRuns = (run: ThemeIconRun) =>
605 run.commands.filter(({ command }) => command === "gtk-update-icon-cache").length;
606
607 it.layer(NodeServices.layer)("DesktopLinuxUrlHandler theme icons", (it) => {
608 it.effect("installs both app id spellings without creating an icon cache", () =>
609 Effect.gen(function* () {
610 const fileSystem = yield* FileSystem.FileSystem;
611 const path = yield* Path.Path;
612 const icon = new Uint8Array([137, 80, 78, 71, 1, 2, 3]);
613 const fixture = yield* themeIconFixture(icon);
614 const run: ThemeIconRun = { root: fixture.root, commands: [] };
615
616 yield* registerWithRealFileSystem(run);
617 assert.deepEqual([...(yield* fileSystem.readDirectory(fixture.appsDir))].sort(), [
618 "com.t3tools.T3Code.png",
619 "com.t3tools.t3code.png",
620 ]);
621 for (const name of ["com.t3tools.t3code", "com.t3tools.T3Code"]) {
622 const target = path.join(fixture.appsDir, `${name}.png`);
623 assert.deepEqual([...(yield* fileSystem.readFile(target))], [...icon]);
624 yield* fileSystem.utimes(target, fixture.pastSeconds, fixture.pastSeconds);
625 }
626
627 yield* registerWithRealFileSystem(run);
628 for (const name of ["com.t3tools.t3code", "com.t3tools.T3Code"]) {
629 const info = yield* fileSystem.stat(path.join(fixture.appsDir, `${name}.png`));
630 assert.equal(Option.getOrThrow(info.mtime).getTime(), fixture.pastSeconds * 1000);
631 }
632 assert.isFalse(yield* fileSystem.exists(fixture.cachePath));
633 assert.equal(iconCacheRuns(run), 0);
634 }),
635 );
636
637 it.effect("replaces same-length stale icons and refreshes an existing cache once", () =>
638 Effect.gen(function* () {
639 const fileSystem = yield* FileSystem.FileSystem;
640 const path = yield* Path.Path;
641 const fixture = yield* themeIconFixture(new Uint8Array([1, 2, 3]));
642 yield* fixture.seedCache;
643 const lower = path.join(fixture.appsDir, "com.t3tools.t3code.png");
644 const upper = path.join(fixture.appsDir, "com.t3tools.T3Code.png");
645 yield* fileSystem.writeFile(lower, new Uint8Array([3, 2, 1]));
646 yield* fileSystem.writeFile(upper, new Uint8Array([1, 2, 3]));
647 for (const target of [lower, upper]) {
648 yield* fileSystem.utimes(target, fixture.pastSeconds, fixture.pastSeconds);
649 }
650 const run: ThemeIconRun = {
651 root: fixture.root,
652 commands: [],
653 onIconCacheRefresh: fixture.rewriteCache,
654 };
655
656 yield* registerWithRealFileSystem(run);
657 yield* registerWithRealFileSystem(run);
658
659 assert.deepEqual([...(yield* fileSystem.readFile(lower))], [1, 2, 3]);
660 const upperInfo = yield* fileSystem.stat(upper);
661 assert.equal(Option.getOrThrow(upperInfo.mtime).getTime(), fixture.pastSeconds * 1000);
662 assert.deepEqual(
663 run.commands.filter(({ command }) => command === "gtk-update-icon-cache"),
664 [{ command: "gtk-update-icon-cache", args: ["-f", "-t", fixture.hicolorDir] }],
665 );
666 }),
667 );
668
669 it.effect("refreshes when this launch changed an icon even if the cache looks newer", () =>
670 Effect.gen(function* () {
671 const fileSystem = yield* FileSystem.FileSystem;
672 const path = yield* Path.Path;
673 const fixture = yield* themeIconFixture(new Uint8Array([1, 2, 3]));
674 yield* fixture.seedCache;
675 const run: ThemeIconRun = {
676 root: fixture.root,
677 commands: [],
678 onIconCacheRefresh: fixture.rewriteCache,
679 };
680 const future = fixture.pastSeconds + 10 * 365 * 24 * 60 * 60;
681 yield* fileSystem.utimes(fixture.cachePath, future, future);
682
683 yield* registerWithRealFileSystem(run);
684
685 assert.isTrue(yield* fileSystem.exists(path.join(fixture.appsDir, "com.t3tools.T3Code.png")));
686 assert.equal(iconCacheRuns(run), 1);
687 }),
688 );
689
690 it.effect("retries a failed icon cache refresh on the next launch", () =>
691 Effect.gen(function* () {
692 const fixture = yield* themeIconFixture(new Uint8Array([1, 2, 3]));
693 yield* fixture.seedCache;
694 const failing: ThemeIconRun = { root: fixture.root, commands: [], iconCacheExitCode: 1 };
695 yield* registerWithRealFileSystem(failing);
696 assert.equal(iconCacheRuns(failing), 1);
697 assert.deepEqual(failing.commands.map(({ command }) => command).slice(1), [
698 "update-desktop-database",
699 "xdg-mime",
700 ]);
701
702 const recovering: ThemeIconRun = {
703 root: fixture.root,
704 commands: [],
705 onIconCacheRefresh: fixture.rewriteCache,
706 };
707 yield* registerWithRealFileSystem(recovering);
708 yield* registerWithRealFileSystem(recovering);
709 assert.equal(iconCacheRuns(recovering), 1);
710 }),
711 );
712
713 it.effect("still registers the handler when the theme icon install fails", () =>
714 Effect.gen(function* () {
715 const fixture = yield* themeIconFixture(new Uint8Array([1, 2, 3]));
716 const missingSource: ThemeIconRun = { root: fixture.root, commands: [], sourceMissing: true };
717 yield* registerWithRealFileSystem(missingSource);
718 assert.deepEqual(
719 missingSource.commands.map(({ command }) => command),
720 ["update-desktop-database", "xdg-mime"],
721 );
722
723 yield* fixture.seedCache;
724 const missingTool: ThemeIconRun = {
725 root: fixture.root,
726 commands: [],
727 iconCacheSpawnFails: true,
728 };
729 yield* registerWithRealFileSystem(missingTool);
730 assert.deepEqual(
731 missingTool.commands.map(({ command }) => command),
732 ["gtk-update-icon-cache", "update-desktop-database", "xdg-mime"],
733 );
734 }),
735 );
736 });