Open History to see the last commit
1import * as Context from "effect/Context";
2import * as Effect from "effect/Effect";
3import * as FileSystem from "effect/FileSystem";
4import * as Layer from "effect/Layer";
5import * as Option from "effect/Option";
6import * as Schema from "effect/Schema";
7import * as ChildProcess from "effect/process/ChildProcess";
8import * as ChildProcessSpawner from "effect/process/ChildProcessSpawner";
9
10import * as ElectronProtocol from "../electron/ElectronProtocol.ts";
11import * as DesktopAssets from "./DesktopAssets.ts";
12import * as DesktopEnvironment from "./DesktopEnvironment.ts";
13import { makeComponentLogger } from "./DesktopObservability.ts";
14
15// Linux ships as an AppImage, so the .desktop entry users end up with is
16// created by whatever integration tool they use (AppImageLauncher names it
17// appimagekit_<hash>-….desktop) and its filename is not under our control.
18// Electron's app.setAsDefaultProtocolClient resolves the desktop id from
19// setDesktopName, which cannot match those files — so the browser keeps
20// prompting "Choose an application" for every OAuth callback.
21const { logInfo, logWarning } = makeComponentLogger("desktop-linux-url-handler");
22
23export class DesktopLinuxUrlHandlerRegistrationError extends Schema.TaggedError<DesktopLinuxUrlHandlerRegistrationError>()(
24 "DesktopLinuxUrlHandlerRegistrationError",
25 {
26 step: Schema.Literals(["write-desktop-entry", "set-default-handler"]),
27 scheme: Schema.String,
28 desktopEntryPath: Schema.optionalKey(Schema.String),
29 exitCode: Schema.optionalKey(Schema.Number),
30 cause: Schema.optionalKey(Schema.Defect()),
31 },
32) {
33 override get message(): string {
34 const exitCode = this.exitCode === undefined ? "" : `, xdg-mime exit code ${this.exitCode}`;
35 return `Failed to register the ${this.scheme}:// URL handler (step: ${this.step}${exitCode}).`;
36 }
37}
38
39const isRegistrationError = Schema.is(DesktopLinuxUrlHandlerRegistrationError);
40
41export class DesktopLinuxUrlHandlerCacheRefreshError extends Schema.TaggedError<DesktopLinuxUrlHandlerCacheRefreshError>()(
42 "DesktopLinuxUrlHandlerCacheRefreshError",
43 {
44 applicationsDir: Schema.String,
45 exitCode: Schema.optionalKey(Schema.Number),
46 cause: Schema.optionalKey(Schema.Defect()),
47 },
48) {
49 override get message(): string {
50 const exitCode =
51 this.exitCode === undefined ? "" : `, update-desktop-database exit code ${this.exitCode}`;
52 return `Failed to refresh the desktop MIME cache at ${this.applicationsDir}${exitCode}.`;
53 }
54}
55
56const isCacheRefreshError = Schema.is(DesktopLinuxUrlHandlerCacheRefreshError);
57
58const escapeDesktopEntryString = (value: string): string =>
59 value
60 .replaceAll("\\", "\\\\")
61 .replaceAll("\n", "\\n")
62 .replaceAll("\r", "\\r")
63 .replaceAll("\t", "\\t");
64
65// Exec values are unescaped twice by implementations: first the general
66// string-value rules, then the Exec quoting rules — so writing composes the
67// layers in reverse.
68export function escapeDesktopEntryExecArgument(value: string): string {
69 const quoted = value
70 .replaceAll("\\", () => "\\\\")
71 .replaceAll("`", () => "\\`")
72 .replaceAll("$", () => "\\$")
73 .replaceAll('"', () => '\\"')
74 .replaceAll("%", () => "%%");
75 return escapeDesktopEntryString(`"${quoted}"`);
76}
77
78// The AppImage integration entry owns the window identity. This
79// hidden URL-only entry must not compete with it for StartupWMClass matching.
80export function renderUrlHandlerDesktopEntry(input: {
81 readonly displayName: string;
82 readonly execTarget: string;
83 readonly scheme: string;
84 readonly iconPath?: string;
85}): string {
86 return [
87 "[Desktop Entry]",
88 "Type=Application",
89 `Name=${escapeDesktopEntryString(input.displayName)}`,
90 `Exec=${escapeDesktopEntryExecArgument(input.execTarget)} %U`,
91 ...(input.iconPath === undefined ? [] : [`Icon=${escapeDesktopEntryString(input.iconPath)}`]),
92 "Terminal=false",
93 "NoDisplay=true",
94 "StartupNotify=false",
95 `MimeType=x-scheme-handler/${input.scheme};`,
96 "",
97 ].join("\n");
98}
99
100// Some docks and bars look the Wayland app id up in the icon theme when no
101// visible desktop entry matches the window, for example an AppImage run without
102// integration. Theme lookups are case-sensitive, so install both spellings.
103const LINUX_THEME_ICON_SIZE = "256x256";
104
105function linuxThemeIconNames(desktopEntryName: string): readonly string[] {
106 const appId = desktopEntryName.replace(/\.desktop$/u, "");
107 return [...new Set([appId.toLowerCase(), appId])];
108}
109
110const sameBytes = (left: Uint8Array, right: Uint8Array): boolean =>
111 left.length === right.length && left.every((byte, index) => byte === right[index]);
112
113export class DesktopLinuxUrlHandler extends Context.Service<
114 DesktopLinuxUrlHandler,
115 {
116 readonly register: Effect.Effect<void>;
117 }
118>()("@t3tools/desktop/app/DesktopLinuxUrlHandler") {}
119
120/** @public Service construction is part of the canonical Effect module API. */
121export const make = Effect.gen(function* () {
122 const environment = yield* DesktopEnvironment.DesktopEnvironment;
123 const fileSystem = yield* FileSystem.FileSystem;
124 const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
125 const assets = yield* DesktopAssets.DesktopAssets;
126
127 const scheme = ElectronProtocol.getDesktopScheme(environment.isDevelopment);
128 const desktopEntryPath = environment.path.join(
129 environment.linuxApplicationsDir,
130 environment.linuxDesktopEntryName,
131 );
132 const iconsDir = environment.path.join(environment.linuxApplicationsDir, "..", "icons");
133 const iconPath = environment.path.join(iconsDir, `${environment.linuxDesktopEntryName}.png`);
134 const hicolorDir = environment.path.join(iconsDir, "hicolor");
135 const themeIconDir = environment.path.join(hicolorDir, LINUX_THEME_ICON_SIZE, "apps");
136
137 const writeDesktopEntry = Effect.gen(function* () {
138 // Inside the mounted AppImage, process.execPath points at a transient
139 // /tmp/.mount_* path — the handler must launch the AppImage itself.
140 const execTarget = Option.getOrElse(environment.appImagePath, () => process.execPath);
141 const content = renderUrlHandlerDesktopEntry({
142 displayName: environment.displayName,
143 execTarget,
144 scheme,
145 ...(environment.isPackaged ? { iconPath } : {}),
146 });
147 // Pre-ready setup normally wrote this already. Avoid truncating a valid
148 // entry while the portal may be reading it during startup.
149 const existing = yield* fileSystem
150 .readFileString(desktopEntryPath)
151 .pipe(Effect.orElseSucceed(() => null));
152 if (existing === content) return;
153 yield* fileSystem.makeDirectory(environment.linuxApplicationsDir, { recursive: true });
154 yield* fileSystem.writeFileString(desktopEntryPath, content);
155 }).pipe(
156 Effect.mapError(
157 (cause) =>
158 new DesktopLinuxUrlHandlerRegistrationError({
159 step: "write-desktop-entry",
160 scheme,
161 desktopEntryPath,
162 cause,
163 }),
164 ),
165 );
166
167 const updateDesktopDatabase = Effect.scoped(
168 Effect.gen(function* () {
169 const command = ChildProcess.make(
170 "update-desktop-database",
171 [environment.linuxApplicationsDir],
172 {
173 stdin: "ignore",
174 stdout: "ignore",
175 stderr: "ignore",
176 },
177 );
178 const handle = yield* spawner.spawn(command);
179 const exitCode = yield* handle.exitCode.pipe(Effect.timeout("5 seconds"));
180 if (exitCode !== 0) {
181 return yield* new DesktopLinuxUrlHandlerCacheRefreshError({
182 applicationsDir: environment.linuxApplicationsDir,
183 exitCode,
184 });
185 }
186 }),
187 ).pipe(
188 Effect.mapError((error) =>
189 isCacheRefreshError(error)
190 ? error
191 : new DesktopLinuxUrlHandlerCacheRefreshError({
192 applicationsDir: environment.linuxApplicationsDir,
193 cause: error,
194 }),
195 ),
196 );
197
198 const refreshIconThemeCache = Effect.scoped(
199 Effect.gen(function* () {
200 const command = ChildProcess.make("gtk-update-icon-cache", ["-f", "-t", hicolorDir], {
201 stdin: "ignore",
202 stdout: "ignore",
203 stderr: "ignore",
204 // Releasing a timed-out helper otherwise waits on SIGTERM indefinitely.
205 forceKillAfter: "1 second",
206 });
207 const handle = yield* spawner.spawn(command);
208 return yield* handle.exitCode.pipe(Effect.timeout("5 seconds"));
209 }),
210 );
211
212 const modifiedAt = (filePath: string) =>
213 fileSystem
214 .stat(filePath)
215 .pipe(Effect.map((info) => Option.getOrUndefined(info.mtime)?.getTime() ?? 0));
216
217 const installThemeIcons = Effect.gen(function* () {
218 const source = yield* assets.resolveResourcePath(`icons/${LINUX_THEME_ICON_SIZE}.png`);
219 if (Option.isNone(source)) return;
220 const icon = yield* fileSystem.readFile(source.value);
221 const targets = linuxThemeIconNames(environment.linuxDesktopEntryName).map((name) =>
222 environment.path.join(themeIconDir, `${name}.png`),
223 );
224 let changed = false;
225 for (const target of targets) {
226 const current = yield* fileSystem.readFile(target).pipe(Effect.option);
227 if (Option.isSome(current) && sameBytes(current.value, icon)) continue;
228 yield* fileSystem.makeDirectory(themeIconDir, { recursive: true });
229 yield* fileSystem.writeFile(target, icon);
230 changed = true;
231 }
232 // Only keep an existing cache current. Creating one would leave GTK reading
233 // a cache that other tools installing user icons do not update. An icon
234 // newer than the cache also retries a refresh that failed on an earlier
235 // launch.
236 const cachePath = environment.path.join(hicolorDir, "icon-theme.cache");
237 const cachedAt = yield* modifiedAt(cachePath).pipe(Effect.option);
238 if (Option.isNone(cachedAt)) return;
239 let stale = changed;
240 for (const target of targets) {
241 if (stale) break;
242 if ((yield* modifiedAt(target)) > cachedAt.value) stale = true;
243 }
244 if (!stale) return;
245 const exitCode = yield* refreshIconThemeCache;
246 if (exitCode !== 0) {
247 yield* logWarning("icon theme cache refresh failed", { hicolorDir, exitCode });
248 }
249 }).pipe(
250 Effect.catch((error) =>
251 logWarning("app id theme icon install failed", { themeIconDir, category: error._tag }),
252 ),
253 );
254
255 const setDefaultHandler = Effect.scoped(
256 Effect.gen(function* () {
257 const command = ChildProcess.make(
258 "xdg-mime",
259 ["default", environment.linuxDesktopEntryName, `x-scheme-handler/${scheme}`],
260 {
261 stdin: "ignore",
262 stdout: "ignore",
263 stderr: "ignore",
264 },
265 );
266 const handle = yield* spawner.spawn(command);
267 const exitCode = yield* handle.exitCode;
268 if ((exitCode as unknown as number) !== 0) {
269 return yield* new DesktopLinuxUrlHandlerRegistrationError({
270 step: "set-default-handler",
271 scheme,
272 exitCode: Number(exitCode),
273 });
274 }
275 }),
276 ).pipe(
277 Effect.mapError((error) =>
278 isRegistrationError(error)
279 ? error
280 : new DesktopLinuxUrlHandlerRegistrationError({
281 step: "set-default-handler",
282 scheme,
283 cause: error,
284 }),
285 ),
286 );
287
288 const register = Effect.gen(function* () {
289 if (environment.platform !== "linux") {
290 return;
291 }
292 yield* writeDesktopEntry;
293 if (!environment.isPackaged) return;
294
295 yield* Effect.gen(function* () {
296 const { png } = yield* assets.iconPaths;
297 if (Option.isNone(png)) return;
298 // The AppImage mount is temporary; the chooser needs the icon after exit.
299 yield* fileSystem.makeDirectory(iconsDir, { recursive: true });
300 yield* fileSystem.copyFile(png.value, iconPath);
301 }).pipe(
302 Effect.catch((error) =>
303 logWarning("URL handler icon copy failed", { iconPath, category: error.reason._tag }),
304 ),
305 );
306
307 yield* installThemeIcons;
308
309 yield* updateDesktopDatabase.pipe(
310 // Some MIME implementations, including GIO, use mimeinfo.cache to verify
311 // that a desktop entry is associated with a scheme. Cache refresh is
312 // independently best-effort so a missing update-desktop-database executable
313 // does not prevent xdg-mime from recording the requested default.
314 Effect.catch((error) =>
315 logWarning("desktop MIME cache refresh failed", {
316 applicationsDir: environment.linuxApplicationsDir,
317 message: error.message,
318 ...(error.exitCode === undefined ? {} : { exitCode: error.exitCode }),
319 }),
320 ),
321 );
322
323 yield* setDefaultHandler;
324 yield* logInfo("registered URL scheme handler", { scheme });
325 }).pipe(
326 Effect.catch((error) =>
327 logWarning("URL scheme handler registration failed", {
328 scheme,
329 step: error.step,
330 message: error.message,
331 ...(error.desktopEntryPath === undefined
332 ? {}
333 : { desktopEntryPath: error.desktopEntryPath }),
334 ...(error.exitCode === undefined ? {} : { exitCode: error.exitCode }),
335 }),
336 ),
337 Effect.withSpan("desktop.linuxUrlHandler.register"),
338 );
339
340 return DesktopLinuxUrlHandler.of({ register });
341});
342
343export const layer = Layer.effect(DesktopLinuxUrlHandler, make);