Local-first AI coding agent desktop: Electron + Rust host core + pi Agent Harness + user-installable plugins
TypeScript ai-agentcoding-agentdesktop-appelectronglobali18nlocal-firstmcppipi-agentpi-desktoppluginsreactrusttypescript
feat(plugin-launcher): launch installed applications from the panel
Tioit-Wang983ff90872a4
diff --git a/apps/desktop/electron/main/index.ts b/apps/desktop/electron/main/index.tsindex 11bc73512..3defa138b 100644--- a/apps/desktop/electron/main/index.ts+++ b/apps/desktop/electron/main/index.ts@@ -6,6 +6,11 @@ import {session,} from "electron";import { join } from "node:path";+import {+ createDefaultLocalAppDeps,+ createLocalAppCatalog,+ type LocalAppCatalog,+} from "./local-apps";import {applyNetworkProxyFromAppSettings,currentNetworkProxy,@@ -583,6 +588,7 @@ const createdLauncher = createLauncher({logger,safeOpenExternal,toggleMainWindow,+ dataDir,});launcherRuntime = createdLauncher;const {@@ -874,6 +880,30 @@ const liveCallService = createLiveCallService({onCallView: (view) => liveVoiceWidget.publish(view),});+/**+ * Installed applications for the plugin launcher.+ *+ * The scanning adapter needs real filesystem and Electron access, whose wiring+ * is asynchronous, while IPC registration is synchronous. This handle awaits+ * that wiring on first use, warms the first scan in the background so the first+ * `Alt+Space` already has application tiles, and reports "still scanning" until+ * it exists (docs/spec/07-plugins/17-plugin-launcher.md §4).+ */+let localAppsCatalog: LocalAppCatalog | null = null;+const localAppsReady = createDefaultLocalAppDeps().then((deps) => {+ const catalog = createLocalAppCatalog(deps);+ localAppsCatalog = catalog;+ void catalog.refresh().catch(() => undefined);+ return catalog;+});+const localApps: LocalAppCatalog = {+ list: async () => (await localAppsReady).list(),+ refresh: async () => (await localAppsReady).refresh(),+ launch: async (appId) => (await localAppsReady).launch(appId),+ isScanning: () => localAppsCatalog?.isScanning() ?? true,+ diagnostics: () => localAppsCatalog?.diagnostics() ?? [],+};+function registerIpc() {return registerIpcHandlers({restartForStorage: () => {@@ -910,6 +940,7 @@ function registerIpc() {persistenceOutbox,logger,plugins,+ localApps,speech,sessionCapabilityContext,enrichSession,diff --git a/apps/desktop/electron/main/ipc/plugin-launcher-ipc.ts b/apps/desktop/electron/main/ipc/plugin-launcher-ipc.tsnew file mode 100644index 000000000..5b285310a--- /dev/null+++ b/apps/desktop/electron/main/ipc/plugin-launcher-ipc.ts@@ -0,0 +1,222 @@+/**+ * IPC surface for the plugin launcher (`Alt+Space`).+ *+ * Two rules shape this module:+ *+ * 1. Only the launcher window may call it. Launching a local application is a+ * capability the main window does not need, and no plugin can reach it: the+ * channels are not exposed through `pluginBridge`, and the sender check+ * rejects anything that is not the launcher's own `webContents`.+ * 2. The renderer never sees a path. It gets display metadata and an opaque+ * `app:<slug>` id; `launch` resolves that id against the host's own scan, so+ * a compromised renderer cannot ask for an arbitrary executable.+ *+ * Docs: docs/spec/07-plugins/17-plugin-launcher.md+ */+import type { BrowserWindow } from "electron";+import {+ IPC,+ LAUNCHER_PAYLOAD_MAX_LENGTH,+ type LauncherAppEntry,+ type LauncherCatalog,+ type LauncherOpenAppRequest,+ type LauncherPluginEntry,+ type LauncherTriggerMeta,+ type PluginSummary,+} from "@pi-desktop/shared";+import type { HostProcess } from "../host-process";+import type { LocalAppCatalog } from "../local-apps";+import type { PluginRuntime } from "../plugin-runtime";+import type { IpcRegistrar } from "./types";++/** A plugin may declare at most this many launcher triggers (mirrors Rust). */+const MAX_TRIGGERS_PER_PLUGIN = 8;+const MAX_PATTERN_LENGTH = 200;+const ALLOWED_TRIGGER_FLAGS = /^[imsu]{0,4}$/;++export type PluginLauncherIpcDependencies = {+ registrar: IpcRegistrar;+ getHost: () => HostProcess | null;+ getPluginLauncherWindow: () => BrowserWindow | null;+ plugins: PluginRuntime;+ localApps: LocalAppCatalog;+ /** Active app locale, used to resolve a localized trigger title. */+ getLocale: () => string;+};++/**+ * Accept or refuse the launcher payload attached to an open request.+ *+ * A payload is only forwarded when it names a trigger and carries text within+ * the documented budget; anything else opens the panel with no payload at all,+ * which is what tells the plugin "the user did not summon you with input".+ */+export function normalizeLauncherLaunch(request: {+ triggerId?: unknown;+ payload?: unknown;+}): { triggerId: string; payload: string } | undefined {+ const triggerId =+ typeof request.triggerId === "string" ? request.triggerId.trim() : "";+ const payload = typeof request.payload === "string" ? request.payload : "";+ if (!triggerId || !payload) return undefined;+ if (payload.length > LAUNCHER_PAYLOAD_MAX_LENGTH) return undefined;+ return { triggerId, payload };+}++function permissionDenied(): Error {+ return Object.assign(new Error("this surface cannot launch applications"), {+ errorCode: "PERMISSION_DENIED",+ });+}++/**+ * Only the persisted launcher may ask what exists and open an application.+ * The window is created lazily, so a missing window means "not the launcher".+ */+function assertLauncherSender(+ getPluginLauncherWindow: () => BrowserWindow | null,+ senderId: number | undefined,+): void {+ const launcher = getPluginLauncherWindow();+ if (!launcher || launcher.isDestroyed() || launcher.webContents.id !== senderId) {+ throw permissionDenied();+ }+}++function resolveTriggerTitle(+ title: unknown,+ locale: string,+): string | undefined {+ if (typeof title === "string") return title || undefined;+ if (title && typeof title === "object") {+ const localized = title as Record<string, unknown>;+ const preferred = locale.toLowerCase().startsWith("zh")+ ? localized["zh-CN"]+ : localized.en;+ if (typeof preferred === "string") return preferred || undefined;+ }+ return undefined;+}++/**+ * Re-shape what the plugin declared into what the renderer may match against.+ *+ * The Rust manifest validator has already rejected unusable declarations; this+ * second pass keeps one malformed plugin from breaking the whole catalog, and+ * drops anything the renderer could not compile.+ */+export function sanitizeLauncherTriggers(+ contributes: unknown,+ locale: string,+): LauncherTriggerMeta[] {+ if (!contributes || typeof contributes !== "object") return [];+ const declared = (contributes as Record<string, unknown>).launcherTriggers;+ if (!Array.isArray(declared)) return [];+ const triggers: LauncherTriggerMeta[] = [];+ const seen = new Set<string>();+ for (const entry of declared.slice(0, MAX_TRIGGERS_PER_PLUGIN)) {+ if (!entry || typeof entry !== "object") continue;+ const record = entry as Record<string, unknown>;+ const id = typeof record.id === "string" ? record.id.trim() : "";+ const pattern = typeof record.pattern === "string" ? record.pattern.trim() : "";+ if (!id || seen.has(id)) continue;+ if (!pattern || pattern.length > MAX_PATTERN_LENGTH) continue;+ const flags = typeof record.flags === "string" ? record.flags : undefined;+ if (flags !== undefined && !ALLOWED_TRIGGER_FLAGS.test(flags)) continue;+ seen.add(id);+ triggers.push({+ id,+ pattern,+ ...(flags ? { flags } : {}),+ ...(resolveTriggerTitle(record.title, locale)+ ? { title: resolveTriggerTitle(record.title, locale) }+ : {}),+ });+ }+ return triggers;+}++/** `ui.panel` is what makes a plugin's Enter key able to open something. */+export function launcherPluginEntry(+ summary: PluginSummary,+ triggers: LauncherTriggerMeta[],+): LauncherPluginEntry | null {+ const launchable =+ summary.enabled &&+ summary.status === "ready" &&+ Boolean(summary.ui?.panel) &&+ summary.permissions.includes("ui.panel");+ if (!launchable) return null;+ return {+ kind: "plugin",+ id: `plugin:${summary.id}`,+ pluginId: summary.id,+ name: summary.name,+ ...(summary.description ? { description: summary.description } : {}),+ triggers,+ };+}++export function launcherAppEntry(+ app: { id: string; name: string; executableName?: string; source: string; iconDataUrl?: string },+): LauncherAppEntry {+ return {+ kind: "app",+ id: app.id,+ name: app.name,+ ...(app.executableName ? { executableName: app.executableName } : {}),+ source: app.source as LauncherAppEntry["source"],+ ...(app.iconDataUrl ? { iconDataUrl: app.iconDataUrl } : {}),+ };+}++export function registerPluginLauncherIpc({+ registrar,+ getHost,+ getPluginLauncherWindow,+ plugins,+ localApps,+ getLocale,+}: PluginLauncherIpcDependencies): void {+ const { handleWithEvent } = registrar;++ handleWithEvent(+ IPC.invoke.pluginLauncherCatalog,+ async (event): Promise<LauncherCatalog> => {+ assertLauncherSender(getPluginLauncherWindow, event.sender.id);+ const host = getHost();+ if (!host) throw new Error("host unavailable");+ const locale = getLocale();+ const listed = await host.call<{ plugins: PluginSummary[] }>("plugins.list");+ const pluginEntries: LauncherPluginEntry[] = [];+ for (const summary of listed.plugins ?? []) {+ const loaded = plugins.getLoaded(summary.id);+ const triggers = sanitizeLauncherTriggers(+ loaded?.manifest.contributes,+ locale,+ );+ const entry = launcherPluginEntry(summary, triggers);+ if (entry) pluginEntries.push(entry);+ }+ const apps = await localApps.list();+ return {+ plugins: pluginEntries,+ apps: apps.map((app) => launcherAppEntry(app)),+ appsScanning: localApps.isScanning(),+ };+ },+ );++ handleWithEvent(+ IPC.invoke.pluginLauncherOpenApp,+ async (event, request: LauncherOpenAppRequest): Promise<{ ok: true }> => {+ assertLauncherSender(getPluginLauncherWindow, event.sender.id);+ const appId = typeof request?.appId === "string" ? request.appId.trim() : "";+ if (!appId) throw new Error("application id is required");+ // `launch` resolves the id against the host's own scan result; a path is+ // never accepted from the renderer.+ await localApps.launch(appId);+ return { ok: true };+ },+ );+}diff --git a/apps/desktop/electron/main/ipc/register.ts b/apps/desktop/electron/main/ipc/register.tsindex 7cf1f16ad..ca2c88981 100644--- a/apps/desktop/electron/main/ipc/register.ts+++ b/apps/desktop/electron/main/ipc/register.ts@@ -18,6 +18,7 @@ import { searchMcpMarket } from "../mcp-registry-catalog";import { registerNotificationIpc } from "./notification-ipc";import { registerPluginIpc } from "./plugin-ipc";import { registerPluginUiIpc } from "./plugin-ui-ipc";+import { registerPluginLauncherIpc } from "./plugin-launcher-ipc";import { registerJevIpc } from "./jev-ipc";import { registerProviderIpc } from "./provider-ipc";import { registerScheduledIpc } from "./scheduled-ipc";@@ -119,6 +120,7 @@ export function registerIpcHandlers(dependencies: RegisterIpcDependencies) {persistenceOutbox,logger,plugins,+ localApps,speech,sessionCapabilityContext,enrichSession,@@ -518,6 +520,14 @@ export function registerIpcHandlers(dependencies: RegisterIpcDependencies) {setActivePluginSession,settleComposerSuggestion,});+ registerPluginLauncherIpc({+ registrar,+ getHost,+ getPluginLauncherWindow,+ plugins,+ localApps,+ getLocale: getUpdaterLocale,+ });registerSpeechIpc({ registrar, speech });if (voiceService) {diff --git a/apps/desktop/electron/main/local-app-parse.ts b/apps/desktop/electron/main/local-app-parse.tsnew file mode 100644index 000000000..a9a7d6813--- /dev/null+++ b/apps/desktop/electron/main/local-app-parse.ts@@ -0,0 +1,177 @@+/**+ * Pure parsing helpers for host-side application discovery (issue #2085).+ *+ * Everything here is string-in / string-out so the discovery scan in+ * `local-apps.ts` stays unit-testable without touching a real filesystem.+ * Path helpers are separator agnostic on purpose: the Windows scan sees `\`+ * paths while the macOS/Linux scans see `/` paths, and one test process+ * exercises all three platform readers.+ */+import { createHash } from "node:crypto";++/** Prefix of every discovered application id handed to the renderer. */+export const LOCAL_APP_ID_PREFIX = "app:";++/** A freedesktop `.desktop` entry, reduced to the fields the launcher needs. */+export interface ParsedDesktopEntry {+ name: string;+ exec: string;+ noDisplay: boolean;+ hidden: boolean;+ type: string;+}++/**+ * Field codes defined by the Desktop Entry Specification. They are+ * placeholders substituted by the launcher, never literal arguments, so they+ * must be removed before the executable is resolved.+ */+const DESKTOP_FIELD_CODE = /%[fFuUdDnNickvm]/g;++/** Shortcut / bundle names that are never launchable user applications. */+const NOISE_MARKERS = ["uninstall", "readme", "help", "documentation", "卸载"] as const;++/**+ * Parse the `[Desktop Entry]` group of a `.desktop` file.+ *+ * Returns `null` when the entry cannot describe a launchable application+ * (`Name` or `Exec` missing). `NoDisplay` / `Hidden` / `Type` are reported+ * verbatim so the caller decides visibility; see `isLaunchableDesktopEntry`.+ */+export function parseDesktopEntry(text: string): ParsedDesktopEntry | null {+ const values = new Map<string, string>();+ let parsedGroupHeader = false;+ let inMainGroup = false;+ for (const rawLine of text.split(/\r?\n/)) {+ const line = rawLine.trim();+ if (line.length === 0 || line.startsWith("#")) continue;+ if (line.startsWith("[")) {+ parsedGroupHeader = true;+ inMainGroup = line === "[Desktop Entry]";+ continue;+ }+ if (parsedGroupHeader && !inMainGroup) continue;+ const separator = line.indexOf("=");+ if (separator <= 0) continue;+ const key = line.slice(0, separator).trim();+ // Localized keys such as `Name[de]` never override the unlocalized value,+ // and the first occurrence of a key wins.+ if (key.includes("[") || values.has(key)) continue;+ values.set(key, line.slice(separator + 1).trim());+ }+ const name = values.get("Name") ?? "";+ const exec = values.get("Exec") ?? "";+ if (name.length === 0 || exec.length === 0) return null;+ return {+ name,+ exec,+ noDisplay: (values.get("NoDisplay") ?? "").toLowerCase() === "true",+ hidden: (values.get("Hidden") ?? "").toLowerCase() === "true",+ type: values.get("Type") ?? "",+ };+}++/** `true` when the parsed entry should appear in the launcher. */+export function isLaunchableDesktopEntry(entry: ParsedDesktopEntry): boolean {+ if (entry.noDisplay || entry.hidden) return false;+ return entry.type.toLowerCase() === "application";+}++/** Remove desktop field codes (`%f`, `%U`, `%i`, `%c`, `%k`, ...). */+export function stripFieldCodes(exec: string): string {+ return exec+ .replace(DESKTOP_FIELD_CODE, " ")+ .replace(/\s+/g, " ")+ .trim();+}++/** First whitespace-delimited token, honouring double-quoted tokens. */+export function firstToken(command: string): string {+ const trimmed = command.trim();+ if (trimmed.startsWith('"')) {+ const closing = trimmed.indexOf('"', 1);+ if (closing > 0) return trimmed.slice(1, closing);+ }+ const space = trimmed.search(/\s/);+ return space < 0 ? trimmed : trimmed.slice(0, space);+}++/**+ * Resolve the executable of an `Exec` line: the first token after field-code+ * removal is either an absolute path or a bare command name looked up on+ * `PATH`. Returns `null` when nothing is left.+ */+export function desktopExecutable(exec: string): string | null {+ const token = firstToken(stripFieldCodes(exec));+ return token.length > 0 ? token : null;+}++/** Last path segment, for both `/` and `\` separated paths. */+export function basename(target: string): string {+ const normalized = target.replace(/\\/g, "/").replace(/\/+$/, "");+ const index = normalized.lastIndexOf("/");+ return index < 0 ? normalized : normalized.slice(index + 1);+}++/** Strip a known, case-insensitive suffix such as `.lnk` or `.app`. */+export function stripExtension(name: string, extension: string): string {+ return name.toLowerCase().endsWith(extension.toLowerCase())+ ? name.slice(0, name.length - extension.length)+ : name;+}++/** Strip the final `.ext` of a file name; dotfiles are left untouched. */+export function stripFileExtension(name: string): string {+ const dot = name.lastIndexOf(".");+ return dot > 0 ? name.slice(0, dot) : name;+}++/** Join two path segments while keeping the separator style of `base`. */+export function joinPath(base: string, name: string): string {+ if (base.length === 0) return name;+ if (base.endsWith("/") || base.endsWith("\\")) return `${base}${name}`;+ const separator = base.includes("\\") && !base.includes("/") ? "\\" : "/";+ return `${base}${separator}${name}`;+}++/** `true` for POSIX absolute paths, drive-letter paths and UNC shares. */+export function isAbsolutePath(target: string): boolean {+ return (+ target.startsWith("/") ||+ /^[A-Za-z]:[\\/]/.test(target) ||+ target.startsWith("\\\\")+ );+}++/** Lowercase slug usable inside an application id. */+export function slugIdPart(text: string): string {+ const slug = text+ .toLowerCase()+ .replace(/[^a-z0-9]+/g, "-")+ .replace(/^-+|-+$/g, "");+ return slug.length > 0 ? slug : "app";+}++/**+ * Stable application id: `app:<executable>-<sha1(seed)[0..8]>`.+ *+ * The seed is the absolute launch target (or bundle / desktop-file path), so+ * an id survives renaming the visible entry but changes when the installed+ * executable moves.+ */+export function localAppId(executableName: string, seed: string): string {+ const digest = createHash("sha1").update(seed).digest("hex").slice(0, 8);+ return `${LOCAL_APP_ID_PREFIX}${slugIdPart(executableName)}-${digest}`;+}++/**+ * Uninstallers, readme files and help documents are shipped next to the real+ * shortcuts but are not applications; match case-insensitively on either the+ * shortcut name or the resolved target.+ */+export function isNoiseShortcut(...candidates: string[]): boolean {+ return candidates.some((candidate) => {+ const lowered = candidate.toLowerCase();+ return NOISE_MARKERS.some((marker) => lowered.includes(marker));+ });+}diff --git a/apps/desktop/electron/main/local-apps-platform.ts b/apps/desktop/electron/main/local-apps-platform.tsnew file mode 100644index 000000000..6606b330e--- /dev/null+++ b/apps/desktop/electron/main/local-apps-platform.ts@@ -0,0 +1,194 @@+/**+ * Per-platform readers for the local application catalog (issue #2085).+ *+ * Each reader turns one registry into `DiscoveredApp` entries and pushes+ * non-fatal I/O problems into `diagnostics` instead of throwing. All+ * filesystem access goes through `LocalAppDeps`, so these readers are+ * unit-testable for every platform from a single host.+ */+import type { DiscoveredApp, LocalAppDeps, ShortcutInfo } from "./local-apps.ts";+import {+ basename,+ desktopExecutable,+ isAbsolutePath,+ isLaunchableDesktopEntry,+ isNoiseShortcut,+ localAppId,+ parseDesktopEntry,+ stripExtension,+ stripFileExtension,+} from "./local-app-parse.ts";++function errorMessage(error: unknown): string {+ return error instanceof Error ? error.message : String(error);+}++/**+ * Windows: Start Menu shortcuts (`*.lnk`), resolved through the injected+ * shortcut reader. Shortcuts pointing at missing files, uninstallers, help+ * files or readme files are skipped.+ */+export async function discoverWindowsApps(+ deps: LocalAppDeps,+ diagnostics: string[],+): Promise<DiscoveredApp[]> {+ const apps: DiscoveredApp[] = [];+ for (const directory of deps.startMenuDirs) {+ let shortcuts: string[];+ try {+ shortcuts = await deps.listShortcutTargets(directory);+ } catch (error) {+ diagnostics.push(`start menu scan failed for ${directory}: ${errorMessage(error)}`);+ continue;+ }+ for (const shortcutPath of shortcuts) {+ if (!shortcutPath.toLowerCase().endsWith(".lnk")) continue;+ const name = stripExtension(basename(shortcutPath), ".lnk");+ let shortcut: ShortcutInfo | null;+ try {+ shortcut = deps.readShortcutLink(shortcutPath);+ } catch (error) {+ diagnostics.push(`shortcut read failed for ${shortcutPath}: ${errorMessage(error)}`);+ continue;+ }+ const target = shortcut?.target?.trim() ?? "";+ if (target.length === 0) continue;+ if (isNoiseShortcut(name, target)) continue;+ let present: boolean;+ try {+ present = await deps.pathExists(target);+ } catch (error) {+ diagnostics.push(`shortcut target check failed for ${target}: ${errorMessage(error)}`);+ continue;+ }+ if (!present) continue;+ const executableName = stripFileExtension(basename(target));+ apps.push({+ id: localAppId(executableName, target),+ name,+ executableName,+ source: "start-menu",+ launchTarget: target,+ iconPath: shortcut?.icon || undefined,+ });+ }+ }+ return apps;+}++function isAppBundlePath(target: string): boolean {+ return target.trim().toLowerCase().endsWith(".app");+}++/**+ * macOS: `.app` bundles directly below each bundle root, plus one nesting+ * level so `/Applications/<Vendor>/*.app` is found.+ */+export async function discoverMacApps(+ deps: LocalAppDeps,+ diagnostics: string[],+): Promise<DiscoveredApp[]> {+ const apps: DiscoveredApp[] = [];+ const visited = new Set<string>();+ for (const directory of deps.appDirectories) {+ let children: string[];+ try {+ children = await deps.listFiles(directory);+ } catch (error) {+ diagnostics.push(`bundle scan failed for ${directory}: ${errorMessage(error)}`);+ continue;+ }+ const bundles: string[] = [];+ for (const child of children) {+ if (isAppBundlePath(child)) {+ bundles.push(child);+ continue;+ }+ // Vendor folders hold one extra level of bundles; plain files (disk+ // images, notes) are simply not directories, so skip them quietly.+ let nested: string[] = [];+ try {+ nested = await deps.listFiles(child);+ } catch {+ nested = [];+ }+ for (const candidate of nested) {+ if (isAppBundlePath(candidate)) bundles.push(candidate);+ }+ }+ for (const bundlePath of bundles) {+ if (visited.has(bundlePath)) continue;+ visited.add(bundlePath);+ const name = stripExtension(basename(bundlePath), ".app");+ if (name.length === 0) continue;+ let executableName: string | undefined;+ try {+ executableName = deps.readBundleExecutable(bundlePath) ?? undefined;+ } catch (error) {+ diagnostics.push(`bundle read failed for ${bundlePath}: ${errorMessage(error)}`);+ }+ apps.push({+ id: localAppId(executableName ?? name, bundlePath),+ name,+ executableName,+ source: "app-bundle",+ launchTarget: bundlePath,+ iconPath: bundlePath,+ });+ }+ }+ return apps;+}++/** Linux: freedesktop `.desktop` entries. */+export async function discoverLinuxApps(+ deps: LocalAppDeps,+ diagnostics: string[],+): Promise<DiscoveredApp[]> {+ const apps: DiscoveredApp[] = [];+ for (const directory of deps.appDirectories) {+ let children: string[];+ try {+ children = await deps.listFiles(directory);+ } catch (error) {+ diagnostics.push(`desktop entry scan failed for ${directory}: ${errorMessage(error)}`);+ continue;+ }+ for (const file of children) {+ if (!file.toLowerCase().endsWith(".desktop")) continue;+ let text: string;+ try {+ text = await deps.readText(file);+ } catch (error) {+ diagnostics.push(`desktop entry read failed for ${file}: ${errorMessage(error)}`);+ continue;+ }+ const entry = parseDesktopEntry(text);+ if (!entry || !isLaunchableDesktopEntry(entry)) continue;+ const executable = desktopExecutable(entry.exec);+ if (!executable) continue;+ const absolute = isAbsolutePath(executable);+ if (absolute) {+ let present: boolean;+ try {+ present = await deps.pathExists(executable);+ } catch (error) {+ diagnostics.push(+ `desktop entry target check failed for ${executable}: ${errorMessage(error)}`,+ );+ continue;+ }+ if (!present) continue;+ }+ const executableName = stripFileExtension(basename(executable));+ apps.push({+ id: localAppId(executableName, absolute ? executable : file),+ name: entry.name,+ executableName,+ source: "desktop-entry",+ launchTarget: executable,+ });+ }+ }+ return apps;+}diff --git a/apps/desktop/electron/main/local-apps.ts b/apps/desktop/electron/main/local-apps.tsnew file mode 100644index 000000000..650a64d66--- /dev/null+++ b/apps/desktop/electron/main/local-apps.ts@@ -0,0 +1,458 @@+/**+ * Host-side discovery of installed OS applications for the plugin launcher+ * (issue #2085).+ *+ * The scan only reads well-known locations (Start Menu shortcuts, macOS+ * application bundles, freedesktop `.desktop` entries). It never spawns a+ * process: no `child_process`, no `exec`, no shell.+ *+ * Every filesystem / Electron capability is injected, so the module can be+ * imported by a plain Node test process. `createDefaultLocalAppDeps()` wires+ * the real `node:fs` + Electron `shell` / `app` implementations and is meant+ * for production only; it loads Electron through a dynamic `import()` (the+ * same pattern as `plugin-runtime.ts`), so importing this module never pulls+ * Electron into a unit test.+ */+import {+ discoverLinuxApps,+ discoverMacApps,+ discoverWindowsApps,+} from "./local-apps-platform.ts";+import { joinPath } from "./local-app-parse.ts";++export {+ LOCAL_APP_ID_PREFIX,+ parseDesktopEntry,+ localAppId,+} from "./local-app-parse.ts";+export {+ discoverLinuxApps,+ discoverMacApps,+ discoverWindowsApps,+} from "./local-apps-platform.ts";++/** Where a discovered entry came from. */+export type LocalAppSource = "start-menu" | "app-bundle" | "desktop-entry";++/**+ * One launchable application.+ *+ * `launchTarget` is the absolute path the main process opens. It must never+ * leave the main process: the IPC layer strips it (and maps `id` to a+ * renderer-facing entry) before anything reaches the renderer, so a+ * compromised renderer cannot make the host open an arbitrary path.+ */+export interface DiscoveredApp {+ id: string;+ name: string;+ executableName?: string;+ source: LocalAppSource;+ launchTarget: string;+ iconPath?: string;+ /** Small icon as a data URL, present only when it fitted the size budget. */+ iconDataUrl?: string;+}++/** Resolved contents of a Windows shortcut (`.lnk`). */+export interface ShortcutInfo {+ target: string;+ args?: string;+ icon?: string;+ iconIndex?: number;+}++/** Minimal image handle; `NativeImage` from Electron satisfies it. */+export interface FileIcon {+ toDataURL(): string;+}++/**+ * Injected host capabilities. Nothing in this file touches the real system+ * directly, which keeps every platform reader unit-testable.+ */+export interface LocalAppDeps {+ /** `process.platform` value ("win32", "darwin", "linux", ...). */+ platform: string;+ /** Windows Start Menu program directories, recursive. */+ startMenuDirs: string[];+ /** macOS bundle roots (`/Applications`, ...) or Linux `.desktop` roots. */+ appDirectories: string[];+ /** Immediate children of a directory, as absolute paths (files + dirs). */+ listFiles(directory: string): Promise<string[]>;+ readText(file: string): Promise<string>;+ pathExists(target: string): Promise<boolean>;+ /** Recursively collected `*.lnk` paths below a Start Menu directory. */+ listShortcutTargets(directory: string): Promise<string[]>;+ readShortcutLink(shortcutPath: string): ShortcutInfo | null;+ /** `CFBundleExecutable` of a bundle, or `null` when unavailable. */+ readBundleExecutable(bundlePath: string): string | null;+ getFileIcon(target: string): Promise<FileIcon | null>;+ /** Electron `shell.openPath`; a non-empty return value is an error string. */+ openPath(target: string): Promise<string>;+}++export interface LocalAppCatalogOptions {+ /** Cache lifetime before the next `list()` rescans. Default 5 minutes. */+ ttlMs?: number;+ /** Hard cap on returned entries. Default 600. */+ maxEntries?: number;+ /** Hard cap on icon lookups per scan. Default 200. */+ maxIcons?: number;+ /** Data URLs longer than this are dropped. Default 4 KiB. */+ maxIconBytes?: number;+ /** Injectable clock, used by the TTL tests. */+ now?: () => number;+}++export interface LocalAppScan {+ apps: DiscoveredApp[];+ /** Non-fatal I/O problems collected while scanning. */+ diagnostics: string[];+ scannedAt: number;+}++export interface LocalAppCatalog {+ /** Memoized scan; joins an in-flight scan, rescans after the TTL. */+ list(): Promise<DiscoveredApp[]>;+ /** Force a fresh scan. */+ refresh(): Promise<DiscoveredApp[]>;+ /** Launch a previously discovered id; never accepts a caller-supplied path. */+ launch(appId: string): Promise<void>;+ isScanning(): boolean;+ /** Diagnostics of the most recent scan. */+ diagnostics(): string[];+}++export const LOCAL_APP_TTL_MS = 5 * 60_000;+export const LOCAL_APP_MAX_ENTRIES = 600;+export const LOCAL_APP_MAX_ICONS = 200;+export const LOCAL_APP_MAX_ICON_BYTES = 4_096;++export interface ScanLimits {+ maxEntries: number;+ maxIcons: number;+ maxIconBytes: number;+}++function errorMessage(error: unknown): string {+ return error instanceof Error ? error.message : String(error);+}++function compareByName(left: DiscoveredApp, right: DiscoveredApp): number {+ const byName = left.name.localeCompare(right.name, undefined, {+ sensitivity: "base",+ });+ return byName !== 0 ? byName : left.id.localeCompare(right.id);+}++/** Keep one entry per id, preferring the shortest (then alphabetical) name. */+function dedupeById(apps: DiscoveredApp[]): DiscoveredApp[] {+ const byId = new Map<string, DiscoveredApp>();+ for (const app of apps) {+ const existing = byId.get(app.id);+ if (!existing) {+ byId.set(app.id, app);+ continue;+ }+ const shorter = app.name.length !== existing.name.length+ ? app.name.length < existing.name.length+ : app.name < existing.name;+ if (shorter) byId.set(app.id, app);+ }+ return [...byId.values()];+}++async function attachIcons(+ apps: DiscoveredApp[],+ deps: LocalAppDeps,+ diagnostics: string[],+ maxIconBytes: number,+): Promise<void> {+ for (const app of apps) {+ const target = app.iconPath ?? app.launchTarget;+ if (!target) continue;+ try {+ const icon = await deps.getFileIcon(target);+ if (!icon) continue;+ const dataUrl = icon.toDataURL();+ if (typeof dataUrl !== "string") continue;+ if (dataUrl.length === 0 || dataUrl.length > maxIconBytes) continue;+ app.iconDataUrl = dataUrl;+ } catch (error) {+ // Icons are cosmetic: a failing lookup must never fail the scan.+ diagnostics.push(`icon lookup failed for ${app.name}: ${errorMessage(error)}`);+ }+ }+}++async function discoverPlatformApps(+ deps: LocalAppDeps,+ diagnostics: string[],+): Promise<DiscoveredApp[]> {+ if (deps.platform === "win32") return discoverWindowsApps(deps, diagnostics);+ if (deps.platform === "darwin") return discoverMacApps(deps, diagnostics);+ if (deps.platform === "linux") return discoverLinuxApps(deps, diagnostics);+ diagnostics.push(`unsupported platform for local app discovery: ${deps.platform}`);+ return [];+}++/**+ * Run one complete scan. Never throws: I/O problems are reported through+ * `diagnostics` and the successfully discovered entries are still returned.+ */+export async function scanLocalApps(+ deps: LocalAppDeps,+ limits: Partial<ScanLimits> = {},+): Promise<LocalAppScan> {+ const resolved: ScanLimits = {+ maxEntries: limits.maxEntries ?? LOCAL_APP_MAX_ENTRIES,+ maxIcons: limits.maxIcons ?? LOCAL_APP_MAX_ICONS,+ maxIconBytes: limits.maxIconBytes ?? LOCAL_APP_MAX_ICON_BYTES,+ };+ const diagnostics: string[] = [];+ let discovered: DiscoveredApp[] = [];+ try {+ discovered = await discoverPlatformApps(deps, diagnostics);+ } catch (error) {+ // Defensive: platform readers already isolate their own failures.+ diagnostics.push(`local app scan failed: ${errorMessage(error)}`);+ discovered = [];+ }+ const apps = dedupeById(discovered)+ .sort(compareByName)+ .slice(0, resolved.maxEntries);+ await attachIcons(+ apps.slice(0, resolved.maxIcons),+ deps,+ diagnostics,+ resolved.maxIconBytes,+ );+ return { apps, diagnostics, scannedAt: Date.now() };+}++/**+ * Build the memoizing application catalog used by the main process.+ *+ * `list()` returns the cached scan when it is younger than the TTL and joins+ * an in-flight scan instead of starting a second one. `launch()` resolves the+ * id against the last scan result only: the caller can never supply a path.+ */+export function createLocalAppCatalog(+ deps: LocalAppDeps,+ options: LocalAppCatalogOptions = {},+): LocalAppCatalog {+ const ttlMs = options.ttlMs ?? LOCAL_APP_TTL_MS;+ const now = options.now ?? (() => Date.now());+ const limits: ScanLimits = {+ maxEntries: options.maxEntries ?? LOCAL_APP_MAX_ENTRIES,+ maxIcons: options.maxIcons ?? LOCAL_APP_MAX_ICONS,+ maxIconBytes: options.maxIconBytes ?? LOCAL_APP_MAX_ICON_BYTES,+ };++ let cache: LocalAppScan | null = null;+ let inFlight: Promise<LocalAppScan> | null = null;++ function startScan(): Promise<LocalAppScan> {+ if (inFlight) return inFlight;+ const scan = scanLocalApps(deps, limits)+ .catch((error: unknown): LocalAppScan => ({+ apps: [],+ diagnostics: [`local app scan failed: ${errorMessage(error)}`],+ scannedAt: now(),+ }))+ .then((result) => {+ const stamped: LocalAppScan = { ...result, scannedAt: now() };+ cache = stamped;+ return stamped;+ })+ .finally(() => {+ inFlight = null;+ });+ inFlight = scan;+ return scan;+ }++ async function ensureScan(force: boolean): Promise<LocalAppScan> {+ if (!force && cache && now() - cache.scannedAt < ttlMs) return cache;+ if (inFlight) return inFlight;+ return startScan();+ }++ async function list(): Promise<DiscoveredApp[]> {+ const scan = await ensureScan(false);+ return [...scan.apps];+ }++ async function refresh(): Promise<DiscoveredApp[]> {+ // A scan already running would otherwise be handed back as "fresh"; wait+ // for it and then start a genuinely new one.+ if (inFlight) await inFlight.catch(() => undefined);+ const scan = await startScan();+ return [...scan.apps];+ }++ async function launch(appId: string): Promise<void> {+ if (typeof appId !== "string" || !appId.startsWith("app:")) {+ throw new Error(`Unknown application id: ${String(appId)}`);+ }+ // Resolve against the last scan result only. A missing cache means the+ // launcher asked before the first scan, so run one.+ const scan = cache ?? (await ensureScan(false));+ const app = scan.apps.find((candidate) => candidate.id === appId);+ if (!app) throw new Error(`Unknown application id: ${appId}`);+ const present = await deps.pathExists(app.launchTarget);+ if (!present) {+ if (cache) {+ cache = {+ ...cache,+ apps: cache.apps.filter((candidate) => candidate.id !== appId),+ };+ }+ void refresh().catch(() => undefined);+ throw new Error(`Application "${app.name}" is no longer installed`);+ }+ const failure = await deps.openPath(app.launchTarget);+ if (typeof failure === "string" && failure.length > 0) {+ throw new Error(`Failed to launch "${app.name}": ${failure}`);+ }+ }++ return {+ list,+ refresh,+ launch,+ isScanning: () => inFlight !== null,+ diagnostics: () => [...(cache?.diagnostics ?? [])],+ };+}++/** Windows Start Menu directories, as injected by the caller. */+export function windowsStartMenuDirs(+ env: Record<string, string | undefined>,+): string[] {+ const roots = [env.APPDATA, env.ProgramData, env.PUBLIC];+ const dirs: string[] = [];+ for (const root of roots) {+ if (!root) continue;+ const dir = joinPath(joinPath(root, "Microsoft"), "Windows/Start Menu/Programs");+ if (!dirs.includes(dir)) dirs.push(dir);+ }+ return dirs;+}++export function macAppDirectories(homeDir: string): string[] {+ return [+ "/Applications",+ "/System/Applications",+ "/System/Applications/Utilities",+ joinPath(homeDir, "Applications"),+ ];+}++export function linuxApplicationDirectories(homeDir: string): string[] {+ return [+ "/usr/share/applications",+ "/usr/local/share/applications",+ joinPath(joinPath(homeDir, ".local"), "share/applications"),+ ];+}++/**+ * Production wiring: real `node:fs` plus Electron `shell` / `app`.+ *+ * Only production code may call this. Electron is loaded dynamically so the+ * module stays importable from `node --test` (where `electron` resolves to a+ * plain path string, not the runtime API).+ */+export async function createDefaultLocalAppDeps(): Promise<LocalAppDeps> {+ const [fs, fsSync, electron] = await Promise.all([+ import("node:fs/promises"),+ import("node:fs"),+ import("electron"),+ ]);+ const { app, shell } = electron;+ const homeDir = app.getPath("home");+ const platform = process.platform;++ return {+ platform,+ startMenuDirs: platform === "win32" ? windowsStartMenuDirs(process.env) : [],+ appDirectories: platform === "darwin"+ ? macAppDirectories(homeDir)+ : platform === "linux"+ ? linuxApplicationDirectories(homeDir)+ : [],+ async listFiles(directory) {+ const entries = await fs.readdir(directory, { withFileTypes: true });+ return entries.map((entry) => joinPath(directory, entry.name));+ },+ async readText(file) {+ return fs.readFile(file, "utf8");+ },+ async pathExists(target) {+ try {+ await fs.access(target);+ return true;+ } catch {+ return false;+ }+ },+ async listShortcutTargets(directory) {+ const shortcuts: string[] = [];+ const walk = async (current: string, depth: number): Promise<void> => {+ if (depth > 8) return;+ let entries: import("node:fs").Dirent[];+ try {+ entries = await fs.readdir(current, { withFileTypes: true });+ } catch {+ // An unreadable subdirectory must not abort the whole Start Menu.+ return;+ }+ for (const entry of entries) {+ const child = joinPath(current, entry.name);+ if (entry.isDirectory()) await walk(child, depth + 1);+ else if (entry.name.toLowerCase().endsWith(".lnk")) shortcuts.push(child);+ }+ };+ await walk(directory, 0);+ return shortcuts;+ },+ readShortcutLink(shortcutPath) {+ try {+ const details = shell.readShortcutLink(shortcutPath);+ return {+ target: details.target,+ args: details.args,+ icon: details.icon,+ iconIndex: details.iconIndex,+ };+ } catch {+ return null;+ }+ },+ readBundleExecutable(bundlePath) {+ try {+ const info = fsSync.readFileSync(+ joinPath(joinPath(bundlePath, "Contents"), "Info.plist"),+ "utf8",+ );+ const match = /<key>CFBundleExecutable<\/key>\s*<string>([^<]+)<\/string>/.exec(info);+ const executable = match?.[1]?.trim();+ return executable && executable.length > 0 ? executable : null;+ } catch {+ return null;+ }+ },+ async getFileIcon(target) {+ try {+ const icon = await app.getFileIcon(target, { size: "small" });+ return icon ?? null;+ } catch {+ return null;+ }+ },+ async openPath(target) {+ return shell.openPath(target);+ },+ };+}diff --git a/apps/desktop/test/local-apps.test.mjs b/apps/desktop/test/local-apps.test.mjsnew file mode 100644index 000000000..518cba428--- /dev/null+++ b/apps/desktop/test/local-apps.test.mjs@@ -0,0 +1,459 @@+import assert from "node:assert/strict";+import test from "node:test";++import {+ createLocalAppCatalog,+ linuxApplicationDirectories,+ localAppId,+ macAppDirectories,+ parseDesktopEntry,+ windowsStartMenuDirs,+} from "../electron/main/local-apps.ts";+import {+ desktopExecutable,+ isLaunchableDesktopEntry,+ stripFieldCodes,+} from "../electron/main/local-app-parse.ts";++const START_MENU = "C:\\Start Menu\\Programs";+const CHROME_TARGET = "C:\\Program Files\\Google\\Chrome\\chrome.exe";++/**+ * Fully injected fake host. Every filesystem capability of `LocalAppDeps` is+ * backed by an in-memory table so no real system is touched.+ */+function createFakeHost(options = {}) {+ const state = {+ startMenuDirs: options.startMenuDirs ?? [START_MENU],+ appDirectories: options.appDirectories ?? [],+ /** shortcut path -> { target, args?, icon? } */+ shortcuts: new Map(Object.entries(options.shortcuts ?? {})),+ /** directory -> absolute child paths */+ children: new Map(Object.entries(options.children ?? {})),+ /** file -> text */+ texts: new Map(Object.entries(options.texts ?? {})),+ existing: new Set(options.existing ?? []),+ /** bundle path -> CFBundleExecutable */+ bundleExecutables: new Map(Object.entries(options.bundleExecutables ?? {})),+ /** icon target -> data URL or Error */+ icons: new Map(options.icons ?? []),+ failShortcutScan: options.failShortcutScan === true,+ shortcutScans: 0,+ fileListings: 0,+ iconRequests: 0,+ openings: [],+ openError: options.openError ?? "",+ };+ const deps = {+ platform: options.platform ?? "win32",+ startMenuDirs: state.startMenuDirs,+ appDirectories: state.appDirectories,+ async listShortcutTargets(directory) {+ state.shortcutScans += 1;+ if (state.failShortcutScan) throw new Error(`EACCES ${directory}`);+ return [...state.shortcuts.keys()];+ },+ async listFiles(directory) {+ state.fileListings += 1;+ const children = state.children.get(directory);+ if (!children) throw new Error(`ENOENT ${directory}`);+ return children;+ },+ async readText(file) {+ const text = state.texts.get(file);+ if (text === undefined) throw new Error(`ENOENT ${file}`);+ return text;+ },+ async pathExists(target) {+ return state.existing.has(target);+ },+ readShortcutLink(shortcutPath) {+ return state.shortcuts.get(shortcutPath) ?? null;+ },+ readBundleExecutable(bundlePath) {+ return state.bundleExecutables.get(bundlePath) ?? null;+ },+ async getFileIcon(target) {+ state.iconRequests += 1;+ const icon = state.icons.get(target);+ if (icon instanceof Error) throw icon;+ if (typeof icon !== "string") return null;+ return { toDataURL: () => icon };+ },+ async openPath(target) {+ state.openings.push(target);+ return state.openError;+ },+ };+ return { deps, state };+}++test("windows shortcuts report the shortcut name and the resolved target", async () => {+ const { deps, state } = createFakeHost({+ shortcuts: {+ [`${START_MENU}\\Google Chrome.lnk`]: { target: CHROME_TARGET, args: "" },+ },+ existing: [CHROME_TARGET],+ });+ const catalog = createLocalAppCatalog(deps);++ const apps = await catalog.list();++ assert.equal(apps.length, 1);+ assert.equal(apps[0].name, "Google Chrome");+ assert.equal(apps[0].executableName, "chrome");+ assert.equal(apps[0].source, "start-menu");+ assert.equal(apps[0].launchTarget, CHROME_TARGET);+ assert.equal(apps[0].id, localAppId("chrome", CHROME_TARGET));+ assert.match(apps[0].id, /^app:chrome-[0-9a-f]{8}$/);++ await catalog.launch(apps[0].id);+ assert.deepEqual(state.openings, [CHROME_TARGET]);+});++test("windows shortcuts that are uninstallers, help files or readmes are skipped", async () => {+ const uninstaller = "C:\\Program Files\\Google\\Chrome\\Application\\unins000.exe";+ const readme = "C:\\Program Files\\Tool\\readme.html";+ const help = "C:\\Program Files\\Tool\\ToolHelp.chm";+ const chineseUninstaller = "C:\\Program Files\\Foo\\卸载.exe";+ const missing = "C:\\Program Files\\Gone\\gone.exe";+ const { deps } = createFakeHost({+ shortcuts: {+ [`${START_MENU}\\Chrome.lnk`]: { target: CHROME_TARGET },+ [`${START_MENU}\\Uninstall Chrome.lnk`]: { target: uninstaller },+ [`${START_MENU}\\Read me.lnk`]: { target: readme },+ [`${START_MENU}\\Tool Help.lnk`]: { target: help },+ [`${START_MENU}\\卸载 Foo.lnk`]: { target: chineseUninstaller },+ [`${START_MENU}\\Gone.lnk`]: { target: missing },+ },+ existing: [CHROME_TARGET, uninstaller, readme, help, chineseUninstaller],+ });++ const apps = await createLocalAppCatalog(deps).list();++ assert.deepEqual(apps.map((app) => app.name), ["Chrome"]);+});++test("shortcut ids are stable and duplicate targets keep the shortest name", async () => {+ const { deps } = createFakeHost({+ shortcuts: {+ [`${START_MENU}\\Google Chrome.lnk`]: { target: CHROME_TARGET },+ [`${START_MENU}\\Chrome.lnk`]: { target: CHROME_TARGET },+ },+ existing: [CHROME_TARGET],+ });++ const first = await createLocalAppCatalog(deps).list();+ const second = await createLocalAppCatalog(deps).list();++ assert.equal(first.length, 1);+ assert.equal(first[0].name, "Chrome");+ assert.equal(first[0].id, localAppId("chrome", CHROME_TARGET));+ assert.equal(second[0].id, first[0].id);+ // A different target for the same executable yields a different id.+ assert.notEqual(localAppId("chrome", "C:\\Other\\chrome.exe"), first[0].id);+});++test("macOS scans bundles one level below each root and uses CFBundleExecutable", async () => {+ const { deps } = createFakeHost({+ platform: "darwin",+ startMenuDirs: [],+ appDirectories: ["/Applications"],+ children: {+ "/Applications": [+ "/Applications/Safari.app",+ "/Applications/Utilities",+ "/Applications/Deep",+ "/Applications/notes.txt",+ ],+ "/Applications/Utilities": ["/Applications/Utilities/Terminal.app"],+ "/Applications/Deep": ["/Applications/Deep/Deeper"],+ "/Applications/Deep/Deeper": ["/Applications/Deep/Deeper/TooDeep.app"],+ },+ bundleExecutables: {+ "/Applications/Safari.app": "Safari",+ "/Applications/Utilities/Terminal.app": "Terminal",+ },+ });++ const apps = await createLocalAppCatalog(deps).list();++ assert.deepEqual(apps.map((app) => app.name), ["Safari", "Terminal"]);+ const safari = apps.find((app) => app.name === "Safari");+ assert.equal(safari.executableName, "Safari");+ assert.equal(safari.source, "app-bundle");+ assert.equal(safari.launchTarget, "/Applications/Safari.app");+ assert.equal(safari.id, localAppId("Safari", "/Applications/Safari.app"));+ const terminal = apps.find((app) => app.name === "Terminal");+ assert.equal(terminal.launchTarget, "/Applications/Utilities/Terminal.app");+ assert.equal(terminal.executableName, "Terminal");+});++test("parseDesktopEntry reads the Desktop Entry group and strips field codes", () => {+ const text = [+ "# a comment",+ "[Desktop Entry]",+ "Type=Application",+ "Name=Firefox",+ "Name[de]=Feuerfuchs",+ "Exec=/usr/lib/firefox/firefox --name %c %u %U %f %F %i %k",+ "NoDisplay=false",+ "Hidden=false",+ "",+ "[Desktop Action new-window]",+ "Name=New Window",+ "Exec=/usr/lib/firefox/firefox --new-window",+ "",+ ].join("\n");++ const entry = parseDesktopEntry(text);+ assert.ok(entry);+ assert.equal(entry.name, "Firefox");+ assert.equal(entry.type, "Application");+ assert.equal(entry.noDisplay, false);+ assert.equal(entry.hidden, false);+ assert.equal(stripFieldCodes(entry.exec), "/usr/lib/firefox/firefox --name");+ assert.equal(desktopExecutable(entry.exec), "/usr/lib/firefox/firefox");+ assert.equal(isLaunchableDesktopEntry(entry), true);+});++test("parseDesktopEntry resolves quoted and bare command executables", () => {+ assert.equal(desktopExecutable('"/opt/My App/app" %F'), "/opt/My App/app");+ assert.equal(desktopExecutable("firefox %u"), "firefox");+ assert.equal(desktopExecutable(" "), null);+ assert.equal(parseDesktopEntry("[Desktop Entry]\nName=No exec\n"), null);+});++test("NoDisplay, Hidden and non-Application desktop entries are filtered out", async () => {+ const appDir = "/usr/share/applications";+ const { deps } = createFakeHost({+ platform: "linux",+ startMenuDirs: [],+ appDirectories: [appDir],+ children: {+ [appDir]: [+ `${appDir}/firefox.desktop`,+ `${appDir}/hidden.desktop`,+ `${appDir}/nodisplay.desktop`,+ `${appDir}/service.desktop`,+ `${appDir}/code.desktop`,+ `${appDir}/readme.txt`,+ ],+ },+ texts: {+ [`${appDir}/firefox.desktop`]:+ "[Desktop Entry]\nType=Application\nName=Firefox\nExec=/usr/lib/firefox/firefox %u\n",+ [`${appDir}/hidden.desktop`]:+ "[Desktop Entry]\nType=Application\nName=Hidden App\nHidden=true\nExec=/usr/bin/hidden %U\n",+ [`${appDir}/nodisplay.desktop`]:+ "[Desktop Entry]\nType=Application\nName=No Display\nNoDisplay=true\nExec=/usr/bin/nodisplay\n",+ [`${appDir}/service.desktop`]:+ "[Desktop Entry]\nType=Service\nName=Service\nExec=/usr/bin/service\n",+ [`${appDir}/code.desktop`]:+ "[Desktop Entry]\nType=Application\nName=Visual Studio Code\nExec=code --unity-launch %F\n",+ },+ existing: ["/usr/lib/firefox/firefox"],+ });++ const apps = await createLocalAppCatalog(deps).list();++ assert.deepEqual(apps.map((app) => app.name), ["Firefox", "Visual Studio Code"]);+ assert.equal(apps[0].source, "desktop-entry");+ assert.equal(apps[0].launchTarget, "/usr/lib/firefox/firefox");+ assert.equal(apps[0].id, localAppId("firefox", "/usr/lib/firefox/firefox"));+ // A bare command name has no filesystem path to validate, so it is kept and+ // its id is seeded from the desktop file itself.+ assert.equal(apps[1].executableName, "code");+ assert.equal(apps[1].launchTarget, "code");+ assert.equal(apps[1].id, localAppId("code", `${appDir}/code.desktop`));+});++test("list() is cached for the TTL and refresh() forces a rescan", async () => {+ let clock = 1_000;+ const { deps, state } = createFakeHost({+ shortcuts: { [`${START_MENU}\\Chrome.lnk`]: { target: CHROME_TARGET } },+ existing: [CHROME_TARGET],+ });+ const catalog = createLocalAppCatalog(deps, {+ ttlMs: 1_000,+ now: () => clock,+ });++ assert.equal(catalog.isScanning(), false);+ await catalog.list();+ assert.equal(state.shortcutScans, 1);++ await catalog.list();+ await catalog.list();+ assert.equal(state.shortcutScans, 1);++ clock += 999;+ await catalog.list();+ assert.equal(state.shortcutScans, 1);++ clock += 1;+ await catalog.list();+ assert.equal(state.shortcutScans, 2);++ await catalog.refresh();+ assert.equal(state.shortcutScans, 3);+ assert.equal(catalog.isScanning(), false);+});++test("concurrent list() calls share a single in-flight scan", async () => {+ const { deps, state } = createFakeHost({+ shortcuts: { [`${START_MENU}\\Chrome.lnk`]: { target: CHROME_TARGET } },+ existing: [CHROME_TARGET],+ });+ const catalog = createLocalAppCatalog(deps);+ const first = catalog.list();+ const second = catalog.list();++ assert.equal(catalog.isScanning(), true);+ const [left, right] = await Promise.all([first, second]);+ assert.equal(state.shortcutScans, 1);+ assert.deepEqual(left.map((app) => app.id), right.map((app) => app.id));+});++test("launch() rejects unknown ids and never accepts a caller-supplied path", async () => {+ const { deps, state } = createFakeHost({+ shortcuts: { [`${START_MENU}\\Chrome.lnk`]: { target: CHROME_TARGET } },+ existing: [CHROME_TARGET],+ });+ const catalog = createLocalAppCatalog(deps);+ await catalog.list();++ await assert.rejects(catalog.launch("app:chrome-00000000"), /Unknown application id/);+ await assert.rejects(catalog.launch(CHROME_TARGET), /Unknown application id/);+ assert.deepEqual(state.openings, []);+});++test("launch() of a removed target drops the entry and reports it is gone", async () => {+ const { deps, state } = createFakeHost({+ shortcuts: { [`${START_MENU}\\Chrome.lnk`]: { target: CHROME_TARGET } },+ existing: [CHROME_TARGET],+ });+ const catalog = createLocalAppCatalog(deps);+ const [chrome] = await catalog.list();++ state.existing.delete(CHROME_TARGET);+ await assert.rejects(catalog.launch(chrome.id), /no longer installed/);+ assert.deepEqual(state.openings, []);++ const remaining = await catalog.list();+ assert.deepEqual(remaining, []);+});++test("launch() surfaces an error string returned by openPath", async () => {+ const { deps } = createFakeHost({+ shortcuts: { [`${START_MENU}\\Chrome.lnk`]: { target: CHROME_TARGET } },+ existing: [CHROME_TARGET],+ openError: "Failed to open path",+ });+ const catalog = createLocalAppCatalog(deps);+ const [chrome] = await catalog.list();++ await assert.rejects(catalog.launch(chrome.id), /Failed to launch "Chrome"/);+});++test("icon failures and oversized icons never fail the scan", async () => {+ const second = "C:\\Program Files\\Tool\\tool.exe";+ const third = "C:\\Program Files\\Huge\\huge.exe";+ const { deps, state } = createFakeHost({+ shortcuts: {+ [`${START_MENU}\\Chrome.lnk`]: { target: CHROME_TARGET },+ [`${START_MENU}\\Tool.lnk`]: { target: second },+ [`${START_MENU}\\Huge.lnk`]: { target: third },+ },+ existing: [CHROME_TARGET, second, third],+ icons: [+ [CHROME_TARGET, new Error("icon extraction failed")],+ [second, "data:image/png;base64,AAAA"],+ [third, `data:image/png;base64,${"A".repeat(5_000)}`],+ ],+ });++ const apps = await createLocalAppCatalog(deps).list();++ assert.equal(apps.length, 3);+ assert.equal(apps.find((app) => app.name === "Chrome").iconDataUrl, undefined);+ assert.equal(apps.find((app) => app.name === "Tool").iconDataUrl, "data:image/png;base64,AAAA");+ assert.equal(apps.find((app) => app.name === "Huge").iconDataUrl, undefined);+ assert.equal(state.iconRequests, 3);+});++test("icons are requested for at most 200 entries", async () => {+ const shortcuts = {};+ const existing = [];+ for (let index = 0; index < 205; index += 1) {+ const target = `C:\\Apps\\app${index}.exe`;+ shortcuts[`${START_MENU}\\App ${index}.lnk`] = { target };+ existing.push(target);+ }+ const { deps, state } = createFakeHost({ shortcuts, existing });++ const apps = await createLocalAppCatalog(deps).list();++ assert.equal(apps.length, 205);+ assert.equal(state.iconRequests, 200);+});++test("entries are sorted by name and capped at 600", async () => {+ const shortcuts = {};+ const existing = [];+ for (let index = 620; index >= 1; index -= 1) {+ const label = `App ${String(index).padStart(4, "0")}`;+ const target = `C:\\Apps\\app${String(index).padStart(4, "0")}.exe`;+ shortcuts[`${START_MENU}\\${label}.lnk`] = { target };+ existing.push(target);+ }+ const { deps, state } = createFakeHost({ shortcuts, existing });++ const apps = await createLocalAppCatalog(deps, { maxIcons: 0 }).list();++ assert.equal(apps.length, 600);+ assert.equal(apps[0].name, "App 0001");+ assert.equal(apps[599].name, "App 0600");+ assert.equal(state.iconRequests, 0);+});++test("an unreadable location is reported as a diagnostic instead of throwing", async () => {+ const { deps } = createFakeHost({ failShortcutScan: true });+ const catalog = createLocalAppCatalog(deps);++ const apps = await catalog.list();++ assert.deepEqual(apps, []);+ assert.match(catalog.diagnostics()[0], /start menu scan failed/);+});++test("an unsupported platform yields no entries and a diagnostic", async () => {+ const { deps } = createFakeHost({ platform: "freebsd", startMenuDirs: [], appDirectories: [] });+ const catalog = createLocalAppCatalog(deps);++ assert.deepEqual(await catalog.list(), []);+ assert.match(catalog.diagnostics()[0], /unsupported platform/);+});++test("platform directories are built from the injected environment", () => {+ const dirs = windowsStartMenuDirs({+ APPDATA: "C:\\Users\\me\\AppData\\Roaming",+ ProgramData: "C:\\ProgramData",+ PUBLIC: "C:\\Users\\Public",+ });+ assert.equal(dirs.length, 3);+ assert.ok(dirs[0].endsWith("Microsoft\\Windows/Start Menu/Programs"));+ assert.deepEqual(windowsStartMenuDirs({}), []);++ assert.deepEqual(macAppDirectories("/Users/me"), [+ "/Applications",+ "/System/Applications",+ "/System/Applications/Utilities",+ "/Users/me/Applications",+ ]);+ assert.deepEqual(linuxApplicationDirectories("/home/me"), [+ "/usr/share/applications",+ "/usr/local/share/applications",+ "/home/me/.local/share/applications",+ ]);+});