Skip to content

Shared task board where people and AI coding agents work as teammates. Source-available, self-hostable.

Go
24.1 KB
Raw Blame
import { contextBridge, ipcRenderer } from "electron";
import { electronAPI } from "@electron-toolkit/preload";
import type { RuntimeConfigResult } from "../shared/runtime-config";
import type { FreezeBreadcrumb } from "../shared/freeze-breadcrumb";
import type {
  ManualUpdateCheckResult,
  UpdaterDownloadState,
  UpdaterPreferences,
} from "../shared/updater-types";
import {
  RENDERER_ROUTE_CONTEXT_CHANNEL,
  type RendererRouteContextInput,
} from "../shared/renderer-route-context";
import {
  isNavigationGesture,
  NAVIGATION_GESTURE_CHANNEL,
  type NavigationGesture,
} from "../shared/navigation-gestures";
import {
  readDesktopWindowContext,
  type IssueWindowRequest,
} from "../shared/issue-window";
import { AUTH_SESSION_STATE_CHANNEL } from "../shared/auth-session";
import {
  DEV_TOOLBAR_VISIBLE_CHANGED_CHANNEL,
  DEV_TOOLBAR_VISIBLE_GET_CHANNEL,
} from "../shared/dev-toolbar";
import {
  CONTEXT_MENU_COMMAND_CHANNEL,
  CONTEXT_MENU_REQUEST_CHANNEL,
  isContextMenuRequest,
  type ContextMenuCommand,
  type ContextMenuRequest,
} from "../shared/context-menu";
import {
  THEME_FOLDER_CHANGED_CHANNEL,
  THEME_FOLDER_OPEN_CHANNEL,
  THEME_FOLDER_READ_CHANNEL,
  THEME_FOLDER_WRITE_CHANNEL,
  type ThemeFolderFile,
  type ThemeFolderSnapshot,
  type ThemeFolderWriteResult,
} from "../shared/theme-folder";
import type {
  DaemonStatus,
  LocalRuntimeProbe,
} from "../shared/daemon-types";
import {
  VOICE_HISTORY_AUDIO_CHANNEL,
  VOICE_HISTORY_CHANGED_CHANNEL,
  VOICE_HISTORY_LIST_CHANNEL,
  VOICE_HISTORY_RETENTION_CHANNEL,
  VOICE_HISTORY_CLEAR_CHANNEL,
  VOICE_HISTORY_REMOVE_CHANNEL,
  VOICE_HISTORY_SAVE_CHANNEL,
  VOICE_HISTORY_UPDATE_CHANNEL,
  VOICE_MODEL_CANCEL_CHANNEL,
  VOICE_MODEL_DELETE_CHANNEL,
  VOICE_MODEL_DOWNLOAD_CHANNEL,
  VOICE_MODELS_CHANGED_CHANNEL,
  VOICE_MODELS_LIST_CHANNEL,
  VOICE_PREPARE_CHANNEL,
  VOICE_TRANSCRIBE_CHANNEL,
  type VoiceHistoryAudio,
  type VoiceHistoryEntry,
  type VoiceHistorySaveRequest,
  type VoiceHistoryUpdate,
  type VoiceModelRequest,
  type VoiceModelsSnapshot,
  type VoiceTranscribeRequest,
  type VoiceTranscribeResult,
} from "../shared/voice";
import {
  MAIN_RENDERER_CHANNEL_STATE_CHANNEL,
  NEW_WINDOW_SHORTCUT_CHANNEL,
  parseTabSelectionShortcutKey,
  TAB_SELECTION_SHORTCUT_CHANNEL,
  WORKSPACE_OPEN_PATH_CHANNEL,
  type MainRendererMessageChannel,
  type TabSelectionShortcutKey,
} from "../shared/main-renderer-messages";
import {
  FOCUS_WORKSPACE_WINDOW_CHANNEL,
  OPEN_WORKSPACE_WINDOW_CHANNEL,
  OTHER_WINDOW_WORKSPACES_CHANNEL,
  WINDOW_WORKSPACE_REPORT_CHANNEL,
  type WorkspacePathOptions,
  type WorkspacePathRequest,
} from "../shared/workspace-window";

// Synchronously fetch app metadata from main at preload time so the renderer
// can pass it into CoreProvider during the initial render — the alternative
// (async ipc.invoke) would race the ApiClient construction in initCore and
// the first few HTTP requests would go out without X-Client-Version/OS.
function fetchAppInfo(): { version: string; os: "macos" | "windows" | "linux" | "unknown" } {
  try {
    const info = ipcRenderer.sendSync("app:get-info") as
      | { version: string; os: "macos" | "windows" | "linux" | "unknown" }
      | undefined;
    if (info && typeof info.version === "string" && typeof info.os === "string") return info;
  } catch {
    // fall through
  }
  // Fallback: derive OS from process.platform; version unknown.
  const p = process.platform;
  const os: "macos" | "windows" | "linux" | "unknown" =
    p === "darwin" ? "macos" : p === "win32" ? "windows" : p === "linux" ? "linux" : "unknown";
  return { version: "unknown", os };
}

function fetchRuntimeConfig(): RuntimeConfigResult {
  try {
    const result = ipcRenderer.sendSync("runtime-config:get") as RuntimeConfigResult | undefined;
    if (result && typeof result === "object" && "ok" in result) return result;
  } catch (err) {
    return {
      ok: false,
      error: {
        message: err instanceof Error ? err.message : String(err),
      },
    };
  }
  return { ok: false, error: { message: "Runtime config unavailable" } };
}

const appInfo = fetchAppInfo();
const runtimeConfig = fetchRuntimeConfig();
const windowContext = readDesktopWindowContext(process.argv);

// Read the OS-preferred locale that main injected via additionalArguments.
// Zero IPC, zero blocking — process.argv is populated before preload runs.
function fetchSystemLocale(): string {
  const arg = process.argv.find((a) => a.startsWith("--multica-locale="));
  return arg?.split("=")[1] ?? "en";
}

const systemLocale = fetchSystemLocale();

function subscribeToMainRendererChannel<T>(
  channel: MainRendererMessageChannel,
  callback: (payload: T) => void,
): () => void {
  const handler = (_event: Electron.IpcRendererEvent, payload: T) =>
    callback(payload);
  ipcRenderer.on(channel, handler);
  ipcRenderer.send(MAIN_RENDERER_CHANNEL_STATE_CHANNEL, {
    channel,
    ready: true,
  });
  return () => {
    ipcRenderer.removeListener(channel, handler);
    ipcRenderer.send(MAIN_RENDERER_CHANNEL_STATE_CHANNEL, {
      channel,
      ready: false,
    });
  };
}

const desktopAPI = {
  /** App version + normalized OS. Read once at preload time so the renderer
   *  can use it synchronously when initializing the API client. */
  appInfo,
  /** OS-preferred locale (BCP 47), passed from main via additionalArguments.
   *  Used by the renderer's LocaleAdapter as the system-preference signal. */
  systemLocale,
  /** Report the renderer's resolved in-app locale to main so native dialogs
   *  and daemon error messages follow the user's Settings choice. */
  setLocale: (locale: string) => {
    ipcRenderer.send("locale:set", locale);
  },
  /** Subscribe to OS language changes detected after boot. The renderer
   *  decides whether to act (no-op when the user has an explicit Settings
   *  choice). Returns an unsubscribe function. */
  onSystemLocaleChanged: (callback: (locale: string) => void) => {
    const handler = (_event: Electron.IpcRendererEvent, locale: string) =>
      callback(locale);
    ipcRenderer.on("locale:system-changed", handler);
    return () => {
      ipcRenderer.removeListener("locale:system-changed", handler);
    };
  },
  /** Validated runtime endpoint config, or a blocking config error. */
  runtimeConfig,
  /** Identifies whether this renderer owns the main tabbed window or a
   *  dedicated issue window, parsed from validated launch arguments. */
  windowContext,
  /** Read any freeze/crash breadcrumb left by a previous session, so the
   *  renderer can flush it to telemetry on boot. Returns null when there's
   *  nothing pending (the normal case). Reading does not consume it — call
   *  `ackFreeze` once the event is on the wire. */
  getLastFreeze: (): FreezeBreadcrumb | null => {
    try {
      return ipcRenderer.sendSync("freeze:get-last") as FreezeBreadcrumb | null;
    } catch {
      return null;
    }
  },
  /** Retire the breadcrumb with this exact timestamp after its event has been
   *  handed to analytics. Anything left unacknowledged is retried next boot. */
  ackFreeze: (ts: number) => ipcRenderer.send("freeze:ack", ts),
  /** Report only the resolved user id (never a token) so main can close
   *  dedicated issue windows that belong to an old account. */
  reportAuthSession: (userId: string | null) =>
    ipcRenderer.send(AUTH_SESSION_STATE_CHANNEL, userId),
  /** Listen for auth token delivered via deep link */
  onAuthToken: (callback: (token: string) => void) =>
    subscribeToMainRendererChannel("auth:token", callback),
  /** Listen for invitation IDs delivered via deep link */
  onInviteOpen: (callback: (invitationId: string) => void) =>
    subscribeToMainRendererChannel("invite:open", callback),
  onIssueOpen: (callback: (url: string) => void) =>
    subscribeToMainRendererChannel("issue:open", callback),
  /** Open a URL in the default browser */
  openExternal: (url: string) => ipcRenderer.invoke("shell:openExternal", url),
  /** Download a file by URL through Electron's native download system.
   *  Shows a save dialog and saves to disk. Unlike openExternal, this
   *  avoids browser rendering of HTML files on Linux.
   *  On non-desktop platforms this property is undefined. */
  downloadURL: (url: string) => ipcRenderer.invoke("file:download-url", url),
  /** Toggle immersive mode — hide macOS traffic lights for full-screen modals */
  setImmersiveMode: (immersive: boolean) =>
    ipcRenderer.invoke("window:setImmersive", immersive),
  /**
   * Show a native OS notification. The source workspace and either the inbox
   * selector or chat session are round-tripped on click. Main owns focus
   * gating and deduplication across windows.
   */
  showNotification: (payload: {
    slug: string;
    itemId: string;
    issueKey?: string;
    chatSessionId?: string;
    title: string;
    body: string;
  }) => ipcRenderer.send("notification:show", payload),
  getWindowForeground: (): Promise<boolean> => ipcRenderer.invoke("window:foreground"),
  onWindowForegroundChanged: (callback: (foreground: boolean) => void) => {
    const handler = (_event: Electron.IpcRendererEvent, foreground: unknown) => {
      if (typeof foreground === "boolean") callback(foreground);
    };
    ipcRenderer.on("window:foreground-changed", handler);
    return () => ipcRenderer.removeListener("window:foreground-changed", handler);
  },
  /**
   * Update the OS dock / taskbar unread badge. Pass 0 to clear. Values
   * above 99 render as "99+" (capping is handled in the main process).
   */
  setUnreadBadge: (count: number) =>
    ipcRenderer.send("badge:set", Math.max(0, Math.floor(count))),
  /**
   * Subscribe to inbox/chat navigation from an OS notification click.
   * The existing channel also carries direct chat targets.
   */
  onInboxOpen: (
    callback: (payload: {
      slug: string;
      itemId: string;
      issueKey?: string;
      chatSessionId?: string;
    }) => void,
  ) => subscribeToMainRendererChannel("inbox:open", callback),
  /** Listen for native macOS back/forward swipe gestures. */
  onNavigationGesture: (callback: (gesture: NavigationGesture) => void) => {
    const handler = (_event: Electron.IpcRendererEvent, gesture: unknown) => {
      if (isNavigationGesture(gesture)) callback(gesture);
    };
    ipcRenderer.on(NAVIGATION_GESTURE_CHANNEL, handler);
    return () => {
      ipcRenderer.removeListener(NAVIGATION_GESTURE_CHANNEL, handler);
    };
  },
  /** Listen for right-clicks the page left unhandled, to draw their menu. */
  onContextMenu: (callback: (request: ContextMenuRequest) => void) => {
    const handler = (_event: Electron.IpcRendererEvent, request: unknown) => {
      if (isContextMenuRequest(request)) callback(request);
    };
    ipcRenderer.on(CONTEXT_MENU_REQUEST_CHANNEL, handler);
    return () => {
      ipcRenderer.removeListener(CONTEXT_MENU_REQUEST_CHANNEL, handler);
    };
  },
  /** Run the item picked in that menu. */
  runContextMenuCommand: (command: ContextMenuCommand) =>
    ipcRenderer.send(CONTEXT_MENU_COMMAND_CHANNEL, command),
  /** Report the renderer's memory-router path for recovery diagnostics. */
  setRendererRouteContext: (context: RendererRouteContextInput) =>
    ipcRenderer.send(RENDERER_ROUTE_CONTEXT_CHANNEL, context),
  /** Open the OS folder picker and return the chosen absolute path. */
  pickDirectory: (defaultPath?: string) =>
    ipcRenderer.invoke("local-directory:pick", defaultPath),
  /** Validate that a path is an existing readable+writable directory. */
  validateLocalDirectory: (path: string) =>
    ipcRenderer.invoke("local-directory:validate", path),
  /** Read every theme in the themes folder, and start watching it. */
  readThemeFolder: (): Promise<ThemeFolderSnapshot> =>
    ipcRenderer.invoke(THEME_FOLDER_READ_CHANNEL),
  /** Called once a change in the themes folder settles. Returns an unsubscribe fn. */
  onThemeFolderChange: (callback: () => void) => {
    const handler = () => callback();
    ipcRenderer.on(THEME_FOLDER_CHANGED_CHANNEL, handler);
    return () => {
      ipcRenderer.removeListener(THEME_FOLDER_CHANGED_CHANNEL, handler);
    };
  },
  /** Open the themes folder, or one theme's folder in it, in the file manager. */
  openThemeFolder: (name?: string): Promise<{ ok: boolean; error?: string }> =>
    ipcRenderer.invoke(THEME_FOLDER_OPEN_CHANNEL, name),
  /** Create a theme folder from files; never replaces an existing one. */
  writeThemeFolder: (name: string, files: ThemeFolderFile[]): Promise<ThemeFolderWriteResult> =>
    ipcRenderer.invoke(THEME_FOLDER_WRITE_CHANNEL, name, files),
  /** On-device voice input: speech models and transcription in main. */
  voice: {
    listModels: (): Promise<VoiceModelsSnapshot> => ipcRenderer.invoke(VOICE_MODELS_LIST_CHANNEL),
    onModelsChanged: (callback: (snapshot: VoiceModelsSnapshot) => void) => {
      const handler = (_event: Electron.IpcRendererEvent, snapshot: VoiceModelsSnapshot) =>
        callback(snapshot);
      ipcRenderer.on(VOICE_MODELS_CHANGED_CHANNEL, handler);
      return () => {
        ipcRenderer.removeListener(VOICE_MODELS_CHANGED_CHANNEL, handler);
      };
    },
    downloadModel: (id: string): Promise<void> => ipcRenderer.invoke(VOICE_MODEL_DOWNLOAD_CHANNEL, id),
    cancelDownload: (id: string): Promise<void> => ipcRenderer.invoke(VOICE_MODEL_CANCEL_CHANNEL, id),
    deleteModel: (id: string): Promise<void> => ipcRenderer.invoke(VOICE_MODEL_DELETE_CHANNEL, id),
    prepare: (request: VoiceModelRequest) => ipcRenderer.send(VOICE_PREPARE_CHANNEL, request),
    transcribe: (request: VoiceTranscribeRequest): Promise<VoiceTranscribeResult> =>
      ipcRenderer.invoke(VOICE_TRANSCRIBE_CHANNEL, request),
    history: {
      list: (): Promise<VoiceHistoryEntry[]> => ipcRenderer.invoke(VOICE_HISTORY_LIST_CHANNEL),
      onChanged: (callback: () => void) => {
        const handler = () => callback();
        ipcRenderer.on(VOICE_HISTORY_CHANGED_CHANNEL, handler);
        return () => {
          ipcRenderer.removeListener(VOICE_HISTORY_CHANGED_CHANNEL, handler);
        };
      },
      save: (request: VoiceHistorySaveRequest): Promise<VoiceHistoryEntry | null> =>
        ipcRenderer.invoke(VOICE_HISTORY_SAVE_CHANNEL, request),
      update: (id: string, patch: VoiceHistoryUpdate): Promise<void> =>
        ipcRenderer.invoke(VOICE_HISTORY_UPDATE_CHANNEL, id, patch),
      audio: (id: string): Promise<VoiceHistoryAudio | null> => ipcRenderer.invoke(VOICE_HISTORY_AUDIO_CHANNEL, id),
      remove: (id: string): Promise<void> => ipcRenderer.invoke(VOICE_HISTORY_REMOVE_CHANNEL, id),
      setRetention: (keepDays: number | null): Promise<void> =>
        ipcRenderer.invoke(VOICE_HISTORY_RETENTION_CHANNEL, keepDays),
      clear: (): Promise<void> => ipcRenderer.invoke(VOICE_HISTORY_CLEAR_CHANNEL),
    },
  },
  /** Listen for Cmd/Ctrl+W tab-close requests from the main process.
   *  The renderer should close the active tab; if it was the last tab,
   *  call `closeWindow()` to dismiss the window. Returns an unsubscribe fn. */
  onCloseActiveTab: (callback: () => void) => {
    const handler = () => callback();
    ipcRenderer.on("tab:close-active", handler);
    return () => {
      ipcRenderer.removeListener("tab:close-active", handler);
    };
  },
  /** Listen for Cmd/Ctrl+, requests to open Settings. Only the main window
   *  subscribes — main delivers the chord there even when it was pressed in
   *  an issue window, because Settings is a tab. Returns an unsubscribe fn. */
  onOpenSettings: (callback: () => void) =>
    subscribeToMainRendererChannel("settings:open", () => callback()),
  /** Listen for fixed Cmd/Ctrl+1..9 tab-selection requests. Only the main
   *  window subscribes; main routes requests there from any focused window. */
  onSelectTabShortcut: (
    callback: (key: TabSelectionShortcutKey) => void,
  ) =>
    subscribeToMainRendererChannel<unknown>(
      TAB_SELECTION_SHORTCUT_CHANNEL,
      (payload) => {
        const key = parseTabSelectionShortcutKey(payload);
        if (key !== null) callback(key);
      },
    ),
  /** Ask the main process to close the window (used after closing the last tab). */
  closeWindow: () => ipcRenderer.send("window:close"),
  /** Open a validated issue-detail route in a dedicated native window. */
  openIssueWindow: (request: IssueWindowRequest) =>
    ipcRenderer.invoke("window:open-issue", request),
  /** Tell main which workspace this main window shows (null while none). */
  reportWindowWorkspace: (workspaceSlug: string | null) =>
    ipcRenderer.send(WINDOW_WORKSPACE_REPORT_CHANNEL, workspaceSlug),
  /** Workspaces shown by the other main windows. Sync so routing decisions
   *  inside click handlers can consult it. */
  getOtherWindowWorkspaces: (): string[] => {
    try {
      const slugs: unknown = ipcRenderer.sendSync(OTHER_WINDOW_WORKSPACES_CHANNEL);
      return Array.isArray(slugs)
        ? slugs.filter((slug): slug is string => typeof slug === "string")
        : [];
    } catch {
      return [];
    }
  },
  /** Hand a workspace (and optionally a path inside it) to the other main
   *  window that shows it. Returns false when no other window does. */
  focusWorkspaceWindow: (
    workspaceSlug: string,
    path?: string,
    options?: WorkspacePathOptions,
  ): boolean => {
    try {
      return (
        ipcRenderer.sendSync(FOCUS_WORKSPACE_WINDOW_CHANNEL, {
          workspaceSlug,
          ...(path === undefined ? {} : { path }),
          navigate: options?.navigate === true,
        }) === true
      );
    } catch {
      return false;
    }
  },
  /** Open a workspace in its own main window, or focus the one showing it. */
  openWorkspaceWindow: (workspaceSlug: string) =>
    ipcRenderer.invoke(OPEN_WORKSPACE_WINDOW_CHANNEL, workspaceSlug),
  /** Listen for workspace paths routed here from another window. */
  onOpenWorkspacePath: (callback: (request: WorkspacePathRequest) => void) =>
    subscribeToMainRendererChannel<unknown>(
      WORKSPACE_OPEN_PATH_CHANNEL,
      (payload) => {
        const request = payload as Partial<WorkspacePathRequest> | null;
        if (typeof request?.path === "string") {
          callback({ path: request.path, navigate: request.navigate === true });
        }
      },
    ),
  /** Listen for Cmd/Ctrl+Shift+N new-window requests. */
  onNewWindowShortcut: (callback: () => void) =>
    subscribeToMainRendererChannel(NEW_WINDOW_SHORTCUT_CHANNEL, () => callback()),
  /** Whether View → Show Dev Toolbar is checked. Always false unless the
   *  dev build was started with VITE_DEV_TOOLBAR. */
  getDevToolbarVisible: (): boolean => {
    try {
      return ipcRenderer.sendSync(DEV_TOOLBAR_VISIBLE_GET_CHANNEL) === true;
    } catch {
      return false;
    }
  },
  /** Listen for View → Show Dev Toolbar being toggled. Returns an unsubscribe fn. */
  onDevToolbarVisibleChange: (callback: (visible: boolean) => void) => {
    const handler = (_event: Electron.IpcRendererEvent, visible: unknown) => {
      if (typeof visible === "boolean") callback(visible);
    };
    ipcRenderer.on(DEV_TOOLBAR_VISIBLE_CHANGED_CHANNEL, handler);
    return () => {
      ipcRenderer.removeListener(DEV_TOOLBAR_VISIBLE_CHANGED_CHANNEL, handler);
    };
  },
};

type DaemonReauthResult =
  | { ok: true }
  | { ok: false; reason: "session_invalid" }
  | { ok: false; reason: "transient"; message: string };

type FocusEnvironmentResult =
  | { ok: true }
  | { ok: false; reason: "gone" | "unsupported" | "unavailable" | "failed"; error?: string };

const daemonAPI = {
  start: (): Promise<{ success: boolean; error?: string }> =>
    ipcRenderer.invoke("daemon:start"),
  stop: (): Promise<{ success: boolean; error?: string }> =>
    ipcRenderer.invoke("daemon:stop"),
  restart: (): Promise<{ success: boolean; error?: string }> =>
    ipcRenderer.invoke("daemon:restart"),
  getStatus: (): Promise<DaemonStatus> =>
    ipcRenderer.invoke("daemon:get-status"),
  probeRuntimes: (): Promise<LocalRuntimeProbe> =>
    ipcRenderer.invoke("daemon:probe-runtimes"),
  getHostName: (): Promise<string> =>
    ipcRenderer.invoke("daemon:get-host-name"),
  focusEnvironment: (key: string): Promise<FocusEnvironmentResult> =>
    ipcRenderer.invoke("daemon:focus-environment", key),
  onStatusChange: (callback: (status: DaemonStatus) => void) => {
    const handler = (_: unknown, status: DaemonStatus) => callback(status);
    ipcRenderer.on("daemon:status", handler);
    return () => ipcRenderer.removeListener("daemon:status", handler);
  },
  setTargetApiUrl: (url: string): Promise<void> =>
    ipcRenderer.invoke("daemon:set-target-api-url", url),
  syncToken: (token: string, userId: string): Promise<void> =>
    ipcRenderer.invoke("daemon:sync-token", token, userId),
  clearToken: (): Promise<void> =>
    ipcRenderer.invoke("daemon:clear-token"),
  reauthenticate: (
    token: string,
    userId: string,
  ): Promise<DaemonReauthResult> =>
    ipcRenderer.invoke("daemon:reauthenticate", token, userId),
  isCliInstalled: (): Promise<boolean> =>
    ipcRenderer.invoke("daemon:is-cli-installed"),
  getPrefs: (): Promise<{ autoStart: boolean; autoStop: boolean }> =>
    ipcRenderer.invoke("daemon:get-prefs"),
  setPrefs: (prefs: Partial<{ autoStart: boolean; autoStop: boolean }>): Promise<{ autoStart: boolean; autoStop: boolean }> =>
    ipcRenderer.invoke("daemon:set-prefs", prefs),
  autoStart: (): Promise<void> =>
    ipcRenderer.invoke("daemon:auto-start"),
  retryInstall: (): Promise<void> =>
    ipcRenderer.invoke("daemon:retry-install"),
  startLogStream: () => ipcRenderer.send("daemon:start-log-stream"),
  stopLogStream: () => ipcRenderer.send("daemon:stop-log-stream"),
  onLogLine: (callback: (line: string) => void) => {
    const handler = (_: unknown, line: string) => callback(line);
    ipcRenderer.on("daemon:log-line", handler);
    return () => ipcRenderer.removeListener("daemon:log-line", handler);
  },
  openLogFile: (): Promise<{ success: boolean; error?: string }> =>
    ipcRenderer.invoke("daemon:open-log-file"),
};

const updaterAPI = {
  getDownloadState: (): Promise<UpdaterDownloadState> => ipcRenderer.invoke("updater:get-download-state"),
  onDownloadState: (callback: (state: UpdaterDownloadState) => void) => {
    const handler = (_: unknown, state: UpdaterDownloadState) => callback(state);
    ipcRenderer.on("updater:download-state", handler);
    return () => ipcRenderer.removeListener("updater:download-state", handler);
  },
  onUpdateAvailable: (callback: (info: { version: string; releaseNotes?: string }) => void) => {
    const handler = (_: unknown, info: { version: string; releaseNotes?: string }) => callback(info);
    ipcRenderer.on("updater:update-available", handler);
    return () => ipcRenderer.removeListener("updater:update-available", handler);
  },
  onDownloadProgress: (callback: (progress: { percent: number }) => void) => {
    const handler = (_: unknown, progress: { percent: number }) => callback(progress);
    ipcRenderer.on("updater:download-progress", handler);
    return () => ipcRenderer.removeListener("updater:download-progress", handler);
  },
  onUpdateDownloaded: (
    callback: (info: { version: string; releaseNotes?: string }) => void,
  ) => {
    const handler = (_: unknown, info: { version: string; releaseNotes?: string }) =>
      callback(info);
    ipcRenderer.on("updater:update-downloaded", handler);
    return () => ipcRenderer.removeListener("updater:update-downloaded", handler);
  },
  downloadUpdate: () => ipcRenderer.invoke("updater:download"),
  installUpdate: () => ipcRenderer.invoke("updater:install"),
  getPreferences: (): Promise<UpdaterPreferences> =>
    ipcRenderer.invoke("updater:get-preferences"),
  setAutomaticUpdates: (enabled: boolean): Promise<UpdaterPreferences> =>
    ipcRenderer.invoke("updater:set-automatic-updates", enabled),
  checkForUpdates: (): Promise<ManualUpdateCheckResult> =>
    ipcRenderer.invoke("updater:check"),
};

if (process.contextIsolated) {
  contextBridge.exposeInMainWorld("electron", electronAPI);
  contextBridge.exposeInMainWorld("desktopAPI", desktopAPI);
  contextBridge.exposeInMainWorld("daemonAPI", daemonAPI);
  contextBridge.exposeInMainWorld("updater", updaterAPI);
} else {
  // @ts-expect-error - fallback for non-isolated context
  window.electron = electronAPI;
  // @ts-expect-error - fallback for non-isolated context
  window.desktopAPI = desktopAPI;
  // @ts-expect-error - fallback for non-isolated context
  window.daemonAPI = daemonAPI;
  // @ts-expect-error - fallback for non-isolated context
  window.updater = updaterAPI;
}