sailfork / t3code-github / apps/ desktop/ src/ app/ DesktopLinuxUrlHandler.ts

import * as Context from "effect/Context";
import * as Effect from "effect/Effect";
import * as FileSystem from "effect/FileSystem";
import * as Layer from "effect/Layer";
import * as Option from "effect/Option";
import * as Schema from "effect/Schema";
import * as ChildProcess from "effect/process/ChildProcess";
import * as ChildProcessSpawner from "effect/process/ChildProcessSpawner";

import * as ElectronProtocol from "../electron/ElectronProtocol.ts";
import * as DesktopAssets from "./DesktopAssets.ts";
import * as DesktopEnvironment from "./DesktopEnvironment.ts";
import { makeComponentLogger } from "./DesktopObservability.ts";

// AppImage integrators choose the .desktop filename, so setDesktopName cannot identify it for protocol registration.
const { logInfo, logWarning } = makeComponentLogger("desktop-linux-url-handler");

export class DesktopLinuxUrlHandlerRegistrationError extends Schema.TaggedError<DesktopLinuxUrlHandlerRegistrationError>()(
  "DesktopLinuxUrlHandlerRegistrationError",
  {
    step: Schema.Literals(["write-desktop-entry", "set-default-handler"]),
    scheme: Schema.String,
    desktopEntryPath: Schema.optionalKey(Schema.String),
    exitCode: Schema.optionalKey(Schema.Number),
    cause: Schema.optionalKey(Schema.Defect()),
  },
) {
  override get message(): string {
    const exitCode = this.exitCode === undefined ? "" : `, xdg-mime exit code ${this.exitCode}`;
    return `Failed to register the ${this.scheme}:// URL handler (step: ${this.step}${exitCode}).`;
  }
}

const isRegistrationError = Schema.is(DesktopLinuxUrlHandlerRegistrationError);

export class DesktopLinuxUrlHandlerCacheRefreshError extends Schema.TaggedError<DesktopLinuxUrlHandlerCacheRefreshError>()(
  "DesktopLinuxUrlHandlerCacheRefreshError",
  {
    applicationsDir: Schema.String,
    exitCode: Schema.optionalKey(Schema.Number),
    cause: Schema.optionalKey(Schema.Defect()),
  },
) {
  override get message(): string {
    const exitCode =
      this.exitCode === undefined ? "" : `, update-desktop-database exit code ${this.exitCode}`;
    return `Failed to refresh the desktop MIME cache at ${this.applicationsDir}${exitCode}.`;
  }
}

const isCacheRefreshError = Schema.is(DesktopLinuxUrlHandlerCacheRefreshError);

const escapeDesktopEntryString = (value: string): string =>
  value
    .replaceAll("\\", "\\\\")
    .replaceAll("\n", "\\n")
    .replaceAll("\r", "\\r")
    .replaceAll("\t", "\\t");

// Exec values undergo general unescaping then Exec unquoting; escape in reverse order.
export function escapeDesktopEntryExecArgument(value: string): string {
  const quoted = value
    .replaceAll("\\", () => "\\\\")
    .replaceAll("`", () => "\\`")
    .replaceAll("$", () => "\\$")
    .replaceAll('"', () => '\\"')
    .replaceAll("%", () => "%%");
  return escapeDesktopEntryString(`"${quoted}"`);
}

// Legacy xdg-open looks up the first Exec word without unquoting it.
const escapeUrlHandlerExecTarget = (value: string): string =>
  /[ \t\n"'\\><~|&;$*?#()`]/.test(value)
    ? escapeDesktopEntryExecArgument(value)
    : escapeDesktopEntryString(value.replaceAll("%", "%%"));

// The AppImage integration entry owns the window identity. This
// hidden URL-only entry must not compete with it for StartupWMClass matching.
export function renderUrlHandlerDesktopEntry(input: {
  readonly displayName: string;
  readonly execTarget: string;
  readonly scheme: string;
  readonly iconPath?: string;
}): string {
  return [
    "[Desktop Entry]",
    "Type=Application",
    `Name=${escapeDesktopEntryString(input.displayName)}`,
    `Exec=${escapeUrlHandlerExecTarget(input.execTarget)} %U`,
    ...(input.iconPath === undefined ? [] : [`Icon=${escapeDesktopEntryString(input.iconPath)}`]),
    "Terminal=false",
    "NoDisplay=true",
    "StartupNotify=false",
    `MimeType=x-scheme-handler/${input.scheme};`,
    "",
  ].join("\n");
}

// Docks may look up the Wayland app id without a desktop entry; icon theme lookups are case-sensitive.
const LINUX_THEME_ICON_SIZE = "256x256";

function linuxThemeIconNames(desktopEntryName: string): readonly string[] {
  const appId = desktopEntryName.replace(/\.desktop$/u, "");
  return [...new Set([appId.toLowerCase(), appId])];
}

const sameBytes = (left: Uint8Array, right: Uint8Array): boolean =>
  left.length === right.length && left.every((byte, index) => byte === right[index]);

export class DesktopLinuxUrlHandler extends Context.Service<
  DesktopLinuxUrlHandler,
  {
    readonly register: Effect.Effect<void>;
  }
>()("@t3tools/desktop/app/DesktopLinuxUrlHandler") {}

/** @public */
export const make = Effect.gen(function* () {
  const environment = yield* DesktopEnvironment.DesktopEnvironment;
  const fileSystem = yield* FileSystem.FileSystem;
  const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
  const assets = yield* DesktopAssets.DesktopAssets;

  const scheme = ElectronProtocol.getDesktopScheme(environment.isDevelopment);
  const desktopEntryPath = environment.path.join(
    environment.linuxApplicationsDir,
    environment.linuxDesktopEntryName,
  );
  const iconsDir = environment.path.join(environment.linuxApplicationsDir, "..", "icons");
  const iconPath = environment.path.join(iconsDir, `${environment.linuxDesktopEntryName}.png`);
  const hicolorDir = environment.path.join(iconsDir, "hicolor");
  const themeIconDir = environment.path.join(hicolorDir, LINUX_THEME_ICON_SIZE, "apps");

  const writeDesktopEntry = Effect.gen(function* () {
    // Distribution packages that run on a shared Electron set
    // T3CODE_DESKTOP_LAUNCHER_PATH, because process.execPath is that Electron.
    // Inside the mounted AppImage, process.execPath points at a transient
    // /tmp/.mount_* path — the handler must launch the AppImage itself.
    const execTarget = environment.desktopLauncherPath.pipe(
      Option.orElse(() => environment.appImagePath),
      Option.getOrElse(() => process.execPath),
    );
    const content = renderUrlHandlerDesktopEntry({
      displayName: environment.displayName,
      execTarget,
      scheme,
      ...(environment.isPackaged ? { iconPath } : {}),
    });
    // Avoid truncating the pre-ready entry while the portal may be reading it.
    const existing = yield* fileSystem
      .readFileString(desktopEntryPath)
      .pipe(Effect.orElseSucceed(() => null));
    if (existing === content) return;
    yield* fileSystem.makeDirectory(environment.linuxApplicationsDir, { recursive: true });
    yield* fileSystem.writeFileString(desktopEntryPath, content);
  }).pipe(
    Effect.mapError(
      (cause) =>
        new DesktopLinuxUrlHandlerRegistrationError({
          step: "write-desktop-entry",
          scheme,
          desktopEntryPath,
          cause,
        }),
    ),
  );

  const updateDesktopDatabase = Effect.scoped(
    Effect.gen(function* () {
      const command = ChildProcess.make(
        "update-desktop-database",
        [environment.linuxApplicationsDir],
        {
          stdin: "ignore",
          stdout: "ignore",
          stderr: "ignore",
          forceKillAfter: "1 second",
        },
      );
      const handle = yield* spawner.spawn(command);
      const exitCode = yield* handle.exitCode.pipe(Effect.timeout("5 seconds"));
      if (exitCode !== 0) {
        return yield* new DesktopLinuxUrlHandlerCacheRefreshError({
          applicationsDir: environment.linuxApplicationsDir,
          exitCode,
        });
      }
    }),
  ).pipe(
    Effect.mapError((error) =>
      isCacheRefreshError(error)
        ? error
        : new DesktopLinuxUrlHandlerCacheRefreshError({
            applicationsDir: environment.linuxApplicationsDir,
            cause: error,
          }),
    ),
  );

  const refreshIconThemeCache = Effect.scoped(
    Effect.gen(function* () {
      const command = ChildProcess.make("gtk-update-icon-cache", ["-f", "-t", hicolorDir], {
        stdin: "ignore",
        stdout: "ignore",
        stderr: "ignore",
        // Releasing a timed-out helper otherwise waits on SIGTERM indefinitely.
        forceKillAfter: "1 second",
      });
      const handle = yield* spawner.spawn(command);
      return yield* handle.exitCode.pipe(Effect.timeout("5 seconds"));
    }),
  );

  const modifiedAt = (filePath: string) =>
    fileSystem
      .stat(filePath)
      .pipe(Effect.map((info) => Option.getOrUndefined(info.mtime)?.getTime() ?? 0));

  const installThemeIcons = Effect.gen(function* () {
    const source = yield* assets.resolveResourcePath(`icons/${LINUX_THEME_ICON_SIZE}.png`);
    if (Option.isNone(source)) return;
    const icon = yield* fileSystem.readFile(source.value);
    const targets = linuxThemeIconNames(environment.linuxDesktopEntryName).map((name) =>
      environment.path.join(themeIconDir, `${name}.png`),
    );
    let changed = false;
    for (const target of targets) {
      const current = yield* fileSystem.readFile(target).pipe(Effect.option);
      if (Option.isSome(current) && sameBytes(current.value, icon)) continue;
      yield* fileSystem.makeDirectory(themeIconDir, { recursive: true });
      yield* fileSystem.writeFile(target, icon);
      changed = true;
    }
    // Creating a cache would leave GTK reading stale icons from other installers.
    // A newer icon retries a refresh that failed on an earlier launch.
    const cachePath = environment.path.join(hicolorDir, "icon-theme.cache");
    const cachedAt = yield* modifiedAt(cachePath).pipe(Effect.option);
    if (Option.isNone(cachedAt)) return;
    let stale = changed;
    for (const target of targets) {
      if (stale) break;
      if ((yield* modifiedAt(target)) > cachedAt.value) stale = true;
    }
    if (!stale) return;
    const exitCode = yield* refreshIconThemeCache;
    if (exitCode !== 0) {
      yield* logWarning("icon theme cache refresh failed", { hicolorDir, exitCode });
    }
  }).pipe(
    Effect.catch((error) =>
      logWarning("app id theme icon install failed", { themeIconDir, category: error._tag }),
    ),
  );

  const setDefaultHandler = Effect.scoped(
    Effect.gen(function* () {
      const command = ChildProcess.make(
        "xdg-mime",
        ["default", environment.linuxDesktopEntryName, `x-scheme-handler/${scheme}`],
        {
          stdin: "ignore",
          stdout: "ignore",
          stderr: "ignore",
          forceKillAfter: "1 second",
        },
      );
      const handle = yield* spawner.spawn(command);
      const exitCode = yield* handle.exitCode.pipe(Effect.timeout("5 seconds"));
      if (exitCode !== 0) {
        return yield* new DesktopLinuxUrlHandlerRegistrationError({
          step: "set-default-handler",
          scheme,
          exitCode,
        });
      }
    }),
  ).pipe(
    Effect.mapError((error) =>
      isRegistrationError(error)
        ? error
        : new DesktopLinuxUrlHandlerRegistrationError({
            step: "set-default-handler",
            scheme,
            cause: error,
          }),
    ),
  );

  const register = Effect.gen(function* () {
    if (environment.platform !== "linux") {
      return;
    }
    yield* writeDesktopEntry;
    if (!environment.isPackaged) return;

    yield* Effect.gen(function* () {
      const { png } = yield* assets.iconPaths;
      if (Option.isNone(png)) return;
      // The AppImage mount is temporary; the chooser needs the icon after exit.
      yield* fileSystem.makeDirectory(iconsDir, { recursive: true });
      yield* fileSystem.copyFile(png.value, iconPath);
    }).pipe(
      Effect.catch((error) =>
        logWarning("URL handler icon copy failed", { iconPath, category: error.reason._tag }),
      ),
    );

    yield* installThemeIcons;

    yield* updateDesktopDatabase.pipe(
      // GIO verifies scheme associations through mimeinfo.cache. A missing cache updater must not block xdg-mime.
      Effect.catch((error) =>
        logWarning("desktop MIME cache refresh failed", {
          applicationsDir: environment.linuxApplicationsDir,
          message: error.message,
          ...(error.exitCode === undefined ? {} : { exitCode: error.exitCode }),
        }),
      ),
    );

    yield* setDefaultHandler;
    yield* logInfo("registered URL scheme handler", { scheme });
  }).pipe(
    Effect.catch((error) =>
      logWarning("URL scheme handler registration failed", {
        scheme,
        step: error.step,
        message: error.message,
        ...(error.desktopEntryPath === undefined
          ? {}
          : { desktopEntryPath: error.desktopEntryPath }),
        ...(error.exitCode === undefined ? {} : { exitCode: error.exitCode }),
      }),
    ),
    Effect.withSpan("desktop.linuxUrlHandler.register"),
  );

  return DesktopLinuxUrlHandler.of({ register });
});

export const layer = Layer.effect(DesktopLinuxUrlHandler, make);