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

DesktopLinuxUrlHandler.test.ts

391 lines13.9 KB

1import { assert, describe, it } from "@effect/vitest";
2import * as Deferred from "effect/Deferred";
3import * as Effect from "effect/Effect";
4import * as Fiber from "effect/Fiber";
5import * as FileSystem from "effect/FileSystem";
6import * as Layer from "effect/Layer";
7import * as Option from "effect/Option";
8import * as Path from "effect/Path";
9import * as PlatformError from "effect/PlatformError";
10import * as Sink from "effect/Sink";
11import * as Stream from "effect/Stream";
12import * as TestClock from "effect/testing/TestClock";
13import * as ChildProcessSpawner from "effect/process/ChildProcessSpawner";
14​
15import * as DesktopEnvironment from "./DesktopEnvironment.ts";
16import * as DesktopAssets from "./DesktopAssets.ts";
17import * as DesktopLinuxUrlHandler from "./DesktopLinuxUrlHandler.ts";
18​
19interface RecordedRegistration {
20 readonly directories: string[];
21 readonly files: Array<{ readonly path: string; readonly content: string }>;
22 readonly commands: Array<{ readonly command: string; readonly args: ReadonlyArray<string> }>;
23 readonly copies: Array<{ readonly source: string; readonly destination: string }>;
25​
26const makeEnvironment = (path: Path.Path, overrides: Record<string, unknown> = {}) =>
27 DesktopEnvironment.DesktopEnvironment.of({
28 platform: "linux",
29 isPackaged: true,
30 isDevelopment: false,
31 displayName: "T3 Code (Alpha)",
32 linuxDesktopEntryName: "com.t3tools.T3Code.desktop",
33 linuxWmClass: "t3code",
34 linuxApplicationsDir: "/home/alice/.local/share/applications",
35 appImagePath: Option.some("/home/alice/Applications/T3-Code.AppImage"),
36 path,
37 ...overrides,
38 } as unknown as DesktopEnvironment.DesktopEnvironment["Service"]);
39​
40const mockProcess = (exitCode: number, stalled = false) =>
41 ChildProcessSpawner.makeHandle({
42 pid: ChildProcessSpawner.ProcessId(1),
43 exitCode: stalled ? Effect.never : Effect.succeed(ChildProcessSpawner.ExitCode(exitCode)),
44 isRunning: Effect.succeed(false),
45 kill: () => Effect.void,
46 unref: Effect.succeed(Effect.void),
47 stdin: Sink.drain,
48 stdout: Stream.empty,
49 stderr: Stream.empty,
50 all: Stream.empty,
51 getInputFd: () => Sink.drain,
52 getOutputFd: () => Stream.empty,
53 });
54​
55const layerHandler = (
56 recorded: RecordedRegistration,
57 input: {
58 readonly environment?: Record<string, unknown>;
59 readonly updateDesktopDatabaseExitCode?: number;
60 readonly updateDesktopDatabaseStalled?: boolean;
61 readonly updateDesktopDatabaseStarted?: Deferred.Deferred<void>;
62 readonly xdgMimeExitCode?: number;
63 readonly writeError?: PlatformError.PlatformError;
64 readonly existingEntry?: string;
65 readonly iconSource?: string;
66 readonly iconCopyError?: PlatformError.PlatformError;
67 } = {},
68) =>
69 DesktopLinuxUrlHandler.layer.pipe(
70 Layer.provide(
71 Layer.mergeAll(
72 Layer.effect(
73 DesktopEnvironment.DesktopEnvironment,
74 Path.Path.pipe(
75 Effect.map((path) => makeEnvironment(path, input.environment)),
76 Effect.provide(Path.layer),
77 ),
78 ),
79 Layer.succeed(DesktopAssets.DesktopAssets, {
80 iconPaths: Effect.succeed({
81 png: Option.fromUndefinedOr(input.iconSource),
82 ico: Option.none(),
83 icns: Option.none(),
84 }),
85 resolveResourcePath: () => Effect.succeedNone,
86 }),
87 FileSystem.layerNoop({
88 copyFile: (source, destination) =>
89 input.iconCopyError
90 ? Effect.fail(input.iconCopyError)
91 : Effect.sync(() => {
92 recorded.copies.push({ source, destination });
93 }),
94 readFileString: () => Effect.succeed(input.existingEntry ?? ""),
95 makeDirectory: (path) =>
96 Effect.sync(() => {
97 recorded.directories.push(path);
98 }),
99 writeFileString: (path, content) =>
100 input.writeError
101 ? Effect.fail(input.writeError)
102 : Effect.sync(() => {
103 recorded.files.push({ path, content });
104 }),
105 }),
106 Layer.succeed(
107 ChildProcessSpawner.ChildProcessSpawner,
108 ChildProcessSpawner.make((command) => {
109 const childProcess = command as unknown as {
110 readonly command: string;
111 readonly args: ReadonlyArray<string>;
112 };
113 if (childProcess.command === "update-desktop-database") {
114 assert.isTrue(
115 recorded.files.length > 0 || input.existingEntry !== undefined,
116 "the desktop entry must exist before refreshing the MIME cache",
117 );
118 }
119 recorded.commands.push({
120 command: childProcess.command,
121 args: childProcess.args,
122 });
123 const exitCode =
124 childProcess.command === "update-desktop-database"
125 ? (input.updateDesktopDatabaseExitCode ?? 0)
126 : (input.xdgMimeExitCode ?? 0);
127 const handle = mockProcess(
128 exitCode,
129 childProcess.command === "update-desktop-database" &&
130 input.updateDesktopDatabaseStalled === true,
131 );
132 return childProcess.command === "update-desktop-database" &&
133 input.updateDesktopDatabaseStarted
134 ? Deferred.succeed(input.updateDesktopDatabaseStarted, undefined).pipe(
135 Effect.as(handle),
136 )
137 : Effect.succeed(handle);
138 }),
139 ),
140 ),
141 ),
142 );
143​
144const runRegister = (
145 recorded: RecordedRegistration,
146 input: Parameters<typeof layerHandler>[1] = {},
147) =>
148 Effect.gen(function* () {
149 const handler = yield* DesktopLinuxUrlHandler.DesktopLinuxUrlHandler;
150 yield* handler.register;
151 }).pipe(Effect.provide(layerHandler(recorded, input)));
152​
153const emptyRecording = (): RecordedRegistration => ({
154 directories: [],
155 files: [],
156 commands: [],
157 copies: [],
158});
159​
160describe("DesktopLinuxUrlHandler", () => {
161 it("renders a scheme-handler desktop entry with freedesktop Exec quoting", () => {
162 const entry = DesktopLinuxUrlHandler.renderUrlHandlerDesktopEntry({
163 displayName: "T3 Code (Nightly)",
164 execTarget: '/home/al ice/Apps/T3 "100%" $HOME\\x.AppImage',
165 scheme: "t3code",
166 iconPath: "/home/al ice/icons/T3\\x.png",
167 });
168​
169 assert.include(entry, "[Desktop Entry]");
170 assert.include(entry, "Name=T3 Code (Nightly)");
171 assert.include(
172 entry,
173 'Exec="/home/al ice/Apps/T3 \\\\"100%%\\\\" \\\\$HOME\\\\\\\\x.AppImage" %U',
174 );
175 assert.include(entry, "NoDisplay=true");
176 assert.notInclude(entry, "StartupWMClass=");
177 assert.include(entry, "MimeType=x-scheme-handler/t3code;");
178 assert.include(entry, "Icon=/home/al ice/icons/T3\\\\x.png");
179 });
180​
181 it("carries structured context on registration errors", () => {
182 const writeError = new DesktopLinuxUrlHandler.DesktopLinuxUrlHandlerRegistrationError({
183 step: "write-desktop-entry",
184 scheme: "t3code",
185 desktopEntryPath: "/home/alice/.local/share/applications/com.t3tools.T3Code.desktop",
186 cause: new Error("boom"),
187 });
188 assert.equal(
189 writeError.message,
190 "Failed to register the t3code:// URL handler (step: write-desktop-entry).",
191 );
192 assert.equal(
193 writeError.desktopEntryPath,
194 "/home/alice/.local/share/applications/com.t3tools.T3Code.desktop",
195 );
196​
197 const exitError = new DesktopLinuxUrlHandler.DesktopLinuxUrlHandlerRegistrationError({
198 step: "set-default-handler",
199 scheme: "t3code",
200 exitCode: 4,
201 });
202 assert.equal(
203 exitError.message,
204 "Failed to register the t3code:// URL handler (step: set-default-handler, xdg-mime exit code 4).",
205 );
206 });
207​
208 it.effect(
209 "writes the handler entry, refreshes the MIME cache, and claims the scheme default",
210 () => {
211 const recorded = emptyRecording();
212​
213 return Effect.gen(function* () {
214 yield* runRegister(recorded);
215​
216 assert.deepEqual(recorded.directories, ["/home/alice/.local/share/applications"]);
217 assert.equal(recorded.files.length, 1);
218 assert.equal(
219 recorded.files[0]?.path,
220 "/home/alice/.local/share/applications/com.t3tools.T3Code.desktop",
221 );
222 assert.include(
223 recorded.files[0]?.content,
224 'Exec="/home/alice/Applications/T3-Code.AppImage" %U',
225 );
226 assert.include(recorded.files[0]?.content, "MimeType=x-scheme-handler/t3code;");
227 assert.deepEqual(recorded.commands, [
228 {
229 command: "update-desktop-database",
230 args: ["/home/alice/.local/share/applications"],
231 },
232 {
233 command: "xdg-mime",
234 args: ["default", "com.t3tools.T3Code.desktop", "x-scheme-handler/t3code"],
235 },
236 ]);
237 });
238 },
239 );
240​
241 it.effect("falls back to the process executable outside an AppImage", () => {
242 const recorded = emptyRecording();
243​
244 return Effect.gen(function* () {
245 yield* runRegister(recorded, { environment: { appImagePath: Option.none() } });
246​
247 assert.include(
248 recorded.files[0]?.content,
249 `Exec=${DesktopLinuxUrlHandler.escapeDesktopEntryExecArgument(process.execPath)} %U`,
250 );
251 });
252 });
253​
254 it.effect("does not rewrite the pre-ready entry while the portal can be reading it", () => {
255 const recorded = emptyRecording();
256​
257 return Effect.gen(function* () {
258 yield* runRegister(recorded, {
259 existingEntry: DesktopLinuxUrlHandler.renderUrlHandlerDesktopEntry({
260 displayName: "T3 Code (Alpha)",
261 execTarget: "/home/alice/Applications/T3-Code.AppImage",
262 scheme: "t3code",
263 iconPath: "/home/alice/.local/share/icons/com.t3tools.T3Code.desktop.png",
264 }),
265 });
266​
267 assert.deepEqual(recorded.files, []);
268 assert.deepEqual(recorded.directories, []);
269 assert.deepEqual(recorded.commands, [
270 {
271 command: "update-desktop-database",
272 args: ["/home/alice/.local/share/applications"],
273 },
274 {
275 command: "xdg-mime",
276 args: ["default", "com.t3tools.T3Code.desktop", "x-scheme-handler/t3code"],
277 },
278 ]);
279 });
280 });
281​
282 it.effect("installs a persistent icon even when the desktop entry is already current", () => {
283 const recorded = emptyRecording();
284 const iconPath = "/home/alice/.local/share/icons/com.t3tools.T3Code.desktop.png";
285 return Effect.gen(function* () {
286 yield* runRegister(recorded, {
287 iconSource: "/tmp/.mount_T3/resources/icon.png",
288 existingEntry: DesktopLinuxUrlHandler.renderUrlHandlerDesktopEntry({
289 displayName: "T3 Code (Alpha)",
290 execTarget: "/home/alice/Applications/T3-Code.AppImage",
291 scheme: "t3code",
292 iconPath,
293 }),
294 });
295 assert.deepEqual(recorded.files, []);
296 assert.deepEqual(recorded.copies, [
297 { source: "/tmp/.mount_T3/resources/icon.png", destination: iconPath },
298 ]);
299 assert.equal(recorded.commands.at(-1)?.command, "xdg-mime");
300 });
301 });
302​
303 it.effect("still registers the handler when copying its icon fails", () => {
304 const recorded = emptyRecording();
305 return Effect.gen(function* () {
306 yield* runRegister(recorded, {
307 iconSource: "/tmp/.mount_T3/resources/icon.png",
308 iconCopyError: PlatformError.systemError({
309 _tag: "PermissionDenied",
310 module: "FileSystem",
311 method: "copyFile",
312 description: "read-only icon directory",
313 }),
314 });
315 assert.equal(recorded.files.length, 1);
316 assert.deepEqual(
317 recorded.commands.map(({ command }) => command),
318 ["update-desktop-database", "xdg-mime"],
319 );
320 });
321 });
322​
323 it.effect("writes the portal identity without claiming the URL scheme in development", () => {
324 const nonLinux = emptyRecording();
325 const unpackaged = emptyRecording();
326​
327 return Effect.gen(function* () {
328 yield* runRegister(nonLinux, { environment: { platform: "darwin" } });
329 yield* runRegister(unpackaged, {
330 environment: {
331 isPackaged: false,
332 linuxDesktopEntryName: "com.t3tools.T3Code.Development.desktop",
333 },
334 });
335​
336 assert.deepEqual(nonLinux.files, []);
337 assert.equal(
338 unpackaged.files[0]?.path,
339 "/home/alice/.local/share/applications/com.t3tools.T3Code.Development.desktop",
340 );
341 assert.deepEqual(unpackaged.commands, []);
342 });
343 });
344​
345 it.effect("never fails startup when registration cannot complete", () => {
346 const desktopDatabaseFailed = emptyRecording();
347 const xdgMimeFailed = emptyRecording();
348 const writeFailed = emptyRecording();
349​
350 return Effect.gen(function* () {
351 yield* runRegister(desktopDatabaseFailed, { updateDesktopDatabaseExitCode: 1 });
352 yield* runRegister(xdgMimeFailed, { xdgMimeExitCode: 1 });
353 yield* runRegister(writeFailed, {
354 writeError: PlatformError.systemError({
355 _tag: "PermissionDenied",
356 module: "FileSystem",
357 method: "writeFileString",
358 description: "read-only filesystem",
359 pathOrDescriptor: "/home/alice/.local/share/applications/com.t3tools.T3Code.desktop",
360 }),
361 });
362​
363 assert.deepEqual(
364 desktopDatabaseFailed.commands.map(({ command }) => command),
365 ["update-desktop-database", "xdg-mime"],
366 );
367 assert.equal(xdgMimeFailed.files.length, 1);
368 assert.deepEqual(writeFailed.commands, []);
369 });
370 });
371​
372 it.effect("continues to xdg-mime when the desktop MIME cache refresh stalls", () =>
373 Effect.gen(function* () {
374 const recorded = emptyRecording();
375 const started = yield* Deferred.make<void>();
376 const registration = yield* runRegister(recorded, {
377 updateDesktopDatabaseStalled: true,
378 updateDesktopDatabaseStarted: started,
379 }).pipe(Effect.forkChild);
380​
381 yield* Deferred.await(started);
382 yield* TestClock.adjust("5 seconds");
383 yield* Fiber.join(registration);
384​
385 assert.deepEqual(
386 recorded.commands.map(({ command }) => command),
387 ["update-desktop-database", "xdg-mime"],
388 );
389 }),
390 );
391});