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

DesktopLinuxUrlHandler.test.ts

768 lines28.9 KB

1import * as NodeServices from "@effect/platform-node/NodeServices";
2import { assert, describe, it } from "@effect/vitest";
3import * as Deferred from "effect/Deferred";
4import * as Effect from "effect/Effect";
5import * as Fiber from "effect/Fiber";
6import * as FileSystem from "effect/FileSystem";
7import * as Layer from "effect/Layer";
8import * as Option from "effect/Option";
9import * as Path from "effect/Path";
10import * as PlatformError from "effect/PlatformError";
11import * as Sink from "effect/Sink";
12import * as Stream from "effect/Stream";
13import * as TestClock from "effect/testing/TestClock";
14import * as ChildProcessSpawner from "effect/process/ChildProcessSpawner";
15​
16import * as DesktopEnvironment from "./DesktopEnvironment.ts";
17import * as DesktopAssets from "./DesktopAssets.ts";
18import * as DesktopLinuxUrlHandler from "./DesktopLinuxUrlHandler.ts";
19​
20interface RecordedRegistration {
21 readonly directories: string[];
22 readonly files: Array<{ readonly path: string; readonly content: string }>;
23 readonly commands: Array<{ readonly command: string; readonly args: ReadonlyArray<string> }>;
24 readonly copies: Array<{ readonly source: string; readonly destination: string }>;
25 readonly binaryReads: string[];
26 readonly binaryWrites: Array<{
27 readonly path: string;
28 readonly bytes: Uint8Array;
29 readonly mode: number | undefined;
30 }>;
32​
33const iconSource = "/tmp/.mount_T3/resources/app.asar/apps/desktop/prod-resources/icon.png";
34const iconPath = "/home/alice/.local/share/icons/com.t3tools.T3Code.desktop.png";
35const iconBytes = new Uint8Array([0x89, 0x50, 0x00, 0xff, 0x80, 0x0a]);
36const currentDesktopEntry = DesktopLinuxUrlHandler.renderUrlHandlerDesktopEntry({
37 displayName: "T3 Code (Alpha)",
38 execTarget: "/home/alice/Applications/T3-Code.AppImage",
39 scheme: "t3code",
40 iconPath,
41});
42const registrationCommands = [
43 { command: "update-desktop-database", args: ["/home/alice/.local/share/applications"] },
44 {
45 command: "xdg-mime",
46 args: ["default", "com.t3tools.T3Code.desktop", "x-scheme-handler/t3code"],
47 },
48];
49​
50const makeEnvironment = (path: Path.Path, overrides: Record<string, unknown> = {}) =>
51 DesktopEnvironment.DesktopEnvironment.of({
52 platform: "linux",
53 isPackaged: true,
54 isDevelopment: false,
55 displayName: "T3 Code (Alpha)",
56 linuxDesktopEntryName: "com.t3tools.T3Code.desktop",
57 linuxWmClass: "t3code",
58 linuxApplicationsDir: "/home/alice/.local/share/applications",
59 appImagePath: Option.some("/home/alice/Applications/T3-Code.AppImage"),
60 path,
61 ...overrides,
62 } as unknown as DesktopEnvironment.DesktopEnvironment["Service"]);
63​
64const mockProcess = (exitCode: number, stalled = false) =>
65 ChildProcessSpawner.makeHandle({
66 pid: ChildProcessSpawner.ProcessId(1),
67 exitCode: stalled ? Effect.never : Effect.succeed(ChildProcessSpawner.ExitCode(exitCode)),
68 isRunning: Effect.succeed(false),
69 kill: () => Effect.void,
70 unref: Effect.succeed(Effect.void),
71 stdin: Sink.drain,
72 stdout: Stream.empty,
73 stderr: Stream.empty,
74 all: Stream.empty,
75 getInputFd: () => Sink.drain,
76 getOutputFd: () => Stream.empty,
77 });
78​
79const layerHandler = (
80 recorded: RecordedRegistration,
81 input: {
82 readonly environment?: Record<string, unknown>;
83 readonly updateDesktopDatabaseExitCode?: number;
84 readonly updateDesktopDatabaseStalled?: boolean;
85 readonly updateDesktopDatabaseStarted?: Deferred.Deferred<void>;
86 readonly xdgMimeExitCode?: number;
87 readonly writeError?: PlatformError.PlatformError;
88 readonly existingEntry?: string;
89 readonly iconSource?: string;
90 readonly existingIcon?: Uint8Array;
91 readonly iconReadError?: PlatformError.PlatformError;
92 } = {},
93) =>
94 DesktopLinuxUrlHandler.layer.pipe(
95 Layer.provide(
96 Layer.mergeAll(
97 Layer.effect(
98 DesktopEnvironment.DesktopEnvironment,
99 Path.Path.pipe(
100 Effect.map((path) => makeEnvironment(path, input.environment)),
101 Effect.provide(Path.layer),
102 ),
103 ),
104 Layer.succeed(DesktopAssets.DesktopAssets, {
105 iconPaths: Effect.succeed({
106 png: Option.fromUndefinedOr(input.iconSource),
107 ico: Option.none(),
108 icns: Option.none(),
109 }),
110 resolveResourcePath: () => Effect.succeedNone,
111 }),
112 FileSystem.layerNoop({
113 copyFile: (source, destination) =>
114 Effect.sync(() => {
115 recorded.copies.push({ source, destination });
116 }),
117 readFile: (path) =>
118 Effect.gen(function* () {
119 recorded.binaryReads.push(path);
120 if (path === input.iconSource) {
121 if (input.iconReadError) return yield* input.iconReadError;
122 return new Uint8Array(iconBytes);
123 }
124 if (path === iconPath && input.existingIcon !== undefined) {
125 return input.existingIcon;
126 }
127 return yield* PlatformError.systemError({
128 _tag: "NotFound",
129 module: "FileSystem",
130 method: "readFile",
131 pathOrDescriptor: path,
132 });
133 }),
134 writeFile: (path, bytes, options) =>
135 Effect.sync(() => {
136 recorded.binaryWrites.push({
137 path,
138 bytes: new Uint8Array(bytes),
139 mode: options?.mode,
140 });
141 }),
142 readFileString: () => Effect.succeed(input.existingEntry ?? ""),
143 makeDirectory: (path) =>
144 Effect.sync(() => {
145 recorded.directories.push(path);
146 }),
147 writeFileString: (path, content) =>
148 input.writeError
149 ? Effect.fail(input.writeError)
150 : Effect.sync(() => {
151 recorded.files.push({ path, content });
152 }),
153 }),
154 Layer.succeed(
155 ChildProcessSpawner.ChildProcessSpawner,
156 ChildProcessSpawner.make((command) => {
157 const childProcess = command as unknown as {
158 readonly command: string;
159 readonly args: ReadonlyArray<string>;
160 };
161 if (childProcess.command === "update-desktop-database") {
162 assert.isTrue(
163 recorded.files.length > 0 || input.existingEntry !== undefined,
164 "the desktop entry must exist before refreshing the MIME cache",
165 );
166 }
167 recorded.commands.push({
168 command: childProcess.command,
169 args: childProcess.args,
170 });
171 const exitCode =
172 childProcess.command === "update-desktop-database"
173 ? (input.updateDesktopDatabaseExitCode ?? 0)
174 : (input.xdgMimeExitCode ?? 0);
175 const handle = mockProcess(
176 exitCode,
177 childProcess.command === "update-desktop-database" &&
178 input.updateDesktopDatabaseStalled === true,
179 );
180 return childProcess.command === "update-desktop-database" &&
181 input.updateDesktopDatabaseStarted
182 ? Deferred.succeed(input.updateDesktopDatabaseStarted, undefined).pipe(
183 Effect.as(handle),
184 )
185 : Effect.succeed(handle);
186 }),
187 ),
188 ),
189 ),
190 );
191​
192const runRegister = (
193 recorded: RecordedRegistration,
194 input: Parameters<typeof layerHandler>[1] = {},
195) =>
196 Effect.gen(function* () {
197 const handler = yield* DesktopLinuxUrlHandler.DesktopLinuxUrlHandler;
198 yield* handler.register;
199 }).pipe(Effect.provide(layerHandler(recorded, input)));
200​
201const emptyRecording = (): RecordedRegistration => ({
202 directories: [],
203 files: [],
204 commands: [],
205 copies: [],
206 binaryReads: [],
207 binaryWrites: [],
208});
209​
210describe("DesktopLinuxUrlHandler", () => {
211 it("renders a scheme-handler desktop entry with freedesktop Exec quoting", () => {
212 const entry = DesktopLinuxUrlHandler.renderUrlHandlerDesktopEntry({
213 displayName: "T3 Code (Nightly)",
214 execTarget: '/home/al ice/Apps/T3 "100%" $HOME\\x.AppImage',
215 scheme: "t3code",
216 iconPath: "/home/al ice/icons/T3\\x.png",
217 });
218​
219 assert.include(entry, "[Desktop Entry]");
220 assert.include(entry, "Name=T3 Code (Nightly)");
221 assert.include(
222 entry,
223 'Exec="/home/al ice/Apps/T3 \\\\"100%%\\\\" \\\\$HOME\\\\\\\\x.AppImage" %U',
224 );
225 assert.include(entry, "NoDisplay=true");
226 assert.notInclude(entry, "StartupWMClass=");
227 assert.include(entry, "MimeType=x-scheme-handler/t3code;");
228 assert.include(entry, "Icon=/home/al ice/icons/T3\\\\x.png");
229 });
230​
231 it.each([
232 {
233 execTarget: "/opt/T3(beta)/t3code.AppImage",
234 execLine: 'Exec="/opt/T3(beta)/t3code.AppImage" %U',
235 },
236 {
237 execTarget: "/opt/t3%20code/t3code.AppImage",
238 execLine: "Exec=/opt/t3%%20code/t3code.AppImage %U",
239 },
240 ])("renders the handler Exec line for $execTarget", ({ execTarget, execLine }) => {
241 const entry = DesktopLinuxUrlHandler.renderUrlHandlerDesktopEntry({
242 displayName: "T3 Code",
243 execTarget,
244 scheme: "t3code",
245 });
246​
247 assert.include(entry.split("\n"), execLine);
248 });
249​
250 it("carries structured context on registration errors", () => {
251 const writeError = new DesktopLinuxUrlHandler.DesktopLinuxUrlHandlerRegistrationError({
252 step: "write-desktop-entry",
253 scheme: "t3code",
254 desktopEntryPath: "/home/alice/.local/share/applications/com.t3tools.T3Code.desktop",
255 cause: new Error("boom"),
256 });
257 assert.equal(
258 writeError.message,
259 "Failed to register the t3code:// URL handler (step: write-desktop-entry).",
260 );
261 assert.equal(
262 writeError.desktopEntryPath,
263 "/home/alice/.local/share/applications/com.t3tools.T3Code.desktop",
264 );
265​
266 const exitError = new DesktopLinuxUrlHandler.DesktopLinuxUrlHandlerRegistrationError({
267 step: "set-default-handler",
268 scheme: "t3code",
269 exitCode: 4,
270 });
271 assert.equal(
272 exitError.message,
273 "Failed to register the t3code:// URL handler (step: set-default-handler, xdg-mime exit code 4).",
274 );
275 });
276​
277 it.effect(
278 "writes the handler entry, refreshes the MIME cache, and claims the scheme default",
279 () => {
280 const recorded = emptyRecording();
281​
282 return Effect.gen(function* () {
283 yield* runRegister(recorded);
284​
285 assert.deepEqual(recorded.directories, ["/home/alice/.local/share/applications"]);
286 assert.equal(recorded.files.length, 1);
287 assert.equal(
288 recorded.files[0]?.path,
289 "/home/alice/.local/share/applications/com.t3tools.T3Code.desktop",
290 );
291 assert.include(
292 recorded.files[0]?.content,
293 "Exec=/home/alice/Applications/T3-Code.AppImage %U",
294 );
295 assert.include(recorded.files[0]?.content, "MimeType=x-scheme-handler/t3code;");
296 assert.deepEqual(recorded.commands, [
297 {
298 command: "update-desktop-database",
299 args: ["/home/alice/.local/share/applications"],
300 },
301 {
302 command: "xdg-mime",
303 args: ["default", "com.t3tools.T3Code.desktop", "x-scheme-handler/t3code"],
304 },
305 ]);
306 });
307 },
308 );
309​
310 it.effect("falls back to the process executable outside an AppImage", () => {
311 const recorded = emptyRecording();
312​
313 return Effect.gen(function* () {
314 yield* runRegister(recorded, { environment: { appImagePath: Option.none() } });
315​
316 assert.include(
317 recorded.files[0]?.content,
318 DesktopLinuxUrlHandler.renderUrlHandlerDesktopEntry({
319 displayName: "T3 Code (Alpha)",
320 execTarget: process.execPath,
321 scheme: "t3code",
322 iconPath: "/home/alice/.local/share/icons/com.t3tools.T3Code.desktop.png",
323 }),
324 );
325 });
326 });
327​
328 it.effect("does not rewrite the pre-ready entry while the portal can be reading it", () => {
329 const recorded = emptyRecording();
330​
331 return Effect.gen(function* () {
332 yield* runRegister(recorded, {
333 existingEntry: DesktopLinuxUrlHandler.renderUrlHandlerDesktopEntry({
334 displayName: "T3 Code (Alpha)",
335 execTarget: "/home/alice/Applications/T3-Code.AppImage",
336 scheme: "t3code",
337 iconPath: "/home/alice/.local/share/icons/com.t3tools.T3Code.desktop.png",
338 }),
339 });
340​
341 assert.deepEqual(recorded.files, []);
342 assert.deepEqual(recorded.directories, []);
343 assert.deepEqual(recorded.commands, [
344 {
345 command: "update-desktop-database",
346 args: ["/home/alice/.local/share/applications"],
347 },
348 {
349 command: "xdg-mime",
350 args: ["default", "com.t3tools.T3Code.desktop", "x-scheme-handler/t3code"],
351 },
352 ]);
353 });
354 });
355​
356 it.effect("installs a persistent icon even when the desktop entry is already current", () => {
357 const recorded = emptyRecording();
358 return Effect.gen(function* () {
359 yield* runRegister(recorded, {
360 iconSource,
361 existingEntry: currentDesktopEntry,
362 });
363 assert.deepEqual(recorded.files, []);
364 assert.deepEqual(recorded.copies, []);
365 assert.deepEqual(recorded.binaryReads, [iconSource, iconPath]);
366 assert.deepEqual(recorded.binaryWrites, [{ path: iconPath, bytes: iconBytes, mode: 0o600 }]);
367 assert.deepEqual(recorded.commands, registrationCommands);
368 });
369 });
370​
371 it.effect("refreshes a stale icon and skips equal bytes on the next registration", () => {
372 const recorded = emptyRecording();
373 return Effect.gen(function* () {
374 yield* runRegister(recorded, {
375 iconSource,
376 existingEntry: currentDesktopEntry,
377 existingIcon: new Uint8Array([0x89, 0x50, 0x00, 0xfe, 0x80, 0x0a]),
378 });
379 assert.deepEqual(recorded.binaryWrites, [{ path: iconPath, bytes: iconBytes, mode: 0o600 }]);
380 yield* runRegister(recorded, {
381 iconSource,
382 existingEntry: currentDesktopEntry,
383 existingIcon: new Uint8Array(recorded.binaryWrites[0]!.bytes),
384 });
385 assert.equal(recorded.binaryWrites.length, 1);
386 assert.deepEqual(recorded.copies, []);
387 assert.deepEqual(recorded.files, []);
388 assert.deepEqual(recorded.commands, [...registrationCommands, ...registrationCommands]);
389 });
390 });
391​
392 it.effect("still registers the handler when reading its icon fails", () => {
393 const recorded = emptyRecording();
394 return Effect.gen(function* () {
395 yield* runRegister(recorded, {
396 iconSource,
397 iconReadError: PlatformError.systemError({
398 _tag: "PermissionDenied",
399 module: "FileSystem",
400 method: "readFile",
401 description: "unreadable bundled icon",
402 }),
403 });
404 assert.deepEqual(recorded.binaryReads, [iconSource]);
405 assert.deepEqual(recorded.binaryWrites, []);
406 assert.deepEqual(recorded.copies, []);
407 assert.equal(recorded.files.length, 1);
408 assert.deepEqual(recorded.commands, registrationCommands);
409 });
410 });
411​
412 it.effect("writes the portal identity without claiming the URL scheme in development", () => {
413 const nonLinux = emptyRecording();
414 const unpackaged = emptyRecording();
415​
416 return Effect.gen(function* () {
417 yield* runRegister(nonLinux, { environment: { platform: "darwin" } });
418 yield* runRegister(unpackaged, {
419 environment: {
420 isPackaged: false,
421 linuxDesktopEntryName: "com.t3tools.T3Code.Development.desktop",
422 },
423 });
424​
425 assert.deepEqual(nonLinux.files, []);
426 assert.equal(
427 unpackaged.files[0]?.path,
428 "/home/alice/.local/share/applications/com.t3tools.T3Code.Development.desktop",
429 );
430 assert.deepEqual(unpackaged.commands, []);
431 });
432 });
433​
434 it.effect("never fails startup when registration cannot complete", () => {
435 const desktopDatabaseFailed = emptyRecording();
436 const xdgMimeFailed = emptyRecording();
437 const writeFailed = emptyRecording();
438​
439 return Effect.gen(function* () {
440 yield* runRegister(desktopDatabaseFailed, { updateDesktopDatabaseExitCode: 1 });
441 yield* runRegister(xdgMimeFailed, { xdgMimeExitCode: 1 });
442 yield* runRegister(writeFailed, {
443 writeError: PlatformError.systemError({
444 _tag: "PermissionDenied",
445 module: "FileSystem",
446 method: "writeFileString",
447 description: "read-only filesystem",
448 pathOrDescriptor: "/home/alice/.local/share/applications/com.t3tools.T3Code.desktop",
449 }),
450 });
451​
452 assert.deepEqual(
453 desktopDatabaseFailed.commands.map(({ command }) => command),
454 ["update-desktop-database", "xdg-mime"],
455 );
456 assert.equal(xdgMimeFailed.files.length, 1);
457 assert.deepEqual(writeFailed.commands, []);
458 });
459 });
460​
461 it.effect("continues to xdg-mime when the desktop MIME cache refresh stalls", () =>
462 Effect.gen(function* () {
463 const recorded = emptyRecording();
464 const started = yield* Deferred.make<void>();
465 const registration = yield* runRegister(recorded, {
466 updateDesktopDatabaseStalled: true,
467 updateDesktopDatabaseStarted: started,
468 }).pipe(Effect.forkChild);
469​
470 yield* Deferred.await(started);
471 yield* TestClock.adjust("5 seconds");
472 yield* Fiber.join(registration);
473​
474 assert.deepEqual(
475 recorded.commands.map(({ command }) => command),
476 ["update-desktop-database", "xdg-mime"],
477 );
478 }),
479 );
480});
481​
482interface 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>;
494​
495const 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​
582const 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 // A fixed time in the past, in whole seconds as fs.utimes expects.
593 const pastSeconds = 1_600_000_000;
594 // An existing cache that predates any installed icon.
595 const seedCache = Effect.gen(function* () {
596 yield* fileSystem.makeDirectory(appsDir, { recursive: true });
597 yield* fileSystem.writeFile(cachePath, new Uint8Array([0]));
598 yield* fileSystem.utimes(cachePath, pastSeconds, pastSeconds);
599 });
600 const rewriteCache = fileSystem
601 .writeFile(cachePath, new Uint8Array([1]))
602 .pipe(Effect.orDie, Effect.provideService(FileSystem.FileSystem, fileSystem));
603 return { root, hicolorDir, appsDir, cachePath, pastSeconds, seedCache, rewriteCache };
604 });
605​
606const iconCacheRuns = (run: ThemeIconRun) =>
607 run.commands.filter(({ command }) => command === "gtk-update-icon-cache").length;
608​
609it.layer(NodeServices.layer)("DesktopLinuxUrlHandler theme icons", (it) => {
610 it.effect("installs both app id spellings without creating an icon cache", () =>
611 Effect.gen(function* () {
612 const fileSystem = yield* FileSystem.FileSystem;
613 const path = yield* Path.Path;
614 const icon = new Uint8Array([137, 80, 78, 71, 1, 2, 3]);
615 const fixture = yield* themeIconFixture(icon);
616 const run: ThemeIconRun = { root: fixture.root, commands: [] };
617​
618 yield* registerWithRealFileSystem(run);
619 assert.deepEqual([...(yield* fileSystem.readDirectory(fixture.appsDir))].sort(), [
620 "com.t3tools.T3Code.png",
621 "com.t3tools.t3code.png",
622 ]);
623 for (const name of ["com.t3tools.t3code", "com.t3tools.T3Code"]) {
624 const target = path.join(fixture.appsDir, `${name}.png`);
625 assert.deepEqual([...(yield* fileSystem.readFile(target))], [...icon]);
626 yield* fileSystem.utimes(target, fixture.pastSeconds, fixture.pastSeconds);
627 }
628​
629 yield* registerWithRealFileSystem(run);
630 for (const name of ["com.t3tools.t3code", "com.t3tools.T3Code"]) {
631 const info = yield* fileSystem.stat(path.join(fixture.appsDir, `${name}.png`));
632 assert.equal(Option.getOrThrow(info.mtime).getTime(), fixture.pastSeconds * 1000);
633 }
634 assert.isFalse(yield* fileSystem.exists(fixture.cachePath));
635 assert.equal(iconCacheRuns(run), 0);
636 }).pipe(Effect.scoped),
637 );
638​
639 it.effect("replaces same-length stale icons and refreshes an existing cache once", () =>
640 Effect.gen(function* () {
641 const fileSystem = yield* FileSystem.FileSystem;
642 const path = yield* Path.Path;
643 const fixture = yield* themeIconFixture(new Uint8Array([1, 2, 3]));
644 yield* fixture.seedCache;
645 const lower = path.join(fixture.appsDir, "com.t3tools.t3code.png");
646 const upper = path.join(fixture.appsDir, "com.t3tools.T3Code.png");
647 yield* fileSystem.writeFile(lower, new Uint8Array([3, 2, 1]));
648 yield* fileSystem.writeFile(upper, new Uint8Array([1, 2, 3]));
649 for (const target of [lower, upper]) {
650 yield* fileSystem.utimes(target, fixture.pastSeconds, fixture.pastSeconds);
651 }
652 const run: ThemeIconRun = {
653 root: fixture.root,
654 commands: [],
655 onIconCacheRefresh: fixture.rewriteCache,
656 };
657​
658 yield* registerWithRealFileSystem(run);
659 yield* registerWithRealFileSystem(run);
660​
661 assert.deepEqual([...(yield* fileSystem.readFile(lower))], [1, 2, 3]);
662 const upperInfo = yield* fileSystem.stat(upper);
663 assert.equal(Option.getOrThrow(upperInfo.mtime).getTime(), fixture.pastSeconds * 1000);
664 assert.deepEqual(
665 run.commands.filter(({ command }) => command === "gtk-update-icon-cache"),
666 [{ command: "gtk-update-icon-cache", args: ["-f", "-t", fixture.hicolorDir] }],
667 );
668 }).pipe(Effect.scoped),
669 );
670​
671 it.effect("refreshes when this launch changed an icon even if the cache looks newer", () =>
672 Effect.gen(function* () {
673 const fileSystem = yield* FileSystem.FileSystem;
674 const path = yield* Path.Path;
675 const fixture = yield* themeIconFixture(new Uint8Array([1, 2, 3]));
676 yield* fixture.seedCache;
677 const run: ThemeIconRun = {
678 root: fixture.root,
679 commands: [],
680 onIconCacheRefresh: fixture.rewriteCache,
681 };
682 // A cache stamped later than the new icons, as after a clock correction.
683 const future = fixture.pastSeconds + 10 * 365 * 24 * 60 * 60;
684 yield* fileSystem.utimes(fixture.cachePath, future, future);
685​
686 yield* registerWithRealFileSystem(run);
687​
688 assert.isTrue(yield* fileSystem.exists(path.join(fixture.appsDir, "com.t3tools.T3Code.png")));
689 assert.equal(iconCacheRuns(run), 1);
690 }).pipe(Effect.scoped),
691 );
692​
693 it.effect("retries a failed icon cache refresh on the next launch", () =>
694 Effect.gen(function* () {
695 const fixture = yield* themeIconFixture(new Uint8Array([1, 2, 3]));
696 yield* fixture.seedCache;
697 const failing: ThemeIconRun = { root: fixture.root, commands: [], iconCacheExitCode: 1 };
698 yield* registerWithRealFileSystem(failing);
699 assert.equal(iconCacheRuns(failing), 1);
700 assert.deepEqual(failing.commands.map(({ command }) => command).slice(1), [
701 "update-desktop-database",
702 "xdg-mime",
703 ]);
704​
705 const recovering: ThemeIconRun = {
706 root: fixture.root,
707 commands: [],
708 onIconCacheRefresh: fixture.rewriteCache,
709 };
710 yield* registerWithRealFileSystem(recovering);
711 yield* registerWithRealFileSystem(recovering);
712 assert.equal(iconCacheRuns(recovering), 1);
713 }).pipe(Effect.scoped),
714 );
715​
716 it.effect("still registers the handler when the theme icon install fails", () =>
717 Effect.gen(function* () {
718 const fixture = yield* themeIconFixture(new Uint8Array([1, 2, 3]));
719 const missingSource: ThemeIconRun = { root: fixture.root, commands: [], sourceMissing: true };
720 yield* registerWithRealFileSystem(missingSource);
721 assert.deepEqual(
722 missingSource.commands.map(({ command }) => command),
723 ["update-desktop-database", "xdg-mime"],
724 );
725​
726 yield* fixture.seedCache;
727 const missingTool: ThemeIconRun = {
728 root: fixture.root,
729 commands: [],
730 iconCacheSpawnFails: true,
731 };
732 yield* registerWithRealFileSystem(missingTool);
733 assert.deepEqual(
734 missingTool.commands.map(({ command }) => command),
735 ["gtk-update-icon-cache", "update-desktop-database", "xdg-mime"],
736 );
737 }).pipe(Effect.scoped),
738 );
739​
740 it.effect("continues to xdg-mime when the icon cache refresh stalls", () =>
741 Effect.gen(function* () {
742 const fixture = yield* themeIconFixture(new Uint8Array([1, 2, 3]));
743 yield* fixture.seedCache;
744 const started = yield* Deferred.make<void>();
745 const iconCacheOptions: Array<Record<string, unknown>> = [];
746 const run: ThemeIconRun = {
747 root: fixture.root,
748 commands: [],
749 iconCacheOptions,
750 iconCacheStalled: true,
751 iconCacheStarted: started,
752 };
753​
754 const registration = yield* registerWithRealFileSystem(run).pipe(Effect.forkChild);
755 yield* Deferred.await(started);
756 yield* TestClock.adjust("5 seconds");
757 yield* Fiber.join(registration);
758​
759 assert.deepEqual(
760 run.commands.map(({ command }) => command),
761 ["gtk-update-icon-cache", "update-desktop-database", "xdg-mime"],
762 );
763 // Without a forced kill, releasing a helper that ignores SIGTERM after
764 // the timeout would still wait for it to exit.
765 assert.equal(iconCacheOptions[0]?.forceKillAfter, "1 second");
766 }).pipe(Effect.scoped),
767 );
768});