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

DesktopLinuxUrlHandler.test.ts

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