Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

DesktopLinuxUrlHandler.test.ts

687 lines26.5 KB

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